# Project: Unified Sovereign Infrastructure Platform Integration

## Architecture
BRAINK Console integrates with the Sovereign Operating Environments, Headless Google Drive Workbook-as-CPU Service Mesh, Zero-Mock Market APEX Benchmarks, and Deterministic 404 IT State Dispatch engine under the governance of GEMINI.md Laws A–E:

1. **Workstation & Runtime Substrate (Ports 3000, 19100, 19104)**:
   - ServerSpace (port 19100) and StoreSpace (port 19104) mounted in `server.ts` with dual static distribution + live development proxy fallback.
   - Trailing slash preservation (`/serverspace-app/`, `/storespace-app/`) ensuring zero 404 asset failures for relative resources (`./assets/*`).
   - PM2 daemon management under `ecosystem.config.cjs` with `--expose-gc --max-old-space-size=1024` and `max_memory_restart: '1024M'`.
   - 5-stage substrate-first process lifecycle (Law D) verified via `KEDDEH_RUNTIME/master_substrate_instantiator.py`.
   - Complete 21-route sidebar navigation in `Sidebar.tsx` mapped to dedicated components in `App.tsx`.

2. **Empirical Zero-Mock Market Software APEX Engine**:
   - `src/lib/market_apex_benchmark_suite.ts` enforces Law B (Anti-Mock Doctrine) via `PhysicalMarketApexEngine`.
   - 5 real physical microbenchmarks on Darwin arm64 using `process.hrtime.bigint()` nanosecond timers:
     1. SQLite on-disk WAL transaction commits vs in-memory `:memory:` vs 128KB ring buffer.
     2. zlib Deflate vs Brotli vs ZCG bijective table mapping.
     3. TCP loopback (127.0.0.1) socket transmission vs direct memory buffer copying.
     4. AES-256-GCM cipher with tag verification vs Bilateral HMAC-SHA256 with timing-safe comparison.
     5. Float64 scalar nested loops vs ARM64 NEON SIMD float array operations.
   - Architectural paradigm falsifications (Clio/Smokeball, AWS EC2, LangChain) evaluating sovereignty, subpoena immunity, and offline capability without fake millisecond numbers.
   - Router mounted at `/api/benchmark/apex`, UI mounted in `MarketApexBenchmarkStudio.tsx`.

3. **Deterministic 404 Incident ID & Autonomous IT State Dispatch**:
   - Standard incident format: `KEX-404-INC-<CATEGORY>-<HASH8>` generated by `src/lib/kex_it_incident_manager.ts`.
   - Full workflow state serialization (active view, navigation breadcrumbs, DOM context, session, state variables) and occurrence particulars (client timestamp, user agent, severity, stack).
   - Sealed with SHA-256 cryptographic proof (`${incidentId}:${requestedUri}:${ts}:${clientIp}`).
   - Dispatched to `POST /api/it/dispatch-incident` and persisted to `.braink/it_incidents/IT_INCIDENT_DISPATCH_LEDGER.ndjson`.
   - Law E bounded compaction: 200-ticket rolling window, 5MB ledger rotation guard.
   - Interactive recovery UI: `Projected404ITModal.tsx` providing non-destructive reset (`onRecover('home')`), VFS re-sync, and diagnostic export.

4. **Headless Google Drive Workbook-as-CPU Integration**:
   - 125 Master Sovereign Workbooks at `/Users/ak/Library/CloudStorage/GoogleDrive-keddeh.servers@gmail.com/My Drive/KEDDEH_GLOBAL_SOVEREIGN_SYSTEMS/`:
     - 100 Server Farm Package workbooks (PKG01–PKG100) governing 100,000 blades across 6 sectors.
     - 25 Core/Non-PKG workbooks (5 stream CPUs, orchestrators, routers, SHA-256 ALU formulas).
   - Relational Epistemology (Axioms 1–4, Proposition 1 in Q32.32 fixed-point log space).
   - 7-Stage Cascade POSIX fsync write-back protocol: MOUNT ➔ VERIFY ➔ HYDRATE ➔ RESOLVE ➔ MUTATE ➔ WRITE-BACK (dual file/dir fsync) ➔ PROOF (disk readback SHA-256 digest).
   - Implemented in `src/braink_runtime/keddeh_cloud_adapter.py` and `src/lib/keddeh_cloud_workbook_adapter.ts`.

5. **Physical Substrate Verification Gate**:
   - `python3 test_runtime_contract.py` executes 26/26 physical contracts covering Liveness, SHM, Parity, SIMD, and Cloud Workbook Matrix.
   - Vitest DOM suite `src/test/dom_full_suite.test.tsx` passes 10/10 tests.
   - Production compilation via `npm run build` produces Vite client and Node.js server bundle (`dist/server.cjs`) with exit code 0.

## Feature Inventory
| # | Feature | Description | Milestone | Source |
|---|---------|-------------|-----------|--------|
| 1 | ServerSpace Workstation Mount & Proxy | ServerSpace (port 19100) mounted at `/serverspace-app/` with dual static + proxy fallback and trailing slash preservation. | M1 | survey_1 |
| 2 | StoreSpace Workstation Mount & Proxy | StoreSpace (port 19104) mounted at `/storespace-app/` with dual static + proxy fallback and trailing slash preservation. | M1 | survey_1 |
| 3 | PM2 Substrate Daemon Architecture | PM2 configuration in `ecosystem.config.cjs` enforcing 1024MB V8 heap, zero restart loops, and Law D startup order. | M1 | survey_1 |
| 4 | Sidebar 21-Route Clean Navigation | All 21 top-level routes in `Sidebar.tsx` mapped 1:1 in `App.tsx` and rendering cleanly without uncaught exceptions. | M1 | survey_1 |
| 5 | Physical Market APEX Compression Benchmark | Real zlib Deflate, Brotli, and ZCG bijective table mapping benchmarks on structured JSON. | M2 | survey_2 |
| 6 | Physical Market APEX Storage Benchmark | Real `better-sqlite3` on-disk WAL vs `:memory:` vs 128KB ring buffer benchmarks. | M2 | survey_2 |
| 7 | Physical Market APEX IPC Benchmark | Real TCP loopback `net.Socket` vs direct memory buffer copying. | M2 | survey_2 |
| 8 | Physical Market APEX Crypto Benchmark | Real AES-256-GCM vs Bilateral HMAC-SHA256 with timing-safe comparison. | M2 | survey_2 |
| 9 | Physical Market APEX Vector Math Benchmark | Real Float64 scalar vs ARM64 NEON SIMD float array calculations. | M2 | survey_2 |
| 10 | Cloud SaaS Architectural Falsifications | Structural comparisons (Clio, AWS EC2, LangChain) with zero fake millisecond timings. | M2 | survey_2 |
| 11 | High-Resolution Hardware Timers | Use of `process.hrtime.bigint()` nanosecond timers, real ops/sec, processed bytes, and SHA-256 seals. | M2 | survey_2 |
| 12 | Deterministic 404 Incident ID Generator | Format `KEX-404-INC-<CAT>-<HASH8>` in `kex_it_incident_manager.ts`. | M3 | survey_2 |
| 13 | Autonomous 404 Safe Fallback Stubs | Dynamic generation of safe ESM/JSON stubs returning HTTP 200 to prevent cascading breakage. | M3 | survey_2 |
| 14 | 404 Incident State Serialization & Zod Schema | Structured serialization of workflow state and occurrence particulars validated via Zod. | M3 | survey_2 |
| 15 | SHA-256 Incident Proof Sealing | Cryptographic seal computation over incident metadata. | M3 | survey_2 |
| 16 | Bounded 404 Dispatch Ledger Persistence | Persistence to `.braink/it_incidents/IT_INCIDENT_DISPATCH_LEDGER.ndjson` with 200-ticket rolling window and 5MB compaction. | M3 | survey_2 |
| 17 | Incident Dispatch API Endpoint | Endpoint `POST /api/it/dispatch-incident` mounted in `server.ts`. | M3 | survey_2 |
| 18 | Interactive Projected404ITModal UI | Non-destructive recovery modal with reset to workspace home, VFS re-sync, and diagnostic export. | M3 | survey_2 |
| 19 | 125 Master Sovereign Workbooks Catalog | Physical integration of 100 PKG server farm workbooks and 25 core/non-PKG workbooks on Google Drive. | M4 | spec_miner_1 |
| 20 | Workbook-as-CPU Formula Logic Gates | Cell formula execution for polarity coupling, absence apertures, consilience, and SHA-256 ALU bitwise gates. | M4 | spec_miner_1 |
| 21 | Relational Epistemology Engine | Axioms 1–4 and Proposition 1 in Q32.32 fixed-point log space eliminating float rounding divergence. | M4 | spec_miner_1 |
| 22 | 7-Stage Cascade POSIX Fsync Protocol | 7-stage write-back cascade with dual POSIX fsync (file and directory fd) and independent disk readback SHA-256 proof. | M4 | spec_miner_1 |
| 23 | Substrate Law A–E Invariants | Zero child process spawns, anti-mock doctrine, modular decomposition, substrate-first lifecycle, bounded memory/ledger. | M4 | spec_miner_1 |
| 24 | Physical Contract Suite Gate | 26/26 physical contracts verified via `python3 test_runtime_contract.py`. | M5 | all |
| 25 | DOM Component Render Verification Suite | 10/10 tests verified via `npx vitest run src/test/dom_full_suite.test.tsx`. | M5 | all |
| 26 | Production Build Compilation Gate | Vite frontend and esbuild server bundle compilation via `npm run build` with exit code 0. | M5 | all |
| 27 | E2E Test Suite Creation & Execution | Comprehensive opaque-box test suite covering Tiers 1–5 published in `TEST_READY.md`. | M5 | test_track |
| 28 | Adversarial Coverage Hardening | White-box adversarial testing (Tier 5) auditing source code, edge cases, and boundary constraints. | M5 | test_track |

## Milestones
| # | Name | Scope | Dependencies | Status |
|---|------|-------|-------------|--------|
| M1 | Workstation & Runtime Substrate Verification | ServerSpace (19100), StoreSpace (19104), PM2 1024MB heap, Port 3000 health, Sidebar 21 routes. | none | DONE |
| M2 | Empirical Zero-Mock Market APEX Engine | 5 physical microbenchmarks, high-res timers, architectural falsifications, zero fake numbers. | none | DONE |
| M3 | Deterministic 404 Incident ID & IT State Dispatch | `KEX-404-INC-...` generator, Zod schema, SHA-256 seal, ledger persistence, `POST /api/it/dispatch-incident`, `Projected404ITModal`. | none | DONE |
| M4 | Headless Google Drive Workbook-as-CPU Integration | 125 master workbooks, Relational Epistemology Axioms 1–4, 7-Stage Cascade dual fsync write-back, Laws A–E. | none | DONE |
| M5 | E2E Test Verification, Adversarial Hardening & Deep Critique Gate | Requirement-driven E2E test suite (Tiers 1–5), Tier 5 adversarial stress testing, Forensic Audit, and DCVG consensus. | M1, M2, M3, M4 | DONE |

## Interface Contracts

### Workstation Reverse Proxy ↔ Express Gateway
- Dynamic mount: `createHttpProxy(port, pathPrefix)`
- Ports: `19100` (ServerSpace), `19104` (StoreSpace)
- Fallback: Pre-built static asset delivery from `dist/` if daemon socket is offline.

### Market APEX Engine ↔ API Router & UI
- Module: `src/lib/market_apex_benchmark_suite.ts`
- Methods:
  - `runFullMatrix()`: Executes all 5 physical microbenchmarks and returns `PlatformBenchmarkReport` with nanosecond timings, ops/sec throughput, and SHA-256 digests.
  - `getArchitecturalAudits()`: Returns structural falsification matrices for Clio, AWS EC2, and LangChain.
- Route: `GET /api/benchmark/apex/run`

### 404 Incident Manager ↔ IT Department Service
- Module: `src/lib/kex_it_incident_manager.ts` & `src/server/services/it_department_service.ts`
- Invariant ID: `KEX-404-INC-${category}-${hash8}`
- Proof: SHA-256 hash over `${incidentId}:${requestedUri}:${timestamp}:${clientIp}`
- Ledger: `.braink/it_incidents/IT_INCIDENT_DISPATCH_LEDGER.ndjson` (max 200 rolling records, 5MB file rotation)
- Route: `POST /api/it/dispatch-incident`

### Keddeh Cloud Adapter ↔ Google Drive Workbooks
- Python Module: `src/braink_runtime/keddeh_cloud_adapter.py`
- TypeScript Module: `src/lib/keddeh_cloud_workbook_adapter.ts`
- Protocol: 7-Stage Cascade:
  1. MOUNT: Verify path accessibility (Google Drive / VFS fallback).
  2. VERIFY: Authenticate workbook signature and schema layout.
  3. HYDRATE: Read cell values and formulas into memory matrix.
  4. RESOLVE: Compute Proposition 1 in Q32.32 fixed-point log space.
  5. MUTATE: Apply updates to formula ALU registers.
  6. WRITE-BACK: Atomic write with dual POSIX `fsync` (file descriptor + directory descriptor).
  7. PROOF: Independent byte readback from disk and SHA-256 hash sealing into append-only lineage ledger.

## Code Layout
- `server.ts`: Express application bootstrap, reverse proxy mounts, static asset routers, `/api/health`.
- `ecosystem.config.cjs`: PM2 daemon configuration with 1024MB V8 heap ceiling.
- `src/App.tsx`: Top-level application shell with 21-route switch and `Projected404ITModal`.
- `src/components/Sidebar.tsx`: Navigation sidebar with 21 route definitions.
- `src/lib/market_apex_benchmark_suite.ts`: Physical microbenchmarks and architectural falsifications.
- `src/server/routes/market_benchmark.routes.ts`: Benchmark API routes.
- `src/components/MarketApexBenchmarkStudio.tsx`: UI studio for benchmark visualization.
- `src/lib/kex_it_incident_manager.ts`: 404 incident ID generator and autonomous fallback stubs.
- `src/server/schemas/it_incident.schema.ts`: Zod validation schema for IT incidents.
- `src/server/services/it_department_service.ts`: Incident ticket persistence and ledger compaction.
- `src/server/routes/it_department.routes.ts`: Incident dispatch routes.
- `src/components/Projected404ITModal.tsx`: Interactive non-destructive recovery modal.
- `src/braink_runtime/keddeh_cloud_adapter.py`: 7-Stage Cascade and Relational Epistemology Python engine.
- `src/lib/keddeh_cloud_workbook_adapter.ts`: Sovereign workbook adapter TypeScript singleton.
- `test_runtime_contract.py`: Physical contract audit suite (26 physical contracts).
- `src/test/dom_full_suite.test.tsx`: DOM component render verification suite (10 tests).

