{"slug":"developers/FRONTEND_PLATFORM_API_AND_DISCOVERY_SPEC","title":"Frontend Platform API and Discovery Specification","section":"developers","sectionLabel":"Developers","status":"unclassified","type":"document","path":"developers/FRONTEND_PLATFORM_API_AND_DISCOVERY_SPEC.mdx","bytes":18237,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n**Status:** Derived implementation handoff — required for frontend/backend wiring\n\n**Date:** 2026-07-28\n**Authority:** `ARCHITECTURE_LOCK.md`, `IMPLEMENTATION_CONTRACT_v1.1.md`, and `RUNTIME_SUBSTRATE_AND_SURFACE_CONTRACT.md`\n\n## 1. Frontend boundary\n\n`apps/web` is a Product client. It communicates with the Cloudflare Gateway\nonly. It does not call Neon, D1, KV, R2, Nango, a provider API, Hermes, or an\ninternal MCP directly.\n\n```text\nWorkbench / Canvas / Onboarding\n→ typed Gateway client\n→ Gateway identity + tenant + RBAC resolution\n→ Projection Engine / Platform service / governed command\n→ semantic response\n→ Product rendering\n```\n\nThe single public base URL is `NEXT_PUBLIC_IW_API_URL`. Release closure must\nretire `NEXT_PUBLIC_API_BASE_URL` and every production fallback to localhost.\n\n## 1.1 Three Product presentation surfaces\n\n| Surface                                    | Controller                          | Communication                                                    |\n| ------------------------------------------ | ----------------------------------- | ---------------------------------------------------------------- |\n| Browser Workbench                          | IntegrateWise frontend              | Typed Gateway client                                             |\n| IW-Spine-Network Plugin                    | ChatGPT/Codex or compatible AI host | MCP App host bridge to the public IW tools/resources             |\n| IW-Spine-Network MCP in an ordinary client | MCP client                          | Remote MCP transport; text/JSON fallback and Open Workbench link |\n\nThe Plugin widget is a sandboxed, focused control surface—not a second full\nfrontend and not a DOM patch. It cannot access host cookies, storage or other\napp credentials. The MCP Marketplace lane launches the browser Workbench for\nthe full tables/pages/canvas experience.\n\n## 2. Every request and response\n\n### Request requirements\n\nGateway derives authority from the Clerk session. The browser may send display\ncontext such as selected canvas or requested view, but may not authoritatively\nsend user ID, tenant ID, role, permission, connector credential, policy\ndecision, or provider scope.\n\n```ts\ninterface GatewayRequestContext {\n  // Clerk access token; transported by the typed client.\n  authorization: `Bearer ${string}`;\n  // Optional correlation for client action tracing.\n  \"x-iw-correlation-id\"?: string;\n  // Optional requested rendering context; Gateway validates it.\n  requestedView?: string;\n}\n```\n\n### Response envelope\n\nEvery non-streaming semantic response uses an equivalent versioned envelope.\n\n```ts\ninterface GatewayResponse<T> {\n  data: T;\n  meta: {\n    contractVersion: string;\n    requestId: string;\n    traceId?: string;\n    tenantId: string;\n    scope: { role: string; permissions: string[] };\n    generatedAt: string;\n    freshnessAt?: string;\n    state: \"ready\" | \"partial\" | \"degraded\" | \"pending\";\n    evidenceRefs?: string[];\n    nextActions?: Array<{ capability: string; approval: \"none\" | \"policy\" | \"human\" }>;\n  };\n}\n\ninterface GatewayProblem {\n  error: {\n    code:\n      | \"UNAUTHENTICATED\"\n      | \"FORBIDDEN\"\n      | \"NOT_FOUND\"\n      | \"CONFLICT\"\n      | \"VALIDATION_FAILED\"\n      | \"RATE_LIMITED\"\n      | \"DEPENDENCY_UNAVAILABLE\"\n      | \"PARTIAL_EVIDENCE\"\n      | \"INTERNAL\";\n    message: string;\n    requestId: string;\n    traceId?: string;\n    retryable: boolean;\n    remediation?: string;\n  };\n}\n```\n\n`partial` and `degraded` are valid render states. Product must show them; it\nmust not substitute seed/demo data for a failed live call.\n\n## 3. Discovery is the frontend’s first read\n\nAfter sign-in or workspace switch, Product calls the discovery manifest before\nrendering navigation or connector-specific capabilities.\n\n```text\nClerk sign-in / workspace switch\n→ GET /api/v1/workspace/discovery\n→ Gateway resolves tenant, membership, RBAC, configuration, activation,\n  connector/schema/capability health and projection manifest\n→ Product renders permitted sidebar, Work routes and action availability\n```\n\n```ts\ninterface WorkspaceDiscoveryManifest {\n  tenant: { id: string; workspaceId: string; name: string };\n  identity: { userId: string; role: string; permissions: string[] };\n  navigation: Array<{\n    id: string;\n    label: string;\n    route: string;\n    mode: \"read\" | \"operate\" | \"admin\";\n  }>;\n  work: { routeKey: string; projectionId: string; department: string; industry?: string }[];\n  connectors: Array<{ key: string; state: \"available\" | \"connected\" | \"degraded\" | \"unavailable\" }>;\n  capabilities: Array<{\n    key: string;\n    state: \"available\" | \"degraded\" | \"unavailable\";\n    approval: \"none\" | \"policy\" | \"human\";\n  }>;\n  activation: { state: \"not_started\" | \"in_progress\" | \"ready\" | \"blocked\"; blockers: string[] };\n}\n```\n\nThis required Gateway projection contract is now routed by Gateway to the Spine\ndiscovery handler and has real-SQL integration coverage. Production deployment,\ncross-tenant/RBAC negative tests and Product acceptance remain open. The\nimplemented route is still not permission to embed sidebar or connector\navailability as client-side constants.\n\n## 4. Endpoint families\n\nEndpoints are semantic contracts, not table APIs. Route spelling may be\nversioned, but the following ownership and request/response semantics are\nrequired.\n\n| Product surface / intent        | Gateway endpoint family                                                                                                                | Backend owner                                     | Response                                                                                  |\n| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------- |\n| Bootstrap Product after sign-in | `GET /api/v1/workspace/discovery`                                                                                                      | Gateway + Configuration + Activation + Projection | navigation, RBAC, Work routes, connector/capability availability, activation blockers.    |\n| Onboarding                      | `/api/v1/workspace/initialize`; `/api/v1/workspace/configure-domain`; `/api/v1/workspace/configure-rbac`; `/api/v1/workspace/activate` | Gateway + Configuration + Activation              | accepted state, next step, hydration/readiness and blockers.                              |\n| Connector tray                  | `GET /api/v1/connectors/catalog`; `GET /api/v1/workspace/connectors`; connection health routes                                         | Integration Manager                               | catalog eligibility, installed connections, health, schema/sync state—never credentials.  |\n| Connect/reconnect/revoke        | `/api/v1/connectors/{provider}/authorize`; callback; governed connection commands                                                      | Integration Manager + credential wall             | redirect/connection lifecycle and remediation.                                            |\n| Shared Workbench                | `GET /api/v1/projections/{projectionKey}`                                                                                              | Projection Engine                                 | versioned `SharedWorkbench`, provenance, freshness, capabilities and degraded state.      |\n| Work views                      | `GET /api/v1/projections/{projectionKey}?view={viewKey}`                                                                               | Projection Engine                                 | RBAC-scoped role/department/industry view contract.                                       |\n| Home, Inbox, My Work            | `GET /api/v1/projections/home`; `/inbox`; `/my-work`                                                                                   | Projection Engine                                 | composite attention projections, not direct event/work table reads.                       |\n| Entity / canvas                 | `GET /api/v1/entities/{entityType}/{entityId}`; projection/canvas route                                                                | Projection Engine + Spine read model              | permitted entity graph, evidence, timeline, context and layout-safe data.                 |\n| Active Context                  | `POST /api/v1/context/assemble` or context included by the entity/projection response                                                  | Projection Engine + Continuity                    | bounded entity/view/evidence/capability context; never raw tables or unrestricted memory. |\n| Communications                  | `/api/v1/projections/communications/*`                                                                                                 | Projection Engine + communication services        | scoped conversation continuity, attachments/evidence references and actions.              |\n| Documents / knowledge           | `/api/v1/knowledge/*`; `/api/v1/search`                                                                                                | Knowledge/evidence service                        | metadata, retrieval results and signed/authorised artifact access—not raw storage keys.   |\n| Twin interaction                | `/api/v1/twin/ask`; `/api/v1/twin/assign`; prepared-work/action-plan routes; corresponding public semantic tools                       | Twin runtime + public semantic contracts          | grounded draft/context/plan; no direct execution.                                         |\n| Approve/reject                  | `/api/v1/approvals/{id}/decision`; governed proposal/capability-run routes                                                             | Governance → Hermes                               | decision, approval token state, receipt and projection invalidation signal.               |\n| Platform modules                | `/api/v1/platform/{module}/*` or the owning versioned service family                                                                   | respective Platform service                       | RBAC-scoped operational projection and governed commands.                                 |\n| Administration                  | `/api/v1/admin/*`                                                                                                                      | Administration services                           | administrative projection; secrets and raw security events remain protected.              |\n\nThese are the target semantic families. A route is not **Implemented** merely\nbecause it appears in this table.\n\n## 5. Frontend call sequence\n\n```mermaid\nsequenceDiagram\n    participant U as User\n    participant W as Workbench\n    participant G as Gateway\n    participant P as Projection Engine\n    participant S as Platform services\n\n    U->>W: Sign in or switch workspace\n    W->>G: GET workspace/discovery\n    G->>S: Resolve identity, tenant, RBAC, activation, availability\n    G-->>W: Discovery manifest\n    U->>W: Open Home / Work / Platform surface\n    W->>G: GET semantic projection\n    G->>P: Compose permitted projection\n    P->>S: Read canonical truth + bounded cache\n    G-->>W: Data + freshness + provenance + available actions\n    U->>W: Request consequential action\n    W->>G: POST semantic command + correlation ID\n    G->>S: Governance → Hermes → connector → re-ingest\n    S-->>G: Outcome + invalidation\n    G-->>W: Receipt / refreshed projection state\n```\n\n## 6. Per-click Active Context and Twin activation\n\nNot every DOM click is a Platform or model request. A **material click** changes\nthe selected route, entity, work item, decision, signal, document, queue,\nproposal or approval.\n\n```text\nMaterial selection\n→ resolve projection/entity version\n→ assemble or reuse tenant/RBAC-bounded Active Context\n→ update selected entity, relationships, timeline, evidence, freshness,\n  capabilities and OODA observation state\n→ render the Workbench\n→ keep Twin silent unless explicitly invoked or a material signal qualifies\n```\n\nFrontend rules:\n\n1. Deduplicate and cancel stale context requests during rapid navigation.\n2. Cache context only by tenant, workspace, authority fingerprint, projection\n   version and selected object; invalidate it on the corresponding Gateway\n   signal.\n3. A click may update lightweight passive observation. It must not\n   automatically open a Twin panel or start expensive model reasoning.\n4. `Ask Your Twin` sends the active context reference plus the user's question;\n   it does not reconstruct organization context in the browser.\n5. `Assign Your Twin` creates a persistent draft/proposal/assignment, never an\n   ungoverned provider action.\n6. A qualified proactive signal may render a small inline notice. Deeper Twin\n   detail still requires review/engagement.\n7. Raw clicks and local hover/scroll telemetry are observations, not canonical\n   truth. Promotion and retention follow policy.\n8. Frontend tables are entity-shaped projections plus draft working state. They\n   are not the canonical store.\n9. The autotuning agent may rank, sort, group or suggest projection changes, but\n   it cannot bypass Triage, approval or governed backend writeback.\n\n## 7. Discovery and connector expansion\n\nThe frontend discovery manifest is a projection of Platform discovery; it is\nnot provider metadata fetched in the browser.\n\n```text\nConnector authenticated\n→ Integration Manager discovery run\n→ provider schemas, operations, events and scopes classified\n→ approved mapping to canonical entities/relationships/capabilities\n→ activation and capability availability recalculated\n→ workspace discovery manifest and affected projections invalidated\n→ Product receives new permitted connector/capability state\n```\n\nUnknown provider structure becomes an extension candidate. It does not create a\nnew frontend table route or automatically alter canonical schema.\n\nHost-connected applications are not automatically inherited by\nIW-Spine-Network. Discovery records one of three origins:\n\n- `host_composed`: the host can use another app in the current conversation;\n- `host_delegated`: the host exposes a supported capability and the user/admin\n  grants a persistent IW binding;\n- `iw_direct`: the user authorizes the provider in Integration Manager.\n\nThe frontend groups duplicate provider/account connections only when tenant,\naccount, user, provider workspace, authority and provenance match. It always\nshows origin and precedence.\n\n## 8. Frontend implementation rules\n\n1. Use one typed Gateway client and one public API base URL.\n2. Call discovery at authentication/workspace boundaries; cache only as bounded,\n   versioned UI state and invalidate on Gateway signals.\n3. Drive sidebar and Work routes from discovery/role config, not from provider\n   names, business domains or direct database assumptions.\n4. Bind each surface to a `projectionId`, contract version, loading state,\n   partial/degraded state, and permitted commands.\n5. Use server-issued identifiers and evidence references. Do not expose provider\n   credentials, raw object keys, internal MCP routes, or internal Pool tools.\n6. For canvas data, render safe semantic shapes. JSON is display data, not a\n   query language against Fortress tables.\n7. Persist an intake draft locally only as a draft. Submit it through Gateway so\n   the artifact/event/provenance/triage path is recorded.\n8. Treat operational-memory and agent-memory records as staged, promoted\n   entities. The frontend may display and edit drafts, but Fortress persistence\n   only happens after triage classification, promotion queue placement and human\n   approval.\n\n## 9. Entity tables and memory promotion\n\n```text\nUser action / external event / agent observation\n→ Frontend creates or updates an entity-shaped draft/table/canvas projection\n→ Gateway emits a semantic event or command\n→ Triage classifies, links, deduplicates and scores it\n→ Promotion queue stages candidate operational memory or canonical truth\n→ Human approval decides whether it is promoted\n→ Fortress writeback occurs through the governed backend writer\n→ Projection invalidation refreshes the frontend tables and canvases\n```\n\nThe frontend repo therefore holds:\n\n- projection contracts for entity tables and canvases;\n- draft working state for agent memory and operational memory;\n- typed Gateway calls for create/update/promote/approve flows; and\n- rendering logic for the resulting RBAC-scoped projections.\n\nThe frontend repo does not hold:\n\n- canonical truth ownership;\n- direct Neon write authority;\n- provider credentials;\n- promotion authority; or\n- an alternate schema that bypasses the backend.\n\n## 10. Wiring acceptance checklist\n\n- [x] Gateway routes `/api/v1/workspace/discovery` to the Spine discovery\n      handler, with real-SQL response-mapping coverage.\n- [ ] Sign-in returns a tenant/RBAC-scoped discovery manifest.\n- [ ] Every sidebar item has a projection/command contract and a forbidden-state\n      behaviour; unavailable items do not leak data or routes.\n- [ ] Home, Inbox and Work prove multi-source composition with freshness and\n      partial-state handling.\n- [ ] Role/department/industry changes re-resolve the Work projection without\n      changing schema or browser authority.\n- [ ] Material record clicks hydrate bounded Active Context without opening a\n      permanent Twin surface or launching unnecessary model work.\n- [ ] Ask/Assign reuse the selected context and evidence; no browser-side\n      provider joins or hidden raw-memory reads occur.\n- [ ] A connector changes from available → authenticated → operational through\n      Gateway, and discovery updates the Product after activation.\n- [ ] A governed action returns a receipt and refreshes the affected projection\n      only after outcome/re-ingestion handling.\n- [ ] Browser network tests show no direct Neon, R2, D1/KV, Nango, provider or\n      internal MCP Pool calls.\n"}