aiConnected v2 Core Shell PRD (Canonical)
Version: 1.0Date: March 26, 2026
Status: Implementation-Ready Draft
Audience: Product, Architecture, Engineering, QA
0. Document Purpose and Authority
This is the highest-priority source of truth for building the aiConnected v2 Core Shell from a blank repository. Interpretation rules:- When this document is explicit, implementation must follow it exactly.
- When this document is silent, implementation must choose the simplest approach that preserves future extensibility and shell/module boundaries.
- When functionality could be shell-owned or module-owned, it must be treated as module-owned unless explicitly marked shell-owned here.
- The shell must prioritize architectural correctness over convenience, decorative polish, and short-term coupling.
- This document governs
Shellphase only; module and capability behavior is deferred by design.
1. Product Identity
aiConnected v2 Core Shell is a white-label, multi-tenant SaaS control plane that owns:- Authentication and session lifecycle.
- Workspace and tenancy hierarchy.
- Role and permission enforcement.
- Routing and navigation infrastructure.
- Theme token governance and white-label branding inheritance.
- Layout Manager integration for shell surfaces.
- Billing entitlement enforcement.
- Module contract validation, registration, installation, and activation infrastructure.
- Shared event bus and API gateway infrastructure.
- Shared platform entities and auditability.
- A chat product.
- A voice product.
- A knowledge-base product.
- A CRM.
- A marketplace.
- A workflow engine.
- A module itself.
- A private assistant/system-chat runtime.
2. Product Goal
The shell must provide a durable operating layer so agencies can run a white-label platform and future modules can plug in without core rewrites. Practical outcomes required:- Agency can onboard and operate platform as agency-owned software.
- Agency can create and manage child business workspaces.
- Shell can enforce permissions, billing state, branding, and route access consistently.
- Modules can be added through contract-driven registration and activation rather than shell source edits.
- Core shell remains stable while module ecosystem evolves.
3. Non-Negotiable Product Principles
- The system must be multi-tenant from day one.
- The shell must be white-label from day one.
- The shell must use a shadcn-based shared UI foundation.
- Theming must be centralized and inheritance-based.
- Layout Manager integration must be in MVP.
- Module import and registration infrastructure must be in MVP.
- Modules must be installable without hardcoded shell route implementations per module.
- Inter-module communication must use declared contracts, events, and gateway routing.
- Business-domain logic must not be embedded into shell code.
- Shell architecture must support unknown future modules.
4. Phase Ownership and Product Boundaries
4.1 Phase Boundaries
Shellphase: control plane only.Modulesphase: first-party and imported module runtime/domain behavior.Capabilitiesphase: capability graph/composition, advanced cross-module automation.
4.2 Shell Done Definition
Shell is done when:- Super, Agency, Business shell workflows are complete.
- Module lifecycle infrastructure (import/validate/register/install/enable/disable/uninstall) is complete.
- Event bus, gateway, billing enforcement, theme engine, and layout governance are complete.
- Shell runs correctly with zero modules installed.
- No module business logic exists in shell implementation.
- Integration-provider control plane and shell AI orchestration hooks are complete and policy-enforced.
4.3 Module-Absent Operating Mode (Required)
- Empty module registry must not break shell routes or navigation.
- Module access attempts must return stable errors (
MODULE_NOT_REGISTERED,MODULE_NOT_ENABLED). - Module admin surfaces must show actionable empty states.
- Gateway and event systems must remain operational for shell-owned flows.
5. Exact MVP Scope (Shell Phase)
MVP shell must include:- Auth/session lifecycle.
- Workspace hierarchy and membership model.
- RBAC and capability-level authorization.
- Super/Agency/Business shell experiences.
- Shared shell UI system and theme engine.
- Layout Manager shell integration.
- Module SDK contract validation and module registry.
- Module installation and workspace activation controls.
- Event bus infrastructure.
- Gateway infrastructure.
- Billing account and subscription entitlement enforcement.
- Shared shell-owned entities and audit logging.
- Container-aware module target model.
- Shell support for standalone module route entrypoints.
- Shell-owned integration-provider infrastructure with Composio-ready connection lifecycle (provider config, oauth callback handling, workspace-scoped connection records).
- Shell-level AI orchestration integration hooks for governed authoring workflows (job state, audit, permissions), without embedding module business behavior.
- Layout Manager
Create Newpath for module draft generation (manifest draft, initial layout draft, route scaffold metadata) with registry persistence.
- Module business logic.
- Module-specific customer workflows.
- Marketplace and developer community UX.
- Capability pipeline features.
- System-chat/private assistant behavior.
- Conversion pipelines (GitHub/WordPress/n8n) beyond shell registration contract handling.
- Module-specific Composio workflow implementations and toolkit business behavior.
- Module domain/business behavior beyond shell-generated draft scaffolds.
6. User Types and Tenant Structure
Top-level user layers:- Super
- Agency
- Business
- Developer
- Personal
- Super
- Agency
- Business
- Workspace is the runtime tenant boundary for permissions, branding, modules, and route access.
- Agencies are parent workspaces.
- Businesses are managed child workspaces.
- Users belong to one or more workspaces via membership records.
- Effective access is always workspace-scoped unless super with explicit platform scope.
- Super impersonation is required and must be auditable.
- Agency impersonation of Business context is required but only for Business workspaces owned by that Agency and only with explicit impersonation capability.
7. Permissions and Access Control
The shell must enforce capability-based authorization. Required permission capabilities (minimum set):users.inviteusers.managebranding.editbilling.managelayouts.editmodules.installmodules.enablemodules.disablesettings.manageimpersonation.super.startimpersonation.agency_business.startimpersonation.stopintegrations.manageai.orchestration.manageusers.password.resetusers.email.updatebranding.login.editdomains.managenavigation.managefeatures.managecredentials.inheritance.manage
super_admin,super_manager,super_useragency_admin,agency_manager,agency_userbusiness_admin,business_manager,business_user
- Route guard level.
- UI feature visibility level.
- API authorization layer.
- Data access policy layer (RLS).
- Super roles can manage all users and workspaces.
- Agency admin/manager roles can manage agency users and users inside child business workspaces they own.
- Business admin/manager roles can manage only users in their own business workspace.
- No role may mutate users outside allowed workspace scope, even with impersonation active.
8. Required Technical Stack
The shell must use:- Next.js 14 App Router.
- TypeScript.
- Turborepo monorepo.
- shadcn/ui.
- Tailwind CSS.
- TweakCN-compatible token architecture.
- Supabase Auth + Postgres.
- Stripe billing integration.
- Containerized module runtime targets (DigitalOcean + Dokploy model).
- Shell-hosted gateway + event bus.
9. Monorepo and Project Structure
Required starting structure:apps/platform(shell app only).packages/ui(shared UI primitives).packages/permissions(role templates, capability maps, guards).packages/module-sdk(manifest schema, validator, registry contracts).packages/theme(theme token schema and inheritance).packages/db(data access and shell entity repositories).packages/events(event contracts and bus helpers).packages/billing(stripe + entitlement logic).packages/layout-manager(shell-side layout contracts/integration hooks).packages/gateway(routing/forwarding contracts and enforcement).packages/integrations(provider registry, connection contracts, oauth callback handlers, secret indirection).packages/ai-orchestration(shell-owned AI job contracts, status model, permission/audit adapters).packages/sdk-contracts(shared public types for manifest/events/gateway/error envelopes).packages/navigation(sidebar/nav policy, override contracts, resolver).packages/features(workspace feature flags and module feature gating contracts).
apps/platform must orchestrate package behavior; it must not absorb package-level logic.
10. Core Shell Architecture
Required shell layers:- Auth/session layer.
- Tenancy/workspace layer.
- Permission policy layer.
- Theme/branding layer.
- Layout governance layer.
- Module registration layer.
- Event layer.
- Gateway layer.
- Billing entitlement layer.
- Modules register with shell via manifest contracts.
- Shell grants routes/nav/permissions from contracts.
- Modules can be enabled/disabled per workspace.
- Modules communicate through events and gateway.
- Modules must not directly mutate other modules’ private data stores.
- Shell must not contain module business logic.
11. Shared Platform Data Model (Shell-Owned)
Required shell-owned entities:usersworkspacesworkspace_membershipsrolespermissionsrole_permissionsmembership_permissionsthemeslayout_definitionslayout_versionsmodule_registrymodule_installationsbilling_accountssubscriptionseventsaudit_logscontactsintegration_connectionsai_jobsworkspace_domainsbranding_assetsworkspace_feature_flagsnavigation_profilescredential_policiessdk_contract_versions
- Shell owns all shared entities above.
- Modules may read shared entities through authorized contracts.
- Module-private tables remain module-owned and isolated.
- Cross-module behavior must use shared entities, event contracts, or gateway calls.
12. Schema + RLS Specification Pack
12.1 Migration Order
001_identities.sql002_workspaces.sql003_memberships_roles_permissions.sql004_themes.sql005_layouts.sql006_module_registry_installations.sql007_events_audit.sql008_integration_connections.sql009_ai_jobs.sql010_billing.sql011_contacts.sql012_rls_policies.sql013_seed_role_templates.sql014_domains_branding_navigation_features.sql015_rls_extension_policies.sql016_sdk_contract_versions.sql
12.2 Table-Level Requirements
| Table | Must include | Required constraints | Required indexes |
|---|---|---|---|
| users | id, auth_user_id, email, status | auth_user_id unique | |
| workspaces | id, type, parent_workspace_id, name, status | parent FK self-ref | (parent_workspace_id,type) |
| workspace_memberships | id, workspace_id, user_id, role_template, active | unique (workspace_id,user_id) | workspace_id, user_id |
| roles | id, code, scope_type | code unique | code |
| permissions | id, code | code unique | code |
| role_permissions | role_id, permission_id | unique pair | role_id |
| membership_permissions | membership_id, permission_id, allow | unique pair | membership_id |
| themes | id, workspace_id, token_payload, version | unique(workspace_id,version) | (workspace_id,version desc) |
| layout_definitions | id, workspace_id, surface_key, current_version_id | unique(workspace_id,surface_key) | (workspace_id,surface_key) |
| layout_versions | id, layout_definition_id, version_num, state, tree_json | unique(layout_definition_id,version_num) | (layout_definition_id,state) |
| module_registry | id, module_key, version, manifest_json, status | unique(module_key,version) | (module_key,status) |
| module_installations | id, workspace_id, module_key, state, config_json | unique(workspace_id,module_key) | (workspace_id,state) |
| billing_accounts | id, workspace_id, stripe_customer_id, status | workspace unique, stripe_customer_id unique | stripe_customer_id |
| subscriptions | id, billing_account_id, stripe_sub_id, state, period_end | stripe_sub_id unique | (billing_account_id,state) |
| events | id, workspace_id, event_name, payload_json, delivery_state, correlation_id | append-only policy | (workspace_id,event_name,occurred_at desc), correlation_id |
| audit_logs | id, workspace_id, actor_user_id, action, target_type, target_id, metadata_json, created_at | append-only policy | (workspace_id,created_at desc), (actor_user_id,created_at desc) |
| contacts | id, workspace_id, name, email, phone | workspace-scoped | (workspace_id,email) |
| integration_connections | id, workspace_id, provider_key, provider_account_ref, status, secret_ref, scopes_json | unique(workspace_id,provider_key,provider_account_ref) | (workspace_id,provider_key,status) |
| ai_jobs | id, workspace_id, job_type, state, context_ref, intent_json, artifacts_json | append-only state transitions | (workspace_id,state,created_at desc), (workspace_id,job_type,created_at desc) |
| workspace_domains | id, workspace_id, host, status, verification_token, verified_at | unique(host) | (workspace_id,status), host |
| branding_assets | id, workspace_id, asset_type, storage_path, mime_type, size_bytes, active | unique(workspace_id,asset_type,active) partial | (workspace_id,asset_type) |
| workspace_feature_flags | id, workspace_id, feature_key, enabled, source_scope | unique(workspace_id,feature_key) | (workspace_id,enabled) |
| navigation_profiles | id, workspace_id, scope_type, role_template, config_json, version | unique(workspace_id,scope_type,role_template,version) | (workspace_id,scope_type,role_template,version desc) |
| credential_policies | id, workspace_id, provider_key, resolution_order_json, allow_parent_fallback | unique(workspace_id,provider_key) | (workspace_id,provider_key) |
| sdk_contract_versions | id, contract_name, semver, status, schema_json | unique(contract_name,semver) | (contract_name,status) |
12.3 Tenancy Invariants
- All mutable records must be workspace-scoped unless explicitly global.
- Cross-workspace access must be denied by default.
layout_versionsmust be immutable.eventsandaudit_logsmust be append-only.- Impersonation must never bypass capability checks.
- Agency impersonation target workspace must have
parent_workspace_id == actor_agency_workspace_id. - Domain hostnames must be globally unique across all workspaces.
- Credential resolution must always evaluate within workspace ancestry (
business -> agency -> super) and must never cross agency boundaries.
12.4 RLS Policy Baseline
workspaces: membership-scoped read; super full access.workspace_memberships: workspace admin manage; user self-read.themes:branding.editrequired for mutation.layout_*:layouts.editrequired for mutation.module_installations: module permissions required for mutation.billing_*:billing.managerequired for mutation, super override.events: emit/read restricted by workspace scope and contracts.audit_logs: service-write only, admin/super read.integration_connections: workspace-scoped read/write,integrations.managerequired for mutation.ai_jobs: workspace-scoped read/write,ai.orchestration.managerequired for mutation.workspace_domains: workspace-scoped read/write,domains.managerequired for mutation.branding_assets: workspace-scoped read/write,branding.editrequired for mutation.workspace_feature_flags: workspace-scoped read/write,features.managerequired for mutation.navigation_profiles: workspace-scoped read/write,navigation.managerequired for mutation.credential_policies: workspace-scoped read/write,credentials.inheritance.managerequired for mutation.sdk_contract_versions: super-only write, read for authorized module tooling endpoints.
12.5 Retention Rules
- Events must retain at least 180 days online.
- Audit logs must retain at least 365 days online.
- AI jobs must retain at least 90 days online.
- Domain verification history must retain at least 365 days online.
- Credential policy change history must retain at least 365 days online.
12.6 Migration Rollback and Recovery Expectations
- Migrations
001through014must be reversible in staging via explicit down scripts during pre-production validation. - Migrations
012_rls_policies.sqland015_rls_extension_policies.sqlare forward-only in production; rollback is performed by applying superseding corrective migrations, not destructive policy deletion. - Migrations
013_seed_role_templates.sqland016_sdk_contract_versions.sqlmust be idempotent and re-runnable safely. - Production rollback strategy must prioritize data integrity:
- schema rollback only for non-destructive migrations
- entitlement and auth-impacting defects fixed by forward corrective migrations
- Every migration must include:
- pre-check query
- post-check query
- failure handling note
13. Authentication and Session Requirements
Required behaviors:- Sign-in and sign-out.
- Session persistence.
- Workspace resolution at login.
- Workspace switching for multi-membership users.
- Route-level authorization and unauthorized handling.
- Invitation-based onboarding.
- Role-aware post-login destination routing.
- Super impersonation start/stop with audit logging.
- Agency admin/manager impersonation start/stop for owned Business workspaces with audit logging.
- Password reset initiation and completion flows.
- Admin-triggered password reset links for in-scope users.
- In-scope email address updates with verification.
- User lifecycle actions (
active,invited,suspended) with audit trail. - Admin password management must use secure reset tokens; no direct password readback or plaintext storage.
- user id
- active workspace id
- effective role template
- effective permission set
- impersonation state
- impersonation actor workspace id
- impersonation target workspace id
- Existing Supabase Auth users from v1 are reused by default.
- v2
usersrecords must be backfilled by stableauth_user_idmapping. - Existing v1 memberships are migrated only where they map to shell-owned workspace model; invalid/missing links must be quarantined for manual resolution.
- No plaintext password material is migrated; password lifecycle remains Supabase Auth managed.
- First login after migration must resolve deterministic workspace context or route user to workspace selection with safe fallback.
14. Multi-Tenant Workspace Requirements
- Super must manage agency workspaces.
- Agency must create/manage business child workspaces.
- Business users must operate only in assigned workspaces.
- Agency A must not access Agency B data.
- Business X must not access Business Y data.
- Theme inheritance must support parent agency defaults and child workspace override compatibility.
- Module enablement must be workspace-scoped.
- Agency impersonation is allowed only from an Agency workspace into its own child Business workspaces.
- Theme inheritance precedence must be
super baseline -> agency override -> business override. - Credential inheritance precedence must be
business key -> agency key -> super keywhen and only when policy permits fallback.
15. UI Foundation and Theme Engine
- Shell UI must be shadcn-based and token-driven.
- Theme tokens must be central source of branding truth.
- Theme inheritance must be deterministic across workspace hierarchy.
- Branding edits must propagate consistently across shell routes.
- Shell must not use ad hoc page-specific branding logic.
- White-label branding must include logo asset management, login-screen customization, and domain-bound branding resolution.
- Agency admins must be able to customize agency login screen branding for their scope.
- Business login branding may override inherited agency branding only where policy allows.
- Super-level baseline theme must be configurable and inherited by agency workspaces unless explicitly overridden.
15.1 White-Label Surface Requirements
- Custom domains:
- workspace domain add/remove/verify lifecycle is required.
- active domain must map deterministically to workspace branding context.
- Logo assets:
- logo upload and activation is required for super, agency, and business scopes subject to permission.
- logo assets must be stored as managed branding assets, not inline blobs.
- Login-screen customization:
- branding profile must support logo, primary/secondary colors, typography tokens, and allowed text copy slots.
- agency and business login screens must inherit from parent scope unless explicit override exists.
- Theme inheritance:
- precedence order must remain
super -> agency -> business. - override behavior must be deterministic and testable.
- precedence order must remain
16. Layout Manager Integration (Shell Perspective)
Layout Manager internals are defined in the dedicated Layout Manager PRD. Shell must provide:- Entry points:
- in-context edit trigger on supported shell surfaces
- admin routes:
Layout Manager > Modules,Layout Manager > Create New
- Authorization and lifecycle enforcement for save/preview/test/publish/rollback.
- Persistence integration with
layout_definitions+layout_versions. - Audit logging for privileged layout lifecycle actions.
- Boundary enforcement: layout edits must not author backend module business logic.
- AI orchestration handoff integration (job status/events/permissions) required for
Create NewandData Source -> Create Newshell-governed entrypoints. - Builder component registry integration must expose approved shadcn/ui builder-compatible components to privileged users on supported shell surfaces.
Create Newmust support module draft generation and return editable draft artifacts to builder workflow.- Module drafts created via builder must remain non-live until manifest validation, permission mapping, and explicit enablement are complete.
17. Module System Overview (Shell Perspective)
- Module must be recognized by manifest contract only.
- Module routes and navigation must be dynamic from registry/installations.
- Module enablement must be workspace-scoped.
- Module access must be gated by permission + billing + installation state.
- Module business workflows are out of shell scope.
18. Module Manifest Contract
Required fields:- module id
- name
- version
- description
- routes
- sidebar config
- required permissions
- capabilities declaration
- required shared entities
- events emitted
- events consumed
- configuration schema
- runtime target definition
- Missing required fields must reject import.
- Invalid semantic version must reject import.
- Duplicate incompatible module key/version must reject import.
- Route collisions must reject import unless namespace-compatible by policy.
- Unknown permission keys must reject import.
- Unknown/invalid event names must reject import.
- Unhealthy runtime target must block enablement.
19. Module Import and Registration Process
Required flow:- Accept module package/scaffold.
- Parse and validate manifest.
- Persist module metadata in
module_registry. - Create/update workspace
module_installationsrecord. - Assign route/nav metadata dynamically.
- Enforce required permission mappings.
- Register gateway target mapping.
- Support install, enable, disable, uninstall transitions.
- Support builder-originated module draft registration (
draftstate) before runtime enablement. - Promote draft module to installable state only after manifest + contract validation pass.
- Import package.
- Show validation failures clearly.
- Install into target workspace.
- Enable/disable.
- Uninstall.
- Show current state and target health.
- Review builder-originated module drafts and promote/reject explicitly.
20. Contract Pack (OpenAPI Baseline)
Required endpoint families:/auth/*/workspaces/*/memberships/*/users/*/permissions/*/themes/*/branding/*/domains/*/navigation/*/features/*/credentials/*/layouts/*/modules/*/events/*/gateway/*/billing/*/integrations/*/ai-orchestration/*/sdk/*
20.1 Canonical Types
WorkspaceContextEffectivePermissionsModuleManifestModuleInstallationStateEventEnvelopeGatewayForwardHeadersBillingEntitlementStateIntegrationConnectionStateAIJobStateBrandingProfileDomainMappingNavigationProfileFeatureFlagSetCredentialResolutionResultSDKContractVersion
20.2 Stable Error Codes
Required stable codes:AUTH_REQUIREDSESSION_INVALIDWORKSPACE_REQUIREDWORKSPACE_FORBIDDENPERMISSION_DENIEDIMPERSONATION_FORBIDDENMANIFEST_INVALIDMANIFEST_INCOMPATIBLEMODULE_NOT_REGISTEREDMODULE_NOT_ENABLEDMODULE_TARGET_UNHEALTHYEVENT_SCHEMA_INVALIDEVENT_DELIVERY_FAILEDBILLING_REQUIREDBILLING_SUSPENDEDVALIDATION_BLOCKINGCONFLICTRATE_LIMITEDINTERNAL_ERRORIMPERSONATION_SCOPE_FORBIDDENINTEGRATION_PROVIDER_UNAVAILABLEINTEGRATION_SCOPE_FORBIDDENAI_JOB_INVALID_STATEAI_JOB_FORBIDDENDOMAIN_INVALIDDOMAIN_ALREADY_CLAIMEDDOMAIN_VERIFICATION_FAILEDBRANDING_ASSET_INVALIDNAVIGATION_INVALIDFEATURE_FLAG_INVALIDCREDENTIAL_RESOLUTION_FAILEDSDK_CONTRACT_INCOMPATIBLE
20.3 Endpoint-Level Contract Baseline (Execution Required)
All protected endpoints must require a validated session and resolvedWorkspaceContext.
Required auth claim shape for protected requests:
sub(user id)workspace_id(active workspace)role_templatepermissions(effective capability array)impersonation(active,actor_user_id,target_workspace_id)session_id
| Endpoint | Request body (minimum) | Response body (minimum) | Primary error codes |
|---|---|---|---|
POST /auth/sign-in | email, password | session, workspace_options, default_workspace_id | AUTH_REQUIRED, INTERNAL_ERROR |
POST /auth/sign-out | none | ok | SESSION_INVALID |
POST /auth/impersonation/start | target_workspace_id, reason | impersonation_state, effective_context | PERMISSION_DENIED, IMPERSONATION_FORBIDDEN, IMPERSONATION_SCOPE_FORBIDDEN |
POST /auth/impersonation/stop | none | impersonation_state, effective_context | SESSION_INVALID |
POST /workspaces | type, name, parent_workspace_id? | workspace | PERMISSION_DENIED, CONFLICT |
POST /workspaces/{id}/children | name, child_type | workspace | WORKSPACE_FORBIDDEN, PERMISSION_DENIED |
POST /workspaces/switch | workspace_id | effective_context | WORKSPACE_FORBIDDEN, SESSION_INVALID |
POST /memberships | workspace_id, email, role_template | membership, invite_status | PERMISSION_DENIED, CONFLICT |
PATCH /memberships/{id} | role_template?, active?, permission_overrides? | membership | PERMISSION_DENIED, WORKSPACE_FORBIDDEN |
PATCH /users/{id} | profile?, status? | user | PERMISSION_DENIED, WORKSPACE_FORBIDDEN |
POST /auth/password/reset | email | reset_status | AUTH_REQUIRED, WORKSPACE_FORBIDDEN |
POST /auth/password/set | token, new_password | reset_status | SESSION_INVALID, VALIDATION_BLOCKING |
PATCH /users/{id}/email | new_email | user, verification_status | PERMISSION_DENIED, CONFLICT |
GET /permissions/effective | none | effective_permissions, role_template | SESSION_INVALID |
GET /themes/current | none | theme_tokens, source_workspace_id, version | WORKSPACE_FORBIDDEN |
PUT /themes/current | theme_tokens, change_note | theme_version, theme_tokens | PERMISSION_DENIED, VALIDATION_BLOCKING |
POST /branding/assets/logo-upload-url | workspace_id, mime_type, size_bytes | upload_url, asset_id | PERMISSION_DENIED, BRANDING_ASSET_INVALID |
PUT /branding/login-screen | workspace_id, branding_profile | branding_profile, version | PERMISSION_DENIED, VALIDATION_BLOCKING |
GET /branding/login-screen | query: workspace_id | branding_profile, effective_source_workspace_id | WORKSPACE_FORBIDDEN |
POST /domains | workspace_id, host | domain_record, verification_token | DOMAIN_INVALID, DOMAIN_ALREADY_CLAIMED |
POST /domains/{id}/verify | none | domain_record | DOMAIN_VERIFICATION_FAILED, WORKSPACE_FORBIDDEN |
DELETE /domains/{id} | none | ok | PERMISSION_DENIED, WORKSPACE_FORBIDDEN |
GET /navigation/sidebar | query: workspace_id, role_template | navigation_profile | WORKSPACE_FORBIDDEN |
PUT /navigation/sidebar | workspace_id, role_template, config_json | navigation_profile, version | PERMISSION_DENIED, NAVIGATION_INVALID |
GET /features | query: workspace_id | feature_flags | WORKSPACE_FORBIDDEN |
PUT /features | workspace_id, feature_flags | feature_flags, version | PERMISSION_DENIED, FEATURE_FLAG_INVALID |
POST /credentials/resolve | workspace_id, provider_key | resolution, source_scope | CREDENTIAL_RESOLUTION_FAILED, WORKSPACE_FORBIDDEN |
GET /layouts/components | query: surface_key?, category? | items[] | PERMISSION_DENIED |
POST /layouts/{id}/save | draft, history_cursor | layout_version, validation_summary | PERMISSION_DENIED, VALIDATION_BLOCKING |
POST /layouts/{id}/preview | draft_version_id | preview_url, validation_summary | VALIDATION_BLOCKING |
POST /layouts/{id}/test | draft_version_id | test_report | VALIDATION_BLOCKING |
POST /layouts/{id}/publish | draft_version_id, publish_note | published_version_id | PERMISSION_DENIED, VALIDATION_BLOCKING |
POST /layouts/{id}/rollback | target_version_id, reason | published_version_id | PERMISSION_DENIED, CONFLICT |
POST /modules/import | package_uri or manifest | assessment, registry_record | MANIFEST_INVALID, MANIFEST_INCOMPATIBLE |
POST /modules/{key}/install | workspace_id, config? | installation_state | MODULE_NOT_REGISTERED, PERMISSION_DENIED |
POST /modules/{key}/enable | workspace_id | installation_state | MODULE_TARGET_UNHEALTHY, BILLING_SUSPENDED |
POST /modules/{key}/disable | workspace_id | installation_state | PERMISSION_DENIED |
DELETE /modules/{key}/uninstall | workspace_id | ok | PERMISSION_DENIED, CONFLICT |
GET /modules/available | query: workspace_id | items[] | WORKSPACE_FORBIDDEN |
POST /events | event_name, payload, correlation_id, idempotency_key | event_id, delivery_state | EVENT_SCHEMA_INVALID, PERMISSION_DENIED |
GET /events | query: workspace_id, event_name?, cursor? | items, next_cursor | WORKSPACE_FORBIDDEN |
ALL /gateway/{module}/{path} | proxied payload | proxied payload + normalized error envelope | MODULE_NOT_ENABLED, MODULE_TARGET_UNHEALTHY, BILLING_SUSPENDED |
GET /billing/status | none | entitlement_state, subscription_state | WORKSPACE_FORBIDDEN |
POST /billing/recovery | action, workspace_id | entitlement_state, next_steps | BILLING_REQUIRED, CONFLICT |
POST /billing/reconcile | workspace_id?, force? | reconcile_result | PERMISSION_DENIED, INTERNAL_ERROR |
POST /integrations/providers/composio/connect | workspace_id, provider_account_ref, scopes | connection_state, oauth_url_or_status | INTEGRATION_PROVIDER_UNAVAILABLE, INTEGRATION_SCOPE_FORBIDDEN |
POST /integrations/providers/composio/disconnect | workspace_id, connection_id | connection_state | PERMISSION_DENIED, INTEGRATION_SCOPE_FORBIDDEN |
GET /integrations/providers/composio/connections | query: workspace_id | items[] | WORKSPACE_FORBIDDEN |
POST /ai-orchestration/jobs | workspace_id, job_type, context_ref, intent_payload | job_id, state | AI_JOB_FORBIDDEN, VALIDATION_BLOCKING |
GET /ai-orchestration/jobs/{id} | none | job_state, artifacts, audit_ref | AI_JOB_FORBIDDEN, SESSION_INVALID |
GET /sdk/contracts | query: contract_name?, status? | items[] | PERMISSION_DENIED |
21. Event Bus and Inter-Module Communication
Required event behavior:- Standard envelope schema.
- Workspace-scoped publishing and subscription.
- Auth and contract validation on emit and consume.
- Durable event storage.
- Delivery state tracking.
- Retry strategy (exponential, bounded attempts).
- Dead-letter path and replay controls.
- Audit trail for delivery and failures.
- Ordering guarantee is per
(workspace, stream)not global. - Publisher idempotency key is required for retry-safe emit.
22. API Gateway Requirements
Gateway must:- Resolve targets dynamically from registry/installations.
- Enforce auth, workspace scope, permission, billing, enabled-state before forwarding.
- Forward trusted server claims (
user,workspace,module,correlation,impersonation). - Strip untrusted client claims/headers.
- Use deterministic error responses.
- Implement timeout and circuit-breaker behavior.
- Log every forward attempt with decision metadata.
23. Billing and Activation Rules
23.1 Billing State Machine
States:activepast_duegracesuspendedcanceled
active -> past_dueon payment failure.past_due -> gracewhen grace starts.grace -> suspendedwhen grace expires unrecovered.past_due|grace|suspended -> activeon successful recovery.suspended -> canceledon cancellation.
23.2 Entitlement Effects
active: normal shell/module access per permissions.past_due: warning state, controlled access.grace: recovery accessible; block new paid module activations.suspended: block module usage; keep recovery/account/billing routes accessible.canceled: no module usage until reactivation.
23.3 Stripe Truth Model
- Stripe webhook events are billing event source of truth.
- Shell stores normalized entitlement state.
- Reconciliation job must be idempotent and auditable.
23.4 Integrations and AI Orchestration Boundary Rule
- Shell manages provider/account connection state, auth lifecycle, and access policy for integrations (including Composio provider support).
- Shell manages AI job lifecycle contracts, permissions, and auditability for shell-governed authoring workflows.
- Module-specific integration workflows, agent/tool execution behavior, and domain automation remain module-phase scope.
23.5 Credential Inheritance and Fallback Rules
- Default credential resolution order is
business -> agency -> super. - Parent fallback is allowed only when
credential_policies.allow_parent_fallback = true. - Credential fallback must never cross agency boundaries.
- Every credential resolution decision must emit audit metadata (
provider,workspace,resolved_scope). - Workspace-level explicit key always overrides inherited keys when valid.
23.6 Module and Feature Access Governance
- Module enable/disable is controlled through
module_installationsstate. - Feature-level enable/disable is controlled through
workspace_feature_flags. - Super may set global baseline feature defaults; agency and business may override only where policy permits.
- Feature flags must not bypass billing or permission checks.
24. Core Shell Screens and Routes (MVP)
Required shell routes/screens:- Sign-in/sign-out.
- Workspace selector/switcher.
- Super dashboard.
- Agency dashboard.
- Business dashboard.
- User management.
- Workspace settings.
- Branding/theme settings.
- Layout Manager shell routes.
- Module registry/installations management.
- Billing status/settings/recovery.
- Platform/system settings.
- Integrations settings (provider connections, including Composio).
- AI job monitor (shell-governed authoring jobs only).
- Super account/profile settings.
- Module draft review queue (including builder-originated drafts).
- White-label branding manager (logo, login-screen profile, baseline tokens).
- Domain manager (custom domains + verification state).
- Navigation manager (sidebar/nav profile editor by scope).
- Feature flags manager (module and shell feature toggles by workspace scope).
- SDK contracts viewer (active contract versions and compatibility state).
- Resolve active workspace.
- Enforce required permissions.
- Use centralized theme token system.
- Avoid embedding module business behavior.
25. Measurable NFRs + Security Controls
25.1 SLO Targets (MVP)
- Auth route guard p95 < 200ms.
- Workspace switch p95 < 500ms.
- Module route resolution p95 < 300ms.
- Gateway shell overhead p95 < 150ms (excluding module runtime).
- Layout publish/rollback ack p95 < 2s.
- Event enqueue p95 < 250ms.
25.2 Reliability Controls
- Publish/rollback operations must be idempotent.
- Layout draft autosave recovery must restore last valid draft.
- Audit logging coverage for privileged shell actions must be 100%.
- Event dead-letter replay must remain workspace-scoped.
- Domain verification jobs must be retry-safe and idempotent.
- Navigation and feature-flag updates must be versioned and rollback-capable.
- Credential-resolution service must fail closed (no silent cross-scope fallback).
25.3 Security Controls
- Deny-by-default authorization.
- Server-side enforcement independent of UI state.
- Impersonation start/stop and effective context must be fully auditable.
- Gateway trust boundary must reject client-forged identity claims.
- Cross-workspace access must be denied by default.
- Branding asset uploads must use signed upload URLs, MIME/size validation, and malware scan hooks.
- Custom-domain verification must require proof-of-control token challenge before activation.
- Password reset and email update flows must enforce anti-enumeration and rate limits.
- Credential fallback decisions must be logged and queryable by super/agency scope.
- SDK contract publication must require super authorization and semver compatibility checks.
- Admin password operations must be tokenized reset flows; direct plaintext password retrieval is prohibited.
25.4 Supabase Security Baseline
- Supabase service-role key must be server-only and must not be exposed to browser bundles.
- Browser clients must use anon/public key only with RLS-protected access paths.
- All workspace-scoped shell tables must have RLS enabled before production launch.
- SECURITY DEFINER database functions must be minimized, schema-qualified, and reviewed with explicit threat notes.
- Supabase Realtime subscriptions must be workspace-scoped and authorization-checked.
- Secrets and provider tokens referenced by integration connections must be encrypted at rest and never returned in plaintext API responses.
- Auth/session, RLS, and impersonation policy tests must run in CI as release-blocking checks.
26. MVP Build Phases
- Phase 1: monorepo bootstrap, auth/session, base shell routing.
- Phase 2: workspaces, memberships, roles/permissions, impersonation, user lifecycle actions.
- Phase 3: UI foundation, theme engine, white-label controls, domain/branding assets.
- Phase 4: module manifest SDK, registry, import/install lifecycle, SDK contract publication.
- Phase 5: integration-provider infrastructure (Composio-ready), credential inheritance/fallback, plus event bus and gateway.
- Phase 6: layout manager shell integration, navigation/feature governance, plus shell AI orchestration hooks.
- Phase 7: billing entitlement enforcement.
- Phase 8: final integration and acceptance validation.
27. Cutover and Validation Runbook
27.1 Blank-Repo Build Sequence
- Set up monorepo boundaries.
- Implement auth/session and workspace context.
- Implement schema + RLS + policy tests.
- Implement user lifecycle admin operations (invite, suspend, reset-password links, email update).
- Implement theme engine, branding assets, login-screen profile, and inheritance.
- Implement domain management and verification flow.
- Implement module contract, SDK contracts, and registry lifecycle.
- Implement integration-provider infrastructure (Composio-ready), credential fallback policy, and secure connection state handling.
- Implement event bus.
- Implement gateway.
- Integrate layout lifecycle, navigation/feature governance, and shell AI orchestration touchpoints.
- Implement billing enforcement.
- Execute acceptance matrix and dry-run audits.
27.2 Environment Contracts
- Local: dev-safe auth, seed data, test billing mode.
- Staging: production-like RLS, webhook integration, full acceptance tests.
- Production: strict secrets, retention policies, audit and alerting enabled.
- Supabase key policy:
SUPABASE_SERVICE_ROLE_KEYserver runtime onlyNEXT_PUBLIC_SUPABASE_ANON_KEYclient-safe only- key rotation runbook documented and tested in staging
27.3 v1 Backfill Policy (Shell Phase)
- Migrate shell-owned entities only.
- Do not migrate module business-domain records in shell phase.
- Reconstruct module installation state from valid manifests.
- Reuse existing Supabase Auth identities and migrate v2
userslinkage byauth_user_id. - Migrate white-label shell settings that map to v2 model:
- theme token sets
- branding profiles
- custom domain records (with re-verification workflow as needed)
- Migrate user/workspace memberships only when tenancy relationships pass v2 invariants; unresolved records must be quarantined for manual review.
27.4 Go-Live Checklist
- Acceptance matrix fully green.
- Billing transition tests passing.
- Impersonation audit verified.
- Module-absent mode verified.
- Rollback drill completed.
28. Master Acceptance Matrix
| Requirement | Schema artifact | API contract | UI route | Enforcement rule | Automated test |
|---|---|---|---|---|---|
| User can sign in successfully and resolve workspace context | users, workspace_memberships | POST /auth/sign-in | sign-in | auth + membership resolution | e2e |
| Super can configure own account/profile | users, audit_logs | PATCH /users/ | super account settings | self-or-super manage checks | integration |
| Super/Agency can trigger in-scope password reset | users, audit_logs | POST /auth/password/reset | user management | scope + users.password.reset + rate limits | integration |
| Super/Agency can update in-scope user email | users, audit_logs | PATCH /users//email | user management | scope + users.email.update + verification | integration |
| Super can create Agency workspace | workspaces, memberships | POST /workspaces | super dashboard | role/capability check | integration |
| Agency can create Business child workspace | workspaces parent model | POST /workspaces//children | agency dashboard | tenancy scope | integration |
| Agency can create Business users in owned workspace | users, workspace_memberships | POST /memberships | business users management | parent-child scope + users.manage | integration |
| RBAC is capability-based | roles, permissions, role_permissions | GET /permissions/effective | all protected shell routes | middleware + RLS | unit + integration |
| Workspace switching works | memberships + session context | POST /workspaces/switch | workspace switcher | membership required | e2e |
| Impersonation is controlled and auditable | audit_logs | POST /auth/impersonation/* | super tools | super scope + audit write | integration |
| Super can impersonate Agency context | audit_logs + workspaces | POST /auth/impersonation/start | super tools | super scope + audit + target validation | integration |
| Agency can impersonate only owned Business workspaces | workspaces parent model + audit_logs | POST /auth/impersonation/start | agency workspace tools | parent-child scope + capability + audit | integration |
| Theme inheritance applies consistently | themes | GET/PUT /themes/current | branding settings | branding.edit + scope | integration |
| White-label logo upload and activation works | branding_assets | POST /branding/assets/logo-upload-url | branding settings | branding.edit + upload policy checks | integration |
| Agency/business login-screen customization works within scope | themes + branding_assets | GET/PUT /branding/login-screen | branding settings | branding.login.edit + scope + inheritance | integration |
| Custom domain add/verify/remove lifecycle works | workspace_domains | POST /domains + POST /domains//verify + DELETE /domains/ | domain manager | domains.manage + host uniqueness + verification challenge | integration |
| Layout lifecycle is governed | layout_definitions, layout_versions | POST /layouts/* | layout manager routes | layouts.edit + validators | e2e |
| Builder component registry exposes approved shadcn components | layout registry + component metadata | GET /layouts/components | layout manager routes | builder-compatibility + role checks | e2e |
| Layout Manager + AI can generate module draft at will | module_registry (draft), layout_definitions, ai_jobs | POST /ai-orchestration/jobs + POST /modules/import (draft path) | Layout Manager > Create New | ai.orchestration.manage + modules.install + validator gates | e2e |
| Manifest-compliant module import works | module_registry | POST /modules/import | modules admin | manifest validator | contract test |
| Module installation state is dynamic | module_installations | POST /modules//* | modules admin | module capability checks | integration |
| Dynamic nav honors enabled state | module_installations state | GET /modules/available | shell nav | enabled + scope checks | e2e |
| Sidebar/navigation overrides are policy-managed | navigation_profiles | GET/PUT /navigation/sidebar | navigation manager | navigation.manage + versioning + scope checks | integration |
| Feature toggles are policy-managed by scope | workspace_feature_flags | GET/PUT /features | feature flags manager | features.manage + billing/permission coupling | integration |
| Event emit/query works with contracts | events | POST/GET /events | events monitor | schema + scope + auth | integration |
| Gateway enforcement is complete | registry + installations | ALL /gateway// | module shell entry route | auth+scope+permission+billing | integration |
| Billing state gates module access | billing_accounts, subscriptions | GET /billing/status | billing settings | entitlement policy | integration |
| Composio provider connections are shell-governed and workspace-scoped | integration_connections | POST/GET /integrations/providers/composio/* | integrations settings | integrations.manage + workspace scope | integration |
| Credential resolution fallback obeys ancestry and policy | credential_policies + integration_connections | POST /credentials/resolve | integrations settings | credentials.inheritance.manage + no cross-agency fallback | integration |
| Shell AI orchestration jobs are permissioned and auditable | ai_jobs + audit_logs | POST/GET /ai-orchestration/jobs* | AI job monitor | ai.orchestration.manage + scope | integration |
| SDK contract versions are published and compatible | sdk_contract_versions | GET /sdk/contracts | platform/system settings | super-only publication + semver compatibility rules | contract test |
| Shell works with zero modules | module tables empty | module + gateway endpoints | modules admin + nav | module-absent mode handlers | e2e |
| Audit coverage is complete for privileged ops | audit_logs | all privileged endpoints | audit UI | service-write immutable logs | integration |
| No module business logic inside shell | package boundaries | n/a | all shell routes | architecture review and static checks | static + review gate |
28.1 Supplemental Normative Traceability (Full-Coverage Controls)
| Normative control | Primary section(s) | Verification artifact |
|---|---|---|
| Shell-only phase boundary is enforced | 4, 5, 29, 30 | architecture review checklist + static policy checks |
| Module-absent mode is fully operable | 4.3, 28 | e2e module-absent test suite |
| v1 parity decisions are explicit and auditable | 31, 34 | parity review sign-off + matrix diff |
| Migration rollback strategy is defined | 12.6, 27 | migration dry-run report |
| RLS and tenancy invariants are enforced | 12.3, 12.4, 14 | policy integration tests |
| Endpoint-level contract detail is complete | 20.3 | OpenAPI lint + contract tests |
| Event delivery + gateway semantics are explicit | 21, 22 | integration tests + failure-mode tests |
| Billing entitlement transitions are deterministic | 23 | billing state machine tests |
| White-label surfaces (domains, logo, login branding) are complete | 15.1, 20.3, 28 | branding/domain integration tests |
| User lifecycle admin controls are complete | 7, 13, 20.3, 28 | identity admin test suite |
| Credential fallback and policy controls are deterministic | 14, 23.5, 28 | credential resolution tests |
| SDK contract publication and compatibility controls are complete | 9, 20, 28 | SDK contract compatibility tests |
| SLO/NFRs are measurable and testable | 25 | performance test report |
| Cutover and rollback are operationally scripted | 27, 33.1 | dry-run checklist execution report |
| No unresolved shell-critical placeholders | 32, 33 | documentation lint check |
29. Out of Scope (Strict)
Not part of Shell phase:- Building any business module domain workflows.
- Customer-facing module interfaces.
- Marketplace/developer portal/community trust pipeline UX.
- Capabilities graph and advanced orchestration systems.
- Future conversion pipeline internals beyond shell import contract handling.
- Private assistant/system-chat runtime behavior.
30. Implementation Guardrails
- Shell and module business logic must not be collapsed.
- Multi-tenancy must not be postponed.
- Module routes must not be hardcoded as permanent shell pages.
- Shared UI/theme systems must not be bypassed with ad hoc styling.
- Layout editing must remain reusable system behavior, not one-off page hacks.
- Billing state must be part of access/activation checks.
- When uncertain, preserve shell/module boundary over convenience.
- No unresolved
TBDis allowed in shell-critical sections. - Duplicate
.jsxand.tsxroute implementations must not be introduced. - Legacy
.oldfiles must not be introduced or retained in active route trees. - Mock-only and placeholder shell pages for billing/reporting must not satisfy acceptance criteria.
- Package internals must not be imported via deep paths (for example
package/src/*).
31. v1 Parity Replication Matrix (Shell-Relevant)
| v1 behavior | Disposition | Reason | v2 owner | Validation | Evidence |
|---|---|---|---|---|---|
| permissions role primitives | Replicate now | shell-core | packages/permissions | unit tests | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/03a-auth-and-permissions.md |
| app-local route ACL hardcoding | Retire | coupling risk | packages/permissions + middleware | static checks | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/03a-auth-and-permissions.md |
| manifest normalize/validate/assess | Replicate now | module infra backbone | packages/module-sdk | contract tests | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/03b-module-manifest-system.md |
| hardcoded fallback app manifests | Retire | must be registry-driven | module_registry seed policy | empty-registry tests | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/03b-module-manifest-system.md |
| import assessment reports | Replicate now | admin operations value | module-sdk + platform admin | integration tests | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/03b-module-manifest-system.md |
| sdk manifest/schemas contracts | Replicate now (v2 package form) | future module compatibility | packages/module-sdk + packages/sdk-contracts | contract compatibility tests | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/08-v1-complete-capability-inventory.md |
| sdk client contract surface | Replicate now (shell contract first) | gateway/event interoperability | packages/sdk-contracts | integration contract tests | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/08-v1-complete-capability-inventory.md |
| deep internal package imports | Retire | boundary fragility | all packages | lint rule | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/02-foundation-vs-apps.md |
| db browser/server/admin wrappers | Replicate now | proven reusable shell pattern | packages/db | integration tests | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/03f-db-client-server-patterns.md |
| integration inheritance resolver pattern | Replicate now (genericized) | strong tenancy behavior | packages/db + theme | inheritance tests | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/03f-db-client-server-patterns.md and /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/07-multi-tenancy-clean-port-plan.md |
| fragmented theming catalogs | Retire | single source of truth required | packages/theme | token consistency tests | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/03c-branding-and-theming.md |
| tenancy context + impersonation rules | Replicate now | operator-critical | permissions + db | scope/impersonation tests | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/07-multi-tenancy-clean-port-plan.md |
| custom domain management | Replicate now (v2 shell form) | white-label requirement | domains + branding surfaces | domain lifecycle tests | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/08-v1-complete-capability-inventory.md |
| logo/login branding controls | Replicate now (tokenized) | white-label requirement | theme + branding assets | branding inheritance tests | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/03c-branding-and-theming.md |
| chat runtime behavior | Defer to modules phase | module business logic | n/a | shell code review | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/02-foundation-vs-apps.md |
| kb runtime/worker behavior | Defer to modules phase | module business logic | n/a | shell code review | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/02-foundation-vs-apps.md |
| plasmic host/render | Retire | out of shell principles | n/a | dependency scan | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/08-v1-complete-capability-inventory.md |
| duplicate route variants/.old files | Retire | maintainability risk | repo hygiene policy | CI file checks | /Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/08-v1-complete-capability-inventory.md |
31.1 Required v1 Capability ID Mapping (Authoritative)
The following v1 capabilities are explicitly required parity references for Shell phase. Disposition is mandatory.| v1 capability id | v1 name (inventory) | Disposition | Shell section target |
|---|---|---|---|
| C-006 | Admin shell role context | Replicate now | 6, 7, 24 |
| C-007 | Effective tenant context resolver | Replicate now | 6, 12, 14, 20 |
| C-008 | Impersonation persistence + lifecycle | Replicate now | 6, 7, 13, 20, 28 |
| C-009 | Authorized business scope helper | Replicate now | 7, 12, 14, 28 |
| C-010 | Settings inheritance resolution | Replicate now | 15, 20, 28 |
| C-011 | Agencies CRUD + onboarding | Replicate now (shell scope only) | 14, 24, 28 |
| C-012 | Agency detail ops | Replicate now (shell scope only) | 14, 24, 28 |
| C-013 | Businesses CRUD | Replicate now | 14, 24, 28 |
| C-014 | Users CRUD and profile management | Replicate now | 13, 14, 24, 28 |
| C-015 | Agency branding management | Replicate now | 15, 24, 28 |
| C-016 | Business branding management | Replicate now | 15, 24, 28 |
| C-017 | Platform branding controls | Replicate now | 15, 24, 28 |
| C-018 | Dashboard theme editor | Replicate now (theme-token based) | 15, 24, 28 |
| C-019 | Custom domain management | Replicate now (shell control plane only) | 15, 24, 28 |
| C-021 | Platform app/module catalog browsing | Replicate now | 17, 19, 24, 28 |
| C-022 | Module import pipeline | Replicate now | 18, 19, 20, 24, 28 |
| C-023 | Manifest validation and compatibility assessment | Replicate now | 18, 19, 20, 28 |
| C-024 | App availability resolution by tenant | Replicate now | 17, 19, 24, 28 |
| C-059 | Permissions package concept | Replicate now | 7, 9, 28 |
| C-056 | app-sdk package concept | Replicate now (v2 package form) | 9, 18, 19, 20, 28 |
| C-064 | sdk schemas package concept | Replicate now (v2 contract form) | 9, 20, 28 |
| C-067 | sdk manifest package concept | Replicate now (v2 module-sdk form) | 9, 18, 20, 28 |
| C-069 | Schema baseline concept | Replicate now (re-modeled for v2 shell) | 11, 12, 28 |
| C-070 | RLS baseline concept | Replicate now (re-modeled for v2 shell) | 12, 28 |
| C-073 | Deployment model reference | Replicate as engineering reference | 8, 27 |
- Chat runtime behavior.
- Knowledge-base runtime behavior.
- Lead capture, email, webhook delivery workflows.
- Capabilities library / n8n conversion lane.
- Marketplace and developer-community behaviors.
- Module-specific product UIs.
32. Documentation Quality and Readiness Validation
32.1 Completeness Checks
- Shell scope areas are fully specified: auth, tenancy, permissions, theme, layout integration, modules infra, events, gateway, billing, shared data.
- Known gaps are explicitly closed: scope mismatch, parity, schema/RLS, contracts, event/gateway semantics, billing semantics, NFRs, cutover, traceability.
32.2 Consistency Checks
- No section contradicts phase boundaries.
- No shell requirement depends on module implementation to validate shell correctness.
- All deferred items are explicitly marked and assigned to later phases.
32.3 Traceability Checks
- Every acceptance criterion maps to schema + API + enforcement + test.
- Every parity item has disposition and validation method.
- Every contract error path maps to stable error code.
32.4 Independent Review Checks
- Independent reviewer can classify all capabilities as shell-owned or deferred with no ambiguity.
- Implementation Ready Gate is objective and binary.
33. Implementation Ready Gate
The shell PRD is implementation-ready only when:- All completeness checks pass.
- All consistency checks pass.
- All traceability checks pass.
- Independent review checks pass.
- No unresolved
TBDexists in shell-critical sections. - This document and the Layout Manager PRD are both marked ready.
33.1 Mandatory Blank-Repo Dry-Run Checklist
- Reviewer receives only this PRD + Layout Manager PRD (no verbal context).
- Reviewer derives monorepo/package scaffold and confirms no unresolved ownership decisions.
- Reviewer derives migration order and validates rollback/recovery expectations are actionable.
- Reviewer derives endpoint contracts and confirms each protected route has required auth claims and stable error outcomes.
- Reviewer derives module-absent mode behavior and confirms deterministic expected outputs.
- Reviewer maps all acceptance rows to concrete test artifacts and confirms no unmapped normative controls remain.
- Reviewer issues one of two results:
READY: no blocking ambiguityNOT READY: explicit blocking gaps with section references
- PRD is build-authorized only after
READYresult is documented.
34. Source References
/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/Users/MrBobHunter-MacPro/Code/platform.sec-admn.com-2/docs/v1-audit/08-v1-complete-capability-inventory.md- aiConnected v2 Layout Manager PRD (approved)
35. Build Authorization Checklist (One-Page)
This checklist must be green before shell implementation starts.35.1 Functional Readiness
- Login and workspace resolution requirements are fully specified.
- Super account/profile management requirements are fully specified.
- Super can create Agency workspaces.
- Agency can create Business workspaces and Business users.
- Super-to-Agency and Agency-to-owned-Business impersonation is fully specified, permissioned, and auditable.
- Branding/theme management and inheritance requirements are fully specified.
- Layout Manager integration requirements are fully specified, including
Create New. - Approved shadcn/ui builder component visibility requirements are fully specified.
- AI orchestration contracts for builder-governed authoring are fully specified.
- Module draft creation path via Layout Manager is fully specified and gated by validation.
- White-label surfaces (custom domains, logo uploads, login-screen customization) are fully specified.
- User lifecycle admin operations (password reset, email update, scope authority) are fully specified.
- Navigation and feature governance are fully specified.
- Credential inheritance and fallback policy are fully specified.
35.2 Platform Infrastructure Readiness
- Shell-owned schema and RLS policies are complete and testable.
- Endpoint contracts and stable error codes are complete for all required shell families.
- Event bus and gateway semantics are complete and testable.
- Billing entitlement state machine is complete and testable.
- Module-absent operating mode is explicitly defined and testable.
- Supabase security baseline and key-handling rules are explicit.
- Deployment domain/base URL policy is explicit and environment-bound.
- Dokploy and Supabase reuse policy is explicit.
- SDK contract strategy and version governance is explicit.
- Dependency validation matrix is complete and build-blocking controls are identified.
35.3 Execution Readiness
- Master acceptance matrix has no unmapped shell-critical requirement.
- No unresolved
TBDremains in shell-critical sections. - Independent dry-run result is
READY. - Shell/module boundary review is
PASS.
36. Domain and URL Policy (sec-admn.com)
36.1 Required Base URL Model
- Shell must not hardcode legacy hostnames.
- Shell must resolve all public URLs from environment variables.
- The canonical base domain for this program is
sec-admn.com. - Environment-specific hostnames must be explicitly configured:
- local:
localhost - staging: subdomain under
sec-admn.com - production: subdomain under
sec-admn.com
- local:
36.2 Required Environment Variables
PLATFORM_PUBLIC_BASE_URLPLATFORM_AUTH_CALLBACK_URLPLATFORM_COOKIE_DOMAINPLATFORM_ALLOWED_ORIGINSPLATFORM_CUSTOM_DOMAIN_ROOT(for future tenant custom domains)
36.3 Domain and Auth Acceptance Checks
- Auth callback and redirect URLs must match configured environment hostnames.
- Session cookies must be valid for intended hostname scope and must not leak across unrelated hosts.
- Cross-origin requests must be denied unless explicitly whitelisted in
PLATFORM_ALLOWED_ORIGINS. - No route, API handler, or UI config may contain committed hardcoded legacy URLs.
37. Existing Environment Reuse Plan (Dokploy + Supabase)
37.1 Supabase Reuse Policy
- Reuse the existing Supabase project and Auth infrastructure unless a formal replacement is approved.
- Do not reuse v1 schema blindly; apply v2 shell migrations defined in this PRD.
- Migrate only shell-owned entities in Shell phase.
- Keep RLS deny-by-default and enforce workspace scope on all shell-owned tables.
- Preserve service-role secrecy and client anon-key boundaries.
37.2 Dokploy Reuse Policy
- Reuse existing Dokploy infrastructure as deployment control plane.
- Provision v2 shell as a distinct app/service from v1 workloads.
- Keep environment-specific deployments isolated (local/staging/production).
- Use environment-bound secrets and URLs; do not share production secrets with staging/local.
- Maintain rollback-capable deployment configuration for shell-only launch.
37.3 What Is Carried Forward vs Rebuilt
Carry forward:- Supabase project/auth tenancy foundation.
- Dokploy operational platform.
- DigitalOcean runtime environment model.
- Shell schema via v2 migrations.
- Shell routing, permissions enforcement, and module registration infrastructure.
- Shell UI and theming implementation.
38. Deployment Input Gate (Required Before Public Launch)
The initial implementation target is local host-first. Public deployment requires the following inputs to be confirmed:- Final production shell hostname under
sec-admn.com. - Final staging hostname under
sec-admn.com. - Supabase project id and callback URL allowlist entries for staging/production.
- Dokploy app names/projects for staging and production shell.
- DNS ownership and SSL issuance path for selected hostnames.
- Final cookie domain policy for each environment.
38.1 Approval Record
Status:APPROVEDApproved by: Product Owner
Approval date:
March 27, 2026
39. Deployment Defaults (Authoritative)
These defaults are approved and are now authoritative for shell implementation, staging rollout, and production preparation.39.1 Hostname and Base URL Defaults
| Environment | Shell URL | Notes |
|---|---|---|
| local | http://localhost:3000 | local development only |
| staging | https://staging.sec-admn.com | private staging for acceptance testing |
| production | https://app.sec-admn.com | public shell entrypoint |
39.2 Environment Variable Defaults
| Variable | local | staging | production |
|---|---|---|---|
PLATFORM_PUBLIC_BASE_URL | http://localhost:3000 | https://staging.sec-admn.com | https://app.sec-admn.com |
PLATFORM_AUTH_CALLBACK_URL | http://localhost:3000/auth/callback | https://staging.sec-admn.com/auth/callback | https://app.sec-admn.com/auth/callback |
PLATFORM_COOKIE_DOMAIN | localhost | staging.sec-admn.com | .sec-admn.com |
PLATFORM_ALLOWED_ORIGINS | http://localhost:3000 | https://staging.sec-admn.com | https://app.sec-admn.com |
PLATFORM_CUSTOM_DOMAIN_ROOT | local.sec-admn.test | staging-customers.sec-admn.com | customers.sec-admn.com |
39.3 Supabase Auth URL Allowlist Defaults
http://localhost:3000/auth/callbackhttp://localhost:3000/auth/confirmhttps://staging.sec-admn.com/auth/callbackhttps://staging.sec-admn.com/auth/confirmhttps://app.sec-admn.com/auth/callbackhttps://app.sec-admn.com/auth/confirm
39.4 Dokploy App Naming Defaults
- project:
aiconnected-v2-staging, app:shell-staging - project:
aiconnected-v2-production, app:shell-production - optional local mirror app:
shell-local
40. Existing Environment Adoption Plan (Execution Defaults)
40.1 Supabase
- Reuse the existing Supabase platform as the baseline infrastructure.
- Apply v2 shell migrations only; do not import v1 schema wholesale.
- Maintain separate environment targets:
- staging target: isolated from public production traffic
- production target: live customer traffic
- Execute migration dry-runs in staging before production apply.
40.2 Dokploy
- Reuse existing Dokploy control plane and deployment workflows.
- Deploy v2 shell as new services (
shell-staging,shell-production) rather than replacing v1 in place. - Keep v1 and v2 deployments parallel until shell acceptance criteria are fully green.
- Cut over DNS only after staging validation and production readiness gate pass.
40.3 Cutover Policy
- Local-first implementation remains the required first execution mode.
- Staging rollout is required before any production cutover.
- Production cutover requires Section 38 inputs confirmed plus Section 35 checklist fully green.
41. SDK Strategy (v1 Carry-Forward -> v2 Shell Contracts)
41.1 Why SDK Is Required in Shell Phase
- The shell cannot remain module-open without stable public contracts for manifests, events, gateway envelopes, and error models.
- Module import/validation depends on SDK-grade schema contracts, not ad hoc JSON parsing.
- Future module teams require a versioned contract surface before module phase starts.
41.2 v1 to v2 SDK Carry-Forward Policy
- Carry forward architecture ideas from v1
app-sdk,sdk/schemas, andsdk/manifest. - Do not copy v1 implementation style where it violates current package boundaries.
- Rebuild SDK contracts as first-class v2 packages:
packages/module-sdkpackages/sdk-contracts
- Expose versioned contract metadata through
/sdk/contracts.
41.3 SDK Minimum Deliverables in Shell Phase
- Manifest schema and validator with semver support.
- Event envelope schema and validation helpers.
- Gateway request/response envelope types.
- Stable error code enum package shared by API/gateway/module tooling.
- Compatibility checker for contract version negotiation.
42. Dependency Validation Matrix (Security, Stability, Expansion)
| Dependency Area | Required now | Validation Method | Build-Blocking if Missing |
|---|---|---|---|
| Supabase auth/session | yes | auth integration tests + callback allowlist checks | yes |
| Supabase RLS | yes | policy integration tests by role/workspace | yes |
| Stripe billing webhooks | yes | webhook replay + reconciliation tests | yes |
| Theme/branding inheritance | yes | super->agency->business inheritance tests | yes |
| Domain verification | yes | token challenge integration tests | yes |
| Branding asset pipeline | yes | signed upload + MIME/size enforcement tests | yes |
| Module SDK contracts | yes | schema compatibility tests | yes |
| Module registry/import lifecycle | yes | manifest import/install/enable tests | yes |
| Event bus durability | yes | retry/dead-letter/replay tests | yes |
| Gateway trust boundary | yes | forged-claim rejection tests | yes |
| Composio connection lifecycle | yes | connect/disconnect/scope tests | yes |
| Credential fallback policy | yes | ancestry + fallback tests | yes |
| Navigation governance | yes | role-scoped sidebar config tests | yes |
| Feature flag governance | yes | scope + billing coupling tests | yes |
| Shell AI orchestration hooks | yes | job lifecycle + permission tests | yes |
| SDK contract publishing | yes | super-only publish + compatibility tests | yes |
| Backup and restore readiness | yes | restore drill report + recovery metrics | yes |
| Observability and alerting coverage | yes | metrics/log/alert validation checklist | yes |
| Incident runbook completeness | yes | tabletop drill + runbook sign-off | yes |
43. User and Admin Capability Coverage (Shell Phase)
43.1 Super User Must Be Able To
- Manage all users, roles, memberships, and profile details in all workspaces.
- Trigger password reset links and update in-scope email addresses.
- Create/modify agencies and business hierarchies.
- Impersonate agency and business contexts with full audit trace.
- Manage baseline theme, branding, login-screen profiles, and domain policy.
- Enable/disable modules and manage feature flags by scope.
- Manage navigation/sidebar policy by scope.
- Manage integration connection policy and credential fallback policy.
43.2 Agency Admin Must Be Able To
- Manage agency and owned business users within delegated scope.
- Trigger password reset links and email updates for in-scope users.
- Impersonate owned business workspaces only.
- Manage agency branding, login screen, and allowed business overrides.
- Manage agency/business modules, feature flags, and integrations within policy.
- Manage agency/business navigation settings within policy.
43.3 Business Admin Must Be Able To
- Manage users inside their own business workspace only.
- Operate allowed branding and feature settings delegated by agency/super policy.
- Operate module access and integrations allowed by higher-scope governance.
44. Final Readiness Determination Rule
Shell implementation may proceed only when:- Sections 35, 38, and 42 are all green.
- Master acceptance matrix has 100% mapped coverage and no red rows.
- Dependency validation matrix has no missing build-blocking area.
- SDK contracts are versioned and discoverable before module-phase work begins.
45. Operational Stability and Production Reliability Requirements
45.1 Backup and Restore
- Database backup policy must be defined for staging and production before first public launch.
- Restore procedures must be tested in staging with documented recovery time and data-loss windows.
- Branding/domain/navigation/feature configuration data must be included in backup scope.
45.2 Observability and Alerting
- Structured logging must include correlation id, workspace id, actor id, and route/endpoint metadata.
- Metrics must be emitted for auth failures, permission denials, gateway failures, billing-gate blocks, and domain verification failures.
- Alerts must be configured for:
- repeated auth/session failures
- gateway target unhealthy rates
- billing reconciliation failures
- background job dead-letter growth
- Dashboard views for shell health must be available to super operators.
45.3 Incident and Recovery Operations
- Incident runbook must define severity levels, ownership, and escalation path.
- Rollback execution steps for schema, deployment, and routing configuration must be documented and tested.
- Post-incident reviews must produce actionable remediation items tied back to acceptance controls.
46. Documentation Adherence and Change-Control Policy
- Implementation must not diverge from this PRD without recorded change approval.
- Any proposed deviation must include:
- impacted sections
- risk assessment
- migration/compatibility impact
- test-plan updates
- PRD changes must be versioned and reviewed before implementation changes are considered complete.
- CI gates must enforce:
- contract compatibility checks
- policy test execution
- acceptance-matrix linkage for changed behavior
- Build execution order must follow Section 26 unless an approved change record explicitly reorders phases.