aiConnected v2 Core Shell — Completeness Pack
Version:1.0Date:
2026-03-26Status:
Implementation-Ready Draft (Pending Quality Gates)Owners:
Product + Architecture + Engineering
Table of Contents
- Purpose and Authority
- Program Boundary Addendum
- v1 Parity Replication Matrix
- Schema + RLS Specification Pack
- Contract Pack (OpenAPI + Canonical Types)
- Event + Gateway Operational Semantics
- Billing Enforcement State Machine
- NFR + Security Control Pack
- Cutover and Validation Runbook
- Master Acceptance Matrix
- Quality Gates
- Implementation-Ready Gate
- Appendix A — Source References
1. Purpose and Authority
This Completeness Pack is the implementation-readiness companion to the Core Shell PRD.It closes remaining ambiguity for the Shell phase so Codex can build from a blank repo without product decisions during implementation. Authority rules:
- This document and the Shell PRD govern
Shellphase behavior. - The Layout Manager PRD governs Layout Manager internals; this pack governs shell integration boundaries.
- If a requirement conflicts with shell/module boundary, shell boundary wins and the requirement is deferred to a later phase.
- Shell must be fully operable with zero modules installed.
2. Program Boundary Addendum
2.1 Phase Boundaries
Shellphase: control-plane infrastructure only.Modulesphase: first-party and imported module runtime/domain behavior.Capabilitiesphase: higher-order capability graph/composition features.
2.2 Shell Done Definition
Shell is considered done when:- Super, Agency, Business workflows operate end-to-end.
- Tenancy, RBAC, branding, billing enforcement, layout lifecycle integration, module lifecycle infra, event bus, and gateway all work.
- No module business logic is present in shell code.
- Shell supports dynamic modules via contracts, while still functioning with none installed.
2.3 Module-Absent Operating Mode (Required)
- Empty module registry does not break navigation or dashboards.
- Gateway returns deterministic errors:
MODULE_NOT_REGISTEREDMODULE_NOT_ENABLED
- Module admin UI shows actionable empty states.
- Event bus remains operational for shell-emitted events with no module subscribers.
3. v1 Parity Replication Matrix
3.1 v1 Input Sources
/Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/02-foundation-vs-apps.md/Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/03a-auth-and-permissions.md/Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/03b-module-manifest-system.md/Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/03c-branding-and-theming.md/Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/03f-db-client-server-patterns.md/Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/07-multi-tenancy-clean-port-plan.md
3.2 Disposition Table
| v1 behavior | Disposition | Reason | v2 owner package | Acceptance check |
|---|---|---|---|---|
Role constants/group helpers (permissions) | Replicate now | Core shell RBAC primitive | packages/permissions | Unit tests for role/group helpers |
| App-local route ACL maps | Retire | Drift risk, route coupling | packages/permissions + middleware | No route ACL hardcoding in page code |
Manifest normalization/validation/assessment (app-sdk) | Replicate now | Required module onboarding backbone | packages/module-sdk | Contract tests pass for valid/invalid manifests |
| Hardcoded fallback module list in manifest layer | Retire | Must be registry-driven | module_registry data | Empty registry works cleanly |
| Import assessment report concept | Replicate now | Operationally valuable for admins | packages/module-sdk + shell UI | Import attempt writes report record |
Deep internal imports (@sec-admn/*/src/*) | Retire | Boundary and version fragility | all packages | Static check fails on internal-path imports |
| Supabase client/server/admin wrapper pattern | Replicate now | Proven shell utility pattern | packages/db | Auth/session tests pass |
| Integration inheritance resolution pattern | Replicate now (genericized) | Strong tenancy behavior | packages/db + packages/theme | Inheritance tests for parent/child contexts |
| Next-coupled shared DB internals | Rebuild | Keep behavior, reduce framework coupling | packages/db | Package APIs usable outside app routes |
| Theme merge/default concept | Replicate now (tokenized) | Needed for white-label inheritance | packages/theme | Token inheritance + override tests |
| Fragmented theming implementation | Retire | Must centralize token governance | packages/theme | Single token source of truth |
| Tenancy context + impersonation behavior | Replicate now | Operator-critical shell behavior | packages/permissions + packages/db | Impersonation and scope tests |
| Chat runtime logic in shell APIs/routes | Defer to Modules phase | Module domain logic | n/a | Shell has no chat business handlers |
| KB pipeline/worker in shell | Defer to Modules phase | Module domain logic | n/a | Shell runs with no KB runtime |
| Plasmic host/render integration | Retire | Not aligned with v2 shell principles | n/a | No Plasmic dependency in shell |
Duplicate .jsx/.tsx route pairs and .old files | Retire | Non-deterministic maintenance | repo hygiene | Zero duplicate legacy route variants |
3.3 Parity Acceptance Rules
- Every
Replicate nowrow has package ownership and automated validation. - Every
Deferrow is absent in shell implementation. - Every
Retirerow has an explicit replacement or removal rationale in docs.
4. Schema + RLS Specification Pack
4.1 Migration Order
001_identities.sql002_workspaces.sql003_memberships_roles_permissions.sql004_themes.sql005_layouts.sql006_module_registry_installations.sql007_events_audit.sql008_billing.sql009_contacts.sql010_rls_policies.sql011_seed_role_templates.sql
4.2 Table-Level Specification
| Table | Key columns | Constraints | Indexes | Primary writers | Primary readers |
|---|---|---|---|---|---|
users | id, auth_user_id, email, status | auth_user_id unique | email | auth sync/system | self/admin/super |
workspaces | id, type, parent_workspace_id, name, status | parent self-FK | (parent_workspace_id,type) | super/agency admin | scoped members |
workspace_memberships | id, workspace_id, user_id, role_template, active | unique (workspace_id,user_id) | workspace_id, user_id | workspace admins | scoped members |
roles | id, code, scope_type | code unique | code | system seed | auth system |
permissions | id, code | code unique | code | system seed | auth system |
role_permissions | role_id, permission_id | unique pair | role_id, permission_id | system/admin | auth system |
membership_permissions | membership_id, permission_id, allow | unique pair | membership_id | workspace admins | auth system |
themes | id, workspace_id, token_payload, version | unique (workspace_id,version) | (workspace_id,version desc) | admins | shell render/settings |
layout_definitions | id, workspace_id, surface_key, current_version_id | unique (workspace_id,surface_key) | (workspace_id,surface_key) | layout manager | shell renderer/admin |
layout_versions | id, layout_definition_id, version_num, state, tree_json | unique (layout_definition_id,version_num) | (layout_definition_id,state) | layout manager | shell renderer/admin |
module_registry | id, module_key, version, manifest_json, status | unique (module_key,version) | (module_key,status) | super/system | module admin/gateway |
module_installations | id, workspace_id, module_key, state, config_json | unique (workspace_id,module_key) | (workspace_id,state) | admins | nav/gateway |
billing_accounts | id, workspace_id, stripe_customer_id, status | unique workspace_id, unique stripe_customer_id | stripe_customer_id | billing service | billing/admin |
subscriptions | id, billing_account_id, stripe_sub_id, state, period_end | unique stripe_sub_id | (billing_account_id,state) | billing service | enforcement/admin |
events | id, workspace_id, event_name, payload_json, delivery_state, correlation_id | append-only | (workspace_id,event_name,occurred_at desc), correlation_id | shell/modules | subscribers/admin |
audit_logs | id, workspace_id, actor_user_id, action, target_type, target_id, metadata_json, created_at | append-only | (workspace_id,created_at desc), (actor_user_id,created_at desc) | system only | admin/super |
contacts | id, workspace_id, name, email, phone | workspace scope | (workspace_id,email) | shell/module contracts | scoped users/modules |
4.3 RLS Policy Baseline
workspaces: member-scoped read, super full read/manage.workspace_memberships: workspace admins manage; users self-read membership rows.themes:branding.editrequired for write, membership required for read.layout_definitions/layout_versions:layouts.editfor write; membership for read.module_installations:modules.install|modules.enable|modules.disablefor write; membership for read.billing_accounts/subscriptions:billing.managefor write/read in scope; super override.events: emitter must be authenticated and scoped; reads scoped by workspace.audit_logs: write by trusted service role only; read by workspace admins and super.
4.4 Tenancy and Integrity Invariants
- All mutable business rows are workspace-scoped unless explicitly global.
- Cross-workspace access is denied-by-default.
layout_versionsare immutable snapshots.eventsandaudit_logsare append-only.- Impersonation must not bypass workspace permission checks.
4.5 Retention Policy (MVP)
events: retain minimum 180 days online.audit_logs: retain minimum 365 days online.- Archival beyond this window is operationally optional in MVP.
5. Contract Pack (OpenAPI + Canonical Types)
5.1 Endpoint Families and Minimum Contracts
| Domain | Endpoint | Purpose | Auth | Required permission |
|---|---|---|---|---|
| Auth | POST /auth/sign-in | start session | no | n/a |
| Auth | POST /auth/sign-out | end session | yes | n/a |
| Auth | POST /auth/impersonation/start | begin impersonation | yes | super scope |
| Auth | POST /auth/impersonation/stop | stop impersonation | yes | super scope |
| Workspaces | POST /workspaces | create top-level workspace | yes | scope admin |
| Workspaces | POST /workspaces/{id}/children | create child business workspace | yes | agency admin |
| Workspaces | POST /workspaces/switch | switch active workspace | yes | membership |
| Memberships | POST /memberships | invite/add member | yes | users.invite |
| Memberships | PATCH /memberships/{id} | role/state update | yes | users.manage |
| Permissions | GET /permissions/effective | resolve effective ACL | yes | membership |
| Themes | GET /themes/current | fetch effective theme | yes | membership |
| Themes | PUT /themes/current | update theme tokens | yes | branding.edit |
| Layouts | POST /layouts/{id}/save | save draft | yes | layouts.edit |
| Layouts | POST /layouts/{id}/preview | preview draft | yes | layouts.edit |
| Layouts | POST /layouts/{id}/test | validate/test draft | yes | layouts.edit |
| Layouts | POST /layouts/{id}/publish | publish version | yes | layouts.edit + policy |
| Layouts | POST /layouts/{id}/rollback | rollback publish | yes | layouts.edit + policy |
| Modules | POST /modules/import | validate/register module package | yes | modules.install |
| Modules | POST /modules/{key}/install | install in workspace | yes | modules.install |
| Modules | POST /modules/{key}/enable | enable module | yes | modules.enable |
| Modules | POST /modules/{key}/disable | disable module | yes | modules.disable |
| Modules | DELETE /modules/{key}/uninstall | uninstall module | yes | modules.install |
| Events | POST /events | emit event | yes | contract-based |
| Events | GET /events | query events | yes | workspace scope |
| Gateway | ALL /gateway/{moduleKey}/{path...} | proxy to module target | yes | auth+perm+billing+enabled |
| Billing | GET /billing/status | entitlement status | yes | workspace admin |
| Billing | POST /billing/recovery | recovery actions | yes | workspace admin |
| Billing | POST /billing/reconcile | stripe reconciliation | yes | super/system |
5.2 Canonical Types
WorkspaceContext
EffectivePermissions
ModuleManifest
ModuleInstallationState
EventEnvelope
GatewayForwardHeaders
BillingEntitlementState
5.3 Stable Error Model
| Code | HTTP | Meaning |
|---|---|---|
AUTH_REQUIRED | 401 | missing/invalid session |
SESSION_INVALID | 401 | session expired/invalidated |
WORKSPACE_REQUIRED | 400 | no active workspace context |
WORKSPACE_FORBIDDEN | 403 | workspace out of scope |
PERMISSION_DENIED | 403 | capability denied |
IMPERSONATION_FORBIDDEN | 403 | invalid impersonation action |
MANIFEST_INVALID | 422 | manifest fails schema/contract |
MANIFEST_INCOMPATIBLE | 422 | manifest conflicts with platform constraints |
MODULE_NOT_REGISTERED | 404 | unknown module key |
MODULE_NOT_ENABLED | 409 | module not enabled in workspace |
MODULE_TARGET_UNHEALTHY | 503 | runtime target unavailable |
EVENT_SCHEMA_INVALID | 422 | event payload/schema invalid |
EVENT_DELIVERY_FAILED | 502 | downstream delivery failed after retries |
BILLING_REQUIRED | 402 | no valid entitlement |
BILLING_SUSPENDED | 402 | entitlement suspended |
VALIDATION_BLOCKING | 422 | lifecycle blocked by validation |
CONFLICT | 409 | optimistic concurrency/version conflict |
RATE_LIMITED | 429 | request throttled |
INTERNAL_ERROR | 500 | server fault |
6. Event + Gateway Operational Semantics
6.1 Event Delivery Behavior
- Ordering guarantee is scoped to
(workspace_id, stream_key)only. - Publisher must provide idempotency key for retry-safe writes.
- Retry policy: exponential backoff, max 5 attempts.
- Terminal failures go to dead-letter store with replay capability.
- Replay requires admin/super authorization in same workspace scope.
- Event envelope schema is validated pre-persist and pre-delivery.
6.2 Event Authorization
- Emitter can publish only declared/allowed event names.
- Subscriber can consume only declared/allowed event names.
- Cross-workspace event reads are forbidden.
- All delivery attempts and failures are auditable.
6.3 Gateway Forwarding Behavior
- Resolve module target from
module_installations + module_registry. - Apply pre-forward checks in this order:
- auth/session
- workspace scope
- permission
- billing entitlement
- module registered/enabled
- target health
- Forward trusted server-issued claims only.
- Default timeout 8s.
- Circuit breaker opens on repeated failures; shell returns
MODULE_TARGET_UNHEALTHY. - Every forward logs correlation id, target, and enforcement decision.
6.4 Impersonation Protections
- Forwarded claims include actor/effective identity separation when impersonating.
- Module cannot self-assert identity.
- Client-supplied identity headers are stripped at gateway edge.
7. Billing Enforcement State Machine
7.1 States
activepast_duegracesuspendedcanceled
7.2 Transition Rules
active -> past_due: Stripe payment failure event.past_due -> grace: grace window begins.grace -> suspended: grace expiry without recovery.past_due|grace|suspended -> active: successful recovery payment.suspended -> canceled: explicit cancellation/termination.active -> canceled: explicit cancellation.
7.3 Entitlement Effects
| State | Module usage | New module activation | Recovery routes |
|---|---|---|---|
active | allowed | allowed | allowed |
past_due | allowed (warn) | allowed (warn) | allowed |
grace | allowed (warn) | blocked | allowed |
suspended | blocked | blocked | allowed |
canceled | blocked | blocked | allowed (reactivation only) |
7.4 Stripe Truth and Reconciliation
- Stripe webhooks are source of truth for billing events.
- Shell stores normalized entitlement snapshots.
- Reconciliation job repairs divergence and is idempotent.
- Every state transition writes
audit_logs.
8. NFR + Security Control Pack
8.1 MVP SLO Targets
- Auth guard decision p95
< 200ms. - Workspace switch p95
< 500ms. - Module route resolution p95
< 300ms. - Gateway overhead p95
< 150ms(excluding module runtime time). - Layout publish/rollback acknowledgment p95
< 2s. - Event enqueue p95
< 250ms.
8.2 Reliability Controls
- Publish and rollback are idempotent by operation key.
- Autosave recovery restores last valid layout draft after interruption.
- Audit log coverage for privileged actions is 100%.
- Dead-letter replay is safe and workspace-scoped.
8.3 Security Controls
- Deny-by-default authorization.
- Server-side enforcement independent of UI.
- Impersonation requires explicit start/stop and audit events.
- Header trust boundary enforced at gateway.
- Cross-workspace access denied unless explicit super scope.
9. Cutover and Validation Runbook
9.1 Blank-Repo Build Sequence
- Bootstrap monorepo + package boundaries.
- Implement auth/session and workspace context.
- Implement tenancy schema + RLS + permission core.
- Implement theme token system + inheritance.
- Implement module manifest validator + registry/install lifecycle.
- Implement event bus baseline.
- Implement gateway baseline.
- Integrate Layout Manager shell touchpoints.
- Implement billing entitlement enforcement.
- Run acceptance suite and dry-run audits.
9.2 Environment Contracts
local: developer auth + seed data + billing sandbox mode.staging: real webhook paths + production-like RLS + full acceptance tests.prod: strict secrets, audit retention enabled, alerting active.
9.3 v1 Backfill Approach (Shell phase)
- Migrate shell-owned entities only.
- Do not migrate module domain records in shell phase.
- Rebuild module installation state from valid manifests.
- Preserve user/workspace/membership continuity.
9.4 Go-Live Checklist
- All acceptance matrix rows passing.
- Billing transition tests passing in staging.
- Impersonation audit verified.
- Module-absent mode verified.
- Rollback drill completed and documented.
10. Master Acceptance Matrix
| Requirement | Schema artifact | API contract | UI route | Enforcement rule | Automated test | Status |
|---|---|---|---|---|---|---|
| Super creates Agency workspace | workspaces,workspace_memberships | POST /workspaces | Super dashboard | role policy | integration | pending |
| Agency creates Business child | workspaces.parent_workspace_id | POST /workspaces/{id}/children | Agency dashboard | scope check | integration | pending |
| Workspace RBAC enforcement | roles/permissions tables | GET /permissions/effective | protected shell screens | middleware + RLS | unit+integration | pending |
| Workspace switch | memberships + session context | POST /workspaces/switch | workspace switcher | membership required | e2e | pending |
| Super impersonation | audit_logs | /auth/impersonation/* | super tools | super-only + scope | integration | pending |
| Branding inheritance | themes | /themes/current | branding settings | branding.edit | integration | pending |
| Layout draft/publish/rollback lifecycle | layout_definitions,layout_versions | /layouts/* | layout manager | layouts.edit + validators | e2e | pending |
| Module import/validation | module_registry | POST /modules/import | module admin | manifest validator | contract tests | pending |
| Module install/enable/disable/uninstall | module_installations | /modules/{key}/* | module admin | module permissions | integration | pending |
| Dynamic nav from installs | install state | modules list APIs | shell nav | enabled-only filter | e2e | pending |
| Event emit/query | events | /events | events monitor | schema + auth + workspace | integration | pending |
| Gateway forwarding | registry+installs | /gateway/{module}/{path} | module shell entry | auth+perm+billing+enabled | integration | pending |
| Billing state access gating | billing_accounts,subscriptions | /billing/status | billing settings | entitlement middleware | integration | pending |
| Module-absent shell behavior | empty registry/installs | modules + gateway APIs | module admin/nav | graceful empty/error paths | e2e | pending |
| Audit completeness | audit_logs | privileged endpoints | audit screen | system-only writes | integration | pending |
| No module business logic in shell | package boundaries | n/a | all shell routes | architecture review gate | static+review | pending |
11. Quality Gates
- No unresolved
TBDin shell-critical sections. - Every endpoint family has request/response/error contracts.
- Every shell-owned entity has schema + RLS policy.
- Every v1 parity item has
replicate/defer/retiredisposition and acceptance method. - Shell/module ownership is unambiguous to independent reviewer.
12. Implementation-Ready Gate
Mark this packREADY only when:
- Quality gates all pass.
- Acceptance matrix has no unresolved ownership or contract gaps.
- Independent architecture review signs shell/module boundary conformance.
- Module-absent mode tests are green.