Capability Compiler

From YAML specs to working code, tests, and metadata in one command

What the Compiler Does

The Capability Compiler takes your CapabilitySpec declarations and generates three file types for each capability: a route handler stub, a test scaffold, and a metadata JSON file. Every generated file is checksummed with SHA-256 and tracked in a manifest, so the compiler can detect manual edits to files it owns and warn you before overwriting them.

The compiler is deterministic. Given the same specs, it always produces the same output. This property is critical for AI agents: they can predict what the compiler will generate before running it, and they can verify that generated files haven't drifted from their spec source.

What It Generates

For each capability in your specs, the compiler produces three files:

File Path Pattern Edit Zone Purpose
Route handler routes/{name}.ts generated Typed handler function with input/output interfaces
Test scaffold tests/{name}.test.ts editable Test stubs for the capability, its policies, and its invariants
Metadata JSON metadata/{name}.json generated Resolved metadata including entities, policies, and invariants

Edit Zone Assignment

Route handlers and metadata files are assigned the generated zone, meaning they will be overwritten on every compile. Test scaffolds are assigned the editable zone, meaning they are generated once as a starting point but are yours to modify. The compiler will not overwrite an edited test file.

Type Mapping

The compiler maps spec field types to TypeScript types when generating input and output interfaces:

Spec Type TypeScript Type
stringstring
number, integer, float, decimalnumber
boolean, boolboolean
date, datetime, timestampDate
string[]string[]
number[]number[]
boolean[]boolean[]
object, jsonRecord<string, unknown>

Example Generated Route Handler

Given the create_user capability from a SaaS billing app:

// ============================================================
// GENERATED BY SYSMARA CAPABILITY COMPILER
// Source: capability:create_user
// Edit Zone: generated
// DO NOT EDIT — this file will be regenerated
// ============================================================

import type { HandlerContext } from '@sysmara/core';

/**
 * Register a new user account in the system
 * Module: users
 * Policies: admin_full_access
 * Invariants: email_must_be_unique
 */
export async function handle(ctx: HandlerContext): Promise<CreateUserOutput> {
  // TODO: Implement create_user
  throw new Error('Not implemented: create_user');
}

// Input/Output types
export interface CreateUserInput {
  email: string;
  name: string;
  role?: string;
}

export interface CreateUserOutput {
  user: unknown;
}

The generated handler includes the capability's description, module, policy references, and invariant references as JSDoc comments. Input fields marked required: false in the spec become optional TypeScript properties.

Example Generated Test Scaffold

The test scaffold creates stubs for each policy and invariant associated with the capability:

// ============================================================
// GENERATED BY SYSMARA CAPABILITY COMPILER
// Source: capability:create_user
// Edit Zone: editable
// This file was generated as a scaffold — you may edit it
// ============================================================

import { describe, it, expect } from 'vitest';

describe('create_user', () => {
  it('should be defined', () => {
    // Capability: Register a new user account in the system
    // Module: users
    expect(true).toBe(true); // Replace with real test
  });

  it('should enforce policy: admin_full_access', () => {
    // Policy enforcement test
    expect(true).toBe(true); // Replace with real test
  });

  it('should maintain invariant: email_must_be_unique', () => {
    // Invariant validation test
    expect(true).toBe(true); // Replace with real test
  });
});

Metadata JSON

The metadata file contains resolved references. Instead of just storing policy names, it resolves them to their descriptions and effects. Instead of just entity names, it resolves them to descriptions and modules. This gives AI agents rich context about each capability without requiring them to cross-reference multiple spec files.

{
  "name": "create_user",
  "description": "Register a new user account in the system",
  "module": "users",
  "entities": [
    {
      "name": "user",
      "description": "A registered user who can own workspaces and subscriptions",
      "module": "users"
    }
  ],
  "input": [
    { "name": "email", "type": "string", "required": true, "description": "User email address" },
    { "name": "name", "type": "string", "required": true, "description": "Display name" },
    { "name": "role", "type": "string", "required": false, "description": "System role — defaults to member" }
  ],
  "output": [
    { "name": "user", "type": "user", "required": true, "description": "The created user entity" }
  ],
  "policies": [
    { "name": "admin_full_access", "description": "System administrators have unrestricted access to all capabilities", "effect": "allow" }
  ],
  "invariants": [
    { "name": "email_must_be_unique", "description": "No two users can share the same email address", "entity": "user", "severity": "error", "enforcement": "runtime" }
  ],
  "sideEffects": [],
  "idempotent": false
}

Checksum Verification and the Manifest

After generating all files, the compiler produces a manifest that records every generated file along with its source capability, edit zone, SHA-256 checksum, and whether it is regenerable.

{
  "generatedAt": "2025-03-14T12:00:00.000Z",
  "files": [
    {
      "path": "generated/routes/create_user.ts",
      "source": "capability:create_user",
      "zone": "generated",
      "checksum": "a1b2c3d4e5f6...",
      "regenerable": true
    },
    {
      "path": "generated/tests/create_user.test.ts",
      "source": "capability:create_user",
      "zone": "editable",
      "checksum": "f6e5d4c3b2a1...",
      "regenerable": false
    },
    {
      "path": "generated/metadata/create_user.json",
      "source": "capability:create_user",
      "zone": "generated",
      "checksum": "1a2b3c4d5e6f...",
      "regenerable": true
    }
  ]
}

Files with zone: "generated" have regenerable: true, meaning the compiler will overwrite them on every run. Files with zone: "editable" have regenerable: false, meaning the compiler generated them once as scaffolds.

Compiler Diagnostics

The compiler validates cross-references during compilation. If a capability references an entity, policy, or invariant that does not exist in the specs, it emits a diagnostic:

These diagnostics include the source capability, the JSON path to the invalid reference, and a suggestion for how to fix it.

Running the Compiler

sysmara compile

This parses your specs, runs cross-reference validation, generates all three file types per capability, computes checksums, writes the manifest, and reports any diagnostics. The output directory is determined by your sysmara.config.yaml generatedDir setting.

AI-Safe Change Workflows

The compiler is central to SysMARA's AI-safe workflow. When an AI agent modifies a capability spec, it runs sysmara compile to regenerate route handlers and metadata. Because route handlers are in the generated zone, the agent knows it can safely overwrite them. Because test scaffolds are in the editable zone, the agent knows not to overwrite tests that a human has customized. The manifest's checksums let the Change Protocol detect drift between specs and generated code.