Skip to content

Latest commit

 

History

History
374 lines (309 loc) · 20.5 KB

README.md

File metadata and controls

374 lines (309 loc) · 20.5 KB

Context Agent Runtime

Repository evidence plugin

New workspace initialization includes context-evidence.sourcegraph.wasm when the workspace is the repository root (or has no enclosing Git repository). For existing workspaces run context evidence install [project-dir] --format json. Nested workspaces require explicit --repository-root <git-root> for full-repo hosting, or --plugin-root <registered-content-root> for scoped hosting. Use the workspace directory relative to that plugin root as workspace_root. Unknown or modified same-name files are preserved. The installer never commits or pushes; the artifact must be committed and synchronized before remote use.

On a compatible read-only MCP host, read/read_many can request plugins: [{"name":"context-evidence"}] to attach registered section sources. This does not verify original source contents or change local retrieval and production. Missing enhancement falls back to ordinary metadata reads. See the plugin ABI and build instructions.

简体中文

@c4a/context-cli ships the local runtime and Agent integration for the Context knowledge production workflow. Despite the package name, its primary user experience is not a terminal command catalog: users invoke the production Agent entry, describe the knowledge they want, and follow the decisions explained in conversation.

The runtime performs deterministic work—workspace observation, source capture, code indexing, evidence validation, candidate staging, review application, verification, and package builds. The Agent performs semantic work, while the user owns permissions and important content decisions. The runtime never calls an LLM itself.

Install the Agent integration

Requires Node.js 20 or newer. Knowledge workspaces install their dependencies with Bun (bun install after context init), so install Bun as well.

npm install -g @c4a/context-cli@latest
context plugin install # global installation
# Alternatively, install only in a repository:
context plugin install --local /path/to/repo --agent auto-detect

The source repository is also a plugin marketplace. Claude Code and Codex can install the c4a plugin from it with claude plugin marketplace add context4ai/context and claude plugin install c4a@c4a, or codex plugin marketplace add context4ai/context and codex plugin add c4a@c4a. The CLI is still required; the plugin delegates the workflow and the bundled Indexers to it.

--local requires explicit --agent: claude, cursor, codex, all, auto-detect, or standalone. The path is a repository root: explicit hosts install into .claude, .cursor, or .agents without detection. all installs all three. Only auto-detect checks existing .claude, .cursor, and .agents directories in the target repository, never PATH or installed desktop applications; it falls back to .agents/skills when none exist. standalone instead writes all skills directly to <path>/skills, with no commands or host subdirectory. All modes support --dry-run and preserve global configuration.

Migration from 0.7.20: add --agent auto-detect to bare --local; for explicit hosts pass the repository root, not its host directory. Global installation is unchanged. Host detection does not verify runtime loading.

Command Local layout
context plugin install --local /path/to/repo --agent claude Public entries in commands/, other skills in skills/; internal skills receive user-invocable: false, without duplicate entry skills
context plugin install --local /path/to/repo --agent cursor Bundled c4a-* commands plus other skills; hiding Providers from the command menu is not guaranteed
context plugin install --local /path/to/repo --agent codex All entries remain skills; bundled agents/openai.yaml policies are preserved; no unsupported commands/ directory

Local entries have no plugin namespace; the host must discover the destination. Use --dry-run to preview. Refresh only replaces unmodified managed content; unrelated files remain and conflicting/customized entries are rejected. Choose a fresh host directory when switching from a standalone installation to command entries, to avoid duplicates. plugin status still inspects global hosts only. Invocation metadata is not a CLI permission or security boundary.

Restart or refresh the Agent host after installation. Global installation creates the host-namespaced Context entry and projects context-code-indexer and context-markdown-indexer, context-note-indexer and context-sessions-indexer as unnamespaced lifecycle Provider Skills for Claude, Codex, and Cursor.

The production entry is /c4a:context. It creates a requested workspace, locates an existing workspace, or resumes the current workflow. The other public entries are /c4a:context-plan, /c4a:context-inspect-search and /c4a:context-repo-content (Cursor: /c4a-context-*); see the plugin contract. Users should start with intent, not internal commands:

/c4a:context Turn these product documents and this repository into a reviewed
Agent knowledge package. Keep every code claim traceable.

If the Agent entry is present but the context executable is missing, the entry reports the exact installation recovery and stops. It does not run an installation preflight on every request and does not confuse a normal workflow not found diagnostic with a missing executable.

How one Agent entry drives the workflow

User knowledge goal
        ↓
single Agent entry
        ↓
context entry ── observes workspace location and state
        ↓
workflow.current ── current Route, resources, Gate, exact commands
        ↓
Agent reads / decides / executes one selected action
        ↓
workspace facts change ── evaluate again

context entry --format json is the read-only bootstrap resolver. It can return an initialization action, a workspace relocation action, or the current workflow evaluation. There is no context continue primitive and no separate public entry for source, review, build, or status.

Once a workspace is ready, workflow.current is the current-step authority:

  • required resources marked read-required are read completely before acting;
  • only Route-returned commands are executed, with their revision and authority arguments preserved;
  • human Gates explain the decision and its impact before collecting a choice;
  • project configuration changes are limited to the file named by the Route;
  • every action is followed by a fresh observation, so stale commands cannot advance a changed workspace.

Long procedures, schemas, diagnostics, and source views remain addressable files in the bundled workflow. The Agent loads only what the current Route selects instead of carrying the entire lifecycle in its prompt.

The knowledge production lifecycle

Phase What the user experiences What the runtime protects
Goal and sources Confirm what knowledge is needed and which materials are in scope Source identity, permission boundary, pinned repository or document inputs
Capture and extraction The Agent reads documents or inspects a confirmed code boundary Complete bodies, resources, symbols, relations, fingerprints, and freshness
Planning and writing Review the proposed knowledge organization and content Articles and source-linked sections, coverage, continuity, and stable identities
Review and close Approve, reject, or adjust the candidate set Atomic review application, durable decisions, and closed structure projection
Verify and build Choose an output and receive a reusable package Validation, package templates, asset policy, and build inventory

Building completes the currently approved state; it does not freeze the workspace. New or changed sources can open another production round later.

Ordinary and fully managed conversations

Ordinary mode is the default. It preserves explicit source, scope, structure, review, and package decisions and can provide HTML inspection reports at content-review Gates.

When the user explicitly authorizes fully managed operation for the current conversation, the Agent uses:

context run --managed --until blocked-or-complete --format json

JSON output for this command is a compact stop receipt: next_route.file contains the complete executable Route, and result_file retains the full run history. Add --verbose to inline the full result. Likewise, status --view summary --format json returns progress and a next_route.file pointer; use --view full for the inline Route. Read the referenced Route before acting.

progress.indexer.task_completion measures accepted tasks in the current stage, not overall delivery. Tasks, planned topics and emitted pages have different denominators; pages.authored_not_delivered counts only already-written pages. Complete resource acknowledgements before editing configuration, then refresh status after the edit instead of acknowledging its old revision.

This collapses consecutive deterministic actions and delegated Gates, then stops when Agent reading, project configuration, additional permission, diagnostic repair, or a non-unique plan needs attention. It reuses the same workflow Graph and does not remove ordinary-mode review capability. The authority is conversation-scoped; it does not persist and cannot authorize new source boundaries, unread external content, repository operations, failed validation, or failed verification.

Workspace state

context/
├── src/                         # declarative project and package templates
├── sources/                     # source registry and captured evidence
├── knowledge/                   # approved Markdown and durable decisions
├── dist/                        # built packages
└── .tmp/context-runtime/
    ├── lifecycle/               # open-round candidates and structure
    ├── debug/                   # optional traces
    └── logs/                    # optional runtime-event outbox

These directories have different durability contracts. sources/ and knowledge/ are project state; dist/ is reproducible output; lifecycle and debug directories are ignored runtime state. A successful close removes the completed lifecycle staging area. Do not repair a workflow by manually editing or deleting CLI-owned state—use the recovery action returned by the current Route.

Evidence and safety boundaries

  • Source registration does not grant permission to read source bodies.
  • The runtime does not silently clone, checkout, reset, fetch, install, build, test, or run scripts in a source repository.
  • Markdown parsing preserves structural evidence but does not infer product meaning or choose a knowledge collection.
  • Code extraction emits structural facts; the Agent and user decide their knowledge meaning and scope.
  • source_ref values are opaque, verified evidence identities. Copy them exactly rather than treating them as filesystem paths.
  • Review decisions become approved Markdown only through atomic review apply; Agents do not hand-write lifecycle output.
  • Package templates shape distribution but never replace approved knowledge as the source of truth.

Package output

Declared packages are built under dist/<package-name>/. Agent knowledge packages may contain wikis/, guides/, rules/, feats/, Skills, indexes, and package-specific retrieval helpers. LLM packages consolidate selected knowledge into a text artifact.

Each build inventory maps the distributed paths back to approved workspace knowledge. Asset delivery can use repository raw URLs, an explicit URL prefix, or bundled assets; the project chooses the policy before build.

See Package Outputs and Package Templates.

Diagnostics and direct CLI use

Normal users should follow the Agent entry. Direct commands remain available for maintainers, automation, and diagnostics:

  • context status --format json inspects the current Route;
  • context <command> --help is the authority for current flags;
  • context plugin status checks installed Agent projections;
  • context debug enable records optional traces below .tmp/context-runtime/debug/;
  • context revise "<current Candidate title, path, or id>" --instruction "<requested correction>" reopens exactly the owning Author workset before approval; it does not create a second revision page or mutate approved knowledge/ directly;
  • code extraction stages reader-facing codeindex Candidates and independently audits source analysis, stable-boundary coverage, content density, evidence scope, and page size before Review; legacy codegraph workspaces migrate through the returned Route action;
  • the context indexer lifecycle builds contract-derived question targets, digest-bound partition and author worksets, exact SubjectKey resolution views, and independent post-author composer worksets. Main runs use a local content-addressed ledger whose accepted Result transition is atomic; ordinal/fixed-count partitions advance through the authorized strategy order, and exhausted strategies use a persisted-predecessor CLI catalog fallback that creates one parent unit without an Agent or user Gate; post-author runs use a separate ledger and atomic envelope record. Observe commands publish pending/accepted/failed/stale counts and never use numeric cursors. Reconciliation then recomputes every required coverage domain from current owner cells, accepted author Results, registered materials, and the complete CLI-owned question-target set; capability or material gaps cannot be reported as complete;
  • the markdown-provider Indexer Route starts only from exact current document capture. Agent discovery reports relevant Host-visible Indexer Skills with document capabilities without persisting the discovery list; the CLI recomputes the route and static validation, resolves and stages exact CLI-bundled Bundles, and stops external resolution or local customization at explicit Host/customization Outcomes;
  • route-index-requirement-confirmation recomputes the canonical requirement comparison before routing. Ordinary confirmation may use its explicit authority, while contraction or incomparable obligation replacement always enters the human-only Gate. validate-subject-key-schemas likewise requires an exact Provider-major re-identification authorization for identity-breaking changes over approved Nodes; incomplete, split, merged, or colliding mappings fail before that Gate. Exact target matches that resolve to multiple Nodes return index-target-resolution-ambiguous, and invalid reuse returns index-target-resolution-invalid;
  • unresolved material questions remain in the current reconciliation report. Newly captured Markdown or other authorized material reruns the normal main Indexer path and updates the same Candidate; there is no second checkpoint, answer-only operation, or Review Route;
  • main Candidate Review requires current precompile/postcompile audit records. The CLI verifies requirement, registry, inventory, layout and candidate-set bindings. A blocking mechanical failure reopens the affected Author or Composer workset before recompilation; advisory profile metrics are warnings and do not create a retry ledger or override Gate;
  • required material gaps block the ordinary lifecycle until new captured input reruns the affected workset. The ordinary context close writes approved structure; task cleanup follows successful delivery, not close alone;
  • context clean-cache --dry-run previews cleanup of Context-owned stale plugin caches.

Revision-bound commands should be copied from workflow.current; examples in documentation are orientation, not a substitute for the current Route. See the installed quickstart and debug tracing guide.

Documentation and development

For source, link, packaged-install, and release workflows, see DEVELOPMENT.md and this package's DEVELOPMENT.md.

bun run --filter @c4a/context-cli build
bun run --filter @c4a/context-cli typecheck
bun run --filter @c4a/context-cli lint
bun run --filter @c4a/context-cli test

Build generates installable host projections under dist/plugins and the direct-Git projection under ../../plugins/context/repo-install; edit only ../../plugins/context/ and the bundled workflow source, never generated output.

License

MIT.

Updating an existing workspace

Lark read identity

CONTEXT_LARK_IDENTITY=user|bot selects the identity for Lark acquisition (default: user). Export it in each shell executing Context commands. In Bot mode, a credential/scope/access failure retries once as the current user; the rest of that capture keeps the fallback identity for pagination and resources. Network, rate-limit and parsing errors do not trigger a user authorization attempt. This does not change source-read consent or the audience of published knowledge. Host-managed OAuth must use the host's authorization flow.

Workspace updates

Start with context entry --format json and read the returned update guide when adding material or changing published knowledge. Entry and status only observe; they do not resume an earlier managed task before the new request is understood.

  • context update --input <file> accepts confirmed source/module scopes and fixed, already acquired versions. The current Route asks which existing pages need changes and whether additions need new pages.
  • context update --pending processes registered repositories whose commit moved past the processed version. Only pages whose cited text changed become candidates; the scope decision still covers additions before the commit settles.
  • context revise <page> --instruction <text> starts from the current approved body. --move-to <path> preserves its identity and updates Markdown navigation when the reviewed move is applied.
  • context source import --input <file|-> saves note/sessions Markdown or imports actual prefetched Lark responses. An array imports several documents and reports each result; failed entries do not discard successful imports.
  • context source rename <ref> --name <name> previews a managed source rename; apply its current plan digest to update existing references safely.
  • context task adjust --input <file> adjusts selected inputs within the current task. context task rollback --input <file> previews explicitly supplied recovery bytes; rollback still needs close, build and cleanup before a new task.

The processed baseline is stored by requirement and source/module scope in knowledge/structure.yaml. It advances after all selected revisions and builds, not after acquisition or the first approved page. Losing temporary drafts calls for a fresh comparison against approved knowledge, not restoration of old runs. Remote writes, Git submission and publication remain separate explicit actions.

Maintenance during production

context revise <page> --instruction <text> keeps current-batch repair behavior; approved pages outside the active batch can be queued without replacing its ledger. --regenerate explicitly prepares current programmatic API blocks even when the source version is unchanged. --timing priority requests early delivery of complete pages; it does not bypass Review.

For multiple approved pages use context task maintain --input <file> --format json with id, operation: revise | regenerate | rebuild, optional timing: after-batch | priority, and targets: [{ path, instruction }]. Rebuild has no targets and packages approved content without completing production. Reuse the same id/input on retry. Status reports active and queued maintenance plus its waiting condition. Source refreshes remain explicit scope adjustments; this entry does not fetch remote sources or rerun every custom Composer.

context task maintenance-status --format json exposes the request state and revision. context task cancel-maintenance <id> --format json cancels a pending request. Discarding an active maintenance draft additionally requires its current --discard-revision; it retains already approved pages and unrelated work.