@stackbilt/cli
v0.10.0
Published
Charter CLI — repo-level governance checks + architecture scaffolding
Readme
@stackbilt/cli
CLI entry point for Charter Kit -- a local-first governance toolkit for software repositories. Orchestrates all other @stackbilt/* packages to parse commit trailers, score risk, detect blessed-stack drift, and classify change scope. No LLM calls at runtime.
This is the only package most users need. One install gives you the full Charter Kit toolkit.
Install (Recommended)
npm install --save-dev @stackbilt/cliIf using a pnpm workspace root:
pnpm add -Dw @stackbilt/cliUse with npx in each repository:
npx charter
npx charter setup --detect-only --format json
npx charter setup --ci github --yes
npx charter doctor --format json
npx charter validate --ci --format json
npx charter drift --ci --format json
npx charter audit --format jsonGlobal install is optional if you want charter available system-wide:
npm install -g @stackbilt/cliThis pulls in all Charter Kit packages automatically. Use charter setup inside each repo to scaffold governance baseline files.
Upgrade existing repos with:
npm install --save-dev @stackbilt/cli@latest
npx --no-install charter --versionFor CI pipelines, install as a dev dependency:
npm install --save-dev @stackbilt/cliRequires Node >= 18.
Quick Start
charter # quick value/risk snapshot + next action
charter why # why teams adopt Charter and expected payoff
charter setup # bootstrap .charter/ directory + policy baseline
charter doctor # check CLI + config health
charter validate # validate commit governance trailers
charter drift # scan for blessed-stack drift
charter audit # generate governance audit report
charter classify "migrate auth provider"
charter hook install --commit-msg
charter adf init # scaffold .ai/ context directory
charter adf fmt .ai/core.adf # reformat ADF to canonical form
charter adf bundle --task "fix React component"
charter adf migrate --dry-run # preview agent config → ADF migration
charter adf sync --check # verify .adf files match locked hashes
charter adf evidence --auto-measure --format json # validate metric ceilings
charter telemetry report --period 24h --format json # passive local usage summary
charter blast src/foo.ts --depth 3 # reverse dep graph → files affected by changing this seed
charter surface --markdown # extract routes (Hono/Express) + D1 schema as markdownHuman Onboarding (Copy/Paste)
Run this in the target repository:
npm install -g @stackbilt/cli
charter
charter setup --ci github
charter classify "describe the planned change"
charter doctor --format json
charter validate --format text
charter drift --format text
charter audit --format textThis ensures people immediately see:
- what Charter is doing in their repo
- where baseline files were created (
.charter/*) - how policy checks behave before merge
LM Agent Onboarding (Deterministic)
Use JSON output and explicit CI semantics:
charter --format json
charter setup --ci github --yes --format json
charter setup --ci github --yes --no-dependency-sync --format json
charter doctor --format json
charter validate --format json --ci
charter drift --format json --ci
charter audit --format jsonAgent handling contract:
exit 0: passexit 1: policy violation (action required)exit 2: runtime/usage failure
Agent decision rules:
- If
mixedStack: true, use--preset fullstack. - If framework signals look wrong, inspect
detected.sourcesand rerun setup with an explicit--preset. - Treat
validate --cianddrift --cias blocking checks. validateandauditboth report commit range explicitly so coverage numbers are comparable.- Use
validate.evidence.policyOffendersfor strict-trailer failures andvalidate.evidence.riskOffendersfor threshold-based risk failures. policyOffendersare policy-context entries (not risk-rule findings); risk metadata is attached toriskOffenders.validate.effectiveRangeSourceandvalidate.defaultCommitRangemake implicit range behavior explicit for agents.
LM Agent Ops Flow
# install in target repo
npm install --save-dev @stackbilt/cli@latest
# setup
npx charter setup --detect-only --format json
npx charter setup --ci github --yes --format json
npx charter classify "describe the planned change" --format json
# enforce on PR/build
npx charter validate --ci --format json
npx charter drift --ci --format json
npx charter audit --format json
# ADF context management
npx charter adf migrate --dry-run --format json
npx charter adf evidence --auto-measure --format json --ci
npx charter adf sync --check --format json
npx charter telemetry report --period 24h --format json
# recurring maintenance
npx charter doctor --format json
npx charter audit --format jsonCommands
charter (no args)
Default first-run experience. Shows:
- repository governance baseline status
- commit governance coverage snapshot
- high-risk unlinked commit count
- one recommended next action
charter why
Explains the adoption case in plain terms (problem, what Charter enforces, expected operational payoff).
charter setup
Bootstrap .charter/ with config, patterns, and policies. Optionally generates a GitHub Actions workflow.
This is the command that applies Charter governance into a repository.
charter setup --ci github --yes
charter setup --detect-only
charter setup --preset frontendFor mixed repos (for example Worker backend + React frontend under client/), prefer:
charter setup --detect-only
charter setup --preset fullstack --ci github --yesDetection output includes detected.sources in JSON mode so agents can verify which manifests were scanned before applying a baseline.
Setup also adds optional root scripts when missing: charter:detect, charter:setup, verify:adf, charter:doctor, and charter:adf:bundle.
Setup JSON now includes mutationPlan and appliedMutations so side effects are explicit before/after apply.
Setup baseline mutation metadata now includes configHashBefore, configHashAfter, and writesPerformed.
charter init
Scaffold .charter/ config templates only. Supports --preset worker|frontend|backend|fullstack.
charter doctor
Validate CLI installation, .charter/ config, and ADF readiness (manifest existence, module parseability, sync lock status).
Use charter doctor --adf-only --ci for strict ADF wiring gates in automation.
charter validate
Validate git commits for Governed-By and Resolves-Request trailers.
charter validate --ci --format json
charter validate --range HEAD~10..HEAD --format jsonWhen --range is omitted, JSON includes effectiveRangeSource and defaultCommitRange so automation can trace default selection behavior.
Trailer formatting requirement:
- Governance trailers must be in one contiguous trailer block at the end of the commit message.
- A blank line inside the trailer section can make governance trailers unparsable by git trailer rules.
Valid:
feat: ship governance checks
Governed-By: ADR-012
Resolves-Request: REQ-078
Co-Authored-By: Dev <[email protected]>Invalid (blank line splits the trailer block):
feat: ship governance checks
Governed-By: ADR-012
Resolves-Request: REQ-078
Co-Authored-By: Dev <[email protected]>charter drift
Scan files against blessed-stack patterns in .charter/patterns/*.json.
charter drift --path ./src --ciJSON output includes patternsCustomized when pattern files declare customization metadata.
charter audit
Generate a governance audit report covering trailers, risk, drift, and policy-section coverage quality.
Use --range <revset> to audit the same commit window used by validation in reviews.
If score is held down by trailer coverage, enforce validate --ci in PR checks and add commit-template guidance for required trailers.
Audit output includes whether preset pattern files are still uncustomized when metadata is present.
charter classify
Classify a change as SURFACE, LOCAL, or CROSS_CUTTING.
charter classify "update button color"charter hook
Install git hooks for commit-time governance ergonomics.
charter hook install --commit-msg
charter hook install --pre-commit--commit-msg: Install a commit-msg hook that normalizesGoverned-ByandResolves-Requesttrailers usinggit interpret-trailers.--pre-commit: Install a pre-commit hook that enforces ADF routing withcharter doctor --adf-only --ciand validates ceilings withcharter adf evidence --auto-measure --ci(orpnpm run verify:adfwhen that script exists). Only gates when.ai/manifest.adfexists — no-op otherwise.--force(or global--yes) allows overwrite when a non-Charter hook already exists.- Both flags can be passed together to install both hooks in one command.
charter adf
ADF (Attention-Directed Format) context management. Replaces monolithic .cursorrules/claude.md files with a modular, AST-backed .ai/ directory.
charter adf init [--ai-dir <dir>] [--force]
charter adf fmt <file> [--check] [--write]
charter adf patch <file> --ops '<json>' | --ops-file <path>
charter adf create <module> [--triggers "a,b,c"] [--load default|on-demand] [--ai-dir <dir>] [--force]
charter adf bundle --task "Fix React component" [--ai-dir <dir>]
charter adf sync --check [--ai-dir <dir>]
charter adf sync --write [--ai-dir <dir>]
charter adf evidence [--task "<prompt>"] [--ai-dir <dir>] [--auto-measure]
[--context '{"key": value}'] [--context-file <path>]
charter adf metrics recalibrate [--headroom <percent>] [--reason "<text>"|--auto-rationale] [--dry-run]
charter adf migrate [--dry-run] [--source <file>] [--no-backup]
[--merge-strategy append|dedupe|replace] [--ai-dir <dir>]init: Scaffold.ai/withmanifest.adf,core.adf,state.adf, and starterfrontend.adf/backend.adfon-demand module stubs. Core module includes a 500-line LOC guardrail metric by default.fmt: Parse and reformat to canonical ADF.--checkexits 1 if not canonical.--writereformats in place. Default prints to stdout.fmt --explain: Print canonical section ordering used by the formatter.patch: Apply typed delta operations (ADD_BULLET, REPLACE_BULLET, REMOVE_BULLET, ADD_SECTION, REPLACE_SECTION, REMOVE_SECTION, UPDATE_METRIC). Accepts--ops <json>inline or--ops-file <path>from a file.create: Create an ADF module file and register it inmanifest.adfunderDEFAULT_LOADorON_DEMANDin one command.bundle: Readmanifest.adf, resolve ON_DEMAND modules via keyword matching against the task, and output merged context with token estimate, trigger observability (matched keywords, load reasons), unmatched modules, and advisory-only warnings. Missing ON_DEMAND files are warnings in output (missingModulesin JSON), while missing DEFAULT_LOAD files still fail.sync --check: Verify source.adffiles match their locked hashes. Exits 1 if any source has drifted since last sync.sync --write: Update.adf.lockwith current source hashes.evidence: Validate all metric ceilings in the merged document and produce a structured pass/fail evidence report.--auto-measurecounts lines in files referenced by the manifest METRICS section.--contextor--context-fileinject external metric overrides that take precedence over auto-measured and document values. In--cimode, exits 1 on constraint failures (warnings don't fail). Also reports stale-baseline warnings (baseline vs current delta + recommended ceiling) when baseline values drift significantly. The governance workflow template runs this automatically on PRs when.ai/manifest.adfis present.metrics recalibrate: Re-measure current LOC from manifest metric sources, propose and apply new ceilings using configurable headroom, and append rationale records toBUDGET_RATIONALES. Requires explicit rationale (--reason) unless--auto-rationaleis used.migrate: Scan existing agent config files (CLAUDE.md, .cursorrules, agents.md, GEMINI.md, copilot-instructions.md), classify content using the ADX-002 decision tree, and migrate into ADF modules.--dry-runpreviews the migration plan without writing files.--source <file>targets a single file.--no-backupskips.pre-adf-migrate.bakcreation.--merge-strategycontrols deduplication:dedupe(default, skip items already in ADF),append(always add), orreplace. Environment-specific rules (WSL, PATH, credential helpers) are retained in the thin pointer.
charter blast
Compute the blast radius of a change: which files transitively depend on the given seed files? Builds a reverse dependency graph (TS/JS imports — handles ESM .js → .ts, tsconfig path aliases including extends chains, src/index.* fallback, cycles, comments) and BFS-traverses up to a configurable depth.
charter blast src/kernel/dispatch.ts # default depth 3
charter blast src/a.ts src/b.ts --depth 4 # multi-seed
charter blast src/foo.ts --format json # structured output
charter blast src/foo.ts --root ./packages/x # scan a subdirectoryReports:
affected— relative paths of transitively dependent fileshotFiles— top 20 most-imported files in the graph (architectural hubs)summary.totalAffected,summary.depthHistogram
Blast radius ≥20 files triggers a CROSS_CUTTING warning — a signal for governance gates to escalate the change. Pure heuristic, no LLM calls, zero runtime dependencies. Backed by @stackbilt/blast.
charter surface
Extract the API surface of a project: HTTP routes and database schema. Designed for Cloudflare Worker projects but works on any Node.js HTTP backend.
charter surface # text summary
charter surface --format json # machine-readable
charter surface --markdown # for .ai/surface.adf injection
charter surface --root ./packages/worker # scan a subdirectory
charter surface --schema db/schema.sql # explicit schema pathDetects:
- Routes — Hono, Express, itty-router via regex (requires
/path prefix; strips comments before scanning) - Schema — D1/SQLite
CREATE TABLEstatements with column flags (pk, unique, nullable, default)
Ignores __tests__/, *.test.*, *.spec.* to avoid false positives from test fixtures.
Use cases: breaking change detection (diff surfaces before/after a PR), auto-generated AI context maps, deploy pipeline gates, mission brief fingerprinting for autonomous task runners. Backed by @stackbilt/surface.
charter telemetry
Passive local observability for Charter/ADF usage. Every CLI run appends command metadata (timestamp, command path, flags, duration, exit code) to .charter/telemetry/events.ndjson.
charter telemetry report --period 24h
charter telemetry report --period 7d --format jsonreport: aggregates events over a time window (--periodsupportss|m|h|d, for example30m,24h,7d).- Privacy: command metadata only. No prompt body, source code, or file contents are captured.
Evidence Example (from Charter's own repo)
Charter uses its own ADF system for self-governance. Running evidence with auto-measurement:
charter adf evidence --auto-measure --format json --ciProduces constraint checks against live source file line counts:
{
"constraints": [
{ "metric": "adf_commands_loc", "value": 413, "ceiling": 500, "status": "pass", "source": "context" },
{ "metric": "adf_bundle_loc", "value": 154, "ceiling": 200, "status": "pass", "source": "context" },
{ "metric": "adf_sync_loc", "value": 204, "ceiling": 250, "status": "pass", "source": "context" },
{ "metric": "adf_evidence_loc", "value": 263, "ceiling": 300, "status": "pass", "source": "context" },
{ "metric": "adf_migrate_loc", "value": 453, "ceiling": 500, "status": "pass", "source": "context" },
{ "metric": "bundler_loc", "value": 415, "ceiling": 500, "status": "pass", "source": "context" },
{ "metric": "parser_loc", "value": 214, "ceiling": 300, "status": "pass", "source": "context" },
{ "metric": "cli_entry_loc", "value": 149, "ceiling": 200, "status": "pass", "source": "context" }
],
"allPassing": true,
"failCount": 0,
"nextActions": []
}source: "context" indicates values were auto-measured from source files (not from the document's static values). In --ci mode, exit code 1 is returned when any constraint fails.
Global Options
| Option | Description | Default |
|---|---|---|
| --config <path> | Path to .charter/ directory | .charter/ |
| --format <mode> | Output: text or json | text |
| --ci | CI mode: exit non-zero on WARN or FAIL | off |
| --yes | Auto-accept safe setup overwrites | off |
Setup-only options:
--preset <worker|frontend|backend|fullstack>: override auto-detected preset--detect-only: print stack detection result and selected preset without writing files--no-dependency-sync: skip rewritingdevDependencies["@stackbilt/cli"]during setup
Exit Codes
| Code | Meaning | |------|---------| | 0 | Success | | 1 | Policy violation (CI mode) | | 2 | Runtime or usage error |
Related Packages
@stackbilt/types-- shared enums and interfaces@stackbilt/core-- Zod schemas and sanitization helpers@stackbilt/git-- trailer parsing and commit risk assessment@stackbilt/classify-- heuristic change classification@stackbilt/drift-- blessed-stack pattern drift detection@stackbilt/validate-- citation validation and intent classification@stackbilt/adf-- ADF parser, formatter, patcher, and bundler@stackbilt/blast-- reverse dependency graph + blast radius analysis@stackbilt/surface-- API surface extraction (routes + D1 schema)@stackbilt/ci-- GitHub Actions integration helpers
License
Apache-2.0
