Skip to content

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


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:

  1. Type-Safe App Manifest (swarm.config.ts): Every client application declares its utilized features using strong TypeScript contracts, guaranteeing zero-drift compile-time safety.
  2. Horizontal vs. Vertical Classification: Distinguishes reusable platform capabilities from one-off, client-specific vertical customizations.
  3. 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.
  4. Governance Tooling & Auditing: Provides CLI tooling (swarm audit, swarm matrix) to verify that targets declared in code match actual file assets on disk.

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"| File3
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”
packages/governance/src/types.ts
/**
* 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)”
packages/governance/src/types.ts
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:

apps/green-leaf-bakery/swarm.config.ts
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.

Terminal window
# 1. Audit all client applications across the monorepo
pnpm swarm audit
# 2. Audit a specific client application
pnpm swarm audit --app green-leaf-bakery
# 3. Generate a cross-fleet capability matrix
pnpm swarm matrix
# 4. Identify vertical customizations that may be candidates for promotion
pnpm swarm verticals
  1. Target File Existence: Every path declared in targets: [...] must physically exist on disk. If a developer or agent deletes or renames ContactForm.astro without updating swarm.config.ts, the audit fails.
  2. Version Conformance: Asserts that horizontal capability versions match the compatible range in @siteswarm/*.
  3. No Ghost Verticals: Uses static analysis / ripgrep to ensure developers do not introduce major bespoke modules without tagging them as a vertical-custom in swarm.config.ts.
  4. Mandatory Metadata: Asserts that all vertical-custom entries include a non-empty description field 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"]

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):

  1. Scaffold: The agent creates apps/apex-auto-repair/ from the technical scaffold blueprint.
  2. Inspect Catalog: The agent inspects packages/governance/src/types.ts to see available horizontal capabilities.
  3. Generate Manifest: The agent authors apps/apex-auto-repair/swarm.config.ts selecting lead-capture, dynamic-seo, and synthetic-alarms.
  4. Compile-Check: The agent runs pnpm --filter apex-auto-repair typecheck to verify zero typos.
  5. 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”:

  1. Matrix Discovery: The agent runs pnpm swarm matrix to find all apps utilizing "lead-capture".
  2. Target Identification: For each app, the agent reads swarm.config.ts to locate exact target files (e.g. src/components/ContactForm.astro).
  3. Isolated Refactor: Inside a dedicated Worktrunk worktree, the agent refactors the target files and updates the version tag in swarm.config.ts.
  4. Vertical Protection: The agent explicitly avoids touching any files listed under vertical-custom.
  5. Automated Verification: The agent runs pnpm swarm audit and 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):

  1. Audit Detection: pnpm swarm verticals flags that multiple apps have similar vertical entries marked candidateForPromotion: true.
  2. Abstraction: A platform engineer (or agent) abstracts the common logic into a new package: @siteswarm/capability-appointment-reminders.
  3. Register Contract: The contract is added to SwarmCapabilityRegistry in packages/governance.
  4. Migrate Clients: The affected client apps update their swarm.config.ts from type: "vertical-custom" to type: "horizontal".

  1. Implement packages/governance:
    • src/types.ts: Core type contracts (SwarmCapabilityRegistry, AppConfig, defineAppConfig).
    • src/cli/audit.ts: Static manifest and disk target validator.
  2. Provide starter technical scaffold in tools/scaffold-client.
  3. Proceed to ADR-001 (Client Data Isolation & Storage Strategy) and ADR-002 (Custom Domain Ingress & Ephemeral Preview Routing).