{"slug":"business/CODEBASE_EXCAVATION","title":"Codebase Excavation — Folder-by-Folder Trace","section":"business","sectionLabel":"Business","status":"unclassified","type":"document","path":"business/CODEBASE_EXCAVATION.mdx","bytes":55100,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n**Date:** 2026-07-30\n**HEAD:** `d941a422` — _feat: marketplace installation runtime + workspace discovery verified_\n**Method:** Independent trace of every folder in the working tree. Not derived from `package.json`, not derived from route files. Every claim below was resolved against the files and cross-checked against `wrangler.toml` bindings, workspace globs, git tracking status, and the canonical release script.\n**Reference authority:** `CLAUDE.md`, `AGENTS.md`, `docs/architecture/ARCHITECTURE_LOCK.md`.\n\n---\n\n## Part 0 — Scale\n\n| Layer           | Folders                                             | Source files (`.ts/.tsx/.js/.jsx/.mjs`, build output excluded) |\n| --------------- | --------------------------------------------------- | -------------------------------------------------------------- |\n| `apps/`         | 5                                                   | 1,006                                                          |\n| `services/`     | 39 (30 with a Worker config, 5 empty, 4 non-Worker) | ~450                                                           |\n| `packages/`     | 40                                                  | ~470                                                           |\n| Everything else | 14                                                  | ~156                                                           |\n| **Total**       |                                                     | **2,082**                                                      |\n\nMarkdown: **787 documents** (33 at repo root, 754 under `docs/`), of which **94 live in `docs/architecture/`** and **16 of those are declared canonical by `AGENTS.md`**.\n\nMigration SQL: **476 `.sql` files across 17 independent migration roots.**\n\n---\n\n# PART I — GROUND-TRUTH MAP\n\n## 1. The release surface (what is actually published)\n\nThere is exactly one authoritative list, and it lives in `scripts/release/deploy-platform.sh:99` (mirrored in `.github/workflows/deploy-workers.yml` and `scripts/release/validate-platform-deployment.sh:64`):\n\n```\npipeline → connector → mcp-connector → connector-sync → knowledge\n        → continuity → intelligence → workflow → gateway\n```\n\n**Nine Workers.** Every other Worker config in the repo is outside the canonical publication path.\n\n`validate-platform-deployment.sh` enforces exactly one hard isolation invariant: `mcp-connector-test` / `mcp-connector-prod` must both exist. No other binding class is checked.\n\n## 2. `services/` — 39 folders, three populations\n\n### 2a. Core nine (in the release path)\n\n| Folder           | Worker name (test / prod)                     | Entry LOC | Owned responsibility                                                                                                                                                   |\n| ---------------- | --------------------------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `pipeline`       | `pipeline-test` / `pipeline-prod`             | 2,041     | Normalizer + spine-v2 merged. Self-declared **only** holder of Spine write credentials. Contains `src/normalizer/` (11 JSON schemas) and `src/spine/` (legacy writer). |\n| `connector`      | `connector-test` / `connector-prod`           | 252       | **Compatibility router only.** Forwards to loader / mcp-connector / store over service bindings. No in-process connector logic.                                        |\n| `mcp-connector`  | `mcp-connector-test` / `mcp-connector-prod`   | 1,319     | MCP tool server + the full Descope provider adapter + OAuth authorization server (11 `lib/oauth-*` modules).                                                           |\n| `connector-sync` | `connector-sync-test` / `connector-sync-prod` | 860       | Schema-driven scheduled/on-demand sync for all providers. Reads `tenant_spine_config` as SSOT.                                                                         |\n| `knowledge`      | `knowledge-test` / `knowledge-prod`           | 2,237     | Chunking, embedding, search, synthesis, promotion gate, lineage tracker, IQ hub.                                                                                       |\n| `continuity`     | `continuity-test` / `continuity-prod`         | 1,026     | D1 session event log (append-only) + checkpoints + continuity assembler.                                                                                               |\n| `intelligence`   | `intelligence-test` / `intelligence-prod`     | 1,816     | **think + act + govern + agents + cognitive-brain, merged.** 65 files. Holds `src/govern/` (governance engine, policies, proposals) and `src/act/`.                    |\n| `workflow`       | `workflow-test` / `workflow-prod`             | 2,291     | Bound as `BFF`. Views, analytics, stream gateway, HITL Durable Object.                                                                                                 |\n| `gateway`        | `gateway-test` / `gateway-prod`               | 2,786     | Single entry point. Hand-rolled 51-entry `ROUTES` prefix table + a 1,340-line `fetch` handler.                                                                         |\n\n### 2b. Worker configs outside the release path (21)\n\nBound by something at runtime but never published by `release:deploy`:\n\n| Folder                          | Bound as                                                    | Inbound binding refs |\n| ------------------------------- | ----------------------------------------------------------- | -------------------- |\n| `spine`                         | `SPINE` (gateway)                                           | 6                    |\n| `iw-agent-runtime`              | `AGENT_RUNTIME` (gateway)                                   | 4                    |\n| `webhook-ingress`               | `WEBHOOK_INGRESS` (gateway)                                 | 1                    |\n| `mcp-pool`                      | `MCP_POOL` (gateway)                                        | 2                    |\n| `admin` / `billing` / `tenants` | `ADMIN` / `BILLING` / `TENANTS` (gateway)                   | 3 each               |\n| `folder-watcher`                | `FOLDER_WATCHER` (gateway prod only; commented out in test) | 3                    |\n| `loader` / `store`              | reached via `connector`                                     | 3 each               |\n| `task-management`               | reached via `mcp-pool`                                      | 1                    |\n\nZero inbound binding references from any `wrangler.toml` in the repo — **11 Workers**:\n\n`agent-registry` · `hermes` · `integration-management-mcp` · `marketplace-installation` · `provider-management-mcp` · `schema-ai` · `signals` · `telemetry` · `twin-orchestrator` · `vercel-mcp` · `gateway` (correctly, it is the edge)\n\n### 2c. Non-Worker folders (9)\n\n| Folder                                 | State                                                                                                                                                                                                                                                                                                                    |\n| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `act`, `govern`, `think`, `normalizer` | **Completely empty.** Untracked in git. Their real implementations live at `intelligence/src/{act,govern,think}` and `pipeline/src/normalizer`. Working-tree residue from the pre-consolidation decomposition.                                                                                                           |\n| `governance-state`                     | Contains only an empty `src/`. Untracked.                                                                                                                                                                                                                                                                                |\n| `core-engine`, `huggingface-inference` | Contain only `node_modules/`. Untracked.                                                                                                                                                                                                                                                                                 |\n| `ai-provider-mcp`                      | Three subfolders (`anthropic`, `openai`, `perplexity`), each containing only `node_modules/` and `.wrangler/`. No source.                                                                                                                                                                                                |\n| `knowledge/server`                     | **Tracked (15 files).** A complete Express + `@google-cloud/firestore` + `@google-cloud/storage` app with its own `Dockerfile` and `package.json` (`knowledge-bank-api`), nested inside a Cloudflare Worker service. Not a workspace member (the glob is `services/*`, not `services/*/*`). Never built, never deployed. |\n\n## 3. `packages/` — 40 folders\n\n### 3a. Live and consumed\n\n| Package                                                                                                                                                                   | Consumers     | Role                                                                                                                     |\n| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------ |\n| `types`                                                                                                                                                                   | 99 files      | The real shared vocabulary. Canonical entity types, aliases, playbook schema.                                            |\n| `connectors`                                                                                                                                                              | 18            | 116 files. ~90 provider modules across 15 category folders + catalog, registry, orchestrator, spine-emitter, resilience. |\n| `connector-contracts`                                                                                                                                                     | 90            | The most widely depended-on contract surface in the repo.                                                                |\n| `lib`                                                                                                                                                                     | 23            | `src/` (neon, crypto, logging, ai-provider, normalizers) **plus** a second `capability-fabric/` tree.                    |\n| `core`                                                                                                                                                                    | 8 (type-only) | Named \"Capability Fabric\". `apps/web` imports **only types** from `web-compat` and `workspace-context/types`.            |\n| `sdk`                                                                                                                                                                     | 6             | Publishable. Gateway-only capability manifest client.                                                                    |\n| `spine-entities`                                                                                                                                                          | 5             | Entity type definitions consumed by `services/spine`.                                                                    |\n| `spine-schema`                                                                                                                                                            | 4             | Publishable (`private: false`).                                                                                          |\n| `config`, `workbench-config`, `bootstrap`, `connector-utils`, `adk`, `accelerators`, `gateway-sdk`, `projection-engine`, `provider-base`, `rbac`, `tenancy`, `db`, `auth` | 1–7 each      | Narrow, single-purpose.                                                                                                  |\n\n### 3b. `packages/api` — a Worker hiding in `packages/`\n\n`packages/api` declares `name: \"hub-controller-api\"`, ships its own `wrangler.toml`, its own `schema.sql`, its own `migrations/`, and **27 route modules** (`auth`, `billing`, `ai`, `mcp`, `spend`, `cs`, `goals`, `insights`, `analytics`, `sync`, `webhooks`, `knowledge-sync`, `capability-routes`, `adk-routes`, …).\n\nIt is bound by the Gateway as `HUB_CONTROLLER` in dev, test, **and** prod — all three pointing at the same unsuffixed worker name.\n\n### 3c. Zero-consumer packages (committed)\n\n| Package                                                                                                                                | Tracked files | Notes                                                                                                                         |\n| -------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------- |\n| `ui`                                                                                                                                   | 70            | Shared component library. **No importer anywhere.** `apps/web` does not declare it as a dependency.                           |\n| `design-system`                                                                                                                        | 39            | UI primitives + shell components. **No importer anywhere.**                                                                   |\n| `contracts`                                                                                                                            | 21            | Self-described \"Frozen Integration Contracts\". **No importer anywhere.**                                                      |\n| `domain-shells`                                                                                                                        | 18            | Workbench shells (`sales-revops-workbench`, `account-success-shell` ×3 variants). No `package.json` → not a workspace member. |\n| `knowledge-bank-ui`                                                                                                                    | 19            | Standalone React app (`index.html`, `App.tsx`, 8 pages). Pairs with the dead `services/knowledge/server`.                     |\n| `coda-pack`, `handoff-adapters`, `hermes-spine-memory`, `spine-network`, `adapters`, `analytics`, `webhooks`, `spine-schema-generator` | —             | No source importer. `spine-network` ships only `dist/`; its distribution channel is the tarballs in `releases/`.              |\n\n### 3d. Local-only residue (untracked — not committed drift)\n\n`packages/config-backup-1782830543` and `packages/lib-backup-1782830543` are **untracked**. Correctly excluded by `pnpm-workspace.yaml` (`!packages/*-backup-*`). Note that `lib-backup` contains eight modules absent from live `lib`: `api-client`, `audit`, `cache`, `circuit-breaker`, `db-gate`, `error-handling`, `gateway-sdk`, `openrouter`.\n\n## 4. `apps/` — 5 folders\n\n| App         | Source files | State                                                           |\n| ----------- | ------------ | --------------------------------------------------------------- |\n| `web`       | 796          | The product. Next.js 16 App Router.                             |\n| `marketing` | 175          | Next.js App Router. 40+ marketing routes.                       |\n| `portfolio` | 24           | Next.js. Separate small site.                                   |\n| `mobile`    | 7            | Expo skeleton (`app/`, `lib/`, `app.json`). Effectively a stub. |\n| `desktop`   | 3            | Electron-Vite skeleton. Effectively a stub.                     |\n\n### `apps/web/src` interior\n\n| Subdir                                                              | Files | Notes                                                                                                                                                              |\n| ------------------------------------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `components`                                                        | 560   | Organised as `l1/` (240), `_deprecated/` (98), `ui/` (60), `l2/` (28), `core/` (28), `workbench/` (24), `activation/` (22), `layers/` (6), `l7/` (6), `l4/` (6), … |\n| `lib`                                                               | 74    | Includes three auth managers: `auth-manager.ts`, `active-auth-manager.ts`, `descope-auth-manager.ts`.                                                              |\n| `hooks`                                                             | 42    |                                                                                                                                                                    |\n| `app`                                                               | 41    | App Router.                                                                                                                                                        |\n| `legacy-pages`                                                      | 23    | 13 marketing pages + 4 `work/` pages + Dashboard/LandingPage/AuthCallback. **Actively loaded** by `app/_components/route-views.tsx` via `dynamic()`.               |\n| `contexts`, `content`, `clients`, `types`, `shims`, `api`, `config` | 32    |                                                                                                                                                                    |\n\n**App Router surfaces:** `/workbench/[department]/work/[module]`, `/workspace/[department]/work/[module]`, `/domains/[domain]/[view]`, `/app/[...segments]`, plus `/admin`, `/administration`, `/governance`, `/knowledge`, `/marketplace`, `/onboarding/[step]`, `/customer-zero`, `/settings`, and three auth entries (`/login`, `/sign-in`, `/sign-up`) plus `/auth/callback` and `/oauth/callback/[provider]`.\n\n## 5. Peripheral folders\n\n| Folder                                 | Contents                                                                                                                                           |\n| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `contracts/shared-workbench`           | 3 files: `v1.ts`, `schema.json`, `CHANGELOG.md`. The only versioned cross-surface contract outside `packages/`.                                    |\n| `infrastructure/config`                | 5 YAML manifests: connector catalog, models, spine-network, MCP tools-registry, ADK.                                                               |\n| `infrastructure/secrets/registry.yaml` | Central secret registry. Lists `normalizer` and `store` as `DATABASE_URL` consumers — `normalizer` is an empty folder.                             |\n| `marketplace`                          | `index.json` + 2 app manifests (`iw-spine-network`, `iw-continuity-bridge`) + `SPEC.md` / `PUBLISHING.md`.                                         |\n| `configs/root`                         | **Duplicate copies** of `vercel.json`, `tsconfig.base.json`, `turbo.json`, `pnpm-workspace.yaml`, plus a `firebase.json` that exists nowhere else. |\n| `configs/templates`                    | Scaffolding templates for new services/packages.                                                                                                   |\n| `scripts`                              | 89 files. 8 distinct deployment scripts predating the canonical `release/` set.                                                                    |\n| `scripts/release`                      | The 5 canonical scripts.                                                                                                                           |\n| `tests`                                | 21 files in 5 unrelated harnesses: `e2e/` (1), `edge/` (1), `functional/` (6), `playwright/` (7 suites + own config), `thesis/` (4).               |\n| `migrations`                           | 18 root SQL + `v0-core/` (11) + `supabase-export/` (1).                                                                                            |\n| `sql-migrations`                       | 85 root SQL + `d1/` (11) + `flow-a/` (57) + `restore_usage/` (2).                                                                                  |\n| `supabase/migrations`                  | 2 SQL.                                                                                                                                             |\n| `releases`                             | 67 files. Signed tarballs of `iw-spine-network` (two dated builds × 5 distribution flavours) + one platform tarball + an unpacked Python SDK.      |\n| `content-lifecycle-bundle`             | 7 GTM markdown files (content calendar, LinkedIn, newsletter, landing copy).                                                                       |\n| `public`                               | 22 brand/SEO assets + `llm.txt`, `context.json`, `.well-known/ai-context.json`.                                                                    |\n| `.hermes`                              | 234 files. Forensic report, 3 plans, and a `desktop-attachments/` archive of source specs and zips.                                                |\n| `.superpowers`                         | Brainstorm session HTML artifacts.                                                                                                                 |\n\n---\n\n# PART II — DRIFT AND DUPLICATION ASSESSMENT\n\nOrdered by severity. Every item cites the file that establishes it.\n\n## S1 — `hub-controller-api` is a second, unauthenticated entry point sharing one D1 database across all surfaces\n\nFour facts, each independently verifiable:\n\n1. `services/gateway/src/index.ts:1877–1887` — the Gateway **explicitly skips its own authentication** for every `/api/*` path that is not `/api/v1/*`, forwarding to `HUB_CONTROLLER`. The comment states: _\"The hub-controller-api handles its own JWT verification (HS256) with its own secret.\"_\n2. `services/gateway/src/index.ts:207` — `[\"/api\", \"HUB_CONTROLLER\"]` is the terminal catch-all in the `ROUTES` table.\n3. `packages/api/wrangler.toml` — **no `[env.test]`, no `[env.prod]`.** One worker, `[vars] ENVIRONMENT = \"production\"` hardcoded, one D1 binding: `database_name = \"hub-controller-db\"`, `database_id = \"b8aca43f-…\"`.\n4. `services/gateway/wrangler.toml:283, 587, 898` — dev, test, **and** prod all bind `service = \"hub-controller-api\"`.\n\n**Consequences.** (a) The \"Governance is a hard gate\" law and \"the Gateway validates JWTs\" invariant do not hold for `/api/*`; a second identity authority with an independent HS256 secret sits behind the single entry point. (b) `gateway-test` and `gateway-prod` route to the _same_ Worker against the _same_ D1 database — a direct violation of _\"Test and prod must never share KV namespaces, Queues, or D1 databases.\"_ (c) It carries `billing.ts`, `auth.ts`, and `capability-routes.ts` — money, identity, and capability execution — on that path. (d) No deploy script or workflow references `packages/api`, so its deployed code is unversioned relative to the release ledger.\n\n## S2 — Fifteen dangling service bindings\n\nCross-referencing every `name =` declaration against every `service =` reference across all 30 service `wrangler.toml` files:\n\n| Referenced target                               | Referenced by                                                                              | Actual declared name                              |\n| ----------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------- |\n| `pipeline`                                      | mcp-connector, twin-orchestrator, workflow                                                 | `integratewise-pipeline`                          |\n| `mcp-connector`                                 | connector                                                                                  | `integratewise-mcp-connector`                     |\n| `connector-sync`                                | gateway                                                                                    | `integratewise-connector-sync`                    |\n| `webhook-ingress-test`                          | gateway (test)                                                                             | `integratewise-webhook-ingress-test`              |\n| `integratewise-connector`, `-test`, `-prod`     | intelligence, iw-agent-runtime, knowledge, pipeline, twin-orchestrator, connector-sync     | `connector` / `connector-test` / `connector-prod` |\n| `integratewise-knowledge`                       | continuity, hermes, intelligence, iw-agent-runtime, knowledge, pipeline, twin-orchestrator | `knowledge`                                       |\n| `integratewise-intelligence`                    | knowledge, pipeline                                                                        | `intelligence`                                    |\n| `integratewise-continuity`                      | hermes                                                                                     | `continuity`                                      |\n| `integratewise-workflow`                        | intelligence                                                                               | `workflow`                                        |\n| `integratewise-bff`                             | hermes                                                                                     | (nothing — `workflow` is the BFF)                 |\n| `integratewise-connector-sync-test`             | workflow                                                                                   | (nothing)                                         |\n| `integratewise-integration-management-mcp-prod` | mcp-pool                                                                                   | `integratewise-integration-management-mcp`        |\n| `hub-controller-api`                            | gateway ×3                                                                                 | declared only in `packages/api/`                  |\n\nThe `integratewise-*` prefix is the pre-consolidation naming convention. The core nine were renamed to bare names (`connector`, `knowledge`, `intelligence`, `workflow`, `continuity`, `gateway`) and **the consumers were never updated**. These bindings resolve to nothing at runtime.\n\n## S3 — Test/prod binding leakage in the Gateway\n\n| Binding                         | test target                       | prod target                                  | Problem                                                         |\n| ------------------------------- | --------------------------------- | -------------------------------------------- | --------------------------------------------------------------- |\n| `HUB_CONTROLLER`                | `hub-controller-api`              | `hub-controller-api`                         | Identical. See S1.                                              |\n| `MCP_POOL`                      | `integratewise-mcp-pool`          | `integratewise-mcp-pool`                     | Identical. `mcp-pool` declares only `dev` and `prod` envs.      |\n| `WEBHOOK_INGRESS`               | `webhook-ingress-test` (dangling) | `integratewise-webhook-ingress` (unsuffixed) | `integratewise-webhook-ingress-prod` exists and is unused.      |\n| `AGENT_RUNTIME`                 | `iw-agent-runtime-test`           | `iw-agent-runtime` (unsuffixed)              | `iw-agent-runtime-prod` exists and is unused.                   |\n| `ADMIN` / `BILLING` / `TENANTS` | `-staging` workers                | unsuffixed workers                           | Those three services expose only `staging` / `production` envs. |\n\n`validate-platform-deployment.sh` only asserts `mcp-connector` isolation, so none of this is caught by `release:check`.\n\n## S4 — Environment vocabulary has four dialects\n\n`CLAUDE.md`: _\"Deployment surfaces are fixed: local `dev`, demo `test`, and live `prod`. Use `--env prod`; `production` is an alias only.\"_\n\n| Dialect                     | Services                                                                                                                                                                                         |\n| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `test` + `prod` ✅          | agent-registry, connector, connector-sync, continuity, folder-watcher, gateway, intelligence, iw-agent-runtime, knowledge, mcp-connector, pipeline, twin-orchestrator, webhook-ingress, workflow |\n| `dev` + `test` + `prod`     | marketplace-installation, provider-management-mcp, schema-ai, spine                                                                                                                              |\n| `dev` + `prod`              | integration-management-mcp, mcp-pool, task-management, vercel-mcp                                                                                                                                |\n| `staging` + `production` ❌ | admin, billing, hermes, loader, store, tenants                                                                                                                                                   |\n| `production` only ❌        | signals                                                                                                                                                                                          |\n| `staging` only ❌           | telemetry                                                                                                                                                                                        |\n\nEight services use the retired `staging`/`production` vocabulary. `signals` and `telemetry` have no test surface at all.\n\nAdditionally, the **root** `wrangler.toml` declares `[env.production]`, `[env.staging]`, `[env.development]` and an invalid `[services]` table with dotted keys — Wrangler has no such schema. The root `wrangler.jsonc` declares `assets.directory = \"services/connector-sync\"`, which is a source directory, not an asset directory. Neither root config is referenced by any release script; both are misleading dead configuration.\n\nAlso: `.github/workflows/ci-cd.yml` is named `\"CI/CD Pipeline (DISABLED)\"` but still contains seven direct `pnpm exec wrangler deploy` invocations, four of them `--env production`. Dispatch-only and disabled, but it is a live second publication path in the tree, contrary to _\"The only CI Worker publication path is Release Core Workers.\"_\n\n## S5 — Three Capability Fabrics, none of them the live one\n\n| Implementation                                                                                              | Modules                                                                                                                                                                | Runtime consumers                                                                                                                                                                                                       |\n| ----------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `packages/core/`                                                                                            | `capability-registry`, `capability-engine`, `capability-context`, `execution-orchestrator`, `governance-engine`, `workflow-router`, `capability-metrics`, `web-compat` | **None.** `apps/web` imports only `type` declarations from `web-compat` and `workspace-context/types`. No `new CapabilityEngine`, no `createDefaultRegistry`, no `CapabilityRegistryImpl` anywhere outside the package. |\n| `packages/lib/capability-fabric/`                                                                           | `registry`, `engine`, `orchestrator`, `metrics`, `bootstrap`, `capabilities`, `context`, `types` — a near-exact mirror of the above                                    | **One**, itself: `context.tsx:36` instantiates `new CapabilityEngine(registry)`. Nothing mounts that provider.                                                                                                          |\n| `services/gateway/src/workbench-capabilities.ts` + `internal/capability-execution.ts` + `services/mcp-pool` | resolve → prepare plan → approve                                                                                                                                       | **The live path.**                                                                                                                                                                                                      |\n\nTwo full engine implementations (~35 files) are committed, mutually redundant, and unreachable. `packages/core` additionally contains its own `governance-engine/` with an `approval-queue`, duplicating `services/intelligence/src/govern/` — which is the deployed one.\n\n## S6 — Retired L-layer vocabulary is the frontend's primary organizing principle, and it leaks to users\n\n`CLAUDE.md`: _\"Never expose `L1`, `L2`, `L4`, or `L7` in user-facing UI. The frontend knows only: `Entity`, `Projection`, `Capability`, `Signal`, `Context`, `Twin`.\"_\n\n- `apps/web/src/components/l1/` — **240 files**, the largest component tree in the repo\n- `l2/` (28), `l4/` (6), `l7/` (6), `layers/` (6)\n- **User-visible leak:** `apps/web/src/components/l1/domains/product-engineering/releases-view.tsx:141` renders the changelog string `\"12 L1 domain views + 14 L2 cognitive overlay components\"` in a product surface.\n- Dozens of `L1`/`L2` references in comments and section labels (`hub-today-view.tsx:142` — _\"Suggested by IntegrateWise — L2 insight card\"_).\n- The Gateway also exposes 19 `/api/v1/cognitive/*` routes. \"Cognitive\" is not one of the 12 kernel terms.\n- `services/intelligence/src/agents/specialized/twin-orchestrator.ts:22` embeds _\"CODA L4 & MCP TOOLS… Coda documents are connected L4 projection surfaces\"_ directly in a live LLM system prompt — so the retired vocabulary is inside the Twin's reasoning context, not merely in comments.\n\n## S7 — The Workbench is not one surface\n\n`CLAUDE.md`: _\"The Workbench is one surface.\"_\n\nFour parallel entry surfaces resolve to Workbench content:\n\n- `/workbench/[department]/work/[module]`\n- `/workspace/[department]/work/[module]`\n- `/domains/[domain]/[view]`\n- `/app/[...segments]`\n\n`app/workbench/[department]/page.tsx` and `app/workspace/[department]/page.tsx` are **byte-identical except for one string** — `routeBase={`/workbench/${department}`}` vs `/workspace/${department}`. Two canonical URL namespaces for the same surface.\n\nSeparately, `apps/web/src/components/capability-shell/` (`capability-dashboard.tsx`, `capability-shell.tsx`), `inline-executor/`, and `proactive-capabilities/` place a capability catalogue and executor inside the Workbench — against _\"Add capability implementations to the Capability Fabric; do not duplicate tools in the Workbench.\"_\n\n## S8 — Two SSOT claims in deployed code\n\n- `services/pipeline/src/index.ts:6` — _\"SECURITY: This is the ONLY service with Spine write credentials. No other worker may write to the Spine SSOT.\"_\n- `services/spine/src/index.ts:4` — _\"Canonical entity CRUD service. Every MCP and service reads/writes through the Spine. This is the platform's single source of truth.\"_ — and it holds `DATABASE_URL` plus a 995-line `canonical-store.ts`.\n- `services/billing/src/index.ts` — _\"v3.6: D1 is edge cache only. Supabase PostgreSQL is SINGLE SOURCE OF TRUTH.\"_\n\nThree deployed Workers assert three different single sources of truth. Compounding this, `services/pipeline/src/spine/` (1,739-line `index.ts`, plus `entity360-assembler`, `vault`, `crypto` — 2,773 LOC total) is a **second Spine implementation**, self-documented as _\"the legacy writer (Supabase tables under 'spine'/'sales'/'cs' schemas)\"_ with _\"SUPABASE is optional during cutover; callers should prefer the D1 path.\"_ Both writers are live in the release path (`pipeline` is core; `spine` is bound by the Gateway).\n\n`services/spine` is bound by the Gateway as `SPINE` and named canonical by `CLAUDE.md` — yet it is **not in `CORE_SERVICES`**, so `release:deploy --service core` never publishes it.\n\n## S9 — Migration ledger has no single ordering\n\n**17 independent migration roots**, 476 SQL files:\n\n`/migrations` · `/migrations/v0-core` · `/migrations/supabase-export` · `/sql-migrations` · `/sql-migrations/d1` · `/sql-migrations/flow-a` · `/sql-migrations/restore_usage` · `/supabase/migrations` · `services/{intelligence,knowledge,mcp-connector,pipeline,signals,tenants,workflow}/migrations` · `services/{connector-sync,workflow}/d1_migrations` · `services/task-management/sql` · `packages/api/migrations` · `packages/webhooks/migrations`\n\n`services/workflow` has **both** `migrations/` and `d1_migrations/`.\n\n**Duplicate sequence numbers** — ordering is ambiguous:\n\n- `/migrations`: `041` (`_app_category_entity_domain_classification` vs `_work_linked_governance`), `042` (`_d1_governance_checkpoints` vs `_real_tenant_rls_and_runtime_scope`), `043` (`_marketplace_installation_contract` vs `_tenant_blueprint_hydration_profiles`)\n- `/sql-migrations`: `007`, `008`, `020`, `025`, `026`, `027`, `042`, `060`, `081` — nine collisions\n\n## S10 — `apps/web` contains a complete second, orphaned application root\n\n`CLAUDE.md`: _\"`apps/web` is a Next.js App Router application with a static export for Cloudflare Pages.\"_\n\nCommitted and tracked, but unreachable from the Next build:\n\n- `apps/web/index.html:53` → `<script type=\"module\" src=\"/src/main.tsx\">`\n- `src/main.tsx` → `ReactDOM.createRoot(...)` → `src/App.tsx` → `createAppRouter()` from `src/routes.tsx`\n- `vite.config.ts`, `vite.config.d.ts`, `vite-plugins/`, `vite-env.d.ts`, and `vite` still a devDependency\n\nAll ten `package.json` scripts are Next commands. `apps/web/vercel.json` still declares `\"framework\": \"vite\"` and `\"outputDirectory\": \"dist\"` with an SPA rewrite — stale, though `git.deploymentEnabled: false` neutralises it.\n\n`next.config.mjs` also contradicts the deployment rule directly: static export is **opt-in** (`STATIC_EXPORT === \"1\"`) and the in-file comment reads _\"Production: no static export; Vercel runs Next.js server or Cloudflare Workers with Pages Functions.\"_ Meanwhile `src/app/api/marketplace/` defines five Next Route Handlers (`activate`, `apps`, `catalog`, `connections`, `onboarding-complete`), which a static export cannot serve.\n\nPlus `src/components/_deprecated/` — **102 tracked files**, excluded in `tsconfig.json` but still in the repo and still in `git`.\n\n## S11 — Retired GCP/Firebase infrastructure still committed\n\n`CLAUDE.md`: _\"Do not introduce retired infrastructure.\"_\n\n- `services/knowledge/server/` — Express + `@google-cloud/firestore` + `@google-cloud/storage` + `Dockerfile`. 15 tracked files. Pairs with the orphaned `packages/knowledge-bank-ui` (19 tracked files) — together, a complete retired \"Knowledge Bank\" product.\n- `services/mcp-connector/src/lib/firestore.ts` — inside a **core release-path Worker**.\n- `services/loader/src/lib/firestore.ts`\n- `configs/root/firebase.json` — a Firebase config existing only in the duplicate config folder.\n\n## S12 — Publishability is not gated\n\n`CLAUDE.md`: _\"The current publishable packages are `@integratewise/sdk` and `@integratewise/spine-schema`; services and implementation packages remain private deployment units.\"_\n\n`spine-schema` correctly sets `private: false` and `sdk` correctly omits it (both are intended to publish). But **16 further packages omit `private` entirely**, which npm treats as publishable:\n\n`accelerators` · `adk` · `auth` · `coda-pack` · `connector-contracts` · `connector-utils` · `connectors` · `contracts` · `core` · `db` · `gateway-sdk` · `integratewise-mcp-tool-connector` · `rbac` · `spine-network` · `tenancy` · `webhooks`\n\n`packages/connectors` contains ~90 provider integrations and `packages/core` contains the governance engine. Nothing in the tree prevents `npm publish` from a package directory.\n\n## S13 — Naming collisions and responsibility overlap\n\n| Collision                                                                                                                          | Detail                                                                                                                                                                                               |\n| ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `packages/adapters` vs `packages/connectors/src/adapters`                                                                          | The first holds **infrastructure** adapters (`r2`, `neon`, `redis`, `blob`, `ai-gateway`); the second holds **provider** adapters (`freshsales`, `razorpay`). Same word, unrelated responsibilities. |\n| `packages/accelerators` vs `packages/connectors/src/accelerators`                                                                  | Two \"accelerator\" concepts: registry/runner/sync-registry vs seven domain packs (`engineering`, `finance`, `hr`, …).                                                                                 |\n| `services/twin-orchestrator` (3,470 LOC, own Worker) vs `intelligence/src/agents/specialized/twin-orchestrator.ts` (268 LOC agent) | Two Twin orchestrators. The Worker has zero inbound bindings.                                                                                                                                        |\n| `contracts/shared-workbench` vs `packages/contracts`                                                                               | Two contract homes; the package has zero consumers.                                                                                                                                                  |\n| `configs/root/*` vs repo root                                                                                                      | Duplicate `vercel.json`, `tsconfig.base.json`, `turbo.json`, `pnpm-workspace.yaml`. No script reads `configs/root`.                                                                                  |\n| `apps/marketing/app/platform/*` vs `apps/marketing/app/product/*`                                                                  | Overlapping IA: `how-it-works`, `security` in both; `the-adaptive-spine` vs `the-adaptive-workspace`.                                                                                                |\n| `apps/marketing` (175 files) vs `apps/web/src/legacy-pages/marketing/` (13 pages)                                                  | Two marketing implementations. The `legacy-pages` set is **live**, dynamically imported by the product app's `route-views.tsx`.                                                                      |\n\n## S14 — Stale workspace and registry entries\n\n- `pnpm-workspace.yaml` includes `\"packages/connectors/*\"` — but `packages/connectors` has no sub-packages, only `src/` and `memory-repo/`. Dead glob.\n- It also includes `\"packages/projection-engine\"` redundantly (already matched by `packages/*`).\n- Its exclusions reference `apps/web-backup-*`, `apps/web.old`, `apps/web-frontend-reference` — none of which exist.\n- `infrastructure/secrets/registry.yaml` lists `normalizer` and `store` as `DATABASE_URL` consumers; `normalizer` is an empty folder.\n- `netlify.toml` exists solely to unconditionally skip Netlify builds for a site that should be disconnected (documented in the file itself).\n\n## S15 — Canonical documentation is itself a sprawl surface\n\n`AGENTS.md` names **16 documents** as canonical. `docs/architecture/` holds **94 entries**, including `CANONICAL_ARCHITECTURE.md` _and_ `CANONICAL_ARCHITECTURE_V4.md` _and_ `CANONICAL_PLATFORM_ARCHITECTURE.md` _and_ `CANONICAL_SPINE_CONVERGED.md` _and_ `CANONICAL_SPINE_SCHEMA_FOUNDATION.md` _and_ `CANONICAL_ENTITY_CONSTITUTION.md`, plus `APP_CATEGORY_ENTITY_DOMAIN_MODEL.md` alongside a `.txt` copy of the same. Thirty-three additional status/summary/audit documents sit at the repo root, several of which (`CODEBASE_OVERVIEW.md`, `CODEBASE_STRUCTURE.md`, `REPO_STRUCTURE_CLARIFICATION.md`, `CODEBASE_ISSUES_AND_CONFUSIONS.md`, `SPEC_VS_CODE_GAP_ANALYSIS.md`) describe the same territory as this document.\n\n`AGENTS.md` and `CLAUDE.md` both correctly declare precedence — the problem is not conflict resolution, it is that 787 markdown files means \"read the canonical set first\" costs 16 documents before any code is written.\n\n---\n\n# PART III — WHAT IS ACTUALLY LOAD-BEARING\n\nStripped of everything unreachable, the live system is:\n\n```\nBrowser (apps/web — Next App Router)\n  │\n  └─► gateway            ROUTES prefix table, 66 entries\n        ├─ INTERNAL_*    auth · projections · billing · tenants · admin · support · capability-status\n        ├─► pipeline     normalize → canonical write (Spine writer #1)\n        ├─► spine        Neon canonical CRUD (Spine writer #2)   ⚠ not in CORE_SERVICES\n        ├─► connector    router only ──► loader · store · mcp-connector\n        ├─► mcp-connector  MCP tools + Descope OAuth server\n        ├─► connector-sync scheduled provider sync\n        ├─► knowledge    chunk · embed · search · synthesis · promotion gate\n        ├─► intelligence think · act · govern · agents\n        ├─► workflow     (BFF) views · analytics · stream · HITL DO\n        ├─► iw-agent-runtime  TWIN_AGENT + TENANT_BRAIN DOs        ⚠ not in CORE_SERVICES\n        ├─► mcp-pool     capability routing control plane          ⚠ shared test/prod\n        └─► hub-controller-api  ⚠ AUTH BYPASSED, shared D1, lives in packages/api\n  continuity            session log — in CORE_SERVICES but not Gateway-bound;\n                        reached via mcp-connector and twin-orchestrator\n```\n\nShared code that genuinely carries weight: `@integratewise/types` (99 consumers), `@integratewise/connector-contracts` (90), `@integratewise/connectors` (18), `@integratewise/lib` (23).\n\nEverything else — 11 unbound Workers, ~14 zero-consumer packages, 2 dead Capability Fabrics, 2 orphaned application roots, a retired GCP product, 102 `_deprecated` components, 5 abandoned service folders — is inert mass.\n\n---\n\n# PART IV — REMEDIATION, ORDERED BY RATIO OF RISK REMOVED TO EFFORT\n\n### Tier 1 — Correctness and security (do first)\n\n1. **Close the `hub-controller-api` bypass (S1).** Either fold `packages/api` into `services/` with proper `env.test`/`env.prod` and isolated D1, behind Gateway auth — or delete the `[\"/api\", \"HUB_CONTROLLER\"]` catch-all and the bypass branch. As it stands, test and prod share a production database on an unauthenticated path that carries billing and identity.\n2. **Repair the 15 dangling bindings (S2)** and the 5 test/prod leaks (S3). Then **extend `validate-platform-deployment.sh`** to assert, for every binding class, that no `env.test` target equals any `env.prod` target and that every `service =` reference resolves to a declared `name =`. This converts S2/S3 into a permanently-caught class of error rather than a one-time cleanup.\n\n### Tier 2 — Restore a single truth\n\n3. **Decide the Spine writer (S8).** `services/pipeline/src/spine/` is self-labelled legacy with Supabase tables. Delete it or promote it, but stop running two writers. Then add `spine` to `CORE_SERVICES` — the Gateway already depends on it.\n4. **Normalise environment vocabulary (S4).** Convert the eight `staging`/`production` services to `test`/`prod`; give `signals` and `telemetry` a test surface. Delete both root `wrangler.toml` and `wrangler.jsonc` — neither is valid, neither is used. Delete `ci-cd.yml`.\n5. **Consolidate the migration ledger (S9).** One root, one sequence, no duplicate numbers. Per-service `migrations/` for Worker-local D1 is defensible; seven overlapping global roots is not.\n\n### Tier 3 — Delete inert mass (mechanical, large surface reduction)\n\n6. `packages/{ui,design-system,contracts,domain-shells,knowledge-bank-ui,coda-pack,handoff-adapters,hermes-spine-memory,adapters,analytics,webhooks,spine-schema-generator}` — ~200 tracked files, zero consumers.\n7. `packages/core` **or** `packages/lib/capability-fabric` — pick one to delete outright; extract only the types `apps/web` actually imports into `@integratewise/types` (S5).\n8. `services/knowledge/server`, `services/{mcp-connector,loader}/src/lib/firestore.ts`, `configs/root/firebase.json` (S11).\n9. `apps/web/{index.html,vite.config.ts,vite.config.d.ts,vite-plugins/,src/main.tsx,src/App.tsx,src/routes.tsx}` and the `vite` devDependency; fix `apps/web/vercel.json` (S10).\n10. `apps/web/src/components/_deprecated/` — 102 files (S10).\n11. Empty/untracked service folders: `act`, `govern`, `think`, `normalizer`, `governance-state`, `core-engine`, `huggingface-inference`, `ai-provider-mcp`; local `packages/*-backup-*` (salvage the eight modules unique to `lib-backup` first, or confirm they are intentionally dropped).\n12. Stale `pnpm-workspace.yaml` globs and exclusions; `configs/root/`; `netlify.toml` after disconnecting the site (S14).\n\n### Tier 4 — Vocabulary and surface discipline\n\n13. **Rename the L-layer trees (S6).** `components/l1` → the projection/domain vocabulary; `l2` → signal/insight; `l4`, `l7`, `layers` → their kernel terms. Fix the rendered string in `releases-view.tsx:141`. Rewrite the `L4` passage in the Twin's system prompt — it currently shapes model reasoning. Rename `/api/v1/cognitive/*` to kernel terms, or document \"cognitive\" as a sanctioned alias.\n14. **Collapse to one Workbench URL namespace (S7).** Keep `/workbench/…`, 301 the other three. Delete `app/workspace/`.\n15. **Retire `apps/web/src/legacy-pages/marketing/`** in favour of `apps/marketing`; resolve the `platform/*` vs `product/*` overlap inside `apps/marketing` (S13).\n16. **Add `\"private\": true`** to the 16 unmarked packages; make `release:packages:check` fail on any non-private package other than `sdk` and `spine-schema` (S12).\n17. **Prune the canonical doc set (S15).** Sixteen canonical documents is a barrier to architectural fidelity, not a guarantee of it. One lock, one implementation contract, one vocabulary reference; everything else moves to `docs/archive/`.\n\n### Tier 5 — Decide the orphans\n\n18. Eleven Workers have zero inbound bindings: `agent-registry`, `hermes`, `integration-management-mcp`, `marketplace-installation`, `provider-management-mcp`, `schema-ai`, `signals`, `telemetry`, `twin-orchestrator`, `vercel-mcp`. Each needs an explicit verdict — **wire, archive, or delete**. `hermes` is one of the 13 stages of the frozen runtime sequence yet is unreachable and still points at `integratewise-bff`, a Worker that has never existed. `twin-orchestrator` is 3,470 lines of the Twin's cognitive layer with no caller.\n19. `apps/mobile` and `apps/desktop` are 10 files combined. Either fund them or move them to `docs/archive/` so the workspace stops building them.\n\n---\n\n## Appendix — Method and confidence\n\nEvery claim above rests on one of five mechanical checks, all reproducible:\n\n1. `find` inventory of every folder with build output, `node_modules`, and release tarballs excluded.\n2. Set difference between all `name =` declarations and all `service =` references across the 30 service `wrangler.toml` files → S2, S3.\n3. `grep -rl \"@integratewise/<pkg>\"` across `apps/*/src`, `services/*/src`, `packages/*/src`, excluding the package's own directory → consumer counts, S3c, S5, S12.\n4. `git ls-files <path> | wc -l` → distinguishes committed drift from local working-tree residue. This is why `packages/*-backup-*` and the empty service folders are classified as residue rather than drift, and why `_deprecated` (102), `packages/ui` (70), and `services/knowledge/server` (15) are classified as committed.\n5. Direct read of the cited line in the cited file for every quoted string.\n\nNot covered: runtime behaviour, deployed Worker state on Cloudflare (the account may hold Workers absent from this tree, and vice versa), test pass rates, and the substance of the 787 markdown documents beyond their inventory and precedence declarations.\n"}