Headless Capability Package Anatomy, Contracts & Module Isolation Specification
Headless Capability Package Anatomy, Contracts & Module Isolation Specification
Section titled βHeadless Capability Package Anatomy, Contracts & Module Isolation SpecificationβDocument Status: π’ Active True Specification (Medium-Level Design)
Authority: Canonical architectural standard for authoring, structuring, and maintaining headless capability packages (packages/capabilities/*).
Primary Maintainer: SiteSwarm Architecture Council
Related Documents: HIGH_LEVEL_DESIGN.md, docs/CAPABILITY_MANAGEMENT.md, docs/DATA_ISOLATION_AND_STORAGE.md, docs/specs/CLIENT_APPLICATION_ANATOMY.md, docs/specs/MULTI_WORKER_PLATFORM_SERVICES.md, docs/specs/ARCHITECTURAL_LINTERS.md
Governing Epic: #35 (epic(architecture): headless capability package contract and module anatomy)
Companion Epics: #34 (Client Application Anatomy), #104 (Strategic Roadmap Initiative)
1. Executive Summary & The Headless Invariant
Section titled β1. Executive Summary & The Headless InvariantβSiteSwarm delivers enterprise-grade software velocity to local businesses by combining a unified monorepo and shared capability engines with 100% bespoke, unrestrained visual user interfaces.
In traditional agency setups, shared components inevitably create a βcookie-cutterβ fleet: every clientβs website looks like the same Bootstrap or WordPress template. SiteSwarm completely rejects shared visual UI components across client applications. Instead, shared leverage is achieved exclusively through Headless Capability Packages (packages/capabilities/*).
The Headless Invariant
Section titled βThe Headless InvariantβThe Headless Invariant: Capability packages provide headless business logic, data models, calculation state machines, client event controllers, and edge server handlers. They must NEVER render DOM elements, provide HTML templates, or inject CSS classes or design tokens.
By strictly severing presentation from capability mechanics, AI agents and engineers can author bespoke Astro pages and Tailwind styling tailored to each local businessβs unique aesthetic, while delegating complex mechanics (Turnstile validation, instant quote algorithms, SEO structured data, booking state machines) to robust, tested platform engines.
flowchart TD subgraph ClientApp["apps/<client>/ (100% Bespoke Visual UI)"] UI_Markup["Bespoke Astro Pages & Components\n(Tailwind CSS, Brand Colors, Custom Layouts)"] UI_Event["User Input / Button Clicks"] end
subgraph CapabilityPackage["packages/capabilities/<name>/ (Headless Capability Engine)"] direction TB subgraph SubpathClient["Subpath: ./client"] Client_Controller["mountLeadForm / State Controllers\n(Event Listeners, Honeypots, Error State)"] end subgraph SubpathSchemas["Subpath: ./schemas (or root)"] Shared_Schemas["Zod Schemas, TypeScript Interfaces,\nPure Calculation Engines"] end subgraph SubpathServer["Subpath: ./server"] Edge_Handler["Edge Route Handlers, Turnstile Verifier,\nService Binding Proxy"] end end
subgraph StoragePlatform["Storage & Platform Services Tier"] D1_DB["Cloudflare D1 / Platform Service Mesh"] end
UI_Markup -->|Attaches unstyled runner| Client_Controller Client_Controller -->|Validates payload| Shared_Schemas UI_Event -->|Dispatches request| Edge_Handler Edge_Handler -->|Validates payload| Shared_Schemas Edge_Handler -->|Queries / Persists| D1_DB2. Capability Package Anatomy & Directory Composition
Section titled β2. Capability Package Anatomy & Directory CompositionβEvery capability package lives inside packages/capabilities/<capability-name>/ and adheres to a standardized directory composition designed for clean runtime boundary isolation and zero circular dependencies.
2.1 Canonical Directory Layout
Section titled β2.1 Canonical Directory Layoutβpackages/capabilities/<capability-name>/βββ package.json # Explicit subpath exports (".", "./client", "./server", "./schemas")βββ tsconfig.json # Strict TypeScript configurationβββ README.md # Usage documentation, options contract, and examplesβββ migrations/ # Optional: D1 SQLite migrations (for client-hosted tables)β βββ 0001_initial.sql # Strictly namespaced: cap_<capability-name>_*βββ src/β βββ index.ts # Root entry point: re-exports universal schemas & core enginesβ βββ schemas/ # Environment-agnostic data models & validationβ β βββ index.ts # Re-exports all schemas and typesβ β βββ models.ts # Pure TypeScript types & interfacesβ β βββ options.ts # Zod options schema for swarm.config.tsβ βββ client/ # Headless browser runtime (zero DOM/CSS)β β βββ index.ts # State controllers, event runners, unstyled DOM hooksβ βββ server/ # Cloudflare Edge runtime (zero browser APIs)β βββ index.ts # Astro APIRoute handlers, verification helpers, middlewareβββ tests/ βββ <capability-name>.test.ts # Node.js test runner unit & contract tests2.2 Subpath Exports & Runtime Boundaries (package.json)
Section titled β2.2 Subpath Exports & Runtime Boundaries (package.json)βTo prevent bundlers from accidentally leaking edge worker secrets or Cloudflare bindings into client-side browser bundles, or leaking browser DOM APIs into edge SSR workers, capability packages define explicit subpath exports:
{ "name": "@siteswarm/quote-estimator", "version": "0.1.0", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", "exports": { ".": { "types": "./src/index.ts", "import": "./src/index.ts", "default": "./src/index.ts" }, "./schemas": { "types": "./src/schemas/index.ts", "import": "./src/schemas/index.ts", "default": "./src/schemas/index.ts" }, "./client": { "types": "./src/client/index.ts", "import": "./src/client/index.ts", "default": "./src/client/index.ts" }, "./server": { "types": "./src/server/index.ts", "import": "./src/server/index.ts", "default": "./src/server/index.ts" } }, "scripts": { "build": "tsc", "check": "tsc --noEmit", "test": "tsx --test tests/**/*.test.ts" }, "dependencies": { "zod": "^3.24.2" }}2.3 Unidirectional Dependency Rule & Circular Dependency Prevention
Section titled β2.3 Unidirectional Dependency Rule & Circular Dependency PreventionβCapability packages must enforce a strict unidirectional internal dependency flow:
flowchart TD Schemas["src/schemas/\n(Pure Types, Models, Zod, Constants)"] Client["src/client/\n(Browser State Controllers)"] Server["src/server/\n(Edge Route Handlers & Adapters)"] Root["src/index.ts\n(Universal Entry Point)"]
Client -->|Imports schemas & types| Schemas Server -->|Imports schemas & types| Schemas Root -->|Re-exports universal symbols| Schemas
Client -.->|β FORBIDDEN (No Server Imports)| Server Server -.->|β FORBIDDEN (No Client/DOM Imports)| Clientsrc/schemas/is Environment-Agnostic: Contains pure TypeScript types, interfaces, request/response models, Zod validation schemas, business constants, and calculation engines. It has zero dependencies on browser globals (window,document,HTMLElement) and zero dependencies on Cloudflare Worker runtime globals (Request,Response,ExecutionContext).src/client/Imports Only fromsrc/schemas/: Browser controllers and unstyled form managers import validation schemas and models from../schemas. They never import from../server. They may re-export client-relevant models for ergonomic consumer convenience.src/server/Imports Only fromsrc/schemas/: Edge handlers and verification adapters import schemas and types from../schemas. They never import from../client. They may re-export server-relevant models for ergonomic consumer convenience.- Zero Circular Dependencies: Because both
client/andserver/depend downward uponschemas/, circular dependencies between browser and server code paths are mathematically eliminated.
3. Database Persistence & D1 Migration Bundling
Section titled β3. Database Persistence & D1 Migration BundlingβIn accordance with Data Isolation & Storage Strategy, capability packages support two distinct persistence archetypes depending on whether data is stored locally in client databases or centrally in platform services.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ Capability Persistence Archetypes βββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββ€β Archetype 1: Client-Hosted β β’ Capability bundled with client app ββ (Decentralized Dedicated D1) β β’ Dedicated D1 binding in wrangler.jsonc ββ β β’ SQL migrations bundled in package ββ β β’ Strict table prefix: cap_<name>_* βββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββ€β Archetype 2: Platform-Hosted β β’ Backed by central Platform Worker Service ββ (Service Mesh Tier 1) β β’ Migrations live in services/<service>/ ββ β β’ Package exports client SDK & edge proxy ββ β β’ Multi-tenant partition via tenant_id βββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββ3.1 Archetype 1: Client-Hosted Capability (Embedded / Dedicated D1)
Section titled β3.1 Archetype 1: Client-Hosted Capability (Embedded / Dedicated D1)βWhen a capability requires database storage and the consuming client application self-hosts the database (e.g. dedicated client D1 for custom quote storage, local cache, or audit logs):
- Bundled SQL Migrations: The capability package maintains idempotent, ordered SQL migration files under
packages/capabilities/<name>/migrations/:-- packages/capabilities/quote-estimator/migrations/0001_initial.sqlCREATE TABLE IF NOT EXISTS cap_quote_estimator_quotes (id TEXT PRIMARY KEY,tenant_id TEXT NOT NULL,service_tier TEXT NOT NULL,estimated_price_cents INTEGER NOT NULL,customer_email TEXT,status TEXT NOT NULL DEFAULT 'draft',metadata TEXT,created_at TEXT NOT NULL DEFAULT (datetime('now')),updated_at TEXT NOT NULL DEFAULT (datetime('now')));CREATE INDEX IF NOT EXISTS idx_cap_quote_estimator_tenantON cap_quote_estimator_quotes(tenant_id, created_at DESC); - Mandatory Table Namespacing: All table and index names must use the strict prefix
cap_<capability_name>_(e.g.cap_quote_estimator_*). This guarantees that when a client application activates multiple capabilities, table namespaces never collide in the shared SQLite catalog. - Composite Primary / Partition Keys: Tables include
tenant_idto allow portable extraction or migration between dedicated and pooled databases without schema alterations.
3.2 Archetype 2: Platform-Hosted Capability (Central Service Mesh)
Section titled β3.2 Archetype 2: Platform-Hosted Capability (Central Service Mesh)βWhen a capability is backed by a shared platform worker service (services/leads-service, services/cms-service, services/analytics-service):
- Database Schema Lives in Platform Service: Migrations live alongside the platform worker service (e.g.,
services/leads-service/migrations/), not inside the capability package. - Capability Package is a Headless SDK & Proxy: The capability package in
packages/capabilities/<name>/provides:- Typed client-side form runner (
/client). - Edge route forwarding proxy (
/server) that calls the platform service via Cloudflare Service Bindings (env.LEADS_SERVICE.fetch()) with tenant context injection (tenantId = manifest.appId). - Pure request/response Zod schemas (
/schemas).
- Typed client-side form runner (
4. Governance Contract Integration (swarm.config.ts)
Section titled β4. Governance Contract Integration (swarm.config.ts)βEvery capability package must integrate with @siteswarm/governance so that client applications can declare it with compile-time type safety in apps/<client>/swarm.config.ts, and CI can verify it with pnpm swarm audit.
4.1 Decentralized Zod Options Schema
Section titled β4.1 Decentralized Zod Options SchemaβRather than centralizing all capability options into a monolithic governance file, each capability package defines its own typed options schema inside src/schemas/options.ts:
import { z } from "zod";
export const quoteEstimatorOptionsSchema = z.object({ currency: z.enum(["USD", "EUR", "GBP"]).default("USD"), baseRateCents: z.number().int().nonnegative(), rushMultiplier: z.number().positive().default(1.5), enableInstantEmail: z.boolean().default(false), maxRangeVariancePercent: z.number().min(0).max(100).default(15),});
export type QuoteEstimatorOptions = z.infer<typeof quoteEstimatorOptionsSchema>;4.2 TypeScript Module Augmentation (SwarmCapabilityRegistry)
Section titled β4.2 TypeScript Module Augmentation (SwarmCapabilityRegistry)βTo register with defineAppConfig without requiring manual edits to @siteswarm/governance, the capability package augments the SwarmCapabilityRegistry interface:
import type { QuoteEstimatorOptions } from "./schemas/options.js";
declare module "@siteswarm/governance" { interface SwarmCapabilityRegistry { "quote-estimator": QuoteEstimatorOptions; }}When a client application imports @siteswarm/quote-estimator and @siteswarm/governance, TypeScript automatically merges the interface. Typing quote-estimator in swarm.config.ts yields instant IntelliSense and compile-time validation:
import { defineAppConfig } from "@siteswarm/governance";import "@siteswarm/quote-estimator"; // Augments SwarmCapabilityRegistry
export default defineAppConfig({ appId: "software-agency", name: "Apex Software Agency", // ... capabilities: { "quote-estimator": { type: "horizontal", version: "0.1.0", targets: [ "src/components/QuoteCalculator.astro", "src/pages/api/estimate.ts", ], options: { currency: "USD", baseRateCents: 15000, rushMultiplier: 1.5, }, }, },});4.3 Static Verification via pnpm swarm audit
Section titled β4.3 Static Verification via pnpm swarm auditβThe governance CLI (pnpm swarm audit) automatically validates:
- Target Existence: Every path declared in
targets: [...]physically exists inapps/<client>/. - Registry Membership: The capability name is a registered horizontal capability in
SwarmCapabilityRegistry. - AST Architectural Compliance: Asserts that client source files do not bypass the capability by directly reimplementing third-party endpoints or hardcoding credentials.
5. Vertical-to-Horizontal Promotion Protocol
Section titled β5. Vertical-to-Horizontal Promotion ProtocolβLocal business client code often begins as a bespoke, vertical customization in apps/<client>/ (tagged as type: "vertical-custom" in swarm.config.ts). Over time, high-value patterns emerge that should be promoted into shared platform capabilities.
5.1 The Human-in-the-Loop Governance Model
Section titled β5.1 The Human-in-the-Loop Governance ModelβThe Human-in-the-Loop Mandate: AI coding agents MUST NEVER autonomously promote client vertical code to a horizontal platform capability or make unilateral decisions about platform capability boundaries. Capability extraction defines our core commercial moat and engineering contracts; it requires explicit human review and direction from the Lead Architect.
5.2 Promotion Qualification Criteria
Section titled β5.2 Promotion Qualification CriteriaβA bespoke vertical customization qualifies for promotion evaluation under the Hybrid Escalation Model:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ Promotion Qualification Criteria βββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββ€β 1. The Rule of Two β β₯2 client applications require the same ββ β underlying workflow, calculation, or API. βββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββ€β 2. Proactive Commercial Valueβ Lead Architect or agent identifies a high- ββ β leverage upsell module for the sales pitch. βββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββ€β 3. 100% Headless Purity Gate β Business mechanics can be 100% severed from ββ β visual DOM markup, Tailwind, and CSS. βββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββ€β 4. Multi-Tenant Feasibility β Operates cleanly with tenant scoping, with ββ β zero hardcoded client IDs or credentials. βββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββ5.3 Step-by-Step Promotion Workflow
Section titled β5.3 Step-by-Step Promotion WorkflowβsequenceDiagram autonumber actor Dev as Lead Architect (Human) participant Agent as AI Coding Agent participant Fleet as apps/<client>/ participant Gov as @siteswarm/governance participant Cap as packages/capabilities/<name>/
Agent->>Fleet: pnpm swarm verticals identifies candidate Agent->>Dev: Escalates issue with Architectural Promotion Brief Dev->>Agent: Approves promotion & defines capability intent Agent->>Cap: Scaffolds package conforming to canonical anatomy Agent->>Cap: Extracts pure schemas, client runner, edge handler Agent->>Cap: Authors unit test suite (100% coverage) Agent->>Gov: Augments SwarmCapabilityRegistry with Zod schema Agent->>Fleet: Refactors origin client apps to import new capability Agent->>Fleet: Updates swarm.config.ts to type: "horizontal" Agent->>Dev: Runs pnpm swarm audit & pnpm test, opens PR- Detection & Discovery: During grooming or audit sessions (
pnpm swarm verticals), candidate verticals marked withcandidateForPromotion: trueor duplicate vertical patterns across $\ge 2$ apps are flagged. - Escalation & Architectural Brief: The agent logs a GitHub issue titled
feat(capability): propose horizontal extraction of <name>containing:- Origin client applications and current LOC.
- Proposed headless boundary separation (
/client,/server,/schemas). - Proposed Zod options schema for
swarm.config.ts. - Commercial value proposition and upsell potential.
- Human Approval: The Lead Architect reviews and approves the product intent and contract design.
- Extraction & Packaging:
- Create
packages/capabilities/<name>/. - Implement
src/schemas/,src/client/, andsrc/server/. - Enforce zero DOM/CSS styling in the capability package.
- Add unit tests verifying calculation engines and validation rules.
- Create
- Fleet Backporting & Verification:
- Refactor origin client apps to import the new package.
- Update
swarm.config.tsfromvertical-customtohorizontal. - Verify
pnpm swarm audit,pnpm run check, and Playwright E2E suites.
6. Living Reference Capabilities (No Static Template Directory)
Section titled β6. Living Reference Capabilities (No Static Template Directory)βSiteSwarm intentionally does NOT maintain a static packages/capabilities/_template/ directory. Standalone template directories inevitably suffer from bit-rot, outdated dependencies, and maintenance drift.
Instead, existing production capabilities serve as the live, tested reference blueprints, enforced by automated AST linters:
| Reference Capability | Canonical Role & Reference Implementation |
|---|---|
@siteswarm/quote-estimator |
Pure Calculation Engine & Zod Schemas: Demonstrates mathematical state modeling, formula calculation engines, parameter variance, and pure schema contracts. |
@siteswarm/lead-capture |
Subpath Client Runner & Server Security: Demonstrates headless client form controllers (@siteswarm/lead-capture/client via mountLeadForm), honeypot absorption, Turnstile verification, and API route handling. |
@siteswarm/seo |
Headless Structured Data & OpenGraph: Demonstrates Schema.org JSON-LD generation, breadcrumb builders, and dynamic meta tag composition. |
7. Automated Architectural Linter Rules for Capabilities
Section titled β7. Automated Architectural Linter Rules for CapabilitiesβIn addition to client application linters, the SiteSwarm governance engine (@siteswarm/governance) enforces capability package anatomy via automated AST lint rules:
// Architectural Rules Enforced in packages/capabilities/*cap-headless-purity(Severity: ERROR):- Capability source files (
src/**/*.ts) must never import UI rendering libraries or contain inline HTML/JSX DOM nodes. - Capability packages must never contain
.astro,.vue,.jsx, or.cssfiles.
- Capability source files (
cap-unidirectional-dependencies(Severity: ERROR):- Source files in
src/client/must never import from../serveror../server/*. - Source files in
src/server/must never import from../clientor../client/*.
- Source files in
cap-d1-table-namespace(Severity: ERROR):- Any SQL file in
packages/capabilities/<name>/migrations/*.sqlmust prefix table and index definitions withcap_<capability_name>_.
- Any SQL file in
cap-subpath-exports(Severity: ERROR):- The package
package.jsonmust declare anexportsmap exposing explicit subpaths (".","./client","./server", or"./schemas").
- The package
8. Summary of Guarantees
Section titled β8. Summary of Guaranteesβ| Invariant | Guarantee |
|---|---|
| Zero-Template Visual Freedom | Clients maintain 100% unique brand aesthetics; capabilities never output HTML or CSS. |
| Runtime Isolation | Client browser bundles never import edge server secrets; edge handlers never import DOM APIs. |
| Zero Circular Dependencies | Strict unidirectional dependency flow (client -> schemas, server -> schemas). |
| D1 Catalog Protection | Strict cap_<name>_* SQL prefixes prevent database table collisions. |
| Compile-Time Safety | defineAppConfig and swarm.config.ts validate options through TypeScript augmentation. |
| Human-Guided Architecture | AI agents recommend and escalate extractions; human engineers govern commercial and platform intent. |