diff --git a/.gitignore b/.gitignore index 48ec5ae..7a438c2 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,8 @@ dist/ .dev.vars *.log .mcp.json +# cc-taskrunner worktree protection +C:* +node_modules/ +.pnpm-store/ +__pycache__/ diff --git a/docs-manifest.json b/docs-manifest.json index e13661c..01979f4 100644 --- a/docs-manifest.json +++ b/docs-manifest.json @@ -1,78 +1,78 @@ -{ - "$schema": "Stackbilt docs sync manifest — maps product repos to doc site pages", - "version": 1, - "contentDir": "src/content/docs", - "org": "Stackbilt-dev", - "sources": { - "charter": { - "repo": "charter", - "pages": { - "getting-started.md": { - "source": "docs/getting-started.md", - "fallback": "README.md", - "section": "charter", - "order": 1, - "color": "#2ea043", - "tag": "01" - }, - } - }, - "edgestack": { - "repo": "edgestack_v2", - "pages": { - "platform.md": { - "source": "docs/platform.md", - "section": "platform", - "order": 4, - "color": "#f472b6", - "tag": "04" - }, - "mcp.md": { - "source": "docs/mcp.md", - "section": "platform", - "order": 5, - "color": "#22d3ee", - "tag": "05" - }, - "api-reference.md": { - "source": "docs/api-reference.md", - "section": "platform", - "order": 7, - "color": "#c084fc", - "tag": "07" - }, - "compass-governance-api.md": { - "source": "docs/compass-governance-api.md", - "section": "platform", - "order": 8, - "color": "#22d3ee", - "tag": "08" - } - } - }, - "ecosystem": { - "repo": "edgestack_v2", - "pages": { - "ecosystem.md": { - "source": "docs/ecosystem.md", - "section": "ecosystem", - "order": 6, - "color": "#c084fc", - "tag": "06" - } - } - }, - "img-forge": { - "repo": "img-forge", - "pages": { - "img-forge.md": { - "source": "docs/img-forge.md", - "section": "platform", - "order": 9, - "color": "#f472b6", - "tag": "09" - } - } - } - } -} +{ + "$schema": "Stackbilt docs sync manifest — maps product repos to doc site pages", + "version": 1, + "contentDir": "src/content/docs", + "org": "Stackbilt-dev", + "sources": { + "charter": { + "repo": "charter", + "pages": { + "getting-started.md": { + "source": "docs/getting-started.md", + "fallback": "README.md", + "section": "charter", + "order": 1, + "color": "#2ea043", + "tag": "01" + } + } + }, + "edgestack": { + "repo": "edgestack_v2", + "pages": { + "platform.md": { + "source": "docs/platform.md", + "section": "platform", + "order": 4, + "color": "#f472b6", + "tag": "04" + }, + "mcp.md": { + "source": "docs/mcp.md", + "section": "platform", + "order": 5, + "color": "#22d3ee", + "tag": "05" + }, + "api-reference.md": { + "source": "docs/api-reference.md", + "section": "platform", + "order": 7, + "color": "#c084fc", + "tag": "07" + }, + "compass-governance-api.md": { + "source": "docs/compass-governance-api.md", + "section": "platform", + "order": 8, + "color": "#22d3ee", + "tag": "08" + } + } + }, + "ecosystem": { + "repo": "edgestack_v2", + "pages": { + "ecosystem.md": { + "source": "docs/ecosystem.md", + "section": "ecosystem", + "order": 6, + "color": "#c084fc", + "tag": "06" + } + } + }, + "img-forge": { + "repo": "img-forge", + "pages": { + "img-forge.md": { + "source": "docs/img-forge.md", + "section": "platform", + "order": 9, + "color": "#f472b6", + "tag": "09" + } + } + } + } +} diff --git a/src/content/docs/compass-governance-api.md b/src/content/docs/compass-governance-api.md index cd70b6d..497597f 100644 --- a/src/content/docs/compass-governance-api.md +++ b/src/content/docs/compass-governance-api.md @@ -7,102 +7,175 @@ color: "#22d3ee" tag: "08" --- -# Compass Governance +# Compass Governance API -Compass is an internal governance service accessed via Cloudflare Service Binding from the Stackbilder flow pipeline. It is **not a public API** — there are no HTTP endpoints, no MCP server, and no admin surface. +Compass is the governance system behind StackBilt. This page documents the current Compass API surface and route taxonomy implemented in the `DigitalCSA` worker. -## Architecture +Base URL (production): accessed via Stackbilder service binding (not a public subdomain) -Compass is a lightweight RPC service (`compass` worker) bound to EdgeStack via `CSA_SERVICE` service binding. It provides governance guidance, quality assessment, and decision persistence for the 6-mode flow pipeline. +## What This Covers -``` -EdgeStack (FlowDO) - │ - ├── fetchGuidance(mode, tier) → constraints + quality thresholds - │ - ├── mode execution (LLM) - │ - ├── assessQuality(artifact) → score + pass/fail - │ - └── persistDecisions(decisions) → ledger write (SPRINT mode only) -``` +- Compass MCP endpoints (`/mcp`, `/mcp/info`, legacy compatibility paths) +- Canonical admin/domain route taxonomy +- JWT + JWKS auth routes +- Core governance APIs (ledger, patterns, requests, triage, validation, exhibits, agent ops) -## RPC Methods +This page is a route map and integration reference, not a full schema-level endpoint spec. -All calls go through `POST /rpc` with JSON-RPC payload. Requires `scope` object with `projectId`, `flowId`, `mode`, `tier`, `effectiveGovernanceMode`. +## Authentication Model -### compass.fetchGuidance +Compass uses scoped API auth for most `/api/*` routes and enforces tenant/domain boundaries in the worker: -Returns governance context and quality thresholds for a flow mode. Called before each mode execution. +- ecosystem scope (`ecosystem_id`) +- optional domain/project scope (`domain_id` / `project_id`) +- payload scope enforcement on write requests (`POST` / `PATCH` / `PUT`) -```json -{ - "method": "compass.fetchGuidance", - "params": { - "scope": { - "projectId": "...", - "flowId": "...", - "mode": "ARCHITECT", - "tier": "pro", - "effectiveGovernanceMode": "ADVISORY" - } - } -} -``` +### MCP Authentication (`/mcp`) -### compass.assessQuality +Compass MCP supports: -Scores a generated artifact against quality thresholds. Called after artifact generation. +- JWT Bearer token (primary) +- session-based follow-up requests via `mcp-session-id` +- query-token compatibility mode (deprecated; can be warn/block mode) -```json -{ - "method": "compass.assessQuality", - "params": { - "scope": { "..." }, - "artifact": "...", - "mode": "ARCHITECT" - } -} -``` +If no valid JWT and no session is present, Compass rejects the request. -### compass.persistDecisions +### JWT / JWKS Routes -Stores ADRs and architectural decisions in the governance ledger. Called at end of SPRINT mode only. +| Endpoint | Method | Notes | +|---|---|---| +| `/api/.well-known/jwks.json` | `GET` | Public JWKS for JWT verification | +| `/api/auth/token` | `POST` | Issue Compass JWT (requires valid API key) | +| `/api/auth/revoke` | `POST` | Revoke JWTs (admin only) | -```json -{ - "method": "compass.persistDecisions", - "params": { - "scope": { "..." }, - "decisions": [{ "..." }] - } -} -``` +## MCP Endpoints -## Governance Modes by Plan +| Endpoint | Method | Purpose | +|---|---|---| +| `/mcp/info` | `GET` | Public server info / capabilities summary | +| `/mcp` | `GET` | SSE stream (session-capable) | +| `/mcp` | `POST` | MCP JSON-RPC requests | +| `/mcp` | `DELETE` | End MCP session | +| `/mcp/*` | `GET/POST` | MCP path variants routed through the same handler | +| `/mcp-client/*` | varies | Admin-only MCP client routes (feature flagged) | -| Plan | Max Mode | Behavior | -|------|----------|----------| -| Free | `PASSIVE` | Log only — never blocks | -| Pro | `ADVISORY` | Warn on issues, flow continues | -| Enterprise | `ENFORCED` | Block on FAIL, require remediation | +## Canonical Route Taxonomy -## Integration +Compass uses a canonical route structure for admin, domain registry, and domain-scoped governance operations. -EdgeStack creates a `CompassExchangeClient` per flow (cached, 5-min TTL). The client calls Compass via service binding with a 10-second timeout. +### Admin Routes (`/api/admin/*`) -```toml -# edgestack-v2/wrangler.toml -[[services]] -binding = "CSA_SERVICE" -service = "compass" -``` +Primary admin surfaces include: -## Future Direction +- `/api/admin/keys` +- `/api/admin/domains` +- `/api/admin/repo-keys` +- `/api/admin/repo-keys/:keyId/rotate` +- `/api/admin/repo-keys/:keyId/revoke` +- `/api/admin/repo-keys/:keyId/events` +- `/api/admin/repos/:repoId/revoke-all-keys` -Compass governance logic is being consolidated into the Stackbilder Engine (`stackbilt-engine`), which already handles blessed pattern enforcement, compatibility scoring, and tier gating deterministically. See [edgestack#32](https://github.com/Stackbilt-dev/edgestack_v2/issues/32) for the migration plan. +These routes require admin auth and apply scope checks before writes. + +### Domain Registry Routes (`/api/domains`) + +Admin-manageable domain registry endpoints: + +- `GET/POST /api/domains` +- `GET/PATCH /api/domains/:domainId` + +### Domain-Scoped Governance Routes (`/api/domains/:domainId/*`) + +These routes enforce domain ownership and payload scoping. + +| Endpoint Pattern | Methods | Purpose | +|---|---|---| +| `/api/domains/:domainId/ledger` | `GET`, `POST` | Ledger entries | +| `/api/domains/:domainId/tickets` | `GET`, `POST` | Governance requests/tickets | +| `/api/domains/:domainId/chat/threads` | `GET`, `POST` | Domain chat threads | +| `/api/domains/:domainId/chat/threads/:id` | `GET`, `PATCH`, `DELETE` | Thread lifecycle | +| `/api/domains/:domainId/chat/threads/:id/messages` | `POST` | Send message | +| `/api/domains/:domainId/patterns` | `GET`, `POST` | Pattern catalog | +| `/api/domains/:domainId/patterns/:id` | `GET`, `PATCH`, `DELETE` | Pattern management | +| `/api/domains/:domainId/protocols` | `GET`, `POST` | Protocols | +| `/api/domains/:domainId/protocols/:id` | `DELETE` | Protocol delete | + +## Core Governance APIs (Top-Level) + +Compass also exposes top-level scoped APIs (with `ecosystem_id` / `project_id` query support in many cases) for compatibility and operational workflows. + +### Ledger, Patterns, Requests + +- `/api/ledger` +- `/api/ledger/:id` +- `/api/ledger/temporal/valid-at` +- `/api/ledger/temporal/approaching-review` +- `/api/ledger/:id/temporal` +- `/api/patterns` +- `/api/patterns/:id` +- `/api/requests` +- `/api/requests/:id` +- `/api/requests/:id/resolve` +- `/api/requests/:id/notes` + +### Triage, Audit, Validation + +- `/api/triage/run` +- `/api/triage/commit` (admin) +- `/api/triage/history` +- `/api/triage/entropy` +- `/api/triage/detect` +- `/api/triage/scope` +- `/api/audit/report` +- `/api/validate` +- `/api/validate/history` (admin) +- `/api/git/validate` +- `/api/git/validations` (admin) + +### Submission + Chat + +- `/api/submit` +- `/api/submit/my` +- `/api/submit/status/:id` +- `/api/chat/threads` +- `/api/chat/threads/:id` +- `/api/chat/threads/:id/messages` + +### Exhibits (Constitution / Policy Content) + +- `/api/exhibits` +- `/api/exhibits/active/:projectId` +- `/api/exhibits/:id` +- `/api/exhibits/:id/sections` +- `/api/exhibits/:exhibitId/sections/:sectionId` + +### Agent Operations (Admin) + +- `/api/agent/request-action` +- `/api/agent/status/:actionId` +- `/api/agent/approve/:actionId` +- `/api/agent/audit/:actionId` +- `/api/agent/kill-switch` +- `/api/agent/actions` +- `/api/agent/operations` +- `/api/agent/cancel/:actionId` +- `/api/agent/execute/:actionId` + +### Miscellaneous Operational Endpoints + +- `/api/heartbeat` (proactive governance health checks) +- `/api/llm` (primary LLM route) +- `/api/gemini` (deprecated compatibility route) + +## Integration Notes + +- Prefer the canonical domain-scoped routes (`/api/domains/:domainId/*`) for new integrations. +- Use JWT auth for MCP clients and reuse the session header for follow-up requests. +- Treat query-token MCP auth as deprecated and migrate to header-based auth. +- For public key verification across services, use Compass JWKS (`/api/.well-known/jwks.json`). ## Related Docs - [Ecosystem](/ecosystem) -- [Platform](/platform) (Stackbilder flow pipeline) +- [MCP Integration](/mcp) (StackBilt MCP server) +- [API Reference](/api-reference) (StackBilt platform API) diff --git a/src/content/docs/ecosystem.md b/src/content/docs/ecosystem.md index 8354136..5e094e4 100644 --- a/src/content/docs/ecosystem.md +++ b/src/content/docs/ecosystem.md @@ -9,29 +9,26 @@ tag: "01" # Ecosystem -Stackbilt is a unified developer platform with four complementary systems spanning the full development lifecycle — from stack selection to governed deployment. +StackBilt is three complementary tools that enforce governance across the full development lifecycle. -## The Four Pieces +## The Three Pieces | Tool | License | Role | |------|---------|------| -| **Charter** (`@stackbilt/cli`) | Apache-2.0 (open source) | Local + CI governance runtime, ADF context compiler, CLI gateway to the engine | -| **Stackbilder Engine** | Commercial | Deterministic tech stack builder — 52-primitive catalog, compatibility scoring, scaffold generation. Zero LLM. | -| **Stackbilder Platform** | Commercial | AI-powered architecture generation, 6-mode flow pipeline, structured artifacts | +| **Charter** (`@stackbilt/cli`) | Apache-2.0 (open source) | Local + CI governance runtime with ADF context compiler | +| **Stackbilder** | Commercial | Architecture generation, scaffold engine, structured artifacts | | **Compass** | Commercial | Governance policy brain, institutional memory, ADR ledger | -Charter is the open-source CLI. The engine, platform, and Compass are commercial services. +Charter is the open-source foundation. Stackbilder and Compass are commercial services. ## Service Map -| Service | URL / Worker | Purpose | +| Service | URL | Purpose | |---------|-----|---------| -| **Stackbilt Platform** | `stackbilt.dev` | Architecture generation, MCP server, flow pipeline | -| **Stackbilt Engine** | `stackbilt-engine` | Deterministic stack builder (52-card tech deck, compatibility matrix, scaffold templates) | -| **Compass** | via service binding | Governance enforcement, blessed patterns, ADR ledger | -| **Auth** | `auth.stackbilt.dev` | Centralized auth — API keys, JWT, SSO, Stripe billing, PAYG credit packs | -| **img-forge** | `imgforge.stackbilt.dev` | AI image generation API (multi-model, MCP + OAuth 2.1) | -| **AEGIS** | `aegis.stackbilt.dev` | Persistent cognitive agent — memory, goals, task pipeline, dreaming cycle | +| **StackBilt** | `stackbilt.dev` | Architecture generation, MCP server, scaffold engine | +| **Compass** | via Stackbilder service binding | Governance enforcement, blessed patterns, ADR ledger | +| **Auth Worker** | `auth-tenant-v2` | Authentication service (Better Auth + D1, OAuth, SSO) | +| **img-forge** | `imgforge.stackbilt.dev` | AI image generation for documentation | ## How They Fit Together @@ -39,23 +36,19 @@ Charter is the open-source CLI. The engine, platform, and Compass are commercial IDEA │ ▼ -Engine: build(description) → deterministic stack selection (zero LLM) - │ 52-primitive catalog, compatibility scoring, scaffold template - │ - ▼ Compass: governance("Can we build X?") │ ├── REJECTED ──► Stop │ ▼ APPROVED -Platform: runFullFlowAsync(idea + engine stack) +Stackbilder: runFullFlowAsync(idea) → PRODUCT → UX → RISK → ARCHITECT → TDD → SPRINT │ ▼ Compass: red_team(architecture) → security review │ ▼ -Platform: getFlowScaffold(flowId) → deployable project +Stackbilder: getFlowScaffold(flowId) → deployable project │ ▼ Charter: validate + drift → commit and stack compliance @@ -79,7 +72,6 @@ npx charter adf init # scaffold .ai/ context directory **Governance commands:** `validate`, `drift`, `audit`, `classify`, `hook install`. **ADF commands:** `adf init`, `adf fmt`, `adf patch`, `adf bundle`, `adf sync`, `adf evidence`. -**Engine commands:** `login`, `architect`, `scaffold` — generate and write tech stacks via the Stackbilder Engine. For quantitative analysis of ADF's impact on autonomous system architecture, see the [Context-as-Code white paper](https://github.com/stackbilt-dev/charter-kit/blob/main/papers/context-as-code-v1.1.md). @@ -171,7 +163,7 @@ For automated pipelines, each service has its own token: ```json { - "stackbilder": { "url": "https://stackbilt.dev/mcp", "token": "STACKBILDER_MCP_TOKEN" }, + "edgestack": { "url": "https://stackbilt.dev/mcp", "token": "EDGESTACK_MCP_TOKEN" }, "compass": { "url": "https://stackbilt.dev/mcp", "transport": "service_binding", "token": "CSA_MCP_TOKEN" }, "imgforge": { "url": "https://imgforge.stackbilt.dev/mcp", "token": "IMGFORGE_MCP_TOKEN" } } diff --git a/src/content/docs/getting-started.md b/src/content/docs/getting-started.md index 0ad1fdd..fcd5794 100644 --- a/src/content/docs/getting-started.md +++ b/src/content/docs/getting-started.md @@ -7,367 +7,102 @@ color: "#2ea043" tag: "02" --- -# Charter Kit +# Getting Started -[![npm version](https://img.shields.io/npm/v/@stackbilt/cli?label=charter&color=5F7FFF&style=for-the-badge)](https://www.npmjs.com/package/@stackbilt/cli) +Charter is a local-first governance toolkit with a built-in AI context compiler. It validates commit governance, detects stack drift, scores risk, and ships **ADF (Attention-Directed Format)** — a modular, AST-backed context system that replaces monolithic `.cursorrules` and `claude.md` files. Everything runs locally and in CI, with no SaaS dependency. +## Install - -## The Problem - -You write a CLAUDE.md. You add a `.cursorrules`. You paste instructions into GEMINI.md. Your AI agent loads all of it into the context window -- 10,000 tokens of flat, unstructured rules competing with the actual work. - -Half get ignored. You don't know which half. - -## The Solution - -Charter is an open-source CLI that replaces monolithic agent config files with **ADF (Attention-Directed Format)** -- a modular context system where agents load only the rules they need for the current task. - -Instead of one big file, you get a manifest. The manifest declares modules, trigger keywords that load them on demand, token budgets, and weighted sections that tell the agent what's load-bearing vs. advisory. +Recommended: local dev dependency per repo. ```bash npm install --save-dev @stackbilt/cli -npx charter bootstrap --yes # detect stack, scaffold .ai/, migrate existing rules ``` -## Five-Minute Adoption - -Already have agent config files? Charter migrates them: +pnpm workspace root: ```bash -# See what would happen (dry run) -charter adf migrate --dry-run - -# Migrate: classifies rules by strength, routes to ADF modules, replaces originals with thin pointers -charter adf migrate -``` - -Your `CLAUDE.md` / `.cursorrules` / `GEMINI.md` content gets classified (imperative vs. advisory vs. neutral), routed to the right module (frontend rules to `frontend.adf`, backend rules to `backend.adf`), and your originals become one-line pointers to `.ai/`. No content lost, no rewrite needed. - -## How ADF Works - -Charter manages context through the `.ai/` directory: - -```text -.ai/ - manifest.adf # Module registry: default-load vs on-demand with trigger keywords - core.adf # Always-loaded: role, constraints, output format, metric ceilings - state.adf # Session state: current task, decisions, blockers - frontend.adf # On-demand: loaded when task mentions "react", "css", etc. - backend.adf # On-demand: loaded when task mentions "endpoint", "REST", etc. +pnpm add -Dw @stackbilt/cli ``` -When you run `charter adf bundle --task "Fix the React login component"`, Charter: -1. Reads the manifest -2. Loads `core.adf` and `state.adf` (always loaded) -3. Sees "React" matches a trigger keyword -- loads `frontend.adf` -4. Skips `backend.adf` (no matching triggers) -5. Merges the loaded modules into a single context payload with token budget tracking +Global (optional, puts `charter` on your PATH): -The agent gets exactly the rules it needs. Nothing more. - -### Format Example - -```text -ADF: 0.1 - -TASK: - Build the user dashboard - -CONTEXT: - - React 18 with TypeScript - - TailwindCSS for styling - - REST API at /api/v2 - -CONSTRAINTS [load-bearing]: - - No external state libraries - - Must support SSR - -METRICS [load-bearing]: - entry_loc: 142 / 500 [lines] - handler_loc: 88 / 300 [lines] - -STATE: - CURRENT: Implementing layout grid - NEXT: Add data fetching - BLOCKED: Waiting on API schema +```bash +npm install -g @stackbilt/cli ``` -Sections use emoji decorations for attention signaling, support four content types (text, list, key-value map, and metric with value/ceiling/unit), and follow a canonical ordering the formatter enforces. `[load-bearing]` vs `[advisory]` weight annotations distinguish measurable constraints from preferences. Metric entries (`key: value / ceiling [unit]`) define hard ceilings that the `evidence` command validates automatically. +## Bootstrap a Repo -## Self-Governance: Charter Enforces Its Own Rules - -This isn't theoretical. Charter uses ADF to govern its own codebase. The `.ai/` directory in this repository contains the same modules and metric ceilings that any adopting repo would use. - -Every commit runs through a pre-commit hook that executes `charter adf evidence --auto-measure`. If a source file exceeds its declared LOC ceiling, the commit is rejected. We can't ship code that violates our own governance rules -- even by accident, even at 2am. +```bash +# Preview what charter detects — no files written +npx charter setup --detect-only --format json -Here is the actual output from Charter's own evidence check (v0.7.0): +# Write governance baseline + optional CI workflow +npx charter setup --ci github --yes -```text - ADF Evidence Report - =================== - Modules loaded: core.adf, state.adf - Token estimate: ~494 - Token budget: 4000 (12%) - - Auto-measured: - adf_commands_loc: 618 lines (packages/cli/src/commands/adf.ts) - adf_bundle_loc: 175 lines (packages/cli/src/commands/adf-bundle.ts) - adf_sync_loc: 213 lines (packages/cli/src/commands/adf-sync.ts) - adf_evidence_loc: 272 lines (packages/cli/src/commands/adf-evidence.ts) - adf_migrate_loc: 474 lines (packages/cli/src/commands/adf-migrate.ts) - bundler_loc: 125 lines (packages/adf/src/bundler.ts) - parser_loc: 214 lines (packages/adf/src/parser.ts) - cli_entry_loc: 191 lines (packages/cli/src/index.ts) - - Constraints: - [ok] adf_commands_loc: 618 / 650 [lines] -- PASS - [ok] adf_bundle_loc: 175 / 200 [lines] -- PASS - [ok] adf_sync_loc: 213 / 250 [lines] -- PASS - [ok] adf_evidence_loc: 272 / 380 [lines] -- PASS - [ok] adf_migrate_loc: 474 / 500 [lines] -- PASS - [ok] bundler_loc: 125 / 500 [lines] -- PASS - [ok] parser_loc: 214 / 300 [lines] -- PASS - [ok] cli_entry_loc: 191 / 200 [lines] -- PASS - - Verdict: PASS +# Mixed repos (frontend + backend): choose preset explicitly +npx charter setup --detect-only +npx charter setup --preset fullstack --ci github --yes ``` -What this shows: +`setup` writes: +- `.charter/config.json` — governance baseline config +- `.charter/patterns/*.json` — blessed-stack pattern definitions +- `.charter/policies/*.md` — human-readable policy summary +- `.github/workflows/charter-governance.yml` — CI workflow (if `--ci github`) -- **Metric ceilings enforce LOC limits on source files.** Each metric in a `.adf` module declares a ceiling. `--auto-measure` counts lines live from the sources referenced in the manifest. -- **Self-correcting architecture.** When `bundler_loc` hit 413/500, Charter's own evidence gate flagged the pressure. The file was split into three focused modules (`manifest.ts`, `merger.ts`, `bundler.ts`) -- now 125/500. The system caught the problem and the system verified the fix. -- **CI gating.** Generated governance workflows run `doctor --adf-only --ci` and `adf evidence --auto-measure --ci` on every PR, blocking merges on ceiling breaches. -- **Available to any repo.** This is the same system you get by running `charter adf init` in your own project. +## Set Up ADF Context -## Quick Reference +ADF turns your LLM context into a compiled, modular system. Scaffold the `.ai/` directory: ```bash -# Scaffold .ai/ with starter modules -charter adf init - -# Reformat to canonical form -charter adf fmt .ai/core.adf --write - -# Apply a typed patch -charter adf patch .ai/state.adf --ops '[{"op":"ADD_BULLET","section":"STATE","value":"Reviewing PR #42"}]' - -# Bundle context for a task (trigger-based module loading) -charter adf bundle --task "Fix the React login component" - -# Migrate existing agent configs into ADF -charter adf migrate --dry-run +# Scaffold .ai/ with manifest, core, and state modules +npx charter adf init -# Verify .adf files haven't drifted from locked hashes -charter adf sync --check - -# Validate metric constraints -charter adf evidence --auto-measure - -# Recalibrate metric ceilings -charter adf metrics recalibrate --headroom 15 --reason "Scope expansion" --dry-run - -# Expose ADF context as an MCP server (for Claude Code / any MCP client) -charter serve +# Verify everything parses and syncs +npx charter doctor --format json ``` -## Why Charter +This creates (for default presets): -- **Modular AI context** -- trigger-routed `.ai/` modules replace monolithic config files -- **Five-minute migration** -- classify and route existing CLAUDE.md / .cursorrules / GEMINI.md rules automatically -- **MCP server** -- `charter serve` exposes your ADF context as an MCP server; Claude Code can query constraints, architectural decisions, and recent changes without reading raw files -- **Evidence-based governance** -- metric ceilings with auto-measurement, structured pass/fail reports, CI gating -- **Self-regulating** -- pre-commit hooks enforce constraints before code lands -- **Commit governance** -- validate `Governed-By` and `Resolves-Request` trailers, score commit risk -- **Drift detection** -- scan for stack drift against blessed patterns -- **Stable JSON output** -- every command supports `--format json` with `nextActions` hints for agent workflows - -## Install - -```bash -npm install --save-dev @stackbilt/cli +```text +.ai/ + manifest.adf # Module registry: default-load vs on-demand with triggers + core.adf # Always-loaded: role, constraints, metric ceilings + state.adf # Session state: current task, decisions, blockers + frontend.adf # Frontend module scaffold (on-demand, triggers: React, CSS, UI) + backend.adf # Backend module scaffold (on-demand, triggers: API, Node, DB) ``` -For pnpm workspaces: `pnpm add -Dw @stackbilt/cli`. For global install: `npm install -g @stackbilt/cli`. +For documentation-heavy repos, use `--preset docs` to get `decisions.adf` and `planning.adf` instead of frontend/backend modules. -## Getting Started +Edit `.ai/core.adf` to define your project constraints and LOC ceilings. The `METRICS [load-bearing]` section enforces hard limits that CI can gate on. -### Human Workflow +## Verify the Setup ```bash -charter # Repo risk/value snapshot -charter bootstrap --ci github # One-command onboarding -charter doctor # Validate environment/config -charter validate # Check commit governance -charter drift # Scan for stack drift -charter audit # Governance summary -charter adf init # Scaffold .ai/ context directory +npx charter doctor --format json +npx charter ``` -### Claude Code Integration (MCP) - -`charter serve` exposes your `.ai/` modules as an MCP server. Add it to `.claude/settings.json`: - -```json -{ - "mcpServers": { - "charter": { - "command": "charter", - "args": ["serve"] - } - } -} -``` +`charter` with no arguments prints a live governance snapshot: risk score, governed commit ratio, drift status. -Claude Code can then call `getProjectContext`, `getArchitecturalDecisions`, `getProjectState`, and `getRecentChanges` directly — no manual `adf bundle` needed in the conversation. +`doctor` validates environment health including ADF readiness: manifest existence, module parse status, and sync lock integrity. -### Agent Workflow +## Run an Evidence Check -Prefer JSON mode and exit-code handling: +If you have ADF set up with metric ceilings, run the evidence pipeline: ```bash -charter --format json -charter setup --ci github --yes --format json -charter doctor --format json -charter validate --format json --ci -charter drift --format json --ci -charter audit --format json -charter adf bundle --task "describe the task" --format json -charter adf evidence --auto-measure --format json --ci -charter adf sync --check --format json -``` +# Validate all metric ceilings and produce a structured report +npx charter adf evidence --auto-measure -Agent contract: -- Inputs: git repo + optional existing `.charter/` -- Stable machine output: `--format json` with `nextActions` hints where applicable -- Exit codes: `0` success, `1` policy violation, `2` runtime/usage error -- CI behavior: with `--ci`, treat `1` as gating failure and surface actionable remediation -- Evidence: `adf evidence --ci` exits 1 on metric ceiling breaches; warnings (at boundary) don't fail - -
-Trailer Adoption Ramp - -Teams often score lower early due to missing governance trailers. Use this ramp: -- Stage 1: run `charter validate --ci --format json` in PR CI and fail on policy violations. -- Stage 2: add a commit template in the repo that includes `Governed-By` and `Resolves-Request`. -- Stage 3: track audit trend; trailer coverage should rise naturally as PR gating normalizes behavior. - -
- -## Cross-Platform Support - -Charter works across WSL, PowerShell, CMD, macOS, and Linux. All git operations use a unified invocation layer with cross-platform PATH resolution. Line endings are normalized via `.gitattributes`. - -## Command Reference - -- `charter`: show repo risk/value snapshot and recommended next action -- `charter bootstrap [--ci github] [--preset ] [--yes] [--skip-install] [--skip-doctor]`: one-command onboarding (detect + setup + ADF + migrate + install + doctor) -- `charter setup [--ci github] [--preset ] [--detect-only] [--no-dependency-sync]`: detect stack and scaffold `.charter/` baseline -- `charter init [--preset ]`: scaffold `.charter/` templates only -- `charter doctor [--adf-only]`: validate environment/config state (`--adf-only` runs strict ADF wiring checks) -- `charter validate [--ci] [--range ]`: validate commit governance and citations -- `charter drift [--path ] [--ci]`: run drift scan -- `charter audit [--ci] [--range ]`: produce governance audit summary -- `charter classify `: classify change scope heuristically -- `charter hook install --commit-msg [--force]`: install commit-msg trailer normalization hook -- `charter hook install --pre-commit [--force]`: install pre-commit ADF routing + evidence gate -- `charter adf init [--ai-dir ] [--force]`: scaffold `.ai/` context directory -- `charter adf fmt [--check] [--write]`: parse and reformat ADF files to canonical form -- `charter adf fmt --explain`: show canonical formatter section ordering -- `charter adf patch --ops | --ops-file `: apply typed delta operations -- `charter adf create [--triggers "a,b,c"] [--load default|on-demand]`: create and register a module -- `charter adf bundle --task "" [--ai-dir ]`: resolve manifest and output merged context -- `charter adf sync --check [--ai-dir ]`: verify .adf files match locked hashes -- `charter adf sync --write [--ai-dir ]`: update `.adf.lock` with current hashes -- `charter adf evidence [--task ""] [--ai-dir ] [--auto-measure] [--context '{"k":v}'] [--context-file ]`: validate metric constraints and produce evidence report -- `charter adf metrics recalibrate [--headroom ] [--reason ""|--auto-rationale] [--dry-run]`: recalibrate metric baselines/ceilings -- `charter adf migrate [--dry-run] [--source ] [--no-backup] [--merge-strategy append|dedupe|replace]`: migrate existing agent config files into ADF modules -- `charter serve [--name ] [--ai-dir ]`: start an MCP server (stdio) exposing ADF context as tools and resources for Claude Code and other MCP clients -- `charter telemetry report [--period <30m|24h|7d>]`: summarize local CLI telemetry -- `charter why`: explain adoption rationale and expected payoff - -Global options: `--config `, `--format text|json`, `--ci`, `--yes`. - -## Exit Code Contract - -- `0`: success/pass -- `1`: policy violation in CI mode -- `2`: runtime/config/usage error - -## CI Integration - -- Reusable template: `.github/workflows/governance.yml` -- Generated in target repos by `charter setup --ci github`: `.github/workflows/charter-governance.yml` -- The governance workflow runs `validate`, `drift`, ADF wiring integrity (`doctor --adf-only --ci`), ADF ceiling evidence (`adf evidence --auto-measure --ci`), and `audit` on every PR. - -## Workspace Layout - -```text -packages/ - types/ Shared contracts - core/ Schemas, sanitization, errors - adf/ ADF parser, formatter, patcher, bundler, evidence pipeline - git/ Trailer parsing and risk scoring - classify/ Heuristic classification - validate/ Governance validation - drift/ Pattern drift scanning - cli/ `charter` command - ci/ GitHub Actions integration helpers +# CI mode: exits 1 if any ceiling is breached +npx charter adf evidence --auto-measure --ci --format json ``` -## Development - -- `pnpm run clean` -- `pnpm run typecheck` -- `pnpm run build` -- `pnpm run test` - -## SemVer and Stability Policy - -Charter uses [Semantic Versioning](https://semver.org/) for this repository and for published `@stackbilt/*` packages. - -Until `1.0.0`, Charter may still evolve quickly, but breaking changes should remain exceptional, deliberate, and clearly documented. The goal of `1.0.0` is simple: a connected coding agent or developer can rely on Charter's machine-facing contracts without source archaeology. - -The following surfaces are semver-governed: - -- **Package APIs** -- exported functions, classes, and types from published `@stackbilt/*` packages -- **CLI behavior** -- command names, flags, exit codes, and machine-readable `--format json` output -- **ADF behavior** -- parse, format, patch, bundle, sync, and evidence semantics -- **Generated artifacts** -- thin pointer files, `.ai/manifest.adf`, `.adf.lock`, and related scaffolded outputs -- **Governance schemas** -- evidence, audit, drift, doctor, and scorecard JSON envelopes - -Versioning rules: - -- **PATCH** -- bug fixes, docs, internal refactors, and non-breaking UX improvements -- **MINOR** -- additive commands, flags, fields, modules, templates, and advisory checks that do not break existing consumers -- **MAJOR** -- incompatible changes to CLI contracts, JSON schemas, ADF semantics, generated artifact conventions, or other machine-facing behavior that agents may rely on - -For agent-facing workflows, schema stability is treated as a core product promise, not a nice-to-have. - -## Research & White Papers - -The [`papers/`](./papers/) directory contains Charter's research narrative: - -| Entry Point | Purpose | -|---|---| -| [Papers Index](./papers/README.md) | Research papers, UX feedback, and release planning docs | -| [UX Feedback Index](./papers/ux-feedback/README.md) | Journey-bucketed ADX findings | -| [Release Plans Index](./papers/releases/README.md) | Versioned plans mapping feedback to implementation | -| [`@stackbilt/adf` API](./packages/adf/README.md) | Full ADF package API documentation | - -## Release Docs - -- `PUBLISHING.md`: first release/publish workflow -- `CHANGELOG.md`: user-visible change history -- `CONTRIBUTING.md`: contribution conventions -- `SECURITY.md`: vulnerability reporting - -## License - -Apache-2.0. See [LICENSE](./LICENSE). +## What's Next -

- - Buy me a coffee - -

+- [CLI Reference](/cli-reference) — full command surface +- [CI Integration](/ci-integration) — GitHub Actions workflow with evidence gating +- [Ecosystem](/ecosystem) — how Charter fits into the StackBilt platform