Capability Management & Type-Safe Governance Specification
Capability Management & Type-Safe Governance Specification
Section titled “Capability Management & Type-Safe Governance Specification”Document Status: Living True Specification (Single Source of Truth)
Authority: System of record for platform capabilities, client manifests, and governance tooling. When architectural designs evolve, this document is updated directly to always reflect the ground-truth state.
Related Documents: PRD.md, HIGH_LEVEL_DESIGN.md, README.md
1. Executive Summary & Objective
Section titled “1. Executive Summary & Objective”In SiteSwarm, a single monolithic repository powers dozens of independent client web applications. To maintain velocity and prevent the fleet from decaying into fragmented, unmaintainable codebases, we need strict, machine-readable governance.
This document specifies the Capability Management System:
- Type-Safe App Manifest (
swarm.config.ts): Every client application declares its utilized features using strong TypeScript contracts, guaranteeing zero-drift compile-time safety. - Horizontal vs. Vertical Classification: Distinguishes reusable platform capabilities from one-off, client-specific vertical customizations.
- Agent Introspection & Verification: Provides AI coding agents with a structured API and compile-time verification loop (
tsc --noEmit) to build, backport, and upgrade features without human micromanagement. - Governance Tooling & Auditing: Provides CLI tooling (
swarm audit,swarm matrix) to verify that targets declared in code match actual file assets on disk.
2. Core Concepts & Taxonomy
Section titled “2. Core Concepts & Taxonomy”flowchart TD subgraph Catalog["Central Capability Catalog (@siteswarm/governance)"] H_Lead["capability:lead-capture (v1.2.0)"] H_Menu["capability:menu-catalog (v2.1.0)"] H_Book["capability:booking-calendar (v1.0.0)"] H_SEO["capability:dynamic-seo (v1.4.0)"] H_Alarm["capability:synthetic-alarms (v2.0.0)"] end
subgraph ClientManifest["apps/<client>/swarm.config.ts"] Decl_Lead["lead-capture: type: 'horizontal', targets: [...]"] Decl_Menu["menu-catalog: type: 'horizontal', targets: [...]"] Decl_Vert["pos-webhook: type: 'vertical-custom', targets: [...]"] end
subgraph ClientCode["apps/<client>/src/"] File1["src/components/ContactSection.astro"] File2["src/pages/menu.astro"] File3["src/pages/api/pos-webhook.ts"] end
H_Lead -.->|"Import contract & options"| Decl_Lead H_Menu -.->|"Import contract & options"| Decl_Menu
Decl_Lead ==>|"Declared target"| File1 Decl_Menu ==>|"Declared target"| File2 Decl_Vert ==>|"Declared target"| File32.1 The Two Types of Capabilities
Section titled “2.1 The Two Types of Capabilities”| Dimension | Type Identifier | Description | Life Cycle & Ownership |
|---|---|---|---|
| Horizontal Platform Capability | 'horizontal' |
A standardized, reusable feature module authored in @siteswarm/* and consumed across multiple client applications (e.g., lead capture with Turnstile, booking calendar, structured SEO schemas). |
Centrally versioned (SemVer), maintained by platform engineers, upgraded fleet-wide. |
| Vertical Customization | 'vertical-custom' |
Bespoke business logic written exclusively for a single client (e.g., syncing orders with a local bakery’s 15-year-old POS terminal or an auto repair VIN lookup). | Isolated to the specific client app directory; tagged and documented in swarm.config.ts to prevent agents from inadvertently deleting or overwriting it. |
3. TypeScript Type Contracts Specification
Section titled “3. TypeScript Type Contracts Specification”All types are defined in @siteswarm/governance (located in packages/governance/src/types.ts).
3.1 Capability Registry & Discriminated Unions
Section titled “3.1 Capability Registry & Discriminated Unions”/** * Known horizontal capabilities in the SiteSwarm platform. * Adding a new platform capability requires extending this registry contract. */export interface SwarmCapabilityRegistry { "lead-capture": { provider: "turnstile" | "recaptcha-v3" | "hcaptcha"; notifyChannel?: "email" | "sms" | "webhook"; storeSubmissions?: boolean; }; "menu-catalog": { currency: string; enableDietaryBadges?: boolean; supportsOrdering?: boolean; }; "booking-calendar": { provider: "cal-com" | "calendly" | "native-edge"; bufferMinutes?: number; allowSameDay?: boolean; }; "dynamic-seo": { schemaType: "LocalBusiness" | "Restaurant" | "AutoRepair" | "MedicalClinic"; enableBreadcrumbs?: boolean; generateOpenGraphImages?: boolean; }; "synthetic-alarms": { probeIntervalMinutes: number; alertWebhookEnvVar: string; assertStatusCode?: number; };}
export type KnownCapabilityName = keyof SwarmCapabilityRegistry;
/** * Base properties required by every capability usage. */export interface BaseCapabilityUsage { /** Relative paths within the app directory where this capability is consumed */ targets: string[]; /** Optional architectural rationale or implementation notes */ notes?: string;}
/** * Strongly typed declaration of a horizontal platform capability. */export interface HorizontalCapabilityUsage<K extends KnownCapabilityName = KnownCapabilityName> extends BaseCapabilityUsage { type: "horizontal"; /** Semantic version of the horizontal capability being consumed */ version: string; /** Strongly typed configuration options matched to the capability name */ options?: SwarmCapabilityRegistry[K];}
/** * Strongly typed declaration of a bespoke vertical customization. */export interface VerticalCustomizationUsage extends BaseCapabilityUsage { type: "vertical-custom"; /** Mandatory description explaining what this one-off code does */ description: string; /** Whether this vertical logic is an architectural candidate for promotion to a horizontal capability */ candidateForPromotion?: boolean; /** Contact or context tag */ owner?: string;}
/** * Combined capability map for a client application. */export type AppCapabilitiesConfig = { [K in KnownCapabilityName]?: HorizontalCapabilityUsage<K>;} & { [customKey: string]: HorizontalCapabilityUsage<any> | VerticalCustomizationUsage;};3.2 Full Client Application Manifest Contract (AppConfig)
Section titled “3.2 Full Client Application Manifest Contract (AppConfig)”export interface AppBrandConfig { primaryColor: string; accentColor: string; fontFamilyHeading?: string; fontFamilyBody?: string; logoAssetPath: string;}
export interface AppDeploymentConfig { productionDomain: string; stagingDomain?: string; cloudPlatform: "cloudflare" | "custom";}
export interface AppConfig { /** Unique kebab-case identifier matching the directory name in apps/<appId> */ appId: string; /** Human-readable business name */ name: string; /** Brand identity declarations */ brand?: AppBrandConfig; /** Deployment and custom domain bindings */ deployment: AppDeploymentConfig; /** Active capabilities and customizations */ capabilities: AppCapabilitiesConfig;}
/** * Type-safe configuration helper providing IntelliSense and compile-time validation. */export function defineAppConfig(config: AppConfig): AppConfig { return config;}4. Real-World Client Example: swarm.config.ts
Section titled “4. Real-World Client Example: swarm.config.ts”Here is an authentic manifest for a local bakery application:
import { defineAppConfig } from "@siteswarm/governance";
export default defineAppConfig({ appId: "green-leaf-bakery", name: "Green Leaf Bakery", brand: { primaryColor: "#2D5A27", accentColor: "#D4A373", logoAssetPath: "public/assets/logo.svg", }, deployment: { productionDomain: "greenleafbakery.com", stagingDomain: "staging.greenleafbakery.siteswarm.dev", cloudPlatform: "cloudflare", }, capabilities: { // 1. Horizontal: Lead Capture with Cloudflare Turnstile & SMS alerts "lead-capture": { type: "horizontal", version: "1.2.0", targets: [ "src/components/ContactForm.astro", "src/pages/api/submit-inquiry.ts", ], options: { provider: "turnstile", notifyChannel: "sms", storeSubmissions: true, }, },
// 2. Horizontal: Menu Catalog "menu-catalog": { type: "horizontal", version: "2.1.0", targets: [ "src/pages/menu.astro", "src/components/PastryGrid.astro", ], options: { currency: "USD", enableDietaryBadges: true, supportsOrdering: false, }, },
// 3. Horizontal: Local Business SEO & Structured Data "dynamic-seo": { type: "horizontal", version: "1.4.0", targets: ["src/layouts/BaseLayout.astro"], options: { schemaType: "Restaurant", enableBreadcrumbs: true, generateOpenGraphImages: true, }, },
// 4. Vertical Customization: Bespoke POS Catering Webhook "legacy-pos-sync": { type: "vertical-custom", description: "Custom webhook forwarding high-value catering inquiries directly to client's legacy Square terminal", targets: ["src/pages/api/catering-pos-relay.ts"], candidateForPromotion: false, notes: "Requires client-specific IP whitelist configured in environment secrets.", }, },});5. Governance CLI & Static Verification Engine
Section titled “5. Governance CLI & Static Verification Engine”TypeScript provides compile-time type safety for swarm.config.ts, but we also need a static verification engine to assert that the manifest agrees with the physical codebase.
5.1 Verification Commands
Section titled “5.1 Verification Commands”# 1. Audit all client applications across the monorepopnpm swarm audit
# 2. Audit a specific client applicationpnpm swarm audit --app green-leaf-bakery
# 3. Generate a cross-fleet capability matrixpnpm swarm matrix
# 4. Identify vertical customizations that may be candidates for promotionpnpm swarm verticals5.2 What pnpm swarm audit Validates:
Section titled “5.2 What pnpm swarm audit Validates:”- Target File Existence: Every path declared in
targets: [...]must physically exist on disk. If a developer or agent deletes or renamesContactForm.astrowithout updatingswarm.config.ts, the audit fails. - Version Conformance: Asserts that horizontal capability versions match the compatible range in
@siteswarm/*. - No Ghost Verticals: Uses static analysis / ripgrep to ensure developers do not introduce major bespoke modules without tagging them as a
vertical-custominswarm.config.ts. - Mandatory Metadata: Asserts that all
vertical-customentries include a non-emptydescriptionfield explaining their business purpose.
flowchart TD A["pnpm swarm audit"] --> B["1. Load all apps/*/swarm.config.ts via jiti / ts-node"] B --> C["2. Validate Types with tsc --noEmit"] C --> D{"Types Valid?"} D -- No --> Err1["Fail CI: TypeScript Compiler Error"] D -- Yes --> E["3. Verify Targets on Disk: fileExists(target)"] E --> F{"All Files Exist?"} F -- No --> Err2["Fail CI: Missing Target File"] F -- Yes --> G["4. Validate Vertical Metadata & Ownership"] G --> H["Pass: Fleet Governance Validated"]6. Agent-First Operational Protocol
Section titled “6. Agent-First Operational Protocol”How do AI coding agents use this capability system during daily work?
Scenario 1: Scaffolding a New Client Application
Section titled “Scenario 1: Scaffolding a New Client Application”When instructed to build a site for a new client (e.g. Apex Auto Repair):
- Scaffold: The agent creates
apps/apex-auto-repair/from the technical scaffold blueprint. - Inspect Catalog: The agent inspects
packages/governance/src/types.tsto see available horizontal capabilities. - Generate Manifest: The agent authors
apps/apex-auto-repair/swarm.config.tsselectinglead-capture,dynamic-seo, andsynthetic-alarms. - Compile-Check: The agent runs
pnpm --filter apex-auto-repair typecheckto verify zero typos. - Implement Bespoke UI: The agent writes tailored pages and components that consume the typed options.
Scenario 2: Fleet-Wide Horizontal Upgrades
Section titled “Scenario 2: Fleet-Wide Horizontal Upgrades”When instructed to “Upgrade the lead capture module to v2.0.0 to support reCAPTCHA-v3 fallback”:
- Matrix Discovery: The agent runs
pnpm swarm matrixto find all apps utilizing"lead-capture". - Target Identification: For each app, the agent reads
swarm.config.tsto locate exact target files (e.g.src/components/ContactForm.astro). - Isolated Refactor: Inside a dedicated Worktrunk worktree, the agent refactors the target files and updates the version tag in
swarm.config.ts. - Vertical Protection: The agent explicitly avoids touching any files listed under
vertical-custom. - Automated Verification: The agent runs
pnpm swarm auditand local smoke tests before submitting PRs.
Scenario 3: Promoting a Vertical to a Horizontal Capability
Section titled “Scenario 3: Promoting a Vertical to a Horizontal Capability”When two or three clients end up needing a similar bespoke feature (e.g. SMS appointment reminders):
- Audit Detection:
pnpm swarm verticalsflags that multiple apps have similar vertical entries markedcandidateForPromotion: true. - Abstraction: A platform engineer (or agent) abstracts the common logic into a new package:
@siteswarm/capability-appointment-reminders. - Register Contract: The contract is added to
SwarmCapabilityRegistryinpackages/governance. - Migrate Clients: The affected client apps update their
swarm.config.tsfromtype: "vertical-custom"totype: "horizontal".
7. Next Steps & Implementation Roadmap
Section titled “7. Next Steps & Implementation Roadmap”- Implement
packages/governance:src/types.ts: Core type contracts (SwarmCapabilityRegistry,AppConfig,defineAppConfig).src/cli/audit.ts: Static manifest and disk target validator.
- Provide starter technical scaffold in
tools/scaffold-client. - Proceed to ADR-001 (Client Data Isolation & Storage Strategy) and ADR-002 (Custom Domain Ingress & Ephemeral Preview Routing).