# @c4a/context-cli

Local knowledge workspace CLI for [c4a — Context For AI](https://github.com/context4ai/c4a).

`@c4a/context-cli` is the **CLI** package — the `context` executable plus its source-of-truth plugin templates. Plugin install trees are distributed separately through the [context4ai/context](https://github.com/context4ai/context) repo (Claude / Codex / Cursor / Vercel-style skills), generated by `bun run build:plugin` from `plugin/` source.

This package ships:

1. **`context` CLI** — a Node/Bun-compatible executable that captures documents, extracts code structure, and manages a local context workspace.
2. **`plugin/` source** — human-maintained command/skill/manifest sources that `scripts/build-plugin.ts` compiles into the four plugin install trees in the `context4ai/context` repo.

The split follows a simple rule: mechanical work is the CLI's job; synthesis work (knowledge alignment, compilation, knowledge-side drop cleanup) is the agent's job. The CLI never calls an LLM. Naming surfaces are deliberately separate: `/context:*` is a Claude slash command, Cursor exposes prefixed command entries such as `/context-align` / `/context-compile`, `Context: ...` / `context-*` is a public skill entry for skill-only agents, `context ...` is the CLI primitive, and `context:skill-*` is an internal procedure invoked by the workflow.

## Install

```bash
# 1. Install the CLI globally (required by every plugin path; `context` must be on PATH).
bun install -g @c4a/context-cli
context --version

# 2. Install the plugin for your editor.
# Claude Code:
claude /plugin marketplace add context4ai/context
claude /plugin install context@c4a

# Codex CLI:
codex marketplace add context4ai/context

# Cursor:
# Dashboard → Settings → Plugins → Import → https://github.com/context4ai/context

# Vercel-style skills (Windsurf / OpenCode / Cline / Copilot etc.):
npx skills add github:context4ai/context context-align
```

All four plugin paths point at the [context4ai/context](https://github.com/context4ai/context) repo (generated from this package's `plugin/` source). They are independent of the npm CLI — the CLI is a hard prerequisite the plugin commands call out to via `$PATH`.

When installed as a Claude Code plugin, the `postinstall` hook checks whether the `context` bin is already on PATH. If not, it prints the two commands you can run yourself (`bun install -g @c4a/context-cli` for registry installs, or `bun link` for a local build). It never spawns an install on your behalf — that would silently substitute a registry build for a local tarball / file: / github: plugin install.

For local checkout development, link installs, or branch-specific plugin testing, see [DEVELOPMENT.md](./DEVELOPMENT.md).

## Quick tour

```bash
# Initialize a workspace in the current project
context init my-product --with-all-aspects

# Dedicated knowledge repo: use the current directory as the data root
context init my-kb --layout root --language English --minimal

# Start without aspects; append them later when needed
context init my-kb --no-aspects
context init --with-aspects code,openapi

# Capture material as sources (CLI does the ingestion)
context capture https://example.feishu.cn/docx/<token>
context capture ./docs/design.md
context capture --inbox
context capture --code packages/extract --plan --format json
context capture --code --module packages/extract --version-from package
context capture --code          # refresh existing code capture config
context compile code <source-slug>
context compile close

# In Claude Code, align → compile → drop are agent-driven
/context:align                   # agent classifies raw into a Node tree; user confirms
/context:compile                 # agent writes Section-level actions for each Node; CLI renders
/context:query "page perf 工具有哪些?"   # answer with cited Node/Section evidence (BM25 + structure, no RAG)
/context:drop feishu:doc:xxx --reason "obsolete"
/context:status
```

## Production Agent Contract

For production Agent workflows, `context` is a semantic service. A local path is valid when it is the external capture input (`context capture ./docs/design.md`) or another user-supplied source target. Agent-authored workflow payloads use stdin plus CLI-owned payload handles, not scratch files. After capture succeeds, continue with the returned `source_id`, `block_id`, `source_ref`, `node_slug`, Section id, workflow payload name, scope id, digest, or query text.

Workspace language is also part of the Agent contract. `config.yaml` can set `workspace.language` or `defaults.compile_language`; align and compile expose this as `generation_policy` in `align-segments` and NodeContext. Agents should generate Node titles, summaries, Section prose, and user-facing reports in that language while preserving product names, code identifiers, flags, slugs, `source_ref` values, and exact quoted evidence.

Do not treat the workspace storage tree as the protocol. Agent-facing workflows should not read, list, grep, cat, or derive state from `.context/**`, `raw/**`, `knowledge/**`, `output/**`, archives, cache roots, or rendered Markdown files. Use `context workflow status/show` for workflow payloads, `context source ...` for source metadata, `context mdrive ...` and `context query` for knowledge, and `context status` / `context doctor` / `context verify` for semantic diagnostics.

Agent-facing output should be stable by construction: shared protocol/schema/lookup context comes before task-specific objects, JSON key order is deterministic, and default output does not add current timestamps, random ids, storage paths, or host absolute paths. Existing knowledge is the registry. Use `context mdrive glossary list|match`, `context mdrive node list`, and `context query` to reuse term/service/system/action/domain handles; do not create or read a separate dynamic registry file.

`source_ref` is an opaque citation token. Copy it into citations and decisions exactly as printed; do not parse it or dereference it as a file path. Human/report views may show clickable files for user inspection. Developer/debug-only `context debug ...` commands may expose storage paths for diagnostics, but those values are not production Agent workflow inputs.

Code knowledge uses a code-first route. `context capture --code` records a raw code snapshot; `context compile code <source-slug>` materializes it into package/category/symbol Nodes such as `pkg`, `pkg/components`, and `pkg/symbol/button`. Package roots and category files are navigation surfaces, while concrete symbol Nodes carry code-owned Sections and can later retain doc-owned examples or manual notes. Agents should address these Nodes by slug and query metadata (`source_id`, `source_type`, `evidence_kind`, `source_ref`, `code_projection_status`) rather than by source file paths.

## Developer Storage Layout

The following tree describes the CLI-owned storage implementation for developers and operators. It is not the production Agent workflow contract.

Embedded layout (default):

```
.context/
├── config.yaml                  # workspace name, schema version, aspects
├── raw/                         # immutable captured source bodies (CLI-owned; metadata lives in _sources.yaml)
│   ├── _sources.yaml            # authoritative source registry
│   ├── feishu/<date>-<slug>…md
│   ├── local/<date>-<slug>…md
│   └── aspect/code/<source-slug>/<snapshot-id>/
├── output/                      # workflow scratch only; root contains directories, not files
│   ├── align/                   # align proposal/review/debug scratch
│   ├── compile/                 # compile context/draft/prepare/review scratch
│   ├── drop/                    # drop plan/prepare/review scratch
│   └── archive/                 # archived workflow scratch
├── .cache/                      # ignored internal cache, including current align binding
├── knowledge/                   # synthesized articles (CLI-rendered, agent-directed)
│   ├── _index.md                # workspace index (derivable, rebuilt by compile close)
│   ├── changelog.md             # append-only compile / drop log (derivable from git)
│   ├── domain/ entity/ action/   # one directory per Node type
├── archive/                     # dropped but restorable raw / knowledge artifacts
└── aspects/<name>/README.md     # per-aspect maintainer guides
```

Root layout (`context init --layout root`) uses the same tree directly in the current directory: `config.yaml`, `raw/`, `output/`, `knowledge/`, `archive/`, `aspects/`, and `inbox/` live at repo root. Root layout is intended for dedicated knowledge repositories; initialization refuses to run if those C4A-owned entries already exist.

`context init` also creates `AGENTS.md` inside the C4A data root (`.context/` in embedded layout, current directory in root layout) and, when absent, a same-directory `CLAUDE.md` symlink pointing to `AGENTS.md`. Existing files are kept.

Data model: Node (`domain` / `entity` / `action`) + Section (ten kinds, mounted by node type) + derived traversal edges. Named concept-layer subjects are modeled as `entity` nodes with the `term` tag when their core content is a stable 1-3 sentence definition. Routing schemes, durable rules, data-shape descriptions, procedures, and design choices live inside the matching domain/entity/action Sections such as `spec`, `principle`, `decision`, `comparison`, or `warning`. `mdrive node list` and `mdrive query` expose a `node_class` (`domain`, `action`, `concrete_entity`, `term`) so glossary-style terms stay visible without flattening them into concrete services/systems.

## Commands

Workflow payload exploration uses a single Agent-facing query protocol:

- `--view` selects the semantic view, such as `source-refs`, `coverage-summary`, `coverage`, or `blocks`.
- `--token-budget <n>` controls the returned context window size. Budgeted views report `token_budget`, `token_used`, `shown_count`, `total`, `omitted_count`, `truncated`, `selection_policy`, `item_id_field`, and `how_to_explore[]`.
- `--source`, `--heading`, `--node`, `--type`, `--status`, `--candidate-id`, and `--item-id` only narrow a view. Agents should follow `how_to_explore[]` when `truncated: true` instead of piping JSON through shell tools or manually slicing payloads.
- Citation-eligible entries appear in `items[]`; background-only entries appear in `context_items[]` when budget allows, with `context_omitted_count` reporting omitted background.

| Command | Role | Notes |
|---|---|---|
| `context init [name]` | CLI | Create or append an embedded `.context/` workspace or a root-layout workspace; copy aspect templates and write `AGENTS.md`. |
| `context capture <url \| ./path.md [./more.md...] \| --stdin \| --inbox \| --refresh \| --code [path]>` | CLI | Ingest external documents or code into the source registry. Feishu URLs use `lark-cli`; local `.md` files can be captured one at a time, as variadic paths, or as newline-separated paths from stdin. `--code` snapshots TypeScript packages/symbols/edges through the code aspect. For Agent interaction, run `context capture --code <path> --plan --format json` first, show only package name / module path / version, then capture with repeated `--module <path>`. After capture, continue with source ids and semantic handles, not storage paths. |
| `context extract <path>` | CLI | Read-only developer/debug print of an extraction; never writes workspace files and is not part of the production Agent workflow. |
| `context debug <workflow\|source\|workspace\|storage\|command\|snapshot> ...` | CLI | Developer/debug-only path diagnostics. Output is storage-coupled and not a production Agent workflow input. |
| `context align scan \| coarse-read --input - \| ops --input - \| validate --input - \| finalize --validated \| finalize --input - \| code [slug]` | CLI | Workflow helpers driven by the `/context:align` skill pipeline. `scan` returns workflow payload names, scopes, digests, route envelope, and budget-safe inspect commands; agents inspect `align-segments` through `context workflow show --payload align-segments --view blocks --token-budget 2000 --unwrap --format json`, then narrow with `--source`, `--heading`, or CLI-provided `how_to_explore[]`. `--unwrap` only removes the workflow metadata envelope. Validate before finalize; successful validate stores an `align-validated-decision` payload and returns the preferred `context align finalize --validated --payload-digest <digest>` command. `finalize --input -` remains for compatibility and advanced repair. Batched `coarse-read` / `ops` are only used when `next_action.command` asks for them. `code` is a dry-run deterministic code projection route and does not enter prose align. `context schema <name>` prints the exact align workflow input schemas. |
| `context compile scan \| context <slug> [--view source-refs] \| cycle <slug> --input - --accept-safe-defaults \| draft <slug> --input - --prepare \| close \| code [source-slug]` | CLI | `code` is the deterministic code projection route: it turns captured code snapshots into package/category/symbol knowledge Nodes and does not enter prose draft/reconcile. Workflow helpers driven by the `/context:compile` skill pipeline handle prose/doc knowledge. `scan` returns the incremental compile workset, resume point, and budget-safe source-ref prefetch commands. `context <slug> --view source-refs --token-budget 2000` is a budgeted projection of `NodeContext.raw_snippets[]` for copying citation handles into draft `source_refs[]`; it is not a separate data source. Coverage payloads are inspected with `context workflow show --payload coverage-candidates --view coverage-summary --token-budget 2000 --unwrap --format json` and narrowed with `--view coverage --type <issue-type>` or `--node <slug>`. `cycle <slug>` is the low-friction per-node path: it validates the submitted draft, prepares reconcile, accepts mechanically safe defaults, and applies only when no semantic judgment remains (`status: applied` / `partial-applied` / `review-required`). Manual `draft <slug> --prepare → reconcile review/apply` remains the fallback for questions and unsupported evidence. `--delegated` is a one-time, workflow-level authorization recorded on the initial scan/context/draft/cycle command; it lets the CLI auto-accept low-risk weak source support but never bypasses unsupported evidence, type drift, schema errors, or destructive gates. Normal handoff uses stdin and current workflow payloads; digest flags are optional stale guards, not values agents need to extract. `--save-input` is only an explicit debug scratch copy, not workspace truth. |
| `context workflow show --payload <name> --view <view> [--token-budget <n>]` | CLI | Inspect workflow payloads through semantic views. High-frequency views are `node-context --view source-refs`, `coverage-candidates --view coverage-summary`, `coverage-candidates --view coverage`, and `align-segments --view blocks`. Follow returned `how_to_explore[]` commands for narrowing or budget expansion. |
| `context mdrive <group> <verb>` | CLI | Knowledge primitive shell: node / section / edge / query / verify / glossary / workspace. Node/query results include `node_class` to distinguish concrete entities from term definitions. `context mdrive verify workspace --experimental` adds heuristic quality warnings for very thin concrete entities and terms that have grown beyond definition shape; these are warnings, not entity-count limits. `context mdrive query --stats-only` prints only workspace counts; run `context mdrive --help` for subcommands. |
| `context drop <source-id\|url> --plan [--save-output [file]]` / `context drop --apply-plan --reason <text> --yes` | CLI | Plans and applies source retraction through the current drop workflow. `drop --plan` stores the canonical `drop-plan` workflow payload; `--save-output` is only an optional human-readable scratch copy, not a later input. `reconcile prepare --mode drop` reads the current workflow plan, `reconcile review --decisions -` stores the ready review when semantic decisions are needed, and `drop --apply-plan` consumes the current workflow plan/review without plan or decisions files. |
| `context purge [--yes]` | CLI | Permanently deletes every archive under `archive/` after a summary + confirmation; active `raw/` and `knowledge/` are not modified. |
| `context verify` | CLI | Whole-workspace verify (schema, Section mount matrix, contains acyclicity, dropped-source references, dangling `src-N`, body ad-hoc headings, domain-inline-child, duplicate slug). |
| `context doctor` | CLI | Workspace diagnostics for current workflow, align output, knowledge, caches, evidence, coverage, semantic ledger, and archive state. |
| `context status [--format json\|table]` | CLI | Workspace overview + next-action suggestions. |
| `context query "<question>" [--intent <intent>] [--scope <slug>] [--evidence code\|prose\|all] [--tag <tag>] [--domain <slug>]` | CLI | Local knowledge query with hit/miss/select protocol. Intents: `orientation` (workspace map, supports `--tag` / `--domain` filters and a token-budgeted Slug Map + Summary), `node_lookup` (BM25 candidate Nodes from query text), `node_view` (open a known Node by slug), `section_search` (BM25 inside a chosen Node), `impact_analysis` (structural relations), `recall` (archive / reconciliation audit). Code package/category scopes search their contains subtree; concrete symbol scopes can return both code-owned and doc-owned Sections. JSON hits expose `source_id`, `source_type`, `evidence_kind`, `source_ref`, and code projection metadata when present. Without `--intent`, the CLI infers from the flags supplied. BM25 only — no vector embeddings. |
| `/context:query <question>`, `/context:align`, `/context:compile`, `/context:capture`, `/context:drop`, `/context:status`, `/context:purge` | Agent | Skill-driven wrappers around the CLI. Read flows (`query`, `status`) answer directly with cited evidence; write flows (`align`, `compile`, `capture`, `drop`, `purge`) produce structured JSON/YAML per skill contract and confirm destructive steps with the user. |
| `/context:context <free text>` | Agent | Fuzzy router over the above. |

CLI commands that require a workspace exit with a workspace-not-found error if run outside a directory tree containing either embedded `.context/` layout or root layout; `context init` is the only command that creates one.

## Development

Source lives at [`packages/context-cli/`](./src) in the c4a monorepo.

```bash
bun run --filter @c4a/context-cli build      # bundle CLI + render plugin.json
bun run --filter @c4a/context-cli test       # unit + integration tests
bun run --filter @c4a/context-cli typecheck
bun run --filter @c4a/context-cli lint
```

The build chains `scripts/build-plugin.ts`, which reads the human-maintained `plugin/` source and generates self-contained install trees into the nested `c4a-plugins/` directory at the c4a repo root. That directory is an independent git repo (remote: [`context4ai/context`](https://github.com/context4ai/context)) and is `.gitignore`d by c4a. Before running `build:plugin` locally for the first time, clone it:

```bash
cd /path/to/c4a
git clone https://github.com/context4ai/context.git c4a-plugins
```

Plugin marketplace releases are pushed from `c4a-plugins/`, separate from the npm tarball that `@c4a/context-cli` publishes. Do not edit generated build trees directly.

## License

MIT.
