Skip to main content

aiConnected v2 Core Shell — Completeness Pack

Version: 1.0
Date: 2026-03-26
Status: Implementation-Ready Draft (Pending Quality Gates)
Owners: Product + Architecture + Engineering

Table of Contents

  1. Purpose and Authority
  2. Program Boundary Addendum
  3. v1 Parity Replication Matrix
  4. Schema + RLS Specification Pack
  5. Contract Pack (OpenAPI + Canonical Types)
  6. Event + Gateway Operational Semantics
  7. Billing Enforcement State Machine
  8. NFR + Security Control Pack
  9. Cutover and Validation Runbook
  10. Master Acceptance Matrix
  11. Quality Gates
  12. Implementation-Ready Gate
  13. 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:
  1. This document and the Shell PRD govern Shell phase behavior.
  2. The Layout Manager PRD governs Layout Manager internals; this pack governs shell integration boundaries.
  3. If a requirement conflicts with shell/module boundary, shell boundary wins and the requirement is deferred to a later phase.
  4. Shell must be fully operable with zero modules installed.

2. Program Boundary Addendum

2.1 Phase Boundaries

  1. Shell phase: control-plane infrastructure only.
  2. Modules phase: first-party and imported module runtime/domain behavior.
  3. Capabilities phase: higher-order capability graph/composition features.

2.2 Shell Done Definition

Shell is considered done when:
  1. Super, Agency, Business workflows operate end-to-end.
  2. Tenancy, RBAC, branding, billing enforcement, layout lifecycle integration, module lifecycle infra, event bus, and gateway all work.
  3. No module business logic is present in shell code.
  4. Shell supports dynamic modules via contracts, while still functioning with none installed.

2.3 Module-Absent Operating Mode (Required)

  1. Empty module registry does not break navigation or dashboards.
  2. Gateway returns deterministic errors:
    • MODULE_NOT_REGISTERED
    • MODULE_NOT_ENABLED
  3. Module admin UI shows actionable empty states.
  4. 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 behaviorDispositionReasonv2 owner packageAcceptance check
Role constants/group helpers (permissions)Replicate nowCore shell RBAC primitivepackages/permissionsUnit tests for role/group helpers
App-local route ACL mapsRetireDrift risk, route couplingpackages/permissions + middlewareNo route ACL hardcoding in page code
Manifest normalization/validation/assessment (app-sdk)Replicate nowRequired module onboarding backbonepackages/module-sdkContract tests pass for valid/invalid manifests
Hardcoded fallback module list in manifest layerRetireMust be registry-drivenmodule_registry dataEmpty registry works cleanly
Import assessment report conceptReplicate nowOperationally valuable for adminspackages/module-sdk + shell UIImport attempt writes report record
Deep internal imports (@sec-admn/*/src/*)RetireBoundary and version fragilityall packagesStatic check fails on internal-path imports
Supabase client/server/admin wrapper patternReplicate nowProven shell utility patternpackages/dbAuth/session tests pass
Integration inheritance resolution patternReplicate now (genericized)Strong tenancy behaviorpackages/db + packages/themeInheritance tests for parent/child contexts
Next-coupled shared DB internalsRebuildKeep behavior, reduce framework couplingpackages/dbPackage APIs usable outside app routes
Theme merge/default conceptReplicate now (tokenized)Needed for white-label inheritancepackages/themeToken inheritance + override tests
Fragmented theming implementationRetireMust centralize token governancepackages/themeSingle token source of truth
Tenancy context + impersonation behaviorReplicate nowOperator-critical shell behaviorpackages/permissions + packages/dbImpersonation and scope tests
Chat runtime logic in shell APIs/routesDefer to Modules phaseModule domain logicn/aShell has no chat business handlers
KB pipeline/worker in shellDefer to Modules phaseModule domain logicn/aShell runs with no KB runtime
Plasmic host/render integrationRetireNot aligned with v2 shell principlesn/aNo Plasmic dependency in shell
Duplicate .jsx/.tsx route pairs and .old filesRetireNon-deterministic maintenancerepo hygieneZero duplicate legacy route variants

3.3 Parity Acceptance Rules

  1. Every Replicate now row has package ownership and automated validation.
  2. Every Defer row is absent in shell implementation.
  3. Every Retire row has an explicit replacement or removal rationale in docs.

4. Schema + RLS Specification Pack

4.1 Migration Order

  1. 001_identities.sql
  2. 002_workspaces.sql
  3. 003_memberships_roles_permissions.sql
  4. 004_themes.sql
  5. 005_layouts.sql
  6. 006_module_registry_installations.sql
  7. 007_events_audit.sql
  8. 008_billing.sql
  9. 009_contacts.sql
  10. 010_rls_policies.sql
  11. 011_seed_role_templates.sql

4.2 Table-Level Specification

TableKey columnsConstraintsIndexesPrimary writersPrimary readers
usersid, auth_user_id, email, statusauth_user_id uniqueemailauth sync/systemself/admin/super
workspacesid, type, parent_workspace_id, name, statusparent self-FK(parent_workspace_id,type)super/agency adminscoped members
workspace_membershipsid, workspace_id, user_id, role_template, activeunique (workspace_id,user_id)workspace_id, user_idworkspace adminsscoped members
rolesid, code, scope_typecode uniquecodesystem seedauth system
permissionsid, codecode uniquecodesystem seedauth system
role_permissionsrole_id, permission_idunique pairrole_id, permission_idsystem/adminauth system
membership_permissionsmembership_id, permission_id, allowunique pairmembership_idworkspace adminsauth system
themesid, workspace_id, token_payload, versionunique (workspace_id,version)(workspace_id,version desc)adminsshell render/settings
layout_definitionsid, workspace_id, surface_key, current_version_idunique (workspace_id,surface_key)(workspace_id,surface_key)layout managershell renderer/admin
layout_versionsid, layout_definition_id, version_num, state, tree_jsonunique (layout_definition_id,version_num)(layout_definition_id,state)layout managershell renderer/admin
module_registryid, module_key, version, manifest_json, statusunique (module_key,version)(module_key,status)super/systemmodule admin/gateway
module_installationsid, workspace_id, module_key, state, config_jsonunique (workspace_id,module_key)(workspace_id,state)adminsnav/gateway
billing_accountsid, workspace_id, stripe_customer_id, statusunique workspace_id, unique stripe_customer_idstripe_customer_idbilling servicebilling/admin
subscriptionsid, billing_account_id, stripe_sub_id, state, period_endunique stripe_sub_id(billing_account_id,state)billing serviceenforcement/admin
eventsid, workspace_id, event_name, payload_json, delivery_state, correlation_idappend-only(workspace_id,event_name,occurred_at desc), correlation_idshell/modulessubscribers/admin
audit_logsid, workspace_id, actor_user_id, action, target_type, target_id, metadata_json, created_atappend-only(workspace_id,created_at desc), (actor_user_id,created_at desc)system onlyadmin/super
contactsid, workspace_id, name, email, phoneworkspace scope(workspace_id,email)shell/module contractsscoped users/modules

4.3 RLS Policy Baseline

  1. workspaces: member-scoped read, super full read/manage.
  2. workspace_memberships: workspace admins manage; users self-read membership rows.
  3. themes: branding.edit required for write, membership required for read.
  4. layout_definitions/layout_versions: layouts.edit for write; membership for read.
  5. module_installations: modules.install|modules.enable|modules.disable for write; membership for read.
  6. billing_accounts/subscriptions: billing.manage for write/read in scope; super override.
  7. events: emitter must be authenticated and scoped; reads scoped by workspace.
  8. audit_logs: write by trusted service role only; read by workspace admins and super.

4.4 Tenancy and Integrity Invariants

  1. All mutable business rows are workspace-scoped unless explicitly global.
  2. Cross-workspace access is denied-by-default.
  3. layout_versions are immutable snapshots.
  4. events and audit_logs are append-only.
  5. Impersonation must not bypass workspace permission checks.

4.5 Retention Policy (MVP)

  1. events: retain minimum 180 days online.
  2. audit_logs: retain minimum 365 days online.
  3. Archival beyond this window is operationally optional in MVP.

5. Contract Pack (OpenAPI + Canonical Types)

5.1 Endpoint Families and Minimum Contracts

DomainEndpointPurposeAuthRequired permission
AuthPOST /auth/sign-instart sessionnon/a
AuthPOST /auth/sign-outend sessionyesn/a
AuthPOST /auth/impersonation/startbegin impersonationyessuper scope
AuthPOST /auth/impersonation/stopstop impersonationyessuper scope
WorkspacesPOST /workspacescreate top-level workspaceyesscope admin
WorkspacesPOST /workspaces/{id}/childrencreate child business workspaceyesagency admin
WorkspacesPOST /workspaces/switchswitch active workspaceyesmembership
MembershipsPOST /membershipsinvite/add memberyesusers.invite
MembershipsPATCH /memberships/{id}role/state updateyesusers.manage
PermissionsGET /permissions/effectiveresolve effective ACLyesmembership
ThemesGET /themes/currentfetch effective themeyesmembership
ThemesPUT /themes/currentupdate theme tokensyesbranding.edit
LayoutsPOST /layouts/{id}/savesave draftyeslayouts.edit
LayoutsPOST /layouts/{id}/previewpreview draftyeslayouts.edit
LayoutsPOST /layouts/{id}/testvalidate/test draftyeslayouts.edit
LayoutsPOST /layouts/{id}/publishpublish versionyeslayouts.edit + policy
LayoutsPOST /layouts/{id}/rollbackrollback publishyeslayouts.edit + policy
ModulesPOST /modules/importvalidate/register module packageyesmodules.install
ModulesPOST /modules/{key}/installinstall in workspaceyesmodules.install
ModulesPOST /modules/{key}/enableenable moduleyesmodules.enable
ModulesPOST /modules/{key}/disabledisable moduleyesmodules.disable
ModulesDELETE /modules/{key}/uninstalluninstall moduleyesmodules.install
EventsPOST /eventsemit eventyescontract-based
EventsGET /eventsquery eventsyesworkspace scope
GatewayALL /gateway/{moduleKey}/{path...}proxy to module targetyesauth+perm+billing+enabled
BillingGET /billing/statusentitlement statusyesworkspace admin
BillingPOST /billing/recoveryrecovery actionsyesworkspace admin
BillingPOST /billing/reconcilestripe reconciliationyessuper/system

5.2 Canonical Types

WorkspaceContext

{
  "user_id": "usr_123",
  "active_workspace_id": "ws_abc",
  "effective_role": "agency_admin",
  "effective_permissions": ["users.invite", "modules.enable"],
  "impersonation": {
    "active": false,
    "actor_user_id": null,
    "target_workspace_id": null
  }
}

EffectivePermissions

{
  "workspace_id": "ws_abc",
  "role_template": "agency_admin",
  "grants": ["users.invite","users.manage","branding.edit","modules.enable"],
  "overrides": [{"permission":"billing.manage","allow":false}]
}

ModuleManifest

{
  "id": "voice-hub",
  "name": "Voice Hub",
  "version": "1.0.0",
  "description": "Voice runtime",
  "routes": ["/voice"],
  "sidebar": {"label":"Voice","icon":"phone","position":3},
  "required_permissions": ["modules.enable"],
  "capabilities": {"inputs":[],"outputs":[]},
  "required_shared_entities": ["contacts"],
  "events_emitted": ["voice.call.completed"],
  "events_consumed": ["contact.updated"],
  "config_schema": {"type":"object","properties":{}},
  "runtime_target": {"type":"http","base_url":"http://voice-hub:3000"}
}

ModuleInstallationState

{
  "workspace_id": "ws_abc",
  "module_key": "voice-hub",
  "state": "enabled",
  "installed_at": "2026-03-26T18:00:00Z",
  "updated_at": "2026-03-26T18:10:00Z"
}

EventEnvelope

{
  "event_id": "evt_01",
  "workspace_id": "ws_abc",
  "emitter": "shell",
  "event_name": "workspace.theme.updated",
  "payload": {"theme_version": 4},
  "occurred_at": "2026-03-26T18:15:00Z",
  "correlation_id": "corr_99"
}

GatewayForwardHeaders

{
  "x-user-id": "usr_123",
  "x-workspace-id": "ws_abc",
  "x-module-key": "voice-hub",
  "x-correlation-id": "corr_99",
  "x-impersonation-active": "false"
}

BillingEntitlementState

{
  "workspace_id": "ws_abc",
  "state": "grace",
  "effective_at": "2026-03-26T18:20:00Z",
  "module_activation_allowed": false,
  "module_usage_allowed": true,
  "recovery_access_allowed": true
}

5.3 Stable Error Model

CodeHTTPMeaning
AUTH_REQUIRED401missing/invalid session
SESSION_INVALID401session expired/invalidated
WORKSPACE_REQUIRED400no active workspace context
WORKSPACE_FORBIDDEN403workspace out of scope
PERMISSION_DENIED403capability denied
IMPERSONATION_FORBIDDEN403invalid impersonation action
MANIFEST_INVALID422manifest fails schema/contract
MANIFEST_INCOMPATIBLE422manifest conflicts with platform constraints
MODULE_NOT_REGISTERED404unknown module key
MODULE_NOT_ENABLED409module not enabled in workspace
MODULE_TARGET_UNHEALTHY503runtime target unavailable
EVENT_SCHEMA_INVALID422event payload/schema invalid
EVENT_DELIVERY_FAILED502downstream delivery failed after retries
BILLING_REQUIRED402no valid entitlement
BILLING_SUSPENDED402entitlement suspended
VALIDATION_BLOCKING422lifecycle blocked by validation
CONFLICT409optimistic concurrency/version conflict
RATE_LIMITED429request throttled
INTERNAL_ERROR500server fault

6. Event + Gateway Operational Semantics

6.1 Event Delivery Behavior

  1. Ordering guarantee is scoped to (workspace_id, stream_key) only.
  2. Publisher must provide idempotency key for retry-safe writes.
  3. Retry policy: exponential backoff, max 5 attempts.
  4. Terminal failures go to dead-letter store with replay capability.
  5. Replay requires admin/super authorization in same workspace scope.
  6. Event envelope schema is validated pre-persist and pre-delivery.

6.2 Event Authorization

  1. Emitter can publish only declared/allowed event names.
  2. Subscriber can consume only declared/allowed event names.
  3. Cross-workspace event reads are forbidden.
  4. All delivery attempts and failures are auditable.

6.3 Gateway Forwarding Behavior

  1. Resolve module target from module_installations + module_registry.
  2. Apply pre-forward checks in this order:
    • auth/session
    • workspace scope
    • permission
    • billing entitlement
    • module registered/enabled
    • target health
  3. Forward trusted server-issued claims only.
  4. Default timeout 8s.
  5. Circuit breaker opens on repeated failures; shell returns MODULE_TARGET_UNHEALTHY.
  6. Every forward logs correlation id, target, and enforcement decision.

6.4 Impersonation Protections

  1. Forwarded claims include actor/effective identity separation when impersonating.
  2. Module cannot self-assert identity.
  3. Client-supplied identity headers are stripped at gateway edge.

7. Billing Enforcement State Machine

7.1 States

  1. active
  2. past_due
  3. grace
  4. suspended
  5. canceled

7.2 Transition Rules

  1. active -> past_due: Stripe payment failure event.
  2. past_due -> grace: grace window begins.
  3. grace -> suspended: grace expiry without recovery.
  4. past_due|grace|suspended -> active: successful recovery payment.
  5. suspended -> canceled: explicit cancellation/termination.
  6. active -> canceled: explicit cancellation.

7.3 Entitlement Effects

StateModule usageNew module activationRecovery routes
activeallowedallowedallowed
past_dueallowed (warn)allowed (warn)allowed
graceallowed (warn)blockedallowed
suspendedblockedblockedallowed
canceledblockedblockedallowed (reactivation only)

7.4 Stripe Truth and Reconciliation

  1. Stripe webhooks are source of truth for billing events.
  2. Shell stores normalized entitlement snapshots.
  3. Reconciliation job repairs divergence and is idempotent.
  4. Every state transition writes audit_logs.

8. NFR + Security Control Pack

8.1 MVP SLO Targets

  1. Auth guard decision p95 < 200ms.
  2. Workspace switch p95 < 500ms.
  3. Module route resolution p95 < 300ms.
  4. Gateway overhead p95 < 150ms (excluding module runtime time).
  5. Layout publish/rollback acknowledgment p95 < 2s.
  6. Event enqueue p95 < 250ms.

8.2 Reliability Controls

  1. Publish and rollback are idempotent by operation key.
  2. Autosave recovery restores last valid layout draft after interruption.
  3. Audit log coverage for privileged actions is 100%.
  4. Dead-letter replay is safe and workspace-scoped.

8.3 Security Controls

  1. Deny-by-default authorization.
  2. Server-side enforcement independent of UI.
  3. Impersonation requires explicit start/stop and audit events.
  4. Header trust boundary enforced at gateway.
  5. Cross-workspace access denied unless explicit super scope.

9. Cutover and Validation Runbook

9.1 Blank-Repo Build Sequence

  1. Bootstrap monorepo + package boundaries.
  2. Implement auth/session and workspace context.
  3. Implement tenancy schema + RLS + permission core.
  4. Implement theme token system + inheritance.
  5. Implement module manifest validator + registry/install lifecycle.
  6. Implement event bus baseline.
  7. Implement gateway baseline.
  8. Integrate Layout Manager shell touchpoints.
  9. Implement billing entitlement enforcement.
  10. Run acceptance suite and dry-run audits.

9.2 Environment Contracts

  1. local: developer auth + seed data + billing sandbox mode.
  2. staging: real webhook paths + production-like RLS + full acceptance tests.
  3. prod: strict secrets, audit retention enabled, alerting active.

9.3 v1 Backfill Approach (Shell phase)

  1. Migrate shell-owned entities only.
  2. Do not migrate module domain records in shell phase.
  3. Rebuild module installation state from valid manifests.
  4. Preserve user/workspace/membership continuity.

9.4 Go-Live Checklist

  1. All acceptance matrix rows passing.
  2. Billing transition tests passing in staging.
  3. Impersonation audit verified.
  4. Module-absent mode verified.
  5. Rollback drill completed and documented.

10. Master Acceptance Matrix

RequirementSchema artifactAPI contractUI routeEnforcement ruleAutomated testStatus
Super creates Agency workspaceworkspaces,workspace_membershipsPOST /workspacesSuper dashboardrole policyintegrationpending
Agency creates Business childworkspaces.parent_workspace_idPOST /workspaces/{id}/childrenAgency dashboardscope checkintegrationpending
Workspace RBAC enforcementroles/permissions tablesGET /permissions/effectiveprotected shell screensmiddleware + RLSunit+integrationpending
Workspace switchmemberships + session contextPOST /workspaces/switchworkspace switchermembership requirede2epending
Super impersonationaudit_logs/auth/impersonation/*super toolssuper-only + scopeintegrationpending
Branding inheritancethemes/themes/currentbranding settingsbranding.editintegrationpending
Layout draft/publish/rollback lifecyclelayout_definitions,layout_versions/layouts/*layout managerlayouts.edit + validatorse2epending
Module import/validationmodule_registryPOST /modules/importmodule adminmanifest validatorcontract testspending
Module install/enable/disable/uninstallmodule_installations/modules/{key}/*module adminmodule permissionsintegrationpending
Dynamic nav from installsinstall statemodules list APIsshell navenabled-only filtere2epending
Event emit/queryevents/eventsevents monitorschema + auth + workspaceintegrationpending
Gateway forwardingregistry+installs/gateway/{module}/{path}module shell entryauth+perm+billing+enabledintegrationpending
Billing state access gatingbilling_accounts,subscriptions/billing/statusbilling settingsentitlement middlewareintegrationpending
Module-absent shell behaviorempty registry/installsmodules + gateway APIsmodule admin/navgraceful empty/error pathse2epending
Audit completenessaudit_logsprivileged endpointsaudit screensystem-only writesintegrationpending
No module business logic in shellpackage boundariesn/aall shell routesarchitecture review gatestatic+reviewpending

11. Quality Gates

  1. No unresolved TBD in shell-critical sections.
  2. Every endpoint family has request/response/error contracts.
  3. Every shell-owned entity has schema + RLS policy.
  4. Every v1 parity item has replicate/defer/retire disposition and acceptance method.
  5. Shell/module ownership is unambiguous to independent reviewer.

12. Implementation-Ready Gate

Mark this pack READY only when:
  1. Quality gates all pass.
  2. Acceptance matrix has no unresolved ownership or contract gaps.
  3. Independent architecture review signs shell/module boundary conformance.
  4. Module-absent mode tests are green.
Last modified on April 20, 2026