# Context --- ## What is Context # What is Context Context is a knowledge workflow for engineering teams and their AI agents. It turns code repositories, documents, notes and conversations into reviewed, versioned knowledge in which every claim leads back to its source, then builds that knowledge into Agent knowledge packages, documentation sites and LLM documents. Agents read the knowledge first and follow its evidence chain to the original only when they need exact detail. You describe what knowledge you need and where the material lives. Your Agent reads the evidence, proposes a structure and explains its decisions. Context keeps the process legal and repeatable: it records source boundaries, checks evidence coverage, stages reviewable candidates, preserves provenance, verifies the approved result and builds the output you chose. ## How it fits together The diagram shows the path from material to the people and Agents who ask questions. ```mermaid flowchart TB subgraph produce["Produce"] direction LR src["Code, documents, notes, sessions"] -->|registered and captured| agent["Your Agent with Context skills"] end subgraph approve["Review"] direction LR review["Human review"] -->|approves| kb["Approved knowledge"] end subgraph use["Use"] direction LR out["Package, site, LLM Docs"] -->|answers with sources| users["Agents, Bots, developers"] end produce -->|writes candidates| approve approve -->|builds| use ``` Context is not a one-shot summarizer. Source snapshots, review state, approved knowledge and package inventories stay in a local Context knowledge workspace, so the result can be inspected, versioned and refreshed when sources change. ## What makes it different - **An index with evidence chains, not copied prose.** Indexers keep only what answers a reader's questions and record where each statement came from. In one large production monorepo, about 202 MB of code and documents became about 1.75 MB of reviewed knowledge, roughly 1/115 of the source volume. See [Knowledge for Agents]() and [Evidence Chains and Index First](). - **Skills and a CLI inside the Agents you already use.** Context does not call an LLM and is not a hosted platform. Its skills run in Claude Code, Codex, Cursor or a managed Agent, and the local CLI performs the deterministic work. See [Why a Workflow](). - **Review before anything is published.** People own the goal, source permission, structure and review decisions; drafts become approved Markdown only after review. See [Knowledge Lifecycle](). - **Knowledge that follows its sources.** Sources are pinned, and a later change reopens only the affected pages. See [Keeping Knowledge Current](). - **One body of knowledge, several outputs.** The same approved pages build an Agent knowledge package, a documentation site and LLM Docs, each mapped back to the knowledge workspace through a build inventory. See [Packages and Sites](). ## Who it is for Context helps when knowledge exists but is not yet ready for an Agent to use. Typical requests: - turn product, architecture, operations or FAQ documents into a navigable knowledge base; - connect code structure with explanatory documents while keeping exact source evidence; - combine several repositories and document sets into one reviewed knowledge package; - update an existing knowledge workspace when its sources change, without rebuilding everything. In a measured comparison on real developer questions, Agents answering from Context knowledge fully solved more questions with far fewer tool calls than with an LLM Wiki; see [Knowledge Retrieval benchmark](). ## Source Graph and Agent Graph Two companion projects carry parts of the workflow: - **Source Graph** searches and reads repositories at a pinned commit over the web, MCP, HTTP and a CLI. Context ships an optional evidence plugin so that an Agent reading code through Source Graph also receives the knowledge sections that cite it, without cloning the repository. See the [Source Graph overview](). - **Agent Graph** is the work-contract layer under the Context workflow. Context observes knowledge workspace facts and executes actions; Agent Graph evaluates those facts and selects the next legal step, which keeps a long workflow resumable and testable. See [Why Graph Engineering]() and [Workflow Execution](). ## How you get it Context is delivered as an npm CLI plus an Agent plugin. Install both once, restart the Agent session, then describe the knowledge goal to the `/c4a:context` entry in plain language. Continue with [Installation]() and [Quick Start](). --- ## Sources - [context/README.md L8–L13 · 3b0ce0a]() - [context/README.md L101–L104 · 3b0ce0a]() - [context/README.md L106–L114 · 3b0ce0a]() - [context/README.md L80–L92 · 3b0ce0a]() - [context/README.md L29–L31 · 3b0ce0a]() - note:20261012/compression.md · compression.md L15–L22 - [context/README.md L22–L35 · 3b0ce0a]() - note:20261012/benchmark-summary.md · benchmark-summary.md L40–L49 - [context/packages/context-cli/README.md L3–L18 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L5–L7 · 3b0ce0a]() - [context/README.md L43–L58 · 3b0ce0a]() --- ## Installation # Installation ## Before you start You need: - Node.js 20 or later with npm; - at least one Agent host: Claude Code, Codex or Cursor; - read access to the repositories and documents you plan to turn into knowledge. Context runs on your machine. The CLI never calls an LLM itself: the Agent in your host does the reading and writing, and the CLI performs deterministic work such as observing the Context knowledge workspace, capturing sources, indexing code, validating evidence, applying reviews and building packages. ## Install the CLI and the plugin ```bash npm install -g @c4a/context-cli@latest context plugin install ``` The first command installs the `context` runtime. The second installs the Agent integration into every supported host it finds. Restart or refresh your Agent host afterwards so it loads the new entries. ```mermaid flowchart LR npm["npm install -g @c4a/context-cli"] --> cli["context runtime"] cli -->|context plugin install| hosts["Claude Code / Codex / Cursor"] hosts --> entries["/c4a:context and other entries"] hosts --> providers["Indexer Provider skills"] ``` A global installation creates the namespaced Context entries and also projects the four Indexer Provider skills — `context-code-indexer`, `context-markdown-indexer`, `context-note-indexer` and `context-sessions-indexer` — without a namespace, so every host can find them. Installing a Provider only makes it discoverable; the workflow selects Providers per task. ## What you get | Entry | Use it to | | --- | --- | | `/c4a:context` | Create a knowledge workspace, continue one, and run production, review, update and build | | `/c4a:context-plan` | Plan a large project in stages before production | | `/c4a:context-inspect-search` | Ask questions against knowledge packages or approved knowledge in a knowledge workspace, with sources | | `/c4a:context-repo-content` | Register or edit same-repository docs and authored Skills without starting production | `/c4a:context` is the production entry for both new and existing knowledge workspaces; the other three entries plan, answer or register content and hand production back to it. You do not need to learn lifecycle commands; describe the knowledge goal in normal language. Ordinary coding or design conversations do not start Context on their own — invoke it explicitly or continue an active Context conversation. [Commands and Skills]() lists every entry, how each host spells it, and the Skills that run without being invoked. ## Install into one repository only If you prefer not to change global configuration, install the entries into a single repository: ```bash context plugin install --local /path/to/repo --agent auto-detect ``` `--local` needs an explicit `--agent`: - `claude`, `cursor` or `codex` install into that repository's `.claude`, `.cursor` or `.agents` directory; - `all` installs all three layouts; - `auto-detect` uses whichever of those directories already exist and falls back to `.agents/skills`; - `standalone` writes all skills directly to `/skills`, without commands. Every mode supports `--dry-run`. A refresh replaces only unmodified managed files; customized entries are kept and reported as conflicts. Local entries have no plugin namespace. ## Check the installation ```bash context --version context plugin status ``` `context plugin status` inspects the global hosts. Then open your Agent and invoke `/c4a:context`. If the entry is present but the `context` executable is missing, the entry reports the exact installation step and stops rather than partially initializing a knowledge workspace. Next: [Quick Start](). --- ## Sources - [context/README.md L5–L5 · 3b0ce0a]() - [context/packages/context-cli/README.md L28–L32 · 3b0ce0a]() - [context/packages/context-cli/README.md L34–L41 · 3b0ce0a]() - [context/packages/context-cli/README.md L55–L59 · 3b0ce0a]() - [context/plugins/context/README.md L13–L22 · 3b0ce0a]() - [context/packages/context-cli/README.md L61–L68 · 3b0ce0a]() - [context/plugins/context/skills/context-repo-content/SKILL.md L1–L3 · 3b0ce0a]() - [context/ARCHITECTURE.md L358–L366 · 3b0ce0a]() - [context/packages/context-cli/README.md L43–L53 · 3b0ce0a]() - [context/packages/context-cli/README.md L53–L53 · 3b0ce0a]() - [context/packages/context-cli/README.md L73–L76 · 3b0ce0a]() --- ## Quick Start # Quick Start This walkthrough turns one code module and one local documentation folder into a reviewed knowledge package with a browsable site. You give instructions in plain language; the Agent runs the commands the workflow returns. The commands shown below are what the Agent runs on your behalf, so you can recognize them in its progress messages. Make sure [Installation]() is done and you have restarted the Agent session so the plugin is loaded. ## 1. Create the knowledge workspace Tell the Agent where the Context knowledge workspace should live and what it is for: ```text /c4a:context Create a Context knowledge workspace in ./context for our component library and its product docs. Readers are frontend developers new to the library. ``` The Agent initializes the directory and installs its dependencies: ```bash context init ./context cd ./context bun install context status --format json ``` You get this layout: ```text context/ ├── AGENTS.md # guidance for the Agent ├── src/ # source, phase and package declarations ├── sources/ # registered sources and captured evidence ├── knowledge/ # approved knowledge (empty for now) ├── dist/ # built packages (ignored by Git) └── .tmp/ # runtime state and reports (ignored by Git) ``` ## 2. Point it at your sources Name the material and anything the Agent should skip: ```text Use ../component-lib for code and ../docs for product documents. Skip the deprecated v1 folder. ``` The Agent registers each boundary. Registration records what is in scope; it does not decide what to write. ```bash context source add repo 20260901 --module component-lib --local ../component-lib --configure context source add file 20260901 --module product-docs --local ../docs --configure ``` For a monorepo, pick the package or service your readers need. Unneeded material costs reading time and tokens, but do not exclude something just because its filename looks old. ## 3. Confirm the work-start report The Agent reads representative material, asks about anything that would change the scope, records the reader purpose in `src/indexers.yaml`, and presents a **work-start report** with: - the confirmed sources and scope; - the Indexer skills it will use; - the first pages you should expect and where they will sit in the site. Nothing is written until you approve the report. If the plan is off, say what to change — for example "merge the two API pages" or "add a troubleshooting page" — and the Agent revises it. ## 4. Let it write, then review After approval, the Agent writes each page with references to exact source lines and submits them for checks on coverage and stale inputs. When writing finishes, you receive a review report showing each page's title, path, summary and content. Approve it, reject pages, or ask for revisions. Approved pages land in `knowledge/` as Markdown; rejected or revised pages go back to writing. ```mermaid flowchart LR write["Agent writes pages"] --> review["You review"] review -->|revise| write review -->|approve| kn["knowledge/"] kn --> build["context build"] build --> kb["dist/component-kb/"] build --> site["dist/component-site/"] ``` ## 5. Build the package and site For a new knowledge workspace, the Agent proposes a knowledge package plus a website by default. The package declaration in `src/index.ts` looks like this: ```ts kbPackage({ name: "component-kb", template: "src/package-templates/kb", site: { title: "Component knowledge", lang: "en-US", base: "/" }, }); ``` `context build` then produces `dist/component-kb/` for Agents and `dist/component-site/` — a static site with article pages and local search — for people. Commit the knowledge workspace to Git so the result can be inspected, versioned and refreshed later. ## Next steps - Ask a question against the new package with `/c4a:context-inspect-search`. - When the code or docs change, tell `/c4a:context` what changed; it reopens only the affected pages. - For larger scopes, read [Large Projects](). - See every entry you can invoke, and the Skills that run on their own, in [Commands and Skills](). --- ## Sources - [context/packages/context/docs/getting-started.md L47–L50 · 3b0ce0a]() - [context/README.md L45–L53 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L29–L45 · 3b0ce0a]() - [context/packages/context-cli/docs/quickstart.md L67–L72 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L47–L60 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L105–L118 · 3b0ce0a]() - [context/README.md L87–L88 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L120–L136 · 3b0ce0a]() - [context/README.md L29–L31 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L33–L54 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L76–L98 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L155–L157 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L1–L3 · 3b0ce0a]() --- ## The Context Knowledge Workspace # The Context Knowledge Workspace A **Context knowledge workspace** is the directory where Context keeps one body of knowledge: its declarations, its registered sources, the approved pages and the outputs built from them. `context init` creates it, and its `package.json` marks it as a Context project. It is usually a Git repository of its own, or a directory inside a project repository. Everything about the knowledge lives here, not in the conversation. Run Context commands from this directory: Route paths and `.tmp/` belong to this knowledge workspace, not to the surrounding repository or a parent directory. ```mermaid flowchart LR subgraph you["You and the Agent declare"] src["src/
project, requirements, map, templates"] end subgraph cli["Context CLI maintains"] sources["sources/
registered evidence"] --> knowledge["knowledge/
approved pages"] knowledge --> tr["translations/"] end src --> sources knowledge --> dist["dist/
packages and sites"] tr --> dist ``` ## The layout Right after `context init`, and after the first deliveries, a knowledge workspace looks like this: ```text my-knowledge/ ├── package.json # version and context.project marker ├── AGENTS.md # rules for Agents working here ├── README.md ├── .gitignore ├── src/ │ ├── index.ts # sources, capture phases and packages │ ├── indexers.yaml # reader purpose and authorized sources │ ├── knowledge-map.yaml # navigation for sites and LLM Docs │ ├── package-templates/ # templates for each package kind │ └── site/ # optional website customization ├── sources/ │ ├── repo/index.yaml # repository sources: remote, commit, modules │ ├── file/ # local document sources and snapshots │ ├── lark/ # Lark document sources and snapshots │ ├── note/YYYYMMDD/ # saved notes │ └── sessions/YYYYMMDD/ # saved conversation summaries ├── knowledge/ │ ├── /… # approved Markdown pages │ └── structure.yaml # page identities, sections and source references ├── translations// # translated pages and navigation titles ├── changelog.yaml # knowledge version history ├── CHANGELOG.md # generated from changelog.yaml ├── dist/ # built packages and sites └── .tmp/ # runtime state, reports, Agent scratch ``` Some files appear only when you use the feature they belong to: `imports.yaml`, `repo-content.yaml` with its `repo-content/` view, `context-evidence.sourcegraph.wasm`, and a `PLAN-*.md` during a planned project. They are described below. ## Who writes what, and what Git keeps | Path | Written by | In Git | | --- | --- | --- | | `package.json`, `AGENTS.md`, `README.md` | Created by `context init`; the version is updated by the CLI | Yes | | `src/index.ts`, `src/indexers.yaml`, `src/package-templates/`, `src/site/` | You or the Agent, only when the current Route asks for a configuration change | Yes | | `src/knowledge-map.yaml` | The CLI, through navigation adjustments the Agent submits | Yes | | `sources/` registries, snapshots, notes and summaries | The CLI | Yes — except repository checkouts under `sources/repo/`, which are recovered from `index.yaml` | | `knowledge/` | The CLI, when you approve a Review | Yes | | `translations/`, `changelog.yaml`, `CHANGELOG.md` | The CLI, from Agent-written translations and change notes | Yes | | `dist/` | `context build` | No — reproducible | | `.tmp/` | The CLI and the Agent | No — runtime only | `sources/` and `knowledge/` are the durable state of the knowledge; `dist/` can always be rebuilt from them. Commit the knowledge workspace only when Git operations are authorized for your task. ## Files that appear as the knowledge grows - **`src/knowledge-map.yaml`** is the persistent knowledge map. It organizes website navigation and LLM Docs without changing page identities, and stays after each delivery. See [Reorganizing at Scale](). - **`translations//`** holds one translated file per approved page plus a `knowledge-map.yaml` of translated navigation titles. Translations are formal content: they count toward versions and are packaged with the site. - **`changelog.yaml` and `CHANGELOG.md`** are updated together with `package.json.version` each time a delivery records a version. See [Versions and Changelog](). ## Files for linked content - **`imports.yaml`** at the root declares external entrances — content elsewhere that pages may link to — without downloading or capturing it. See [External Entrances](). - **`repo-content.yaml`** registers documentation and authored Skills that live in the same repository; **`repo-content/`** is a symlink view of them, and the originals stay where they are. See [Same-Repository Docs](). - **`context-evidence.sourcegraph.wasm`** is an optional plugin for reading code evidence remotely. `context evidence install` maintains it; queries never install it on their own. See [Reading Code Evidence Remotely](). ## Runtime and scratch space | Path | Holds | | --- | --- | | `.tmp/context-runtime/` | Unfinished workflow state: production stages, candidates, review reports, routes | | `.tmp/agent-payloads/` | Command inputs the Agent prepares, such as translations | | `.tmp/install/` | Temporary files used while installing dependencies | | `.tmp/context-plans//` | Research for a planned project: `repos/`, `documents/`, `research/`, `stage-inputs/` | `.tmp/context-runtime/` is not the only record of progress. After a successful delivery the CLI removes completed task state, and approved knowledge with `structure.yaml` keeps what later updates need. Its absence never means accepted work may be replayed. A planned project also keeps `PLAN-YYYYMMDD-slug.md` at the Git root, committed so work can resume; see [Planning a Large Project](). ## Rules that keep it healthy - **Do not edit CLI-owned state by hand.** `sources/`, `knowledge/`, `dist/` and `.tmp/context-runtime/` change only through Context commands. To change a page, ask for a [revision](). - **One knowledge workspace per directory.** Do not create a hidden second workspace, and do not mix revisions, tasks or `.tmp/` files with a parent directory that is also a knowledge workspace. - **Repair through the Route.** When something looks broken, follow the recovery action the current Route returns instead of deleting runtime files. Next: [Commands and Skills]() lists what you can invoke in this knowledge workspace, and [Core Concepts]() explains how its parts relate. --- ## Sources - [context/packages/context-cli/src/project/workspaceGuidanceTemplates.ts L104–L108 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L38–L45 · 3b0ce0a]() - [context/packages/context-cli/src/project/workspace.ts L22–L25 · 3b0ce0a]() - [context/packages/context-cli/src/project/workspace.ts L467–L537 · 3b0ce0a]() - [context/packages/context-cli/src/project/workspaceGuidanceTemplates.ts L119–L131 · 3b0ce0a]() - [context/packages/context/src/managedSources.ts L18–L21 · 3b0ce0a]() - [context/packages/context-cli/src/project/workspace.ts L454–L465 · 3b0ce0a]() - [context/packages/context/docs/reference/project-api.md L217–L222 · 3b0ce0a]() - [context/packages/context-cli/README.md L159–L178 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L500–L505 · 3b0ce0a]() - [context/packages/context/docs/guides/site-translation.md L8–L16 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L169–L169 · 3b0ce0a]() - [context/packages/context/docs/guides/imports.md L1–L7 · 3b0ce0a]() - [context/packages/context/docs/guides/repo-content.md L1–L20 · 3b0ce0a]() - [context/packages/context-cli/src/project/workspaceGuidanceTemplates.ts L125–L126 · 3b0ce0a]() - [context/packages/context-cli/src/project/workspaceGuidanceTemplates.ts L128–L130 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L150–L153 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/references/project-planning.md L10–L28 · 3b0ce0a]() - [context/packages/context-cli/src/project/workspaceGuidanceTemplates.ts L132–L132 · 3b0ce0a]() - [context/packages/context-cli/src/project/workspaceGuidanceTemplates.ts L154–L158 · 3b0ce0a]() - [context/packages/context-cli/README.md L173–L178 · 3b0ce0a]() --- ## Commands and Skills # Commands and Skills You work with Context through a handful of conversational entries. Everything else — the lifecycle CLI commands, the Indexers and the workflow's own step Skills — runs behind them, chosen by the current Route rather than typed by you. ```mermaid flowchart LR you["You, in plain language"] --> entry["Entry Skill
/c4a:context and others"] entry --> cli["context CLI
current Route"] cli --> step["Workflow step Skills"] cli --> idx["Indexer Skills"] step --> cli idx --> cli ``` ## Entries you invoke | Entry | Use it to | Example | | --- | --- | --- | | `/c4a:context` | Create a Context knowledge workspace, continue one, and run production, review, update and build | *"Build reviewed knowledge for ../billing-service for on-call engineers."* | | `/c4a:context-plan` | Plan a large project or a broad update in stages before production | *"Plan knowledge for these three repositories and the design folder."* | | `/c4a:context-inspect-search` | Ask questions against knowledge packages or approved knowledge, with sources | *"How are refunds retried? Cite the code."* | | `/c4a:context-repo-content` | Register or edit documentation and authored Skills in the same repository, without starting production | *"Register docs/ and .agents/skills as repository content."* | `/c4a:context` is the production entry for new and existing knowledge workspaces. The other three entries do not drive production themselves: a plan, an answer that points to a gap, or registered repository content is handed back to `/c4a:context` when knowledge should be produced. A conversation where Context is already active continues without invoking it again; ordinary coding or design conversations never start it on their own. To create a new Indexer, ask in plain language — *"Create an Indexer Skill for our RPC framework in ./skills"*. The `context-indexer-create` Skill picks this up; it is not a menu command. ## How each host spells them | Host | How entries appear | | --- | --- | | Claude Code | Plugin commands `/c4a:context`, `/c4a:context-plan`, `/c4a:context-inspect-search`, `/c4a:context-repo-content` | | Cursor | Commands `/c4a-context`, `/c4a-context-plan`, `/c4a-context-inspect-search`, `/c4a-context-repo-content` | | Codex | Skills invoked by name: `context`, `context-plan`, `context-inspect-search`, `context-repo-content` | | Local install into one repository (`context plugin install --local`) | The same entries without the `c4a` plugin namespace | Restart or refresh the host after installing or updating the plugin so it loads the current entries. See [Installation](). ## Skills that run on their own | Skill | When it runs | | --- | --- | | `context-code-indexer`, `context-markdown-indexer`, `context-note-indexer`, `context-sessions-indexer` | The Agent selects them for the current sources and requirements during planning and writing. Installing one makes it available; it is not enabled for every knowledge workspace. See [Community Indexers](). | | `context-inspect-search` | Also when a host or Bot configuration routes knowledge questions to it. | | Workflow step Skills: `work-production-stage`, `translate-site-locales`, `record-workspace-version`, the Indexer lifecycle steps, and `recover-workspace` | Each runs when the current Route selects its step — writing a production stage, translating the site, recording a version, or recovering a stuck task. | Indexer Skills are installed without a plugin namespace, so they keep the same names in every host. Every Skill in the Agent plugin, with its trigger and hand-off, is listed in the [Skills reference](). ## What you never need to type The lifecycle commands — `context source add`, `context review …`, `context build` and the rest — are run by the Agent with the exact revision the Route returns. You will see them in progress messages, but you describe goals instead. There is no `context continue` command: when the Agent starts, `context entry` and `context status` observe the knowledge workspace and return the next step. The full command list is in the [CLI Commands reference](). ## Requests you will use often | You want to | Say something like | Read more | | --- | --- | --- | | Start | *"Create a Context knowledge workspace in ./kb for …; readers are …"* | [Quick Start]() | | Add material | *"Add ../docs/refunds to the sources and re-plan the affected part."* | [Working with Agents]() | | Fix a page | *"Revise the retry page: the limit is five, not three."* | [Revising a Page]() | | Follow a change | *"The billing repository moved to a new release; update the affected pages."* | [Updating Knowledge]() | | Hand off review | Add a `CONTEXT_RUN_POLICY` block to the task | [Managed Mode and Review Policy]() | --- ## Sources - [context/plugins/context/README.md L19–L26 · 3b0ce0a]() - [context/packages/context-cli/README.md L78–L111 · 3b0ce0a]() - [context/packages/context-cli/README.md L61–L73 · 3b0ce0a]() - [context/ARCHITECTURE.md L358–L366 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/SKILL.md L1–L16 · 3b0ce0a]() - [context/packages/context-cli/README.md L43–L59 · 3b0ce0a]() - [context/plugins/context/README.md L72–L74 · 3b0ce0a]() - [context/plugins/context/README.md L10–L17 · 3b0ce0a]() - [context/plugins/context/README.md L14–L26 · 3b0ce0a]() - [context/plugins/context/README.md L74–L81 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/graphs/workspace.yaml L331–L350 · 3b0ce0a]() - [context/packages/context-cli/README.md L94–L107 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L155–L157 · 3b0ce0a]() - [context/packages/context/docs/guides/agent-guide.md L17–L42 · 3b0ce0a]() --- ## The Workflow at a Glance # The Workflow at a Glance ## Six steps A Context task follows the same six steps whether it covers one document set or several repositories. You talk to the Agent; the Agent follows the workflow the CLI returns. ```mermaid flowchart LR s1["1 Install"] --> s2["2 Initialize"] s2 --> s3["3 Research and plan"] s3 -->|work-start report| s4["4 Produce"] s4 --> s5["5 Review and preview"] s5 -->|revise| s4 s5 -->|approve| s6["6 Build and commit"] ``` | Step | What you do | What happens | | --- | --- | --- | | 1 Install | Install the CLI and plugin once | Entries appear in your Agent host; see [Installation]() | | 2 Initialize | Ask `/c4a:context` to create a Context knowledge workspace in a directory | The CLI creates `src/`, `sources/`, `knowledge/` and the guidance in `AGENTS.md` | | 3 Research and plan | Describe the knowledge, its sources and its intended form, then answer the Agent's questions | The Agent registers sources, investigates them and presents a **work-start report**: confirmed configuration and scope, the planned content, and the expected package or site layout | | 4 Produce | Wait, or ask for a local preview at any time | The Agent writes articles bound to source evidence and reports progress against the task count | | 5 Review and preview | Read the review report and approve, reject or ask for revisions | Approved candidates become durable Markdown under `knowledge/` | | 6 Build and commit | Confirm the package and other outputs | Context verifies and builds; the Agent commits the knowledge workspace to Git | ## What to expect Production is the longest step: on average each writing task takes about a minute. Ask for a preview whenever you want to see pages in a browser. The work-start report and the review report are the two moments where your judgment shapes the result most; the Guides section on review explains what to look for. ## Production, updates and questions The six steps describe a first production round. Two other paths reuse the same knowledge workspace: - **Updates.** Building completes the currently approved state; it does not freeze the knowledge workspace. When sources change, a new round reopens only the affected knowledge. See [Keeping Knowledge Current](). - **Questions.** `/c4a:context-inspect-search` answers questions from knowledge packages or approved knowledge in the knowledge workspace and traces each answer back to its sources. ## Why you can stop and resume Each step is chosen from the knowledge workspace's actual state, not from the conversation. After every action the CLI observes the knowledge workspace again and returns the current step, its required reading and the exact commands. If you close the conversation and invoke `/c4a:context` later, it resumes where the work actually is. See [Workflow Execution](). --- ## Sources - note:20261012/usage-practices.md · usage-practices.md L5–L9 - [context/README.md L80–L92 · 3b0ce0a]() - [context/packages/context-cli/docs/quickstart.md L67–L72 · 3b0ce0a]() - note:20261012/usage-practices.md · usage-practices.md L8–L8 - note:20261012/usage-practices.md · usage-practices.md L16–L22 - [context/packages/context-cli/README.md L123–L124 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L1–L3 · 3b0ce0a]() - [context/packages/context-cli/README.md L80–L111 · 3b0ce0a]() - [context/README.md L94–L97 · 3b0ce0a]() --- ## Large Projects # Large Projects ## When a task is large Plan a task in stages when its scope has **more than 30 source documents, or at least two repositories that need real investigation**. Use `/c4a:context-plan` explicitly, or let the `/c4a:context` entry hand over to it when an authorized task crosses that threshold. Starting a new knowledge project whose scope still needs research is also a good reason to plan first. A very large multi-domain monorepo may be better served by one Context knowledge workspace per direction than by a single knowledge workspace. ## The PLAN report Planning produces a `PLAN-YYYYMMDD-slug.md` report at the project's Git root. It inventories sources, maps overlaps with knowledge you already have, and divides the work into stages. You review the first report before any production starts. ```mermaid flowchart LR research["Research"] --> plan["PLAN report"] plan -->|you approve| stage["Run one stage"] stage -->|record in PLAN, next stage| stage stage -->|all delivered| done["Remove PLAN"] ``` Approving the PLAN does not approve any article. Each stage still runs the normal workflow with its own work-start report and content review. [Planning a Large Project]() walks through every part of the report, its review and how to resume. ## Stage size | Boundary | Recommendation | | --- | --- | | Source documents per stage | 30, at most 50 (groups above 30 are explained in the PLAN) | | New repositories investigated per stage | 1 | | Target articles in a revision stage | 30 | | Scope above 100 documents | The Agent checks with you whether bounded research gives a useful scope | | Scope above 500 documents | The whole task pauses until a person confirms the scope | These are planning boundaries, not CLI gates. After each stage the Agent records the actual research, production, review and delivery results in the PLAN and commits it before the next stage begins. ## Steer early On a large task, preview the work-start report and the first changed pages as soon as they exist. If the wording, examples or style are off, say so with counter-examples. Corrections made in the first stage carry into every later stage; the earlier you correct, the higher the final quality. If a session is interrupted, the PLAN records the exact position and next action, so a new conversation can continue the same stage. --- ## Sources - [context/plugins/context/skills/context-plan/SKILL.md L15–L20 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L29–L31 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L36–L60 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L123–L128 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L106–L118 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L44–L48 · 3b0ce0a]() - note:20261012/usage-practices.md · usage-practices.md L13–L13 - note:20261012/usage-practices.md · usage-practices.md L14–L14 - [context/plugins/context/skills/context-plan/SKILL.md L123–L125 · 3b0ce0a]() --- ## Core Concepts # Core Concepts ## How the concepts relate ```mermaid flowchart LR subgraph ws["Context knowledge workspace"] direction LR src["Sources"] --> idx["Indexers"] req["Requirements"] --> idx idx --> cand["Candidates"] cand -->|Review| kn["Approved knowledge"] end kn --> pkg["Packages and sites"] facts["Facts"] -.-> route["Route and Gate"] route -.->|next action| idx ``` Everything lives in one **Context knowledge workspace**. **Sources** and **requirements** go in; **Indexers** turn them into **Candidates**; **Review** admits Candidates into **approved knowledge**; builds turn that knowledge into **packages and sites**. Throughout, the workflow reads **Facts** about the knowledge workspace and selects the next **Route**, pausing at **Gates** for human decisions. ## Context knowledge workspace A local directory, usually committed to Git, that holds everything about one body of knowledge: | Directory | Holds | | --- | --- | | `src/` | Source, phase and package declarations, plus `indexers.yaml` requirements | | `sources/` | Registered sources and captured evidence | | `knowledge/` | Approved knowledge and durable decisions | | `dist/` | Built packages (reproducible, ignored by Git) | | `.tmp/` | Disposable runtime state and reports (ignored) | The CLI owns writes under `sources/`, `knowledge/`, `dist/` and the runtime state; the Agent edits project configuration only when the current Route asks for it. Every directory and file is described in [The Context Knowledge Workspace](). ## Sources, capture, notes and sessions A **source** is a registered boundary: a repository module, a local document directory or an online document. Registering a source records its identity and permission boundary; it does not decide what knowledge to write and does not grant permission to read beyond it. **Capture** preserves document bodies and resources as auditable snapshots; repositories are read at a pinned commit and need no capture. **Notes** are curated excerpts and observations; **sessions** are saved conversation summaries. Both are imported directly with `context source import` and become evidence like any other source. ## Requirements and Indexers **Requirements** in `src/indexers.yaml` record who the knowledge is for, the questions it must answer and which sources are authorized. **Indexers** are Agent skills that read one kind of source and write source-grounded articles: Code, Markdown, Note and Sessions Indexers are built in, and teams can create their own. The Agent picks the relevant Indexers for each task during planning. See [Community Indexers]() and [The Indexer System](). ## Candidates, Review and approved knowledge Articles the Agent writes are submitted as **Candidates**: drafts bound to source evidence and checked for coverage and stale inputs. **Review** shows readable titles, paths, summaries and content; approval applies the pages to `knowledge/` as durable Markdown, while rejection sends them back to writing. A rejected Candidate's status lives only in the temporary lifecycle ledger; `knowledge/` holds approved pages alone. Each section of approved knowledge keeps its **evidence**: references to exact source locations. Together they form the [evidence chain]() that lets readers and Agents verify a statement. The **knowledge map** (`knowledge/structure.yaml`) is the closed projection of collections, articles and sections that sites and packages navigate by. ## Packages and sites A **build** turns approved knowledge into an output: an Agent knowledge package, a documentation site or LLM documents. Every build emits an inventory that maps distributed files back to the knowledge workspace. See [Packages and Sites](). ## Route, Gate and Facts **Facts** are what the CLI observes in the knowledge workspace and records as outcomes; conversation claims are not completion evidence. From the Facts, the workflow selects one **Route**: the current action, the resources to read for it and its completion contract. A **Gate** pauses a Route for a decision that needs a person or additional authority, such as approving the work-start report or the review. See [Workflow Execution](). --- ## Sources - [context/README.md L80–L92 · 3b0ce0a]() - [context/packages/context-cli/docs/quickstart.md L67–L75 · 3b0ce0a]() - [context/packages/context-cli/README.md L159–L178 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L47–L74 · 3b0ce0a]() - [context/packages/context-cli/README.md L115–L118 · 3b0ce0a]() - [context/packages/context-cli/README.md L182–L184 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L114–L118 · 3b0ce0a]() - [context/plugins/context/README.md L5–L7 · 3b0ce0a]() - [context/README.md L87–L90 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L133–L136 · 3b0ce0a]() - [context/ARCHITECTURE.md L158–L158 · 3b0ce0a]() - [context/README.md L106–L114 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L44–L53 · 3b0ce0a]() - [context/packages/context-cli/README.md L99–L107 · 3b0ce0a]() --- ## FAQ # FAQ ## Does a small module need a central knowledge base? Not necessarily. A central knowledge base suits knowledge that many people share and use remotely: the team registers its repositories, documents and meeting notes once, and its Bot, documentation site and each member's coding Agent all read the same reviewed knowledge. Content for a small module or a single maintainer can stay in the repository's `docs/`. Context can register same-repository documents as repository content without copying them into knowledge. ## Knowledge is written by AI. How is quality kept, and does it bloat? People decide the direction; the Agent handles the detail. - In the review report, a person judges whether the categories, update scope and granularity are right. Nothing is published before its Diff report is approved. - Every conclusion records its source (file, line and version), and citations are checked before anything is written into knowledge. - During production and updates the Agent cross-checks sources. It often finds upstream documents that lag behind the code, corrects the knowledge from the code, and can also write the correction back upstream when asked. - Knowledge compresses sources around questions and keeps only what answers them. When a knowledge base grows, ask the Agent to reorganize its directories and titles. See [Evidence Chains and Index First]() and [Knowledge for Agents](). ## How is a knowledge package different from an LLM Wiki? A knowledge package is a container; it does not prescribe how content is written. Context ships default Indexers and writing patterns, and a team can customize its own production skills and the skills a package hands to Agents. Compared with an LLM Wiki that has only pages, a package also carries an index, evidence chains and an Agent-facing query entry. Iterations of the knowledge base maintain these directories, so nobody syncs them by hand. See [Packages and Sites](). ## The update process looks long. What does a maintainer actually handle? Only review. Committing the Context knowledge workspace, building the package and publishing the site run quietly by default; the maintainer is interrupted only for the Diff review, a permission problem, or an objection. Once the Diff report is reviewed on the website, the process continues on its own. --- ## Sources - note:20261012/faq.md · faq.md L5–L7 - note:20261012/faq.md · faq.md L9–L16 - note:20261012/faq.md · faq.md L18–L20 - note:20261012/faq.md · faq.md L22–L24 --- ## Code Repositories # Code Repositories A registered repository is a **source boundary**: the code the Agent may read and cite while writing knowledge. Registration pins the repository to one commit, so every citation points at code that will not shift underneath it. It does not decide what to write; that comes later, in the work-start report. ```mermaid flowchart LR you["You name a local checkout"] --> agent["Agent resolves the path"] agent --> cli["CLI reads origin and HEAD"] cli --> reg["Registered source
date/module @ commit"] reg --> plan["Planning and writing
read this commit only"] ``` ## Ask the Agent Name the checkout and the part of it the readers need. Plain language is enough: ```text Use ../payments-service as a code source. Readers need the refund flow; skip the legacy admin module. ``` When your request already names exact local modules, the Agent does not ask you to repeat them or to supply remote URLs: it resolves each name to one local directory and lets the CLI read that checkout's Git root, `origin` and current commit. It asks only when a name is ambiguous, nothing matches, or picking a match would widen the scope you gave. ## What gets recorded The Agent registers the module with a command like this: ```bash context source add repo 20261012 --module payments-service --local ../payments-service --configure ``` | Option | Meaning | | --- | --- | | `20261012` | The capture batch date. Several repositories and documents can share one date. | | `--module` | Required. The concrete repository or package name. | | `--local` | Local checkout path; may point at a monorepo subdirectory. | | `--remote` / `--ref` | Remote URL and pinned commit. Inferred from the local `origin` and `HEAD` when omitted. | | `--configure` | Also selects the source in a simple `src/index.ts`. It never captures anything. | The source is addressed as `date/module`, for example `20261012/payments-service`. That name appears in source references; stable code knowledge paths use the module name without the date. Code sources need no capture phase: the Agent reads the checkout at the pinned commit. ## Monorepos: pick packages, not the whole tree Context never widens a boundary from the current directory, package names or Git remotes. When a monorepo has several package boundaries, the Agent shows their paths and asks which ones should become sources. Point `--local` at each chosen package. Filtering files inside a source cannot select a monorepo package, so choose the packages explicitly. Discuss obsolete or unrelated areas before indexing them — unnecessary code costs reading time and tokens — but do not drop a directory merely because its name looks old. ## How the code is read Parsing is a detail of the selected Indexer, not something you configure per repository. The Indexer inspects languages, manifests, entries, routes and contracts, then uses the smallest parser set that answers the reader's questions. Community parsers cover TypeScript/JavaScript, Go, Rush monorepos, Thrift, Protobuf, Markdown/MDX, API contracts, stylesheets and SQL schemas. See [Code Extraction]() for how parser facts become pages. ## Checkouts on another machine Git stores only the recovery recipe for a repository source: remote, pinned commit and module paths. It does not store the checkout. When a Context knowledge workspace is opened elsewhere and a task needs that code, the Agent offers three choices: 1. point it at an existing local checkout; 2. name a bounded directory it may scan for a matching checkout; or 3. allow Context to clone the registered repository into `.tmp/repo/`. A recovery clone always uses the registered commit, so existing knowledge stays reproducible. In ordinary mode the Agent asks before cloning; it never scans an unspecified disk root or substitutes another branch or nearby repository. ## When the code moves on Registration keeps its commit until you decide otherwise. To bring knowledge up to a newer commit, ask for an update: the Agent prepares the new version, compares it with what existing pages cite, and asks which pages need changes. The processed baseline advances only after the selected revisions are approved and built. See [Updating Knowledge](). --- ## Sources - [context/packages/context-cli/context-workflow/resources/procedures/source-boundary.md L15–L17 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L56–L58 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/dialogue/source-boundary.md L31–L39 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-boundary.md L39–L43 · 3b0ce0a]() - [context/packages/context-cli/src/project/sourceCommands.ts L362–L369 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/dialogue/source-boundary.md L20–L29 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L100–L103 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-boundary.md L28–L37 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/dialogue/source-boundary.md L41–L45 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L57–L60 · 3b0ce0a]() - [context/packages/context/docs/reference/code-extractors.md L3–L29 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/repository-source-recovery.md L9–L34 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-boundary.md L85–L89 · 3b0ce0a]() - [context/packages/context-cli/README.md L322–L340 · 3b0ce0a]() --- ## Document Directories # Document Directories Use a file source when the material is local Markdown: one file, several files, or a documentation folder. Unlike a code repository, a document source is **captured**: Context takes a reproducible snapshot under `sources/file/`, and pages cite that snapshot rather than the live folder. ```mermaid flowchart LR reg["Register
date/module + include"] --> decl["Declare captureFile
in src/index.ts"] decl --> cap["Capture
snapshot under sources/"] cap --> write["Plan and write
cite the snapshot"] ``` ## Ask the Agent Say which documents to ingest, not just which folder you happen to be in: ```text Ingest ../docs/user-guide as product documentation. Only the getting-started and billing chapters. ``` Run instructions, handbooks, plans or batch lists you hand the Agent are treated as task guidance, not as sources, unless you explicitly ask to ingest them. If the documents to capture are unclear, the Agent asks once instead of capturing the instructions themselves. ## Register and declare capture ```bash context source add file 20261012 --module user-guide --local ../docs/user-guide \ --include "getting-started/**" --include "billing/**" --configure ``` | Option | Meaning | | --- | --- | | `--local` | Required. A local Markdown directory or file, used as the refresh location. | | `--module` | Document module name; derived from `--local` when omitted. | | `--include` | Markdown include glob relative to `--local`; repeat it for several patterns. | | `--include-list` | A file of include globs, one per line; blank lines and `#` comments are ignored. | | `--configure` | Also declares the source and a default capture phase in a simple `src/index.ts`. It does not capture. | Registration reads no content. With `--configure`, the project gains a declaration like: ```ts const docs = source("20261012/user-guide", { type: "file" }); export default defineProject({ sources: [docs], phases: [captureFile({ source: docs })], }); ``` If `src/index.ts` already has custom entries, the configuration result is `manual` and the Agent makes a focused edit instead of retrying. ## Capture Capture is an external read, so it needs your permission in the current conversation. Asking to capture, ingest or read the named documents grants it; merely mentioning them or asking to register does not. The Agent then runs the capture command returned by the workflow, reports the outcome and continues until every document in the batch is done. Capture creates the snapshot; it does not classify, summarize or approve anything. The CLI owns normalization, hashes and manifests, and the Agent never edits a captured snapshot by hand. ## Documentation sites (MDX) Default capture handles `.md`. If the folder turns out to be a documentation site — `.mdx` pages, `_meta.json`, sidebars or a docs config — the Agent stops and confirms before changing the configuration. For MDX sites that use `_meta.json`, the capture phase gains the MDX processor: ```ts captureFile({ source: docs, processor: mdxJsonDocs() }); ``` The processor keeps route metadata and static component text as evidence. If a page is only a shell that mounts runtime-rendered content, the Agent tells you and asks for the rendered site or its data source instead of inventing the body. ## When the documents change Pages keep citing the snapshot they were written from. When the folder changes, ask for an update: the Agent captures the new version and asks which pages need changes. See [Updating Knowledge](). --- ## Sources - [context/packages/context-cli/context-workflow/resources/procedures/document-capture.md L9–L10 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-capture-detailed.md L159–L162 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-capture-detailed.md L157–L157 · 3b0ce0a]() - [context/packages/context-cli/src/project/sourceCommands.ts L397–L404 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L68–L98 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-capture-detailed.md L149–L155 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/document-capture.md L18–L28 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/document-capture.md L45–L61 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-capture-detailed.md L165–L179 · 3b0ce0a]() - [context/packages/context/docs/reference/project-api.md L73–L77 · 3b0ce0a]() - [context/packages/context-cli/README.md L322–L324 · 3b0ce0a]() --- ## Lark Documents # Lark Documents A Lark source is a remote document that Context captures into a local snapshot, together with the evidence embedded in it: images, attachments, sheets, Base tables, whiteboards and synced blocks. Pages then cite the snapshot. The Agent never reconstructs resource bytes or substitutes a summary for them; capture handles resources mechanically. ```mermaid flowchart LR url["Document or Wiki URL"] --> reg["Register
date/module"] reg --> cap["Capture body and resources
one read identity"] cap --> snap["Snapshot
sources/lark/date/"] snap --> pages["Approved pages
knowledge/assets/"] pages --> pkg["Package
others/assets/"] ``` ## Register a document Pass the document or Wiki URL directly; capture fetches the title with the body, so no separate lookup is needed: ```bash context source add lark 20261012 --module handbook \ --url https://example.larkoffice.com/wiki/example-token --configure ``` `--doc-token` and `--wiki-token` accept an identity token instead of a URL, and `--title` records a title you already know. Register every requested document under the same date. For several documents with the same settings, the Agent declares capture once from the source registry instead of repeating a phase per document; independent documents do not mean independent articles. For a whole Wiki subtree, the Agent can first run `context source discover lark ` to save the directory tree and page identities without reading bodies, so you can choose which pages to register. ## Read identity Capture reads the body and every resource under **one** identity. `CONTEXT_LARK_IDENTITY=user|bot` selects it, and the default is `user`. Export it in every shell that runs Context commands; a setting in a Bot prompt is not an environment variable. - **User** reads only as the current user. - **Bot** may fall back once to the current user when reading the body fails on credentials, scope or access. The fallback restarts the whole body, so pages from two identities are never combined. Once the body is read, all resources use that identity. A resource failure never asks for another identity's credentials, and network, rate-limit and format errors do not switch identity. ## What happens to embedded resources | Resource | Captured as | | --- | --- | | Image | The original; if download is denied, one same-identity preview, marked as a preview | | Attachment | The original file, linked from the Markdown | | Sheet | A Markdown table plus a CSV snapshot | | Base | The selected table or view as a Markdown table plus a JSON snapshot | | Whiteboard, diagram | A readable preview plus the raw structured export | | Synced block | The source block's body plus a Markdown evidence snapshot | | Bookmark, sub-document, chat, embed | A stable navigation reference | | Video | A reference; downloaded only with `resources.videos: "bundle"` | A required resource that cannot be obtained stops capture. Two cases are recorded and continue with a warning: a whiteboard or diagram the API confirms was deleted, and an explicit permission denial for one embedded resource. Both leave a visible "unavailable resource" notice; neither is reported as downloaded. ## Image choices for large tasks Image handling for a task is decided once, not per document. The task instruction `DOCUMENT_IMAGE_CAPTURE` accepts `ON` (include images), `OFF` (references only) or a document-count threshold, default `10`: above it, bodies are captured with image references only. When a task would acquire more than 30 distinct images without a policy, the work-start report asks you to choose between intelligent conversion and inclusion (recommended), including all images, or placeholders only. To fix the choice in the project instead: ```ts captureLark({ source: handbook, resources: { images: "reference-only" } }); captureLark({ source: handbook, resources: { gifs: "reference-only" } }); ``` ## Where the files live ```text sources/lark// ├── .md # captured body ├── manifest.json # compact inventory with hashes └── assets// ├── source.xml # structured source ├── capture-report.json # fidelity and resource handling └── materialized/** # downloaded files and exports knowledge/assets//. # only resources approved pages use ``` Source assets are part of the evidence snapshot, so keep them in Git; repositories with many binaries can store `materialized/` in Git LFS. Keep the Context knowledge workspace private when the documents or screenshots are access-controlled. ## Reusing a fetch you already have If research already fetched a document, `context source fetch lark --output ` saves a portable snapshot before any knowledge workspace exists. After registering the matching source, `context source import` with `snapshot_dir` imports it without reading the document again. Import checks integrity and keeps the original capture time; it does not make the snapshot any fresher. --- ## Sources - [context/packages/context/docs/guides/lark-resources.md L3–L9 · 3b0ce0a]() - [context/packages/context/docs/guides/lark-resources.md L122–L153 · 3b0ce0a]() - [context/packages/context-cli/src/project/sourceCommands.ts L433–L441 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-capture-detailed.md L180–L196 · 3b0ce0a]() - [context/packages/context/docs/guides/source-batches.md L49–L64 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/document-capture.md L66–L75 · 3b0ce0a]() - [context/packages/context/docs/guides/lark-resources.md L98–L103 · 3b0ce0a]() - [context/packages/context/docs/guides/lark-resources.md L61–L73 · 3b0ce0a]() - [context/packages/context/docs/guides/lark-resources.md L75–L90 · 3b0ce0a]() - [context/packages/context/docs/guides/lark-resources.md L201–L222 · 3b0ce0a]() - [context/packages/context/docs/guides/lark-resources.md L225–L237 · 3b0ce0a]() - [context/packages/context/docs/guides/lark-resources.md L120–L144 · 3b0ce0a]() - [context/packages/context/docs/guides/lark-resources.md L159–L163 · 3b0ce0a]() - [context/packages/context/docs/guides/lark-resources.md L11–L50 · 3b0ce0a]() --- ## Notes # Notes A note is Markdown you supply directly: an excerpt from a document Context cannot read, a summary of a decision, a field observation, a checklist from experience. Context saves it as a source under `sources/note/YYYYMMDD/topic.md`. There is no registry and no capture phase — the saved file *is* the evidence that pages cite. Use a note when the material is text you already hold. Use a [session summary]() when it comes from an Agent conversation, and a [document source]() or [Lark source]() when Context can capture the original itself. ## Prepare the content A note may hold original text, selected verbatim excerpts, a summary, or a mix. No fixed template is required, but when both originals and a summary are present, separate them with headings or prose, and label any summary as a summary rather than a transcript. - Keep qualifications, exceptions, disagreements and open questions that affect the conclusion. - State where the material came from and what was left out, when the omission matters. - Quote only actual input; do not invent links, speakers, dates or confirmations. - A link in a note does not mean its target was read. Pages cite the note as saved, so leave out anything the eventual readers must not see before you save it. ## Save and select it Ask the Agent in plain language: ```text Save these release-process notes as a Context note, then use them for a page on hotfix releases. ``` The Agent saves the body with `context source import`. Saving alone starts no knowledge work. To use the note in a production task, the Agent adds its typed reference to `src/index.ts`, keeping existing sources and phases: ```ts source("20261012/release-process.md", { type: "note" }); ``` A note that only supports an existing page does not need this: it joins that page's reading scope during a revision. ## How notes become knowledge The Agent integrates what is useful into explanations, rules or steps for the reader; it does not copy the note wholesale or turn proposals into facts. A short exact passage is quoted only when its wording matters. Citations point at the stored note, never at an original the Agent could not read. ## Correcting a note Two different problems, two different fixes: | Problem | Fix | | --- | --- | | The note misrepresents the material | Correct the note itself through `source import`, passing its current `base_digest`. | | The note is right but a page is misleading | Revise only that page and send it through Review. | Approving knowledge never changes or removes the note. To rename one, `context source rename --name ` previews the change and then updates existing references safely. --- ## Sources - [context/packages/context/docs/guides/note.md L19–L21 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L71–L74 · 3b0ce0a]() - [context/packages/context/docs/guides/note.md L6–L17 · 3b0ce0a]() - [context/packages/context/docs/guides/note.md L29–L30 · 3b0ce0a]() - [context/packages/context/docs/guides/note.md L19–L25 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-boundary.md L49–L59 · 3b0ce0a]() - [context/packages/context/docs/guides/note.md L27–L30 · 3b0ce0a]() - [context/packages/context/docs/guides/note.md L32–L37 · 3b0ce0a]() - [context/packages/context-cli/README.md L331–L332 · 3b0ce0a]() --- ## Session Summaries # Session Summaries Design discussions, troubleshooting sessions and requirement conversations with an Agent often settle things that no document records. A **sessions** source keeps a bounded summary of such a conversation so that pages can cite it. It is a summary, never the transcript: Context does not scan your Agent's history or ingest a whole conversation. ## What to keep The Agent (or whoever supplies the summary) prepares it before import: | Keep | Drop | | --- | --- | | The problem, confirmed decisions and the reasons that matter | Repetitive turns | | Constraints and open questions | Tool logs | | Whether each statement was proposed, agreed, implemented or verified | Abandoned attempts, unless they explain a current limit | If only a supplied summary exists, the source says so. Speakers, dates and approvals are never made up, and a conversation with nothing reusable can stay out of the Context knowledge workspace. ## Save it Ask at the end of the conversation: ```text Summarize what we decided about retry limits and save it as a Context session summary, linked to the merge request we just opened. ``` The Agent imports a payload like this with `context source import --input `: ```yaml type: sessions name: 20261012/retry-limits.md markdown: | # Retry limits for payment callbacks ... changes: - mr: https://git.example.org/team/payments/merge_requests/42 ``` Use the actual conversation date, or the collection date if unknown, and keep the same name for later corrections. The optional `changes` field links one or more code changes: each row takes a full `commit` SHA, an `mr` URL, or both, plus an optional `repository`. Omit it for a discussion with no code. A link records an association; it does not prove the change was merged or tested, and it does not authorize fetching the code. ## How it is used Saving starts no knowledge work. A summary that opens a new reader topic goes through the normal structure review and writing; one that only supports an existing page joins that page's reading scope while the page keeps its primary source. Either way, knowledge turns the conclusions into answers, explanations and procedures — not a meeting recap — and `knowledge/structure.yaml` records which sections cite the summary. See [Capturing from Conversations]() for the end-to-end flow after a Q&A. ## Corrections Correct a faulty summary by importing it again with its current `base_digest`; existing `changes` are kept unless you remove them, and `changes: []` clears them. If the summary is accurate but a page is wrong, revise the page instead. Neither saving a summary nor approving knowledge approves the upstream code change it mentions. --- ## Sources - [context/packages/context/docs/guides/sessions.md L3–L8 · 3b0ce0a]() - [context/packages/context/docs/guides/sessions.md L10–L15 · 3b0ce0a]() - [context/packages/context/docs/guides/sessions.md L17–L20 · 3b0ce0a]() - [context/packages/context/docs/guides/sessions.md L22–L31 · 3b0ce0a]() - [context/packages/context/docs/guides/sessions.md L38–L44 · 3b0ce0a]() - [context/packages/context/docs/guides/sessions.md L48–L49 · 3b0ce0a]() - [context/packages/context/docs/guides/sessions.md L32–L36 · 3b0ce0a]() - [context/packages/context/docs/guides/sessions.md L46–L50 · 3b0ce0a]() --- ## Source Batches # Source Batches When a task involves many sources — a dozen services, a folder of handbooks, a Wiki section — register them as one batch rather than one command at a time. A batch is one serial registry write under one date, so sources do not race each other, and with checkpoints a long registration survives interruption. Registering many sources is not the same as producing a large knowledge base. For work spanning more than 30 documents or substantive investigation of two or more repositories, the Agent first plans the project in stages; see [Large Projects](). ## The payload ```yaml sources: - type: repo module: billing-service local: ../billing-service - type: file local: ../docs/user-guide.md - type: lark url: https://example.larkoffice.com/wiki/example-token ``` ```bash context source add batch 20261012 --input .tmp/sources.yaml --configure --format json ``` - `repo.module` is required; `file` and `lark` modules are derived from the path or URL when omitted, and duplicates in the batch are rejected. - `repo.local` is resolved from the Context project root. A valid checkout supplies its remote and commit, so `remote`/`ref` are needed only when they cannot be read. - `--configure` also declares the sources and default capture phases in a simple `src/index.ts`. Without it, the batch only registers. ## Long batches: checkpoints and resume ```mermaid flowchart LR start["add batch
--checkpoint --progress"] --> run["Register in chunks"] run -->|interrupted| status["batch-status job-id"] status --> resume["add batch --resume job-id"] resume -->|revalidate every item| run run --> receipt["Final receipt
registered / total"] ``` ```bash context source add batch 20261012 --input .tmp/sources.yaml --checkpoint --progress --format json context source batch-status --format json context source add batch --resume --progress --format json ``` The saved input stays under `.tmp/context-runtime/source-batches/`, so resuming does not need the original file. Resume replays and revalidates every item against the current registry; the saved cursor is only a hint. Do not combine `--resume` with a date or a new input. Progress goes to stderr as bounded JSON; stdout keeps the final receipt. ## Partial failure and locks A batch keeps what succeeded: entries before a failed item stay registered, and the error names the completed entries and the failed position. Lark entries are validated in memory and committed in bounded atomic chunks. Only one writer runs in a Context knowledge workspace at a time. Wait for an active command rather than starting another or deleting its lock. If a forced stop leaves a stale lock, run `context task recover --format json` before resuming. --- ## Sources - [context/packages/context-cli/context-workflow/resources/procedures/source-boundary.md L67–L70 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L1–L4 · 3b0ce0a]() - [context/packages/context-cli/src/project/sourceCommands.ts L292–L320 · 3b0ce0a]() - [context/packages/context/docs/guides/source-batches.md L7–L29 · 3b0ce0a]() - [context/packages/context/docs/guides/source-batches.md L31–L34 · 3b0ce0a]() - [context/packages/context/docs/guides/source-batches.md L42–L47 · 3b0ce0a]() --- ## External Entrances # External Entrances Some content belongs next to your knowledge without becoming part of it: a team's engineering handbook on another site, a Skill published in another repository. `imports.yaml` at the root of the Context knowledge workspace declares such **entrances**. Context never downloads, installs or captures them; it only knows where they are so pages and packages can link to them. | You need | Use | | --- | --- | | A link readers can follow | An import in `imports.yaml` | | A conclusion that must be traceable and tracked for change | A registered, captured source | | Docs or Skills in this same repository | [Same-Repository Docs]() | ## Declare an entrance Ask the Agent to keep a lasting association; quick lookups during a question do not register anything. ```yaml protocol: context.imports/v1 imports: engineering-guide: kind: knowledge url: https://docs.example.org/engineering/ description: Engineering conventions release-check: kind: skill url: https://github.com/example/skills/tree/v1/skills/release-check path: skills/release-check version: v1 ``` The stable ID and `url` are required; `kind`, `format`, `title`, `description`, `path` and `version` are optional free-form hints. URLs must be HTTP(S) without credentials — never put access tokens in query strings. Use a new ID when the target's identity changes. ## Link to it from a page ```markdown See the [Engineering guide](context:import/engineering-guide). ``` Build turns this into the declared URL as-is; it never guesses provider URLs, appends `path` or rewrites the version. An unknown ID keeps the label as plain text and produces a build warning. To give readers a directory of all entrances, enable the imports page on the package; `importsPage: { site: true }` also adds it to the website navigation: ```ts kbPackage({ name: "handbook", template: { path: "src/package-templates/kb" }, importsPage: true }); ``` The page lists declared metadata only. Check that every entrance suits the audience before exposing private ones. ## Entrances are not evidence An import adds nothing to `knowledge/structure.yaml` references and has no citation format. When asked to check imports, the Agent compares current versions with `version` using its own authorized tools; a target it cannot reach is reported as "version unknown", never as a change. The CLI itself never contacts providers. --- ## Sources - [context/packages/context/docs/guides/imports.md L3–L7 · 3b0ce0a]() - [context/packages/context/docs/guides/imports.md L39–L43 · 3b0ce0a]() - [context/packages/context/docs/guides/imports.md L3–L31 · 3b0ce0a]() - [context/packages/context/docs/guides/imports.md L52–L59 · 3b0ce0a]() - [context/packages/context/docs/guides/imports.md L61–L80 · 3b0ce0a]() - [context/packages/context/docs/guides/imports.md L39–L48 · 3b0ce0a]() --- ## Same-Repository Docs # Same-Repository Docs When the Context knowledge workspace sits inside a project repository, that repository usually already has documentation and Agent Skills. They should stay where they are and keep being edited there. `repo-content.yaml` registers them as **same-repository content**: Context links to the originals instead of copying their bodies into knowledge or source snapshots. ```mermaid flowchart LR orig["docs/ and .agents/skills/
the only originals"] --> links["repo-content/
relative symlinks"] orig --> ev["Evidence
repo-content:docs@commit"] links --> pages["Pages link with
context:repo/..."] pages --> pkg["Optional entrance page
in the package or site"] ``` Use the `context-repo-content` Skill to choose and edit these entries; it does not start knowledge production. ## Register At the knowledge workspace root: ```yaml protocol: context.repo-content/v1 entries: docs: kind: docs path: docs tools: kind: skills path: .agents/skills ``` Paths are relative to the Git root, not the knowledge workspace. Kinds are `docs`, `document`, `skills` and `skill`. Optional `group` adds one module level, `mount` overrides the default mount name, and `exclude` globs skip files inside an entry (they are not access control). Overlapping entries, targets outside the repository, nested repositories and cycles are rejected. `context source ensure repo-content --format json` maintains the relative symlinks under `repo-content/`; `context status` reports problems without repairing them. Ordinary files are never overwritten, and no Git configuration or index changes. ## Link and cite A page links to an original with `[Guide](context:repo/docs/guide.md)`; build turns it into an upstream link when one is available, otherwise a plain location. Evidence records `repo-content:docs@` with the real path, line range and digest; uncommitted text is recorded as `+worktree`. ## Optional entrance page ```ts kbPackage({ name: "project-kb", template: { path: "src/package-templates/kb" }, repoContentPage: true }); ``` This projects each group's README and the Skill names and descriptions into `wikis/repo-content.md`; it does not copy all docs or Skill scripts. `{ site: true }` adds the entrance to a configured website. Review README sensitivity before exposing it. ## When something is wrong - An invalid `repo-content.yaml` is reported by `status`, and `context build` stops before replacing existing outputs. Correct the file rather than rerunning `ensure`. - `ensure` is suggested only for missing or misdirected symlinks. - Other repositories and externally installed Skills are not same-repository content; declare them as [External Entrances](). Registering an entrance does not authorize installing, running or publishing anything. --- ## Sources - [context/packages/context/docs/guides/repo-content.md L3–L5 · 3b0ce0a]() - [context/plugins/context/skills/context-repo-content/SKILL.md L1–L4 · 3b0ce0a]() - [context/packages/context/docs/guides/repo-content.md L7–L31 · 3b0ce0a]() - [context/packages/context/docs/guides/repo-content.md L43–L48 · 3b0ce0a]() - [context/packages/context/docs/guides/repo-content.md L50–L67 · 3b0ce0a]() - [context/packages/context/docs/guides/repo-content.md L33–L41 · 3b0ce0a]() - [context/packages/context/docs/guides/repo-content.md L69–L71 · 3b0ce0a]() --- ## Start Reports # Start Reports Before the Agent writes pages in bulk, it shows you a **work-start report**: what it found in the sources, which articles it plans, and how they will be organized. This is your cheapest moment to steer. Changing a plan costs a sentence; changing thirty written pages costs a revision round. ```mermaid flowchart LR talk["Describe the goal
and sources"] --> inv["Agent registers sources
and investigates lightly"] inv --> rep["Work-start report
.tmp/work-start-report.md"] rep -->|change scope| inv rep -->|confirm| write["Bulk writing"] write --> review["Knowledge Review"] ``` ## How you get there Start by talking freely: what the knowledge should cover, where it comes from (repositories, modules, document links) and what form you expect — a package for Agents, a site, or both. The Agent researches representative material and asks only about gaps that would change the scope or the output. It does not run a fixed questionnaire, and fully managed mode does not authorize guessing your answers. For a first build, the Agent registers and captures the confirmed sources, takes a code skeleton and document outlines, and only then writes the report. It does not deep-read every implementation first; broad scope calls for a horizontal survey. ## What the report contains The report is written in your language, under `.tmp/`, and adapts to the task. Typical sections: | Section | What to look for | | --- | --- | | Readers, goal and current delivery | Who uses the knowledge, the whole outcome, and what this first batch delivers | | What the materials support | Checked topics versus provisional ones, and what is still uninvestigated | | Articles and batches | Each reader topic, new or existing article, supporting sources, and its depth: an entry point, an explanation or a procedure | | Reading organization | Proposed navigation; for a new site, a sketch of top-level groups, a representative menu and page outlines | | Indexing guidance | Which Indexer Skills are used on which sources | | Decisions and gaps | Confirmed choices versus recommendations, conflicts, exclusions and unchecked coverage | Material counts, article counts and investigated scope are kept separate, and unknown totals are never shown as zero. A first batch is not presented as the whole goal. ## Answering it Reply in plain language: confirm, or say what to change. Requested changes are made before the Agent records your confirmation. You are asked when the scope is complex and touches more than five articles, or when a separate decision is open — most often a **top-level navigation change**, which always shows a before/after tree and needs its own explicit answer. When a task exceeds 30 distinct images without a policy, the report also asks how to handle them. Small bounded tasks — a few documents, one module, a revision — get a short proposal instead, and a specific earlier request can already cover it. Silence, elapsed time, questions and objections are never approval. Approval of an unchanged plan carries across batches and retries; material changes or scope expansion bring the plan back to you. ## Large projects For work spanning more than 30 source documents or substantive investigation of two or more repositories, the `context-plan` Skill first produces a project PLAN that splits the work into stages. Each stage then gets its own work-start report within the approved plan. See [Large Projects](). --- ## Sources - [context/packages/context-cli/context-workflow/resources/procedures/work-start-report.md L7–L16 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L107–L112 · 3b0ce0a]() - [context/packages/context/docs/guides/agent-dialogue.md L68–L74 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/work-start-report.md L18–L46 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/templates/work-start-report.md L9–L70 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/work-start-report.md L55–L66 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/work-start-report.md L124–L157 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/work-start-report.md L85–L95 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/work-start-report.md L47–L53 · 3b0ce0a]() - [context/packages/context/docs/guides/agent-guide.md L6–L15 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L1–L4 · 3b0ce0a]() --- ## Working with Agents # Working with Agents You drive Context through your Agent, not through the CLI. Invoke `/c4a:context` (Cursor: `/c4a-context`), describe the knowledge in normal language, and answer the decisions it brings back. The Agent reads the workflow's current Route from the CLI, runs the returned commands and writes the pages; the CLI validates sources and page identities, derives paths and owns Review, `knowledge/` and `dist/`. Ordinary coding or design conversations never start Context on their own; invoke it explicitly, or continue a conversation where it is already active. ## Brief it well The more the first message settles, the fewer questions follow. Cover: - **Readers and questions** — who will use the knowledge and what they need to answer. - **Sources** — repositories, modules, document folders or links, and what to skip. - **Output** — a package for Agents, a website, or both, and the language. ```text /c4a:context Initialize a Context knowledge workspace in ./kb and build knowledge for ../billing-service and ../docs/billing. Readers are on-call engineers who need to diagnose failed invoices. Skip the legacy-export module. Investigate first, then give me the work-start report. ``` Answers you have already given are reused for the rest of the task, not asked again at every step. ## What it asks you, and what it decides | You decide | The Agent decides | | --- | --- | | Which sources and modules are in scope | Which Indexer Skills to use | | Which readers and questions matter | Topics, page boundaries and organization within the approved plan | | Whether two subjects are the same knowledge owner | Wording and structure of each page | | Whether a custom Indexer or executable extension is acceptable | Mechanical steps returned by the Route | | Whether the outline and the candidate pages are approved | — | Even in fully managed mode the Agent asks when missing purpose or scope would change the outcome. Before indexing a large boundary it identifies obsolete or irrelevant areas with you from the actual material, rather than guessing from names. ## Following progress Production is the long phase — roughly a minute per article task on average. The Agent reports progress against the task total, and you can ask for a local preview at any time. Transition reports stay short: what changed, the current state and the next decision. Look at the work-start report and the first changed pages early. If something is off — tone, a counterexample, a style rule — say so. The earlier a correction lands, the better the final result. ## Adding material or changing course Say it in the conversation: ```text Add ../docs/refunds to the sources, re-plan the affected part and give me a new work-start report. ``` New material within the confirmed purpose becomes a plan amendment that keeps completed work; a new purpose or source still goes back through your confirmation. To correct a page, see [Revising a Page](). ## Interruptions and resuming Workflow state lives in the knowledge workspace, not in the conversation. After a closed session or a crash, open a new conversation in the same knowledge workspace and invoke `/c4a:context`; the Agent reads the current Route and continues. Accepted tasks are never resubmitted, and deleting temporary runtime files is not a way to restart — it does not authorize replaying accepted work. ## Several Agents in parallel When your host can coordinate child Agents, the work can be split across them. The CLI decides which batches are eligible; each worker writes only its assigned drafts, and one coordinator submits everything to Context. Without that capability the Agent uses a single batch — no simulated workers. Parallelism never waives a decision that is yours. ## Git and publishing Completing Context work does not authorize Git operations. The Agent stages, commits, pushes, publishes or deploys only when you ask. --- ## Sources - [context/plugins/context/README.md L19–L26 · 3b0ce0a]() - [context/packages/context/docs/guides/agent-guide.md L71–L74 · 3b0ce0a]() - [context/plugins/context/README.md L30–L31 · 3b0ce0a]() - note:20261012/usage-practices.md · usage-practices.md L7–L7 - note:20261012/usage-practices.md · usage-practices.md L66–L66 - [context/packages/context/docs/guides/agent-guide.md L65–L66 · 3b0ce0a]() - [context/packages/context/docs/guides/agent-guide.md L54–L74 · 3b0ce0a]() - note:20261012/usage-practices.md · usage-practices.md L8–L8 - note:20261012/usage-practices.md · usage-practices.md L14–L14 - [context/packages/context/docs/guides/agent-dialogue.md L45–L46 · 3b0ce0a]() - note:20261012/usage-practices.md · usage-practices.md L67–L67 - [context/packages/context-cli/context-workflow/resources/procedures/production-stage-files.md L55–L59 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L140–L153 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/parallel-agent-batch.md L7–L19 · 3b0ce0a]() - [context/packages/context/docs/guides/agent-guide.md L178–L179 · 3b0ce0a]() --- ## Managed Mode and Review Policy # Managed Mode and Review Policy The workflow pauses at **Gates**: decisions that belong to a person. How the Agent handles each one is governed by a named **policy switch**. In ordinary mode, the Agent applies each switch's ordinary default. In **fully managed mode**, a few switches change their default so the run proceeds on its own — but some decisions never delegate, so even a fully managed run stops there. Three layers can change a switch. Later layers win: ```mermaid flowchart LR ord["Ordinary default"] --> man["Fully managed default"] man --> bot["Custom Bot setting"] bot --> task["Task-scoped CONTEXT_RUN_POLICY
(review switches only)"] task --> eff["Effective policy
for this task"] ``` ## All policy switches The `context.gate.*` IDs are stable Agent policy switches defined by the `context` Skill. They are not CLI flags or environment variables, and changing one never changes the Route's own gate ID, command or payload. | Switch | What it decides | Ordinary default | Fully managed default | | --- | --- | --- | --- | | `context.gate.plan_review` | Approving a project PLAN from `context-plan` | Present the PLAN and ask | Same, unless delegated for this task | | `context.gate.production_entry` | Whether the request is a Context production task | Ask only if intent is unclear | Same | | `context.gate.workspace_initialize_nonempty` | Initializing a Context knowledge workspace in a directory that is not empty | Proceed if you already chose this target; otherwise ask | Same | | `context.gate.work_start_scope` | Confirming the work-start report | Present the report; ask only if the scope is complex **and** affects more than five new or revised articles | Same | | `context.gate.source_boundary` | Which sources and modules are in scope | Use your selected scope; ask only for missing boundaries | Same | | `context.gate.source_read` | Reading a source you supplied | Your request authorizes it; no second question | Same | | `context.gate.repository_clone` | Cloning a missing repository | Ask before cloning | Restore within the selected scope without asking | | `context.gate.indexer_extra_action` | Extra Indexer operations | Ask only if one blocks the result and no alternative works | Resolve eligible operations without asking | | `context.gate.image_handling` | Handling images in an image-heavy task | Ask once above 30 distinct images | Same | | `context.gate.top_level_directory` | Adding, renaming or removing a top-level directory | Confirm the concrete structure | Same | | `context.gate.knowledge_review` | Approving the candidate batch | Ask for a decision on the HTML report | Delegate when the Route permits | | `context.gate.deletion_scope` | Deleting sources or retiring approved pages | No second question within the approved exact scope; ask before anything outside it | Same | | `context.gate.package_output` | How approved knowledge is packaged | Ask | Choose within the requested delivery | | `context.gate.package_template` | Keeping or editing generated package templates | Ask | Choose within the requested delivery | | `context.gate.git_delivery` | Commit, push or merge request | Ask | Same | | `context.gate.publication` | Publishing a package or site | Ask | Same | | `context.gate.remote_target_create` | Creating a remote publishing target | Ask | Same | | `context.gate.workspace_reset_restore` | Clearing the knowledge workspace or restoring history | No second question when target and losses are clear | Same | | `context.gate.exceptional_recovery` | Recovery from an unexpected failure | Ask only for a blocker that prevents the requested result | Same | A decision you already made for the same scope is reused rather than asked again. ## Turning on fully managed mode Ask for it in the conversation, for example *"Run this fully managed and report back."* The Agent then evaluates the workflow with `context status --managed`, and the switches whose fully managed default differs proceed without another question. That authority belongs to the current conversation only. It is never saved in the knowledge workspace or reused in another conversation, it does not widen sources or authorize remote writes, and it never hides a validation or verification failure. Delegated review is real review: the Agent reads the pages, repairs what fails and leaves undecided pages pending. ## Changing defaults for a custom Bot When you build a team Bot or knowledge service on Context, its instance configuration — the trusted instructions in its prompt — can override any switch for every task that Bot runs. For example, a Bot whose reviewers always read the HTML report, and that may package and publish within its configured target, could state: ```text Context policy for this Bot: - context.gate.knowledge_review: ask — always send the HTML review report. - context.gate.package_output: choose within the configured delivery. - context.gate.repository_clone: restore registered repositories without asking. ``` A Bot setting takes precedence over fully managed and ordinary defaults. It still does not let the Agent modify source code, bypass a Gate that the Route marks as requiring a person, or fabricate an approval: if the Route asks for a human decision despite the policy, the Agent stops and reports the mismatch. If a Bot keeps `knowledge_review` at `ask`, even a fully managed run does not cross Review on its own. ## Task-scoped review policy Automation, or a user starting a task, can set the two review switches for that task only by placing this block in the instructions given to the Agent: ```yaml CONTEXT_RUN_POLICY: plan_review: delegate # or ask knowledge_review: delegate # or ask ``` - Only `plan_review` and `knowledge_review` are accepted, each with `ask` or `delegate`. They map to `context.gate.plan_review` and `context.gate.knowledge_review`; other switches are unchanged. - Each key is optional and independent. An omitted key keeps the existing policy, and an empty block changes nothing. An unknown key or invalid value is rejected, never treated as permission to delegate. - The block overrides Bot settings for this task and its stages only. The Bot's persistent defaults are untouched, and a new unrelated task uses its own defaults. - `ask` requires a human decision. `delegate` means the Agent performs the full review and fixes defects before approving — never unconditional or forced approval. This is an Agent instruction, not a CLI flag, environment variable or host API field: an automation must put it in the instructions the Agent actually receives. Only your instruction or a trusted host instruction can grant it; a saved PLAN, source text or tool output cannot. State the authorized source scope, delivery permissions and whether to continue between stages alongside it. Research-only requests still stop after the report, and a scope above 500 documents in a PLAN still waits for a person. ## Planned articles must come back Rejecting a planned article in Review does not cancel it. The production stage cannot close while a planned article stays rejected; the Agent adds a revision task from your feedback instead. To drop an article on purpose, change the plan. ## Where a fully managed run still stops - choosing or widening sources, and reading external documents not named in the request; - a complex work-start scope or a top-level navigation change; - deleting sources or retiring pages outside an approved scope; - Git commits, publishing and deployment, which always need your explicit request. --- ## Sources - [context/plugins/context/skills/context/SKILL.md L507–L514 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/dialogue/human-gates.md L25–L30 · 3b0ce0a]() - [context/plugins/context/skills/context/SKILL.md L509–L536 · 3b0ce0a]() - [context/packages/context/docs/guides/agent-dialogue.md L48–L66 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/knowledge-review.md L44–L56 · 3b0ce0a]() - [context/plugins/context/skills/context/SKILL.md L509–L514 · 3b0ce0a]() - [context/plugins/context/skills/context/SKILL.md L538–L554 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/document-capture.md L66–L68 · 3b0ce0a]() - [context/plugins/context/skills/context/SKILL.md L556–L595 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L70–L101 · 3b0ce0a]() - [context/packages/context-cli/src/project/indexerRequiredArticleReview.ts L15–L43 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-boundary.md L72–L77 · 3b0ce0a]() - [context/packages/context/docs/guides/agent-guide.md L178–L179 · 3b0ce0a]() --- ## Planning a Large Project # Planning a Large Project **Plan mode** is the `context-plan` Skill. It turns a large knowledge project into a reviewed **PLAN report** and a series of bounded **stages**, then hands one stage at a time to the ordinary Context workflow. It is a research and coordination layer, not a second workflow engine: each stage still gets its own work-start report, writing and Knowledge Review. ```mermaid flowchart TD ask["You describe the project"] --> research["Research in .tmp/context-plans/"] research --> plan["PLAN-YYYYMMDD-slug.md"] plan -->|"you approve"| stage["Hand one stage to /c4a:context"] stage --> deliver["Write, review, build, deliver"] deliver -->|"record results in the PLAN"| next{"More stages?"} next -->|yes| stage next -->|no| close["Remove the PLAN in the final commit"] ``` ## When plan mode applies Use it when the scope has **more than 30 source documents, or at least two repositories that need real investigation**, or for a broad update across source versions. Invoke `/c4a:context-plan` (Cursor: `/c4a-context-plan`) explicitly, continue an existing `PLAN-*.md`, or let `/c4a:context` hand over when an authorized task crosses the threshold. Small bounded tasks continue through `/c4a:context` directly. ```text /c4a:context-plan Build a knowledge base for our three payment services and the design folder. Readers are new backend engineers. Plan it in stages and report after each stage. ``` A very large monorepo with several business directions may be better served by one Context knowledge workspace per direction; plan mode does not migrate existing knowledge workspaces on its own. ## What happens during research The Agent works in scratch space under the project's Git root: ```text / PLAN-YYYYMMDD-slug.md .tmp/context-plans/YYYYMMDD-slug/ repos/ # new checkouts, when existing local ones cannot be reused documents/ # retrieved document bodies and resources research/ # inventory and investigation notes stage-inputs/ # the current stage's production handoff ``` It starts from directory metadata, versions and existing coverage, reads representative material and code entry points, and expands only as far as needed to divide the work. Repository `latest` or a branch is resolved to an exact commit before it is used as evidence. Scratch data stays out of Git; the committed PLAN keeps enough source identity to resume if scratch files disappear. Before proposing any article, it reads the knowledge workspace's current organization and the relevant approved pages, and decides per topic: **reuse unchanged**, **revise or extend**, **consolidate**, **add**, or **investigate** an unresolved conflict or access gap. Research is read-only for approved knowledge. For a broad source update, each repository gets its own baseline and target commit, and only the files the approved articles actually cite are compared. The Agent first compares their Git object IDs at both commits — an unchanged ID needs no content read — and, in a partial clone, fetches the objects it still needs in one batch instead of letting each read download files one at a time. A changed file is a candidate for investigation, not proof that an article must be rewritten. ## Reading the PLAN report The report is ordinary Markdown at the Git root. Check each part: | Section | What to check | | --- | --- | | Outcome and current position | The readers and requested outcome are yours; the knowledge workspace and Git root are right | | Research scope and findings | Every source you meant is listed with an exact version; access gaps are named, not hidden | | Existing knowledge and material relationships | Overlaps with pages you already have are reused or revised, not duplicated | | Proposed stages | Each stage has a clear reader outcome, its sources and pinned refs, and sensible prerequisites | | Approval and execution choices | Review policy, reporting, delivery destination and Git process match what you intend | | Current stage handoff | The next stage's sources, targets and decisions to preserve | | Results and synchronization | Actual production, review, delivery, commits and merge state per stage | | Resume notes | The exact position and next action if work is interrupted | To change it, say so — *"split S03 into references and guides"*, *"drop the legacy folder"*. Approving the PLAN does not approve any article, source permission, Git operation or publication. ## Stage size and large scopes | Boundary | Default | | --- | --- | | Source documents per stage | Recommended 30; never more than 50, with a reason recorded for groups above 30 | | New repository investigation | One repository per stage; previously studied repositories may support later stages | | Revision stage | At most 30 target articles | | More than 100 documents | The Agent checks whether bounded research can establish a useful scope and confirms it with you | | More than 500 documents | The whole task pauses until a person narrows the scope or explicitly keeps all of it | Filters you may be offered include selected directories or domains, excluding archives, a recent-update cutoff with its date, or durable documentation only. Nothing is excluded silently. The 500-document pause cannot be resolved by delegation, managed mode or a scheduled trigger. ## Who reviews the PLAN PLAN review asks you by default, including in fully managed mode. A task can hand it to the Agent with `plan_review: delegate` in a [`CONTEXT_RUN_POLICY` block](); the Agent then reads the whole report, checks scope, stage limits, dependencies, overlaps, evidence gaps and delivery settings, and repairs deficiencies before recording its decision. Article review is independent: delegating PLAN review leaves Knowledge Review unchanged. The Agent also settles how you want to hear about progress: once after all stages, or after each stage — and for stage reports, whether to continue automatically or wait for your reply. A research-only request stops at the report; executing the plan needs your explicit go-ahead. ## Running the stages For each stage, the Agent hands the ordinary `context` Skill the PLAN path, stage ID, selected sources and pinned refs, target articles, reuse and revision decisions, and the inherited review, reporting and publishing settings. Production then follows its fresh Route for that scope only. After each stage it records the actual research, production, review, merge and delivery results. A stage that must be published is marked delivered only after publication succeeds — a local build or an open merge request is not publication. Before the next stage, it rechecks the affected knowledge, including pages delivered by earlier stages, so nothing is recreated or overwritten. ## Interruptions and finishing If a session ends, the PLAN keeps the current position and next action. Open a new conversation in the same knowledge workspace and invoke `/c4a:context-plan`; it resumes the current stage instead of repeating the project-wide research. A saved review policy in the PLAN is only a record: on resume, delegation is honored only if trusted task instructions still grant it. When every agreed stage is delivered and integration is resolved, the PLAN is removed in the authorized final commit. Its history stays in Git. For the short overview, see [Large Projects](). --- ## Sources - [context/plugins/context/skills/context-plan/SKILL.md L8–L13 · 3b0ce0a]() - [context/plugins/context/README.md L36–L43 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L15–L26 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L28–L34 · 3b0ce0a]() - [context/plugins/context/README.md L28–L35 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/references/project-planning.md L10–L36 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/references/project-planning.md L109–L152 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/references/project-planning.md L194–L212 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/templates/PLAN.md L1–L118 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L54–L60 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/references/project-planning.md L164–L180 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/references/project-planning.md L46–L73 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/references/project-planning.md L90–L95 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L70–L102 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/references/project-planning.md L228–L247 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L61–L63 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/references/project-planning.md L261–L294 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L113–L125 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/references/project-planning.md L310–L320 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/templates/PLAN.md L112–L118 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L123–L128 · 3b0ce0a]() --- ## Reading Review Reports # Reading Review Reports Nothing the Agent writes becomes knowledge until it passes **Knowledge Review**. The Agent opens one HTML report for the whole current batch of candidate pages and waits for your answer. This report decides both the scope and the quality of what gets published, so it is worth reading with three questions in mind. ## What is in the report | Part | What it shows | | --- | --- | | Change overview | The batch at a glance, with the existing navigation and the expected file tree of the Context knowledge workspace | | Navigation | Where each page will sit; pages without a placement are flagged so the Agent can bind them before asking you | | Pages | Each candidate's title, path, summary and full rendered content, including diagrams and source citations. New pages are marked *New*; changed pages show the changed blocks next to the previous text | | Revision notes | A note box per page; typing in it marks the page for revision | Opening a page marks it READ in your browser. Read counts and notes are local conveniences, not approval. The revision counter lists every page with notes, and **Copy** exports them as plain text with article IDs and titles for pasting into the conversation. ## Three things to judge 1. **Structure** — Are the topics, directories and pages divided the way readers will look for them? 2. **Content** — Do the pages carry the intended purpose, depth and style? Can a reader actually complete the promised task with them? 3. **Scope** — Is related material missing that should be included, or is something here that should be dropped? Citations and placements alone do not prove a page is useful. Spot-check a few pages against their sources, especially defaults, conditions and steps. ## Answering ```mermaid flowchart LR rep["Review report"] --> a{"Your reply"} a -->|approve| ok["Approved into knowledge/"] a -->|notes only| fix["Agent repairs"] fix --> rep2["Updated report"] rep2 --> a a -->|notes + approve after fixing| fix2["Agent repairs and verifies"] fix2 --> ok ``` Reply in the conversation; no review code or magic phrase is needed. | You say | What happens | | --- | --- | | Approve, or continue | The presented batch is approved | | Revision notes only | The Agent repairs those pages, checks the result and shows an updated report | | Notes plus "approve after fixing" | The Agent repairs, verifies the fix, and approves only the agreed pages without asking again | | "Fix it and show me" | Editing only; it waits for your decision on the new report | Silence, an ignored card or read progress is never approval. Rejecting a page leaves it out of this batch; it does not retire an already approved article. ## Taking part of a batch now You can approve the pages that are ready while others go back for repair. Approval alone does not build; to see the approved pages published before the rest are finished, ask for an early delivery. The Agent runs close and build for them, as long as they do not link to pages still pending, and then returns to the remaining review. ## After approval Approval writes the pages to `knowledge/`. Close then rebuilds `knowledge/structure.yaml` and verifies the approved knowledge without rewriting its prose, and build produces the package and site. Nothing is published before approval. --- ## Sources - [context/packages/context-cli/context-workflow/resources/procedures/knowledge-review.md L12–L14 · 3b0ce0a]() - note:20261012/usage-practices.md · usage-practices.md L18–L18 - [context/packages/context-cli/context-workflow/resources/procedures/knowledge-review.md L69–L90 · 3b0ce0a]() - [context/packages/context/docs/guides/agent-guide.md L111–L122 · 3b0ce0a]() - note:20261012/usage-practices.md · usage-practices.md L16–L22 - [context/packages/context-cli/context-workflow/resources/procedures/knowledge-review.md L142–L152 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/dialogue/knowledge-review.md L9–L37 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/knowledge-review.md L92–L94 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/knowledge-review.md L132–L140 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L133–L136 · 3b0ce0a]() --- ## Revising a Page # Revising a Page Revision changes a page without producing it again. It starts from the current text, changes only what your instruction and the sources support, and sends the result back through Review. The page keeps its identity and URL, which makes revision the right tool for wording, structure and factual fixes. ## Two situations | The page is | How to ask | What happens | | --- | --- | --- | | A candidate in the current Review | Write a note in the report, or say it in the conversation | The Agent repairs it within the same batch and shows an updated report | | Already approved | *"Revise ``: ``, keep the source citations"* | The Agent runs `context revise --instruction ""`; the new version enters Review | For an approved page outside the active batch, the revision is queued and runs after the batch by default; `--timing priority` asks for earlier delivery but never skips Review. Several approved pages can be revised together with `context task maintain`. ## What the Agent does - Reads the whole page first and keeps explanations that are still correct, including your earlier contributions. - For a wording-only change, uses the approved text alone; it does not recapture or re-parse the source. - For a changed fact, reads the relevant registered material. A new fact that only exists in your instruction is first saved as a source, such as a [note](). - Edits one section or the whole page. Section edits leave other sections and their citations untouched; a citation change replaces that section's references, which Context re-fingerprints. Before submitting, the Agent can preview the assembled page and the previous text without accepting the edit. ## Moving or renaming a page `context revise --move-to ` revises and moves in one step. The page keeps its article identity and section IDs, its relative links are rebased to the new location, and approval updates incoming Markdown links together — no second copy and no manual deletion. To change only the title or menu position, adjust the knowledge map instead; see [Reorganizing at Scale](). ## Generated reference pages Pages with generated API tables are regenerated, not hand-edited: `--regenerate` rebuilds their program blocks from the current source even when the version has not changed. If the same wrong value survives regeneration, the Agent reports the page, field and source comparison instead of repeating the repair. ## When the source is wrong If the page faithfully reflects a source that is itself wrong, correct the source — recapture it, or correct the note or session summary — and then update the page. If the source is right and the page misleads, revise only the page. --- ## Sources - [context/packages/context-cli/context-workflow/resources/procedures/approved-revision.md L9–L11 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/approved-revision.md L40–L44 · 3b0ce0a]() - [context/packages/context-cli/README.md L345–L357 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/knowledge-review.md L98–L104 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/approved-revision.md L9–L18 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L323–L343 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/approved-revision.md L60–L66 · 3b0ce0a]() - [context/packages/context-cli/README.md L325–L327 · 3b0ce0a]() - [context/packages/context-cli/README.md L347–L349 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/knowledge-review.md L106–L115 · 3b0ce0a]() - [context/packages/context/docs/guides/note.md L32–L35 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L161–L166 · 3b0ce0a]() --- ## Reorganizing at Scale # Reorganizing at Scale First-round titles tend to be abstract, and the first directory structure is rarely ideal. Once the knowledge base has reached a useful size, the Agent can survey what is already approved and propose a more readable, direct structure — and at that point its proposal is better than anything possible during planning, because the content exists. Apply it, then observe for another round. Reorganizing is a series of revisions, far cheaper than producing again. ```text Survey the approved knowledge and propose a more direct directory and title structure. Show me the before/after, then revise once I confirm. ``` ## Pick the lightest tool ```mermaid flowchart TB q{"What needs to change?"} -->|menu titles, order, grouping| map["Adjust the knowledge map
no prose rewritten"] q -->|a page's location| move["revise --move-to
same identity, links updated"] q -->|content boundaries| split["Split or merge
new and revision tasks"] split --> retire["Retire obsolete pages
after destinations are approved"] ``` | Change | Tool | What stays | | --- | --- | --- | | Rename a directory, reorder, regroup, place a page in a second location | Knowledge-map adjustment | Article identity, URL and prose | | Move a page to another path | `context revise --move-to ` | Identity and section IDs; incoming Markdown links are updated on approval | | Split one page, or merge several | Ordinary new and revision tasks | Useful detail, until its destination is approved | | Remove pages now covered elsewhere | `context task retire` | Sources and shared assets | ## Knowledge-map adjustments The knowledge map controls the website navigation and the LLM Docs organization together. Ask in conversation to move a topic, rename a directory, change the order or organize the same articles for another reader task; this works during production or after it, without recapturing sources. Each entry keeps a stable key, so a renamed menu needs no new article and moving a menu entry does not change the article URL. Prefer, in this order: revise an existing article, add a page to a matching category, add a coherent child category. A **top-level** addition, rename or removal is proposed with a before/after tree and needs your explicit approval. ## Splits and merges The Agent reads the affected pages and current sources before deciding what to keep, deepen, split, merge or retire. Destination content is approved first; only then are the original page and its incoming links revised. Useful conditions, steps and explanations must have a destination before anything is removed — omitting a page in Review rejects the candidate, it does not retire the approved article. ## Retiring pages ```yaml reason: These reader tasks are now covered by the approved guide. targets: - path: architecture/old-guide.md replacement: sop/current-guide.md ``` `context task retire --input ` previews the retirement; it does not go through the HTML Review, and once you have approved the deletion the Agent applies the returned command without asking again. Retirement removes the Markdown and structure entries together, points incoming page links at the replacement, and returns a restore input for rollback. Links into a specific paragraph of a split page are repaired first, because the CLI cannot infer where a paragraph went. Pages with continuing value — such as documentation for an older version — normally stay. A shorter new text or a changed menu is not a reason to retire. ## Make the new structure stick Before delivery, check that each page sits under its main reader task, titles match bodies, siblings are ordered deliberately and no directory is empty or an accidental duplicate. Record the lasting intent of each category briefly in the `AGENTS.md` of the Context knowledge workspace, so later updates place new pages the same way. --- ## Sources - note:20261012/usage-practices.md · usage-practices.md L24–L26 - note:20261012/usage-practices.md · usage-practices.md L69–L69 - [context/packages/context/docs/guides/knowledge-updates.md L192–L219 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/approved-revision.md L60–L66 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L609–L651 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L230–L250 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L609–L620 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/knowledge-review.md L61–L67 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L622–L659 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L252–L261 · 3b0ce0a]() --- ## Updating Knowledge # Updating Knowledge Every approved page records which source version it was written from. When a repository moves on or a document is edited, an **update** compares the new version with that baseline, revises only the affected pages and then moves the baseline forward. Unaffected pages are left alone. ```mermaid flowchart LR ask["You name the scope
and target version"] --> acq["Agent acquires the
fixed new version"] acq --> upd["context update
conservative page match"] upd --> decide["Agent reads the change
keep / revise / add"] decide --> rev["Changed pages
Knowledge Review"] rev --> build["Close and build"] build --> base["Baseline advances"] ``` ## Ask for the update Name the scope — a whole repository, some modules or specific documents — and, when it matters, the version: ```text billing-service has moved to the release-2.4 merge. Locate the affected knowledge and update it. Only the invoicing and refunds modules. ``` For a single page whose text is wrong, a [revision]() is the better tool. The Agent also tells you when other work is still unfinished in the Context knowledge workspace and asks whether to finish or roll it back before starting an independent update. ## How the new version is chosen Context does not poll platforms or discover remote changes; the Agent uses its own Git and document tools once, for the scope you named. - For a branch or merge request, it establishes the target branch, merge state and the actual commit on that branch. An unmerged proposal is not the mainline, and a squash or rebase can produce a different commit than the feature branch. - Intervening commits that touch the registered modules are included; reverts are real changes. - A new commit with unchanged module trees can conclude "no knowledge change". - If the old baseline is unavailable after a force push or history cleanup, the Agent says so and compares the current material with approved knowledge instead. - For documents, a read failure, a deletion and a move are reported differently; none of them is a reason to retire a page. ## The update request ```yaml scopes: - requirement_ref: reader-guide source_ref: repo:20261012/billing-service changes: The selected change adds one public option; inspect its explanation and examples. ``` The Agent submits this with `context update --input `. Omitting module references selects the whole confirmed source. The returned candidate list is a conservative match of pages citing the changed material, not a list of pages that must change: the Agent reads the change and the current pages, keeps what is still right, revises what changed and proposes pages for genuinely new topics, which go through structure review first. ## Review and the baseline Changed pages appear in the review report with their changed blocks next to the previous text. The processed baseline advances only after every selected revision is approved, closed and built — or after an explicit conclusion that nothing needs to change. It does not move on acquisition or after the first approved page, so an interrupted update can resume without losing track of what remains. ## Only the sources the update needs Unrelated repositories do not need to be checked out for an update. A note, a document-only change, a wording fix or a navigation change needs no code at all. When required code is missing, the Agent restores only that repository at its pinned commit; see [Code Repositories](). --- ## Sources - [context/packages/context-cli/README.md L322–L340 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L1–L17 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L367–L398 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L400–L420 · 3b0ce0a]() - [context/packages/context/docs/guides/agent-guide.md L164–L167 · 3b0ce0a]() - [context/packages/context-cli/README.md L337–L340 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/knowledge-review.md L76–L82 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L52–L62 · 3b0ce0a]() --- ## Capturing from Conversations # Capturing from Conversations Answers worked out in conversation are easy to lose. When a Q&A or troubleshooting session settles something worth keeping, ask the Agent to capture it. What you bring becomes a source, the Agent plans which pages it affects, and the normal update flow turns it into reviewed knowledge. ```mermaid flowchart LR qa["Q&A or discussion"] --> keep{"Worth keeping?"} keep -->|yes| src["Save as a source
summary / document / code / MR"] src --> plan["Agent proposes
affected pages"] plan --> upd["Update and Review"] upd --> kb["Approved knowledge"] ``` ## What can become a source | You have | It becomes | | --- | --- | | The conclusions of this conversation | A [session summary](), optionally linked to commits or merge requests | | Text you paste or an excerpt you hold | A [note]() | | A new document | A [document]() or [Lark]() source, captured | | Specific code or a merge request | An update of the registered [repository]() to the merged commit | ```text That explanation of the retry limits is right. Save this conversation as a session summary linked to the merge request, and update the affected pages. ``` ## What the Agent does 1. Saves the material. A conversation is summarized — the problem, confirmed decisions, reasons and open questions — never stored as a transcript. 2. Proposes a plan: which existing pages to revise and whether a new page is warranted. A new topic goes through structure review first. 3. Runs the update with the saved source in the affected pages' scope, and brings the changed pages to Knowledge Review. Saving a source alone starts no knowledge work, so you can also save now and update later. A summary that arrives after the code was already processed can still update a page; the code version is reused, not re-parsed. ## When a question finds a gap When querying shows that the knowledge is missing or out of date, the query Skill suggests an update with the affected page, the proposed change and the source scope — and starts nothing until you accept. On acceptance it hands the evidence to the production entry in the selected Context knowledge workspace. See [Asking Questions](). ## Boundaries - Only material you supply or authorize is captured; the Agent does not scan its own history. - A linked merge request records an association; it does not prove the change was merged or tested. - Saving a conversation or approving knowledge does not approve any upstream change discussed in it. --- ## Sources - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L47–L47 - [context/packages/context/docs/guides/sessions.md L3–L8 · 3b0ce0a]() - [context/packages/context/docs/guides/sessions.md L22–L29 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L71–L74 · 3b0ce0a]() - [context/packages/context/docs/guides/sessions.md L10–L15 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L450–L457 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L492–L497 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L462–L471 · 3b0ce0a]() - [context/packages/context/docs/guides/sessions.md L25–L26 · 3b0ce0a]() - [context/packages/context/docs/guides/sessions.md L48–L49 · 3b0ce0a]() --- ## Scheduled Updates # Scheduled Updates Context itself never polls for changes. To keep knowledge current without anyone asking, schedule an Agent run: at a fixed time, the Agent checks the registered sources for changes since the last processed baseline, prepares an update for what changed and stops where a person must decide. Use whatever scheduler your Agent environment provides; the instructions are what matter. ```mermaid flowchart LR timer["Scheduled trigger"] --> check["Agent checks upstream
documents and code"] check -->|no change| report["Short report, stop"] check -->|changes| upd["Update plan and
changed pages"] upd --> review["Knowledge Review
waits for a person"] ``` ## Write the task instructions A scheduled prompt runs unattended, so it must say what a person would otherwise answer: - **Scope** — which Context knowledge workspace and which sources or modules to check. - **No change** — what to do when nothing changed, such as a one-line report. - **When to stop** — which situations need a person: Knowledge Review, new sources, failed reads. - **Delivery** — whether to build, and whether anything may be published. ```text /c4a:context In ./kb, check billing-service and the billing docs for changes since the last processed version. If nothing changed, report "no change" and stop. Otherwise prepare the update and stop at Knowledge Review. Do not publish or commit. ``` ## Delegating review — or not By default the run stops at Knowledge Review and a person reviews the changed pages. If the automation is trusted to review on its own, put the policy block in the instructions it actually delivers to the Agent: ```yaml CONTEXT_RUN_POLICY: knowledge_review: delegate ``` Delegation applies to that task only, and it does not widen the source scope, authorize publishing or bypass Gates that never delegate. See [Managed Mode and Review Policy](). ## What each run does Each run follows the ordinary [update flow](): the Agent acquires the new fixed versions with its own Git and document tools, submits the update, revises only affected pages and brings them to review. Unchanged module trees produce a "no knowledge change" conclusion instead of new pages. A source that cannot be read is reported as a gap; it is never treated as a change or as a reason to remove a page. --- ## Sources - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L49–L49 - [context/packages/context/docs/guides/knowledge-updates.md L369–L373 · 3b0ce0a]() - [context/packages/context/docs/guides/agent-guide.md L37–L42 · 3b0ce0a]() - [context/packages/context/docs/guides/agent-guide.md L17–L42 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L382–L398 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L400–L420 · 3b0ce0a]() --- ## Writing Back Upstream # Writing Back Upstream Production cross-checks sources, and documentation lagging behind code is the normal case. By default the Agent corrects the knowledge from the code facts, so the knowledge is right but the original document stays stale. If you want the originals fixed too, ask the Agent to collect the differences as it goes and handle them together at the end. ```mermaid flowchart LR diff["Document lags code"] --> fix["Knowledge follows
the code facts"] diff --> log["Record in update-remote/
context, judgment, suggestion"] log --> choose["After the task:
you decide"] choose -->|authorized| write["Agent edits the original
and reads it back"] choose -->|not now| sugg["Concise suggestion
for the owner"] ``` ## Ask for it once Add the instruction at the start of a task, or permanently in the `AGENTS.md` of the Context knowledge workspace: ```text When a revision is caused by documentation lagging behind the code, record it in update-remote/-.md with the context, the judgment and the suggested change. After the task, work through update-remote: find each upstream document and either revise it or give a concise suggestion for me to decide on. ``` Upstream documents then catch up promptly, and knowledge and originals do not drift apart for long. ## Is the original actually wrong? Before proposing an upstream edit, the Agent distinguishes three cases: | Case | What happens | | --- | --- | | The knowledge misunderstood correct source text | Only the local page is corrected | | A confirmed decision has not reached the document | The decision can be saved as a local note while the upstream change is considered | | The conclusion is still uncertain | It is not written anywhere as fact | ## Making the edit Neither approving knowledge nor fully managed mode authorizes a remote write. For each edit, the Agent shows the exact document, the affected passage, the before/after text, the reason and the knowledge it affects, and uses an authorization you have already given for that concrete edit or asks for one. It rereads the passage just before writing, adapts only within the authorized scope if someone else changed it, writes with its document tool and reads the result back. The returned document then feeds the normal capture and update flow, so the local snapshot reflects what is really upstream. If the remote edit succeeded but the local build failed, the Agent resumes the local delivery rather than editing again. It does not post comments, notify groups or change permissions; when it lacks permission, it leaves you a concrete suggestion. --- ## Sources - note:20261012/usage-practices.md · usage-practices.md L28–L30 - note:20261012/usage-practices.md · usage-practices.md L30–L37 - [context/packages/context/docs/guides/knowledge-updates.md L499–L505 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L501–L521 · 3b0ce0a]() --- ## Versions and Changelog # Versions and Changelog A Context knowledge workspace has its own version: `package.json.version`, a SemVer. Each completed delivery records **one** new version with a short changelog, and the package, the website and LLM Docs all carry it. Intermediate batches and worker results never get their own version. ```mermaid flowchart LR rv["Review approved"] --> cl["Close"] cl --> pk["Package and template
decisions"] pk --> tr["Site translation"] tr --> ver["Record version
and changelog"] ver --> b["Final build"] ``` ## Which number changes | Change in the delivery | Increment | | --- | --- | | Added modules or material that expands coverage | Minor | | Corrections, updates to existing modules, navigation, persistent status | Patch | | Anything you explicitly call a major version | Major — only on your instruction | The first version is `0.1.0` unless the knowledge workspace already has a higher one or you specify another. Temporary progress under `.tmp/` never changes the version. ## How it is recorded The Agent runs `context version inspect` to see the formal changes — article bodies, assets, structure, navigation and templates — then writes the entry and submits it with `context version record`: ```yaml expected_digest: "" version: 0.2.0 title: Add module recovery guidance changes: - Document recovery conditions and the supported retry flow. triggers: - kind: module description: Additional module material requested in this iteration. ``` Trigger kinds are `initial`, `note`, `sessions`, `mr`, `module`, `document`, `navigation`, `repair`, `dist`, `translation` and `other`. The optional `actor` defaults to the local Git `user.name`; the Agent never guesses an identity. Each entry stays within 1500 visible characters, compressed by merging related changes rather than truncated or split. Entries never contain credentials, raw transcripts, local absolute paths or private account IDs. The CLI updates `package.json`, `changelog.yaml` and the generated `CHANGELOG.md` together. `version inspect --base ` compares against a specific Git point; by default it uses the current version's `v` tag, or `HEAD`. ## Retries and republishing A failed build reuses the recorded version; retrying does not bump it. If formal content has to change after a failed build, an unpublished version can be amended. Once content has been published, any further change needs a higher version. A local build alone does not seal a version, and recording one never commits, tags, uploads or deploys anything. ## Where readers see it The website has a history page, `changelog.html`: cards newest first, the latest three expanded and older ones collapsed. The History button beside the theme switch and the footer's update time link to it. Knowledge packages and LLM Docs carry the same version and changelog. ## Going back to an earlier version Ask the Agent to restore a version — *"restore the knowledge as of last Friday"* or *"go back to the previous version"*. It resolves that to a concrete commit and path scope, abandons unfinished task state, restores only the agreed knowledge workspace paths with Git, and restores the sources pinned by that version. It never resets the whole repository, and existing build output is stale until rebuilt. Nothing is committed or pushed automatically. --- ## Sources - [context/packages/context/docs/guides/knowledge-updates.md L116–L121 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/skills/record-workspace-version/SKILL.md L11–L17 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/skills/record-workspace-version/SKILL.md L40–L44 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L143–L174 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/skills/record-workspace-version/SKILL.md L19–L32 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L123–L133 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/skills/record-workspace-version/SKILL.md L34–L35 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/skills/record-workspace-version/SKILL.md L52–L53 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L187–L190 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-restore.md L6–L54 · 3b0ce0a]() --- ## Asking Questions # Asking Questions `/c4a:context-inspect-search` answers questions from approved knowledge and traces answers back to their sources. It reads the knowledge first, because that is where conclusions are already worked out; only when the knowledge leaves a gap that could change the answer does it read the original documents or code. Every answer cites what was actually read. ```mermaid flowchart LR q["Question"] --> k["Search approved knowledge
or a package"] k -->|enough| a["Answer with citations"] k -->|gap that matters| s["Trace recorded sources
at their pinned versions"] s --> a a -.->|knowledge missing or stale| u["Suggest an update
starts only if you accept"] ``` ## Ask ```text /c4a:context-inspect-search Why does a refund stay pending after the provider confirms it? Cite the code. ``` A knowledge workspace is optional: the Skill can answer from installed or supplied knowledge packages alone. Querying is read-only — it never changes source registrations, snapshots, tasks, approvals or your checkouts, and it never builds just to answer. ## How it searches - It searches approved `knowledge/` with business terms, symbols and synonyms, chooses articles from match excerpts rather than filenames, and reads the relevant sections with their conditions. - Zero hits lead to relaxed or equivalent terms; noisy results lead to a narrower path. A miss alone does not establish that something is absent. - When the knowledge leaves a gap that could change the conclusion, it traces the recorded sources directly, at the commit or snapshot the knowledge cites — never the default branch in its place. One failed source affects only the claims that depend on it. - If the knowledge already answers the question, it does not restore code or check every associated source. ## Retrieval order and access The host or Bot configuration can set two independent policies: | Setting | Values | Effect | | --- | --- | --- | | `CONTEXT_QUERY_SOURCE_MODE` | `repo-first` (default), `package-first`, `dual` | Read the knowledge workspace's approved knowledge first, a package first, or both at once and reconcile differences | | `CONTEXT_QUERY_ACCESS_MODE` | `auto` (default), `remote`, `local` | Whether knowledge and code are read through a remote read-only code service or local checkouts | They change the order and access path, not what counts as evidence. With `remote`, see [Reading Code Evidence Remotely](). ## What an answer looks like The answer comes first, with the conditions that change it right beside it. Complex questions also get the mechanism behind the result, with a short excerpt when it helps you verify. Implementation, declared contracts, tests, runtime observations and inferences are kept distinct. Citations link to what was read: source files at the inspected commit, knowledge site articles and original documents. When no reliable link exists, you get checkable paths, symbols and short excerpts instead. Site links come from the package's `context-site-map.json`; a link is not a claim that the site has deployed that version. ## When the knowledge is missing The Skill scopes any gap to what it inspected — an unanswered question in one article is not absence across the knowledge base. With supporting evidence it may suggest an update: the affected page or gap, the proposed change and the source scope. Nothing starts until you accept; then it hands over to the production entry in the selected knowledge workspace. See [Capturing from Conversations](). --- ## Sources - [context/plugins/context/skills/context-inspect-search/SKILL.md L1–L4 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L143–L156 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L24–L31 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L139–L142 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L126–L136 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L254–L263 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L33–L57 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L399–L416 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L422–L427 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L447–L453 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L462–L471 · 3b0ce0a]() --- ## Using Packages in Agents # Using Packages in Agents `context build` turns approved knowledge into a **knowledge package** under `dist//`: a plain folder of Markdown that any Agent can read, with a bundled Skill that teaches it how. The package is what you hand to Agents that should *use* the knowledge without the Context knowledge workspace that produced it. ## What is inside ```text dist// ├── AGENTS.md # how to use this package ├── skills/knowledge-query/ # bundled query Skill and search script ├── wikis/index.md # entities and relationships ├── guides/ # architecture, procedures, FAQs, decisions ├── rules/ # standards, constraints, test scenarios ├── context-build-inventory.json # package coverage ├── context-site-map.json # page → website URL └── others/assets/ # images and files the pages use ``` Approved collections map to roots: `codeindex`, `business` and `product` go to `wikis/`; `architecture`, `sop`, `faq`, `decision` and `incident` go to `guides/`; `standards` and `test` go to `rules/`. A root that was not selected is simply absent. ## How the query Skill reads it The bundled `knowledge-query` Skill makes the Agent navigate before it searches: 1. Classify the request: lookup, explanation, procedure, rule, relationship, detail or coverage. 2. Open the matching root index and follow links to a likely page. 3. Read only the needed sections; titles and descriptions select scope but do not support claims. 4. Answer from visible section content and cite the page and heading. 5. When the package lacks evidence, report the gap and what was checked. When indexes do not narrow the scope, it searches: `rg` for an exact name or error string, and for several terms or non-English phrases the bundled BM25 script: ```bash node /scripts/search.mjs --query '' --limit 8 ``` Hits are leads; the Agent opens the page before answering. ## Making it available A package can be used where it was built, from a global installation, or from any directory your Agent host can read. Point the Agent at the folder, or install `skills/knowledge-query` into the host's skills directory; if the Skill ends up outside the package tree, the search script takes `--root `, or `--base ` to find the package by its inventory name. Before publishing a package, replace or edit the generic query Skill template with your project's terminology, common intents and preferred entry pages — or explicitly accept the default during package-template review. ## Going back to the sources Package pages carry exported source attributions. When the package is not enough, `/c4a:context-inspect-search` can trace those attributions to the original documents and code at their recorded versions. See [Asking Questions]() and [Reading Code Evidence Remotely](). --- ## Sources - [context/packages/context/docs/guides/package-outputs.md L3–L5 · 3b0ce0a]() - [context/packages/context/templates/package-templates/kb/AGENTS.md L9–L15 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L124–L147 · 3b0ce0a]() - [context/packages/context/templates/package-templates/kb/AGENTS.md L17–L26 · 3b0ce0a]() - [context/packages/context/templates/package-templates/kb/skills/knowledge-query/SKILL.md L39–L47 · 3b0ce0a]() - [context/packages/context/templates/package-templates/kb/skills/knowledge-query/SKILL.md L12–L24 · 3b0ce0a]() - [context/packages/context/templates/package-templates/kb/skills/knowledge-query/SKILL.md L85–L107 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L109–L122 · 3b0ce0a]() - [context/packages/context/templates/package-templates/kb/skills/knowledge-query/SKILL.md L97–L101 · 3b0ce0a]() - [context/packages/context/templates/package-templates/kb/skills/knowledge-query/SKILL.md L141–L149 · 3b0ce0a]() - [context/packages/context/templates/package-templates/kb/skills/knowledge-query/SKILL.md L74–L83 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L237–L243 · 3b0ce0a]() --- ## Reading Code Evidence Remotely # Reading Code Evidence Remotely Answering from knowledge sometimes needs the code behind it. Cloning repositories into every Agent sandbox is slow; instead, the query Skill can read both the Context knowledge workspace and the source code through a read-only code service, Source Graph, at exactly the commit the knowledge cites. The optional **context-evidence** plugin, a WebAssembly module that runs inside that service, attaches each knowledge section's recorded source references to the text the Agent reads. ```mermaid flowchart LR agent["Agent with
context-inspect-search"] -->|read knowledge at commit| sg["Source Graph
read-only MCP"] sg --> wasm["context-evidence plugin
joins sections to references"] wasm -->|text + references| agent agent -->|read cited code at its commit| sg ``` > **Source Graph is optional.** You do not need to install or configure it. Without a service, the query Skill still works well by reading code locally: it makes a shallow, sparse partial clone of the recorded commit and searches it with grep or rg. In the default `auto` mode it prefers Source Graph only when an authorized instance is available. ## Turn it on 1. Connect your Agent host to a read-only Source Graph MCP service that covers the knowledge workspace and its source repositories. Endpoints and credentials belong to the host configuration, never to the Skill or the knowledge. 2. Choose the access policy with `CONTEXT_QUERY_ACCESS_MODE`: | Value | Behavior | | --- | --- | | `auto` (default) | Reuse suitable local material, otherwise prefer the remote service before any local checkout | | `remote` | Read knowledge and code only through the service; never clone automatically, even on failure | | `local` | Local retrieval only; no service required | An explicit request to work locally or offline always wins. ## What happens on a read - The Agent reads knowledge pages from the configured knowledge workspace at one pinned commit, searching within `knowledge/**`. - With the plugin enabled — it is on by default for `read` and `read_many` where the service supports that — each returned file carries a `references:` list: the recorded sources of the sections in that range, as commit-specific URLs where the remote supports it. The Agent reuses them instead of looking up the structure and source registries. - For code, the Agent passes the exact repository and the recorded full commit as the revision, with repository-root-relative paths, and reads only the ranges that decide the answer. - The knowledge workspace's commit and each source's recorded commit are kept separate; neither is replaced by a default branch. ## What it does not do The plugin joins existing section markers, `knowledge/structure.yaml` and source registrations. It does not verify source contents, search code, restore sources or modify knowledge, and a reference is not proof that the source was reread in this query. It has no network, filesystem or process access; the host binds every read to the invocation's repository, immutable revision and readable scope. When the service or plugin is unavailable, the Agent keeps the readable text and continues; in `auto` it may fall back to local retrieval, in `remote` it qualifies the affected claims instead of cloning. ## Running the service Deploying and connecting Source Graph itself — repositories, monorepo path groups, authentication and operations — is covered in the Source Graph guides. On the Context side, nothing else needs configuring: the evidence plugin ships compiled with the CLI. --- ## Sources - [context/plugins/context/skills/context-inspect-search/SKILL.md L160–L167 · 3b0ce0a]() - [context/packages/context-evidence-wasm/README.md L1–L9 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L348–L352 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L49–L57 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L254–L263 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L160–L200 · 3b0ce0a]() - [context/packages/context-evidence-wasm/README.md L58–L80 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L223–L230 · 3b0ce0a]() - [context/packages/context-evidence-wasm/README.md L3–L5 · 3b0ce0a]() - [context/packages/context-evidence-wasm/README.md L31–L34 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L210–L213 · 3b0ce0a]() - [context/packages/context-evidence-wasm/README.md L7–L9 · 3b0ce0a]() --- ## Knowledge Packages # Knowledge Packages A **knowledge package** is the Agent-facing output of a Context knowledge workspace: a folder under `dist/` that turns approved knowledge into something another Agent can install and query. It carries the approved articles in reader-facing form, a query Skill that knows how to search them, and an inventory that maps every file back to its approved source. The same build can also produce a documentation website and LLM text; this page covers the package itself. ```mermaid flowchart LR approved["Approved, closed knowledge
knowledge/"] --> build["context build"] tpl["Package template
src/package-templates/kb"] --> build build --> kb["dist/name/
knowledge package"] build --> site["dist/base-site/
website (optional)"] kb --> agent["Agents query it with
knowledge-query"] ``` ## What is inside ```text dist// ├── AGENTS.md ├── skills/ │ └── knowledge-query/ │ ├── SKILL.md │ └── scripts/search.mjs ├── wikis/ │ ├── index.md # package entry page │ ├── codeindex/ ... │ ├── business/ ... │ └── product/ ... ├── guides/ ... # architecture, sop, faq, decision, incident ├── rules/ ... # standards, test ├── feats/ ... ├── others/assets/ ... # bundled images and resources └── context-build-inventory.json ``` The package name already names the folder, so roots inside are flat: `wikis/`, `guides/`, `rules/`, `feats/`. Each article lands under the root for its collection — `sop` pages under `guides/sop/`, `codeindex` pages under `wikis/codeindex/` — as listed in [Knowledge Collections](). `wikis/` is the structured entity-and-relationship layer; `guides/` and `rules/` explain, operationalize or constrain it. Pages in the package are written for consumers: they keep their reader-facing frontmatter, drop lifecycle comments, section markers and fingerprints, and end with a readable Sources section generated from the article's references — repository links with file and line ranges, document links with their captured attribution. Exact section evidence stays in the mapped page of the knowledge workspace. ## How Agents read it The default `knowledge-query` Skill is a complete, generic query entry. It works structure first: 1. Start from the generated directory indexes in each root. 2. Use relationship records in `context-build-inventory.json` for package-visible connections. 3. Read the candidate pages and cite their visible headings and passages. 4. Report a gap when the package does not cover the fact asked for. When the indexes do not narrow the scope, or a page is too large to read directly, its bundled `scripts/search.mjs` ranks bounded Markdown chunks with BM25. Search results are leads; page bodies and typed relationship records establish what the package says. A package-only reader must not claim to have read the original sources. See [Using Packages in Agents]() for installing a package into an Agent. ## Declaring a package Packages are declared in the knowledge workspace's `src/index.ts`. The Agent edits this for you when you choose outputs in the work-start report; you never need to write it by hand. ```ts kbPackage({ name: "project-kb", template: "src/package-templates/kb", select: { exclude: ["**/internal/**"] }, site: { title: "Project knowledge", lang: "en-US", base: "/" }, }); ``` | Field | Meaning | | --- | --- | | `name` | Lowercase, path-safe package name; output goes to `dist//` | | `template` | Template directory, or `{ path, vars }` | | `select` | Optional selection by `collections`, OKF `okfRoots`, or `include` / `exclude` paths under `knowledge/`; omitted means all approved knowledge | | `navigation` | Directory-index policy; defaults to folding indexes with up to 50 inline entries | | `assets` | Resource delivery: bundled by default, Git raw links or omission when explicitly configured | | `site` | Also build a [documentation website]() | Full details are in [Package Templates](). ## Choosing outputs Outputs can be combined. The work-start report shows them as one multi-select list and later steps reuse your choice: - [x] Agent knowledge package — the default for a new knowledge workspace. - [x] Documentation website — the default together with the package, for local preview or later hosting. - [ ] LLM text — optional input for model context or RAG; see [LLM Docs](). You can also stop at approved Markdown: keep `packages: []` and no build runs. There is no separate website Skill and no second permission per selected output. ## Building and assets `context build` consumes only approved and closed knowledge; if close is pending, the workflow runs it first. A newly initialized generic template must be edited or explicitly accepted before the first build — `context status` shows this as a package template review step. Images and resources referenced by approved pages are bundled into `others/assets/` by default. Each packaged image is kept at or below 1 MiB and all images together at or below 40 MiB; oversized images are compressed into new WebP files inside `dist/` only, never touching `sources/` or `knowledge/assets/`. Source audit files and capture reports are never shipped as reader assets. ## What the build checks - **Template boundary.** Template prose that describes coverage, scope or known gaps must cite approved knowledge, the inventory or rendered structure data; otherwise the build reports a diagnostic. - **Index links.** Every generated directory index is checked so relative links resolve inside the package. - **Path collisions.** A rendered template path may not collide with a selected knowledge path; rename the template file or exclude the knowledge path with `select.exclude`. - **Relationship coverage.** The inventory's `structure.relationship_coverage` records whether code index pages carry current relationship data, so an empty edge list is evidence of coverage, not permission to invent a dependency. Fix problems in the template, the approved knowledge or the package declaration and rebuild. Never patch `dist/` as the durable fix. To change the template itself, see [Custom Output Templates](). --- ## Sources - [context/packages/context/docs/guides/package-outputs.md L1–L16 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L45–L48 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L189–L241 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L282–L317 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L323–L327 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L243–L260 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L15–L57 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L396–L402 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L463–L475 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L384–L393 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L12–L16 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L337–L342 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L262–L275 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L344–L361 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L276–L281 · 3b0ce0a]() --- ## Documentation Sites # Documentation Sites A Context documentation site is a static website built from the same approved knowledge as your knowledge package. Turn it on with a `site` option on the package; every `context build` then writes the package and a sibling `dist/-site/` folder you can preview locally and upload to any static host. ```mermaid flowchart LR map["src/knowledge-map.yaml"] --> build["context build"] approved["Approved knowledge"] --> build ext["src/site/ (optional)"] --> build build --> site["dist/base-site/"] site --> preview["Local preview"] site --> host["Your static host"] ``` ## Turning it on ```ts kbPackage({ name: "project-kb", template: "src/package-templates/kb", site: { title: "Project knowledge", lang: "en-US", base: "/", home: { slogan: "Find the context behind the work", resources: [{ title: "Project workspace", description: "Open the repository that maintains this knowledge.", href: "https://example.com/project", featured: true, }], }, }, }); ``` | Option | Meaning | | --- | --- | | `title`, `description` | Site title (defaults to the package name) and description | | `lang` | Primary language, default `en-US` | | `base` | URL prefix, default `/`; use `/docs/` when hosted under that path. It does not change output folders | | `home` | Landing-page title, slogan, description and resource cards; each card needs a safe `href`, a copyable `command`, or both; `featured` also places it among the hero actions | The output folder drops one trailing `-kb` from the package name: `project-kb` builds `dist/project-kb/` and `dist/project-site/`. Resource cards come from confirmed settings, repository remotes or real deployment results; unknown destinations are omitted, never filled with placeholders. ## What the site offers - **Homepage** — every first-level knowledge-map section as a card with a bounded preview of its pages, plus LLM Docs and Changelog. - **Navigation** — top-bar sections; the left sidebar shows only the current section's descendants. - **Search** — local search, opened with the search button or Cmd/Ctrl+K; no search service. - **Theme** — light and dark, following the operating system until the reader chooses; the choice is remembered and applied from the first paint, so pages do not flash the other scheme while loading. - **Missing pages** — an unknown address shows a centred 404 page in the reader's language with a link back to the site home. - **Diagrams** — Mermaid rendered in the browser with fit, 100%, zoom, full-screen and source controls. Invalid diagrams keep their source with a notice instead of blocking publication. - **Provenance** — each article ends with its sources: repository entries link to the recorded revision, document entries to their registered URL. Code samples and raw HTML are displayed as content, never executed. ## Navigation comes from the knowledge map `src/knowledge-map.yaml` decides the sidebar: each entry binds to an article by its identity, so labels and parent groups never change an article's URL, and one article can appear in several places while keeping one URL. Every selected article needs a valid place before packaging; missing bindings block the build and the CLI returns the list to place. Category entries may stay empty while articles are still planned. | Setting | Adds | | --- | --- | | `site.nav` | Links after the reading sections in the top bar | | `site.more` | Items in the More menu, before LLM Docs and Changelog; an item may target an approved article kept outside the map, such as release notes | | `socialLinks` | Icon links in the top bar (`https` only) | | `titleLink` | Where the site title leads; a root-relative link such as `/` addresses the origin, not `base` | Links starting with `/` are origin paths, which lets a site under `/docs/` link to a sibling application on the same domain. `locales` on a nav or More item translates its label. ## Building and previewing The site is generated in a staging folder before anything is replaced, so a failed website build keeps the previous package and site. Removing `site` deletes the old site on the next successful build. `dist/-site/context-site-map.json` records each article's approved path, package path and site path, plus the menu and any unresolved targets. Preview it through a local HTTP server: ```sh python3 -m http.server 8000 --bind 127.0.0.1 --directory dist/project-site ``` The Agent's completion report lists the package folder, website folder and LLM text separately, each as generated, failed or not selected, with navigation coverage and the verified preview URL. ## Deploying Deploy the **contents of `dist/-site/`** with your chosen static hosting tool. Context's build includes no hosting SDK, login or deployment step; after every successful website build the Agent tells you which folder to deploy and, if you have authorized a target, uses a compatible deployment Skill. Only the website folder is published — never sources, private workspace state or the whole package — and success is reported only after the hosted URL is checked. Once deployed, record the public root so query Skills can link to pages: ```bash context package site-url project-kb https://example.com/docs/ ``` The address is an access hint, not proof of publication; rebuilds keep it. | You ask for | The Agent does | | --- | --- | | Package and website | One `kbPackage` with `site` | | Package only | Removes `site` and rebuilds; the old site is deleted | | Add a website later | Adds `site`, places any unplaced articles, rebuilds | | Website only for sharing | Builds the package too, shares only the website folder | To change pages, slots and colors, see [Page and Theme Customization](); for other languages, [Multilingual Sites](). --- ## Sources - [context/packages/context/docs/guides/package-outputs.md L39–L54 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L183–L187 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L56–L87 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L89–L95 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L97–L121 · 3b0ce0a]() - [context/CHANGELOG.md L10–L14 · 3b0ce0a]() - [context/packages/context-cli/src/project/packageSiteTheme.ts L329–L334 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L123–L150 · 3b0ce0a]() - [context/packages/context/docs/guides/page-customization.md L37–L40 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L167–L182 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L454–L461 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L477–L497 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L533–L552 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L445–L452 · 3b0ce0a]() --- ## Page and Theme Customization # Page and Theme Customization A Context site works without any frontend code, but you can tailor it: replace parts of the homepage, add a logo, float a chat widget on every page, publish website-only pages and change the color palette. All of this lives in your Context knowledge workspace — presentation code under `src/site/`, colors in `src/site/theme.json` — and is applied by the normal `context build`. Approved knowledge and generated output are never edited by hand. ```mermaid flowchart LR ext["src/site/
components, pages, CSS"] --> build["context build"] theme["src/site/theme.json"] --> build cfg["kbPackage site.extensions"] --> build build --> site["Website"] ``` ## Declaring extensions ```ts site: { title: "Engineering handbook", extensions: { root: "src/site", slots: { banner: "components/Banner.vue", floating: "components/Chat.vue", }, pages: { support: "pages/support.md" }, }, } ``` Paths are relative to `root`. The folder may contain Vue components, CSS, Markdown and imported assets; use relative imports within it and declare external dependencies in the knowledge workspace's package manifest. Hidden files, `node_modules` and `dist` are not copied, and symbolic links are rejected. Never put credentials or private configuration in frontend files. ## Homepage and page slots | Slot | Default | Customization | | --- | --- | --- | | `banner` | Homepage hero and actions | Replace with a component | | `knowledge` | Knowledge-map card group | Replace with a component | | `resources` | Resource card group | Replace with a component | | `footer` | Homepage footer | Replace with a component | | `floating` | Empty | Client-only component fixed bottom right on all pages | | `brand` | Site title text | Component at the start of the top bar, such as a logo | Omit a slot to keep its default, or set it to `false` to hide it. A component replaces only its slot — never the global navigation, language switch or article provenance. Components can use VitePress `useData()` and `useRoute()` and import scoped CSS. Pages prerender in the light theme; for readers starting in dark mode, slot components mount again after load so markup bound to `isDark` matches. To show the right language from the first paint, render each language and mark it with `data-context-locales=""`; the site stylesheet hides the others. `useData().lang` gives the reader's language after mount. ## A chat or Bot widget The `floating` component owns its button, panel and open/close behavior. Keep the panel inside the viewport, preserve keyboard focus and a close control, and load heavy chat SDKs only when opened. The static site provides no chat backend or secret storage: send requests to an authorized service of your own, and make sure a service failure never prevents reading the documentation. Other components must render statically; use `onMounted` for browser APIs. ## Custom pages Each `pages` key becomes `/custom/.html` under the site base. A page is trusted Markdown and may import Vue components: ```md # Support ``` Place it in navigation with an ordinary knowledge-map entry whose target is `artifact_ref: "site:support"`, setting `parent`, `title` and `order` as for any entry. Pages without an entry are still reachable directly, and several entries can point to one page. Custom pages are website-only: they are not approved articles and do not enter the knowledge package or LLM Docs. Change formal articles through revision, not with a custom page. ## Colors The first website build creates `src/site/theme.json` with the default light and dark palettes if it is missing; builds never overwrite your values, and deleting the file restores the defaults. Each `light` and `dark` object accepts `brand`, `accent`, `background`, `surface`, `text`, `mutedText` and `border` as hexadecimal colors; missing keys inherit defaults. A package can override the shared file: ```ts kbPackage({ site: { theme: { light: { brand: "#6750a4" }, dark: { brand: "#d0bcff" }, } } }) ``` Precedence is built-in defaults, then `theme.json`, then `site.theme`. Offline Review reports and Mermaid diagrams use the same colors. Custom components should read `--context-brand`, `--context-accent`, `--context-background`, `--context-surface`, `--context-text`, `--context-muted-text` and `--context-border` instead of hard-coding colors. ## Building and checking Customization needs no capture, Indexer work or new review: edit and run the usual build. Extension files and dependency manifests take part in build fingerprints, and a failed build keeps the previous output. Before publishing, preview the homepage, custom pages and floating panel on desktop and mobile, with a non-root `base`, in dark mode and with keyboard navigation. Publish only the website folder. For the base site options, see [Documentation Sites](). --- ## Sources - [context/packages/context/docs/guides/page-customization.md L1–L4 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L554–L561 · 3b0ce0a]() - [context/packages/context/docs/guides/page-customization.md L3–L24 · 3b0ce0a]() - [context/packages/context/docs/guides/page-customization.md L26–L55 · 3b0ce0a]() - [context/packages/context/docs/guides/page-customization.md L57–L63 · 3b0ce0a]() - [context/packages/context/docs/guides/page-customization.md L65–L90 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L554–L580 · 3b0ce0a]() - [context/packages/context/docs/guides/page-customization.md L92–L103 · 3b0ce0a]() --- ## LLM Docs # LLM Docs **LLM Docs** are plain-text exports of your approved knowledge for models: an index, the complete text in one file, and each article as raw Markdown. Every Context documentation site includes them automatically under **LLM Docs** in the top bar. If you need the text without a website — to paste into a model's context or import into a retrieval system — declare a standalone LLM text package. ```mermaid flowchart LR approved["Approved articles
and knowledge map"] --> site["Website build"] approved --> llms["llmsPackage (optional)"] site --> sitellms["llms/ inside the site"] llms --> pkg["dist/name/ text bundle"] ``` ## What you get | File | Content | | --- | --- | | `llms.txt` | Index that preserves the knowledge map's grouping, order and repeated placements | | `llms-full.txt` | All selected approved text, each article once, in first-placement order | | `llms/pages/.txt` | One raw Markdown file per approved article | | `llms/index.html` | Landing page on the website: index and full-text links followed by the knowledge map | On a website these files sit inside the site folder and use the configured `base`; no extra declaration or command is needed. They stay in the primary language even when the site has translations. Text files carry a UTF-8 byte-order mark so browsers detect the encoding when a host omits the charset; serve them as `text/plain; charset=utf-8`. ## A standalone text package Choose an LLM text package when you want one consolidated file that is easy to copy, index or upload, without Agent Skill packaging: ```ts llmsPackage({ name: "project-llms", template: "src/package-templates/llms" }); ``` It produces `llms.txt` from its template, plus `llms-full.txt` and the per-article files, organized by the same knowledge map. It can sit alongside a knowledge package in the same declaration; ask the Agent to add it in the work-start report or later. ## Freshness Only approved, selected content is exported. Any change to the map or an article invalidates both the website and its LLM Docs, and a failed build keeps the previous output. For packages built for Agents with a query Skill, see [Knowledge Packages](). --- ## Sources - [context/packages/context/docs/guides/package-outputs.md L513–L520 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L363–L367 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L513–L527 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L162–L163 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L363–L382 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L528–L531 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L526–L529 · 3b0ce0a]() --- ## Multilingual Sites # Multilingual Sites A Context site can show every page in several languages at the same address. You declare the reader languages; the Agent translates approved articles and navigation titles during delivery; the site shows each reader their language and falls back to the original where a translation is missing. Approved knowledge in the primary language stays the only source of truth: translations are a reader projection and never change Review, verification or the knowledge package. ```mermaid flowchart LR approved["Approved article
primary language"] --> tr["Translation step"] tr --> files["translations/zh-CN/..."] approved --> build["context build"] files --> build build --> page["One page,
every language"] ``` ## Declaring languages ```ts site: { lang: "en-US", locales: { "zh-CN": { title: "项目知识" } }, } ``` Each locale may override `label`, `title`, `description` and `home`. Set only the homepage fields that differ: an unset `home` title, slogan, description, hero actions or resources falls back to the site's own `home` setting, and then to the built-in default, so a translated title alone keeps the primary language's actions and resource cards. Links, navigation and custom pages need no per-language routes, because every page carries all languages. A reader's saved choice wins, then the browser's languages, then `site.lang`; the choice is remembered under `site.localePreferenceKey` (default `context-locale::`), which several sites on one origin can share. Without `site.locales` the language button still switches the interface between Chinese and English. ## Where translations live | Path | Content | | --- | --- | | `translations//.md` | Translated article; frontmatter holds `title`, optional `description` and a `translation` record with locale, article identity, source digest and time | | `translations//knowledge-map.yaml` | Translated navigation titles keyed by knowledge-map entry | Translations are formal content of the Context knowledge workspace: they are committed, included in versions and package fingerprints, and changing one rebuilds the website. ## Freshness Each translation records the digest of the approved title, description and body it was made from: | State | Meaning | On the site | | --- | --- | --- | | `current` | Digest matches | Translation shown | | `stale` | Approved article changed since | Translation shown with an outdated notice and a button to switch to the original | | `missing` | No translation file | Original shown with a notice | Runtime metadata changes do not make a translation stale. Translations whose article no longer exists are reported as orphans and removed on the next submission. `context-site-map.json` lists translated, stale and missing counts per locale. ## The translation step When a package declares locales and anything is not current, the workflow adds a translation step after package template approval and before the knowledge workspace version is recorded. The Agent runs it: ```bash context translate status --format json context translate prepare --format json context translate submit --input --format json context translate skip --digest --format json ``` `prepare` lists pending articles and navigation titles with an `expected_digest`; `submit` takes the translated files and titles: ```yaml expected_digest: articles: - locale: zh-CN approved_path: knowledge/sop/example.md file: .tmp/agent-payloads/translations/zh-CN/sop/example.md map_entries: - locale: zh-CN key: getting-started title: 入门 ``` A translation must keep every section marker, id and order, every fenced code block (Mermaid labels may change) and every link target. The submission is validated as a whole and saves nothing if any item fails; a digest from before an approved change is rejected. `skip` publishes the current pending items in the primary language for this iteration only — the next approved change asks again. ## What readers see Each page is published once with every language and the reader's language selects what is visible. Navigation titles without a translation use the translated article title, then the original. Search covers every language, and opening a result in another language switches to it. LLM Docs and the Changelog stay in the primary language. For other site options, see [Documentation Sites](). --- ## Sources - [context/packages/context/docs/guides/site-translation.md L1–L6 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L152–L166 · 3b0ce0a]() - [context/packages/context-cli/src/project/packageSite.ts L170–L187 · 3b0ce0a]() - [context/CHANGELOG.md L10–L13 · 3b0ce0a]() - [context/packages/context/docs/guides/site-translation.md L8–L17 · 3b0ce0a]() - [context/packages/context/docs/guides/site-translation.md L19–L26 · 3b0ce0a]() - [context/packages/context/docs/guides/site-translation.md L65–L70 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L164–L164 · 3b0ce0a]() - [context/packages/context/docs/guides/site-translation.md L28–L63 · 3b0ce0a]() - [context/packages/context/docs/guides/site-translation.md L65–L72 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L162–L163 · 3b0ce0a]() --- ## Custom Output Templates # Custom Output Templates Every knowledge package is rendered from a **package template** in your Context knowledge workspace, by default `src/package-templates/kb/`. The template supplies the package entry page, the query Skill and any instructions for Agents; `context build` renders it and adds the selected approved articles. The generated default is a usable generic starting point. Customize it when your package needs project terminology, curated navigation, routing rules or task-specific Skills. ```mermaid flowchart LR tpl["src/package-templates/kb/"] --> render["Render with Handlebars"] vars["Built-in and template.vars"] --> render render --> out["dist/name/"] approved["Selected approved articles"] --> out out --> check["Path, link and
boundary checks"] ``` ## What the template contains ```text src/package-templates/ ├── kb/ │ ├── AGENTS.md │ ├── wikis/ │ │ └── index.md │ └── skills/ │ └── knowledge-query/ │ ├── SKILL.md │ └── scripts/ │ └── search.mjs └── llms/ └── llms.txt ``` A knowledge package template must contain at least one `SKILL.md` and `wikis/index.md`; a template with only `AGENTS.md` is rejected. Each rendered Skill lives at `skills//SKILL.md` with a matching frontmatter `name`. To give the query Skill a project prefix, rename its template folder — for example `skills/android-query/` — since Context never derives Skill names from the package name. Add another Skill only when you want behavior beyond knowledge lookup. ## Accept or edit before the first build A newly initialized generic template must be edited or explicitly accepted before the first build. `context status` shows this as a package template review step: the Agent either accepts the unchanged default through the command the workflow returns, or you edit files under `src/package-templates/`. Context compares file digests and records the decision; it does not judge the template's prose. ## The entry page and navigation `wikis/index.md` is the package's entry page. Tell readers what the package covers, who it is for and how to query it. Every selected root — `wikis/`, `guides/`, `rules/`, `feats/` — always gets an index. By default, small directories fold into their nearest generated ancestor index and a directory gets its own `index.md` only when it would expose more than 50 entries to its parent; set `navigation.foldDirectoryIndexes: false` to generate one per directory, or change `maxInlineEntries`. For curated navigation, loop over the built-in variables in `wikis/index.md`: ```handlebars {{#each knowledgeGroups}} ## {{title}} ({{count}}) {{#each items}} - [{{title}}]({{href}}) {{/each}} {{/each}} ``` | Variable | Gives you | | --- | --- | | `{{displayName}}`, `{{packageName}}` | Package display name and name | | `{{knowledgeCount}}`, `{{knowledgeTimestamp}}` | Number of selected pages and the latest timestamp | | `{{knowledgeItems}}` | Selected page metadata for loops | | `{{knowledgeGroups}}` | Pages grouped by root and first directory | | `{{knowledgeTreeNodes}}`, `{{knowledgeTree}}` | Nested tree, or its Markdown preview | | `{{wikisRoot}}` … `{{featsRoot}}` | Package-relative root paths, for links inside Skills | The complete list, with loops, conditionals and helpers, is in [Template Variables](). Custom values come from `template.vars`. ## The query Skill The default `knowledge-query` Skill already carries the structure-first query discipline and a BM25 search fallback. Edit its template when you need project terminology, entry points or task workflows. Put authoring notes in template comments or separate guidance — not in a final section addressed to authors inside the delivered Skill. ## Rules the build enforces - **No second knowledge source.** Template prose that describes coverage, scope, known gaps or limits must cite approved knowledge, `context-build-inventory.json` or rendered structure data; otherwise the build reports a template-boundary diagnostic. Facts belong in approved articles. - **No collisions.** Template paths are rendered first; a rendered path may not collide with a selected knowledge path or a generated index path. Rename the template file or exclude the knowledge path with `select.exclude`. - **Valid links.** Links in every root index and generated child index must resolve inside the package; broken ones are reported as `package/index-link-invalid`. - **Fix at the source.** Repair the template, the approved knowledge path or the declaration and rebuild; never patch `dist/`. `context build` and `context verify` check structure, not whether the selected knowledge is meaningful for your readers — inspect the output yourself. The template API is in [Package Templates](). --- ## Sources - [context/packages/context/docs/reference/package-templates.md L339–L351 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L294–L300 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L208–L231 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L159–L164 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L337–L342 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L247–L251 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L263–L279 · 3b0ce0a]() - [context/packages/context/docs/reference/template-variables.md L168–L201 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L243–L260 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L375–L395 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L285–L292 · 3b0ce0a]() --- ## Community Indexers # Community Indexers An **Indexer** is a Skill that tells the Agent how to investigate one kind of source and how to write source-grounded articles from it. It helps the Agent understand authorized material; it does not own workflow routing, source authorization, Review or the permanent identity of an article. Several Indexers can contribute to the same module or article. The community edition ships four Indexer Skills — for code, documents, notes and session summaries — and one creator Skill that writes new Indexers. All of them are maintained in `plugins/context/skills/` of the Context repository, and `context plugin install` makes them available to your Agent host. ```mermaid flowchart LR repo["Repository modules"] --> code["context-code-indexer"] docs["Captured documents"] --> md["context-markdown-indexer"] notes["Saved notes"] --> note["context-note-indexer"] sess["Saved session summaries"] --> ses["context-sessions-indexer"] code --> art["Source-grounded articles"] md --> art note --> art ses --> art family["A source family that needs
specialist guidance"] --> create["context-indexer-create"] create --> own["Your own Indexer Skill"] ``` ## At a glance | Category | Skill | | --- | --- | | Code | `context-code-indexer` | | Documents | `context-markdown-indexer` | | Notes | `context-note-indexer` | | Session summaries | `context-sessions-indexer` | | Creator | `context-indexer-create` | The first four are Indexer Provider Skills that the Context workflow uses during planning and writing. The creator is an authoring assistant: it writes a new Indexer Skill for code, documents, notes or session summaries when you ask for one. ## Code: `context-code-indexer` - **Reads:** the authorized module of a registered repository, starting from the directory and file navigation the CLI supplies. - **Investigation produces:** the relevant technology, the visible capability families, and proposed reader topics and writing batches. It may inspect representative source, but it does not parse the whole repository, enumerate every symbol or build a relationship graph during planning. Partial counts are named as partial. - **Writing reads:** the actual implementation and contracts needed for each reader question. Drafts go to the Agent's temporary directory and are submitted through the current CLI action; the Skill never writes formal knowledge or modifies the source repository. - **Bundled resources:** `references/indexer.md` with investigation and writing guidance, an article catalog for each module profile, diagram and source-visual guidance, and a template for each profile. The profiles cover 16 kinds of module, from monorepo containers, web applications, component and SDK libraries and CLI tools to API services, event consumers, storage repositories, adapters, contract sources and generated sources. - **Tests:** anonymized fixture sets under `tests/fixtures/`. Source: `plugins/context/skills/context-code-indexer/`. ## Documents: `context-markdown-indexer` - **Reads:** captured documents. Same-repository docs and authored Skills registered as repo-content stay originals; the Skill uses them only as bounded supporting evidence unless you explicitly ask for knowledge production from them. - **Investigation produces:** topics and writing batches decided from the CLI's document titles, bounded opening excerpts and complete H2/H3 outlines, with selective full reading where needed. The outline is navigation, not proof of a claim and not an instruction to write one article per heading. - **Writing reads:** the relevant full source, keeping its useful guidance, examples and limits, with citations to the actual regions used. - **Bundled resources:** planning guidance (`references/semantic-planning.md`), writing guidance (`references/indexer.md`), reader outcomes (`references/classification.md`) and article boundaries (`references/structure-and-artifacts.md`), plus article catalogs and templates that are not read by default. Its 13 document profiles range from domain references, product requirements and technical guides to runbooks, FAQs, decision records, incident reviews, test validation, release and migration guides, and documentation sites. - **Tests:** anonymized fixture sets under `tests/fixtures/`, such as document-routing cases. Source: `plugins/context/skills/context-markdown-indexer/`. ## Notes: `context-note-indexer` - **Reads:** saved notes, excerpts and observations, by direct reading. These sources normally need no parser or separate inventory pass. - **Investigation produces:** a useful skeleton rather than an exhaustive fact ledger, and article targets proposed against existing topics with the help of `references/classification.md`. - **Writing reads:** the selected material, guided by `references/writing.md`; when a note revises or combines existing topics, `references/updates-and-composition.md` and `references/extension-placement.md` apply. - **Bundled resources:** nine reader profiles of its own (domain reference, product requirements, technical guide, user and developer guide, runbook, FAQ, decision record, incident review, test validation) and a `note/`-prefixed extension profile for each code and document profile, such as `note/api-service` or `note/runbook`. Templates and article catalogs are loaded only when needed. - **Boundaries:** it does not scan host history, fetch an unapproved URL, alter evidence to fit a claim or write formal knowledge. - **Tests:** anonymized profile fixtures under `tests/fixtures/`. Source: `plugins/context/skills/context-note-indexer/`. ## Session summaries: `context-sessions-indexer` - **Reads:** a bounded summary of a conversation, prepared by the host or an external supplier. The Indexer does not scan chat history, load a full transcript or synthesize a conversation from a diff. The summary need not concern code or have a commit. - **Investigation produces:** a skeleton and article targets from direct reading, in the same way as the Note Indexer. - **Writing extracts:** the problem, the decisions actually reached, the reasons needed to understand them, remaining questions and applicability — keeping "proposed", "agreed", "implemented" and "verified" distinct. An optional `changes` association (a full `commit` SHA or an `mr` URL) records what was discussed; it does not prove that a change merged, deployed or passed tests. - **Bundled resources:** the same kinds of references, templates and article catalogs as the Note Indexer, loaded only when needed. Source: `plugins/context/skills/context-sessions-indexer/`. ## The creator: `context-indexer-create` `context-indexer-create` writes a reusable Indexer Skill in the directory you choose. It activates only when you explicitly ask to create a new Context Indexer Skill for code, documents, notes or session summaries — not for indexing existing sources, ordinary coding, knowledge queries or choosing an installed Skill. It is not a slash command, so ask for it in plain language. It writes Skills only: it does not initialize a knowledge workspace or start production. It delivers a `SKILL.md` with only the references, templates or scripts that are useful, and no Provider registration manifest, version or hash verification flow. At the end it reports the files it created, the inputs it supports and its remaining limitations. Installing the new Skill makes it available, not selected. See [Creating an Indexer]() for the full walkthrough. Source: `plugins/context/skills/context-indexer-create/`. ## How they are installed `context plugin install` installs the Context Agent integration. A global installation creates the host-namespaced Context entry and also projects the four Indexer Skills as **unnamespaced** Skills for Claude, Codex and Cursor: into the shared `~/.agents/skills` directory for Codex and Cursor, and into `~/.claude/skills` for Claude. Their names therefore stay `context-code-indexer`, `context-markdown-indexer`, `context-note-indexer` and `context-sessions-indexer`, without a plugin prefix. The creator is different: it ships inside the host-specific plugin roots, next to the production, project-planning and query entries. Restart or refresh the Agent host after installing. Installing an Indexer makes it discoverable. It does not enable it for every Context knowledge workspace. ## How the Agent selects them You do not call an Indexer directly. Indexer Skills are activated only through the Context workflow, so invoke Context explicitly or continue an active Context conversation; ordinary coding and design discussions do not start it. When work starts, the Agent declares the relevant Skills that are available in the host. It then selects the ones that fit the actual materials and reader task, and records that choice in the current planning schema. There is no separate Provider selection, primary-owner or resolution stage to pass. The Agent: - respects Skills you have disabled in the host; - respects an explicit business replacement, such as your own Indexer standing in for a built-in one; - reads only the selected guidance, without scanning plugin caches or building another Skill registry. Skill names are guidance, not version pins or evidence of completed reading. See [Providers and Customization]() for replacing or disabling an Indexer. ## Several Indexers on one module Several Skills may examine different aspects of the same module. The Agent combines their findings without making any one of them the permanent owner. Code establishes implemented behavior, while authorized notes or documents can explain business intent and rationale. Contributions from several selected Skills go into the same article rather than producing copies. A note that only supports an existing page is written into that page, using its evidence and read scope. A note that answers an independent reader question can become its own article through the selected Note Indexer, whether that is the default one or a business replacement. A compatible extension layer is selected explicitly when specialized interpretation is needed; another Skill is not enabled merely because a note exists. Next: - [The Indexer System]() explains how Indexers fit into the production lifecycle. - [Creating an Indexer](), [Code Indexers]() and [Document Indexers]() cover writing your own. - [Providers and Customization]() covers combining, replacing and disabling Indexers. --- ## Sources - [context/packages/context/docs/guides/indexer-skill-creation.md L1–L6 · 3b0ce0a]() - [context/plugins/context/README.md L5–L17 · 3b0ce0a]() - [context/packages/context-cli/README.md L55–L59 · 3b0ce0a]() - [context/plugins/context/README.md L5–L14 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/SKILL.md L1–L7 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/SKILL.md L1–L8 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/SKILL.md L11–L31 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/context-indexer.yaml L332–L445 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/tests/fixtures/scenarios.json L1–L3 · 3b0ce0a]() - [context/plugins/context/skills/context-markdown-indexer/SKILL.md L9–L38 · 3b0ce0a]() - [context/plugins/context/skills/context-markdown-indexer/context-indexer.yaml L24–L38 · 3b0ce0a]() - [context/plugins/context/skills/context-markdown-indexer/tests/fixtures/routing.json L1–L4 · 3b0ce0a]() - [context/plugins/context/skills/context-note-indexer/SKILL.md L1–L31 · 3b0ce0a]() - [context/plugins/context/skills/context-note-indexer/context-indexer.yaml L21–L60 · 3b0ce0a]() - [context/plugins/context/skills/context-note-indexer/tests/fixtures/profiles.json L1–L6 · 3b0ce0a]() - [context/plugins/context/skills/context-sessions-indexer/SKILL.md L9–L31 · 3b0ce0a]() - [context/plugins/context/skills/context-sessions-indexer/references/indexer.md L3–L28 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/SKILL.md L1–L15 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/SKILL.md L28–L41 · 3b0ce0a]() - [context/plugins/context/README.md L13–L22 · 3b0ce0a]() - [context/plugins/context/README.md L19–L26 · 3b0ce0a]() - [context/plugins/context/skills/context/SKILL.md L605–L614 · 3b0ce0a]() - [context/packages/context/docs/guides/indexer-provider-and-customization.md L9–L21 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/references/indexer.md L32–L35 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/references/indexer.md L145–L150 · 3b0ce0a]() - [context/packages/context/docs/guides/note.md L21–L25 · 3b0ce0a]() --- ## Creating an Indexer # Creating an Indexer An Indexer is source-specific investigation and writing guidance: it helps the Agent understand authorized material and produce useful articles. When the built-in Indexers do not know enough about a technology or a family of documents, you can ask the Agent to create one with the **`context-indexer-create`** Skill. The creator writes a reusable Skill in the directory you choose. It writes Skills only: it does not initialize a Context knowledge workspace or start knowledge production. Your new Indexer contributes investigation and writing guidance; the current Context stage still supplies the purpose, scope, scheduling and submission schemas. ```mermaid flowchart TD ask["You ask for a new Indexer
in plain language"] --> clarify["Creator asks only for missing choices
that change the result"] clarify --> study["Reads the authoring guide and,
if useful, a host-visible example Skill"] study --> write["Writes SKILL.md plus only
useful references, templates or scripts"] write --> check["Validates resources and scripts,
exercises anonymous realistic material"] check --> report["Reports files, supported inputs,
helper behavior and limits"] report --> install["You install it through
your chosen channel"] install --> select["The Agent may select it
in a later Context run"] ``` ## When a custom Indexer helps Write a custom Indexer when a technology or document family keeps needing guidance that the built-in Indexers do not carry — for example, a framework whose services are declared in its own files, or a document family with its own structure. A reusable specialist Skill describes how to interpret that source, how to investigate a lightweight skeleton, any optional bounded helpers, and how to write from it. Organization and project knowledge belongs in its own Skills rather than in community examples. Do not create one just because a topic is unfamiliar. When writing choices can solve the problem — a different outline, grouping or headings — adjust the outline instead. An unfamiliar topic is not a request for a new Provider; an actual tooling gap is explained, with its recovery, outside the knowledge page. ## How to ask for it There is no slash command for the creator. It activates when you explicitly ask, in plain language, to create a new Context Indexer Skill for code, documents, notes or session summaries. It does not activate for indexing existing sources, ordinary coding, knowledge queries or choosing an installed Skill. The creator works in your conversation language and asks only for missing source, reader or capability choices that materially affect the result. Before you start, have these ready: - **Where to create it** — the creator writes into the directory you choose. - **Which material family** — code, documents, notes or session summaries, and the technology or document type within it. - **Realistic anonymous samples** — the creator exercises realistic anonymous material for the capability it claims. For example: ```text Create a Context Indexer Skill for code built with the Acme RPC framework. Put it in ./skills/acme-rpc-indexer. Acme RPC services are declared in *.acme files and registered in each module's server entry. Use the anonymized sample module in ./fixtures/acme-sample to check it. ``` ## What it produces | You get | You do not get | | --- | --- | | A `SKILL.md` with a discoverable name and a precise description of when the Skill helps, which sources it understands and its real limits | A `context-indexer.yaml` or other Provider registration manifest | | References for substantial source-specific guidance, when needed | A primary/extension binding | | Templates, when they help readers | A version or hash verification flow or integrity receipts | | Scripts, only when a concrete repeated operation needs deterministic assistance | A per-symbol fact ledger, article producer records or a persistent producer log | Bundled resources are referenced with portable relative paths. A simple note interpreter needs no script, manifest, profile registry or template catalog. When it finishes, the creator reports the files it created, the inputs the Skill supports, how any bounded helper behaves and the remaining limitations. ## What a good Indexer contains **Recognizable signals and cheap investigation.** The Skill explains which source signals identify its material and how to examine them cheaply. The result of investigation is a **skeleton**: the source structure, recognizable features, names, counts that have actually been established, and entry locations. - For code, it identifies useful feature families from declarations or registrations, with names and locations. A dependency or filename is a hint, not proof of runtime behavior. - For documents, it uses titles, opening excerpts and heading hierarchy, with optional full reading to settle grouping. - For saved notes and sessions, it interprets the provided record directly rather than scanning history. **Bounded helpers, if any.** A technology-specific helper has an explicit input boundary, bounded time and output, and a useful stopping behavior. It returns names, counts and entry locations — not source bodies or a full symbol or relationship graph. It separates checked counts from totals, names unfinished scope, never turns file counts into feature counts or a timeout into an empty result, and stores large results in temporary files. It does not install dependencies or parse the whole repository by default; expensive semantic analysis belongs to selected writing tasks. Direct Agent investigation is a valid default when a helper adds nothing. **Topic guidance that does not own the plan.** The Skill describes which reader questions the visible signals can suggest and what further evidence the writer needs. A route family, component or storage boundary may justify a recurring outline, but never an automatic fixed number of pages. Code can establish structure while documents supply better business topics. The Agent still selects Skills and article batches. **Writing guidance.** The Skill explains source authority, meaningful reader output, real references and revision behavior, and keeps examples, assumptions and confirmed facts distinct. It consumes the current task directory rather than a schema copied from a past release, and writes drafts to the designated temporary directory. It never writes formal knowledge or adds Skill identity to formal content. The details for each family are in [Code Indexers]() and [Document Indexers](). ## How it is validated The creator validates the Skill's references and any scripts, then exercises realistic anonymous material for the capability the Skill claims. It keeps three levels of evidence apart: static validation, review of model output, and a real production run. It does not silently install dependencies or claim tests that could not run. What to check, and what each check proves: | Check | What it covers | | --- | --- | | Frontmatter and every referenced local resource | The package is complete | | New scripts against small anonymous fixtures | Empty input, a bounded partial scan, claimed failure and recovery behavior, no escape from the selected scope, no secret or source-body dumps | | Useful output, insufficient evidence and a revision of an existing article | The guidance works beyond the happy path | | Representative differences for each advertised family | For example an unadopted proposal, a document needing deeper reading, or two technologies in one module | | An actual Context run in an isolated knowledge workspace, if available and requested | Report confirmation and file submission through the existing workflow | A static resource check does not prove semantic quality, and a reviewed example does not prove that CLI submission works. Do not claim support for families you have not tested. ## Installing it and making it selectable Keep the package portable and install it through the channel you prefer. Installation makes a Skill available, not selected: the host lists the available Skills, and the Agent chooses the relevant ones for the actual materials and reader task, respecting disabled Skills and explicit business replacements. Planning records only temporary usage of the Skills it chose. Nothing about the Skill has to be restored later. Formal articles, sources and long-term scope decisions survive a new machine, while drafts, candidates, Skill choices and execution receipts stay temporary. A new user can start a fresh production run without your former Skill bundle. The creator starts no production of its own. When you want to use your new Indexer, start Context production through its existing entry. Next: - [Code Indexers]() — investigation signals, helpers and writing guidance for frameworks and technologies. - [Document Indexers]() — outlines, grouping and visuals for document families. - [Providers and Customization]() — how several Indexers combine, and how to replace or disable one. --- ## Sources - [context/plugins/context/skills/context-indexer-create/references/guides/indexer-skill-creation.md L1–L6 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/SKILL.md L12–L20 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/SKILL.md L28–L41 · 3b0ce0a]() - [context/plugins/context/skills/context-note-indexer/references/customization.md L14–L18 · 3b0ce0a]() - [context/plugins/context/skills/context-note-indexer/references/writing.md L47–L51 · 3b0ce0a]() - [context/packages/context/docs/guides/code-indexer-skill-authoring.md L75–L78 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/SKILL.md L1–L4 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/SKILL.md L12–L15 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/SKILL.md L34–L37 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/references/guides/indexer-skill-creation.md L8–L23 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/references/guides/indexer-skill-creation.md L25–L45 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/references/guides/indexer-skill-creation.md L47–L64 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/references/guides/indexer-skill-creation.md L66–L82 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/references/guides/indexer-skill-creation.md L84–L100 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/references/guides/indexer-skill-creation.md L102–L109 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/SKILL.md L39–L41 · 3b0ce0a]() - [context/plugins/context/skills/context/SKILL.md L605–L612 · 3b0ce0a]() --- ## Code Indexers # Code Indexers A code Indexer teaches the Agent how to read one technology: where its features are declared, how to find them cheaply during planning, and what to read in full before explaining them. It exposes the module's skeleton and guides source-grounded writing; it does not recreate the workflow's routing. This page covers what to put in one, following the shipped `context-code-indexer`. ```mermaid flowchart LR sig["Signals
manifests, entries, registrations"] --> skel["Skeleton
names, counts, locations"] skel --> topics["Reader topics
and writing batches"] topics -->|"report confirmed"| read["Read the code each
article needs"] read --> art["Article with
real references"] ``` ## What the Skill is responsible for Describe the supported technology, the signals that activate it, the reader questions it can help answer and how to investigate an authorized module. A module may use several Skills for different concerns — say, one for the web framework and another for its message consumers. There is no exclusive primary owner, version pin, integrity receipt or registration step before production; Skill names and usage choices are temporary planning guidance, not article metadata. Keep `SKILL.md` focused on discovery and decisions. Put detailed writing guidance and reusable scripts beside it, linked by relative path with a clear note on when to read them. ## Skeleton first During planning the Indexer should point the Agent at directories, manifests, registration points and bounded search — either for direct inspection or through a fast helper suited to the stack — and report matching names, known counts and file locations. It must not require complete symbol extraction, call graphs or reading every implementation before articles are proposed. Typical signals and the questions they suggest: | Signal | Suggests | | --- | --- | | Public exports or component declarations | How to consume a capability | | Inbound registrations or interface definitions | Which operations are served | | Event or scheduled registrations | What triggers work and how it completes | | Storage interfaces | Data ownership and transaction boundaries | | Adapters and generated clients | Contracts at an external handoff | | Package and workspace entry points | Responsibility and consumption boundaries | Signals suggest topics; they do not prove meaning. A route registration can suggest an API topic, but not its error behavior. File counts are not feature counts, and a stopped scan is never a full total. ## Bounded helpers Scripts are optional and serve one concrete, repeated task. A good helper takes explicit authorized paths and bounded options, keeps source files read-only, returns concise output or writes a file in the supplied temporary area, and stops within its budget. It reports inspected and uninspected scope, returns a continuation when it can, and labels partial counts. It must not execute repository code, read credentials, traverse unrelated directories or contact external services. Unsupported syntax and incomplete traversal are reported separately from zero matches. Full parsing belongs to selected writing tasks; where a structural fact needs a real parser, use the built-in extractors described in [Code Extraction](). ## Writing guidance Once the work-start report is confirmed, the Agent reads the source each article needs. Guide it to explain contracts, state changes, failure behavior and integration points — what the module is responsible for, how to enter it, what it hands off. Parsing can locate declarations; it is not proof of runtime behavior. Preserve expressions without executing project code, keep declared defaults apart from implemented defaults, and state unknowns. An Indexer may suggest a recurring outline for a feature family such as route groups or components, but not a fixed page count: a component manual may need component-by-component reading, while one page per symbol or a catch-all page for a large module are both wrong. Each section cites at most three real source locations; split an explanation when it needs separate evidence. ## Example outline A minimal Indexer for a hypothetical Acme RPC framework: ```text acme-rpc-indexer/ SKILL.md references/ investigate.md # where services, methods and middleware are declared writing.md # integration and maintenance guide outlines scripts/ list-services.mjs # bounded: given paths, prints service and method names with locations tests/fixtures/ orders-service/ # anonymous sample module ``` ```markdown --- name: acme-rpc-indexer description: Investigate services built on Acme RPC and write integration and maintenance articles. Use when selected for a Context planning or writing task on such a module. --- # Acme RPC Indexer During planning, read `service.yaml` files and `@Method` registrations in the authorized module. Report service names, method counts and file locations; mark partial counts as partial. For large modules run `scripts/list-services.mjs --max-files 2000`. During writing, read [writing guidance](references/writing.md). For each method, explain the request contract, errors and middleware actually applied. A generated client is outbound, not proof that this module serves the method. ``` ## Testing Test the supported technology with anonymous fixtures: feature discovery, bounded stopping, unsupported input, repeated names in different paths, and the references in the final article. For generated API explanations, check defaults, shared types and unresolved cross-file links in the final page as well as the helper output. Use fixtures relevant to the technology, not a matrix of unrelated stacks. Verify packaged relative links and executable helpers, and keep community examples free of company-specific services; organization knowledge belongs in its own Skills. See [Creating an Indexer]() for the creation flow and [Providers and Customization]() for combining Skills. --- ## Sources - [context/packages/context/docs/guides/code-indexer-skill-authoring.md L1–L5 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/SKILL.md L16–L31 · 3b0ce0a]() - [context/packages/context/docs/guides/code-indexer-skill-authoring.md L7–L17 · 3b0ce0a]() - [context/packages/context/docs/guides/code-indexer-skill-authoring.md L19–L36 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/references/indexer.md L37–L44 · 3b0ce0a]() - [context/packages/context/docs/guides/code-indexer-skill-authoring.md L58–L65 · 3b0ce0a]() - [context/packages/context/docs/guides/code-indexer-skill-authoring.md L27–L30 · 3b0ce0a]() - [context/packages/context/docs/guides/code-indexer-skill-authoring.md L38–L50 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/references/indexer.md L46–L50 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/references/indexer.md L84–L98 · 3b0ce0a]() - [context/packages/context/docs/guides/indexer-skill-creation.md L8–L18 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/references/indexer.md L94–L98 · 3b0ce0a]() - [context/packages/context/docs/guides/code-indexer-skill-authoring.md L67–L78 · 3b0ce0a]() --- ## Document Indexers # Document Indexers A document Indexer helps the Agent interpret one family of captured documents — design reviews, runbooks, API specifications, product requirements — and turn them into articles organized around reader questions rather than around the source files. This page covers what to put in one, following the shipped `context-markdown-indexer`. Notes and session summaries have their own interpreters but can support the same reader topics. ```mermaid flowchart LR outline["Titles, opening excerpts,
H2/H3 outlines"] --> group["Group by reader task
and existing topics"] group -->|"report confirmed"| read["Read the passages
each article needs"] read --> art["Articles with
regional references"] ``` ## Start from captured sources The Indexer works on authorized captured Markdown and its source identity. Capture proves which bytes are available, not what they mean; titles, headings and file names are navigation aids, not proof that the body has been read. It must not fetch new documents, follow external links or widen source authorization on its own. Missing material is requested through the current workflow, and an unavailable source is kept distinct from an irrelevant one. ## Planning from outlines For each document the CLI supplies its title, a bounded introduction and the complete H2/H3 outline, plus existing article titles, descriptions and references. The Agent reads more — a section or the whole document — only where the reader question, grouping or authority is unclear. Full reading of every document is not required before a plan can be submitted. Guide the grouping: - Reuse an existing article, including a topic first discovered from code, when it answers the same question for the same audience. - Let business definitions in documents correct a mechanical code-topic name, rather than forcing a document under a code directory. - Split distinct reader tasks or lifecycles; combine sources that answer the same task. A broad shared label such as "operations" does not make all its procedures one summary. - Neither file count nor heading count decides article count. One document may support several articles, and several documents one article. Age, archive location and polished language prove neither authority nor irrelevance; compare substance, audience and applicability. The first plan is shown in the work-start report and waits for your feedback before bulk writing, also in managed mode. ## Writing and repairs Before writing, the Agent reads the actual passages each article needs, and keeps authoritative rules, examples, decisions and proposals distinct — a suggestion in a meeting summary is not implemented behavior. Each section cites at most three real source regions; the CLI handles digests and safety, the Agent judges whether the evidence supports the explanation. A local failure is repaired at the reported section, and finished tasks can be submitted without waiting for the rest of a batch. Revisions keep stable article and section identities and preserve useful steps, examples, images and limitations. Do not inflate page counts, write one page per heading or turn missing evidence into speculative prose. ## Images, tables and diagrams Authorized images in a document arrive as registered visual resources. The Agent reads only those, prefers structured whiteboard or table data when available, and converts a clear flow, sequence, state or relationship diagram to Mermaid, or a table to Markdown, only when every label, value and footnote survives. Screenshots, photos and designs where the appearance is the information are kept as originals, and so is anything it cannot read reliably. It never guesses relationships or numbers. A document Indexer can add guidance for diagrams typical of its family. ## Example outline A minimal Indexer for design-review documents: ```text design-review-indexer/ SKILL.md references/ writing.md # decision record and architecture guide outlines tests/fixtures/ reviews/ # three anonymous design reviews, one superseded ``` ```markdown --- name: design-review-indexer description: Interpret design-review documents and write decision records and architecture guides. Use when selected for a Context planning or writing task on such documents. --- # Design Review Indexer During planning, use the title, "Context", "Decision" and "Alternatives" headings to group reviews by the system they change. A superseded review still explains history; link it from the current decision instead of dropping it. During writing, read [writing guidance](references/writing.md). State the decision, its rationale and limits; mark open questions as open. A proposal without a recorded decision is not adopted behavior. ``` ## Testing Cover the document forms the Skill claims to support: an ordinary one-to-one article, a synthesis from several documents, reuse of an existing topic, a section repair, source line changes, links and images, and missing material. Check both fidelity to the source and the final page, keep examples anonymous and verify packaged links. Drafts and scheduling details stay temporary; clearing `.tmp` simply starts fresh production from formal knowledge and available sources. See [Creating an Indexer]() for the creation flow, [Code Indexers]() for the code counterpart and [Providers and Customization]() for combining Skills. --- ## Sources - [context/packages/context/docs/guides/markdown-indexer-skill-authoring.md L1–L6 · 3b0ce0a]() - [context/plugins/context/skills/context-markdown-indexer/SKILL.md L17–L28 · 3b0ce0a]() - [context/packages/context/docs/guides/markdown-indexer-skill-authoring.md L8–L16 · 3b0ce0a]() - [context/plugins/context/skills/context-markdown-indexer/references/semantic-planning.md L3–L22 · 3b0ce0a]() - [context/plugins/context/skills/context-markdown-indexer/references/semantic-planning.md L41–L45 · 3b0ce0a]() - [context/packages/context/docs/guides/markdown-indexer-skill-authoring.md L18–L31 · 3b0ce0a]() - [context/packages/context/docs/guides/markdown-indexer-skill-authoring.md L33–L50 · 3b0ce0a]() - [context/plugins/context/skills/context-markdown-indexer/references/semantic-planning.md L47–L49 · 3b0ce0a]() - [context/plugins/context/skills/context-markdown-indexer/references/visual-source-processing.md L9–L11 · 3b0ce0a]() - [context/packages/context/docs/guides/indexer-skill-creation.md L8–L18 · 3b0ce0a]() - [context/packages/context/docs/guides/markdown-indexer-skill-authoring.md L35–L36 · 3b0ce0a]() - [context/packages/context/docs/guides/markdown-indexer-skill-authoring.md L52–L59 · 3b0ce0a]() --- ## Providers and Customization # Providers and Customization In Context, an Indexer Skill is also called an **Indexer Provider**: a bundle that provides investigation and writing guidance for one kind of source. This page explains how Providers are chosen and combined for your Context knowledge workspace, how to steer that choice — adding a specialist, replacing a built-in, disabling one — and what is and is not recorded about it. ```mermaid flowchart TD host["Skills visible in your Agent host"] --> avail["Available Indexers"] disabled["Disabled Skills"] -.->|"excluded"| avail replace["Explicit business replacements"] -.->|"preferred"| avail avail --> pick["Agent picks per material
and reader task"] pick --> usage["indexer_usage
in the temporary stage plan"] usage --> write["Writing tasks"] ``` ## How selection works When a stage is planned, the Agent declares the relevant Skills available in the current host and whether it can schedule sub-agents. It then picks the Indexers that fit the actual material and reader task and records them, with any configuration, as `indexer_usage` in the temporary stage plan; the CLI hands that guidance back during planning and writing. There is no Provider resolution stage and no primary owner to select. The Agent does not inspect caches, compare Skill hashes, resolve exact versions or keep a second installation registry — installing and enabling Skills belongs to the host. A Skill name is a discovery hint, not proof that the Skill fits. ## Combining Indexers on one module Several Indexers can explain different aspects of one module, and their findings can support the same article. A typical combination is the general `context-code-indexer` together with a specialist for the module's framework, or a code Indexer for structure with notes that explain business intent. Combining needs no primary or extension binding: each Skill contributes guidance, and a different source type alone does not call for another page. ## Adding, replacing and disabling | You want to | Do this | | --- | --- | | Add a specialist | Create it with [Creating an Indexer]() and install it where your host can see it. Installation makes it available, not selected. | | Prefer your team's Indexer over a built-in one for some material | State the replacement explicitly in your request or standing instructions; the Agent respects explicit business replacements. | | Stop an Indexer from being used | Disable the Skill in your Agent host; the Agent respects disabled Skills. | | Adjust the guidance for one task | Say so in the task. Choices recorded in `indexer_usage` are temporary and do not change the Skill. | Where a needed structural fact is missing from code, writing guidance cannot create it; that calls for a parser. See [Code Extraction](). ## Where custom Indexers live | Location | Visible to | | --- | --- | | A repository's `.claude`, `.cursor` or `.agents` directory | Anyone opening that repository in the matching host; no plugin namespace | | A user-level directory: `~/.agents/skills` (Codex, Cursor) or `~/.claude/skills` (Claude Code) | All your projects on that machine; the shipped Indexers are installed here too | | A plugin you distribute | Everyone who installs the plugin | Keep the bundle portable and use your usual installation channel. An Indexer release may carry ordinary version metadata, but production never verifies an Indexer version or hash before working. ## What the workflow records | Recorded | Not recorded | | --- | --- | | Formal articles, their sources and real references | Skill identity on articles, sections or production results | | Long-term requirements in `src/indexers.yaml`: purpose, reader goals, coverage domains and authorized sources | Production assignments or Indexer choices | | Temporary `indexer_usage`, drafts and receipts under `.tmp` | Skill hashes, version pins or a producer log | With intact temporary state, current work can resume or retry. After clearing `.tmp` or cloning elsewhere, new production starts from formal knowledge and sources, without restoring the former Skill bundle. ## Provider manifests The shipped Indexers also carry a `context-indexer.yaml` Provider manifest (protocol `context.indexer.provider/v1`) declaring their domains, activation signals, profiles, resources and supported customization steps. The SDK exposes this protocol and its validators. A new Indexer does not need a manifest — `context-indexer-create` deliberately does not generate one — and production does not require it. For the protocol and the workflow's use of Indexers, see [The Indexer System](). --- ## Sources - [context/plugins/context/README.md L5–L7 · 3b0ce0a]() - [context/plugins/context/skills/context/SKILL.md L605–L614 · 3b0ce0a]() - [context/packages/context/docs/guides/indexer-provider-and-customization.md L9–L21 · 3b0ce0a]() - [context/packages/context/docs/guides/indexer-provider-and-customization.md L64–L69 · 3b0ce0a]() - [context/plugins/context/skills/context-note-indexer/references/customization.md L3–L12 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/SKILL.md L22–L25 · 3b0ce0a]() - [context/plugins/context/skills/context/SKILL.md L611–L614 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/references/indexer.md L144–L150 · 3b0ce0a]() - [context/plugins/context/skills/context/SKILL.md L605–L611 · 3b0ce0a]() - [context/plugins/context/README.md L19–L22 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/SKILL.md L39–L41 · 3b0ce0a]() - [context/plugins/context/skills/context/references/local-install.md L7–L21 · 3b0ce0a]() - [context/plugins/context/README.md L13–L17 · 3b0ce0a]() - [context/packages/context/docs/guides/indexer-skill-creation.md L20–L23 · 3b0ce0a]() - [context/packages/context/docs/guides/indexer-provider-and-customization.md L23–L49 · 3b0ce0a]() - [context/packages/context/docs/guides/indexer-provider-and-customization.md L90–L101 · 3b0ce0a]() - [context/packages/context/docs/reference/indexer-provider-protocol.md L1–L10 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/SKILL.md L28–L32 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/context-indexer.yaml L1–L25 · 3b0ce0a]() --- ## Building a Knowledge Service # Building a Knowledge Service A **knowledge service Agent** is a resident Agent that uses the Context Skills to produce, update and answer from a team's knowledge, with people reviewing at the key decision points. It is not a new Agent platform: you take an existing Agent runtime and give it the Context Skills plugin, a Bot prompt and remote retrieval. The same Skills work anywhere — in a hosted Agent runtime or in a local coding Agent such as Claude Code, Codex or Cursor. A resident service pays off for knowledge a team shares: production involves a lot of searching and confirmation, and questions need an answer at any time. Knowledge for a small module can simply live with its repository under `docs/`. > **Status.** The community edition does not ship a Bot implementation. The runtime and service interface below describe the design planned for this site's own Bot. The Skills, the flows and the interaction lessons have been proven in practice. ## Layers ```mermaid flowchart TB entry["Entrances
website chat, team chat Bot,
scheduled task, API"] --> service["Service layer
session API"] service --> agent["Agent runtime
one isolated sandbox per session"] agent --> skills["Context Skills plugin"] skills --> base["context CLI, Agent Graph,
Source Graph MCP, Git"] base --> out["Knowledge repository,
package, website"] ``` | Layer | Made of | Responsible for | | --- | --- | --- | | Entrances | Website chat, team chat Bot, scheduled tasks, API calls | Questions, production or update requests, routine patrols | | Service layer | Session API | Authentication, rate limiting, one runtime per session, relaying the event stream, rendering results as web messages or chat cards, collecting ratings | | Agent | Hosted Agent runtime | One isolated sandbox per session; system prompt plus the Bot prompt; picks Skills by intent | | Skills | Context Skills plugin | Production: `context`, `context-plan` and the four Indexers. Retrieval: `context-inspect-search`. Same-repository docs: `context-repo-content` | | Foundations | `context` CLI with Agent Graph, Source Graph MCP, Git | Advancing and resuming the workflow, reading code remotely by commit, committing the Context knowledge workspace | | Outputs | Knowledge repository (Git), knowledge package, documentation site | Published together after a build | ## Three flows | Flow | Steps | | --- | --- | | Production | Prepare the environment (restore the workspace and source versions, `context`) → plan (the Bot prompt recognizes intent, `context-plan`) → capture (code pinned to a commit, documents snapshotted) → write (Indexer Skills, each section with source references) → review (references checked automatically, people review the diff report) → build and publish → archive (version and changelog) | | Retrieval | Prepare (mount the plugin and packages) → recognize a question → find knowledge (`context-inspect-search`: indexes first, then page bodies and evidence) → if knowledge is not enough, read originals by commit through Source Graph → answer conclusion-first with sources | | Update | Triggered by a request in chat, by a gap found while answering and confirmed by the user, or by a scheduled patrol → assess impact (compare old and new source versions, find affected articles) → revise only the affected parts and their references → people review the diff report → publish → report changed articles and the new version | ## Choosing a runtime Any hosted Agent runtime with an isolated sandbox per session works; choose on: - **Sandbox start time** — cold start dominates the first answer. - **Session length limit** — production sessions run long. - **File system persistence** — whether the Context knowledge workspace and installed tools survive between sessions. - **Egress control** — which sources and services the sandbox may reach. Keep the service layer on a generic session interface — create a session, send a message, read the event stream, end the session — so that switching runtimes does not change the Skills. ## Configuring the Bot The Bot prompt is the Bot's trusted instance configuration. Use it to: - **Set review policy.** A Bot setting can override any `context.gate.*` switch for every task it runs; precedence is Bot, then fully managed, then ordinary defaults, and an authorized task-scoped override of the two review switches still wins for that task. See [Managed Mode and Review Policy](). - **Set retrieval order.** `CONTEXT_QUERY_SOURCE_MODE` (`repo-first`, `package-first`, `dual`) and `CONTEXT_QUERY_ACCESS_MODE` (`auto`, `remote`, `local`) come from the host or Bot configuration. See [Asking Questions](). - **Describe patrols.** Scheduled tasks need their own prompts; see [Scheduled Updates](). How people interact with the Bot day to day is in [Using the Bot in Team Chat](). --- ## Sources - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L7–L11 - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L5–L5 - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L13–L24 - [context/plugins/context/README.md L1–L8 · 3b0ce0a]() - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L28–L34 - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L26–L26 - [context/plugins/context/skills/context/SKILL.md L507–L514 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L33–L54 · 3b0ce0a]() - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L49–L49 --- ## Using the Bot in Team Chat # Using the Bot in Team Chat These are the interaction patterns that proved to work when the Context Skills run behind a team chat Bot. They apply whether you build your own Bot or use the one planned for this site. > **Status.** The community edition does not ship a Bot; this site's own Bot is planned. The patterns below come from running the Context Skills behind a team chat Bot. ## Messages: start, progress, result - A task replies with three kinds of messages: **start**, **progress** and **final result**. Keep updating the same progress message instead of posting many. - The Bot **asks only when someone must decide** — confirming a work-start report, confirming publication, choosing a scope — and offers selectable options. Nobody should have to reply with a code word or review code. - When a reviewer finishes the diff report on the website, the workflow continues from there; there is no need to come back to chat to confirm. - Maintainers should not have to think about committing the knowledge repository or publishing the package and site. These complete silently by default; the Bot interrupts only for a diff review, a permission problem or a disagreement. ## Answers people can check - Every answer carries **clickable sources**: knowledge pages, code lines with their commit, and original documents. "According to the knowledge package" alone is too abstract to verify. - Each answer has thumbs-up and thumbs-down ratings. Ratings and the conversation are used together to improve retrieval and prompts. ## Capturing knowledge while you talk - When an answer is worth keeping, ask the Bot to capture it. The chat, a document you just shared, or a specific piece of code or merge request can all become sources; the Bot first proposes a plan, then runs the update flow. See [Capturing from Conversations](). - You can also ask for an update of the whole knowledge base or part of it. The Bot analyzes what changed upstream in documents and code since the last update, presents an update plan, then a diff report against the website baseline. - **Scheduled patrols** trigger at fixed times, track upstream changes and capture knowledge. A patrol prompt must state its scope, what to do when nothing changed, and which situations need a person. See [Scheduled Updates](). ## Speed - **Cold start** is the main reason a first answer is slow. Preinstall the CLI, the knowledge packages and the Context knowledge workspace in the runtime so that sessions do not install and clone each time. - **Read knowledge first**, and read originals remotely only when the evidence is not enough — fetch code by commit through Source Graph instead of cloning repositories in the sandbox. Measured effects are in [Knowledge Retrieval Benchmark](). - Simple questions still have room to improve; the target is an answer within a minute. ## Boundaries for a public Bot - Public visitors may only ask questions. Production, updates and publication are open to maintainers only, enforced by the service layer. - The Bot reads only registered public sources. Credentials stay on the server and never enter knowledge, prompts or replies. - Prefer a long-connection event subscription to connect the chat platform; it needs no public callback address. --- ## Sources - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L5–L5 - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L36–L41 - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L42–L43 - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L45–L49 - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L56–L60 - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L62–L66 --- ## Operational Knowledge # Operational Knowledge Operations skills that drive command-line tools — deploying, rotating a cache, checking a service — can be written as knowledge articles and then used directly through an Agent conversation. A knowledge service Agent reads the runbook, runs the commands in its runtime and reports back, so the procedure is documented and executable in one place. ## Getting the procedure into the knowledge base Pick the source that matches where the procedure lives today: - **Notes** for procedures that only exist in people's heads or chat threads. Save the steps as a note — original text, verbatim excerpts or a labeled summary — and let the Note Indexer turn it into a reader-facing article. Proposals stay proposals; the article does not turn them into facts. See [Notes](). - **Same-repository docs** for runbooks and authored Skills already kept next to the code, such as under `docs/` or `.agents/skills/`. Register them as an entrance; the originals remain the only place to edit them. See [Same-Repository Docs](). - **Document sources** for runbooks maintained in a document system. Write each procedure as concrete steps: the commands, the expected output, how to tell success from failure, and when to stop and ask a person. ## Variables, not values Configure the environment variables a procedure needs in the Agent runtime. The knowledge names the variables only — never their values. Credentials stay on the server side and never enter knowledge, prompts or replies, so a procedure is safe to publish in a package or on a site. ## Keeping runbooks current When a procedure changes, update its source and let the normal update flow revise the article. If the source is right but the article misleads, revise only that page. When an article ends up more accurate than the document it came from, see [Writing Back Upstream]() for keeping the two from drifting apart. --- ## Sources - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L51–L53 - [context/packages/context/docs/guides/note.md L3–L30 · 3b0ce0a]() - [context/packages/context/docs/guides/repo-content.md L1–L31 · 3b0ce0a]() - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L54–L54 - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L65–L65 - [context/packages/context/docs/guides/note.md L32–L37 · 3b0ce0a]() --- ## Connecting # Connecting Every Source Graph instance serves four entry points under the `/sourcegraph/` path of its origin. Pick the one that fits the caller; all of them run the same operations with the same rules. | Caller | Entry point | | --- | --- | | A person | The website at `/sourcegraph/` — search, code reading, repositories and the **Connect** page | | An AI Agent or MCP client | `/sourcegraph/mcp` — Streamable HTTP, stateless, JSON responses | | A script or service | The HTTP API — `/sourcegraph/v1/…` for repository reads and `/sourcegraph/api/search` for search | | A terminal | `sourcegraph-cli`, a small HTTP client for the same routes | The website's **Connect** page always shows ready-to-copy configuration for the instance you are on, including the right address and whether a token is needed. Prefer it over hand-written examples when they differ. ## Source Graph is optional Context does not require Source Graph. If you never install or configure it, Context's query skill still reads code evidence by itself: it makes a shallow, sparse partial clone of the recorded commit and searches it with grep or rg. In the default `auto` mode the skill prefers Source Graph only when an authorized instance is available, so connect one when you want pinned remote reads without local checkouts. To try it without deploying anything, use the public demo at [https://context4ai-portal.fly.dev/sourcegraph/](https://context4ai-portal.fly.dev/sourcegraph/); its MCP endpoint is `/sourcegraph/mcp`. ## Choose a credential | Credential | How to get it | What it allows | | --- | --- | --- | | None (anonymous) | — | Read-only access to repositories marked public, when the site allows public reading; rate-limited per client | | Personal API key (`sgk_…`) | Sign in, open your user settings and create an API token | The same reads as your account, over HTTP or MCP. Administrators can create keys that may also request indexing over MCP | | Service token | The `SOURCEGRAPH_API_TOKEN` setting of the instance, at least 32 characters | Every HTTP and MCP operation, including registration and indexing — for automation you control | Send keys and tokens as `Authorization: Bearer `. An invalid credential is rejected with `AUTHENTICATION_REQUIRED`; it never falls back to anonymous access. Keep credentials in your client's secret store or environment, never in shared configuration files. [Authentication and Access Control]() explains each mode in detail. ## Connect an MCP client Point any client that supports Streamable HTTP at the `/mcp` endpoint. For the public demo: ```json { "mcpServers": { "context-sourcegraph": { "type": "http", "url": "https://context4ai.org/sourcegraph/mcp?plugins=auto" } } } ``` For an instance that needs a credential, add `"headers": { "Authorization": "Bearer " }`. The Connect page also shows the equivalent command or file for Claude Code, Codex and Cursor. Naming the server `context-sourcegraph` lets Context's query Skill find it, as described in [Reading Code Evidence Remotely](). The optional `plugins` query parameter controls repository plugins for the whole connection: `auto` (default selection), `off`, or up to 16 comma-separated plugin names. Anonymous connections and personal keys get the read-only tools; `prepare` appears only for the service token and for administrator keys allowed to prepare. Use MCP tool discovery for the current input schemas — the [HTTP and MCP]() reference lists them. ## Call the HTTP API Every repository-specific request names the repository with the `repo` query parameter, as `owner/repository`. Request bodies are JSON objects with capitalized field names; unknown fields are rejected. ```bash # Search at the default branch head curl -s -X POST 'https://context4ai.org/sourcegraph/api/search?repo=context4ai/context' \ -H 'Content-Type: application/json' \ -d '{"Pattern":"timeout","IgnoreCase":true,"Paths":["packages"]}' # Read lines at the commit returned in Meta.Commit curl -s -X POST 'https://context4ai.org/sourcegraph/v1/repo/read?repo=context4ai/context' \ -H 'Content-Type: application/json' \ -d '{"Revision":"","Path":"README.md","StartLine":1,"EndLine":40}' ``` `read_many` is available only over MCP; over HTTP, issue several `read` calls. ## Use the command-line client `sourcegraph-cli` is built with the service and reads two environment variables: `SOURCEGRAPH_URL`, the instance's `/sourcegraph` base address (default `https://context4ai.org/sourcegraph`, and it must be HTTPS), and the optional `SOURCEGRAPH_API_TOKEN`. Search flags follow `rg`: ```bash export SOURCEGRAPH_URL="https://context4ai.org/sourcegraph" sourcegraph-cli search -repo context4ai/context -g '*.ts' 'OnboardingVersion' packages sourcegraph-cli read -repo context4ai/context -revision \ -path README.md -start-line 1 -end-line 40 ``` It prints the raw JSON response and exits with `3` when a request is accepted but not ready yet. All commands and flags are in the [CLI]() reference. ## The search-then-read loop Agents get the most from Source Graph with a short loop: 1. **Search** the repository. Omit the revision to use its default branch head, or pass a monitored branch or a full commit you already know. 2. **Pin the commit** returned in the result's metadata. 3. **Read** the decisive ranges at that commit — directly when the file is known, several at once with `read_many`. 4. **Continue** from the returned next line if the file goes on, and treat `Partial`, `Truncated` and coverage flags as limits, not as proof that something is absent. There is no need to list repositories or resolve the revision before every query; do that only when the repository is unknown or a request fails. A `409 INDEX_NOT_READY` means that commit has not been indexed yet — see [Operations]() for what to do. --- ## Sources - [sourcegraph/docs/interfaces.md L1–L16 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L272–L426 · 4e5c555]() - [sourcegraph/web/assets/clients.js L1–L21 · 4e5c555]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L49–L55 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L348–L352 · 3b0ce0a]() - note:20261013/demo-deployment.md · demo-deployment.md L12–L13 - [sourcegraph/internal/httpserver/runtime.go L180–L240 · 4e5c555]() - [sourcegraph/internal/sso/api_keys.go L63–L98 · 4e5c555]() - [sourcegraph/internal/sso/api_key_auth.go L20–L75 · 4e5c555]() - [sourcegraph/internal/mcpserver/plugin_connection.go L19–L62 · 4e5c555]() - [sourcegraph/internal/mcpserver/server.go L14–L82 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L241–L248 · 4e5c555]() - [sourcegraph/internal/contract/types.go L1–L46 · 4e5c555]() - [sourcegraph/internal/contract/json.go L12–L55 · 4e5c555]() - [sourcegraph/cmd/sourcegraph-cli/main.go L24–L162 · 4e5c555]() - [sourcegraph/internal/mcpserver/server.go L30–L30 · 4e5c555]() - [sourcegraph/internal/service/scoped_search.go L160–L168 · 4e5c555]() --- ## Registering Repositories # Registering Repositories A repository becomes searchable once it is registered: Source Graph then mirrors its monitored branches, keeps a window of eligible commits and indexes each branch head. Registration needs an administrator — signed in on the website — or the instance's service token. On the website, open **Repositories** and choose **Register a repository**. Over HTTP, send the same fields to `POST /sourcegraph/api/admin/v1/repos`, optionally with an `Idempotency-Key` header so retries do not register twice: ```json { "name": "context4ai/context", "code_provider": "github", "public_read": true, "index_mode": "full", "policy": { "default_branch": true, "count": 20 }, "sync_interval_minutes": 5 } ``` The request returns `202 Accepted` and queues the first sync; the repository page's jobs tab shows progress. ## Registration fields | Field | Meaning | | --- | --- | | `name` | The repository key, `owner/repository` (nested `a/b/c` paths are allowed, up to 512 characters). The Git remote is `/.git` | | `code_provider` | `github` (default) or `git`; selects which stored credential kind is used | | `public_read` | Whether anonymous visitors may read it. Omitted means public | | `index_mode` | `full` (default) indexes the whole repository; `monorepo` indexes only path groups | | `path_groups` | Required for `monorepo`; see below | | `policy.branches` | Exact branch names to monitor | | `policy.default_branch` | Also follow the remote's default branch, discovered on each sync | | `policy.days` or `policy.count` | The retention window — exactly one of days (1–365) or first-parent commits per branch (1–4096). Omit both to use the site's repository defaults (initially 30 days) | | `sync_interval_minutes` | 1, 3, 5, 10, 30, 60, 180, 360, 720 or 1440; default 5 | A policy monitors one to eight branches in total, counting the default branch. Tags are never fetched, so they cannot be searched or read. The code host is part of the build's deployment defaults (`https://github.com` in the published image); see [Configuration](). ## Private repositories Public GitHub repositories need no credential. For private ones, store a Git access token in one of two places: - **Your own credential** — signed-in users can save a token for their account. Repositories they register use it first. - **The global credential** — administrators can save a site-wide token in settings. It is the fallback for every repository. Each credential is stored per kind (`github` or `git`), encrypted with the instance's credential key, and shown as ready, expiring (within seven days), expired or invalid. As an alternative for GitHub, the `SOURCEGRAPH_GIT_TOKEN` environment variable acts as a legacy global credential: the bundled Git credential helper supplies it only for HTTPS requests to `github.com`. Registering a private repository does not hide it from signed-in users; `public_read: false` only removes it from anonymous access. Use sign-in and registration policy to control who is a signed-in user, as described in [Authentication and Access Control](). ## Monorepo path groups A very large repository can be registered with `index_mode: "monorepo"` and one or more **path groups**, so that only the directories you need are fetched and indexed: ```json { "name": "acme/platform", "index_mode": "monorepo", "path_groups": [ { "name": "web", "paths": ["apps/web", "packages/ui"] }, { "name": "api", "paths": ["services/api"] } ], "policy": { "branches": ["main"], "count": 50 } } ``` The rules: - 1 to 16 groups and at most 64 directories in total. Group names use letters, digits, `_` and `-`, up to 64 characters; an empty name becomes `default`. - Paths are relative directories without wildcards, traversal or `.git`. A directory inside another one in the same group is merged; overlapping directories in different groups are rejected. - Each group has its own partial Git mirror fetched with blob filtering, so the Git server must support partial clone (`PARTIAL_CLONE_UNSUPPORTED` otherwise). - Searches, reads, listings and diffs only see registered paths (`PATH_NOT_REGISTERED` otherwise), and a read needs its group prepared at that commit (`CONTENT_NOT_READY`). - A commit counts as ready for the repository only when every group is indexed at that same commit. ## After registration Once registered, a repository runs on its own: 1. The first sync fetches the monitored branches, records each head and builds the eligible versions from the retention window. 2. Each branch head that is not yet indexed is queued for indexing; a head that fails three times is not retried until the next change. 3. A scanner checks every minute and queues the next sync when the interval has elapsed. To search an older commit inside the window, ask for it to be prepared — from the repository page, with `POST /sourcegraph/api/admin/v1/repo/prepare`, or with the MCP `prepare` tool for authorized callers. Preparation is asynchronous; accepted does not mean ready. Editing a repository's branches or retention window clears its observed heads and versions, cancels queued and running work and waits for a fresh sync. Disabling and deleting keep the data; a deleted, disabled repository can be purged permanently after one minute. [Operations]() covers cleanup and maintenance. An instance started with `SOURCEGRAPH_SEED_DEMO=true` registers the two public example repositories, `context4ai/context` and `context4ai/sourcegraph`, following their default branch with one retained commit and an hourly sync. --- ## Sources - [sourcegraph/internal/httpserver/runtime.go L295–L311 · 4e5c555]() - [sourcegraph/web/assets/repos-page.js L93–L100 · 4e5c555]() - [sourcegraph/internal/service/service.go L160–L230 · 4e5c555]() - [sourcegraph/internal/httpserver/registration.go L9–L55 · 4e5c555]() - [sourcegraph/internal/control/model.go L22–L40 · 4e5c555]() - [sourcegraph/internal/control/model.go L59–L68 · 4e5c555]() - [sourcegraph/internal/codecredentials/manager.go L99–L155 · 4e5c555]() - [sourcegraph/internal/codecredentials/manager.go L200–L240 · 4e5c555]() - [sourcegraph/cmd/git-credential-sourcegraph/main.go L1–L36 · 4e5c555]() - [sourcegraph/internal/control/scopes.go L14–L115 · 4e5c555]() - [sourcegraph/internal/gitstore/partial.go L15–L50 · 4e5c555]() - [sourcegraph/internal/service/scoped_search.go L90–L107 · 4e5c555]() - [sourcegraph/internal/service/schedule.go L155–L230 · 4e5c555]() - [sourcegraph/internal/service/management.go L105–L140 · 4e5c555]() - [sourcegraph/cmd/repo-service/main.go L145–L154 · 4e5c555]() --- ## Self-Hosting # Self-Hosting A Source Graph instance is one container or one process with a persistent data directory. The fastest way to try it is the Docker image built from the repository: ```bash docker build -t context-sourcegraph . docker volume create sourcegraph-data docker run --rm -p 8080:8080 -v sourcegraph-data:/data \ -e SOURCEGRAPH_ORIGIN=http://localhost:8080 \ -e SOURCEGRAPH_SEED_DEMO=true \ context-sourcegraph ``` Open `http://localhost:8080/sourcegraph/`. With `SOURCEGRAPH_SEED_DEMO=true` it registers two public example repositories; public GitHub repositories need no token. Without sign-in providers the site is anonymous and read-only — add Google or GitHub sign-in to administer it, as described in [Authentication and Access Control](). The image contains four binaries — the service `repo-service`, the command-line client `sourcegraph-cli`, the Git credential helper and the Zoekt search server — and runs as an unprivileged user with `/data` as its data root and port 8080 exposed. ## Build from source Building locally needs Go 1.26 or later, Bun 1.3.9 and Git: ```bash bun install --frozen-lockfile bun run build:web bun run build SOURCEGRAPH_DATA_ROOT="$PWD/.tmp/data" SOURCEGRAPH_ORIGIN=http://localhost:8080 output/bin/repo-service ``` `output/bin` then holds the same four binaries. The service starts the search server itself and manages background indexing; there is nothing else to run. Every setting is an environment variable, listed in [Configuration](). Put credentials only in environment variables or your platform's secret store, never in the deployment JSON, source code or images. ## Choose a topology Source Graph runs either as one instance with a large disk, or as repository-sharded instances that share one PostgreSQL or MongoDB database and each own a disjoint set of repositories on their own volume. Each instance keeps its Git mirrors and indexes on local disk, so size by disk and place instances in the same region as their callers. [Deployment Recommendations]() covers how to choose, size and shard. ## Choose a database | Database | `SOURCEGRAPH_DATABASE` | Use when | | --- | --- | --- | | SQLite (default) | `sqlite` | One instance. The file defaults to `/data/sourcegraph.db`, with write-ahead logging and full synchronous commits | | PostgreSQL | `postgres` | Shared state for sharded instances, or an existing managed database. Uses serializable transactions | | MongoDB | `mongodb` | Shared state on MongoDB. Sign-in admission needs transactions, so use a replica set or a managed cluster | Pass the connection in `DATABASE_URL`: a SQLite file path, a PostgreSQL DSN or a MongoDB URI. Changing the database does not migrate data — start with an empty destination or run a separately reviewed export and import. An external database never replaces the instance's persistent volume, which still holds Git, indexes and the credential key. ## Example: Fly.io The repository's `fly.toml` deploys one instance with a `sourcegraph_data` volume mounted at `/data` and a health check on `/sourcegraph/healthz`. [Deployment Recommendations]() shows how the public demo is deployed on Fly.io from it, including the commands and the rules for serving Source Graph behind another site's reverse proxy. ## Back up and restore Source Graph has no built-in backup job. Back up four things outside the machine, with restricted access: the database, the credential encryption key, the runtime storage configuration and the repository metadata. Indexes and bare Git mirrors can be rebuilt from the remotes; identities, settings, credentials and their key cannot. - **SQLite:** use the online backup API — never copy a live `sourcegraph.db` on its own. For example: `sqlite3 /data/sourcegraph.db '.backup /data/sourcegraph-backup.db'`, then copy the result and the key and configuration files away. Alternatively stop the service and copy the database with its write-ahead log. - **PostgreSQL:** `pg_dump`. **MongoDB:** your replica-set or managed-cluster backup. To restore, stop the instance, restore the database together with its matching key and configuration, start one instance, and check administrator access, repository metadata and index recovery. Rolling back the image and restoring the database are separate operations; keep a known-good image and take a backup before upgrades. --- ## Sources - [sourcegraph/README.md L65–L78 · 4e5c555]() - [sourcegraph/Dockerfile L20–L32 · 4e5c555]() - [sourcegraph/DEVELOPMENT.md L5–L45 · 4e5c555]() - [sourcegraph/docs/deployment.md L3–L17 · 4e5c555]() - [sourcegraph/README.md L80–L91 · 4e5c555]() - [sourcegraph/internal/gitstore/fetch.go L186–L198 · 4e5c555]() - [sourcegraph/docs/deployment.md L33–L37 · 4e5c555]() - [sourcegraph/cmd/repo-service/main.go L56–L95 · 4e5c555]() - [sourcegraph/fly.toml L1–L39 · 4e5c555]() - [sourcegraph/docs/deployment.md L19–L31 · 4e5c555]() - [sourcegraph/docs/deployment.md L39–L51 · 4e5c555]() --- ## Deployment Recommendations # Deployment Recommendations Source Graph supports two deployment shapes. Each instance owns its Git mirrors, search indexes and data directory on local disk, and a database holds the shared application state. The choice between the shapes is therefore about disk and repository ownership, not about adding replicas. This page helps you pick a shape and avoid the mistakes that break it. For building the image, choosing a database and backing up, see [Self-Hosting](). ## Choose a shape | Question | One instance with a large disk | Sharded instances | | --- | --- | --- | | Repositories | Fit on one persistent volume, with Git mirrors plus indexes | More than one volume can hold, or you want to spread indexing load | | Database | SQLite (default) is enough | PostgreSQL or MongoDB shared by every instance; SQLite cannot be shared | | Routing | None; every request goes to the one instance | An access layer routes each request to the instance that owns its repository | | Operations | One machine, one volume, one backup | One volume per instance, a stable repository mapping and a shared credential key | Start with one instance unless you already know the repositories will not fit. Moving to sharding later means adding a shared database and an access layer; repositories moved to a new instance are fetched and indexed again there. In both shapes, place instances in the same region as the Agents and services that call them. Search speed comes from local indexes, so cross-region calls add latency that a larger machine does not remove. ```mermaid flowchart TB subgraph single["One instance"] s1["Instance + large volume
all repositories
SQLite"] end subgraph sharded["Sharded instances"] router["Access layer
routes by repo"] --> a["Instance A + own volume
repositories of shard A"] router --> b["Instance B + own volume
repositories of shard B"] a --> db[("Shared PostgreSQL
or MongoDB")] b --> db end ``` ## One instance - **Size the volume for bare Git repositories plus their indexes.** Keep free space above `SOURCEGRAPH_MIN_FREE_BYTES`, 1 GiB by default, which is the floor below which fetching and indexing stop. - **Run exactly one machine for the volume.** Two processes must never serve the same repositories or share one data directory, because index ownership is per process. - **Keep the default SQLite database** unless you already operate PostgreSQL or MongoDB. An external database does not replace the persistent volume, which still holds Git, indexes and the credential key. - **Measure before resizing.** Index memory and disk needs depend on repository size, so observe real indexing before changing capacity. - **Expect brief interruptions on redeploy.** Restarting a single instance may interrupt requests and indexing for a moment; persisted tasks recover after the restart. ## Sharded instances - **Share one PostgreSQL or MongoDB database** across all instances, and give each instance its own data volume. - **Set the same `SOURCEGRAPH_CREDENTIAL_KEY` on every instance.** Otherwise each instance generates its own key on its volume and cannot decrypt credentials stored by the others. - **Give each repository exactly one owner.** Assign repositories to instances with consistent hashing or an explicit repository-to-instance table, and keep that mapping stable. - **Route by the repository named in the request:** the `repo` query parameter over HTTP and the `repo` argument of an MCP tool call, in `owner/repository` form. Requests not tied to one repository, such as listing repositories, may go to any instance. - **Scale by adding shards, never replicas.** On Fly.io this means one App per shard behind your routing layer, not several Machines in one App, because Machines of one App would share repositories. ## Example: the public demo The Source Graph behind this documentation site is a demo, not a capacity recommendation. It runs as two Fly.io Apps in the `sin` region: | App | Role | Machine | | --- | --- | --- | | Portal | nginx serving the home page, the Context documentation site and `llms.txt`, and reverse-proxying `/sourcegraph/` | One shared CPU, 256 MB, auto-stop off, health check `/healthz` | | Source Graph | One instance deployed from the repository's `fly.toml` | One shared CPU, 1 GB, auto-stop off, volume `sourcegraph_data` at `/data`, SQLite, demo seeding on, health check `/sourcegraph/healthz` | The Portal forwards the whole `/sourcegraph/` prefix to the Source Graph App over the Fly private network, so the instance is reachable under the site's own domain without a second public hop. The same instance therefore has two public entrances: - [https://context4ai-portal.fly.dev/sourcegraph/](https://context4ai-portal.fly.dev/sourcegraph/), through the Portal - [https://context4ai-sourcegraph.fly.dev/sourcegraph/](https://context4ai-sourcegraph.fly.dev/sourcegraph/), on the Source Graph App itself The MCP endpoint is `/sourcegraph/mcp` under either entrance. The demo serves `context4ai/context` and `context4ai/sourcegraph` anonymously and read-only, synchronizing the `main` branch every 60 minutes. Agent Graph is not registered there, so the knowledge service reads it with local retrieval instead. To reproduce the Source Graph half, create the App and a volume of at least 20 GB, then deploy once: ```bash fly apps create fly volumes create sourcegraph_data --region --size 20 --app fly deploy --remote-only --ha=false ``` If you put it behind another site, proxy the whole prefix while preserving query strings, cookies and authorization, keep the configured external origin fixed, and do not cache sign-in, API or MCP responses. The demo repository's own pipeline deploys to Fly after a successful build of `main`. --- ## Sources - [sourcegraph/docs/deployment.md L3–L8 · 4e5c555]() - [sourcegraph/docs/deployment.md L5–L17 · 4e5c555]() - [sourcegraph/docs/deployment.md L37–L37 · 4e5c555]() - [sourcegraph/docs/deployment.md L7–L17 · 4e5c555]() - [sourcegraph/docs/deployment.md L21–L37 · 4e5c555]() - [sourcegraph/DEVELOPMENT.md L37–L37 · 4e5c555]() - [sourcegraph/docs/deployment.md L8–L21 · 4e5c555]() - note:20261013/demo-deployment.md · demo-deployment.md L5–L24 - [sourcegraph/fly.toml L1–L39 · 4e5c555]() - [sourcegraph/docs/deployment.md L19–L31 · 4e5c555]() --- ## Authentication and Access Control # Authentication and Access Control Source Graph has five kinds of caller, and every request is treated as exactly one of them: | Caller | How it is recognized | Can do | | --- | --- | --- | | Anonymous | No `Authorization` header, while public reading is on | Read-only operations on repositories marked public; rate-limited | | Signed-in user | A browser session after Google or GitHub sign-in | Read every registered repository; create personal API keys; save a personal Git credential | | Administrator | A signed-in user with the administrator role | Everything a user can, plus registering and maintaining repositories, site settings, users and global credentials | | Personal API key | `Authorization: Bearer sgk_…` | Its owner's reads over HTTP and MCP; administrator keys created with prepare permission may also request indexing over MCP | | Service token | `Authorization: Bearer ` | Every HTTP and MCP operation, for automation | Any other `Authorization` value is rejected with `401 AUTHENTICATION_REQUIRED`; an invalid credential never silently becomes anonymous access. ## Set up sign-in Source Graph signs users in with Google (OpenID Connect) or GitHub (OAuth). A provider is enabled when both its client ID and client secret are set; with neither configured, the sign-in screen explains what is missing and the site stays anonymous and read-only. | Provider | Environment variables | Callback URL | Scopes | | --- | --- | --- | --- | | Google | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | `/sourcegraph/auth/google/callback` | `openid`, `profile`, `email` | | GitHub | `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET` | `/sourcegraph/auth/github/callback` | `read:user` | `` is the value of `SOURCEGRAPH_ORIGIN`, the public origin without a path. Register exactly that callback with the provider: for Google, create an OAuth client of type **Web application** and add it as an authorized redirect URI; for GitHub, create an **OAuth App** and use it as the authorization callback URL. Store the secrets in your platform's secret store, restart the service, and sign in. When the public origin changes — for example when the service moves behind another domain — update `SOURCEGRAPH_ORIGIN` and both provider callbacks together. GitHub sign-in only identifies users; it does not grant repository access. Git credentials for private repositories are configured separately, as described in [Registering Repositories](). ## The first administrator Users are identified by provider and that provider's stable subject ID. Matching email addresses never merge identities or grant administrator rights, so the same person signing in with Google and with GitHub becomes two separate users. The first verified sign-in on a new instance atomically becomes the administrator. Configure one provider, complete the owner's first sign-in, and only then add a second provider or make the site public. Administrators can promote other users on the **Users** page; at least one enabled administrator must always remain, and administrators cannot demote themselves. ## Who may sign in The site setting **Allow other users to sign in or register** is off by default. While it is off, only administrators can sign in. Anyone else is refused with a server-rendered `403` page that shows the configurable notice in both languages, links to the project and returns to the previous page after five seconds. Turning the setting off also cuts off existing non-administrator sessions, and their personal API keys are refused with `REGISTRATION_CLOSED`. Anonymous reading is independent of this setting: visitors can still read repositories marked public while public reading is enabled in the site's access settings. A repository registered with `public_read: false` is hidden from anonymous visitors only — every admitted signed-in user can read it. ## Sessions and API keys A browser session lasts 90 days in an HTTP-only, same-site cookie scoped to `/sourcegraph`, marked secure on HTTPS origins. Signing in again replaces the browser's previous session. Personal API keys are for scripts and Agents acting as you. Create them in your user settings with a name and an optional expiry; each key starts with `sgk_` and can be copied later from the same page. Keys stop working when they expire, when you delete them, when your account is disabled, or when registration is closed and you are not an administrator. Personal keys are read-only over HTTP. Over MCP they get the read-only tools, unless an administrator created the key with **Prepare index** permission — then the `prepare` tool is also available, limited to 10 requests per minute per key and 60 per minute in total. The permission is re-checked on every request, so it lapses if the owner stops being an administrator. The service token, set with `SOURCEGRAPH_API_TOKEN` and at least 32 characters long, is compared in constant time and grants full access. Treat it like a root credential and keep it out of shared configuration. ## Access errors | Code | Status | Meaning | | --- | --- | --- | | `AUTHENTICATION_REQUIRED` | 401 | No usable credential, or an invalid, expired or disabled one | | `ACCESS_DENIED` | 403 | The credential is valid but not allowed here — for example a personal key on a management route | | `ADMIN_REQUIRED` | 403 | A non-administrator tried to create a key with prepare permission | | `REGISTRATION_CLOSED` | 403 | Sign-in is restricted to administrators | | `PREPARATION_NOT_ALLOWED` | 403 | Anonymous callers can never request indexing | | `RATE_LIMITED` | 429 | An anonymous or prepare rate limit was reached; retry after the `Retry-After` interval | --- ## Sources - [sourcegraph/internal/httpserver/runtime.go L180–L240 · 4e5c555]() - [sourcegraph/internal/service/visibility.go L9–L35 · 4e5c555]() - [sourcegraph/docs/interfaces.md L16–L16 · 4e5c555]() - [sourcegraph/internal/sso/community.go L40–L72 · 4e5c555]() - [sourcegraph/docs/authentication.md L7–L35 · 4e5c555]() - [sourcegraph/internal/sso/roles.go L116–L186 · 4e5c555]() - [sourcegraph/docs/authentication.md L1–L3 · 4e5c555]() - [sourcegraph/internal/sso/community.go L28–L39 · 4e5c555]() - [sourcegraph/internal/sitesettings/service.go L25–L35 · 4e5c555]() - [sourcegraph/docs/authentication.md L5–L5 · 4e5c555]() - [sourcegraph/internal/sso/handler.go L118–L124 · 4e5c555]() - [sourcegraph/internal/sso/api_keys.go L63–L98 · 4e5c555]() - [sourcegraph/internal/sso/api_key_auth.go L20–L75 · 4e5c555]() - [sourcegraph/internal/httpserver/website_access.go L100–L112 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L40–L56 · 4e5c555]() - [sourcegraph/internal/sso/api_keys.go L86–L92 · 4e5c555]() --- ## Operations # Operations A Source Graph instance mostly runs itself: background workers synchronize repositories, index new branch heads and remove retired indexes. Operating it means watching health and jobs, keeping enough disk, reclaiming space when needed and knowing what an error code is telling you. Administrators do most of this from the website's **Operations**, **Repositories** and **Settings** pages; the same actions exist under `/sourcegraph/api/admin/`. ## Health and status | Check | Use | | --- | --- | | `GET /sourcegraph/healthz` | Liveness — returns `{"status":"alive"}`; suitable for platform health checks | | `GET /sourcegraph/readyz` | Readiness — succeeds only when the repository catalog can be read; `503` otherwise | | `GET /sourcegraph/access-policy` | Whether public reading and sign-in are enabled | | **Operations** page | Service status, request counts, mean and maximum time and error rate for search, read and `read_many`, active jobs, and per-instance heartbeats | The **Query errors** page in settings keeps the most recent 1,000 failed queries with their request details; administrators can inspect or clear it. ## Background jobs Every repository has its own job list, shown on the repository page's jobs tab. - **Kinds:** `sync` fetches monitored branches, `index` builds an index for one commit, and `prepare` synchronizes and indexes a requested commit, across all path groups if needed. - **States:** `queued`, `running`, `succeeded`, `failed` or `cancelled`. - **Automatic and manual work** run on separate workers, so a long manual preparation does not block scheduled syncs. - **Recovery:** a running job holds a 45-second lease that its worker renews. If a process dies, another worker takes the job over after the lease expires; after three attempts it fails with `RECOVERY_EXHAUSTED`. Persisted jobs resume after a restart. - **Budgets:** a sync or index job may run for 45 minutes; a prepare job up to 16 times that, one path group after another. - **Capacity:** up to 8 active jobs per repository (or one per path group when a monorepo has more than 8 groups), and at most 256 recorded jobs. A full queue returns `QUEUE_FULL`. You can cancel a queued or running job from the jobs tab. Finished jobs are pruned automatically (see below); **Clear completed tasks** in settings removes finished records across all repositories immediately, keeping queued and running work, repositories and indexes. ## What is kept, and for how long | Data | Retention | | --- | --- | | Eligible commits | The repository's retention window — days or commit count — recalculated on each sync | | Search indexes | One per indexed commit; indexes no longer referenced by any retained commit are removed in the background | | Git mirrors | Kept until the repository is permanently deleted; changing the retention policy does not shrink them | | Finished jobs | 24 hours, or longer while a request receipt still refers to them. Automatic jobs keep at most 32 recent entries, and automatic syncs that found no changes are dropped right away | | Request receipts (idempotency) | 24 hours, at most 256 per repository | | Query error log | The most recent 1,000 entries | | Usage observations behind the statistics | 30 days | | Browser sessions | 90 days | Identities, settings and stored credentials are never expired automatically; back them up as described in [Self-Hosting](). ## Rate limits Only two kinds of traffic are rate-limited, both in one-minute windows: | Traffic | Limit | | --- | --- | | Anonymous requests | 1,200 per client and 3,000 in total per minute | | MCP `prepare` with a personal API key | 10 per key and 60 in total per minute | An anonymous client is identified by its connection address; forwarded-for headers are not trusted. Behind a reverse proxy every anonymous request therefore arrives from the proxy's address and shares one per-client allowance. When a limit is reached the response is `429 RATE_LIMITED` with `Retry-After: 60`. Signed-in sessions, other personal-key traffic and the service token are not rate-limited, so give heavy automated callers their own credential rather than relying on anonymous access. Per-request bounds — page sizes, line and byte limits — still apply to everyone; see [HTTP and MCP](). ## Disk and storage Fetching and indexing stop with `503 INSUFFICIENT_STORAGE` when free space falls below `SOURCEGRAPH_MIN_FREE_BYTES` (1 GiB by default). Reads and searches of existing indexes keep working. The **Storage** settings page shows where the bare Git mirrors live and lets an administrator move them to another absolute directory on the server; the service keeps them in a `space` folder inside it. Search indexes and their manifests always stay in the data root, so size both locations. Switching deletes the old Git copies and indexes, and every repository synchronizes and indexes again from the new location; preparation pauses until the old data has been cleaned up. ## Repository maintenance The repository page offers maintenance actions, each with a preview that shows what will be kept and how many bytes will be reclaimed: - **Add index** — index a recent commit of a monitored branch, or any full SHA inside the retention window. Ready indexes are reused. - **Cleanup** — remove every index except the latest one of each monitored branch. It requires those latest heads to be indexed, and every path group aligned on the same head. - **Delete** — permanently remove the repository, its Git mirror and its indexes. Stop running jobs before maintenance; otherwise it returns `REPOSITORY_BUSY`. A repository can also be disabled or soft-deleted from its settings, which keeps its data; a disabled, deleted repository can be purged for good one minute later. ## Common errors | Code | Status | What it means | What to do | | --- | --- | --- | --- | | `INDEX_NOT_READY` | 409 | The commit is eligible but not indexed | Wait for the head index, or prepare that commit | | `CONTENT_NOT_READY`, `SCOPE_NOT_READY` | 409 | A monorepo path group is not prepared or synchronized at that commit | Prepare the commit for that group | | `REVISION_NOT_ELIGIBLE` | 404 | The commit or branch head is outside the retention window | Use a retained commit, or widen the policy | | `BRANCH_NOT_MONITORED` | 404 | The branch is not in the policy | Add it to the repository's branches | | `SHORT_SHA_UNSUPPORTED`, `INVALID_REVISION` | 400 | Abbreviated SHA, tag, `HEAD` or another ref | Pass a full 40-character SHA or a monitored branch | | `DEFAULT_BRANCH_NOT_OBSERVED` | 409 | No sync has recorded the default branch yet | Wait for or request a sync | | `PATH_NOT_REGISTERED` | 400 | The path is outside the monorepo's path groups | Search registered paths, or add a group | | `GIT_AUTH_FAILED`, `GIT_ACCESS_DENIED` | 401, 403 | The Git host rejected the credential | Update the personal or global Git credential | | `PARTIAL_CLONE_UNSUPPORTED` | 422 | The Git server cannot filter blobs for monorepo mode | Register in full mode, or use a server that supports partial clone | | `HISTORY_SCAN_LIMIT` | 422 | A days-based window covers too much history | Use a commit count or a shorter window | | `INSUFFICIENT_STORAGE` | 503 | Free disk is below the configured floor | Free or add disk, or run cleanup | | `QUEUE_FULL` | 503 | Too many active or recorded jobs | Let jobs finish, cancel some, or clear finished jobs | | `ENGINE_RESPONSE_TOO_LARGE` | 502 | Even the smallest result page exceeded its budget | Narrow the pattern, globs or paths | | `RATE_LIMITED` | 429 | A rate limit was reached | Retry after one minute, or use a credential | --- ## Sources - [sourcegraph/internal/httpserver/repository_maintenance.go L12–L60 · 4e5c555]() - [sourcegraph/internal/service/worker.go L25–L45 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L129–L159 · 4e5c555]() - [sourcegraph/internal/httpserver/server.go L40–L68 · 4e5c555]() - [sourcegraph/internal/querylog/log.go L15–L20 · 4e5c555]() - [sourcegraph/internal/control/jobs.go L1–L50 · 4e5c555]() - [sourcegraph/internal/service/worker.go L166–L178 · 4e5c555]() - [sourcegraph/internal/control/model.go L225–L256 · 4e5c555]() - [sourcegraph/internal/control/jobs.go L100–L140 · 4e5c555]() - [sourcegraph/internal/control/telemetry.go L40–L47 · 4e5c555]() - [sourcegraph/internal/sso/handler.go L336–L340 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L40–L56 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L204–L218 · 4e5c555]() - [sourcegraph/internal/httpserver/website_access.go L54–L105 · 4e5c555]() - [sourcegraph/internal/gitstore/fetch.go L186–L198 · 4e5c555]() - [sourcegraph/web/assets/storage-page.js L1–L32 · 4e5c555]() - [sourcegraph/internal/service/storage.go L40–L105 · 4e5c555]() - [sourcegraph/internal/service/repository_maintenance.go L49–L166 · 4e5c555]() - [sourcegraph/internal/service/cleanup.go L17–L35 · 4e5c555]() - [sourcegraph/internal/service/service.go L289–L349 · 4e5c555]() - [sourcegraph/internal/gitstore/remote_error.go L1–L27 · 4e5c555]() - [sourcegraph/internal/gitstore/fetch.go L200–L244 · 4e5c555]() --- ## Getting Started # Getting Started Agent Graph is useful only as part of a Skill or an Agent host; installing the CLI does not by itself change how any Agent works. Decide which boundary you are changing first: | Your situation | Path | Start with | | --- | --- | --- | | A Skill works but has grown long, repeats context every turn, loses its place across sessions, or describes Gates and recovery in prose | Improve an existing Skill | [Migration]() | | The capability does not exist yet and its operating contract can be designed with the Skill | Create a new Skill or workflow | This tutorial, then [Authoring Graphs]() | | A product already owns Agent discovery, command execution, UI or workspace state | Embed Agent Graph in a host | [Skills and Providers]() and [CLI and SDK]() | The tutorial below needs Node.js 20 or later. Every command pins the CLI with `npx @c4a/agent-graph@0.3.0` so the results are reproducible. ## 1. Create a Provider ```bash npx @c4a/agent-graph@0.3.0 init ./example-provider --id example-provider cd example-provider ``` The generated project is a complete, minimal Provider: | File | What it is | | --- | --- | | `provider.yaml` | The Provider manifest: ID, version, Graph list and Code Catalog | | `graphs/main.yaml` | One Graph, entry `default`, an Action node `work` and a Terminal `done` | | `actions/work.yaml` | An Agent Action (`runner: agent`, `effect: write`) bound to the Skill below | | `skills/getting-started/SKILL.md` | A thin Skill whose metadata binds Provider, Graph `main` and Entry `default` | | `resources/procedure.md` | The procedure the Route requires the Agent to read | | `codes.yaml` | The Code Catalog declaring the reason code `route.main.work` | | `tests/main.yaml` | One graph test asserting the starter Route is actionable | No runtime directory is created. Where a host keeps Run files is the host's choice; the protocol reserves no directory. ## 2. Validate and test ```bash npx @c4a/agent-graph@0.3.0 validate --format json npx @c4a/agent-graph@0.3.0 test tests --format json ``` Validation checks JSON Schemas, that relative paths stay inside the Provider, IDs and references, entrypoints, explicit Terminals, edge endpoints, Subgraph calls, recursion, dynamic resource materializers and duplicate identities. It never executes an Action. For the starter it reports `"state":"valid"` with 1 Graph, 2 nodes and 1 edge; the test run reports `"state":"passed","total":1,"failed":0`. ## 3. Find the current Route ```bash npx @c4a/agent-graph@0.3.0 evaluate main --format json ``` The Evaluation contains a stable `statusCode`, a `revision` digest, one `primaryRoute`, compact alternatives and diagnostics. For the starter, the primary Route is the `work` node with `reasonCode: route.main.work`, `availability: immediate` and the catalog hint "The requested work is ready to perform." No Skill or procedure body is inlined. Resolve that Route using both values from the same Evaluation: ```bash npx @c4a/agent-graph@0.3.0 route main --revision --format json ``` The Route returns the selected node and its call path, the Action, an empty `commandPlan` (an Agent Action runs no command), the required resources — the Skill and `resources/procedure.md`, each as an absolute file path with a content digest and `readState: read-required` — and `afterAction: {evaluate: true, recordNode: "main/work"}`. If a Provider file or input changed in between, the CLI rejects the stale revision instead of returning a mismatched plan. Because the Skill already binds Provider, Graph and Entry, the same Evaluation works from the Skill alone: ```bash npx @c4a/agent-graph@0.3.0 --skill ./skills/getting-started/SKILL.md evaluate --format json ``` ## 4. Track a long task with a Run ```bash npx @c4a/agent-graph@0.3.0 run start main --state ./runtime/run.json --workspace "$PWD" # ... the Agent reads the required resources and does the work ... npx @c4a/agent-graph@0.3.0 run record main/work completed --state ./runtime/run.json npx @c4a/agent-graph@0.3.0 run status --manifest ./provider.yaml --state ./runtime/run.json --format json ``` Record with the exact `afterAction.recordNode` key. `run record` reminds you that recorded Outcomes are not proof of Facts, and `run status` evaluates again: for the starter it now returns `statusCode: complete` with `outcome: completed`. In a real Graph a historical `completed` does not override a missing fact check; the next Evaluation may route to verification or recovery instead. See [Runs and Recovery](). ## 5. Build a relocatable bundle ```bash npx @c4a/agent-graph@0.3.0 build ./dist/provider --format json npx @c4a/agent-graph@0.3.0 --manifest ./dist/provider/manifest.json validate ``` The bundle contains only reachable Provider files, a normalized `provider.yaml` and a `manifest.json` with every file digest, the Graph dependency index and an overall digest. Tests stay out, and no source-machine absolute path is written, so the bundle can be shipped inside your own package. ## Next steps - Turn the starter into a real workflow with Facts, a Gate, recovery and a loop: [Authoring Graphs](). - Cover every branch in CI and ship the bundle: [Testing and Publishing](). - Learn the evaluation model behind what you just ran: [Core Model](). - Browse runnable patterns in the repository's `examples/` directory, such as `review-gate`, `facts-recovery`, `fact-driven-batch`, `monitoring-loop` and `subgraphs`. --- ## Sources - [agent-graph/docs/en/adoption-paths.md L1–L56 · 9e8b98a]() - [agent-graph/docs/en/getting-started.md L1–L3 · 9e8b98a]() - [agent-graph/docs/en/getting-started.md L5–L12 · 9e8b98a]() - [agent-graph/templates/basic/graphs/main.yaml L1–L19 · 9e8b98a]() - [agent-graph/templates/basic/skills/operator/SKILL.md L1–L12 · 9e8b98a]() - [agent-graph/docs/en/getting-started.md L14–L21 · 9e8b98a]() - [agent-graph/templates/basic/tests/main.yaml L1–L8 · 9e8b98a]() - [agent-graph/docs/en/getting-started.md L23–L66 · 9e8b98a]() - [agent-graph/src/router.ts L261–L279 · 9e8b98a]() - [agent-graph/docs/en/getting-started.md L68–L88 · 9e8b98a]() - [agent-graph/src/runStore.ts L1–L66 · 9e8b98a]() - [agent-graph/docs/en/getting-started.md L90–L97 · 9e8b98a]() - [agent-graph/docs/en/testing-and-publishing.md L56–L71 · 9e8b98a]() - [agent-graph/docs/en/adoption-paths.md L46–L51 · 9e8b98a]() --- ## Authoring Graphs # Authoring Graphs Start from the stable work model, not from a list of commands: 1. Identify the Facts the host can actually observe. 2. Define the legal Actions and their effects. 3. State what proves each Action complete. 4. Add user Gates where authority matters. 5. Make failure, partial work, verification and recovery explicit. 6. Attach long instructions only to the Routes that need them. 7. Write graph tests for the important states and choices. 8. Bind one or more thin Skills to the Graph and Entry. Do not turn every paragraph of an old Skill into a node. A node is a state transition that is independently actionable, gated, recoverable or testable; supporting explanation stays a Resource. Module names, document IDs, dates and queue entries stay Facts — a stable Host Action resolves the current target instead of the Provider generating a node per item. ## Project layout Directory names are conventions, not protocol. All references are relative to the Provider manifest, and the loader rejects any path that escapes the Provider root. ```text provider.yaml Provider ID, version, Graph list, optional Code Catalog graphs/ Graph definitions actions/ Action contracts skills/ Agent Skills used by agent Actions resources/ Procedures, templates, schemas, dynamic view descriptors schemas/ Action input and output schemas tests/ Graph tests (not shipped in the bundle) ``` ## Worked example: a weekly report The example drafts a report, asks for approval, publishes it and checks the publication when the publish step claims success without evidence. It validates and its seven tests pass with `@c4a/agent-graph@0.3.0`. ```mermaid flowchart LR draft["draft (agent)"] -->|"completed"| approve["approve (gate)"] draft -->|"partial: repeat"| draft approve -->|"gatedBy"| publish["publish (command, external)"] publish -->|"completed"| done["done (terminal)"] publish -->|"unverified"| check["check-publication (host, read)"] check -->|"completed"| done ``` ```yaml schema: agent-graph.graph.v1 id: report entrypoints: default: draft nodes: - id: draft kind: action reasonCode: route.report.draft action: actions/draft.yaml resources: required: [resources/procedure.md] satisfiedBy: - path: report.digest exists: true - id: approve kind: gate reasonCode: route.report.approval-required gate: id: report-approval prompt: Publish this report? authority: report.publish delegatable: true satisfiedBy: - path: report.approved equals: true - id: publish kind: action reasonCode: route.report.publish action: actions/publish.yaml satisfiedBy: - path: publication.url exists: true - id: check-publication kind: action reasonCode: route.report.check-publication action: actions/check-publication.yaml - id: done kind: terminal join: any terminalOutcome: completed edges: - { from: draft, to: draft, kind: repeat, outcomes: [partial] } - { from: draft, to: approve } - { from: approve, to: publish, kind: gatedBy } - { from: publish, to: done } - { from: publish, to: check-publication, outcomes: [unverified] } - { from: check-publication, to: done } ``` Every Action and Gate has a `reasonCode` beginning with `route.`; because the Provider declares a Code Catalog, each of those codes must also appear in `codes.yaml`, or validation fails with `route-reason-code-missing`. `done` uses `join: any` because two alternative paths reach it. ## Actions ```yaml # actions/publish.yaml schema: agent-graph.action.v1 id: publish runner: command effect: external command: ./scripts/publish-report.sh ``` | Runner | Required field | What the Route returns | | --- | --- | --- | | `command` | `command` | The exact shell command | | `script` | `entry`, `runtime`, optional `args` | The runtime and the absolute installed entry path | | `agent` | `skill` | The Skill as a required file resource | | `host` | `handler` | A host-defined handler identity | Runner fields are mutually exclusive, so a host cannot read the same Action two ways. `effect` is mandatory: `read` (should not change lifecycle Facts), `write` (local mutation) or `external` (outside state may change — normally behind a Gate). `cwd` is `workspace` by default or `provider`; `inputSchema`, `outputSchema` and `files` are packaged with the Action. Agent Graph resolves Actions but does not execute them automatically; the host does, then refreshes Facts and evaluates again. ## Facts, not history `satisfiedBy` is how a node is proven complete. Checks are a restricted data model: a dotted `path` (numeric segments index arrays, as in `artifacts.0.digest`) and exactly one of `exists` or `equals` with a scalar value. There is no expression language. - Matching Facts complete a node even with no Run record — the example's `draft` is skipped when `report.digest` already exists. - A recorded `completed` without matching Facts becomes `unverified`; the example routes that to `check-publication`. - `requiresFacts` makes a node legal only under current external state; use it, not `priority`, to decide which option applies. When evidence has a lifecycle, keep it in ordinary nested Facts such as `{digest, sourceRevision, available, fresh}` and check only the fields that make it trustworthy. Every Fact feeds the Evaluation revision, so the host should publish stable states such as `fresh: false` after applying its own clock or lease — not a constantly changing poll timestamp. Keep `missing`, `unavailable`, `stale` and an explicit `false` distinct when they need different recovery Routes. To stop a producer from verifying its own work, add a separate `effect: read` host Action whose `satisfiedBy` requires a verification receipt; the host binds it to an independently authorized verifier. ## Edges and loops An edge matches explicit Outcomes; omitting `outcomes` means `[completed]`. The edge kind records intent and does not change reachability: | Kind | Use it when | | --- | --- | | `flow` | An ordinary transition (the default) | | `consumes` | The target consumes something the source produced | | `requires` | The source is a prerequisite of the target | | `gatedBy` | A Gate resolves the target's policy boundary; must start at a Gate | | `repeat` | A matching Outcome rearms an Action or Gate | Edges carry no data. Persist outputs through the host and publish references, digests or receipts as Facts. Ordinary edges must be acyclic: adding `publish → draft` on `failed` to the example is rejected with `graph-flow-cycle` and the message "use a repeat edge". A `repeat` edge is the explicit loop — the Agent does one round, records `partial`, evaluates again and gets the same Action until it records something else. Fan-out and fan-in describe reachability only; nothing runs in parallel. ## Gates and delegation Without the named authority, a Gate Route is `waiting-user` with an empty `commandPlan`. With a `delegatable` authority in the current input or Run, it becomes actionable with `resolution: session-authority`. Authority never satisfies Facts; in the example, `report.approved` must still be observed before `publish` becomes legal. A Gate can add three optional contracts: ```yaml inspectionAction: actions/inspect-review.yaml # effect: read; prepares evidence, safe before confirmation resolutionAction: actions/apply-review.yaml # effect: write or external; persists the decision after confirmation delegated: inspection: skip # only with a delegatable authority and an inspection Action resolutionAction: actions/accept-review.yaml # replaces resolution on the delegated Route only resources: { required: [], recommended: [] } # replaces the Gate's resources on the delegated Route ``` Keep the Gate prompt short and put structured decision input on the resolution Action's `inputSchema`. A host must not run the resolution while the Route still requires the user. The repository's `examples/review-gate` shows both the waiting and delegated cases. ## Resources Put long instructions in Markdown with frontmatter, and declare them on the node that needs them: ```yaml --- id: procedure.prepare kind: procedure media-type: text/markdown --- ``` Non-Markdown files such as JSON Schemas use an `agent-graph.resource.file.v1` descriptor with `id`, `kind`, `mediaType` and `path`. Dynamic context views use `agent-graph.resource.graph-action.v1` with a read-only command or script materializer, and host-produced content uses `agent-graph.resource.host-action.v1`. An agent Action's Skill is loaded only at the Action that uses it; a Gate's inspection or resolution Skill stays on that nested Action until that phase is selected. Details are in [Skills and Providers](). ## Subgraphs and ranking A `subgraph` node calls a named entry of another Graph in the same Provider. The child Route keeps its own Graph and node identity plus the parent call path, and the child's terminal Outcome flows back to the parent edge. Recursion into an ancestor is rejected statically and at runtime, and cross-Provider Subgraphs are not supported in version 1. When several Routes are legal at once, `priority` ranks them within an availability class; it never decides which option is semantically right. Every Graph needs at least one Terminal, and reaching Terminals with conflicting Outcomes is an error (`terminal-outcome-ambiguous`), never resolved by declaration order. Next, pin each of these behaviours with a test: [Testing and Publishing](). --- ## Sources - [agent-graph/docs/en/adoption-paths.md L29–L44 · 9e8b98a]() - [agent-graph/docs/en/adoption-paths.md L17–L21 · 9e8b98a]() - [agent-graph/docs/en/authoring.md L1–L17 · 9e8b98a]() - [agent-graph/docs/en/specification.md L63–L82 · 9e8b98a]() - [agent-graph/docs/en/authoring.md L19–L30 · 9e8b98a]() - [agent-graph/examples/facts-recovery/graphs/build.yaml L1–L30 · 9e8b98a]() - [agent-graph/docs/en/specification.md L172–L202 · 9e8b98a]() - [agent-graph/docs/en/specification.md L84–L105 · 9e8b98a]() - [agent-graph/docs/en/authoring.md L59–L96 · 9e8b98a]() - [agent-graph/docs/en/specification.md L137–L164 · 9e8b98a]() - [agent-graph/docs/en/authoring.md L34–L57 · 9e8b98a]() - [agent-graph/docs/en/specification.md L107–L135 · 9e8b98a]() - [agent-graph/docs/en/authoring.md L98–L122 · 9e8b98a]() - [agent-graph/examples/review-gate/graphs/review.yaml L1–L35 · 9e8b98a]() - [agent-graph/docs/en/authoring.md L124–L154 · 9e8b98a]() - [agent-graph/docs/en/authoring.md L32–L32 · 9e8b98a]() - [agent-graph/docs/en/specification.md L166–L170 · 9e8b98a]() - [agent-graph/docs/en/specification.md L56–L61 · 9e8b98a]() - [agent-graph/docs/en/authoring.md L156–L158 · 9e8b98a]() --- ## Testing and Publishing # Testing and Publishing A graph test supplies a state — `facts`, `outcomes` and `authorities` — and asserts what the Evaluation and Route must be. It never runs a command or calls a model, so it is fast, deterministic and safe in CI. ```yaml schema: agent-graph.test.v1 name: claimed publication without a URL is checked graph: report entry: default state: facts: report: { digest: "sha256:abc", approved: true } outcomes: report/publish: completed expect: statusCode: actionable primaryNode: check-publication ``` Outcome keys use the same `/` form as `afterAction.recordNode`. | Assertion group | `expect` fields | | --- | --- | | Status and selection | `statusCode`, `primaryNode`, `primaryReasonCode`, `alternativeNodes`, `availability`, `outcome` | | What the Route runs | `command`, `handler`, `recordNode` | | What the Route loads | `requiredResources`, `recommendedResources` | | Gates | `gateResolution`, `inspectionCommand`, `inspectionHandler`, `inspectionSkill`, `inspectionInputSchema`, `resolutionCommand`, `resolutionHandler`, `resolutionSkill`, `resolutionInputSchema` | | Diagnostics | `diagnosticsInclude` | Assert on schema fields and codes, never on human descriptions. ## What to cover For each production Graph, write a case for: - the initial Route, and its stable reason code; - every branch Outcome; - the user Gate and the explicitly delegated Gate; - missing required Facts; - fact-backed completion, and claimed completion without proof (`unverified`); - partial and failed batch recovery; - `join: all` and `join: any` where used; - repeat continuation and terminal stopping; - Subgraph child Routes and parent continuation; - primary and alternative ranking where several Routes are legal; - every diagnostic expected to block execution. The weekly-report Graph from [Authoring Graphs]() needs seven cases to reach that bar: | Case | State | Expected | | --- | --- | --- | | Fresh week | none | `actionable`, `draft`, `route.report.draft` | | Loop | `report/draft: partial` | `actionable`, `draft` again | | Draft observed | `report.digest` | `waiting-user`, `approve`, `gateResolution: user` | | Delegated | `report.digest`, authority `report.publish` | `actionable`, `approve`, `gateResolution: session-authority` | | Approved | `report.digest`, `report.approved: true` | `actionable`, `publish` | | Unproven publish | approved, `report/publish: completed`, no URL | `actionable`, `check-publication` | | Done | approved, `publication.url` | `complete`, `outcome: completed` | If a Provider uses dynamic or host-produced Resources, also cover coexistence of the three resource protocols, rejection of bad host input before dispatch, inline and managed-resource results, handler or schema mismatches, stale revisions and recovery of persisted results. ## Run it in CI ```bash npx @c4a/agent-graph@0.3.0 --manifest provider.yaml validate npx @c4a/agent-graph@0.3.0 --manifest provider.yaml test tests npx @c4a/agent-graph@0.3.0 --manifest provider.yaml build dist/provider npx @c4a/agent-graph@0.3.0 --manifest dist/provider/manifest.json validate ``` Pin the version for reproducible automation. Failures exit non-zero and, with `--format json`, print an `agent-graph.error.v1` envelope; branch on `error.code`. Typical codes while authoring: | Code | Cause | | --- | --- | | `graph-flow-cycle` | An ordinary edge closes a loop; use a `repeat` edge | | `route-reason-code-missing` | A node's `reasonCode` is not declared in the Code Catalog | | `test-path-missing` | The test path does not exist — an empty or missing path is an error, not a vacuous pass | Validation separately catches missing files, duplicate IDs, paths that escape the Provider, missing Subgraph entries, invalid repeat targets and recursion. ## The bundle `build` loads and validates everything reachable, then copies only what the runtime needs: Graphs, referenced Actions and their entries, schemas and declared `files`, the directories of referenced Skills, static and dynamic Resource definitions with their content, materializer Actions, and the Code Catalog with its documents. Tests and unrelated files stay out. `manifest.json` records every file digest, catalogs, the same-Provider Graph dependency index and an overall digest. It has no timestamp, so unchanged inputs give the same digest — building the weekly-report Provider twice yields an identical `sha256:` digest. The builder refuses to overwrite referenced sources and rejects any file that contains the source Provider's absolute path. Loading the bundle verifies the overall and per-file digests, the Provider identity, and that no reachable file is missing or extra. ## Ship it A Provider project normally depends on `@c4a/agent-graph` and publishes its built bundle inside its own package — a plugin, CLI or product. It can also copy the CLI's single-file `dist/agent-graph.mjs` next to the bundle for a no-install entry; that file validates and routes on Node.js 20+ and is the same implementation, not a second one. Whichever way you install it — from source, a link, a packed tarball or a registry — the Provider should return the same Graph, Action and Resource identities. Only absolute `filePath` values differ, and Route IDs change whenever relevant definitions or inputs change. Before releasing, check that: 1. no test, fixture or bundle contains credentials, business data or machine-specific paths; 2. built digests match the installed files; 3. `path:` Skill bindings still resolve after relocation, and `provider:` bindings resolve through a clean registry; 4. dynamic view materialization writes only to the explicit cache; 5. host-produced Resources never execute inside Agent Graph, and their results survive serialization and recovery validation. ## Security boundary Validation proves structure, not safety. Provider authors and the hosts that install them must review Action commands, effects, scripts and resources as executable supply-chain content. `effect: read` is a declaration, not a sandbox, and `external` effects should normally sit behind an explicit Gate or product policy. For the exact commands and SDK functions, see [CLI and SDK](). --- ## Sources - [agent-graph/docs/en/testing-and-publishing.md L1–L21 · 9e8b98a]() - [agent-graph/schemas/test-case.schema.json L1–L60 · 9e8b98a]() - [agent-graph/docs/en/specification.md L384–L386 · 9e8b98a]() - [agent-graph/docs/en/testing-and-publishing.md L23–L43 · 9e8b98a]() - [agent-graph/examples/review-gate/tests/delegated.yaml L1–L14 · 9e8b98a]() - [agent-graph/examples/facts-recovery/tests/unverified.yaml L1–L10 · 9e8b98a]() - [agent-graph/docs/en/testing-and-publishing.md L45–L54 · 9e8b98a]() - [agent-graph/docs/en/testing-and-publishing.md L85–L89 · 9e8b98a]() - [agent-graph/docs/en/specification.md L408–L410 · 9e8b98a]() - [agent-graph/docs/en/testing-and-publishing.md L56–L71 · 9e8b98a]() - [agent-graph/docs/en/specification.md L388–L400 · 9e8b98a]() - [agent-graph/docs/en/testing-and-publishing.md L83–L83 · 9e8b98a]() - [agent-graph/docs/en/testing-and-publishing.md L91–L110 · 9e8b98a]() - [agent-graph/docs/en/testing-and-publishing.md L112–L114 · 9e8b98a]() - [agent-graph/src/materialize.ts L40–L54 · 9e8b98a]() --- ## Preparing a Workspace # Preparing a Workspace Preparing a Context knowledge workspace leaves it with **usable registered sources and no unfinished task**, while keeping approved knowledge and configuration. Ask for it explicitly — for example "prepare this workspace for the next task". A clear request authorizes the task-state cleanup it describes; the Agent asks only about an unresolved target or a loss you have not agreed to. The switch that governs this is `context.gate.workspace_reset_restore`. ```mermaid flowchart LR scope["Establish the scope"] --> finish_old["End the old task
task prepare preview, then apply"] finish_old --> sources["Restore usable sources"] sources --> ready["Verify and stop"] ``` ## When you only want to capture documents Capturing named documents and pausing is not preparation and does not start article production. The Agent registers the sources and stops after reporting what was captured; existing tasks, drafts, approved content and registrations are untouched, and no `task resume` is needed. Production resumes only when you ask for knowledge. ## 1. Establish the scope The Agent locates the workspace with `context entry`, then looks at current work, running processes, Git changes and source registrations, and tells you which unfinished drafts and queued maintenance will be discarded. If a writer is still running, it waits for the result first. A broken `status` is investigated, not taken as proof that the workspace is empty. Registered sources are not an active task. Preparation does not repair invalid snapshots or change which sources are registered, and leaving a source out of one task never deletes its registration or evidence. ## 2. End the old task ```bash context task prepare --format json ``` The command first **previews** exactly which Context-owned task files — production, Review and maintenance state — would be removed. Once you have agreed to discard that scope, the Agent runs the returned apply command with its plan digest. If interrupted, it reruns the preview and uses the resume command it returns. | Removed | Always kept | | --- | --- | | Unfinished production stages, drafts, Review state and queued maintenance | Approved pages, source records and snapshots, project configuration, repository checkouts, other `.tmp` files and existing outputs | Other caches are optional cleanup. Keep reports, unique material, unknown files and modified checkouts unless you agree to lose them; never delete locks, transaction records or active tool directories. Keep repository checkouts used by registered sources — removing them forces a costly clone on the next update — and keep source-region baselines, which let updates tell moved text from changed text. Prepare **after** a successful delivery rather than straight after close: recording the version, building and retries may still need the current task. Delivery cleanup already removes completed drafts and Review state. ## 3. Restore usable sources | Source | How it is restored | | --- | --- | | Repositories | `context source recovery-plan --format json` lists what is missing; a matching local checkout is reused, or `context source restore --input --format json` clones it when authorized. Modules sharing a remote and commit are cloned once, at the registered commit — never a newer one. A dirty checkout you supplied is never reset. | | Lark documents | The stored body and required attachments are checked against the source records and repaired with the document tools. If the current remote differs from the old snapshot, that is a source update to decide, not a recovery. | | Notes, session summaries, local files | Formal source content is kept and its paths checked. Lost originals are never reconstructed from generated knowledge. | ## 4. Verify and stop The workspace is ready when the preview shows no task files, no writer is running, the configuration loads, and the selected sources resolve to their registered versions and paths. The Agent reports any blockers with their next action and then stops — it does not start writing or recapture everything. To go back to an older version instead, see [Restoring a Version](). --- ## Sources - [context/packages/context/docs/guides/workspace-prepare.md L15–L22 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-prepare.md L3–L13 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-prepare.md L24–L37 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-prepare.md L39–L52 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-prepare.md L54–L71 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-prepare.md L77–L103 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-prepare.md L105–L113 · 3b0ce0a]() --- ## Restoring a Version # Restoring a Version Restoring brings a Context knowledge workspace back to a saved state in Git: its files and the sources they need. It **does not** reset the whole repository, rewind source repositories, or bring back ignored runtime progress. An explicit restore request needs no second approval when the target and the affected files are clear. ```mermaid flowchart LR target["Resolve the target
commit SHA and path scope"] --> clear["End unfinished work"] clear --> files["Restore agreed paths"] files --> src["Restore pinned sources"] src --> check["Verify and stop"] ``` ## 1. Resolve the target The Agent inspects Git history for the workspace path and turns your request into a **concrete commit SHA and path scope**: | You say | Target | | --- | --- | | Nothing specific | The latest commit that saved the workspace — this undoes uncommitted results | | "The previous version" | The preceding saved state of the workspace, not simply `HEAD~1` of a large repository | | A SHA | That SHA, after validation | | A date | Interpreted in your timezone and meaning (for example, as of the end of that day); ambiguous candidates are confirmed with you | It then compares the target with current tracked, untracked and staged files. Files added since the target are proposed for removal; unrelated files, existing staged work and ignored source checkouts are kept. Moves and renames are accounted for. ## 2. Restore files and sources 1. Wait for any running Context writer, then abandon unfinished work with the task-state preview and apply described in [Preparing a Workspace](). Old Routes are not reused afterwards. 2. Restore only the agreed paths, preserving branch history: ```bash git restore --source= --worktree -- ``` Files added since the target are deleted explicitly. `reset --hard` and `clean -fdx` are never used as a shortcut. 3. Use the restored source records to restore pinned repository versions, module paths, document snapshots and attachments. Newer remote content cannot stand in for a lost old snapshot, and usable sources are not recloned. Old build output does not describe the restored version. If you want output, the Agent runs the current close and build; until then it reports existing output as stale. It does not start full indexing just because the old configuration is back, and if the historical format is incompatible it reports the migration or tool-version choice instead of rewriting pages silently. ## 3. Verify and stop The Agent compares the restored files with the target commit, confirms unrelated changes and index entries survived, and checks that sources are ready and no old task state remains. If only some sources could be restored, it reports partial completion with the missing access or version. Nothing is committed, rewritten or pushed automatically; commit the result separately with [Committing Results](). --- ## Sources - [context/packages/context/docs/guides/workspace-restore.md L1–L8 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-restore.md L10–L26 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-restore.md L28–L46 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-restore.md L48–L54 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-restore.md L56–L63 · 3b0ce0a]() --- ## Committing Results # Committing Results Context has no commit command of its own: the Agent uses ordinary Git. It commits **only when you ask** — fully managed production does not by itself authorize commits or pushes. When your whole requested scope has finished close and every requested build with nothing pending, the Agent mentions once that the results can be committed; intermediate deliveries do not get that suggestion. ## 1. Select the files The Agent finds the Context knowledge workspace and its actual Git root — in an embedded workspace that root may be a much larger source repository — and inspects staged, unstaged and untracked changes and the ignore rules. It selects workspace files explicitly; it never runs a blanket `git add -A` or commits the entire staged index. The `.gitignore` that `context init` writes already separates formal content from runtime state: ```text .tmp/ node_modules/ dist/ sources/repo/* !sources/repo/index.yaml sources/**/.tmp/ sources/**/.cache/ ``` So configuration, source records and snapshots, approved `knowledge/`, translations and changelogs are committed; `dist/`, `.tmp/` and repository checkouts are not — checkouts are recovered from `sources/repo/index.yaml`. Ignored files are never force-added, and generated files are included only if your project's rules require them. The full ownership table is in [The Context Knowledge Workspace](). If there is no Git repository yet, the Agent agrees with you where it should be before initializing one; if nothing changed, it reports that no commit is needed. An intermediate snapshot cannot resume ignored task state from Git alone. ## 2. Commit the selected change The Agent summarizes the actual change and writes a message that follows your repository's conventions, committing precise paths: ```bash git commit --only -- ``` `--only` leaves unrelated staged files out; new files must be added to the index first. Partially staged files that overlap the selection are inspected so that nothing you did not select slips in, and unrelated staged entries — including deletions — are preserved. Git identity, hooks, signing, conflicts and permissions are diagnosed, not bypassed: the Agent does not disable hooks or signing, change global Git configuration, stash your other work or work around ignore rules. It uses an authorized alternative or reports the blocker. ## 3. Verify the result The Agent reads the new commit SHA and its changed files, compares them with the selected scope, and checks that unrelated worktree and index content are unchanged. If a hook modified the result, it reports that. It finishes with the SHA and a short description, and does not push, publish or create a remote repository unless you ask for that too. --- ## Sources - [context/packages/context/docs/guides/workspace-commit.md L1–L7 · 3b0ce0a]() - [context/plugins/context/skills/context/SKILL.md L500–L505 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-commit.md L9–L23 · 3b0ce0a]() - [context/packages/context-cli/src/project/workspace.ts L454–L465 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-commit.md L25–L37 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-commit.md L39–L45 · 3b0ce0a]() --- ## Best Practices # Best Practices These practices come from teams using Context to build knowledge for large engineering organizations. Most of them are about one thing: **correct course early**, while it is cheap. ## Talk first, then start After initializing the Context knowledge workspace, have a free conversation before any production. Explain what the knowledge should cover, where it comes from — document links, repository addresses, the modules you care about — and what form you expect. The Agent researches and asks back until it can write a **work-start report**: the confirmed configuration and scope, the planned content, and the expected package or site layout. See [Start Reports](). Production then takes time — on average about one minute per task. The Agent keeps reporting progress and the total number of tasks, and you can ask for a local preview at any point. After publication, check the package and other outputs; the Agent commits the workspace to Git to close the production. ## Preview early, correct with examples On a large task, open the work-start report and the changed pages as soon as they are available. If something is off, ask for a revision and be specific: show the wording you want, give a counterexample, describe the style. The earlier you correct, the better the final quality. ## Three questions for every review The review report decides the scope and quality of what gets approved. Read it with three questions: 1. Does the **structure** — topics, directories, documents — match what you expected? 2. Does the **content** — the intent of each article, its style — match what you expected? 3. Is anything relevant still **missing from the scope**, or included that should be left out? See [Reading Review Reports](). ## Reorganize once the knowledge grows First-version titles tend to be abstract, and directory names and structure are rarely ideal. Once the knowledge has grown, ask the Agent to research the approved knowledge again and propose a more readable, intuitive directory and article structure — it does this better now than it could during planning. Revise, then observe for another round. Revising costs far less than producing again and suits fine-tuning of both structure and content. See [Reorganizing at Scale](). ## When documents lag behind code Production cross-checks sources, and documents lagging behind code is normal. By default the Agent revises the knowledge to match the code. To fix the upstream documents as well, add a rule at the start of the task or in the workspace `AGENTS.md`: ```text When a revision is caused by a document lagging behind code, record it in update-remote/-.md with the context, the judgment and a suggested fix. After the task, work through update-remote: find each upstream document and revise it, or give a concise suggested fix for the user to decide. ``` Upstream documents then stay current and the knowledge does not drift away from them. See [Writing Back Upstream](). ## Split very large work into batches A very large task goes through planning first, with at most about 30 to 50 documents per batch. Each batch is produced, published, recorded in the plan file (`PLAN-*.md`) and committed before the next one starts. See [Planning a Large Project](). --- ## Sources - note:20261012/usage-practices.md · usage-practices.md L1–L3 - note:20261012/usage-practices.md · usage-practices.md L5–L9 - note:20261012/usage-practices.md · usage-practices.md L14–L14 - note:20261012/usage-practices.md · usage-practices.md L16–L22 - note:20261012/usage-practices.md · usage-practices.md L24–L26 - note:20261012/usage-practices.md · usage-practices.md L28–L37 - note:20261012/usage-practices.md · usage-practices.md L11–L13 - [context/plugins/context/README.md L33–L46 · 3b0ce0a]() --- ## Choosing Models # Choosing Models Context works with whichever model your Agent runs, but the choice changes speed and cost a lot. The roles below come from teams' experience; the model names are examples of each role at the time of writing, not endorsements. ## Four roles | Role | Example | Use it for | | --- | --- | --- | | **Primary** | Claude Opus 5.5 | First creation, everyday production and querying. Roughly two to three times faster than the others, and in practice it consumes less. | | **Balanced** | GPT 5.6 SOL, Grok 4.6 | Moderate speed and cost; text, code and medium-intensity code exploration. | | **Low-cost and fast** | DeepSeek 4.1 Flash | Processing documents meant for people and summarizing code. | | **High-end** | GPT 6.0 Astra | Planning the first build of a very large knowledge base and deep attribution in code. Expensive. | For large work you do not need to orchestrate several Agents yourself: Context's built-in multi-Agent scheduling runs the work in parallel. ## How much it matters when answering In one benchmark run, with the same knowledge and the same retrieval method, two models both fully resolved 23 of 24 questions — but one averaged 139.3 seconds and the other 304.0 seconds, about 2.2 times as long. At equal quality, model choice can more than double answer time. This is a single run on one question set, so treat it as an indication rather than a ranking. The method and its limits are in [Knowledge Retrieval Benchmark](); to measure your own setup, see [Evaluating Your Knowledge Base](). --- ## Sources - note:20261012/usage-practices.md · usage-practices.md L39–L45 - note:20261012/usage-practices.md · usage-practices.md L39–L44 - note:20261012/benchmark-summary.md · benchmark-summary.md L65–L67 - note:20261012/benchmark-summary.md · benchmark-summary.md L76–L79 --- ## Prompt Recipes # Prompt Recipes You drive Context by talking to your Agent. These are phrasings that work for common requests; replace the placeholders in angle brackets. Each one is a starting point — the Agent researches, asks back where needed, and stops at the decisions that are yours. ## Producing and revising | You want to | Say | What happens | | --- | --- | --- | | Start | "Initialize a Context knowledge workspace in `` and build knowledge for `` and ``. Research first, then give me the work-start report." | Workspace setup, source research, then a work-start report for you to confirm | | Add material | "Add `` as a source, re-plan the affected parts and give me a new work-start report." | Source registration and a revised plan | | Revise | "Revise `
`: ``. Keep the source references." | A revision task and a review report for the changed page | | Reorganize | "Research the approved knowledge again and propose a more intuitive directory and title structure. Revise after I confirm." | A structure proposal, then revisions | | Plan a large project | "Plan a knowledge project for ``." | The `context-plan` Skill researches and writes a `PLAN-*.md` for review | ## Updating, evaluating and migrating | You want to | Say | What happens | | --- | --- | --- | | Update | "The sources have moved to ``. Find the affected knowledge and review the updates." | Impact assessment, targeted revisions, a review report | | Evaluate | "Evaluate the current knowledge base with ``, grade each answer on the four-level criteria and give me P50/P90." | An evaluation run with grades and timings | | Migrate | "Research what Context can do, then migrate the current knowledge base …" | See [Migrating an Existing Knowledge Base]() for the full prompt | ## Building and asking | You want to | Say | What happens | | --- | --- | --- | | Build and preview | "Build the knowledge package and documentation site, and give me a local preview." | `context build`, then a local HTTP preview whose URL is checked before it is shared; publishing to hosting needs your separate authorization | | Ask a question | "Using the `` knowledge, how does `` work?" | `context-inspect-search` answers from the knowledge with sources and reports gaps | The commands and Skills behind these requests are listed in [Commands and Skills](). --- ## Sources - note:20261012/usage-practices.md · usage-practices.md L5–L7 - note:20261012/usage-practices.md · usage-practices.md L62–L70 - [context/plugins/context/README.md L33–L40 · 3b0ce0a]() - note:20261012/usage-practices.md · usage-practices.md L62–L72 - note:20261012/usage-practices.md · usage-practices.md L47–L60 - [context/packages/context/docs/guides/package-outputs.md L417–L421 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L1–L30 · 3b0ce0a]() --- ## Migrating an Existing Knowledge Base # Migrating an Existing Knowledge Base If you already have a knowledge base — an LLM Wiki, a set of Skills, a documentation folder — you do not have to start from nothing. Create a Context knowledge workspace, describe the existing base to the Agent, and let it plan the migration up to the work-start report, where you review the approach and decide the batches. ## The migration prompt Once the workspace exists, start with: ```text Research what Context can do, then migrate the current knowledge base: - Location, content and document scope of the current knowledge base: - How it is produced today (scripts, prompts, and so on): - Desired published structure and form: keep it as is, or new requirements - Historical Q&A or an evaluation question set, to show how the knowledge base is used Turn this into a research report, continue up to the work-start report and pause. I will review the approach and plan the batches. ``` The last item matters most: real questions tell the Agent what the knowledge base is *for*, and they become your evaluation set later. ## Bringing the existing material in Existing material can be connected in different ways, depending on whether it should become a source of new articles or stay where it is: - **Document directories** — register a folder of existing documents as a source so its contents are captured and cited. See [Document Directories](). - **Same-repository docs and Skills** — documents and authored Skills already kept in the same repository are registered as an entrance; the originals stay where they are and remain the only place to edit them. See [Same-Repository Docs](). - **External entrances** — content elsewhere that pages should link to, declared in `imports.yaml` without downloading or capturing it. See [External Entrances](). ## Switch over after you have measured Keep the old knowledge base running until the new one is proven. Run the same question set against both and compare quality, time and tool calls, as described in [Evaluating Your Knowledge Base](). --- ## Sources - note:20261012/usage-practices.md · usage-practices.md L47–L60 - [context/packages/context/docs/guides/imports.md L1–L7 · 3b0ce0a]() - [context/packages/context/docs/guides/repo-content.md L1–L5 · 3b0ce0a]() - note:20261012/usage-practices.md · usage-practices.md L73–L75 --- ## Evaluating Your Knowledge Base # Evaluating Your Knowledge Base Answer quality and speed depend on the knowledge — its accuracy, completeness and links to evidence — but also on the model, the runtime, retrieval planning and how tools are executed. A good evaluation compares your knowledge base against an alternative, or against its own earlier version, on real questions, and then uses the run traces to find out *why* answers were slow or wrong. This page is the design guide: follow it, or hand it to an Agent, to plan an evaluation for your own business. The exact grading, statistics and timing rules are in [Evaluation Scoring and Timing Standard](); a complete worked run is [Knowledge Retrieval Benchmark](). ```mermaid flowchart LR set["1 Questions
and guides"] --> freeze["2 Freeze
conditions"] freeze --> run["3 Run and
keep evidence"] run --> grade["4 Blind
grading"] grade --> review["5 Review and
attribute"] review --> report["6 Publish with
limits"] ``` ## Decide what you are measuring - **Grade the final answer the user received.** Ask two things: is the core conclusion correct, and did it deliver what the question asked? Traces explain retrieval, tools and time; the Agent does not have to show its reasoning or retell how it checked. - **Report quality, end-to-end time and visible tool calls separately.** Do not merge them into one score with arbitrary weights. - **You are comparing whole setups.** Even with the same model, knowledge organization, system prompt, tools, permissions and runtime can differ, so not every difference belongs to the knowledge base. - **Say what is out of scope.** Answering with deployed knowledge is one thing; producing and updating the knowledge — its quality, time, review effort and cost — is another, and needs its own evaluation. ## Build and freeze the question set 1. **Sample real user questions.** Keep their wording, necessary context and terms. Follow-ups that belong together can be merged into one frozen input, but never add answer hints, source paths, extra locating words or grading requirements. 2. **Give every question a stable ID and keep its origin.** The input sent to an Agent contains only the user's question — no ID, earlier answer, rubric or reference evidence. 3. **Turn images into faithful text** when they cannot be sent identically to every setup; mark unreadable parts as unknown. Leave out questions that cannot be answered without the missing image, and add them in a later version. 4. **Separate rule explanations, code lookups and live troubleshooting.** Do not quietly add online permissions, deployment versions or real requests the user never gave. 5. **Freeze the list and record its hash.** Questions already used to tune prompts or fill knowledge gaps are a *regression set*; keep unseen *held-out* questions to check that improvements generalize. 6. **Cover the questions people actually ask** — for example locating interfaces and pages, interaction rules, parameters, permissions and roles, versions and call relationships, debugging and environments. ## Write a guide for every question Each question gets its own file with: - the exact test input; - the date it was checked, the source version (a pinned commit) and what is still unchecked; - the confirmed reference facts and the conditions under which the conclusion holds; - what the answer must deliver; - acceptable equivalent wordings, other valid approaches, and what is **not** required; - concrete criteria for each of the four grades, and counterexamples that would overturn a wrong claim; - where the evidence is, which fact it supports, and known gaps. The reference answer is for checking facts. It does not prescribe length, headings, number of citations, tool order or a full chain of proof, and it is not a template to reproduce. A conclusion that stayed inside the Agent's process and never reached the user does not count. When a deciding fact cannot be verified, mark it pending rather than borrowing an earlier assistant's answer or a knowledge page as proof. If a guide later turns out to be incomplete, record the correction with evidence instead of failing every answer that disagrees with the old guide. ## Freeze the comparison conditions Fix, and write down, everything that could change the result: - question text, model and reasoning settings, knowledge and source-code scope, system prompt, tool permissions, region and dates; - whether a setup answers from **knowledge only** or **knowledge plus source checks** — never let only one side read sources without saying so; - cache and long-term memory state, concurrency, run order and number of repeats. Start a new task for every question and send every setup exactly the same text. Grading guides never enter the answering context. The default recommendation is **three runs per question, concurrency one, alternating setup order**, with the order or random seed recorded; state it plainly when you choose otherwise. Each change to the questions, guides or configuration gets a new version and a new results directory; old material is kept, and re-runs never overwrite earlier results. ## Run and keep the evidence For every attempt, keep the start and end timestamps with time zone, task or session IDs and links, the complete final answer, the raw tool events, the status, timing precision and any anomaly. The first progress message is not the answer; even when a platform marks a task done, check that the answer was actually delivered. Keep the original receipts of platform failures, timeouts, cancellations, quota refusals and retries. An extra run is linked to the attempt it repeats; never replace a result with the best of several. If a question needs the user to supply more information, define one multi-turn protocol for every setup and label any ad hoc follow-up or resume. If the Agent under test is configured for a chat channel — for example it assembles reply cards — a direct-call evaluation may still run channel checks and card preparation. To measure answering alone, switch to a reply policy suited to direct calls, or record that overhead separately. ## Grade blind, then review - Give each answer a random alias per question and record the seed. First-pass graders see neither the setup nor the time, tool count or earlier scores. Links or wording inside an answer can still reveal its origin, so call this *limited* anonymity. - Check material errors first, then whether the question was fully answered, and assign one of four grades — or *pending verification* when a deciding fact cannot yet be checked. The rules are in the [standard](). - Review every material error, pending item, partial resolution and borderline call, and spot-check full resolutions. Graders must give reasons someone else can check; length, style, tool order and whether the process is shown are not reasons on their own. - Check grader consistency with separate calibration samples: the same facts in a short and a long version, as a paragraph and as a table, and the same pair shown in swapped order should get the same grade. Without human-labelled samples, call it *internal consistency review*, not human calibration. ## Find the causes Numbers say *that* something is slow or wrong; traces say *why*. Only after grading, reveal which setup produced which answer, then read the raw tool trace and classify each gap: - **Wrong or missing knowledge** — the knowledge base does not cover the fact, or states it wrongly. - **A key condition left out** — for example a component's branch condition, leading to an over-generalized answer. Turn such gaps into revision tasks. - **Search scope misjudged** — for example concluding "nothing calls this" from a partial checkout. - **Inference or generalization error**, or **delivery gap** — the Agent knew it but did not tell the user. - **Evidence unreachable**, **repeated searching**, **channel overhead** or **waiting for startup**. A log supports only the behaviour it actually shows, and correlation is not cause. More tool calls do not mean more care, and faster does not mean more accurate. ## Publish results with their limits Show the four grade counts with their denominator, mean, P50 and P90 time, visible tool calls, and the sample and protocol. Compare on all questions *and* on the subset every setup fully resolved. Link each question to its answer, guide, grading, timings and evidence, and seal the raw package with a manifest and hashes. State everything a reader needs to interpret the numbers: how many times each question ran (a single run says nothing about stability), differences between environments, system prompts, models, versions, dates, concurrency and timeouts, whether the questions had been seen before, how many graders there were and whether they were calibrated, what the timings include, and how any cost figure was estimated. Label every improvement figure as measured, conditional estimate (with its formula and assumptions) or untested direction. ## What the evaluation should produce For the target business: a question document with origins, a separate scoring standard, one guide per question, a collection plan (configurations, repeats, order, timeout, recorded fields), a raw-records directory and a summary report. Freeze the questions and criteria before running any Agent. A new business checks its own sources, question scope, required conditions and counterexamples; it does not reuse another business's factual judgements. ## Have an Agent design it An Agent can draft the whole plan if it reads this page and the standard first. Copy the prompt below, fill in the brackets, and review the result before any run: ```text Read the "Evaluation" group of the Context documentation at https://context4ai.org/context/llms.txt — "Evaluating Your Knowledge Base", "Evaluation Scoring and Timing Standard" and "Knowledge Retrieval Benchmark". Then design an evaluation of [knowledge base or assistant] against [baseline or earlier version] for [business area]. Produce, without running anything yet: 1. A question document: 20–30 real user questions sampled from [where], each with a stable ID, its origin, the frozen input text and its question type. 2. A scoring standard adapted from the documented one: two primary metrics, material errors, four grades and pending verification. 3. One guide per question: checked facts with the pinned source version, required deliverables, acceptable alternatives, what is not required, grade criteria, counterexamples and evidence locations. Mark anything unverified. 4. A collection plan: configurations to freeze, repeats, order or seed, concurrency, timeout, timing events and every field to record. 5. A blind-grading and review plan, and the report outline with its limits. Do not reuse facts from the documentation's examples, do not add hints to the questions, and list every decision you need from me. ``` --- ## Sources - note:20261013/evaluation-method.md · evaluation-method.md L5–L9 - note:20261013/evaluation-method.md · evaluation-method.md L25–L32 - note:20261013/evaluation-method.md · evaluation-method.md L7–L10 - note:20261013/evaluation-method.md · evaluation-method.md L36–L43 - note:20261013/evaluation-method.md · evaluation-method.md L45–L57 - note:20261013/evaluation-method.md · evaluation-method.md L28–L29 - note:20261013/evaluation-method.md · evaluation-method.md L34–L34 - note:20261013/evaluation-method.md · evaluation-method.md L123–L123 - note:20261013/evaluation-method.md · evaluation-method.md L29–L29 - note:20261013/evaluation-method.md · evaluation-method.md L129–L137 - note:20261013/evaluation-method.md · evaluation-method.md L30–L31 - note:20261013/evaluation-method.md · evaluation-method.md L87–L89 - note:20261013/evaluation-method.md · evaluation-method.md L111–L116 - note:20261013/evaluation-method.md · evaluation-method.md L139–L141 - note:20261013/evaluation-method.md · evaluation-method.md L32–L32 - note:20261013/evaluation-method.md · evaluation-method.md L124–L125 - note:20261013/evaluation-method.md · evaluation-method.md L143–L145 - note:20261013/evaluation-method.md · evaluation-method.md L27–L32 --- ## Evaluation Scoring and Timing Standard # Evaluation Scoring and Timing Standard This page is the rulebook referred to by [Evaluating Your Knowledge Base](). Use it as written, or adapt it and say what you changed. It covers how one answer is graded, how grades become rates, and how time and tool calls are measured. [Knowledge Retrieval Benchmark]() applies it. ## Industry methods it draws on The standard borrows ideas from published work. The four grades, sampling and recording conventions are choices made for this project, not an industry-wide standard. | Source | What was borrowed | | --- | --- | | [SimpleQA](https://openai.com/index/introducing-simpleqa/) (OpenAI) | Classify answers as correct, incorrect or not attempted, and count "not attempted" separately so refusals are neither errors nor successes. | | [FACTS Grounding](https://deepmind.google/blog/facts-grounding-a-new-benchmark-for-evaluating-the-factuality-of-large-language-models/) (Google DeepMind) | First judge whether the answer addresses the request, then check its factual grounding — two separate judgements. | | [Demystifying evals for AI agents](https://www.anthropic.com/engineering/demystifying-evals-for-ai-agents) (Anthropic) | Grade an Agent by its outcome rather than a fixed tool order or path; keep the full trace to explain the result. | | [Ragas Factual Correctness](https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/factual_correctness/) and [Faithfulness](https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/faithfulness/) | Distinguish "agrees with the reference facts" from "agrees with the retrieved material": material can be stale or miss a condition, so faithfulness is not correctness. | | [Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena](https://arxiv.org/abs/2306.05685) | Model judges show position, verbosity and self-preference bias; swap order, anonymize and check with calibration samples. | | Nearest-rank percentile | P90 is the ⌈0.9 × n⌉-th sorted sample, so the figure is always a real, checkable run. | ## Two primary metrics and material errors | Metric | What is judged | Recorded value | | --- | --- | --- | | Core-conclusion correctness | Do the key conclusions given hold within the question's scope? Is a condition missing that makes them misleading? | correct / material error / no gradable conclusion / pending | | Request fulfilment | Was what the user asked for actually delivered? Judged only against the question and its necessary context. | full / partial / not met / pending | Material errors are recorded separately as yes, no or pending. For a yes, record the exact claim, the evidence against it and its effect on the user's judgement or action. Any one of these, once confirmed, is a material error: 1. the core conclusion is wrong; 2. a key recommendation would lead the user to do the wrong thing; 3. deciding evidence is fabricated; 4. an unverified live situation is asserted as confirmed fact; 5. a necessary condition is left out, turning the answer into a wrong unconditional statement. Typos and minor wording issues that change no judgement or action are only noted. A correct main conclusion with a materially wrong side recommendation is still a material error. Correct but irrelevant extra information earns nothing. ## Four grades and the grading order | Grade | Rule | | --- | --- | | Fully resolved (`resolved`) | Core conclusion correct, request fully met, nothing materially misleading. | | Partially resolved (`partially_resolved`) | Useful, correct content delivered, but part of the request or a needed fact is missing; no confirmed material error. | | Material error (`material_error`) | The core conclusion or a key recommendation is materially wrong, including misleading unconditional generalizations and fabricated deciding evidence. | | Not resolved (`unresolved`) | No substantive answer — only a plan, only a request for more information, or "cannot answer". A wrong refusal that itself contains a confirmed key error is still a material error. | **Order:** first look for confirmed material errors, then judge coverage of the request. Correct content does not offset a key error. **Pending verification** (`pending_verification`) is a review state, not a fifth grade. When a deciding fact cannot be checked yet, keep the check open and do not grade; never record it as pass or fail. If existing evidence already confirms a material error, grade it directly. **Needs more information** is an interaction state that can coexist with a grade: only asking questions is not resolved; answering part and then asking can be partially resolved. ## Fairness rules - Accept semantically equivalent short answers, long answers, lists, tables and different valid evidence paths. Check meaning and facts; do not match the reference text, fixed wording, headings or tool order. Form gains or loses nothing unless it actually hinders understanding, hides a key condition or creates ambiguity. - A condition is necessary only if it changes the conclusion or what the user does. Do not universally require version fields, full call chains, parameter flows, edge-case lists or next steps. - For "how do I debug this", the actionable method, prerequisites and steps are the deliverable; how the Agent searched need not appear. - For "list all", check the complete set within the question's scope — a few correct examples may be only partial. Side topics the user did not ask about are not omissions. - The user's assumptions, counts or terms may be wrong. Correcting the premise accurately and answering the real question can be fully resolved. - Separate static rules from live facts. Honestly admitting an evidence gap is not an error, but the unfinished part of the request is still recorded. - Missing citations, an unshown process or a short reply are not grounds for calling a conclusion wrong. Sources are a deliverable only when the user or the shared test protocol asks for them, told identically to every setup. Volunteered citations are checked for existence and support, not counted for points; a temporarily unreachable link is not fabrication. Local evidence existing, a link path being correct, and the link opening for the user's account are three different checks. ## Using counterexamples The grader asks: within the question's scope, is there an evidenced case that overturns a deciding claim, or shows that an omission would change the user's judgement? The counterexample must belong to the question's scope and affect the conclusion — do not widen the question on the fly. The answer need not contain a "counterexamples" section; a correct condition or scope statement is enough. Not mentioning a branch is not itself an error. An answer that keeps its scope and generalizes nothing wrongly but skips part of the request is partially resolved. ## Three calibration patterns These patterns are rewritten from real grading decisions with every business detail removed. **A definition existing is not a call happening.** *Where does the front end call an old endpoint?* The code keeps a request wrapper and a monitoring list registers the address, but nothing in the checked scope calls it; pages now use a newer endpoint. - Saying "no business call was found in the checked scope" fully resolves it. - Listing the wrapper without judging whether it is called is partial. - Treating the monitoring entry as a request, or claiming the endpoint is absent from the code entirely, is a material error. - Only suggesting searches is not resolved. Lesson: grade the real meaning and the user's intent, allow correcting the premise, and never score by how often an address appears. **Role differences are also gated by state and permission.** *What can an owner do on a list page that a non-owner cannot?* In reality each action has its own conditions — role, workflow state, item type — and a detail entry is further controlled by a switch and an organization grant, so non-owners may also reach it. - Stating the differences with their conditions fully resolves it. - "Non-owners see no actions" or "owners can always act" is a material error. Lesson: counterexamples test unconditional generalizations. Necessary conditions come from the question's scope; the answer need not show the grader's whole control chain. **An outer choice and an inner data switch are different layers.** *When the current workflow is the new version, does viewing an old snapshot bring back the old interface?* The parent page picks a component from the *current* workflow; switching history inside it only changes the data. Only a different component renders history by its own version, and a revision number is not a version generation. - Explaining both layers fully resolves it. - Asserting that history always restores the old interface, or treating the revision number as the generation, is a material error. Lesson: when existing knowledge misses the parent-level condition, go back to the source and correct the criteria — do not treat a knowledge page as the answer key. ## Grader calibration and review - Give each answer a random alias per question and record the seed. First-pass grading hides setup, time, tool count and earlier scores. Links or wording inside an answer can still reveal its origin, so state that anonymity is limited. - Check consistency with separate calibration samples: the same facts short and long, as a paragraph and as a table, should get the same grade, and swapping the display order of two answers should not change the judgement. Store calibration samples apart from the real questions. - Review every material error, pending item, partial resolution and borderline call, and spot-check full resolutions. Graders give reasons someone else can check; length, style, tool order and whether the process is shown are not universal plus or minus points. - With only model graders and no human-labelled samples, call it an *internal consistency review*, never human calibration. ## Denominators and statistics - With Q frozen questions and R repeats, each configuration plans **N = Q × R** runs. Every grade rate divides by N; a partial resolution is never counted as half. - Grade counts + pending + not run = N. Graded coverage = runs placed in one of the four grades ÷ N. - A delivery failure or timeout with no answer is graded not resolved, and the platform, tool or cancellation reason is kept; it is not automatically a knowledge error. - The default is three runs per question. A question counts toward the **stable-resolution count** only if all three runs are fully resolved; with single runs, do not report a stable-resolution rate. - Compare performance on all questions *and* on the **common subset** every setup fully resolved, showing each denominator, so setups are not compared on different, easier questions. - Label every improvement figure as **measured**, **conditional estimate** (with formula and assumptions) or **untested direction**. ## Timing - **Primary end-to-end (E2E) time** = when the tester received the complete final answer − when the question was submitted. It includes network, platform initialization, retrieval, tools, polling and delivery. Unit: seconds. - Keep full timestamps with time zone. Across systems, state clock skew and precision; a missing value is never 0. - Startup, first progress, first token, model text finished, runner finished and user received the final answer are different events. Name each by what was actually captured and never substitute one for another. A first progress message is not the final answer, and a task marked done still needs its answer confirmed as delivered. - If only platform creation and final send receipts exist, report a separate **platform E2E** marked as a proxy; never mix it with receiver-side E2E. - Agree the timeout before running; 600 seconds is a reasonable default. It is an execution limit, not a business target. Record the actual stop time for a timeout and give a re-run its own run ID; a timeout is never a successful 600-second sample. Failures without a final answer are not latency samples of successful delivery, but their rate and waiting time must be shown. - **Mean** = sum of same-definition times ÷ sample count. **P50** = median (average of the middle two for an even count). **P90** = nearest-rank, the ⌈0.9 × n⌉-th sorted value. Always show the sample count; with repeats, also report each question's median. ## Tool calls and channel overhead - Count tool calls by unique call ID and state the coverage — events the platform exposes; internal calls of unexposed sub-Agents are not counted. One shell call may run several commands. Tool calls describe the execution path; they are not model calls or tokens. The span from first to last tool event includes reasoning, waiting and concurrency, so do not call it pure tool time. - Keep original receipts for platform failures, timeouts, cancellations, quota refusals and retries. Link an extra run to the attempt it repeats; never replace a result with the best one. When a question needs the user to supply more information, define one multi-turn protocol for all setups and label ad hoc follow-ups and resumes. - **Channel overhead:** an Agent configured for a chat channel — for example one that assembles reply cards — may still detect the channel, read card instructions and resolve links when called directly. For pure question answering, switch to a reply policy suited to direct calls, or record and exclude that overhead. --- ## Sources - note:20261013/evaluation-method.md · evaluation-method.md L1–L3 - note:20261013/evaluation-method.md · evaluation-method.md L12–L23 - note:20261013/evaluation-method.md · evaluation-method.md L61–L76 - note:20261013/evaluation-method.md · evaluation-method.md L78–L89 - note:20261013/evaluation-method.md · evaluation-method.md L91–L99 - note:20261013/evaluation-method.md · evaluation-method.md L101–L103 - note:20261013/evaluation-method.md · evaluation-method.md L105–L109 - note:20261013/evaluation-method.md · evaluation-method.md L111–L116 - note:20261013/evaluation-method.md · evaluation-method.md L118–L125 - note:20261013/evaluation-method.md · evaluation-method.md L127–L134 - note:20261013/evaluation-method.md · evaluation-method.md L135–L137 --- ## Knowledge Retrieval Benchmark # Knowledge Retrieval Benchmark ## Results at a glance On 24 real developer questions from a large production full-stack monorepo, Agents answering from Context knowledge fully solved more questions, faster and with far fewer tool calls than Agents using an LLM Wiki. Adding Source Graph for remote code reading cut time and tool calls further. | Metric | LLM Wiki | Context | Context + Source Graph | | --- | ---: | ---: | ---: | | Answering model | GPT 5.6 SOL | GPT 5.6 SOL | Claude Opus 5.5 | | Fully solved | 19 (79.2%) | 21 (87.5%) | 23 (95.8%) | | Partly solved / substantively wrong | 2 / 3 | 2 / 1 | 0 / 1 | | Mean end-to-end time | 223.2 s | 157.1 s | 93.2 s | | P50 / P90 | 137.2 / 464.7 s | 136.8 / 256.2 s | 89.0 / 123.0 s | | Mean tool calls | 77.5 | 24.5 | 7.8 | ```mermaid xychart-beta title "Mean tool calls per question" x-axis ["LLM Wiki", "Context", "Context + Source Graph"] y-axis "Tool calls" 0 --> 80 bar [77.5, 24.5, 7.8] ``` LLM Wiki and Context used the same model and are directly comparable. The third configuration also changed the model; the same-model comparison below isolates Source Graph's effect. The method follows [Evaluating Your Knowledge Base](); the grading and timing rules are in [Evaluation Scoring and Timing Standard](). ## What was compared | Configuration | Knowledge and retrieval | | --- | --- | | LLM Wiki | A one-off generated LLM Wiki; the Agent searches and reads files locally | | Context | A Context knowledge package; the Agent retrieves locally | | Context + Source Graph | A Context knowledge package; code is read remotely at a pinned version through Source Graph | The benchmark measures **answering** with deployed knowledge. Knowledge production — quality, time, review effort and cost of producing and updating knowledge — has not been benchmarked yet. ## Questions and scoring The 24 questions came from real developer questions and were frozen before any run. Each configuration answered each question once. | Question type | Count | | --- | ---: | | Locating interfaces and pages | 7 | | Business interaction rules | 5 | | Interfaces and parameters | 4 | | Permissions and roles | 3 | | Versions and call relationships | 3 | | Debugging and environments | 2 | - Each question had criteria written in advance; answers were graded fully solved, partly solved, substantively wrong or unanswered. - Grading was done by a model (GPT-6 Astra Ultra) blind to the configuration, without human calibration. - Time is the end-to-end time until the caller saw the complete answer: mean, P50 and P90 (nearest-rank). - Tool calls count only calls visible to the Agent. ## On the 17 questions all three solved To remove differences in question difficulty, the 17 questions that every configuration fully solved were compared separately: | Metric | LLM Wiki | Context | Context + Source Graph | | --- | ---: | ---: | ---: | | Mean end-to-end time | 232.6 s | 160.7 s | 93.5 s | | P90 | 534.5 s | 258.8 s | 123.2 s | | Mean tool calls | 78.3 | 24.9 | 8.0 | ## Source Graph with the same model With Claude Opus 5.5 in both runs, Context with local retrieval fully solved 23 of 24 questions with a mean of 139.3 s, P90 188.7 s and 11.6 tool calls. Adding Source Graph kept 23 of 24 and reduced mean time by 33.1%: 256 local calls for repository preparation, shell, search and file reads were replaced by 164 remote retrievals. Eight remote calls failed parameter validation and the Agent recovered from all of them. Under the same knowledge and retrieval, another model (Grok 4.7) also fully solved 23 of 24 but took a mean of 304.0 s, about 2.2 times as long. At equal quality, model choice has a large effect on time. ## Three models on the same knowledge setup With the same Context knowledge package on a managed Agent platform, the same 24 questions, one run each and the same blind model grader: | Metric | GPT 5.6 SOL (first run) | Grok 4.7 | Claude Opus 5.5 | | --- | ---: | ---: | ---: | | Fully solved | 21 (87.5%) | 23 (95.8%) | 23 (95.8%) | | Partly solved / substantively wrong | 2 / 1 | 0 / 1 | 0 / 1 | | Mean / P50 / P90 end-to-end | 157.1 / 136.8 / 256.2 s | 304.0 / 314.2 / 465.9 s | 139.3 / 141.4 / 188.7 s | | Mean visible tool calls | 24.5 | 40.3 | 11.6 | | Mean observed startup | 31.8 s | 34.4 s | 40.0 s | - On the **20 questions all three fully solved**, mean end-to-end time was 162.8 s, 312.7 s and 142.3 s, with 25.4, 41.3 and 12.2 tool calls. - Against the first run, Claude Opus 5.5 was faster on 18 of 24 questions, with P90 26.3% lower and 52.6% fewer tool calls. Grok 4.7 was slower on all 24 and made 64.0% more tool calls; the longer investigations did not raise the full-resolution rate. - **Equal counts are not equal answers.** Each newer model fixed some of the first run's gaps and introduced a different error of its own. - **The same conclusion can come by very different paths.** On one question both models were correct: one took 493.7 s and 75 calls, the other 176.4 s and 18. ## What the traces showed - When the host repository did not contain the target address, the knowledge gave the page → remote SDK → interface chain directly, so the Agent did not search blindly across repositories. - Questions about differences between versions first need "compared with which version"; the knowledge recorded the pinned commits and comparison range of its sources. - The few errors came from knowledge that missed a component's branch condition and over-generalized. Such gaps should become revision tasks. - Tool calls fell from 77.5 to 24.5 and then to 7.8: knowledge reduced blind exploration, and remote retrieval replaced local repository preparation and file reads. ## Where the errors and overhead came from - **Search scope misjudged.** In a sparse checkout the caller's directory was not checked out, yet a local search was taken as proof that nothing in the whole repository referred to the target. Having read source code is not the same as having searched all of it; confirm the checkout scope before any repository-wide negative conclusion. - **A condition generalized.** The knowledge stated a region for direct calls and kept field-based calls for dynamic forms; the answer extended the first to every request, and a field for another region in the source was the counterexample. The grade fell because of the wrong claim, not because the process was not shown. - **Targeted source checks worked.** On the question where the first run missed a parent-page branch condition, both later models traced the parent's component choice and the history data switch and corrected the conclusion. - **Channel preparation.** Called directly, the configuration under test still ran the steps meant for a chat channel's reply cards: 54 visible related calls across the first run's 24 questions, and for another model — which resolved links and checked channel context on every question — 149 deduplicated calls, 15.4% of its tool calls. They do not mean a card was sent, and their time was not separated. Trimming delivery preparation at the entry point would remove steps unrelated to answering. - **Waiting for startup.** From submission to first observing "running" took about 32 s on the managed platform, including polling granularity. ## Conditional estimate: faster startup This is a **conditional estimate**, not a measurement. Replace each first-run question's measured startup with an assumed target and keep every other stage unchanged: estimated E2E = measured E2E − measured startup + assumed startup target | Assumed startup | Mean | P50 | P90 | | ---: | ---: | ---: | ---: | | 5 s | 130.4 s | 105.5 s | 229.9 s | | 10 s | 135.4 s | 110.5 s | 234.9 s | Whether such a target is reachable has to be re-measured on the same questions and configuration. ## What to improve next - Verify the checkout scope before concluding that nothing in a repository uses something. - Keep branch conditions when knowledge is merged or summarized. - Skip reply-card preparation in direct sessions that have no delivery target. ## Estimated cost Per question, tokens fell from about 567,000 to about 63,000. At standard API prices (input \$4 and output \$20 per million tokens, no cache discount) that is about \$2.45 → \$0.27, a reduction of 88.9%. The first and model-switched runs were estimated by replaying requests; the LLM Wiki and latest runs were extrapolated from tool-call counts. ## Limits of this comparison - Each question was run once, so stability cannot be inferred. - These are whole configurations: LLM Wiki and Context ran in different Agent environments with different system prompts; Context + Source Graph also changed the model and Context version, the run date, concurrency and timeout limits, and is a regression on already-seen questions with a single grader. - End-to-end time includes environment start-up and polling granularity, not quota queuing. - Cost is an estimate, as described above. - In the three-model comparison, the two later runs allowed up to four concurrent questions per model; the first allowed at most two and was partly serial. Dates, Skills, runtime and some read versions also differed, so not every difference belongs to the model. Size reduction is a different measure: knowledge is about 1/115 of its sources by volume, which says nothing about quality on its own. See [Knowledge for Agents](). --- ## Sources - note:20261012/benchmark-summary.md · benchmark-summary.md L40–L49 - note:20261012/benchmark-summary.md · benchmark-summary.md L16–L16 - note:20261012/benchmark-summary.md · benchmark-summary.md L5–L15 - note:20261012/benchmark-summary.md · benchmark-summary.md L19–L30 - note:20261012/benchmark-summary.md · benchmark-summary.md L32–L38 - note:20261012/benchmark-summary.md · benchmark-summary.md L51–L57 - note:20261012/benchmark-summary.md · benchmark-summary.md L59–L67 - note:20261013/evaluation-method.md · evaluation-method.md L147–L162 - note:20261012/benchmark-summary.md · benchmark-summary.md L69–L74 - note:20261013/evaluation-method.md · evaluation-method.md L164–L170 - note:20261013/evaluation-method.md · evaluation-method.md L170–L170 - note:20261013/evaluation-method.md · evaluation-method.md L125–L125 - note:20261013/evaluation-method.md · evaluation-method.md L172–L172 - note:20261012/benchmark-summary.md · benchmark-summary.md L81–L81 - note:20261012/benchmark-summary.md · benchmark-summary.md L76–L80 - note:20261012/compression.md · compression.md L21–L27 - note:20261013/evaluation-method.md · evaluation-method.md L171–L171 --- ## Architecture Overview # Architecture Overview ## The parts ```mermaid flowchart TB user["You"] --> agent["Your Agent"] subgraph plugin["Agent plugin"] entries["Entry skills"] indexers["Indexer skills"] end agent --> plugin plugin --> cli["context CLI"] subgraph runtime["Local runtime"] cli --> provider["Workflow Provider"] cli --> extract["Extractors"] cli --> sdk["SDK declarations"] end cli --> ws["Context knowledge workspace"] ws --> out["Package, site, LLM Docs"] ``` | Part | Role | | --- | --- | | Agent entries | Thin skills that tell the Agent how to start or continue a Context knowledge workspace and how to follow the current step | | Indexer skills | Provider skills that read one kind of source and write source-grounded articles | | `context` CLI | Observes the knowledge workspace, captures sources, runs extractors, validates evidence, applies reviews and builds outputs | | Workflow Provider | The work contract evaluated by Agent Graph: legal steps, Gates and required reading | | SDK (`@c4a/context`) | The declaration surface for a knowledge workspace's `src/index.ts`: sources, phases and packages | | Extractors | Parser packages that turn code and interface definitions into structural facts | | Evidence plugin | An optional WebAssembly plugin that lets Source Graph attach knowledge sections to code reads | ## Local-first by design There is no server, daemon, database, hosted API or web frontend in Context. The CLI reads declared sources, writes knowledge workspace files, validates invariants and produces portable packages. Everything a team needs to inspect lives in the knowledge workspace and can be committed to Git; a hosted Agent or Bot runs the same CLI. ## Who does what The Agent performs semantic work: reading evidence, proposing structure and content, explaining decisions. The CLI performs deterministic work and never calls an LLM. The user owns the goal, source permissions, structure choices and review decisions. Keeping these apart is what makes a long workflow repeatable — see [Why a Workflow](). ## How a request travels 1. The Agent entry runs `context entry`, which resolves initialization, relocation or the current workflow. 2. The CLI observes knowledge workspace facts and asks the Provider for the current Route: the step, its reading list, any Gate and the exact commands. 3. The Agent reads, decides and runs one selected action. 4. The knowledge workspace changes, and the CLI evaluates again. Details are in [Workflow Execution](); the stages a source passes through are in [Knowledge Lifecycle](); package boundaries are in [Module Layout](). --- ## Sources - [context/ARCHITECTURE.md L7–L47 · 3b0ce0a]() - [context/plugins/context/README.md L5–L17 · 3b0ce0a]() - [context/packages/context-cli/README.md L3–L18 · 3b0ce0a]() - [context/ARCHITECTURE.md L49–L52 · 3b0ce0a]() - [context/ARCHITECTURE.md L420–L423 · 3b0ce0a]() - [context/README.md L101–L104 · 3b0ce0a]() - [context/packages/context-cli/README.md L28–L32 · 3b0ce0a]() - [context/packages/context-cli/README.md L80–L107 · 3b0ce0a]() --- ## Why a Workflow # Why a Workflow ## Teams already have Agents Engineering teams already work in Claude Code, Codex, Cursor or a managed Agent environment, and many run team Bots. A hosted knowledge platform would ask them to move their sources, permissions and review habits somewhere new. Context goes the other way: it adds skills to the Agents a team already uses, and a local CLI does the deterministic work. The same skills run in a local coding Agent or a managed Agent environment. ## Semantic work and deterministic work Knowledge production mixes two kinds of work: | Kind | Examples | Done by | | --- | --- | --- | | Semantic | Reading evidence, proposing structure, writing and explaining | The Agent | | Deterministic | Recording source boundaries, capturing snapshots, indexing code, checking evidence, staging candidates, applying reviews, building | The CLI | | Decisions | Goal, source permission, scope, structure, review, output | People | The CLI never calls an LLM and never silently clones, fetches, installs or builds a source repository; registering a source does not grant permission to read its contents, and review decisions stay with people. That keeps the parts that must be repeatable out of the model's hands, while the Agent stays free to choose the best wording and structure. ## A workflow, not a long prompt The lifecycle is long: sources must be scoped and captured, articles written against evidence, human Gates may pause the run, and approved knowledge must be closed, verified and built. Putting all of that in one prompt would be fragile and expensive. Instead the workflow is a contract: at each step the CLI returns only the action that is legal now, the resources to read for it and the commands to run. Interrupting and resuming converge from the actual state of the Context knowledge workspace rather than from conversation memory. See [Workflow Execution](). ## From one person's Agent to a knowledge service Because the skills are platform-independent, a team can run them as a resident knowledge service: an Agent environment with the Context plugin, a Bot prompt and remote code reading, taking requests from chat, the web, schedules or an API. It produces, updates and answers continuously, and people step in only at the decisions that matter — the work-start report, the review report and scope trade-offs. Shared knowledge that needs a lot of searching and confirmation, and answers that must be available at any time, suit such a resident service. Knowledge for a small module can simply live in the repository's `docs/`. --- ## Sources - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L9–L11 - [context/packages/context-cli/README.md L22–L32 · 3b0ce0a]() - [context/README.md L101–L104 · 3b0ce0a]() - [context/packages/context-cli/README.md L28–L32 · 3b0ce0a]() - [context/packages/context-cli/README.md L182–L184 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L5–L7 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L38–L42 · 3b0ce0a]() - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L15–L24 - note:20261012/knowledge-service-agent.md · knowledge-service-agent.md L39–L41 --- ## Knowledge Lifecycle # Knowledge Lifecycle ## From source to package ```mermaid flowchart LR reg["Register"] --> cap["Capture"] cap --> idx["Indexer lifecycle"] idx --> cand["Candidates"] cand -->|approve| appr["Approved"] appr --> closed["Close"] closed --> built["Verify and build"] ``` | Stage | What happens | What it protects | | --- | --- | --- | | Register | A repository module, document folder or online document is recorded as a source boundary | Source identity and permission boundary; registration does not grant permission to read beyond it | | Capture | Document bodies and embedded resources are saved as snapshots; repositories are read at a pinned commit | Complete bodies, resources and fingerprints, so later checks can detect stale inputs | | Indexer lifecycle | Requirements are confirmed, a plan and work-start report are approved, then Indexer skills write articles in stages | Every section is bound to exact source locations | | Review | You see the whole current batch of Candidates and approve, reject or ask for revisions | Approval is applied atomically; rejected material keeps a minimal fingerprint so it is not proposed again | | Close | `knowledge/structure.yaml` is rebuilt from approved pages and their edges | The knowledge map matches the approved pages, without rewriting prose | | Verify and build | Source references, frontmatter, structure and assets are checked, then packages and sites are produced | Distributed files map back to approved knowledge through a build inventory | ## Inside the Indexer lifecycle The top-level workflow has a single production step, `run-indexer-lifecycle`, which hands over to the nested Indexer graph: 1. **Requirements.** The reader purpose, questions and authorized sources are recorded in `src/indexers.yaml`. 2. **Planning.** The Agent investigates and writes a plan of articles in batches. 3. **Work-start report.** The plan is presented for confirmation; managed authority does not waive a required decision. 4. **Stage writing.** Each task produces an article and its references; the CLI checks that every cited source is authorized for that task. 5. **Gaps and repair.** Missing evidence becomes further investigation or a repair, not an invented answer. Code, Markdown, notes and session summaries all converge into one current Candidate batch, and one content Review admits it. See [The Indexer System](). ## Where state lives | Location | Lifetime | | --- | --- | | `sources/` | Project state: registries and captured evidence | | `.tmp/context-runtime/lifecycle/` | Disposable: structure drafts and the active Candidate ledger, removed after a successful close | | `knowledge/` | Project state: approved pages and `structure.yaml` | | `dist/` | Reproducible build output | Candidate IDs are workflow state and never become the identity of approved knowledge; approved Markdown stores its stable identity in frontmatter and section metadata. ## After the build Building completes the currently approved state; it does not freeze the Context knowledge workspace. The workflow records a new knowledge workspace version when content changes, before building. Later, `context revise` corrects a selected page and `context update` handles a selected source change; both run through Review and delivery again and touch only what is affected. See [Keeping Knowledge Current]() and [Version-Aware Knowledge](). --- ## Sources - [context/packages/context-cli/README.md L113–L121 · 3b0ce0a]() - [context/ARCHITECTURE.md L236–L257 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/graphs/workspace.yaml L351–L369 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/graphs/indexer.yaml L1–L67 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L57–L66 · 3b0ce0a]() - [context/ARCHITECTURE.md L236–L252 · 3b0ce0a]() - [context/ARCHITECTURE.md L151–L160 · 3b0ce0a]() - [context/ARCHITECTURE.md L275–L277 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/graphs/workspace.yaml L343–L349 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L150–L157 · 3b0ce0a]() - [context/packages/context-cli/README.md L123–L124 · 3b0ce0a]() --- ## Module Layout # Module Layout ## Package dependencies ```mermaid flowchart BT core["@c4a/core"] extract["@c4a/extract"] ts["@c4a/extract-ts"] go["@c4a/extract-go"] catalogs["Catalog parsers"] sdk["@c4a/context"] ag["@c4a/agent-graph"] cli["@c4a/context-cli"] extract --> core ts --> extract go --> extract catalogs --> core cli --> sdk cli --> ag cli --> extract cli --> ts cli --> go cli --> catalogs ``` Arrows point from a package to what it depends on; catalog parsers are `extract-rush`, `-mdx`, `-proto`, `-thrift`, `-contract`, `-sql` and `-style`. `@c4a/context-cli` is the only package users install; the SDK, extractors and Agent Graph come with it. ## What each package does | Package | Responsibility | | --- | --- | | `@c4a/context` | Declarative SDK for a Context knowledge workspace's `src/index.ts`: sources, phases and package outputs, plus the versioned Indexer contracts | | `@c4a/context-cli` | The `context` command: knowledge workspace lifecycle, source capture, validation, review, close, build, the documentation website builder, the bundled workflow Provider and the Agent plugin | | `@c4a/core` | Shared extraction types, schemas and utilities | | `@c4a/extract` | Language-plugin framework and repository runner for code evidence | | `@c4a/extract-ts`, `@c4a/extract-go` | TypeScript/JavaScript and Go extraction plugins: symbols, spans, imports and exports | | `@c4a/extract-rush`, `-mdx`, `-proto`, `-thrift`, `-contract`, `-sql`, `-style` | Lightweight catalogs for Rush workspaces, MDX components, Protocol Buffers, Thrift, OpenAPI/GraphQL contracts, SQL and CSS/SCSS | | `context-evidence-wasm` | Builds the optional `context-evidence.sourcegraph.wasm` plugin for Source Graph | | `@c4a/agent-graph` | External, model-free workflow-contract runtime used only by the bundled Provider | Parser packages materialize structural facts; they never write approved knowledge. See [Code Extraction](). ## Inside the CLI package | Path | Contents | | --- | --- | | `src/project/` | Knowledge workspace observation, sources, Indexer lifecycle, review, close, verify and package build | | `src/project/workflow/` | Observes facts and binds the selected graph action to a revisioned command | | `context-workflow/` | The Provider source: graphs, actions, resources, schemas and route tests | | `plugins/context/` (repository root) | The only maintained source of the Agent plugin: four public entry Skills (`context`, `context-plan`, `context-inspect-search`, `context-repo-content`), four Indexer Provider Skills and `context-indexer-create`; host-specific entries are generated at build | The build emits one bundle: the CLI binary, the immutable Provider under `dist/providers/context`, the plugin projections, the Indexer skills, the diagram viewer and the evidence plugin. ## Where a change lands - `@c4a/context` changes affect knowledge workspace declarations and phase plans. - `@c4a/context-cli` changes affect commands, Agent workflows, knowledge workspace file formats, review behavior and package output. - `@c4a/extract` and the extractor and catalog packages (`extract-ts`, `extract-go`, `extract-rush`, `-mdx`, `-proto`, `-thrift`, `-contract`, `-sql`, `-style`) affect only the code facts of their languages and formats; see [Code Extraction](). - `context-evidence-wasm` changes affect only how Source Graph enriches remote code reads; local retrieval and knowledge production stay unchanged. - Agent Graph is a pinned external dependency; Context owns its Provider and host bindings. --- ## Sources - [context/packages/context-cli/package.json L55–L67 · 3b0ce0a]() - [context/CLAUDE.md L7–L33 · 3b0ce0a]() - [context/ARCHITECTURE.md L54–L75 · 3b0ce0a]() - [context/ARCHITECTURE.md L338–L356 · 3b0ce0a]() - [context/README.md L130–L145 · 3b0ce0a]() - [context/ARCHITECTURE.md L358–L389 · 3b0ce0a]() - [context/packages/context-cli/package.json L37–L38 · 3b0ce0a]() - [context/ARCHITECTURE.md L77–L89 · 3b0ce0a]() --- ## Workflow Execution # Workflow Execution ## The evaluation loop Context does not run a fixed script. Every time the Agent asks what to do, the CLI observes the Context knowledge workspace, turns what it sees into **Facts**, and asks the workflow Provider for the current **Route**. ```mermaid flowchart LR facts["Knowledge workspace facts"] --> evaluate["Agent Graph evaluates"] evaluate --> route["Current Route"] route --> act["Agent runs one action"] act -->|"knowledge workspace changes"| facts ``` A Route carries the selected step, a reason code, the resources the Agent must read before acting, any unresolved Gate and the exact commands to run. Only `workflow.current` chooses the next lifecycle step; a command that finishes returns control to a fresh evaluation instead of choosing the next step itself. ## Two graphs The Provider in `packages/context-cli/context-workflow/` contains two static graphs: | Graph | Covers | | --- | --- | | `workspace` | The top-level lifecycle: repair, source boundary, capture, Indexer lifecycle, review, close, package output, translation, version recording, build and completion, plus rollback | | `indexer` | Requirements, planning, the work-start report, stage writing, gap handling, source updates and approved-page revisions | The top-level order is fixed by the graph's edges: source boundary → capture → `run-indexer-lifecycle` → review → close → package output → version → build. Nodes describe stable task categories such as "a capture target remains"; source names, dates and modules are runtime facts and never become graph nodes. That is why one graph serves every knowledge workspace. ## Gates Some nodes are **Gates**: they wait for a decision. Examples are choosing the source boundary, authorizing document capture, approving the work-start report, reviewing the current batch and choosing the package output. Each Gate declares whether it is delegatable. In ordinary mode a person decides. When you explicitly authorize fully managed operation for the current conversation, the Agent may resolve delegatable Gates — for example applying a review it has checked — but never those marked non-delegatable, such as the work-start report when a scope decision is required. Managed authority is scoped to the conversation and cannot authorize new source boundaries, failed validation or failed verification. ## Revisions and stale commands Every write command is bound to the revision of the observation that produced it. If the knowledge workspace changed since then — another action ran, a file was edited — the command is rejected instead of being applied to newer state. Required resources are acknowledged by digest; dynamic views are tied to the revision that selected them. A receipt proves the Agent received a resource; it does not claim the task is done. ## Resuming With the same Provider, the same observed Facts and the same recorded outcomes, Agent Graph selects the same Route. Work already satisfied by knowledge workspace facts is skipped or advances. So an interruption, a retry or a new conversation converges from observable state, not from conversation memory. The CLI keeps each filesystem effect atomic, guarded or a proven no-op; Agent Graph keeps evaluation repeatable. ## How the workflow improves Route selection is tested without a model: `context-workflow/tests/` holds fact-to-Route scenarios. With debug mode on, Context records CLI invocations and graph evaluations; a replay shows which Route was chosen at each fact change, where a loop advanced and where a Gate paused. Inefficient loops, repeated reads or misleading priorities found in traces become new route tests and graph changes. Long procedures live in separate resources, so they can be improved without touching the entry skill. --- ## Sources - [context/packages/context-cli/context-workflow/README.md L8–L18 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L34–L34 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/README.md L75–L78 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/README.md L37–L51 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/graphs/workspace.yaml L351–L372 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L68–L68 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/graphs/workspace.yaml L183–L202 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/graphs/indexer.yaml L50–L63 · 3b0ce0a]() - [context/packages/context-cli/README.md L151–L157 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/README.md L57–L68 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L38–L42 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L74–L88 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/README.md L47–L47 · 3b0ce0a]() --- ## Packages and Sites # Packages and Sites ## One body of knowledge, several outputs ```mermaid flowchart LR kn["Approved knowledge"] --> build["context build"] kmap["Knowledge map"] --> build tpl["Package templates"] --> build build --> kb["Knowledge package"] build --> site["Documentation site"] build --> llms["LLM Docs"] build --> inv["Build inventory"] ``` Build consumes only approved and closed knowledge. Output channels can be combined; for a new knowledge workspace the Agent proposes a knowledge package plus a website by default, and LLM text is an additional choice. Every build emits an inventory that maps distributed files back to approved knowledge in the knowledge workspace. ## Agent knowledge packages A knowledge package uses flat roots: | Root | Internal collections | | --- | --- | | `wikis/` | `codegraph`, `business`, `product` | | `guides/` | `architecture`, `sop`, `faq`, `decision`, `incident` | | `rules/` | `standards`, `test` | | `feats/` | `feats` | The default `knowledge-query` skill is the Agent-facing entry: it starts from directory indexes, follows edge records in the inventory, reads candidate pages and cites their headings, and reports gaps when the package does not cover a fact. When indexes do not narrow the scope, its bundled `scripts/search.mjs` ranks Markdown chunks locally. Consumer pages omit `sources` and section metadata; exact attribution stays in the workspace and is reached through the inventory. ## Documentation sites Enabling `site` on a package also produces `dist/-site/`: a static site with article pages, local search, scripts and styles, built in a sibling staging directory so a failed site build keeps the previous output. - **Navigation** comes from the accepted `src/knowledge-map.yaml`. Entries bind to article identity, so labels and groups do not change URLs, and one article can appear in several places. - **Homepage** uses the first-level knowledge map as a complete site map. - **Diagrams** written in Mermaid render in the browser with the site theme and offer fit, zoom, full-screen and source controls. - **Source footer** on each article links repositories at their recorded revision and documents at their registered URL. - **Languages** can be added with `site.locales`; untranslated pages show the original with a notice. Context does not deploy. Preview with any static HTTP server and deploy the contents of `dist/-site/` with your own hosting. ## LLM Docs `llmsPackage()` produces a text bundle for model context, offline evaluation or downstream ingestion: ```text llms.txt # knowledge-map index llms-full.txt # consolidated approved text llms/pages/.txt # individual articles ``` ## Customizing without forking the knowledge Package templates shape distribution — extra Agent instructions, static files, query helpers — but never replace approved knowledge as the source of truth. Presentation sources for a site, such as homepage slots, custom pages and theme components, live under `src/site/`, separate from generated knowledge. --- ## Sources - [context/packages/context/docs/guides/package-outputs.md L12–L16 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L33–L37 · 3b0ce0a]() - [context/README.md L106–L114 · 3b0ce0a]() - [context/ARCHITECTURE.md L304–L317 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L243–L255 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L45–L54 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L97–L133 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L174–L187 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L363–L376 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L294–L300 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L39–L43 · 3b0ce0a]() --- ## Knowledge for Agents # Knowledge for Agents ## An index, not a copy An Agent that has to answer a question needs to know **where to look** and **what is true**, quickly. It does not need a second copy of the codebase, and it does not need long, polished prose that restates every function. Context therefore treats knowledge as an index with explanations: - each article answers specific reader questions agreed in the requirements; - each statement points to the exact source region it came from; - the source itself stays where it is, readable at a pinned version when more detail is needed. ```mermaid flowchart LR src["Sources"] --> idx["Indexer"] idx -->|keeps| kept["Entries, contracts, rules"] idx -.->|leaves in source| left["Bodies, boilerplate"] kept --> art["Article with references"] ``` ## Extract on demand Indexers do not start with a full symbol scan or a complete relationship graph. During planning they expose a useful skeleton — directories, manifests, registration points, public entries — and propose reader topics. Detailed reading happens while writing each topic, bounded to what that topic needs. Signals such as public exports, registered interfaces, scheduled jobs, storage interfaces or generated clients suggest reader questions, not mandatory pages; one page per symbol is explicitly avoided. Symbol count is not a quality measure. Internal or out-of-scope items can be left out with a reason; Review checks whether the pages actually answer the reader's questions. ## How much smaller In a large production full-stack monorepo, the two repositories that could be counted locally held about 33,700 code files and 5.84 million lines (about 200 MB); together with about 1,130 document snapshots (about 1.77 MB), they became 220 reviewed articles totalling about 1.75 MB — roughly **1/115** of the source volume. Two limits apply to that figure: - only part of the registered sources was counted, so the real ratio is higher; - the ratio measures size, not coverage or quality. Quality is measured separately in the [Knowledge Retrieval benchmark](). The knowledge is not lossless and does not "cover all code". It keeps the facts needed to answer questions, each with a pointer back to the code line or document section. See [Evidence Chains and Index First](). --- ## Sources - [context/plugins/context/skills/context-code-indexer/references/indexer.md L1–L28 · 3b0ce0a]() - note:20261012/compression.md · compression.md L28–L28 - [context/packages/context/docs/reference/indexer-provider-protocol.md L257–L264 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/SKILL.md L16–L31 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/references/indexer.md L37–L50 · 3b0ce0a]() - [context/packages/context/docs/reference/code-extractors.md L47–L51 · 3b0ce0a]() - note:20261012/compression.md · compression.md L15–L22 - note:20261012/compression.md · compression.md L26–L28 --- ## Evidence Chains and Index First # Evidence Chains and Index First ## The chain ```mermaid flowchart LR q["Question"] --> map["Knowledge map and indexes"] map --> page["Article section"] page -->|source_ref + file and lines| region["Source region at a pinned version"] region -->|content digest| check["Verified at write and verify time"] ``` An answer starts from the knowledge map, lands on an article section, and from there follows a reference to an exact region of a registered source. Each step is checkable: the reference names the source and the lines; the source is pinned; the region's content is fingerprinted. ## Sections carry their own evidence Approved articles are divided into sections. Each written fragment cites at most three source positions, each a `source_ref` plus a file and line `locator`. When an article is submitted, the CLI checks that each cited source is authorized for that task, reads the current captured text and computes the region's content digest. Unknown or unauthorized paths and source-version drift are errors, not warnings. There is no separate fact table or claim ledger to maintain — the references are the evidence. `source_ref` values are opaque, verified identities. Agents copy them exactly; they are not file-system paths. ## Checked again before delivery `context verify` re-checks approved pages before close and build: source references for freshness and verbatim match, frontmatter identity, section blocks, assets and the derived structure. Verification errors block close and build. Approved Markdown keeps a stable identity in frontmatter and section metadata, so a page can be revised without losing its history. ## Index first, then the original Agents answering from a knowledge package start from directory indexes and the edge records in the build inventory, read the candidate pages, and cite their headings and passages. When the package does not cover a requested fact, they report the gap instead of guessing. Consumer packages omit section metadata to stay small; a maintainer can map any page back to the Context knowledge workspace through the inventory to see its full evidence. With Source Graph, the chain reaches the code without a clone: the optional evidence plugin joins section markers, `knowledge/structure.yaml` and source registrations, so an Agent reading code at a pinned revision also receives the knowledge sections that cite it. The plugin is read-only; it does not verify source contents or modify knowledge. ## Visible to readers On a documentation site, each article ends with a source footer built from its recorded references: repository entries link to the recorded revision and module, and document entries link to their registered URL. Links are never inferred from prose. --- ## Sources - [context/packages/context/docs/reference/indexer-provider-protocol.md L257–L262 · 3b0ce0a]() - [context/ARCHITECTURE.md L233–L234 · 3b0ce0a]() - [context/packages/context/docs/reference/indexer-provider-protocol.md L257–L264 · 3b0ce0a]() - [context/packages/context/docs/reference/indexer-provider-protocol.md L418–L423 · 3b0ce0a]() - [context/packages/context-cli/README.md L189–L190 · 3b0ce0a]() - [context/ARCHITECTURE.md L279–L302 · 3b0ce0a]() - [context/ARCHITECTURE.md L275–L277 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L243–L254 · 3b0ce0a]() - [context/packages/context-evidence-wasm/README.md L1–L5 · 3b0ce0a]() - [context/packages/context-cli/README.md L14–L17 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L174–L174 · 3b0ce0a]() --- ## Version-Aware Knowledge # Version-Aware Knowledge ## Every source has a fixed version Knowledge is only checkable if you know which version of the source it describes. Context records that for every input: | Source | Fixed by | | --- | --- | | Repository module | The registered commit; restoring a Context knowledge workspace checks out that commit and never substitutes a newer one | | Online or local document | A captured snapshot with a fingerprint | | Note or session summary | The saved file; a session's related commits and merge requests stay in its frontmatter | References store the real repository path at the cited commit, even if the module is later registered under a different path. ## What has been processed `knowledge/structure.yaml` keeps compact `processed_scopes`: for each requirement, source and module range, the version that knowledge has been brought up to. A source update starts from that version, and the processed version only advances after every requested page in the range has been approved, closed and built — a partial update or failed build leaves it where it was. If temporary progress is lost, the next inspection starts again from the recorded version and keeps already approved pages. ```mermaid flowchart LR v1["Processed at commit A"] --> diff["Compare A with B"] diff --> pages["Affected pages and new topics"] pages --> review["Review"] review --> build["Close and build"] build --> v2["Processed at commit B"] ``` ## The knowledge workspace has its own version Besides source versions, the knowledge workspace itself carries a SemVer in `package.json`. At the end of each completed delivery — after Review, close and package configuration, before the final build — the workflow asks the Agent to inspect formal changes and record the next version with a concise changelog: - **minor** for added modules or expanded material coverage; - **patch** for corrections, updates to existing modules and navigation changes; - **major** only on explicit instruction. The CLI updates `package.json`, `changelog.yaml` and `CHANGELOG.md` together. Knowledge packages and LLM Docs carry the same version and changelog, and a documentation site shows the history on its Changelog page. Temporary progress never increases the version, and intermediate batches do not each get one. ## Going back Because the knowledge workspace is in Git, a historical version can be restored: the Agent resolves the target to a concrete commit and path scope, compares it with current files and restores the selected knowledge workspace files and usable sources. It does not reset the whole repository or rewind source repositories. --- ## Sources - [context/packages/context/docs/guides/workspace-prepare.md L88–L91 · 3b0ce0a]() - [context/packages/context-cli/README.md L117–L118 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L29–L30 · 3b0ce0a]() - [context/packages/context/docs/reference/project-api.md L224–L229 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-update.md L29–L32 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L114–L133 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L169–L169 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L187–L190 · 3b0ce0a]() - [context/packages/context/docs/guides/workspace-restore.md L6–L26 · 3b0ce0a]() --- ## Keeping Knowledge Current # Keeping Knowledge Current ## The update loop ```mermaid flowchart LR change["Source changes"] --> cmp["Compare versions"] cmp --> decide["Keep, revise, add"] decide --> write["Write"] write --> review["Review"] review --> deliver["Close and build"] deliver --> base["New baseline"] ``` Building completes the currently approved state; it does not freeze the Context knowledge workspace. When a source moves on, `context update` opens a new round for the selected change. The workflow hands the Agent the fixed old and new source versions and the confirmed requirement scope, plus a list of pages that cite the changed material. ## Deciding what to change The listed pages are candidates to inspect, not an instruction to rewrite all of them. For each page the Agent reads its current approved Markdown and the change, then submits one decision: no change, or a concrete correction. Unrelated content and readers' earlier improvements are preserved. Existing references cannot discover every new topic, so the Agent also inspects additions and shared dependencies and lists necessary **new pages**, each with a path, title, registered sources and instruction. New pages go through the same writing and review as revisions. A renamed subject is revised in place rather than given a new identity; a retirement explains what disappeared and which readers are affected instead of silently deleting pages. ## Moving the baseline The CLI keeps the previous processed version until every requested page has been approved, closed and built. If temporary progress is lost, the next inspection starts again from that version and keeps pages already approved. A saved report or acquisition receipt does not prove the update was completed. See [Version-Aware Knowledge](). ## Keep the update local For one or two documents or a clearly bounded module, the update stays local: which articles to add or revise, and where readers expect them. It does not turn into a taxonomy for the whole knowledge workspace or a navigation redesign. Only the sources needed for the current change are restored; missing material stays a gap rather than being treated as investigated. ## Ways an update starts | Trigger | How | | --- | --- | | A source changed | Tell `/c4a:context` the new version; it runs `context update` for the selected scope | | A page is wrong or incomplete | `context revise "" --instruction ""` continues through Review and delivery, with no recapture for wording-only changes | | Unattended or scheduled runs | An authorized task can pass `CONTEXT_RUN_POLICY` with `plan_review` and `knowledge_review` set to `ask` or `delegate`; human-only Gates still stop | Gaps found while answering questions are handled the same way: they become revision tasks for the affected pages. --- ## Sources - [context/packages/context-cli/README.md L123–L124 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-update.md L9–L16 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L155–L157 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-update.md L15–L27 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-update.md L41–L47 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/resources/procedures/source-update.md L29–L32 · 3b0ce0a]() - [context/packages/context/docs/reference/indexer-provider-protocol.md L637–L639 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L64–L69 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L52–L58 · 3b0ce0a]() - [context/packages/context/docs/guides/knowledge-updates.md L13–L17 · 3b0ce0a]() - [context/packages/context/docs/getting-started.md L9–L27 · 3b0ce0a]() --- ## The Indexer System # The Indexer System ## What an Indexer is An Indexer is an Agent skill that helps the Agent expose a source's skeleton and write source-grounded articles from it. It is guidance for reading and writing, not a mandatory full scan and not a classifier inside the CLI. The CLI prepares each stage, supplies its material and acceptance rules, and checks the result; the Indexer contributes how to investigate and explain one kind of source. ## Four built-in Indexers | Indexer | Reads | Starts from | | --- | --- | --- | | `context-code-indexer` | Repository modules | Directory and file navigation, manifests, entries and registrations; detailed code reading during writing | | `context-markdown-indexer` | Captured documents and same-repository docs | Titles, bounded opening excerpts and H2/H3 outlines; full text before writing | | `context-note-indexer` | Saved notes, excerpts and observations | Direct reading, no parser | | `context-sessions-indexer` | Saved conversation summaries | Direct reading, no parser | All four are installed with the plugin and discoverable in every supported host. Installing an Indexer makes it available; it does not select it. [Community Indexers]() describes each one in more detail. ## How the workflow uses them ```mermaid flowchart LR req["Requirements"] --> plan["Planning"] plan -->|"picks Indexers"| usage["indexer_usage"] usage --> write["Stage writing"] write -->|"CLI checks"| cand["Candidates"] ``` - `src/indexers.yaml` holds only confirmed requirements: purpose, reader goals, coverage domains and authorized sources. - During planning the Agent chooses the relevant Indexers and records them as `indexer_usage` in the temporary plan; that choice is not persisted on articles. - Several Indexers may explain different aspects of the same module, and their findings can support one article. There is no primary owner, no Provider resolution step and no version or hash pinning of skills. - Each writing task produces Markdown and references in a temporary directory; the CLI accepts them and owns Candidates, Review and formal output. ## Creating your own When a technology or document family needs specialist guidance, `/c4a:context-indexer-create` writes a new reusable Indexer skill in a directory you choose. A new Indexer starts with a useful skeleton — source structure, recognizable features, names, established counts and entry locations — and may add a bounded helper for its technology. It delivers a `SKILL.md` plus only the references, templates or scripts that help, and is validated against realistic anonymous material. It does not register a Provider manifest or start production; after installation it is available for the Agent to select. See [Creating an Indexer]() for the step-by-step guide and [Providers and Customization]() for combining, replacing and disabling Indexers. Where a needed structural fact is missing, writing guidance cannot create it — that calls for a parser. See [Code Extraction](). --- ## Sources - [context/packages/context/docs/guides/indexer-provider-and-customization.md L7–L13 · 3b0ce0a]() - [context/packages/context/docs/guides/indexer-provider-and-customization.md L75–L81 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/SKILL.md L16–L31 · 3b0ce0a]() - [context/plugins/context/skills/context-markdown-indexer/SKILL.md L24–L38 · 3b0ce0a]() - [context/plugins/context/skills/context-note-indexer/SKILL.md L11–L27 · 3b0ce0a]() - [context/plugins/context/README.md L13–L22 · 3b0ce0a]() - [context/plugins/context/skills/context-sessions-indexer/SKILL.md L24–L27 · 3b0ce0a]() - [context/packages/context/docs/reference/project-api.md L204–L215 · 3b0ce0a]() - [context/packages/context/docs/guides/indexer-provider-and-customization.md L23–L43 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/SKILL.md L22–L25 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/SKILL.md L10–L41 · 3b0ce0a]() - [context/packages/context/docs/reference/code-extractors.md L37–L45 · 3b0ce0a]() --- ## Code Extraction # Code Extraction ## Parsers produce facts, not knowledge Parser packages read code and interface definitions and emit deterministic structural facts: symbols, source spans, imports and exports, routes, contracts. They never create Candidates, write `knowledge/` or control Review. The selected Indexer interprets those facts together with the readable source and writes reader-oriented articles. ```mermaid flowchart LR code["Pinned module"] --> parsers["Parsers"] parsers --> facts["Structural facts"] facts --> indexer["Code Indexer"] code --> indexer indexer --> art["Articles"] ``` ## Available parsers | Package | Structural facts | | --- | --- | | `@c4a/extract-ts` | TypeScript/JavaScript symbols, exports, imports, calls and React Router routes | | `@c4a/extract-go` | Go declarations, imports, calls and common HTTP routes | | `@c4a/extract-rush` | Rush projects, tags, entries, dependencies and owner boundaries | | `@c4a/extract-thrift` | Thrift services, methods and declared data types | | `@c4a/extract-proto` | Protobuf messages, fields and service definitions | | `@c4a/extract-mdx` | Markdown/MDX structure, component references, examples and source spans | | `@c4a/extract-contract` | Supported structured API contract declarations (OpenAPI, GraphQL) | | `@c4a/extract-style` | Stylesheet declarations and selectors | | `@c4a/extract-sql` | Supported SQL schema declarations | | `@c4a/extract` | The shared extraction protocol, plugin runner, scanner and snapshot records | All of them ship inside `@c4a/context-cli`. ## Smallest parser set first Parsing is an Indexer implementation detail, not a separate phase in `src/index.ts`. The order is: 1. identify the target boundary and the reader's questions; 2. let the Indexer inspect language, manifests, entries, routes and contracts; 3. use the smallest parser set that covers those questions; 4. keep parser output as facts and write articles from facts plus readable source. During planning, the Code Indexer does not run a full-repository parse just to learn whether a feature exists; deep extraction belongs to writing a selected topic. ## When a technology is not supported Distinguish a parser limitation from missing writing guidance. Configuration can select supported behavior, but instructions and templates cannot create missing structural facts. The workflow reports the capability gap and the smallest supported step; when a technology is useful across projects, a reusable parser is preferred over a project-local pipeline. --- ## Sources - [context/packages/context/docs/reference/code-extractors.md L31–L35 · 3b0ce0a]() - [context/ARCHITECTURE.md L338–L356 · 3b0ce0a]() - [context/packages/context/docs/reference/code-extractors.md L16–L29 · 3b0ce0a]() - [context/packages/extract-mdx/README.md L5–L5 · 3b0ce0a]() - [context/packages/context-cli/package.json L55–L67 · 3b0ce0a]() - [context/packages/context/docs/reference/code-extractors.md L1–L14 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/references/indexer.md L14–L19 · 3b0ce0a]() - [context/packages/context/docs/reference/code-extractors.md L37–L45 · 3b0ce0a]() --- ## Source Graph Overview # Source Graph Overview **Context Source Graph** is a self-hosted service for searching and reading code at pinned Git revisions. It is built on Go, Git and the Zoekt trigram index, and it exists for the workload AI coding Agents create: many small, precise *search, then read* round trips against code the Agent has not checked out. Every request resolves to one exact commit before anything is read, so a search hit, the file it points to and a later diff all describe the same snapshot. The same operations are available in a browser, over HTTP, as an MCP server and from a command-line client. ```mermaid flowchart LR callers["People, scripts
and AI Agents"] --> surfaces["Website · HTTP · MCP · CLI"] surfaces --> service["repo-service
one shared contract"] service --> git["Git mirrors
per repository"] service --> engine["Zoekt index
child process"] service --> db["Application database
SQLite, PostgreSQL or MongoDB"] git -->|background sync and indexing| engine ``` Source Graph is part of the Context project. The name does not imply any affiliation with the Sourcegraph platform. ## Code and live demo - **Source code:** [github.com/context4ai/sourcegraph](https://github.com/context4ai/sourcegraph). - **Live demo:** [https://context4ai-portal.fly.dev/sourcegraph/](https://context4ai-portal.fly.dev/sourcegraph/), also reachable at [https://context4ai-sourcegraph.fly.dev/sourcegraph/](https://context4ai-sourcegraph.fly.dev/sourcegraph/). It is the public, read-only instance behind this documentation site's knowledge service and serves `context4ai/context` and `context4ai/sourcegraph`. Its MCP endpoint is `/sourcegraph/mcp`. [Deployment Recommendations]() shows how it is deployed. - **Optional for Context:** Context works without Source Graph. When no instance is installed or configured, Context's query skill reads code through a shallow, sparse partial clone and grep instead. ## Why it exists An Agent answering a question about code usually needs a handful of exact lines, not a whole repository. Cloning every repository into every Agent sandbox at the right revision is slow, and running `rg` or `git grep` over a checkout repeats the same scan on each call. Source Graph keeps an index per repository and answers instead: - **Fast.** Indexed search typically completes in a few milliseconds on the server. With the service in the same region as its callers, a full request including the network stays well under 100 ms. [Pinned Search and Reads]() explains where the speed comes from and shows the measured comparison. - **Reproducible.** Branches resolve to a commit first, and full commit SHAs are accepted only inside the repository's retention window, so answers never drift to a different snapshot mid-conversation. - **Agent-ready.** The MCP endpoint is stateless Streamable HTTP and works with any MCP client. Anonymous access is read-only and limited to public repositories. - **Small footprint.** One process manages the Git mirrors, the search engine and background indexing; SQLite is the default database. ## One contract, four surfaces All four entry points expose the same operations: | Operation | What it does | | --- | --- | | `repositories` | List registered repositories and their observed branches | | `availability` | Show a repository's retained versions and indexing status | | `resolve` | Turn a branch, or an eligible full SHA, into the fixed commit to use next | | `search` | Search file contents at one commit, shaped like `rg` | | `read` | Read a line range of one file at one commit | | `read_many` | Read up to ten known ranges at one commit in a single MCP call | | `list` | List one directory at one commit | | `diff` | Compare two eligible commits | | `prepare` | Ask for a commit to be synchronized and indexed (authorized callers only) | The website lives under `/sourcegraph/`, the MCP endpoint at `/sourcegraph/mcp`, and the HTTP API under `/sourcegraph/v1/` and `/sourcegraph/api/`. The command-line client `sourcegraph-cli` calls the same HTTP routes. Exact routes, tool inputs and limits are in the [HTTP and MCP]() and [CLI]() references. ## How an instance is put together A Source Graph instance is a single `repo-service` process. It starts the Zoekt search server as a child process listening only on the loopback interface, keeps a bare Git mirror for each registered repository on its data volume, and runs background workers that synchronize monitored branches and index new branch heads. The application database stores repositories, jobs, identities and settings. SQLite is the default; PostgreSQL and MongoDB are supported for larger or sharded deployments. Git mirrors and indexes always stay on the instance's local disk — search speed comes from that locality — so capacity is planned around disk rather than CPU. To grow, run several instances that each own a disjoint set of repositories; never run two instances over the same repositories or data directory. [Self-Hosting]() covers both topologies. Repositories can also ship WebAssembly plugins named `.sourcegraph.wasm` that add text to `read` and `read_many` results. Context uses this to attach each knowledge section's sources, described in [Evidence for Context](). ## Who can do what Without any sign-in provider configured, an instance is an anonymous, read-only site: visitors can search and read repositories marked public, subject to per-minute rate limits. Adding Google or GitHub sign-in enables administration, and the first verified user becomes the administrator. Signed-in users can create personal API keys for scripts and Agents, and a service token covers automation. Registering repositories, indexing older commits and other changes require an administrator or the service token. [Authentication and Access Control]() lists the full matrix. ## Where to go next A public demo instance at [context4ai.org/sourcegraph](https://context4ai.org/sourcegraph/) indexes the Context and Source Graph repositories and allows anonymous reading. | To… | Read | | --- | --- | | Understand pinned search and the speed comparison | [Pinned Search and Reads]() | | See how Context knowledge and Source Graph combine | [Evidence for Context]() | | Connect a browser, MCP client, script or the CLI | [Connecting]() | | Add repositories and monorepo path groups | [Registering Repositories]() | | Deploy your own instance | [Self-Hosting]() | | Configure sign-in and API keys | [Authentication and Access Control]() | | Run, monitor and troubleshoot it | [Operations]() | | Look up routes, tools, flags and settings | [HTTP and MCP](), [CLI](), [Query Syntax](), [Configuration]() | --- ## Sources - [sourcegraph/README.md L1–L16 · 4e5c555]() - [sourcegraph/README.md L105–L109 · 4e5c555]() - [sourcegraph/cmd/repo-service/main.go L113–L126 · 4e5c555]() - [sourcegraph/README.md L43–L43 · 4e5c555]() - note:20261013/demo-deployment.md · demo-deployment.md L12–L19 - [context/plugins/context/skills/context-inspect-search/SKILL.md L348–L352 · 3b0ce0a]() - [sourcegraph/README.md L18–L25 · 4e5c555]() - [sourcegraph/internal/service/service.go L289–L349 · 4e5c555]() - [sourcegraph/README.md L22–L22 · 4e5c555]() - [sourcegraph/docs/interfaces.md L1–L8 · 4e5c555]() - [sourcegraph/internal/mcpserver/server.go L29–L82 · 4e5c555]() - [sourcegraph/cmd/repo-service/main.go L96–L161 · 4e5c555]() - [sourcegraph/internal/service/worker.go L25–L45 · 4e5c555]() - [sourcegraph/docs/deployment.md L3–L17 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L180–L240 · 4e5c555]() - [sourcegraph/internal/httpserver/website_access.go L15–L36 · 4e5c555]() - [sourcegraph/docs/authentication.md L1–L5 · 4e5c555]() - [sourcegraph/README.md L41–L63 · 4e5c555]() --- ## Pinned Search and Reads # Pinned Search and Reads Source Graph answers each request at exactly one Git commit. It first turns the requested revision into a commit inside the repository's retention window, then searches the index or reads Git at that commit, and returns the commit with the result so the caller can keep using it. This page explains how revisions resolve, how versions are kept and indexed, what bounds a search or read, and why the approach is faster than running `rg` over a checkout. ```mermaid sequenceDiagram participant A as Agent participant S as Source Graph participant Z as Zoekt index participant G as Git mirror A->>S: search(repo, pattern) — no revision S->>S: resolve default branch to commit C S->>Z: generated query at C Z-->>S: bounded hits S-->>A: hits + Commit C + Partial / Truncated / Coverage A->>S: read(repo, revision C, path, lines) S->>G: blob at C S-->>A: numbered lines + Commit C + next range ``` ## How a revision resolves Every operation accepts an optional revision and resolves it with the same rules: | You pass | Source Graph uses | | --- | --- | | Nothing | The repository's discovered default branch when the policy follows it; otherwise the single configured `main` or `master` branch, at its last synchronized head | | A monitored branch name | That branch's last synchronized head | | A full 40-character lowercase commit SHA | That commit, if it is inside the retention window | | A short SHA, a tag, `HEAD` or another ref | Rejected (`SHORT_SHA_UNSUPPORTED`, `INVALID_REVISION`) | | An unmonitored branch | Rejected (`BRANCH_NOT_MONITORED`) | A commit outside the window returns `REVISION_NOT_ELIGIBLE` rather than a nearby substitute. Source Graph never silently replaces a requested baseline with another commit, so a caller that pins the returned commit gets the same snapshot on every later call. ## Which versions exist Each repository has a retention policy: one to eight monitored branches (optionally including the remote's default branch) and a window defined either by **days** (1–365) or by **count** (1–4096 first-parent commits per branch). Background synchronization fetches only the monitored branches — never tags — on the repository's sync interval, records each branch head and builds the set of eligible versions from the window. Many versions of one repository can therefore coexist. Indexing is separate from eligibility. After a successful sync, the service queues an index job for each branch head that is not yet indexed, and stops retrying a head after three failures. Older commits in the window stay readable from Git but are searchable only after someone with permission asks for them with `prepare`; searching an unindexed commit returns `INDEX_NOT_READY`. Each index is stored as a separate generation, and generations no longer referenced by any retained version are removed in the background, at most one per collection pass. ## What bounds a search Callers never send engine syntax. A search is a set of structured, `rg`-like fields — a line-oriented regular expression or literal, case folding, globs and directory paths — that the service compiles into an engine query at the resolved commit. The [Query Syntax]() reference lists every field. Results are a bounded first page. The first attempt returns up to 100 files and 1,000 matches with two lines of context; if the response would exceed its 2 MiB budget, the service retries with smaller pages and finally a file-only listing, all within a five-second deadline. The response metadata tells the caller what it got: - `Commit` and `Repository` identify the snapshot. - `Partial` means the engine stopped early, for example at its 10,000-match cap. - `Truncated` means more files or matches existed than were displayed. - `Coverage` describes what was indexed — text only, no symbol index, the registered paths and groups — so a zero-hit result is not proof that something is absent from the repository. ## What bounds a read A `read` returns an inclusive line range of one file at one commit, at most 500 lines and 256 KiB per call; when no range is given over MCP it starts at line 1 and covers up to 500 lines. The response says which lines were returned and where to continue, and flags truncation, binary content, unsupported encodings and Git LFS pointers instead of guessing. In a full-repository registration, reads go straight to Git and do not wait for indexing. In a monorepo registration, the path group must already be prepared at that commit (`CONTENT_NOT_READY` otherwise). `read_many` reads one to ten known ranges at one commit in a single MCP call, sharing a budget of 1,000 lines, 256 KiB and 30 seconds; each item reports its own content and error. ## Why it is faster than a checkout `rg` and `git grep` scan files on every call; the trigram index does that work once per commit. The project's README reports this comparison against the public demo repository (`context4ai/context`, 2,359 indexed files) and a local checkout of the same commit: | Query | Source Graph (server) | `rg` (local) | `git grep` (local) | `grep -r` (local) | | --- | ---: | ---: | ---: | ---: | | Literal, 13 matching files | 0.7–0.9 ms | 61 ms | — | — | | Literal, ~100+ matching files | 3.6–5.2 ms | 61 ms | 39 ms | 3.6 s | | Regex, no matches | 0.4 ms | 62 ms | — | — | Server time is the search duration the engine reports. The local tools ran on an Apple M4 Pro with a warm page cache. Add the network round trip — a few milliseconds within one region — for end-to-end latency. The gap widens as repositories grow, and the service also removes the need to check out every repository at the right revision. Speed depends on locality: each instance keeps its Git mirrors and indexes on its own disk, so deploy instances in the same region as the Agents that call them. How Context's own measurements compare answering with and without Source Graph is covered in [Knowledge Retrieval](). --- ## Sources - [sourcegraph/internal/service/scoped_search.go L120–L168 · 4e5c555]() - [sourcegraph/internal/service/scoped_read.go L32–L62 · 4e5c555]() - [sourcegraph/internal/service/service.go L289–L349 · 4e5c555]() - [sourcegraph/internal/mcpserver/server.go L30–L30 · 4e5c555]() - [sourcegraph/internal/control/model.go L22–L40 · 4e5c555]() - [sourcegraph/internal/gitstore/fetch.go L128–L146 · 4e5c555]() - [sourcegraph/internal/service/schedule.go L155–L230 · 4e5c555]() - [sourcegraph/internal/zoektclient/client.go L105–L190 · 4e5c555]() - [sourcegraph/internal/service/scoped_search.go L215–L260 · 4e5c555]() - [sourcegraph/internal/gitstore/read_content.go L13–L30 · 4e5c555]() - [sourcegraph/internal/mcpserver/server.go L54–L65 · 4e5c555]() - [sourcegraph/internal/service/read_many.go L13–L20 · 4e5c555]() - [sourcegraph/README.md L26–L39 · 4e5c555]() - [sourcegraph/README.md L80–L91 · 4e5c555]() --- ## Evidence for Context # Evidence for Context Context knowledge records, for every section, which source files and line ranges it was written from, each pinned to a commit. Source Graph can read any registered repository at any eligible commit. Together they let an Agent go from an answer to the exact code behind it without cloning anything: read the knowledge page, receive its recorded sources alongside the text, then read those sources at their recorded commits. ```mermaid flowchart LR ws["Knowledge workspace repo
knowledge/ + structure.yaml
+ context-evidence plugin"] -->|registered in| sg["Source Graph"] code["Source code repos
at recorded commits"] -->|registered in| sg agent["Agent with
context-inspect-search"] -->|read knowledge page| sg sg -->|text + references| agent agent -->|read cited range at its commit| sg ``` Two pieces make this work: a WebAssembly plugin that Context places in the knowledge workspace repository, and the query Skill's access policy for using Source Graph. ## The evidence plugin Source Graph lets a repository ship plugins named `.sourcegraph.wasm`. When it serves a `read` or `read_many`, it discovers plugins in that repository at the same commit being read and runs them after the ordinary read has succeeded; their output is appended to the returned text. Plugins have no network, filesystem or process access — the host binds every file they read to the same repository, commit and readable scope. Context's plugin is `context-evidence.sourcegraph.wasm`. For each returned file under `knowledge/` that ends in `.md`, it: 1. Reads the full article at that commit only to locate its `` markers, then selects the sections that overlap the lines actually returned. 2. Looks up those sections in `knowledge/structure.yaml`, the approved structure that records each section's references. 3. Appends a YAML `references:` list for the item, deduplicated. Repository references with a full commit and a supported remote become commit-pinned web URLs with line anchors; other references keep their structured fields. If anything fails, the ordinary text is still returned and the plugin adds diagnostics instead of references. A reference is recorded metadata, not proof that the source was reread during this query. ## Getting the plugin into the repository `context init` writes the plugin when the workspace is the repository root, or when it has no enclosing Git repository. For an existing workspace run: ```bash context evidence install --format json ``` A workspace nested inside a larger repository needs an explicit choice: `--repository-root ` when Source Graph hosts the whole repository, or `--plugin-root ` when it hosts only a registered path; the workspace directory relative to that root is then passed to the plugin as `workspace_root`. The installer upgrades only files it recognizes as earlier versions of the plugin, preserves unknown or modified files with the same name, and never commits or pushes — commit the file and let Source Graph synchronize before relying on it remotely. ## How the query Skill uses Source Graph The `context-inspect-search` Skill reads Source Graph through a read-only MCP server the host names `context-sourcegraph`. `CONTEXT_QUERY_ACCESS_MODE` decides when: | Mode | Behavior | | --- | --- | | `auto` (default) | Reuse suitable local material first, then prefer the authorized read-only service before local retrieval | | `remote` | Read knowledge and original code only through the service; never clone automatically, and on failure use only material that already carries a version | | `local` | Local retrieval only; no MCP required | For remote knowledge, the Skill resolves a branch once and pins the returned full commit for every knowledge read in that answer. It searches within `knowledge/**`, reads the matching sections, and consumes the references the plugin already attached rather than rereading to request them; when a host does not enable plugins by default it asks for `plugins: [{"name":"context-evidence"}]` once. ## Reading the cited code For code, the Skill passes the exact repository from the source registration, the recorded full commit as the revision, and a repository-root-relative path that already includes any registered subpath. It reads directly when the file is known and searches that repository and commit when it is not, without a discovery pass before every query. It never replaces a missing baseline with the default branch. Each piece of evidence keeps four things together: the repository, the returned full commit, the path and the returned line range. Multi-step reads stay on the same commit, follow the continuation range the service returns, and treat `Partial`, `Truncated` and coverage as limits rather than proof of absence. With `read_many`, every item's content and error are checked separately. ## Related pages - [Reading Code Evidence Remotely]() — turning this on for an Agent. - [Evidence Chains and Index First]() — why every section records its sources. - [Pinned Search and Reads]() — how Source Graph resolves commits and bounds reads. --- ## Sources - [context/packages/context-evidence-wasm/README.md L1–L5 · 3b0ce0a]() - [sourcegraph/docs/ref/repository-plugins.md L1–L15 · 4e5c555]() - [sourcegraph/internal/service/plugins.go L70–L116 · 4e5c555]() - [context/packages/context-evidence-wasm/src/lib.rs L144–L235 · 3b0ce0a]() - [context/packages/context-evidence-wasm/README.md L60–L96 · 3b0ce0a]() - [context/packages/context-cli/README.md L1–L12 · 3b0ce0a]() - [context/packages/context-cli/src/project/evidencePlugin.ts L70–L92 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L47–L56 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L158–L190 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L266–L276 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L302–L321 · 3b0ce0a]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L158–L166 · 3b0ce0a]() --- ## Why Graph Engineering # Why Graph Engineering Agent Graph is a work-contract layer for Agent Skills. You describe a workflow as a small graph of legal steps; at runtime it reads the current **Facts** and tells an Agent what to do next, which files to read for that step and what proves the step is done. It never calls a model, assigns Agent identities, moves shared state or schedules workers — it coordinates the work, not the Agents. Existing Agents and hosts consume its Routes and keep the execution boundary. Agent Graph ships as `@c4a/agent-graph`: versioned file specifications with JSON Schemas, a Node.js SDK and an `agent-graph` CLI for authoring, inspecting, testing, building and resuming workflows. Context runs its whole knowledge workflow on it; see [Agent Graph in Context](). The source code, issues and discussions live in the GitHub repository [context4ai/agent-graph](https://github.com/context4ai/agent-graph). Where to go next: - **How it works:** [Core Model](), [Runs and Recovery](), [Skills and Providers](). - **Guides:** [Getting Started](), [Authoring Graphs](), [Testing and Publishing](). - **Reference:** [Specification](), [CLI and SDK](), [Migration](). ## The problem Agents usually know enough. The harder problem in a long task is knowing which part applies **now**, which action is legal next, what proves that action is complete and where to resume after an interruption. Making the prompt longer does not solve this reliably: a complex Skill in one document has a flat topology, every rule sits next to every other and is often loaded together, and the Agent has to infer the current phase from the conversation. Such a workflow is also hard to test without running the whole model behavior. > Context should be discovered, not accumulated. The plan is explicit; the path is selected from current reality. ## A small example An Agent has one job: write a draft, check it, finish. ```mermaid flowchart LR write["Write draft"] -->|"completed"| check["Check draft"] check -->|"completed"| done(["Done"]) ``` The host can observe two facts: `draft.saved = true` and `review.passed = false`. The draft exists but has not passed the check, so Agent Graph returns **Check draft** as the current Route. Nothing is guessed from the conversation: when `review.passed` becomes `true` the next evaluation reaches **Done**; while it stays `false` the Route stays **Check draft**. Four ideas carry the example: the **Graph** describes the legal sequence, **Facts** describe what is true now, the **Route** is the next legal step selected from those Facts and the **Action** tells the Agent or host how to perform it. Real workflows add required files, human Gates, explicit Outcomes, choices and recovery paths without changing this loop. ## The Graph Engineering principles "Graph Engineering" is an emerging architecture label, not an official protocol or a single implementation; writing under that name covers feedback and audit loops, durable multi-Agent organizations and dynamically generated task graphs. Agent Graph takes the engineering principles without claiming the term, and narrows the question to: *how can an Agent discover the next legal action and only the context it needs, while a long workflow stays observable, testable and recoverable?* - **From prompt to topology.** Prompt engineering improves one interaction and context engineering shapes what one interaction sees. Graph Engineering adds how information, authority, actions, evidence and feedback move across many interactions. A graph does not add context; it creates boundaries so the Agent loads a small, relevant slice after a Route is chosen. - **Reality stays outside the optimizer.** Agent Graph separates **facts** (observable state from a Provider or host), **outcomes** (explicit results of an attempted action) and **instructions** (procedures). Instructions cannot assert facts, and a recorded success without the evidence a node requires becomes `unverified`. Source digests, build receipts, test results and scoped review decisions are typical external anchors; another model agreeing is useful evidence, not an anchor. - **Contracts, not diagrams of prose.** Only steps that are independently actionable, gated, recoverable, repeatable or testable become nodes; explanation stays in files. Every element carries a boundary contract — an Action its runner and effect, a Gate who decides, a node the facts it needs and the facts that prove it done — so the visual graph is a view of executable contracts. - **Graphs of loops.** Review, repair, polling and re-planning loops are explicit `repeat` edges with typed Outcomes and stop conditions. Each iteration is a Route and each result an event, so a host can checkpoint, enforce budgets or hand work to another Agent. - **Stable organization, dynamic work.** Graphs describe stable categories of work; current targets, dates and queue items are Facts resolved by stable host Actions, so the Graph never has to be rewritten per run. - **Progressive disclosure as structure.** A thin Skill holds the bootstrap loop, evaluation returns summaries and each Route returns only its own resources as file locations with digests, never document bodies. - **Observability without a mandatory runtime.** Evaluation can be stateless; an optional Run records events and outcomes at a path the host chooses. - **Testability before autonomy.** Route tests assert which step a known state exposes, without calling a model. ## How the principles become implementation | Principle | Agent Graph implementation | | --- | --- | | External reality | Restricted fact checks and `satisfiedBy` | | Boundary contracts | Strict JSON Schemas with closed object fields | | Typed feedback | Eight distinct Outcomes | | Progressive context | Required and recommended file Resource locations | | Explicit authority | Gates plus session-scoped authority input | | Recovery | Failure and repeat edges, Run events, checkpoint and resume | | Explainability | Deterministic Evaluation and Route, inspection, digests | | Stable reasons | Route reason codes plus an optional Code Catalog | | Testability | Declarative state-to-route cases | | Portability | Relative Provider references and host-selected stores | | Supply-chain clarity | Action effects, reachable-file bundles, content digests | Version 1 deliberately does **not** provide arbitrary expressions, self-modifying graphs, cross-Provider calls, model invocation or multi-Agent orchestration, parallel execution, edge-carried artifacts or shared mutable state, schedulers or durable timers, automatic trust in commands or third-party Skills, or semantic proof that an Agent's output is correct. Those limits keep it a standard and toolchain rather than another all-encompassing Agent framework. ## When to use it Not every Skill needs a Graph. Keep a short, single-session task in `SKILL.md`. Adopt Agent Graph when a host can supply trustworthy external facts and the work truly needs verifiable completion, recovery across sessions, or testable routing and human Gates. It pays off for: - **large knowledge without a giant prompt** — procedures, schemas and manuals stay files, loaded only when a Route needs them; - **long tasks across session boundaries** — Facts and Outcomes reconstruct where the work is; an optional Run adds events and checkpoints; - **plans that react without drifting** — the Graph fixes the legal choices and stop conditions, current evidence picks the path; - **testing before model behavior** — references, cycles, resource boundaries and expected Routes are checked without a model. Agent Graph does not rewrite its own plan. Runtime routing follows the evidence; people improve the Graph from events, diagnostics and route tests. Installing the CLI alone does not make an Agent follow a workflow: a Provider defines the contract, a Skill makes it discoverable and a host supplies facts, enforces Gates and records outcomes. Pick your starting point in [Authoring Graphs](). --- ## Sources - [agent-graph/README.md L1–L12 · 9e8b98a]() - [agent-graph/README.md L80–L91 · 9e8b98a]() - [agent-graph/package.json L1–L12 · 9e8b98a]() - [agent-graph/README.md L12–L16 · 9e8b98a]() - [agent-graph/docs/en/graph-engineering.md L13–L22 · 9e8b98a]() - [agent-graph/README.md L20–L50 · 9e8b98a]() - [agent-graph/docs/en/graph-engineering.md L1–L37 · 9e8b98a]() - [agent-graph/docs/en/graph-engineering.md L39–L98 · 9e8b98a]() - [agent-graph/docs/en/graph-engineering.md L99–L124 · 9e8b98a]() - [agent-graph/docs/en/graph-engineering.md L125–L153 · 9e8b98a]() - [agent-graph/README.md L14–L16 · 9e8b98a]() - [agent-graph/README.md L52–L70 · 9e8b98a]() - [agent-graph/README.md L93–L98 · 9e8b98a]() --- ## Core Model # Core Model Agent Graph turns a static work contract and the current state into one legal next step. Every interaction follows the same loop: ```mermaid flowchart LR facts["Facts, Outcomes, authorities"] --> evaluate["evaluate: status, revision, routes"] evaluate --> resolve["route: one Route at that revision"] resolve --> act["Agent or host performs the Action"] act --> record["Record an Outcome, refresh Facts"] record --> facts ``` Evaluation and route resolution are read-only and deterministic: the same definitions and inputs give the same revision, the same Routes and the same order. Nothing is executed by Agent Graph itself; it returns what to run and what to read. ## Providers and Graphs A **Provider** is one independently versioned trust and publication boundary. Its manifest (`agent-graph.provider.v1`) lists Graph files explicitly — nothing is discovered by scanning — plus an optional Code Catalog and the supported toolchain range. References stay inside the Provider root, and several Providers stay isolated from each other. A **Graph** (`agent-graph.graph.v1`) is a deterministic route definition: named `entrypoints`, nodes and edges. Its topology is static. Target names, dates, phases or queue items belong in Facts, and a stable host Action resolves the concrete target, so a Provider never regenerates nodes because parameters changed. Every Graph declares at least one terminal node. | Node kind | Required field | Meaning | | --- | --- | --- | | `action` | `action` | Work done by a command, script, Agent Skill or host handler | | `gate` | `gate` | A decision that needs user or session authority | | `subgraph` | `graph`, `entry` | Enter another Graph in the same Provider | | `terminal` | `terminalOutcome` | End the frame with an explicit Outcome | Action and Gate nodes must carry a `reasonCode` starting with `route.` — a stable machine explanation of why the Route is offered. `priority` ranks routes that are legal at the same time; it never decides semantic fitness. `join: all` (the default) needs every incoming edge to match, `join: any` needs one. ## Facts Facts are observed state supplied by the Provider integration or host. Nodes test them with a deliberately small data model, not expressions: ```yaml requiresFacts: - path: sources.registered equals: true satisfiedBy: - path: artifact.digest exists: true ``` `path` is a dotted lookup in which numeric segments index arrays (`items.0.digest`); each check has exactly one of `exists` or `equals` with a scalar value. There is no JavaScript, template expansion or shell evaluation. - `requiresFacts` makes a node legal only under current state; if a check fails the node is `blocked` with a `required-fact-missing` diagnostic. - `satisfiedBy` proves a node complete without replaying it. Matching facts make it `completed` even with no Run record; a recorded `completed` without them becomes `unverified`. A claim made in conversation never creates a fact. ## Outcomes and edges Outcomes are the typed results of nodes: ```text completed partial failed unverified skipped pending blocked waiting-user ``` They are not aliases: `partial`, `unverified` and `skipped` never silently become `completed`, because the difference is what lets a graph recover. Every edge names the Outcomes that permit it (default `[completed]`): | Edge kind | Meaning | | --- | --- | | `flow` | General control transition | | `consumes` | The target consumes an artifact the source produced | | `requires` | The source is a prerequisite of the target | | `gatedBy` | A Gate source resolves the target's policy boundary | | `repeat` | A matching result re-arms an Action or Gate for another iteration | All non-repeat kinds use the same reachability rule; the kind records causal intent for inspection, tests and host policy. Edges carry no values or artifacts — hosts persist outputs and publish references or digests as Facts. Non-repeat edges must form an acyclic graph, so every loop is an explicit `repeat`. Fan-out and fan-in describe legal reachability, not parallel execution. ## How an Evaluation is computed Starting at the entry node, the evaluator repeatedly settles each reached node's Outcome — from `satisfiedBy` facts, then the recorded Outcome, then `pending` — and follows every edge whose Outcomes match, honouring `join` and re-arming `repeat` targets. Subgraph nodes evaluate their child Graph in place and take its terminal Outcome. Then: - a pending Action becomes an **immediate** candidate; - a pending Gate becomes a **requires-user** candidate, or an immediate one when the input carries its delegatable authority; - if exactly one terminal Outcome is reached the frame is `complete`; conflicting terminal Outcomes are an `error` (`terminal-outcome-ambiguous`); nothing reachable is `blocked` with `no-route`. Candidates are ordered by availability (immediate, then requires-user), then by higher `priority`, then by route ID. The `agent-graph.evaluation.v1` result has a `statusCode` (`actionable`, `waiting-user`, `blocked`, `complete` or `error`), an optional terminal `outcome`, one `primaryRoute` and up to three `alternativeRoutes` — each with its `reasonCode`, an optional Catalog `hint` and a label — plus compact diagnostics. A `route-alternatives-truncated` info diagnostic reports when more alternatives exist. The `revision` is a digest of the selected Graph's same-Provider dependency closure, the facts, the normalized outcomes and the authorities. Timestamps on outcome records and files used only by unrelated Graphs do not change it. ## Routes `route` resolves one route ID from an Evaluation into an `agent-graph.route.v1` plan: | Field | Content | | --- | --- | | `revision`, `routeId` | The Evaluation it belongs to; the route ID is derived from that revision | | `graph`, `node`, `callPath` | Where the step sits, including the Subgraph path | | `statusCode`, `reasonCode`, `hint`, `availability` | Why and how it is offered | | `action` | Action identity, runner and effect | | `commandPlan` | The exact command, script invocation or host handler, with its working directory | | `resources` | Required and recommended locations, each keeping its complete file, Graph-action or Host-action location envelope and a `readState` of `current` or `read-required` | | `gate` | For Gates: authority, resolution, and the separate inspection and resolution Actions | | `afterAction` | `recordNode` — the state key to record — and `evaluate: true` | If the caller passes the Evaluation's revision and the state has changed, resolution fails with `route-revision-stale`; a route ID no longer available fails with `route-stale`. An Agent Skill used by an `agent` Action is added as the first required resource. Document bodies are never embedded; the Route points to files and digests. ## Gates and authority ```yaml kind: gate reasonCode: route.review.approval-required gate: id: result-review prompt: Review the prepared result. authority: review delegatable: true inspectionAction: actions/inspect-review.yaml resolutionAction: actions/apply-review.yaml delegated: inspection: skip resolutionAction: actions/accept-review.yaml resources: { required: [], recommended: [] } ``` Without matching authority the Route is `waiting-user` and its ordinary `commandPlan` is empty. The optional read-only **inspection Action** prepares evidence for the decision and stays available while the Gate waits. The optional **resolution Action** (effect `write` or `external`) applies the decision, but a host must not run it until the user has confirmed. When `delegatable` is true and the current evaluation or Run carries the named authority, the Gate becomes actionable with `resolution: session-authority`; the `delegated` policy can then skip inspection, swap in a different resolution Action and replace the Gate's resources. Authority belongs to the current input or Run, never to the Provider definition. It resolves only delegatable Gates and never satisfies facts or bypasses validation. Context's fully managed mode is built on exactly this mechanism; see [Agent Graph in Context](). ## Explaining every step Every Route carries a machine-stable `reasonCode`. A Provider may add a Code Catalog (`agent-graph.code-catalog.v1`) whose `route-reason` entries give each code a short summary and an optional explanatory document, and whose `diagnostic` entries name product conditions with a severity. Once a Catalog exists, every Action and Gate reason code must be listed in it, turning reasons into a closed, documented set. Hosts and Agents branch on schema, status, reason and diagnostic codes, never on human descriptions. The exact fields of every object are in the [Specification](); how Runs persist Outcomes is in [Runs and Recovery](). --- ## Sources - [agent-graph/docs/en/README.md L20–L32 · 9e8b98a]() - [agent-graph/src/evaluator.ts L356–L391 · 9e8b98a]() - [agent-graph/src/router.ts L261–L354 · 9e8b98a]() - [agent-graph/docs/en/specification.md L7–L28 · 9e8b98a]() - [agent-graph/docs/en/specification.md L44–L81 · 9e8b98a]() - [agent-graph/docs/en/authoring.md L18–L32 · 9e8b98a]() - [agent-graph/docs/en/specification.md L84–L105 · 9e8b98a]() - [agent-graph/src/evaluator.ts L52–L60 · 9e8b98a]() - [agent-graph/src/evaluator.ts L137–L149 · 9e8b98a]() - [agent-graph/docs/en/specification.md L138–L166 · 9e8b98a]() - [agent-graph/docs/en/specification.md L330–L338 · 9e8b98a]() - [agent-graph/src/types.ts L1–L20 · 9e8b98a]() - [agent-graph/src/evaluator.ts L166–L326 · 9e8b98a]() - [agent-graph/src/evaluator.ts L126–L135 · 9e8b98a]() - [agent-graph/src/evaluator.ts L337–L391 · 9e8b98a]() - [agent-graph/docs/en/specification.md L352–L368 · 9e8b98a]() - [agent-graph/src/router.ts L198–L215 · 9e8b98a]() - [agent-graph/docs/en/specification.md L107–L136 · 9e8b98a]() - [agent-graph/examples/review-gate/graphs/review.yaml L1–L35 · 9e8b98a]() - [agent-graph/src/evaluator.ts L277–L291 · 9e8b98a]() - [agent-graph/docs/en/specification.md L310–L328 · 9e8b98a]() - [agent-graph/docs/en/specification.md L404–L410 · 9e8b98a]() --- ## Runs and Recovery # Runs and Recovery ## Facts first, history second The most robust state is the real system. When a host can observe what has happened — an artifact digest, a source revision, a test receipt, a deployed version — it passes those values as Facts and evaluation needs no stored state at all: ```bash agent-graph evaluate build --manifest provider.yaml --facts @observed-facts.json --format json ``` Such facts survive restarts and can invalidate stale work by themselves. When trust depends on who observed a value, the Fact carries the observer's identity and health too (for example `sourceRevision`, `available`, `fresh`). The host applies its own clock, lease or health policy and publishes stable states; Agent Graph never reads the wall clock. Because the whole Facts object is part of the revision, replacing an observer or a value turning stale invalidates an already resolved Route without touching the Graph. Use a **Run** only when you need execution history, a checkpoint for a long task, Outcomes that cannot be observed from outside, or repeated iterations. ## Runs A Run (`agent-graph.run.v1`) is optional, host-owned execution memory in one JSON file: | Field | Content | | --- | --- | | `provider`, `graph`, `entry`, `workspace` | What the Run executes | | `facts` | Facts supplied to routing | | `outcomes` | The latest Outcome record per fully qualified state key | | `authorities` | Session authorities currently granted | | `events` | Append-only, numbered events such as `run.started`, `node.outcome-recorded`, `facts.updated`, `run.checkpointed`, `run.resumed` | ```bash agent-graph run start monitor --manifest provider.yaml --state .runtime/monitor.json --workspace . agent-graph route monitor --manifest provider.yaml --state .runtime/monitor.json --format json agent-graph run record monitor/poll partial --state .runtime/monitor.json ``` After an Action, record its Outcome under the exact `afterAction.recordNode` key from the Route — a key such as `monitor/poll`, prefixed with the Subgraph call path when nested. Outcomes keep only the latest record per key, while events keep every iteration. `run start`, `checkpoint` and `resume` refuse to overwrite an existing file, and every write is validated against the Run schema and written atomically. There is no default directory: the host chooses where Runs live. ## Loops ```yaml edges: - { from: poll, to: poll, kind: repeat, outcomes: [partial] } - { from: poll, to: done, outcomes: [completed] } ``` Recording `partial` re-arms `poll`; recording `completed` reaches the terminal. Agent Graph does not busy-wait, sleep or run the loop itself: the Agent or host decides when to take each Route and may stop by its own time or budget policy. Transport retries, model retries and workflow Outcomes are different things — an exhausted retry should be recorded as `failed` or `unverified`, never `completed`. ## Partial work and failure paths Recovery is modelled with explicit Outcomes and edges, not hidden in prose: ```yaml edges: - { from: verify, to: done, outcomes: [completed] } - { from: verify, to: repair, outcomes: [failed, unverified] } ``` Use `partial` when some required work succeeded and some did not; counts and receipts go in event details or Facts, while routing still uses the Outcome. Never drop the failed items and report the rest as a complete batch. When a result must be provable, add `satisfiedBy`: a recorded success without its proof evaluates as `unverified`, so a crash or handoff between "done" and "proved" routes deterministically to verification or repair. ## Checkpoint and resume ```mermaid flowchart LR run["Run file: facts, outcomes, events, authorities"] -->|"run checkpoint"| cp["Checkpoint: same state, authorities removed"] cp -->|"run resume"| resumed["New Run file: authorities cleared, event appended"] resumed --> eval["Refresh Facts, then evaluate again"] ``` ```bash agent-graph run checkpoint --state .runtime/monitor.json --to .runtime/checkpoints/before-handoff.json agent-graph run resume .runtime/checkpoints/before-handoff.json --state .runtime/resumed.json ``` A checkpoint is a validated copy of the Run with session authorities stripped. Resume copies it to a new path, clears authorities again, appends `run.resumed` and evaluates against the **current** Provider definitions. Authority must be granted again explicitly, so a checkpoint can never become a permanent unattended mode. Facts may have changed while paused, so the host refreshes them first; `satisfiedBy` checks run again. A checkpoint is execution memory, not a truth anchor. ## Rejecting stale plans Every Evaluation has a revision derived from the Graph closure, Facts, Outcomes and authorities, and every route ID is derived from that revision. An Agent passes the revision when resolving: ```bash agent-graph route main --revision --format json ``` If anything relevant changed in between, resolution fails with `route-revision-stale`; a route that is no longer available fails with `route-stale`. The Agent then evaluates again instead of executing a plan computed for older state. Hosts extend the same idea to their own write commands — Context binds every mutating command to the workflow revision that selected it, see [Agent Graph in Context](). ## Session authority Authority can be given to one evaluation (`--authority release.approve`) or set on a Run for a host-defined session (`run authority --set release.approve`). The host clears it when the user's delegation ends, and `run resume` clears it automatically. It only resolves Gates marked `delegatable` and never bypasses fact checks, schema validation, verification or non-delegatable Gates. ## What the host owns Agent Graph selects a legal Route; it does not own the resources used to execute it. A host running several Actions in one process should give each one an execution scope for child processes, timers, temporary files, locks and watchers, closed in reverse order before it publishes the Action's receipt or evaluates again. That scope is not a transaction: lasting results still need their own revision checks, atomic commits and verification, published as Facts. The same holds for host-materialized resources: the host validates the result envelope against the computed input digest, persists it as a Run Fact or in its own store, and on recovery reuses it only if the digest still matches; a mismatch must lead to an explicit `failed` or `unverified` path rather than silent re-execution. Run files, checkpoints and caches live wherever the host chooses — a product runtime directory, an ignored workspace folder, a task store or a temporary location. Provider bundles stay read-only, and materialized resources are cache entries that must be reproducible after deletion. --- ## Sources - [agent-graph/docs/en/runtime-and-recovery.md L1–L18 · 9e8b98a]() - [agent-graph/docs/en/authoring.md L72–L92 · 9e8b98a]() - [agent-graph/docs/en/runtime-and-recovery.md L23–L26 · 9e8b98a]() - [agent-graph/src/runStore.ts L1–L66 · 9e8b98a]() - [agent-graph/src/runStore.ts L74–L93 · 9e8b98a]() - [agent-graph/docs/en/runtime-and-recovery.md L26–L45 · 9e8b98a]() - [agent-graph/docs/en/runtime-and-recovery.md L47–L71 · 9e8b98a]() - [agent-graph/src/evaluator.ts L235–L245 · 9e8b98a]() - [agent-graph/docs/en/runtime-and-recovery.md L72–L88 · 9e8b98a]() - [agent-graph/src/evaluator.ts L137–L149 · 9e8b98a]() - [agent-graph/src/runStore.ts L113–L136 · 9e8b98a]() - [agent-graph/docs/en/runtime-and-recovery.md L90–L104 · 9e8b98a]() - [agent-graph/src/router.ts L261–L279 · 9e8b98a]() - [agent-graph/src/evaluator.ts L81–L84 · 9e8b98a]() - [agent-graph/src/evaluator.ts L337–L354 · 9e8b98a]() - [agent-graph/docs/en/runtime-and-recovery.md L106–L122 · 9e8b98a]() - [agent-graph/src/runStore.ts L104–L111 · 9e8b98a]() - [agent-graph/docs/en/runtime-and-recovery.md L18–L24 · 9e8b98a]() - [agent-graph/docs/en/runtime-and-recovery.md L124–L143 · 9e8b98a]() --- ## Skills and Providers # Skills and Providers Agent Graph extends Agent Skills instead of replacing them. Each part of an integration has one job: ```mermaid flowchart LR skillNode["Skill: name, description, binding"] --> providerNode["Provider bundle"] providerNode --> graphNode["Graph and Entry"] graphNode --> routeNode["Route for current Facts"] routeNode --> resourceNode["Required and recommended Resources"] hostNode["Host: Facts, execution, Gates, storage"] --> routeNode ``` | Part | Responsibility | | --- | --- | | Skill | Advertise when the capability applies and bind Provider, Graph and Entry | | Provider bundle | Define the static legal work, Resources, Gates, reason codes and route tests | | Host | Resolve bundles, observe Facts, persist state, materialize dynamic Resources, run host Actions, enforce Gates | | Agent | Consume the selected Route, read required Resources, do the work and report an Outcome | | Agent Graph | Validate contracts and deterministically evaluate and resolve Routes | ## Binding a Skill A host still uses the Skill's `name` and `description` to decide whether it matches a request. Once selected, three metadata fields form one machine binding: ```yaml --- name: release-package description: Inspect, review, and release a package through the installed workflow. metadata: agent-graph: path:../../release-graph/provider.yaml agent-graph.graph: release agent-graph.entry: default --- ``` | Field | Purpose | | --- | --- | | `agent-graph` | Locate the Provider | | `agent-graph.graph` | Select one Graph in it | | `agent-graph.entry` | Select a public entrypoint in that Graph | All three are required and validated together; the Agent never infers the Graph or Entry from prose. The Skill body keeps only the bootstrap contract — evaluate the bound Graph, resolve the Route, read every required resource marked `read-required`, stop at unresolved Gates, record an explicit Outcome and evaluate again. Phase procedures, schemas and generated context stay Route resources instead of being copied into the Skill. ## Locating Providers - **`path:`** resolves from the directory of that exact `SKILL.md`, never from the process working directory, and points to a source manifest or a built `manifest.json`. The Provider directory can have any name. - **`provider:`** delegates the location to a host registry or bundle resolver, for example a registry file mapping `company/release` to an installed `manifest.json`. The registry belongs to the host. Skills must not hard-code npm prefixes, plugin cache versions or machine paths, and there is no global `~/.agent-graph` or per-project `.agent-graph` directory. The host separately decides where bundles are resolved from, where Run files live (`--state`) and where dynamic resources are cached (`--cache`). ## One Provider, many Skills Several Skills can share one Provider and select different Graphs or Entries; Graph files, procedures and schemas stay single-source, and sharing an Action or Resource creates no execution dependency. One host can also install several Providers: their identities and state stay separate by Provider ID, manifests are never merged, the current Skill picks its own Provider, and a Subgraph cannot call into another Provider in version 1. Each plugin publishes its own bundle instead of mutating a shared manifest. Graphs stay static while work stays dynamic. Instead of a node per module, document or date, a stable host Action such as `handler: batch.process-next` receives the same Facts used for evaluation and resolves the concrete target itself, then the host refreshes Facts and evaluates again. ## Resources Long material lives in Resources declared on the node that needs it. Three independent protocols can appear in the same Route: | Protocol | What it is | How it is delivered | | --- | --- | --- | | File (`agent-graph.resource-location.file.v1`) | Static procedures, diagnostics, templates, schemas and Skills; Markdown carries `id`, `kind` and `media-type` in frontmatter, other formats use a small descriptor | Absolute installed path, media type and content digest | | Graph action (`agent-graph.resource.graph-action.v1`) | A dynamic context view whose materializer is a read-only command or script Action | An opaque materialization request bound to the Route revision; runs only when the host calls `resource materialize` | | Host action (`agent-graph.resource.host-action.v1`) | A resource the integrating host produces through a stable handler with versioned input and output schemas | Handler, input schema and canonical input value; Agent Graph computes the input digest and validates the returned envelope | Normative instructions belong in procedures; generated or workspace-derived evidence does not. Routes return locations and digests, never document bodies, so routine output never becomes an accidental prompt. ## Materializing context views Evaluation and route resolution never run a materializer. `resource materialize` runs it explicitly with the selecting Route's revision, writes stdout to a content-addressed file in the host-chosen cache (`.json`, `.md`, `.txt` or `.bin` by media type) plus a receipt recording the revision and digest, and returns a location the host can check for staleness. The process gets `AGENT_GRAPH_PROVIDER_ROOT`, `AGENT_GRAPH_WORKSPACE`, `AGENT_GRAPH_REVISION` and `AGENT_GRAPH_INPUT` (JSON), plus only a minimal inherited environment — `PATH`, temporary-directory, locale and time-zone variables and their Windows equivalents. SDK hosts can add variables explicitly. Defaults are a 30-second timeout, 10 MiB of stdout and 1 MiB of stderr; exceeding one terminates the process without writing a receipt. `effect: read` is a declared contract, not a sandbox, so hosts isolate untrusted Provider code themselves. For a host-action resource, materialization returns `materializer-host-required`: the host invokes the handler, echoes the computed input digest, returns exactly one inline value or managed resource reference, validates the content against the Provider's output schema and persists it before exposing it to the Agent. ## Read receipts To avoid re-reading unchanged material, a host may attach an `agent-graph.resource-read-receipts.v1` set for the current conversation when resolving a Route. Each Route resource then gets a `readState`: - `current` — a receipt matches: the same ID and exact digest for a static file, or the same ID and the selecting Route revision for a dynamic view; - `read-required` — anything else, including no receipt or a stale one. A receipt may be issued only after the Agent actually read that content and while it is still in the conversation. Receipts are scoped to one Provider, are never stored in Runs or checkpoints, and are not Facts, Outcomes, authority or proof that an Action finished — they only suppress redundant reads. ## A thin host ```ts import { evaluateGraph, loadProvider, resolveRoute, resolveSkillBinding } from "@c4a/agent-graph"; const binding = await resolveSkillBinding(skillPath, { registry }); const provider = await loadProvider(binding.manifestPath); const { evaluation } = evaluateGraph(provider, binding.graph, binding.entry, currentState); if (evaluation.primaryRoute) { const route = await resolveRoute(provider, binding.graph, binding.entry, evaluation.primaryRoute.routeId, currentState, evaluation.revision); // Present the route's resources and action to the Agent; do not execute implicitly. } ``` Use the SDK for an in-process Node.js host, or the JSON CLI when the host runs in another runtime or needs a process boundary; both read the same files. Only explicitly named authoring, Run, build and materialization functions write anything. The full export list is in [CLI and SDK](). --- ## Sources - [agent-graph/docs/en/adoption-paths.md L52–L66 · 9e8b98a]() - [agent-graph/docs/en/skills-and-providers.md L1–L8 · 9e8b98a]() - [agent-graph/docs/en/skills-and-providers.md L1–L28 · 9e8b98a]() - [agent-graph/README.md L116–L148 · 9e8b98a]() - [agent-graph/docs/en/specification.md L30–L41 · 9e8b98a]() - [agent-graph/docs/en/skills-and-providers.md L29–L72 · 9e8b98a]() - [agent-graph/docs/en/skills-and-providers.md L107–L118 · 9e8b98a]() - [agent-graph/docs/en/skills-and-providers.md L73–L105 · 9e8b98a]() - [agent-graph/docs/en/specification.md L203–L270 · 9e8b98a]() - [agent-graph/docs/en/authoring.md L124–L154 · 9e8b98a]() - [agent-graph/src/materialize.ts L40–L100 · 9e8b98a]() - [agent-graph/src/materialize.ts L186–L237 · 9e8b98a]() - [agent-graph/docs/en/specification.md L234–L252 · 9e8b98a]() - [agent-graph/docs/en/specification.md L278–L309 · 9e8b98a]() - [agent-graph/src/router.ts L217–L236 · 9e8b98a]() - [agent-graph/docs/en/skills-and-providers.md L119–L159 · 9e8b98a]() - [agent-graph/docs/en/adoption-paths.md L78–L82 · 9e8b98a]() --- ## Agent Graph in Context # Agent Graph in Context Context is the largest public Agent Graph adopter, and it shows when a graph is worth having. Its lifecycle is long and stateful: sources must be scoped and captured, one Indexer lifecycle turns every authorized input into a current Candidate batch, human Gates may pause the run, and approved knowledge must be closed, verified, translated, versioned and built. A plain Skill would need to carry all of that in its prompt and still could not prove what had already happened. Context is not evidence that every Skill needs a graph. It is evidence that a graph helps when a Skill fronts a workflow with external Facts, several Gates, repeated batches and a real recovery requirement. Agent Graph does not extract code, interpret documents or approve knowledge; Context remains the host. ## Who does what ```mermaid flowchart LR skill["/c4a:context Skill"] --> status["context status"] status -->|"Facts"| ag["Agent Graph evaluation"] ag -->|"Route"| current["workflow.current"] current --> agent["Agent reads resources and runs commands"] agent -->|"guarded writes"| host["Context host"] host -->|"new Facts"| status ``` | Layer | Responsibility in Context | | --- | --- | | Skill | Discovery and the small Route-consumption contract | | Context host | Observe files and external systems, execute commands, enforce authority, record evidence | | Provider | Bind the `workspace` Graph, entrypoints, Actions, resources and the reason-code catalog | | Graph | Describe legal lifecycle states, dependencies, Gates, loops and terminal outcomes | | Route | Expose one current action, its required resources and its completion contract | | Facts and Outcomes | Prove what has actually happened; conversation claims are not completion evidence | `context status` is the observation boundary: it inspects the workspace, supplies Facts to Agent Graph and returns `workflow.current` with the selected Route, reason code, command plan, Gate and only the resources needed now. The Context-side view of this loop is in [Workflow Execution](). ## One thin public entry Knowledge production has one public Agent entry, `/c4a:context`. Its first `context entry` call resolves initialization, workspace relocation or ordinary continuation, then hands control to `workflow.current`. The plugin's other public Skills — `context-plan` for planning, `context-inspect-search` for querying and `context-repo-content` for same-repository content — do not drive the lifecycle themselves; they hand plans and accepted knowledge suggestions back to this entry. The entry's body describes only how to start and how to consume a Route; phase procedures, schemas, source views, review contracts and package guidance live in independently addressable workflow resources. That is the [Skills and Providers]() pattern at scale: one small, stable shell in front of a large body of instructions that the Graph selects piece by piece. The detail has not been summarized away — it is separated, selected and made verifiable instead of being loaded on every turn. ## The published workflow The whole integration is public in the Context repository under `packages/context-cli/context-workflow/`: | Path | Contents | | --- | --- | | `provider.yaml` | Provider `c4a/context`, binding the `workspace` and `indexer` Graphs, Actions, Resources and the entrypoint | | `graphs/workspace.yaml` | The static top-level lifecycle, from task start through capture, Indexer lifecycle, review, close, package output, translation, version and build | | `graphs/indexer.yaml` | The single Indexer lifecycle: requirement confirmation, Provider selection, authorized worksets, partitioned authoring, reconciliation, layout and Candidate compilation | | `actions/` | Executable contracts: runner, host command or handler, effect, authority boundary and expected Outcome | | `resources/` | Procedures, dialogue files for human decisions, live workspace views, semantic references, diagnostics and manuals | | `codes.yaml` | Stable meanings for Route and diagnostic codes | | `tests/` | Route-selection tests from Facts, run without an Agent or model | The top-level `run-indexer-lifecycle` Action is an Agent Action that hands indexing to the Indexer Graph and is satisfied only when `indexer.lifecycle_current` is true. Repeated sources and partitions do not need repeated graph definitions: the workspace Graph has stable states such as "a capture target remains", and runtime Facts identify the current workset. ## Managed mode is a delegated Gate Context calls its unattended experience *managed mode*. That is a host concept, not an Agent Graph field: the host maps it to session-scoped authorities and each Gate's `delegated` policy. The final knowledge review shows the shape: ```yaml - id: review-current-batch kind: gate reasonCode: route.review.decision-required inspectionAction: actions/inspect-review.yaml resolutionAction: actions/apply-confirmed-review.yaml delegated: inspection: skip resolutionAction: actions/apply-managed-review.yaml resources: required: - resources/views/review-current.yaml gate: id: knowledge-review authority: context.knowledge-review delegatable: true satisfiedBy: - path: gates.knowledge_review_resolved equals: true ``` Without the authority the Route stops for a person. With `context.knowledge-review` granted for the session, the same Gate resolves through the host handler `context.review.approve-current`. A route test, `tests/managed-review.yaml`, pins exactly that: with the authority present it expects `primaryNode: review-current-batch`, `gateResolution: session-authority` and that resolution handler. Session authority never becomes permanent project configuration, and Routes that need semantic judgment or an unsafe repair still stop. ## Idempotent continuation Invoking the Skill again does not replay every instruction or repeat every write. With the same Provider bundle, Facts and Outcomes, Agent Graph selects the same Route, and unchanged resource receipts keep the same read state. Context binds mutating commands to the selected workflow revision and checks their external evidence: work already satisfied by workspace Facts is skipped, and a stale command is rejected instead of being applied to newer state. The boundary is explicit. Agent Graph makes evaluation repeatable and exposes completion contracts; the Context host makes each filesystem effect atomic, guarded or a proven no-op. Agent Graph does not make an arbitrary script idempotent by itself — see [Runs and Recovery](). ## Recording and replay With Context debug mode on, the host records CLI invocation boundaries and Agent Graph evaluations. A replay then shows which Route was selected at each Fact change, where a multi-source loop advanced and how many iterations completed, when an authority or review Gate paused progress, which reason code justified each transition and how the final package was reached. The [interactive replay](https://context4ai.github.io/context/case-studies/workflow/?lang=en) is normalized from a sanitized Context recording; its **Workspace graph** control draws the static contract, and each step links its Action and Resources back to the workflow files. Route traces like these expose wasteful loops, repeated resource reads, incomplete recovery paths and misleading status priorities, and those observations become new route tests and graph changes — the improvement loop described in [Why Graph Engineering](). ## Built with Context This documentation site is itself a Context knowledge workspace, produced through the same `/c4a:context` entry and workflow. - **Workspace.** The Portal repository root is the workspace: `package.json` declares it, `src/index.ts` registers sources and outputs, `src/indexers.yaml` states each reader group's needs, and `src/knowledge-map.yaml` holds the navigation. - **Sources.** Three community repositories, each pinned to one commit (Context first at `v0.7.60` and updated to `v0.7.61` before the final stage, Agent Graph at `v0.3.0`, and Source Graph at a commit without a release number), plus five sanitized notes on usage experience, measured compression, retrieval evaluation, the knowledge service Agent design and frequently asked questions. A maintainer reviewed each note before registering it. - **Plan.** Because the sources span three repositories, production started with a `context-plan` investigation and a PLAN report that split the site into six stages — getting started and Context internals; source, production, review, update and query guides; outputs, Indexers, the knowledge service, workspace maintenance, practices and the Context reference; Source Graph; Agent Graph; and the More menu with homepage links — plus one revision round that added seven pages and unified naming and links. - **Each stage.** `task prepare` and `task resume` opened a new production stage; the Agent wrote articles in batches by reader question, every section carrying references to source lines or notes, and submissions were checked for format, links and references. - **Review.** Each stage produced an HTML review report that was checked for unplaced navigation and diagrams that fail to render before approval. The maintainer reviewed the first two stages, then delegated review to the Agent, which checked each article against its sources and used `revise` to correct approved pages when it found a factual deviation. - **Translation and versions.** Approved articles and navigation titles were translated into Simplified Chinese by several parallel sub-Agents, with a script confirming that section markers, code blocks, links and inline code were unchanged. Each stage recorded a workspace version and Changelog entry, counting up from 0.1.0, before building the site and package. Three observations from the run: - One public entry carried every stage. After each interruption or new session, the Agent resumed from the Route that `context status` returned, not from conversation memory. - Several drafts disagreed with the source code — for example which error code a timeout returns, or what anonymous rate limiting counts. Section references made those checks possible one section at a time, and each was fixed before submission. - Revising an approved page changed only the affected sections instead of reproducing the whole article. - Updating the Context source from `v0.7.60` to `v0.7.61` did not restart production: `context verify` listed the pages whose cited source regions had changed or moved, `context update` offered them as candidates, and the Agent decided page by page whether a revision was needed. The More menu pages were written as new topics of the same update. --- ## Sources - [context/docs/en/case-studies/agent-graph-workflow.md L1–L9 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L90–L94 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L44–L55 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L34–L35 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L11–L21 · 3b0ce0a]() - [context/ARCHITECTURE.md L358–L380 · 3b0ce0a]() - [context/plugins/context/skills/context/SKILL.md L1–L30 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L23–L33 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/provider.yaml L1–L13 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/graphs/workspace.yaml L165–L180 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/graphs/workspace.yaml L182–L212 · 3b0ce0a]() - [context/packages/context-cli/context-workflow/tests/managed-review.yaml L1–L41 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L70–L74 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L38–L42 · 3b0ce0a]() - [context/docs/en/case-studies/agent-graph-workflow.md L76–L88 · 3b0ce0a]() - note:20261012/portal-production.md · portal-production.md L1–L25 --- ## CLI Commands # CLI Commands The `context` CLI holds the workflow state of a Context knowledge workspace. You rarely type these commands yourself: the Agent runs them, and most of them are returned by the current **Route** — the single next step that `context status` or a previous command hands back, often with an exact `--revision` to pass. Commands that drive the workflow print JSON with `--format json`, which is what the Agent reads. Run `context --help` for the full option list of any command. For the Skills that call these commands, see [Skills](); for a short tour, see [Commands and Skills](). ## Setup | Command | What it does | Key options | | --- | --- | --- | | `context entry [dir]` | Resolves the single Agent entry: plans initialization for a new directory or evaluates the workflow of an existing workspace | `--name`, `--language en\|zh-CN`, `--managed`, `--authority` | | `context init [dir]` | Initializes a Context knowledge workspace in the directory | `--name`, `--language`, `--allow-nonempty` (after explicit confirmation) | | `context plugin path` | Prints the bundled plugin root used by install | | | `context plugin status` | Shows the bundled plugin root and which Agents have the plugin globally | | | `context plugin install` | Installs the Agent plugin globally, or copies standalone Skills into a repository | `--agent claude\|codex\|cursor\|all`, `--local ` (also `auto-detect`, `standalone`), `--dry-run` | | `context evidence install [dir]` | Installs or safely upgrades the bundled remote code evidence plugin, without starting production | | | `context clean-cache` | Removes orphaned Claude Code plugin caches | `--dry-run` | ## Workflow | Command | What it does | Key options | | --- | --- | --- | | `context status` | Prints the workspace overview and the next Route | `--format table\|json`, `--view summary\|full`, `--managed`, `--authority` | | `context run [phase]` | Inspects or runs a declared phase; with no phase, advances deterministic Routes | `--list`, `--dry-run`, `--until blocked-or-complete`, `--max-steps`, `--deliver`, `--resume-writing` | | `context resource acknowledge-current` | Records that every resource required by the current Route was read | | | `context resource materialize ` | Writes one revision-bound Context view to a local file | | | `context action prepare-current` | Prepares or retries the current production batch directories without resubmitting accepted articles | `--revision`, `--input` | | `context action complete-current` | Submits the semantic output — a report decision, drafts, a Gate answer — for the exact current revision | `--revision`, `--input`, `--managed`, `--multi-agent`, `--preview` | ## Tasks and maintenance | Command | What it does | | --- | --- | | `context task prepare` | Previews or discards current task state; keeps knowledge, sources and other temporary files | | `context task resume` | Explicitly reopens cleared production from registered requirements and retained knowledge | | `context task adjust` | Adjusts current source and module inputs, or the knowledge map, without disturbing unrelated work (`--input`, `--schema`, `--inspect`) | | `context task maintain` | Registers a scoped page revision, regeneration or approved-output rebuild | | `context task advance-maintenance` | Executes the current maintenance transition | | `context task maintenance-status` | Shows maintenance requests and the current cancellation revision | | `context task cancel-maintenance ` | Cancels a pending maintenance request without discarding an active draft | | `context task retire` | Previews or applies retirement of an approved article and cleanup of references to it | | `context task recover` | Inspects or previews scoped recovery outside the normal Route | | `context task rollback` | Previews exact user-selected reversions and discarded drafts; never resets the repository | | `context task finish-rollback` | Finishes a rollback after close and all builds succeed | | `context update` | Checks acquired source changes against approved knowledge in confirmed scopes (`--input`) | | `context revise ` | Repairs one draft or approved page through the Indexer lifecycle (`--instruction`, `--regenerate`, `--timing after-batch\|priority`, `--move-to`) | ## Review | Command | What it does | Key options | | --- | --- | --- | | `context review html [collection]` | Renders a self-contained local review report | `--all`, `--out`, `--open` | | `context review list [collection]` | Lists draft candidates in the terminal | | | `context review apply ` | Applies scoped JSON or JSONL decisions and revision instructions | | | `context review approve-all [collection]` | Approves the whole current review scope | `--all`, `--confirmed` (your confirmation), `--managed` | | `context review approve ` / `reject ` | Approves or rejects one draft candidate | | | `context review deprecate ` | Marks an approved page deprecated without deleting it | | ## Delivery | Command | What it does | Key options | | --- | --- | --- | | `context close` | Closes approved knowledge: derives `structure.yaml` and runs final verification | `--format` | | `context verify` | Validates the workspace | `--compact`, `--view diagnostics`, `--page-size`, `--page-token` | | `context build` | Builds the declared packages and sites | `--verbose` | | `context translate status` | Reports translation freshness per locale | | | `context translate prepare` | Writes the pending translation task | | | `context translate submit` | Validates and saves translated articles and navigation titles | `--input` | | `context translate skip` | Publishes pending translations in the primary language for now | | ## Versions and packages | Command | What it does | Key options | | --- | --- | --- | | `context version inspect` | Shows formal changes since the current version tag or a given ref | `--base` | | `context version record` | Records the workspace SemVer and changelog entry | `--input` | | `context package site-url ` | Records a deployed site root in the site maps, without network checks | | | `context package template accept [package]` | Explicitly accepts an unchanged generated starter template | | ## Sources and Indexers | Command | What it does | | --- | --- | | `context source add repo\|file\|lark [date]` | Registers a repository, local file or Lark document module under a `YYYYMMDD` batch | | `context source add batch [date]` | Registers several modules under one batch | | `context source import` | Imports managed Markdown (notes, session summaries) or prefetched Lark content, singly or in a batch | | `context source discover` / `fetch` | Discovers a source inventory, or fetches a portable snapshot, without registering anything | | `context source batch-status ` | Reads a saved registration checkpoint | | `context source list` / `get ` | Lists registry entries, or shows one | | `context source rename ` | Renames a note or session summary and updates its references | | `context source remove ` | Previews or removes an unreferenced source and its snapshot | | `context source inspect [name]` | Shows repository module boundaries without extraction | | `context source ensure [name]` | Checks repository checkouts without cloning, checking out or resetting | | `context source recovery-plan [name]` | Plans recovery of missing repository checkouts without changing files | | `context source restore` | Restores repository checkouts from explicit local or clone decisions | | `context indexer catalog` | Lists bundled Skill names, descriptions and entries | | `context indexer report-benchmark` | Builds a forward-test report from an independently loaded oracle | ## Diagnostics | Command | What it does | | --- | --- | | `context debug enable` / `disable` | Turns workspace-local tracing on or off; disabling keeps existing traces | | `context debug status` | Shows debug configuration, counts and trace paths | | `context debug export` | Builds a replay projection from the event stream | Tracing can also be enabled at creation with `context init --debug`. --- ## Sources - [context/packages/context-cli/src/registerProjectLifecycleCommands.ts L29–L62 · 3b0ce0a]() - [context/packages/context-cli/src/registerProjectLifecycleCommands.ts L101–L150 · 3b0ce0a]() - [context/packages/context-cli/src/registerProjectLifecycleCommands.ts L63–L100 · 3b0ce0a]() - [context/packages/context-cli/src/registerPluginCommands.ts L18–L50 · 3b0ce0a]() - [context/packages/context-cli/src/commands/evidenceCommands.ts L6–L12 · 3b0ce0a]() - [context/packages/context-cli/src/commands/runProject.ts L202–L230 · 3b0ce0a]() - [context/packages/context-cli/src/commands/resourceCommands.ts L44–L95 · 3b0ce0a]() - [context/packages/context-cli/src/commands/actionCommands.ts L27–L80 · 3b0ce0a]() - [context/packages/context-cli/src/commands/documentRevisionCommands.ts L20–L188 · 3b0ce0a]() - [context/packages/context-cli/src/commands/documentRevisionCommands.ts L189–L230 · 3b0ce0a]() - [context/packages/context-cli/src/cli.ts L217–L398 · 3b0ce0a]() - [context/packages/context-cli/src/registerProjectLifecycleCommands.ts L151–L220 · 3b0ce0a]() - [context/packages/context-cli/src/commands/translateCommands.ts L28–L84 · 3b0ce0a]() - [context/packages/context-cli/src/commands/versionCommands.ts L11–L25 · 3b0ce0a]() - [context/packages/context-cli/src/registerPackageCommands.ts L11–L40 · 3b0ce0a]() - [context/packages/context-cli/src/project/sourceCommands.ts L260–L610 · 3b0ce0a]() - [context/packages/context-cli/src/project/indexerCommands.ts L29–L45 · 3b0ce0a]() - [context/packages/context-cli/src/project/sourceDiscoveryCommands.ts L1–L30 · 3b0ce0a]() - [context/packages/context-cli/src/commands/debugCommands.ts L44–L80 · 3b0ce0a]() --- ## Project API # Project API A Context knowledge workspace has two durable declarations with separate jobs: | File | Declares | | --- | --- | | `src/index.ts` | Source references, document capture, custom non-knowledge orchestration, and package outputs — through the `@c4a/context` SDK | | `src/indexers.yaml` | Long-term reader requirements, authorized target and supporting sources, and confirmed exclusions | Never describe the same knowledge transformation in both. The Agent edits these declarations when the current Route asks for a configuration change; you do not need to write code yourself. ## `defineProject` ```ts import { defineProject } from "@c4a/context"; export default defineProject({ sources: [], phases: [], packages: [], }); ``` The definition is declarative: loading it must not change knowledge or runtime state. ## Sources ```ts const repo = source("20260901", "component-lib"); const docs = source("20260901/product-docs", { type: "file" }); const handbook = source("20260901/handbook", { type: "lark" }); const note = source("20260908/decision-context.md", { type: "note" }); const session = source("20260908/design-discussion.md", { type: "sessions" }); const everyRepo = allSources("repo"); // spread inside sources: [...everyRepo] ``` | Type | Resolves against | Registered with | | --- | --- | --- | | `repo` (default), `file`, `lark` | `sources//index.yaml`; the name includes the registration date and module | `context source add …` | | `note`, `sessions` | Saved Markdown under `sources/note/YYYYMMDD/` or `sources/sessions/YYYYMMDD/`; no separate registry or capture phase | `context source import` | Saving a source does not select it — include its reference in `sources`. The source list enables acquisition and initial selection; the requirements and each Indexer's target and read scopes decide what it owns and may read. ## Capture phases ```ts captureFile({ source: docs }); captureFile({ source: docs, processor: mdxJsonDocs() }); captureLark({ source: handbook }); ``` Capture only creates a deterministic, readable snapshot; classification and writing follow the selected Indexer. Adding `--configure` to `context source add repo|file|lark|batch` generates the source references and default capture phases in `src/index.ts` for you. It keeps existing settings, is idempotent, and leaves custom or dynamic entries untouched with a `configuration.status: manual` hint. For many documents with the same settings, map the registry instead of repeating declarations: ```ts const registry = await loadSourcesRegistry({ rootDir: workspaceRoot }); const documents = registry.larks.map(entry => source(entry.name, { type: "lark" })); export default defineProject({ sources: documents, phases: documents.map(document => captureLark({ source: document })), packages: [], }); ``` File documents use `registry.files` with `captureFile`. Filter entries for a subset. `allSources("lark")` selects a whole collection and cannot be mapped into per-document phases. Capture boundaries do not dictate article boundaries. ## `customPhase` ```ts customPhase("project:refresh-catalog", async (ctx) => { await ctx.ensureSources(); }); ``` For project orchestration that neither publishes knowledge nor bypasses the Indexer lifecycle. Declare stable reads and writes when the phase has them. ## Packages ```ts kbPackage({ name: "component-kb", template: "src/package-templates/kb", select: { collections: ["codeindex", "architecture"] }, site: { title: "Component knowledge", base: "/" }, }); llmsPackage({ name: "component-context", template: "src/package-templates/llms", select: { collections: ["codeindex"] }, }); ``` | Field | Required | Meaning | | --- | --- | --- | | `name` | Yes | Lowercase, path-safe; output goes to `dist//` | | `template` | Yes | Template directory, or `{ path, vars }` | | `select` | No | `collections`, `okfRoots`, `include`, `exclude`; omit for all approved knowledge | | `navigation` | No | Directory-index policy; default `{ foldDirectoryIndexes: true, maxInlineEntries: 50 }` | | `assets` | No | `{ delivery: "bundle" }` (default), `"git-raw"` with `urlPrefix`, or `"omit"`; optional `optimize` | | `site` | No (`kbPackage` only) | Adds a documentation site at `dist/-site/`, where `` is the name without one trailing `-kb` | Packages read approved `knowledge/` only; `dist/` is generated. Details are in [Package Templates](). ## Site options | Option | Meaning | | --- | --- | | `title`, `description` | Site title and description | | `lang` | Primary language, default `en-US` | | `base` | Deployment path such as `/` or `/docs/` | | `titleLink` | Target of the top-bar title; defaults to the site home | | `home` | `title`, `slogan`, `description`, hero `actions` (`text`, `link`, `theme`), and `resources` (each needs `href`, `command` or both) | | `locales` | Additional reader languages keyed by BCP 47 tag, each with optional `label`, `title`, `description`, `home`; must differ from `lang` | | `nav` | Top links after the knowledge sections: `text`, `link`, optional per-locale `locales` text | | `more` | Items placed in the More menu before the built-in LLM Docs and Changelog entries: `text` with exactly one of `link` or `target.artifact_ref` (an approved article shown only there) | | `socialLinks` | `icon` (`github`, `discord`, `x`, `youtube`, `slack`, `linkedin`, `mastodon`, `npm`), an https `link`, optional `ariaLabel` | | `localePreferenceKey` | Shared storage key so sites on one origin keep the same reader language | | `theme` | `light` and `dark` colors: `brand`, `accent`, `background`, `surface`, `text`, `mutedText`, `border` as hex values | | `extensions` | Trusted presentation code: `root` (default `src/site`), `slots` (`brand`, `banner`, `knowledge`, `resources`, `footer`, `floating`; `false` hides one) and custom Markdown `pages` | Links accept https or `mailto:` URLs, root-relative paths or page anchors. Custom pages are placed in the knowledge map with `target.artifact_ref: "site:"`. See [Documentation Sites]() and [Page and Theme Customization](). ## Requirements and Indexer Skills When `src/indexers.yaml` is missing, the configuration Route supplies its schema. Write `requirements` only — no `protocol`, `indexers`, Provider selections or profiles. Which installed Indexer Skills to use, and their optional configuration, belongs to `indexer_usage` in the temporary production plan, not to this durable file. The Agent writes drafts and references under the returned temporary directory; the CLI accepts them and owns candidates, review and formal output. ## Durable and runtime state Source registries and snapshots, saved notes and summaries, project declarations, package templates and approved knowledge are durable inputs, versioned in Git when Git operations are authorized. `.tmp/context-runtime/` holds unfinished execution state and stays out of Git. `knowledge/structure.yaml` keeps shared page and source metadata and compact `processed_scopes`; a partial update or failed build does not advance a whole range's processed version. Use the CLI to adjust or roll back work rather than editing these baselines. The workspace `package.json` also accepts `context.convertVisuals` (default `true`): a capable Agent may convert source diagrams and tables into faithful text structures, keeping the original image when it cannot preserve the meaning. --- ## Sources - [context/packages/context/docs/reference/project-api.md L1–L10 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L400–L402 · 3b0ce0a]() - [context/packages/context/docs/reference/project-api.md L12–L23 · 3b0ce0a]() - [context/packages/context/docs/reference/project-api.md L25–L56 · 3b0ce0a]() - [context/packages/context/docs/reference/project-api.md L58–L83 · 3b0ce0a]() - [context/packages/context/docs/reference/project-api.md L85–L135 · 3b0ce0a]() - [context/packages/context/docs/reference/project-api.md L137–L146 · 3b0ce0a]() - [context/packages/context/docs/reference/project-api.md L148–L196 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L48–L57 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L109–L116 · 3b0ce0a]() - [context/packages/context/src/packageSite.ts L1–L106 · 3b0ce0a]() - [context/packages/context-cli/src/project/packageSiteTheme.ts L310–L318 · 3b0ce0a]() - [context/packages/context/docs/reference/project-api.md L183–L202 · 3b0ce0a]() - [context/packages/context/docs/reference/project-api.md L204–L215 · 3b0ce0a]() - [context/packages/context/docs/reference/project-api.md L217–L229 · 3b0ce0a]() - [context/packages/context/docs/reference/project-api.md L231–L235 · 3b0ce0a]() --- ## Skills # Skills The Context Agent plugin contains nine Skills. Four are **entries** you invoke, one is an **authoring assistant** you start in plain language, and four are **Indexers** the workflow selects. All of them leave workspace state and lifecycle decisions to the `context` CLI. For a short tour aimed at first-time users, see [Commands and Skills](). ## Entries | Skill | Activates when | Does | Hands off to | | --- | --- | --- | --- | | `context` | You invoke Context explicitly, ask to reorganize an existing knowledge map or site navigation, or continue an active Context workflow to build, inspect, update, recover or package knowledge | Creates or continues a Context knowledge workspace and follows the CLI's current Route through production, review, update and build | The CLI; Indexers selected for each stage | | `context-plan` | You ask for project planning or continue a `PLAN-*.md`, or an authorized Context task involves more than 30 source documents or substantive investigation of at least two repositories | Researches in temporary storage and writes a root `PLAN-YYYYMMDD-topic.md` for review, then runs the project one stage at a time | `context`, which performs each stage | | `context-inspect-search` | You ask a knowledge question, or a host or Bot configuration routes questions here | Answers from knowledge packages or approved knowledge and traces answers to their sources; read-only, no workspace required | `context` for accepted improvement suggestions | | `context-repo-content` | You ask to create, edit or register documentation and authored Skills in the same repository | Maintains `repo-content.yaml` and its symlink view, keeping one original in its project directory; never starts production, builds, publishes or commits | — | None of them starts on its own for ordinary planning, design or coding. ## Authoring assistant | Skill | Activates when | Does | | --- | --- | --- | | `context-indexer-create` | You explicitly ask to create a new Indexer Skill for code, documents, notes or session summaries | Writes a reusable Skill into the directory you choose; does not initialize a workspace or start production. It has no menu command — ask in plain language. See [Creating an Indexer](). | ## Indexers | Skill | Interprets | Selected | | --- | --- | --- | | `context-code-indexer` | Code skeletons of an authorized module, to write source-grounded articles | For the current planning or writing task — not as a standalone repository audit | | `context-markdown-indexer` | Outlines of captured documents | For the current authorized planning or writing task — not as an import workflow | | `context-note-indexer` | Saved notes, excerpts and observations | When the current authorized task selects it — not for importing sources or scanning conversation history | | `context-sessions-indexer` | Saved conversation summaries | When the current authorized task selects it — same limits as notes | Installing an Indexer makes it discoverable, not enabled for every workspace: the Agent chooses Indexers for the current sources and requirements, and the CLI supplies task directories and checks every source reference. Indexers are installed without a plugin namespace, so their names are the same in every host. See [Community Indexers](). ## Host spelling | Host | Entries | | --- | --- | | Claude Code | `/c4a:context`, `/c4a:context-plan`, `/c4a:context-inspect-search`, `/c4a:context-repo-content` | | Cursor | `/c4a-context`, `/c4a-context-plan`, `/c4a-context-inspect-search`, `/c4a-context-repo-content` | | Codex | Skills by name: `context`, `context-plan`, `context-inspect-search`, `context-repo-content` | A local install into one repository with `context plugin install --local` has no plugin namespace; the host discovers the entries in its own directory. Restart the Agent session after installing or updating the plugin. --- ## Sources - [context/plugins/context/README.md L1–L27 · 3b0ce0a]() - [context/plugins/context/skills/context/SKILL.md L1–L4 · 3b0ce0a]() - [context/plugins/context/skills/context-plan/SKILL.md L1–L21 · 3b0ce0a]() - [context/plugins/context/skills/context-repo-content/SKILL.md L1–L9 · 3b0ce0a]() - [context/plugins/context/skills/context-indexer-create/SKILL.md L1–L15 · 3b0ce0a]() - [context/plugins/context/skills/context-code-indexer/SKILL.md L1–L4 · 3b0ce0a]() - [context/plugins/context/skills/context-markdown-indexer/SKILL.md L1–L4 · 3b0ce0a]() - [context/plugins/context/skills/context-note-indexer/SKILL.md L1–L27 · 3b0ce0a]() - [context/plugins/context/README.md L28–L33 · 3b0ce0a]() - [context/plugins/context/README.md L72–L81 · 3b0ce0a]() - [context/packages/context-cli/README.md L43–L53 · 3b0ce0a]() --- ## Package Templates # Package Templates Packages project approved knowledge into `dist//`. This page is the API and template reference; for choosing outputs, see [Knowledge Packages](), and for editing templates, see [Custom Output Templates](). ```ts import { kbPackage, llmsPackage } from "@c4a/context"; kbPackage({ name: "component-lib-kb", template: { path: "src/package-templates/kb", vars: { displayName: "Component Library KB" } }, select: { collections: ["architecture", "sop"], okfRoots: ["wikis", "guides"], include: ["architecture/component-lib/**", "sop/component-lib/**"], exclude: ["**/internal/**"], }, navigation: { foldDirectoryIndexes: true, maxInlineEntries: 50 }, assets: { delivery: "bundle" }, }); llmsPackage({ name: "component-lib-llms", template: "src/package-templates/llms", select: { include: ["codeindex/component-lib/**"] }, }); ``` ## Fields | Field | Required | Meaning | | --- | --- | --- | | `name` | Yes | Lowercase, path-safe package name; output goes to `dist//` | | `template` | Yes | Template directory, or `{ path, vars }` | | `select` | No | Approved knowledge selector; omit to include everything approved | | `navigation` | No | Directory-index policy; default `{ foldDirectoryIndexes: true, maxInlineEntries: 50 }` | | `assets` | No | Resource delivery: bundled (default), Git raw links, or omitted | | `distribution` | No | Legacy input from older workspaces; no longer changes paths — do not add it | `template` is always required; `kbPackage({ name })` alone is rejected. A `kbPackage` can also take `site` for a documentation site — see [Project API](). ## Assets | `assets` | Behavior | | --- | --- | | `{ delivery: "bundle" }` (default) | Selected resources are written under `others/assets/`. Images are compressed when needed to stay within 1 MiB each and 40 MiB per package; source snapshots and `knowledge/assets/` are never changed | | `{ delivery: "git-raw", urlPrefix }` | Links point at raw files in Git. Without `urlPrefix`, the workspace must be in Git and GitHub remotes are derived and pinned to the current commit; other hosts need an explicit HTTPS prefix, where `{commit}` is replaced only inside Git | | `{ delivery: "omit" }` | Leaves unresolved links and reports them | The resolved commit and raw URL count toward package freshness. Context does not check that resources are pushed or remotely readable. An explicit `assets.optimize` (for example `mode: "webp"` with `quality`, optional `maxDimension`) overrides the automatic image policy; if it cannot meet the image budgets, the build stops before replacing the previous package. ## Layout Package roots are flat; the package name is not repeated inside: ```text skills/knowledge-query/SKILL.md wikis/index.md guides/... rules/... feats/... ``` A knowledge package template must contain at least one `SKILL.md` and `wikis/index.md`. Each Skill lives at `skills//SKILL.md` with a matching frontmatter `name`; Skill names are author-maintained and never derived from the package name. Use `{{wikisRoot}}`, `{{guidesRoot}}`, `{{rulesRoot}}`, `{{featsRoot}}` and `{{skillName}}` in templates. Installed examples are in `node_modules/@c4a/context/templates/package-templates/{kb,llms}/`. The default template ships `skills/knowledge-query/SKILL.md` (a reusable query Skill), its `scripts/search.mjs` (a dependency-free BM25 fallback), and `wikis/index.md`. ## Directory indexes - Every selected root — `wikis/`, `guides/`, `rules/`, `feats/` — gets its own `index.md`; `wikis/index.md` is rendered from the template and is the default entry. - With `foldDirectoryIndexes: true`, indexes are planned bottom-up: a directory gets its own `index.md` only when it would expose more than `maxInlineEntries` entries (default 50) to its parent. Folded pages are listed in the nearest generated ancestor, grouped by relative path. The count is of navigation entries, not lines or headings. - `foldDirectoryIndexes: false` generates an index for every directory. - Generated indexes carry OKF frontmatter (`type: Knowledge Directory`, `title`, `description`, `tags`, `timestamp`, `resource`, `package`, `package_kind`, `knowledge_count`) and list child indexes before pages. - Links in root and generated indexes must resolve inside `dist//`; broken ones are reported as `package/index-link-invalid`. ## Article metadata | Owned by | Holds | | --- | --- | | Approved Markdown | `title`, `type`, `description`, ISO UTC `timestamp`; optional `resource` and `tags` | | `knowledge/structure.yaml` | Stable `article_id`, `path`, `collection`, `visibility`, and each section's references (at most three per section: `source_ref`, `locator { path, start_line, end_line }`, `content_digest`) | Section markers in Markdown contain only their ID: `` … ``. Package pages keep reader metadata and receive a generated Sources section from the references; repository links include file and line ranges. ## Build behavior `context build`: 1. Selects approved Markdown from `knowledge/`. 2. Renders every file under `template.path`. 3. Projects the selected articles into consumer pages. 4. For `llmsPackage`, appends the selected knowledge to `llms.txt` unless the template already uses `{{knowledge}}` or `{{approvedKnowledge}}`. 5. Writes `context-build-inventory.json`, recording each selected file with `selected_by` reasons and its production metadata. 6. Writes everything under `dist//`. Build packages the current closed state; when status reports `route.close.projection-stale`, run the returned close command first. Rendered template paths must be safe and unique and must not collide with copied knowledge — rename the template file or use `select.exclude`. Template prose about coverage, scope or limits must cite approved knowledge, the inventory or rendered structure data, or the build reports a template-boundary diagnostic. Fix problems at the source and rebuild; never patch `dist/`. ## Selection order 1. `collections` — internal collections such as `architecture`, `sop`, `standards`, `feats` (see [Knowledge Collections]()). 2. `okfRoots` — output roots after mapping: `wikis`, `guides`, `rules`, `feats`. 3. `include` — path patterns relative to `knowledge/`. 4. `exclude` — removes matches after the previous filters. Without `include`, all approved knowledge is included unless excluded. When `collections` or `okfRoots` are present, a file must pass them before path patterns apply. --- ## Sources - [context/packages/context/docs/reference/package-templates.md L1–L46 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L48–L57 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L121–L122 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L59–L91 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L109–L119 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L124–L164 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L199–L246 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L247–L292 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L302–L327 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L339–L395 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L397–L422 · 3b0ce0a]() --- ## Template Variables # Template Variables Files under `src/package-templates/**` are rendered with Handlebars during `context build`. Templates can render values, loop over arrays, branch on conditions and carry template-only comments; they cannot run JavaScript. Variables work in file contents and in file paths. Custom values come from `template.vars`. ## Syntax ```handlebars Package: {{packageName}} Approved pages: {{knowledgeCount}} Inventory name: {{buildInventory.package.name}} {{#each knowledgeGroups}} ## {{title}} {{#each items}} {{inc @index}}. [{{title}}]({{href}}) {{/each}} {{/each}} {{#if description}} Description: {{description}} {{/if}} ``` - Values support dotted paths. - Loops can nest; `{{@index}}` is zero-based. - `{{#if}}` renders when the value exists and is not `false`, an empty string or an empty array. Template-only comments are stripped from the output: ```handlebars {{! Removed by Handlebars. }} ``` | Helper | Example | Meaning | | --- | --- | --- | | `inc` | `{{inc @index}}` | Adds 1 — for numbered lists | | `json` | `{{json knowledgeGroups}}` | Formatted JSON, for debugging or machine-readable docs | ## Built-in variables | Variable | Type | Meaning | | --- | --- | --- | | `packageName` | string | Package name from the declaration | | `packageKind` | string | `kb` or `llms` | | `displayName` | string | Title-cased `packageName` unless `template.vars.displayName` overrides it | | `skillsRoot`, `wikisRoot`, `guidesRoot`, `rulesRoot`, `featsRoot` | string | Final package roots: `skills`, `wikis`, `guides`, `rules`, `feats` | | `skillName`, `skillPath` | string | Name and package-relative `SKILL.md` path of the Skill being rendered; empty outside a Skill | | `knowledgeCount` | number | Number of selected approved pages | | `knowledgeTimestamp` | string | Latest selected `timestamp`, or the epoch when empty | | `knowledge`, `approvedKnowledge` | string | All selected pages concatenated for consumers, with path headings and without lifecycle metadata — can be large | | `knowledgeItems` | array | One record per selected page | | `knowledgeGroups` | array | Pages grouped by root and first directory | | `knowledgeTreeNodes` | array | Nested path tree, for custom navigation | | `knowledgeTree` | string | Markdown tree preview | | `knowledgeItemsMarkdown` | string | Markdown list of up to 50 pages | | `knowledgeGroupsMarkdown` | string | Navigation for the current index: direct links for folded directories, index links for expanded ones | | `buildInventory`, `buildInventoryJson`, `buildInventoryPath` | object, string, string | The deterministic build inventory, its JSON, and its path `context-build-inventory.json` | | `knowledgeStructure`, `knowledgeStructureJson`, `knowledgeStructurePath` | object or null, string, string | The selected-package projection of `knowledge/structure.yaml`; not copied into the package unless a template renders it | | `knowledgeNamespace`, `namespacedKnowledge` | string, boolean | Legacy; empty and `false` for new workspaces | `buildInventory.structure.edge_records` holds typed edges whose endpoints are in the package — use them for package-local relationship evidence. ## `knowledgeItems` fields | Field | Meaning | | --- | --- | | `path` (`dist_path`) | Package-relative path, such as `guides/architecture/entity/button.md` | | `sourcePath` (`approved_path`) | Approved path before mapping, such as `architecture/entity/button.md` | | `article_id` | Stable article identity | | `collection` (`internalCollection`, `internal_collection`) | Internal collection | | `okf_root`, `okf_root_path` | Output root and its final path | | `pathWithinCollection` | Path below the root | | `href` (`hrefFromTemplate`) | Link relative to the template file being rendered — use this | | `hrefFromPackageRoot` | Link from a root file such as `AGENTS.md` | | `hrefFromCollectionIndex` | Link from the current root index | | `title`, `type`, `description`, `timestamp`, `tags` | Frontmatter values; `title` falls back to the file name | | `source` | First source reference, or the group name | | `group`, `parentPath`, `depth`, `segments` | Position below the root | ## `knowledgeGroups` fields | Field | Meaning | | --- | --- | | `name` | First directory under the root, or `root` | | `title` | Display title; defaults to `name`, or the root title | | `count` | Number of pages | | `collection` (`internalCollection`, `internal_collection`) | Internal collection | | `okf_root`, `okf_root_path` | Output root and its final path | | `hasIndex` (`has_index`) | Whether the navigation policy generates `indexPath` | | `indexPath` | Index path, such as `wikis/codeindex/index.md` | | `indexHrefFromTemplate`, `indexHrefFromCollectionIndex` | Links to `indexPath`; check `hasIndex` first | | `items` | The group's `knowledgeItems` | ```handlebars {{#each knowledgeGroups}} ## {{title}} ({{count}}) {{#if hasIndex}} [Open directory index]({{indexHrefFromTemplate}}) {{/if}} {{#each items}} - [{{title}}]({{href}}) - {{type}} {{/each}} {{/each}} ``` ## `knowledgeTreeNodes` fields Each node has `name`, `title`, `path`, `depth`, `count` (pages under it), `items` (pages directly under it) and `children`. Handlebars has no recursive partials by default, so keep tree templates shallow or write sections for the levels you care about. ## The starter `wikis/index.md` The default template uses these variables for the bundle count and timestamp in its frontmatter, direct links for folded directories, and links to generated indexes for directories over the threshold. It is only a starter: edit `src/package-templates/kb/` when the package needs different reading paths, or accept the unchanged starter explicitly through the package-template review step. --- ## Sources - [context/packages/context/docs/reference/template-variables.md L1–L8 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L166–L194 · 3b0ce0a]() - [context/packages/context/docs/reference/template-variables.md L10–L86 · 3b0ce0a]() - [context/packages/context/docs/reference/template-variables.md L88–L126 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L182–L182 · 3b0ce0a]() - [context/packages/context/docs/reference/template-variables.md L128–L166 · 3b0ce0a]() - [context/packages/context/docs/reference/template-variables.md L168–L202 · 3b0ce0a]() - [context/packages/context/docs/reference/template-variables.md L204–L222 · 3b0ce0a]() - [context/packages/context/docs/reference/template-variables.md L224–L242 · 3b0ce0a]() --- ## Knowledge Collections # Knowledge Collections Every approved article in `knowledge/` lives under a **collection** — the first directory of its path, such as `knowledge/sop/…`. The collection says what kind of reading the article serves. At build time it decides which package root the article goes to, and package `select.collections` filters by it. ```mermaid flowchart LR k["knowledge/collection/..."] --> w["wikis/
entities and relationships"] k --> g["guides/
explanations and procedures"] k --> r["rules/
standards and checks"] k --> f["feats/
feature records"] ``` ## The collections | Collection | Holds | Package path | OKF type | | --- | --- | --- | --- | | `codeindex` | Source-backed code indexes, with optional structured relationships | `wikis/codeindex/` | Wiki | | `business` | Structured business entities and relationships | `wikis/business/` | Wiki | | `product` | Structured product entities, behavior and relationships | `wikis/product/` | Wiki | | `architecture` | Architecture explanations and design narratives | `guides/architecture/` | Guide | | `sop` | Procedures and runbooks | `guides/sop/` | Guide | | `faq` | Question-oriented explanations and troubleshooting | `guides/faq/` | Guide | | `decision` | Decision records and trade-off narratives | `guides/decision/` | Guide | | `incident` | Incident timelines, response and follow-up | `guides/incident/` | Guide | | `standards` | Normative standards and constraints | `rules/standards/` | Rule | | `test` | Validation rules, scenarios and acceptance checks | `rules/test/` | Rule | | `feats` | Feature capability records | `feats/` | Feature | `codegraph` is still accepted as the legacy name of the code index collection and maps to `wikis/` like `codeindex`. ## What the package roots mean - **`wikis/`** is the structured entity-and-relationship layer and the required default entry of a knowledge package, starting at `wikis/index.md`. - **`guides/`** and **`rules/`** explain, operationalize or constrain that knowledge. Placing an article there does not create a relationship to anything; only a typed edge recorded by Context does. - **`feats/`** holds feature records. A package can choose roots with `select.okfRoots` as well as collections; see [Package Templates](). ## Choosing a collection The Indexer proposes a collection from the reader's need, not from the source type: a document can become a runbook in `sop`, a decision record in `decision` or a standard in `standards`. Typical pairings: | Reader need | Useful form | | --- | --- | | Understand a term, boundary or business rule | Domain explanation with scope and examples | | Understand architecture or integration | Technical explanation, contracts and limitations | | Complete a repeatable task | Guide with prerequisites, actions and checks | | Diagnose or recover | Runbook with symptoms, safe actions and verification | | Understand a choice | Decision, alternatives, rationale and consequences | | Learn from an incident | Impact, observations, causes and response | | Interpret a test | Method, scope and what the result establishes | You can move an approved article to another collection later with `context revise --move-to `, which keeps its identity. ## Reserved names `index.md` is reserved for package bundle and directory indexes. A source document may be called `index.md`, but an article must use another name such as `index-page.md`; `context build` rejects copied knowledge that would occupy `wikis/**/index.md`. --- ## Sources - [context/packages/context/src/contracts.ts L45–L59 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L397–L408 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L299–L313 · 3b0ce0a]() - [context/packages/context-cli/src/project/okfTypes.ts L7–L35 · 3b0ce0a]() - [context/packages/context-cli/src/project/codeIndexCollection.ts L3–L8 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L315–L317 · 3b0ce0a]() - [context/packages/context/docs/reference/package-templates.md L253–L261 · 3b0ce0a]() - [context/plugins/context/skills/context-markdown-indexer/references/classification.md L1–L23 · 3b0ce0a]() - [context/packages/context-cli/src/commands/documentRevisionCommands.ts L204–L216 · 3b0ce0a]() - [context/packages/context/docs/guides/package-outputs.md L319–L322 · 3b0ce0a]() --- ## HTTP and MCP # HTTP and MCP All routes live under the `/sourcegraph` prefix of the instance's origin. Query routes are under `/sourcegraph/v1/` (search is `/sourcegraph/api/search`), management routes under `/sourcegraph/api/admin/`, and the MCP endpoint is `/sourcegraph/mcp`. Both surfaces call the same service, so revisions, limits and error codes are identical. For how to choose a credential see [Connecting](). > **Optional service.** Context does not require Source Graph or its MCP server. When neither is installed or configured, Context's query skill still reads code evidence locally through a shallow, sparse partial clone and grep; in its default `auto` mode it prefers Source Graph only when an authorized instance is available. ## Request conventions - **Repository** — routes that act on one repository take it as the `repo` query parameter, `owner/repository`. - **Query parameters** — only `repo` and `after` are accepted, plus `revision` on `/v1/repo/plugins` and `branch` on `/api/admin/v1/repo/commit-options`. Unknown or repeated parameters return `400 INVALID_QUERY_PARAMETERS`. - **Bodies** — JSON objects of at most 64 KiB. Unknown fields, `null` values, duplicate keys and trailing data are rejected. Query-route fields use capitalized names (`Revision`, `Pattern`); management routes use lowercase names (`name`, `policy`). - **Credentials** — `Authorization: Bearer ` or `Bearer sgk_…` for a personal key; otherwise a browser session or anonymous access. An invalid credential returns `401` and never falls back to anonymous access. - **Time** — each request has a 30-second processing budget; a request that exceeds it returns `503 QUERY_DEADLINE_EXCEEDED`, and an unexpected dependency failure returns `503 DEPENDENCY_UNAVAILABLE`. ## Query routes These are available anonymously when public reading is enabled, and to every credential. | Method | Path | Body | Returns | | --- | --- | --- | --- | | GET | `/v1/capabilities` | — | Protocol and supported operations | | GET | `/v1/repos` | — (`after` for the next page) | Registered repositories, 100 per page | | GET | `/v1/repo/availability` | — | One repository: retained versions, heads, groups and jobs, with an `ETag` | | GET | `/v1/repo/commits` | — | Same as availability | | GET | `/v1/repo/plugins` | — (optional `revision`) | Repository plugins found at that commit, without running them | | POST | `/v1/repo/resolve` | `{"Revision"}` | The fixed commit and whether it is indexed | | POST | `/api/search` | `{"Revision","Pattern","FixedStrings","IgnoreCase","Glob","Paths","Output"}` | Search hits and `Meta`; see [Query Syntax]() | | POST | `/v1/repo/read` | `{"Revision","Path","StartLine","EndLine"}` | One file range | | POST | `/v1/repo/list` | `{"Revision","Path","First","After"}` | Direct children of one directory | | POST | `/v1/repo/diff` | `{"Base","Head","Paths","First","After"}` | Changed files and patches between two commits | `Revision` is optional everywhere except `diff`, where `Base` and `Head` are required. `read_many` has no HTTP route; it exists only as an MCP tool. ## Management routes These need the service token or an administrator's browser session. Personal API keys are read-only and get `403 ACCESS_DENIED` here. A few read routes — `GET /api/admin/v1/repos`, `GET /api/admin/v1/repo` and `GET /api/admin/v1/statistics` — are also open to anonymous reading. | Method | Path | Body or headers | Purpose | | --- | --- | --- | --- | | GET | `/api/admin/v1/statistics` | — | Request and job statistics | | GET | `/api/admin/v1/instances` | — | Instance heartbeats | | GET | `/api/admin/v1/repos` | — | Repository catalog | | POST | `/api/admin/v1/repos` | Registration fields; optional `Idempotency-Key` | Register a repository (`202`) | | GET | `/api/admin/v1/repo` | — | Repository with `ETag` | | PATCH | `/api/admin/v1/repo` | Update fields; `If-Match` revision | Change branches, window, visibility, interval, path groups; enable, disable or delete | | POST | `/api/admin/v1/repo/preview` | Update fields | Preview an update | | POST | `/api/admin/v1/repo/prepare` | `{"kind","commit","group"}`; optional `Idempotency-Key` | Queue `sync` or `index` work (`202`) | | GET | `/api/admin/v1/repo/commit-options` | — (optional `branch`) | Recent synchronized commits to choose from | | POST | `/api/admin/v1/repo/index/preview`, `/api/admin/v1/repo/index` | `{"branch","commit"}`; the second also `preview` and `If-Match` | Add an index for one commit | | POST | `/api/admin/v1/repo/cleanup/preview`, `/api/admin/v1/repo/cleanup` | `{"preview"}` and `If-Match` for the second | Keep only the latest index per branch | | POST | `/api/admin/v1/repo/delete/preview`, `/api/admin/v1/repo/delete` | `{"preview"}` and `If-Match` for the second | Permanently delete repository data | | POST | `/api/admin/v1/repo/jobs/cancel` | `{"job_id"}` | Cancel a job | | POST | `/api/admin/v1/repo/purge` | `If-Match` revision | Purge a disabled, deleted repository | Registration fields are listed in [Registering Repositories](). ## Health, sign-in and settings routes | Path | Access | Purpose | | --- | --- | --- | | `GET /healthz` | Open | Liveness: `{"status":"alive"}` | | `GET /readyz` | Open | Readiness; `503` when the catalog cannot be read | | `GET /access-policy` | Open | `public_read`, `public_prepare` (always `false`) and `sso_enabled` | | `GET /site-settings` | Open | Public repository defaults | | `/auth/…` | Browser | Providers, sign-in and callback, current user, sign-out, `api-keys`, user administration | | `/auth/code-credentials` | Signed-in session | Your own Git credentials | | `/api/admin/settings/…` | Administrator session only | Site settings sections, `code-credentials`, `query-errors`, `jobs/clear`, `storage` | Site administration under `/api/admin/settings` refuses any request that carries an `Authorization` header — it is reachable only from a signed-in administrator's browser. ## MCP endpoint `/sourcegraph/mcp` speaks stateless Streamable HTTP with JSON responses; the server identifies itself as `context-sourcegraph`. The toolset depends on the credential: | Credential | Tools | | --- | --- | | Anonymous (public reading on), personal key | Read-only: every tool except `prepare` | | Administrator personal key created with prepare permission | Read-only tools plus `prepare`, rate-limited to 10 per key and 60 in total per minute | | Service token | All tools | The optional connection parameter `?plugins=` sets the default plugin selection for `read` and `read_many`: `auto`, `off`, or up to 16 comma-separated names. Invalid values return `400 INVALID_PLUGINS`. ## MCP tools | Tool | Required | Optional (default) | | --- | --- | --- | | `repositories` | — | `after` | | `availability` | `repo` | `job_id`, `include_plugins`, `revision` | | `resolve` | `repo` | `revision` | | `search` | `repo`, `pattern` | `revision`, `fixed_strings`, `ignore_case`, `glob`, `paths`, `output` (`content` or `files`), `max_lines_per_file` (10, range 1–1000) | | `read` | `repo`, `path` | `revision`, `start_line` (1), `end_line` (start + 499), `plugins` | | `read_many` | `repo`, `files` (1–10 items of `path`, `start_line`, `end_line`) | `revision` (resolved once for the batch), `plugins` | | `list` | `repo`, `first` (1–1000) | `revision`, `path`, `after` | | `diff` | `repo`, `base`, `head`, `first` (1–100) | `paths`, `after` | | `prepare` | `repo`, `idempotency_key` (8–128 bytes) | `revision`, `group` | `plugins` is a list such as `[{"name":"context-evidence"}]`; `[]` disables enhancements for that call, and a connection opened with `plugins=off` always disables them. `prepare` accepts an omitted revision (default branch), a monitored branch or a full SHA inside the retention window; it is asynchronous, so poll `availability` afterwards. ## MCP output `search`, `read` and `read_many` return readable text rather than raw JSON: - **search** starts with `Repository`, `Commit`, `Status`, `Partial`, `Truncated`, a `Coverage` line, registered `Paths` and `Groups`, and the returned and total file counts, then lists each `File` with numbered matching lines. - **read** starts with `Repository`, then `Path`, `Commit` and `Lines: start-end`, continuation fields when more remains (`Truncated`, `HasMore`, `NextStartLine`), notes for symlinks, submodules and LFS pointers, then numbered lines `N: text`. - **read_many** returns one text block per item, each with `Item N; RequestedLines`, an `Error` line if that item failed, and the same file header and lines. Plugin output is appended after the item it belongs to; plugin diagnostics come in a separate block and never replace the original text. The other tools return compact JSON. Errors come back as a tool result marked as an error, whose text is `{"code","message"}`, with a recovery hint for not-ready states. ## Limits | Limit | Value | | --- | --- | | Catalog page | 100 repositories | | Search pattern | 8,192 bytes; cannot match a newline or the empty string | | Search globs | 64, each up to 1,024 bytes | | Search or diff paths | 64 directories | | Search page | 100 files and 1,000 matches with 2 context lines, then smaller fallbacks; 2 MiB response; 5-second deadline | | Engine match cap | 10,000 matches | | Read | 500 lines and 256 KiB per call | | `read_many` | 1–10 items, 1,000 lines, 256 KiB and 30 seconds shared | | List page | 1–1,000 entries | | Diff page | 1–100 files; patches 64 KiB per file and 256 KiB total | | Request body | 64 KiB | ## Error format HTTP errors return a JSON body with an `Error` message and `Meta` containing `Protocol`, `RequestID`, `Status`, `Code` and `Retryable`. Transport-level codes include `NOT_FOUND`, `METHOD_NOT_ALLOWED`, `INVALID_QUERY_PARAMETERS`, `INVALID_REQUEST`, `AUTHENTICATION_REQUIRED`, `ACCESS_DENIED`, `RATE_LIMITED`, `PRECONDITION_REQUIRED`, `QUERY_DEADLINE_EXCEEDED` and `DEPENDENCY_UNAVAILABLE`. Operation codes such as `INDEX_NOT_READY`, `REVISION_NOT_ELIGIBLE`, `INVALID_PATTERN` or `READ_BUDGET_EXCEEDED` carry their own status. [Operations]() explains the common ones and what to do about them. --- ## Sources - [sourcegraph/internal/httpserver/server.go L16–L16 · 4e5c555]() - [sourcegraph/docs/interfaces.md L1–L8 · 4e5c555]() - [context/plugins/context/skills/context-inspect-search/SKILL.md L49–L55 · 3b0ce0a]() - [sourcegraph/internal/httpserver/runtime.go L241–L250 · 4e5c555]() - [sourcegraph/internal/contract/json.go L12–L55 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L426–L442 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L291–L326 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L389–L422 · 4e5c555]() - [sourcegraph/internal/httpserver/website_access.go L15–L31 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L278–L387 · 4e5c555]() - [sourcegraph/internal/httpserver/repository_maintenance.go L12–L60 · 4e5c555]() - [sourcegraph/internal/httpserver/registration.go L9–L22 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L86–L128 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L129–L159 · 4e5c555]() - [sourcegraph/internal/httpserver/code_credentials.go L74–L78 · 4e5c555]() - [sourcegraph/internal/mcpserver/server.go L14–L30 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L40–L56 · 4e5c555]() - [sourcegraph/internal/mcpserver/plugin_connection.go L19–L62 · 4e5c555]() - [sourcegraph/internal/mcpserver/inputs.go L1–L115 · 4e5c555]() - [sourcegraph/internal/mcpserver/server.go L31–L82 · 4e5c555]() - [sourcegraph/internal/mcpserver/read_defaults.go L1–L16 · 4e5c555]() - [sourcegraph/internal/mcpserver/read_text.go L38–L110 · 4e5c555]() - [sourcegraph/internal/mcpserver/search_text.go L60–L125 · 4e5c555]() - [sourcegraph/internal/mcpserver/plugin_text.go L1–L36 · 4e5c555]() - [sourcegraph/internal/zoektclient/client.go L20–L30 · 4e5c555]() - [sourcegraph/internal/zoektclient/client.go L105–L190 · 4e5c555]() - [sourcegraph/internal/service/read_many.go L13–L20 · 4e5c555]() - [sourcegraph/internal/contract/types.go L36–L46 · 4e5c555]() - [sourcegraph/internal/contract/errors.go L1–L18 · 4e5c555]() - [sourcegraph/internal/httpserver/server.go L49–L86 · 4e5c555]() --- ## CLI # CLI `sourcegraph-cli` is a small, bounded HTTP client for a Source Graph instance. It sends one request per invocation to the routes described in [HTTP and MCP](), prints the JSON response and exits; it never clones repositories or installs anything. It is built with the service into `output/bin/` and is included in the container image. ```text sourcegraph-cli [flags] [arguments] ``` ## Environment | Variable | Default | Rules | | --- | --- | --- | | `SOURCEGRAPH_URL` | `https://context4ai.org/sourcegraph` | The instance's `/sourcegraph` base address. Must be an HTTPS URL without user information, query or fragment | | `SOURCEGRAPH_API_TOKEN` | — | Optional bearer credential — a personal API key or the service token. At least 32 characters when set | Because the address must be HTTPS, a local instance on `http://localhost` needs a TLS-terminating proxy in front of it for CLI use. ## Commands | Command | Route | Flags used | | --- | --- | --- | | `repositories` | `GET /v1/repos` | `-after` | | `availability` | `GET /v1/repo/availability` | `-repo` | | `resolve` | `POST /v1/repo/resolve` | `-repo`, `-revision` | | `search` | `POST /api/search` | `-repo`, `-revision`, `-e`, `-F`, `-i`, `-l`, `-g`; then `PATTERN [PATH...]` | | `read` | `POST /v1/repo/read` | `-repo`, `-revision`, `-path`, `-start-line`, `-end-line` | | `list` | `POST /v1/repo/list` | `-repo`, `-revision`, `-path`, `-first`, `-after` | | `diff` | `POST /v1/repo/diff` | `-repo`, `-base`, `-head`, `-first`, `-after` | | `prepare` | `POST /api/admin/v1/repo/prepare` | `-repo`, `-revision`, `-kind`, `-key` | There is no `read_many` command; use several `read` calls or the MCP tool. `diff` compares all registered paths, and `prepare` targets all path groups. `prepare` is a management route, so it needs the service token. ## Flags Flags use Go syntax: one or two leading dashes both work (`-repo` or `--repo`), and every flag must come before positional arguments. | Flag | Default | Meaning | | --- | --- | --- | | `-repo` | — | Repository key, `owner/repository` | | `-revision` | — | A monitored branch or a full SHA; omitted means the default branch. For `prepare`, the commit to prepare | | `-e` | — | Search pattern, like `rg -e`; otherwise the first positional argument | | `-F` | `false` | Match the pattern as literal text, like `rg -F` | | `-i` | `false` | Ignore case, like `rg -i` | | `-l` | `false` | Print only matching paths, like `rg -l` | | `-g` | — | Include, or `!`-exclude, files by glob, like `rg -g`; repeatable | | `-path` | — | Repository-relative file or directory | | `-start-line` | `1` | First line to read | | `-end-line` | `100` | Last line to read | | `-first` | `100` | Page size for `list` (1–1000) and `diff` (1–100) | | `-after` | — | Cursor from the previous page | | `-base`, `-head` | — | The two revisions for `diff` | | `-key` | — | Idempotency key sent as `Idempotency-Key` for `prepare` | | `-kind` | `index` | `index` or `sync`, for `prepare` | Search arguments after the pattern are directories to search within, like `rg`'s `PATH` arguments. ## Output and exit codes The CLI writes the response body — always JSON — to standard output unchanged, up to 3 MiB, and diagnostics to standard error. Each request has a 35-second timeout, and redirects are refused. | Exit code | Meaning | | --- | --- | | `0` | Success | | `1` | Request failed, timed out, returned an invalid or oversized body, or a non-2xx status | | `2` | Usage error: unknown command, bad flags, missing pattern, invalid `SOURCEGRAPH_URL` or token | | `3` | Accepted but not ready yet — `202 Accepted`, or `409 INDEX_NOT_READY` | After a timeout, delivery is unknown; inspect `availability` before retrying a `prepare`. ## Examples ```bash export SOURCEGRAPH_URL="https://context4ai.org/sourcegraph" # Literal search in TypeScript files under packages/ sourcegraph-cli search -repo context4ai/context -F -g '*.ts' 'defineProject' packages # Read lines 1–40 at the commit returned in Meta.Commit sourcegraph-cli read -repo context4ai/context -revision -path README.md -end-line 40 # List the repository root sourcegraph-cli list -repo context4ai/context -first 50 # Ask an instance you administer to index a commit (service token required) SOURCEGRAPH_API_TOKEN=... sourcegraph-cli prepare -repo acme/app -revision -key index- ``` ## Git credential helper `git-credential-sourcegraph` is used by the service itself, not by people. For every Git fetch, the service selects a credential — the repository creator's stored credential, the global one, or the legacy `SOURCEGRAPH_GIT_TOKEN` value, as described in [Registering Repositories]() — and passes it to the helper through the `SOURCEGRAPH_GIT_TOKEN` environment variable of that Git process. The helper answers only Git's `get` action and only for HTTPS requests to `github.com`, returning the token as the password; it prints nothing when the token is empty or contains line breaks or NUL characters. --- ## Sources - [sourcegraph/cmd/sourcegraph-cli/main.go L1–L28 · 4e5c555]() - [sourcegraph/DEVELOPMENT.md L24–L24 · 4e5c555]() - [sourcegraph/Dockerfile L20–L28 · 4e5c555]() - [sourcegraph/cmd/sourcegraph-cli/main.go L50–L63 · 4e5c555]() - [sourcegraph/cmd/sourcegraph-cli/main.go L64–L125 · 4e5c555]() - [sourcegraph/cmd/sourcegraph-cli/main.go L29–L49 · 4e5c555]() - [sourcegraph/cmd/sourcegraph-cli/main.go L78–L99 · 4e5c555]() - [sourcegraph/cmd/sourcegraph-cli/main.go L126–L162 · 4e5c555]() - [sourcegraph/web/assets/clients.js L1–L21 · 4e5c555]() - [sourcegraph/cmd/git-credential-sourcegraph/main.go L1–L36 · 4e5c555]() - [sourcegraph/internal/gitstore/fetch.go L146–L152 · 4e5c555]() - [sourcegraph/internal/codecredentials/manager.go L203–L240 · 4e5c555]() --- ## Query Syntax # Query Syntax A Source Graph search is not a query language with filters. It is a small set of structured fields that mean what the matching `rg` options mean: a pattern matched line by line against file contents, plus switches for literal matching, case folding, globs and directories. The service compiles them into its own engine query; callers never write engine syntax, and text such as `file:` or `lang:` inside a pattern is matched literally. | Meaning | `rg` | HTTP body | MCP `search` | CLI | Website | | --- | --- | --- | --- | --- | --- | | Pattern | `PATTERN`, `-e` | `Pattern` | `pattern` | `PATTERN` or `-e` | Search box | | Literal text | `-F` | `FixedStrings: true` | `fixed_strings` | `-F` | **Regular expression** toggle off | | Ignore case | `-i` | `IgnoreCase: true` | `ignore_case` | `-i` | **Match case** toggle off | | Globs | `-g` | `Glob: [...]` | `glob` | `-g`, repeatable | Include and exclude fields | | Directories | `PATH...` | `Paths: [...]` | `paths` | Arguments after the pattern | — | | Paths only | `-l` | `Output: "files"` | `output: "files"` | `-l` | — | | Revision | — | `Revision` | `revision` | `-revision` | Branch or commit selector | ## Patterns - A pattern is an RE2 regular expression, close to `rg`'s default syntax, matched against **file contents**, never against paths. - Matching is **line-oriented**, like `rg` without `-U`: a pattern that could match a newline is rejected. Search for each line separately. - A pattern must consume at least one character. Patterns that match the empty string, or only zero-width assertions, are rejected. - Lookaround and backreferences are not supported; use `FixedStrings` to match such text literally. - The pattern must be non-empty valid UTF-8 of at most 8,192 bytes. - Searches are **case-sensitive by default**. `IgnoreCase` folds case for the whole pattern. Invalid patterns return `400 INVALID_PATTERN` with the reason. ## Globs Globs follow `rg -g` and gitignore conventions: | Glob | Matches | | --- | --- | | `*.go` | Files named `*.go` at any depth — a glob without `/` matches names anywhere | | `src/**/*.ts` | TypeScript files under `src/`, anchored at the repository root because it contains `/` | | `!**/*_test.go` | Excludes test files | | `!vendor/` | Excludes everything under any `vendor` directory | | `*.{ts,tsx}` | Either extension | `*` and `?` never cross `/`, `**` spans directories, and `[...]` character classes are supported. When includes are given, a file must match at least one of them; when includes and excludes overlap, the later glob wins, as in `rg`. An include glob ending in `/` is rejected — use `Paths`, or append `/**`. Up to 64 globs of at most 1,024 bytes each are allowed; bad ones return `400 INVALID_GLOB`. On the website, the include and exclude fields take comma-separated globs; commas inside `{a,b}` belong to the glob. ## Paths and output `Paths` lists repository-relative directories to search, like `rg`'s trailing `PATH` arguments, up to 64. In a monorepo registration they must lie inside the registered path groups (`PATH_NOT_REGISTERED` otherwise); omitting them searches every registered group at the same commit, never mixing versions. `Output` is `content` (the default), returning matching lines, or `files`, returning only paths, like `rg -l`. Over MCP, `max_lines_per_file` (1–1000, default 10) bounds how many matching lines are shown per file in content mode. ## Reading the results Each result names its `Repository` and `Commit`; read surrounding code at that same commit. Results are a bounded first page — up to 100 files and 1,000 matches with two context lines, reduced automatically if the response would exceed 2 MiB — so check the metadata before drawing conclusions: | Field | Meaning | | --- | --- | | `Partial` | The engine stopped early, for example at its 10,000-match cap or because shards were skipped | | `Truncated` | More files or matches existed than were returned | | `Coverage` | What the index covers: index mode, registered paths and groups, text-only profile without symbols, and skipped unsupported paths | A search with no hits is not proof of absence outside that coverage or beyond the limits. Text files the index skipped, such as generated or very large files, can still be read directly at that commit within the read limits. ## Website search links The website's search page encodes the same request in its address, using the API field names: `repo`, `pattern`, `fixed_strings=1`, `ignore_case=1`, repeated `glob`, and either `commit` (a full SHA) or `revision` (a branch). Code pages accept `repo`, `path` and `commit` or `revision`, with a line range in the fragment such as `#L20-L40`. Links copied from the website therefore reproduce the exact search or read at the same commit. ## Examples | Goal | HTTP body | CLI | | --- | --- | --- | | Find a function call | `{"Pattern":"WithTimeout\\("}` | `sourcegraph-cli search -repo R 'WithTimeout\('` | | Literal text, any case | `{"Pattern":"todo:","FixedStrings":true,"IgnoreCase":true}` | `sourcegraph-cli search -repo R -F -i 'todo:'` | | Only Go files, no tests | `{"Pattern":"func New","Glob":["*.go","!*_test.go"]}` | `sourcegraph-cli search -repo R -g '*.go' -g '!*_test.go' 'func New'` | | Within two directories | `{"Pattern":"retry","Paths":["internal/service","cmd"]}` | `sourcegraph-cli search -repo R retry internal/service cmd` | | List matching files | `{"Pattern":"deprecated","Output":"files"}` | `sourcegraph-cli search -repo R -l deprecated` | --- ## Sources - [sourcegraph/internal/contract/types.go L17–L28 · 4e5c555]() - [sourcegraph/internal/service/scoped_search.go L120–L135 · 4e5c555]() - [sourcegraph/web/assets/search-page.js L10–L22 · 4e5c555]() - [sourcegraph/internal/zoektclient/pattern.go L36–L66 · 4e5c555]() - [sourcegraph/internal/mcpserver/inputs.go L22–L32 · 4e5c555]() - [sourcegraph/internal/zoektclient/pattern.go L170–L230 · 4e5c555]() - [sourcegraph/internal/zoektclient/pattern.go L232–L335 · 4e5c555]() - [sourcegraph/web/assets/search-model.mjs L54–L70 · 4e5c555]() - [sourcegraph/internal/service/scoped_search.go L20–L107 · 4e5c555]() - [sourcegraph/internal/zoektclient/client.go L105–L190 · 4e5c555]() - [sourcegraph/internal/service/scoped_search.go L215–L260 · 4e5c555]() - [sourcegraph/internal/mcpserver/search_text.go L60–L115 · 4e5c555]() - [sourcegraph/web/assets/search-model.mjs L12–L53 · 4e5c555]() - [sourcegraph/cmd/sourcegraph-cli/main.go L77–L99 · 4e5c555]() --- ## Configuration # Configuration Source Graph is configured in four layers, each with a different owner and lifetime: | Layer | Where | Changed by | Takes effect | | --- | --- | --- | --- | | Environment variables | Process environment, for example Fly.io secrets or a container env file | Operator | On restart | | Deployment settings | `config/deployment.json`, embedded at build time | Whoever builds the image | On the next build | | Site settings | Database, edited on the **Settings** page | Administrators | Immediately, with revision checks | | Repository policy | Database, set per repository at registration or later | Administrators | On the next synchronization | Secrets — Git tokens, OAuth client secrets, the service token, the credential key and database URLs with passwords — belong only in environment variables or the database, never in the deployment file or the image. For deployment steps see [Self-hosting](). ## Environment variables | Variable | Default | Purpose | | --- | --- | --- | | `SOURCEGRAPH_LISTEN` | `0.0.0.0:8080` | Listen address | | `SOURCEGRAPH_ORIGIN` | `http://localhost:8080` | Public origin, used for sign-in callbacks and links | | `SOURCEGRAPH_DATA_ROOT` | `/data` | Data directory; must be absolute | | `SOURCEGRAPH_DATABASE` | `sqlite` | `sqlite`, `postgres` or `mongodb` | | `DATABASE_URL` | `/sourcegraph.db` for SQLite | Database location or connection string | | `SOURCEGRAPH_MIN_FREE_BYTES` | `1073741824` (1 GiB) | Free-space floor below which fetching and indexing stop with `INSUFFICIENT_STORAGE` | | `SOURCEGRAPH_API_TOKEN` | Unset | Optional service token of at least 32 characters; a matching bearer token gets full HTTP API access, except site settings, which require a browser session. The CLI reads the same variable | | `SOURCEGRAPH_CREDENTIAL_KEY` | Generated `code-credentials.key` in the data root | Base64 of 32 bytes; encrypts stored code-host credentials | | `SOURCEGRAPH_GIT_TOKEN` | Unset | Legacy global GitHub credential, used only while no global `github` credential has been saved | | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | Unset | Google sign-in | | `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET` | Unset | GitHub sign-in | | `SOURCEGRAPH_SEED_DEMO` | Unset | `true` registers `context4ai/context` and `context4ai/sourcegraph` at startup if they are missing | Changing `SOURCEGRAPH_CREDENTIAL_KEY` after credentials have been stored makes them unreadable; keep the key with the database backup. With PostgreSQL or MongoDB, several instances can share one database while each keeps its own data directory. ## Deployment settings `config/deployment.json` is compiled into the binaries and describes what this deployment is, not how it is secured: | Field | Community default | Meaning | | --- | --- | --- | | `code_host` | `https://github.com` | Code host that registrations and credentials target | | `example_repo` | `context4ai/context` | Repository used in interface examples | | `public_url` | `https://context4ai.org/sourcegraph` | Public address shown in links and connection snippets | | `source_repository` | `https://github.com/context4ai/sourcegraph` | Source link shown in the interface | | `sso` | Google issuer and endpoints, empty client ID | Sign-in provider metadata, plus `registration_url`, the provider console where an operator creates the OAuth client; no secrets | A fork that deploys under its own name or address edits this file and rebuilds; sign-in client IDs and secrets still come from the environment. ## Site settings Administrators edit two sections on the **Settings** page or through `/api/admin/settings`. Each save carries the section's current revision; a stale revision is rejected so two administrators cannot silently overwrite each other. | Section | Field | Default | Meaning | | --- | --- | --- | --- | | `repository_defaults` | `retention_mode` | `days` | Default retention for new registrations: `days` or `count` | | | `retention_days` | 30 | Days of history kept, 1–365 | | | `retention_count` | 20 | Commits kept per branch, 1–4,096 | | `access` | `public_read` | `true` | Whether anonymous visitors can search and read public repositories | | | `allow_registration` | `false` | Whether a first-time sign-in creates an account | | | `registration_notice_zh`, `registration_notice_en` | A built-in notice | Text shown to people who cannot register | Requests to `/api/admin/settings` must use a browser session; requests carrying an `Authorization` header are refused. The **Storage** page separately moves where Git mirrors are kept; see [Operations](). ## Repository policy Each registration has its own policy, initialized from the repository defaults: | Setting | Range | Default | | --- | --- | --- | | Monitored branches | 1–8 | The default branch | | Retention | Days 1–365 **or** commits 1–4,096, not both | Site default | | Sync interval (minutes) | 1, 3, 5, 10, 30, 60, 180, 360, 720 or 1440 | 5 | | Index mode | Whole repository, or registered path groups for a monorepo | Whole repository | | Public read | On or off | On | | Credential kind (`code_provider`) | `github` or `git`; the registrant's own credential of that kind is tried first, then the global one | `github` | A repository with public read off is hidden from anonymous visitors only; every signed-in user can still read it. See [Registering repositories]() for how branches and retention decide which commits are searchable. ## Plugin limits Wasm evidence plugins run inside the service under resource guards set by `SOURCEGRAPH_PLUGINS_*` variables. Invalid values stop startup rather than removing a guard. | Variable suffix | Default | Limits | | --- | --- | --- | | `DISABLED` | Unset | `1` disables plugins | | `TIMEOUT` | `10s` | Wall time per run (Go duration) | | `MEMORY_MIB` | 256 | Memory per instance, at most 4,096 | | `ARTIFACT_BYTES` | 32 MiB | Plugin module size | | `METADATA_BYTES` | 256 KiB | Plugin metadata size | | `FILE_BYTES` | 32 MiB | Size of one file the plugin reads | | `READ_BYTES` | 128 MiB | Total bytes read per run | | `READ_CALLS` | 1,024 | File reads per run | | `OUTPUT_BYTES` | 2 MiB | Output size | | `CONCURRENCY` | 8 | Concurrent runs | | `CACHE_ENTRIES` | 16 | Compiled modules kept | | `IDLE_INSTANCES` | 8 | Warm instances kept | ## Built-in limits Some limits are fixed in code and cannot be configured: request bodies up to 64 KiB, a 30-second request deadline, HTTP server timeouts of 5 seconds for headers, 120 seconds for reading and 125 seconds for writing, and the search, read, list and diff page sizes described in [HTTP and MCP](). The search engine runs as a local helper on `127.0.0.1:6070` and is never exposed. ## Data directory | Path under the data root | Contents | Rebuildable | | --- | --- | --- | | `sourcegraph.db` | SQLite database: users, keys, settings, registrations, credentials | No | | `code-credentials.key` | Generated credential key, when `SOURCEGRAPH_CREDENTIAL_KEY` is unset | No | | `storage.json` | Where Git mirrors are stored on this machine | No | | `space/` | Bare Git mirrors, unless moved on the **Storage** page | Yes, from the remotes | | `index/`, `manifests/` | Search index shards and the manifests that describe them | Yes, by indexing again | The container runs as an unprivileged user (uid 10001) and needs write access to the whole data root. --- ## Sources - [sourcegraph/config/deployment.go L1–L30 · 4e5c555]() - [sourcegraph/internal/sitesettings/service.go L20–L40 · 4e5c555]() - [sourcegraph/cmd/repo-service/main.go L60–L112 · 4e5c555]() - [sourcegraph/cmd/repo-service/main.go L60–L160 · 4e5c555]() - [sourcegraph/internal/codecredentials/manager.go L58–L125 · 4e5c555]() - [sourcegraph/internal/httpserver/runtime.go L180–L230 · 4e5c555]() - [sourcegraph/config/deployment.json L1–L12 · 4e5c555]() - [sourcegraph/internal/sitesettings/model.go L1–L137 · 4e5c555]() - [sourcegraph/internal/control/model.go L15–L40 · 4e5c555]() - [sourcegraph/internal/httpserver/registration.go L1–L55 · 4e5c555]() - [sourcegraph/internal/control/model.go L115–L125 · 4e5c555]() - [sourcegraph/internal/wasmplugin/types.go L46–L85 · 4e5c555]() - [sourcegraph/internal/config/config.go L12–L75 · 4e5c555]() - [sourcegraph/cmd/repo-service/main.go L155–L182 · 4e5c555]() - [sourcegraph/internal/service/storage.go L40–L105 · 4e5c555]() - [sourcegraph/internal/service/storage_cleanup.go L55–L80 · 4e5c555]() - [sourcegraph/Dockerfile L1–L32 · 4e5c555]() --- ## Specification # Specification This page summarizes the `agent-graph.*.v1` protocols implemented by `@c4a/agent-graph@0.3.1`. The JSON Schemas shipped in the package's `schemas/` directory are normative for file shape; this page lists fields and behavioural rules. For the reasoning behind them, read [Core Model](); for step-by-step use, read [Authoring Graphs](). | Schema identity | Object | | --- | --- | | `agent-graph.provider.v1` | Provider manifest | | `agent-graph.graph.v1` | Graph | | `agent-graph.action.v1` | Action | | `agent-graph.resource.file.v1`, `.graph-action.v1`, `.host-action.v1` | Resource descriptors | | `agent-graph.resource-location.file.v1`, `.graph-action.v1`, `.host-action.v1` | Resolved Resource locations | | `agent-graph.resource-read-receipts.v1` | Current-conversation read receipts | | `agent-graph.host-action-result.v1` | Host materialization result | | `agent-graph.code-catalog.v1` | Code Catalog | | `agent-graph.evaluation.v1`, `agent-graph.route.v1` | Evaluation and Route output | | `agent-graph.run.v1` | Run file | | `agent-graph.test.v1` | Graph test | | `agent-graph.bundle.v1` | Built bundle manifest | | `agent-graph.error.v1` | CLI error envelope | Unknown fields are rejected in every v1 object, so a misspelled safety field cannot be silently ignored. ## Provider and Skill binding ```yaml schema: agent-graph.provider.v1 id: company/release version: 0.1.0 graphs: [graphs/release.yaml] catalogs: codes: codes.yaml compatibility: agentGraph: ^0.3.0 node: ">=20" ``` | Field | Rule | | --- | --- | | `id` | Identifies the Provider; runtime identities are qualified by Provider, Graph and node ID | | `version` | Semantic version of this Provider, independent of the `@c4a/agent-graph` package version | | `graphs` | Provider-root-relative paths; Graphs are never discovered by scanning | | `catalogs.codes` | Optional Code Catalog | | `compatibility` | Supported toolchain (`agentGraph`) and Node.js ranges | All references stay inside the Provider root: no absolute paths and no escape through `..` or a symbolic link. Several Providers stay isolated — no merging and no cross-Provider Subgraphs. A source manifest may have any filename; a built bundle uses `provider.yaml` plus a generated `manifest.json`. A bound Skill declares `metadata.agent-graph` (a `path:` locator relative to that `SKILL.md`, or a host-resolved `provider:` locator), `agent-graph.graph` and `agent-graph.entry`. The three are validated together, and an Agent must never infer Graph or Entry from prose. ## Graph and nodes A Graph has `id`, `entrypoints` (public entry name → node), `nodes` and `edges`. Topology is static: target names, dates, phase IDs and queue items are Facts, not generated nodes. Every Graph needs at least one Terminal; Terminals have no outgoing edges, and reaching Terminals with conflicting Outcomes is `terminal-outcome-ambiguous` with status `error`. | Kind | Required field | Meaning | | --- | --- | --- | | `action` | `action` | A Provider-relative Action can be selected | | `gate` | `gate` | User or session authority must resolve a policy boundary | | `subgraph` | `graph`, `entry` | Enter another Graph in the same Provider | | `terminal` | `terminalOutcome` | End the frame with an explicit Outcome | | Common field | Rule | | --- | --- | | `description` | Short human label, never a condition | | `reasonCode` | Required on Action and Gate nodes; shape `route.` | | `priority` | Ranks Routes within one availability class; never a semantic chooser | | `join` | `all` (default) requires all incoming edges; `any` requires one | | `requiresFacts` | All checks must pass before the node is legal | | `satisfiedBy` | Facts that prove an Action or Gate complete without replaying it | | `resources.required`, `resources.recommended` | Resources selected with an Action or Gate | Subgraph and Terminal nodes cannot carry Action or Gate resources or satisfaction rules. ## Fact checks ```yaml satisfiedBy: - path: artifact.digest exists: true - path: verification.state equals: passed ``` `path` is a dotted lookup in which numeric segments index arrays (`items.0.digest`). Each check has exactly one of `exists` or `equals`, with a scalar JSON value. There is no JavaScript, templating, shell or condition language. | Situation | Result | | --- | --- | | `satisfiedBy` matches | `completed`, even with no Run record | | Recorded `completed`, `satisfiedBy` does not match | `unverified` | | Explicit `unverified` edge | Can route to recovery | | A claim made in conversation | Creates no Fact | ## Gates | Field | Rule | | --- | --- | | `gate.id`, `gate.prompt` | Gate identity and a short question | | `gate.authority` | Authority that may resolve it | | `gate.delegatable` | Only when true can a session authority resolve it | | `inspectionAction` | Optional `effect: read` Action that prepares evidence; exposed as `gate.inspectionAction`, safe while waiting | | `resolutionAction` | Optional `write` or `external` Action that records or applies the decision after confirmation; exposed as `gate.resolutionAction` | | `delegated.inspection` | `skip` hides the inspection on the delegated Route; requires an authored inspection Action | | `delegated.resolutionAction` | Replaces the resolution Action on the delegated Route only; `write` or `external` | | `delegated.resources` | Replaces the Gate's resources on the delegated Route only | Without the authority the Route is `waiting-user` with an empty `commandPlan`; with a delegatable authority it is actionable with `resolution: session-authority`. Authorities live in the current input or Run, never in the Provider, and never satisfy Facts. A host must not run a resolution Action while the Route still requires the user. ## Edges Each edge has `from`, `to`, optional `kind` and optional `outcomes` (default `[completed]`). | Kind | Semantics | | --- | --- | | `flow` | General control transition | | `consumes` | The target consumes an artifact produced by the source | | `requires` | The source is a legal prerequisite of the target | | `gatedBy` | A Gate resolves the target's policy boundary; must start at a Gate | | `repeat` | A matching Outcome resets an Action or Gate to pending | All non-repeat kinds share the same reachability rule; the kind records causal intent only. Edges carry no runtime values. Non-repeat edges must be acyclic (`graph-flow-cycle` otherwise), `repeat` must target an Action or Gate, and Run history keeps earlier iterations. Fan-out and fan-in are reachability, not concurrency. A Subgraph target is resolved statically in the same Provider; recursion into an ancestor is rejected. ## Actions ```yaml schema: agent-graph.action.v1 id: inspect-package runner: command effect: read command: npm pack --dry-run cwd: workspace ``` | Runner | Fields | Route result | | --- | --- | --- | | `command` | `command` | Exact shell command | | `script` | `entry`, `runtime`, optional `args` | Runtime and absolute installed entry path | | `agent` | `skill` | The Skill as a required file resource | | `host` | `handler` | Host-defined handler identity | | Field | Rule | | --- | --- | | `effect` | Required: `read`, `write` or `external` | | `cwd` | `workspace` (default) or `provider` | | `inputSchema`, `outputSchema` | Bundled; installed locations exposed on the Route | | `files` | Extra runtime files to package | Runner fields are mutually exclusive. A Skill in its own directory carries that directory into the bundle; a Provider-root `SKILL.md` carries only itself. Agent Graph resolves Actions and never executes them implicitly. ## Resources | Protocol | Key fields | Behaviour | | --- | --- | --- | | Static file | Markdown frontmatter `id`, `kind`, `media-type`; or a `resource.file.v1` descriptor with `id`, `kind`, `mediaType`, `path` | Kinds `procedure`, `diagnostic`, `template`, `schema`, `skill`; located by absolute path, media type and content digest | | Graph action | `id`, `kind: context-view`, `mediaType`, `materializer` | Materializer must be a `read` command or script Action; runs only through `resource materialize` with the selecting Route revision | | Host action | `id`, `kind`, `mediaType`, `materializer`, `input` | Materializer must be a `read` host Action with `handler`, `inputSchema` and `outputSchema`, each schema with a versioned protocol identity; input validated before any Route is returned | Materializers receive `AGENT_GRAPH_PROVIDER_ROOT`, `AGENT_GRAPH_WORKSPACE`, `AGENT_GRAPH_REVISION` and `AGENT_GRAPH_INPUT`, a minimal inherited environment, and default limits of 30 s, 10 MiB stdout and 1 MiB stderr. For host-action Resources, Agent Graph computes `input_digest` from `{handler, input.schema, input.value}`; the host returns `agent-graph.host-action-result.v1` with the same handler and digest, adapter identity and exactly one of `inline` or `resource` (`ref` plus `digest`), checked by `validateHostActionResult`. Read receipts (`agent-graph.resource-read-receipts.v1`) are scoped to one Provider. A static receipt matches ID and digest; a dynamic one matches ID and selecting Route revision. Every Route resource gets `readState: current` or `read-required`. Receipts never affect evaluation and are never persisted in Runs. ## Code Catalog ```yaml schema: agent-graph.code-catalog.v1 codes: - code: route.release.inspect kind: route-reason summary: The release artifact still needs inspection. document: resources/release-checklist.md ``` `kind` is `route-reason` or `diagnostic` (which may add `severity`, including `info`). `summary` is a hint, never a condition; `document` is an optional static Resource. Without a Catalog, `reasonCode` is only shape-checked; with one, every Action and Gate `reasonCode` must resolve to a `route-reason` entry. ## Outcomes, Evaluation and Route Outcomes are `completed`, `partial`, `failed`, `unverified`, `skipped`, `pending`, `blocked` and `waiting-user`. They are not aliases; `partial`, `unverified` and `skipped` never become `completed`. | Evaluation field | Content | | --- | --- | | `provider`, `graph`, `entry` | Identities | | `revision` | Digest of the Graph's same-Provider dependency closure, Facts, normalized Outcomes and authorities | | `statusCode` | `actionable`, `waiting-user`, `blocked`, `complete` or `error` | | `outcome` | Terminal Outcome, when complete | | `primaryRoute`, `alternativeRoutes` | One primary and up to three alternatives, each with `routeId`, `node`, `reasonCode`, optional `hint`, `availability` | | `diagnostics` | Compact diagnostics | Evaluation is read-only and deterministic; outcome timestamps and files used only by unrelated Graphs do not change the revision. A Route (`agent-graph.route.v1`) carries `revision` and `routeId`, Graph, node and `callPath`, `statusCode`, `reasonCode`, `hint`, `availability`, optional Gate resolution and Gate Actions, the Action with its effect, `commandPlan` or handler, resolved working directory, required and recommended resource locations — each keeping its complete file, Graph-action or Host-action location envelope — with `readState`, and `afterAction: {evaluate: true, recordNode}`. A Route ID is accepted only while still available, and a revision mismatch is rejected before any command plan is returned. ## Run, tests and bundle A Run (`agent-graph.run.v1`) is optional host-owned memory: Provider, Graph, entry, optional workspace, Facts, the latest Outcome per state key, session authorities, append-only numbered events and timestamps. A checkpoint is a validated copy without authorities; resume copies it to an explicit path, clears authorities and appends an event. No default state directory exists. A graph test (`agent-graph.test.v1`) declares `state` (`facts`, `outcomes`, `authorities`) and `expect` assertions, and never executes Actions or calls a model; see [Testing and Publishing](). `build` validates everything reachable, copies reachable files, writes a normalized `provider.yaml` and a `manifest.json` with catalogs, file digests, the Graph dependency index and an overall digest, excludes tests, refuses to overwrite sources and rejects any file containing the source absolute path. Loading a bundle rejects digest mismatches, missing or extra files, incomplete catalogs, identity mismatches and inconsistent dependency indexes. ## Compatibility Until `@c4a/agent-graph` reaches `1.0.0`, the v1 family is in public draft finalization: a `0.x` release may tighten a required field or invariant, but must document the break and update every shipped template, example and test. `0.2.0` made Action and Gate `reasonCode` mandatory and completed the Skill binding with explicit Graph and Entry fields; `0.3.0` replaced the numbered Resource and Resource Location protocols with separate file, Graph-action and Host-action protocols. After `1.0.0`, incompatible semantics need a new schema version and compatible additions need a defined extension point. Hosts branch on schema identities, status codes, reason codes and diagnostic codes — never on human text. Version-by-version changes are in [Migration](). --- ## Sources - [agent-graph/docs/en/specification.md L1–L3 · 9e8b98a]() - [agent-graph/docs/en/specification.md L402–L406 · 9e8b98a]() - [agent-graph/package.json L1–L4 · 9e8b98a]() - [agent-graph/docs/en/specification.md L5–L41 · 9e8b98a]() - [agent-graph/docs/en/specification.md L43–L82 · 9e8b98a]() - [agent-graph/docs/en/specification.md L84–L105 · 9e8b98a]() - [agent-graph/docs/en/specification.md L107–L135 · 9e8b98a]() - [agent-graph/docs/en/specification.md L137–L170 · 9e8b98a]() - [agent-graph/docs/en/specification.md L172–L202 · 9e8b98a]() - [agent-graph/docs/en/specification.md L204–L252 · 9e8b98a]() - [agent-graph/docs/en/specification.md L252–L276 · 9e8b98a]() - [agent-graph/docs/en/specification.md L278–L309 · 9e8b98a]() - [agent-graph/docs/en/specification.md L311–L328 · 9e8b98a]() - [agent-graph/docs/en/specification.md L330–L367 · 9e8b98a]() - [agent-graph/docs/en/specification.md L369–L400 · 9e8b98a]() - [agent-graph/docs/en/specification.md L402–L410 · 9e8b98a]() --- ## CLI and SDK # CLI and SDK The package `@c4a/agent-graph` (version 0.3.1, Node.js 20 or later) ships one CLI binary, `agent-graph`, an ESM SDK and the public JSON Schemas and templates. All invocation modes run the same bundled CLI: ```bash agent-graph ... # installed binary npx @c4a/agent-graph@0.3.1 ... # npm one-shot bunx @c4a/agent-graph@0.3.1 ... # Bun one-shot node ./agent-graph.mjs ... # single file shipped beside a Provider bundle ``` | Global option | Meaning | | --- | --- | | `-m, --manifest ` | Source Provider manifest or built `manifest.json`; default `provider.yaml` | | `--skill ` | Take Provider, Graph and Entry from a Skill's `agent-graph*` metadata; a conflicting explicit Graph or Entry is rejected | | `--registry ` | Host registry for `provider:` Skill locators | | `--format human\|json` | Concise terminal text (default) or one-line JSON for Agents and automation | | `-V, --version` | Print the CLI version | ## Authoring commands | Command | What it does | | --- | --- | | `init [directory] --id ` | Create a minimal Provider: an agent Action, a bound Skill, a procedure, a Code Catalog and a route test. Refuses to replace any path it would generate | | `import skill --into [--graph ]` | Copy the whole Skill directory, add a relative binding to the copy, create an agent Action and Graph, append it to the Provider and write `IMPORT_REPORT.md` | | `import scripts --into [--graph ]` | Create a sequential Graph from scripts; runtime inferred from the extension, effect defaults to `write` | | `import workflow --into [--graph ]` | Convert a compact `steps` / `dependsOn` workflow into edges with default `join: all`; gates, facts and recovery are listed as gaps in `IMPORT_REPORT.md` | See [Migration]() for how to finish an imported draft. ## Validation and discovery | Command | What it does | | --- | --- | | `validate` | Load the complete reachable Provider and report `valid` or a structured error; no side effects | | `inspect provider` | List Graphs, entries, node counts, dependencies, Actions, Resources and paths | | `inspect skill ` | Show the binding (locator, Provider, `graph#entry`) and resolved Provider; add `--registry` for `provider:` | | `schema list` / `schema path ` / `schema extract --output ` | Discover the public JSON Schemas; `extract` works even from a copied single-file CLI | | `code list` | List the Code Catalog (`route-reason` and `diagnostic` entries) | | `code locate ` | Return the code, summary and optional document location, never the document body | | `test [file-or-directory]` | Run every YAML/JSON graph test recursively; any failure sets a non-zero exit code | | `build [output]` | Write a deterministic bundle, default `dist/provider`; output may sit inside the source tree only if it replaces no referenced source | ## Routing commands `evaluate [graph]` (omit `graph` with `--skill`) accepts: | Option | Meaning | | --- | --- | | `--entry ` | Entry name; default `default` | | `--state ` | Take Facts, Outcomes and authorities from a Run | | `--facts ''` or `--facts @file.json` | Facts, merged over the Run for this invocation | | `--outcomes ''` or `@file.json` | Outcomes, e.g. `'{"release/inspect":"completed"}'` | | `--authority ` | Session authorities | `route [route-id]`, or `--skill route [route-id]`, takes the same options plus: | Option | Meaning | | --- | --- | | `--revision ` | The revision of the preceding Evaluation; a change returns `route-revision-stale` | | `--resource-receipts ''` or `@file.json` | Current-conversation read receipts that set each resource's `readState` | Without `route-id`, the current primary Route is resolved. An unavailable ID returns `route-stale`. Route resolution locates files but never runs commands or materializers; a waiting Gate exposes `gate.inspectionAction` and `gate.resolutionAction` separately from its empty `commandPlan`. ## Run commands ```text run start --state [--workspace ] run status --state run record --state [--detail ] run facts --state --set [--replace] run authority --state [--set ] run checkpoint --state --to run resume --state run events --state ``` `run status` re-evaluates the Graph, so it also needs the Provider options (`--manifest` or `--skill`). `run record` takes the exact key from `route.afterAction.recordNode`, such as `main/work`. `run facts` merges by default and replaces with `--replace`. `run start`, `run checkpoint` and `run resume` refuse to overwrite an existing target (`run-target-exists`). See [Runs and Recovery](). ## Resource commands | Command | What it does | | --- | --- | | `resource locate ` | Return an installed static file and digest, or a materialization reference for a dynamic resource | | `resource materialize --cache --revision ` | Run a read-only command or script materializer and write content-addressed output plus a receipt | | `materialize` option | Default | | --- | --- | | `--workspace ` | Current directory | | `--input ''` or `@file.json` | none | | `--timeout-ms ` | `30000` | | `--max-output-bytes ` | `10485760` | | `--max-error-bytes ` | `1048576` | Pass the revision of the Route that selected the view. A host-action Resource is never run by the CLI and returns `materializer-host-required`. ## Errors With `--format json`, failures go to stderr with a non-zero exit code: ```json { "schema": "agent-graph.error.v1", "state": "error", "error": { "code": "route-stale", "message": "...", "diagnostics": [] } } ``` Branch on `error.code` and diagnostic codes, never on message text. | Area | Codes | | --- | --- | | Routing | `route-revision-stale`, `route-stale`, `route-unavailable` | | Graph validation | `graph-flow-cycle`, `graph-terminal-missing`, `graph-entry-missing`, `graph-edge-node-missing`, `graph-repeat-target-invalid`, `graph-gated-by-source-invalid`, `graph-recursion`, `terminal-outcome-ambiguous`, `route-reason-code-missing` | | Gates | `gate-inspection-effect-invalid`, `gate-resolution-effect-invalid`, `gate-delegated-policy-invalid`, `gate-delegated-inspection-missing` | | Paths and files | `path-outside-provider`, `path-symlink-outside-provider`, `absolute-path-forbidden`, `file-missing` | | Skill binding | `skill-binding-missing`, `skill-graph-missing`, `skill-entry-missing`, `skill-graph-conflict`, `skill-entry-conflict`, `provider-unresolved` | | Runs | `run-target-exists`, `run-provider-mismatch` | | Materialization | `materializer-timeout`, `materializer-output-limit`, `materializer-error-limit`, `materializer-failed`, `materializer-host-required` | | Host results | `host-action-handler-mismatch`, `host-action-input-stale`, `host-action-output-schema-mismatch` | | Bundles | `build-output-overlaps-source`, `build-absolute-path-leak`, `bundle-digest-mismatch`, `bundle-file-digest-mismatch`, `bundle-files-mismatch` | | Tests | `test-path-missing`, `test-cases-empty` | Evaluation problems are reported as diagnostics inside a successful Evaluation rather than as an error envelope: for example `required-fact-missing` (a reached node is blocked by `requiresFacts`), `no-route` (nothing actionable or terminal is reachable) and the informational `route-alternatives-truncated` when more than three alternatives exist. ## SDK ```ts import { evaluateGraph, loadProvider, resolveRoute, resolveSkillBinding } from "@c4a/agent-graph"; ``` | Responsibility | Functions | | --- | --- | | Provider discovery | `readSkillBinding`, `resolveSkillBinding`, `readProviderRegistry`, `loadProvider` | | Routing | `evaluateGraph`, `computeRevision`, `resolveRoute`, `nodeStateKey` | | Resources and codes | `locateResource`, `materializeResource`, `locateCode`, `hostActionInputDigest`, `validateHostActionResult`, `hostActionOutputDigest`, `hostActionResourceReadReceipt` | | Optional Run files | `createRun`, `loadRun`, `recordOutcome`, `updateRunFacts`, `updateRunAuthorities`, `checkpointRun`, `resumeRun` | | Authoring | `initProvider`, `importSkill`, `importScripts`, `importWorkflow` | | Quality and release | `validateSchema`, `runGraphTests`, `buildProviderBundle`, `inspectProvider` | Evaluation and route resolution are side-effect free; only the named authoring, Run, build and materialization functions write files. Paths returned by the SDK are resolved for the current installation while definitions stay relative. `materializeResource` accepts `timeoutMs`, `maxOutputBytes` and `maxErrorBytes`, and a trusted host may add variables with `env` (Agent Graph's own variables take precedence). Errors are `AgentGraphError` instances with `code` and `diagnostics`. The package also exports `./schemas/*` and `./templates/*`. A complete host loop is shown in [Skills and Providers](). --- ## Sources - [agent-graph/docs/en/cli.md L1–L25 · 9e8b98a]() - [agent-graph/package.json L1–L40 · 9e8b98a]() - [agent-graph/docs/en/cli.md L27–L57 · 9e8b98a]() - [agent-graph/docs/en/cli.md L59–L75 · 9e8b98a]() - [agent-graph/docs/en/cli.md L132–L150 · 9e8b98a]() - [agent-graph/docs/en/cli.md L77–L97 · 9e8b98a]() - [agent-graph/docs/en/cli.md L99–L112 · 9e8b98a]() - [agent-graph/src/runStore.ts L26–L32 · 9e8b98a]() - [agent-graph/docs/en/cli.md L114–L130 · 9e8b98a]() - [agent-graph/docs/en/cli.md L152–L168 · 9e8b98a]() - [agent-graph/src/evaluator.ts L200–L210 · 9e8b98a]() - [agent-graph/src/evaluator.ts L316–L324 · 9e8b98a]() - [agent-graph/docs/en/skills-and-providers.md L141–L163 · 9e8b98a]() - [agent-graph/src/index.ts L1–L14 · 9e8b98a]() - [agent-graph/src/errors.ts L1–L13 · 9e8b98a]() --- ## Migration # Migration Agent Graph is pre-1.0: a `0.x` release may tighten a field or invariant, but documents the break and updates every template, example and test. A Provider's own `version` is independent of the `@c4a/agent-graph` package version. | Release | What changed for Provider authors | | --- | --- | | 0.1.0 | Initial specification, SDK, CLI, schemas, templates and examples | | 0.1.1 | Stricter Graph validation and materialization boundaries; explicit Run state and recovery | | 0.2.0 | **Breaking.** Action and Gate nodes require a `route.*` `reasonCode`; Skill bindings need all three metadata fields; a declared Code Catalog is a closed set | | 0.2.1 | Gate `resolutionAction`, which must be able to change observable state | | 0.2.2 | Read-only Gate `inspectionAction`, exposed separately from the resolution plan | | 0.2.3 | Current-conversation read receipts and `readState` on Route resources | | 0.2.4 | Documentation and replay updates to the Context case study | | 0.2.5 | Lifecycle-aware evidence modelled as ordinary revision-bound Facts | | 0.2.6 | Gate `delegated` policies for session-authority Routes | | 0.2.7 | Host-materialized resources with versioned input and output schemas | | 0.3.0 | **Breaking.** Resource identifiers split into three independent v1 protocols | | 0.3.1 | Scaffold, templates and examples declare `compatibility.agentGraph: ^0.3.0`; the 0.3.0 Resource migration is documented | ## Upgrading to 0.2.x 1. Give every Action and Gate node a stable `reasonCode` beginning with `route.`. 2. If the Provider declares `catalogs.codes`, add every one of those codes as a `route-reason` entry, or validation fails with `route-reason-code-missing`. 3. Update every bound Skill to declare all three fields: ```yaml metadata: agent-graph: path:../../provider.yaml agent-graph.graph: release agent-graph.entry: default ``` 4. Validate every Provider before switching hosts to the new runtime. The later 0.2 releases are additive: Gate inspection and resolution Actions, read receipts, delegated policies and host-materialized resources are opt-in. ## Upgrading to 0.3.0 0.3.0 removed the numbered resource identifiers `agent-graph.resource.v1`, `agent-graph.resource.v2`, `agent-graph.resource-location.v1` and `agent-graph.resource-location.v2`; the old names now fail schema validation with `schema-invalid`. Replace them by what the descriptor actually is: | Before | Used for | After | | --- | --- | --- | | `agent-graph.resource.v1` with `path` | A non-Markdown file (schema, template, diagnostic) | `agent-graph.resource.file.v1` | | `agent-graph.resource.v1` with `materializer` | A command or script context view | `agent-graph.resource.graph-action.v1` | | `agent-graph.resource.v2` | A host-materialized resource | `agent-graph.resource.host-action.v1` | | `agent-graph.resource-location.v1` | Resolved file or context-view location | `agent-graph.resource-location.file.v1` or `.graph-action.v1` | | `agent-graph.resource-location.v2` | Resolved host-action location | `agent-graph.resource-location.host-action.v1` | Then raise the Provider's `compatibility.agentGraph` to `^0.3.0` and run `agent-graph validate`; the `examples/host-materialized-resource` example shows a Host-action resource. Markdown resources that carry `id`, `kind` and `media-type` in frontmatter are unaffected. Hosts that read Route resources should branch on the new location schema names; the host-action input and output ABI and its recovery rules are unchanged. ## Importing an existing Skill ```bash agent-graph init ./provider --id product-workflow agent-graph import skill ../legacy-skill/SKILL.md --into ./provider --graph legacy-capability agent-graph --manifest ./provider/provider.yaml validate ``` The importer copies the whole Skill directory to `skills//`, adds the Provider, Graph and Entry binding to the copied `SKILL.md` and creates one agent Action and one Graph. The original instructions are preserved, not split into guessed phases, and the source Skill is left untouched. ## Importing scripts and workflows ```bash agent-graph import scripts ./inspect.sh ./package.sh --into ./provider --graph package-flow agent-graph import workflow ./workflow.yaml --into ./provider ``` - **Scripts** become a sequential Graph. The extension selects Node, Bun, Python or shell; the effect defaults to `write`, because the importer cannot know which scripts are read-only or external. - **Workflows** use a compact shape — `id` plus `steps` with `id`, `command`, `effect` and `dependsOn`. The importer checks step shapes, missing dependencies, ID collisions and cycles before writing anything, turns dependencies into edges (fan-in uses `join: all`), adds a start Action and a Terminal after the leaves, and registers a reason code per step. Topology does not mean parallel execution. Templating, expressions, secrets, matrices and vendor retry policies are not interpreted. Every import appends a section to `IMPORT_REPORT.md` beside `provider.yaml` and refuses to replace an existing Graph, Action, script directory or copied Skill. The report lists what must not be guessed — effects, Outcomes, recovery, Gates, resources and fact-backed completion. Treat it as an authoring checklist, then remove or archive it per your repository policy. ## Finishing the draft Review the imported Provider for: - which operations are separate Actions; - which resources are needed by only one Route; - each Action's effect (`read`, `write`, `external`); - human Gates and whether delegation is allowed; - Facts that prove success; - `failed`, `partial`, `unverified` and recovery transitions; - stopping conditions for repeated work. For a large Skill, change it in small, testable steps: 1. Import without changing the source Skill. 2. Validate the generated Provider. 3. Add one graph test for today's happy path. 4. Extract deterministic commands into Action files. 5. Move long phase-specific instructions into Route resources. 6. Add Facts and `satisfiedBy` before trusting recorded success. 7. Add explicit Gates and failure and recovery Outcomes. 8. Add loop tests if work can repeat. 9. Build and test the relocatable bundle. 10. Only then replace the original Skill with a thinner bound entry. Not every paragraph should become a node: nodes are independently actionable, gated, recoverable or testable transitions, and the rest stays a Resource. See [Authoring Graphs]() and [Testing and Publishing](). --- ## Sources - [agent-graph/CHANGELOG.md L1–L74 · 9e8b98a]() - [agent-graph/docs/en/specification.md L402–L406 · 9e8b98a]() - [agent-graph/docs/en/migration.md L17–L25 · 9e8b98a]() - [agent-graph/CHANGELOG.md L59–L63 · 9e8b98a]() - [agent-graph/CHANGELOG.md L12–L16 · 9e8b98a]() - [agent-graph/docs/en/specification.md L204–L276 · 9e8b98a]() - [agent-graph/docs/en/migration.md L5–L15 · 9e8b98a]() - [agent-graph/docs/en/migration.md L27–L37 · 9e8b98a]() - [agent-graph/docs/en/cli.md L29–L35 · 9e8b98a]() - [agent-graph/docs/en/migration.md L49–L69 · 9e8b98a]() - [agent-graph/docs/en/cli.md L37–L57 · 9e8b98a]() - [agent-graph/docs/en/migration.md L39–L47 · 9e8b98a]() - [agent-graph/docs/en/migration.md L71–L84 · 9e8b98a]() --- ## Contributing # Contributing Context and Agent Graph are developed in the open on GitHub, in [context4ai/context](https://github.com/context4ai/context) and [context4ai/agent-graph](https://github.com/context4ai/agent-graph). Both welcome bug reports, documentation, tests and implementation changes. Common ways in: - **Report a defect** with a minimal, sanitized reproduction through the issue templates. - **Improve the documentation.** This site is built from [context4ai/portal](https://github.com/context4ai/portal); package references live in each project's repository. - **Share an Indexer** that teaches Context to read a new kind of source; see [Creating an Indexer]() and [Community Indexers](). - **Add a language extractor** under Context's `packages/extract-*`, following the `@c4a/extract` protocol. - **Propose an Agent Graph protocol change or example.** Newcomers start with [Why Graph Engineering](), [Authoring Graphs]() and the repository's `getting-started` example. The two projects follow the same rhythm: 1. Search existing Issues and Discussions first. 2. Discuss anything that changes a public contract before writing it. Small documentation fixes and isolated bug fixes can go straight to a pull request. 3. Develop with Bun, keep runtime code working on Node.js 20 or later, and run the project's verification command. 4. Open a focused pull request that explains the problem, the behavior you chose, the compatibility impact and how you verified it. Never report a security vulnerability in a public Issue; see [Support]() for private reporting. | | Context | Agent Graph | | --- | --- | --- | | Discuss first | Workspace protocols, lifecycle ordering, public CLI JSON, package layout | Protocol changes, new public fields, compatibility behavior | | Verification | `bun run verify:full` | `bun run verify` | | Developer guide | `DEVELOPMENT.md` | `DEVELOPMENT.md` | ## Context ```bash git clone https://github.com/context4ai/context.git cd context bun install bun run build bun run verify ``` `bun run verify` runs type checking, lint and the default tests; `verify:full` adds the full-only CLI tests and checks of the built Node artifacts, so build first. `DEVELOPMENT.md` in the repository covers the repository layout, running a local CLI and plugin, verification scopes and releases. A pull request is ready for review when: - `bun run verify:full` passes; - lifecycle behavior comes with Route and recovery coverage; - the CLI does not make semantic decisions that belong to the Agent or the user; - tests use neutral fixtures rather than business-specific content; - English and Simplified Chinese user documentation still describe the same behavior; - user-visible changes have an entry under the next version in `CHANGELOG.md`; - no generated `dist/`, workspace data, snapshots, credentials or private source material is committed. Write commit messages as English conventional commits that name the target version, for example `fix(v0.7.62): exempt More menu targets from knowledge map coverage`. Maintainers release by creating a GitHub Release whose tag matches the package version; the publish workflow verifies and publishes every package through npm Trusted Publishing. ## Agent Graph ```bash git clone https://github.com/context4ai/agent-graph.git cd agent-graph bun install bun run verify ``` `bun run verify` runs type checking, lint, the tests and the build. Use GitHub Discussions for design or adoption questions and ideas that are not yet actionable. `DEVELOPMENT.md` describes the source layout, protocol rules, testing principles and the release audit. A pull request is ready for review when: - `bun run verify` passes; - public TypeScript types and JSON Schemas agree; - protocol behavior has unit or integration coverage, and at least one published example covers new protocol behavior; - English and Simplified Chinese documentation still describe the same behavior; - runtime code uses standard Node.js APIs rather than Bun-only APIs; - no generated `dist/`, `.tmp/`, coverage or package archive files are committed. Write commit messages as English conventional commits, with the project version when practical: ```text feat(v0.3.0): add route inspection metadata fix(v0.2.2): reject stale evaluation revisions docs(v0.3.0): clarify provider adoption paths ``` Maintainers may ask for changes that preserve protocol portability, deterministic behavior or documentation parity. To test a Graph change end to end, see [Testing and Publishing](). ## Fixing this documentation Every article on this site ends with its sources, linked to the exact repository revision it was written from. If an article is wrong because the documentation or code it cites is wrong, fix it in that repository. Both projects keep English and Simplified Chinese documentation equivalent, so update both languages in the same pull request. Participation in both projects is governed by their Code of Conduct. --- ## Sources - [context/CONTRIBUTING.md L1–L32 · 3b0ce0a]() - [agent-graph/CONTRIBUTING.md L1–L16 · 9e8b98a]() - [context/CONTRIBUTING.md L34–L68 · 3b0ce0a]() - [context/CONTRIBUTING.md L70–L84 · 3b0ce0a]() - [context/DEVELOPMENT.md L356–L365 · 3b0ce0a]() - [agent-graph/CONTRIBUTING.md L7–L55 · 9e8b98a]() - [agent-graph/package.json L65–L65 · 9e8b98a]() - [context/CONTRIBUTING.md L9–L17 · 3b0ce0a]() - [agent-graph/CONTRIBUTING.md L37–L55 · 9e8b98a]() - [context/packages/context/docs/guides/package-outputs.md L174–L174 · 3b0ce0a]() --- ## Release Notes # Release Notes These notes summarize recent product releases by what readers and Agents notice. The complete history is in the [Context CHANGELOG](https://github.com/context4ai/context/blob/main/CHANGELOG.md) and the [Agent Graph CHANGELOG](https://github.com/context4ai/agent-graph/blob/main/CHANGELOG.md). The site's own **Changelog** entry in the More menu is different: it lists the versions of this documentation, not product releases. To upgrade Context, run the same two commands as a first installation — `npm install -g @c4a/context-cli@latest` and `context plugin install` — and restart the Agent session; see [Installation](). An active knowledge workspace needs no migration step: the next `context status` returns a fresh Route for the upgraded CLI, and workflow read receipts are kept when a task resumes. ## Context 0.7.62 (2026-10-13) - An approved article that a More menu item targets no longer needs a knowledge map entry: package builds, knowledge map adjustments and structure approval accept it, and review reports no longer list it as unplaced. - The repository README and the contributing, support and development guides link to this documentation site and describe the Context ecosystem. ## Context 0.7.61 (2026-10-12) **Knowledge websites** - The reader's saved light or dark choice is applied from the first paint, so pages no longer flash the system scheme while loading. - A reader language that leaves homepage fields unset inherits the site's own homepage title, slogan, description and actions instead of falling back to defaults. - Unknown addresses show a centred 404 page in the reader's language with a link back home. - Diagrams render in a single frame in both offline Review and websites; edge labels are smaller and centred on their edge, and subgraph titles no longer touch the border. **Planning** - Broad version updates compare the cited repository files by Git object ID before reading content and fetch partial-clone objects in one batch, avoiding long stalls. ## Context 0.7.60 (2026-10-08) **Multilingual websites** - `site.locales` publishes one website in several languages. Translations live under `translations//`, remember which approved version they were written from, and show a notice when stale or missing. - `context translate status|prepare|submit|skip` validates sections, code blocks and links; translation is a workspace Route step before the version is recorded, and it counts toward package freshness with a new `translation` changelog trigger. **Site navigation** - `site.nav`, `site.more` and `site.socialLinks` add top links, More menu items and social icons. A More menu item may target an approved article kept outside the knowledge map — as this page is — and root-relative paths can link to sibling applications on the same domain. See [Multilingual Sites]() and [Documentation Sites](). ## Context 0.7.50 (2026-10-03) **Same-repository content** - Register a repository's own documentation and authored Skills without copying their bodies into knowledge, with safe relative symlink entrances; see [Same-Repository Docs](). - The evidence plugin and local or remote queries understand these references, including incomplete symlink-index coverage. **Evidence and builds** - Evidence keeps historical repository paths and commits, detects relocated document regions, and notices changes anywhere in a Skill directory. - Optional repository entrance pages, original-source links, localized navigation and offline build fallbacks. - Invalid registrations stay advisory with repair guidance, and invalid build inputs are rejected without replacing the previous output. ## Context 0.7.40 – 0.7.43 (2026-09-29 to 2026-10-01) These releases made remote code evidence part of normal querying: - **0.7.40** — queries can use optional read-only remote code evidence at the recorded repository baselines before retrieving unavailable local sources, preserving fixed commits, returned line ranges, partial batch results and permission boundaries. - **0.7.42** — approved knowledge and recorded code evidence can be read remotely without a checkout. The CLI bundles a read-only repository Wasm plugin that attaches section evidence and commit-specific source URLs, installed with `context evidence install` or at workspace initialization. - **0.7.43** — the plugin moves to ABI 2 and attaches compact references to individual read items without replacing their content; remote query guidance follows bounded default reads, file-only search and per-file match limits. Local and offline retrieval keep working throughout. See [Reading Code Evidence Remotely](). ## Context 0.7.35 – 0.7.36 (2026-09-22) - **Planning for large projects.** The `context-plan` Skill researches a project or a broad source update, hands one stage at a time to production, and recovers from a Git-backed plan. A stage is recommended at thirty documents and capped at fifty, with one newly researched repository per stage; broad discovery needs scope confirmation, and more than five hundred documents needs a person. See [Planning Large Projects](). - **Delegated review.** A task can delegate plan and article review while human review stays the default and authorization boundaries are kept; see [Managed Mode and Review Policy](). - **Document capture.** Online document snapshots can be fetched without a workspace and imported later; directory discovery is resumable, and registrations are staged with checkpoints, status, replay and cancellation. - **Review reports** list unplaced articles with navigation recovery guidance. Releases before 0.7.35 are listed in the full CHANGELOG. ## Agent Graph **0.3.1 (2026-10-13)** raises the `compatibility.agentGraph` range in the scaffold, templates and examples to `^0.3.0`, documents the 0.3.0 Resource protocol migration, and links the repository guides to this site. **0.3.0 (2026-08-31)** is a breaking release for Provider authors. The Resource v1/v2 split is replaced by three independent v1 protocols — file, Graph-action and Host-action resources and their locations — and the former `agent-graph.resource.v1`, `.v2`, `agent-graph.resource-location.v1` and `.v2` identifiers are removed. The Host Action input, output and recovery interface is unchanged, but each materialization authority is now explicit in serialized Routes and SDK types. Follow [Migration]() to rename the protocols in an existing Provider. The 0.2 line built the contract that 0.3.0 renamed: | Release | Main addition | | --- | --- | | 0.2.7 | Host-materialized resources with versioned input and output schemas and pre-dispatch Provider validation | | 0.2.6 | Gate-owned delegated execution policies | | 0.2.5 | Lifecycle-aware evidence as ordinary revision-bound Facts | | 0.2.3 | Resource read receipts for the current conversation | | 0.2.1 – 0.2.2 | Gate resolution and read-only Gate inspection Actions | | 0.2.0 | Fact-grounded routing contracts and catalog-backed reason codes | 0.1.0 (2026-07-22) published the first specification, SDK, CLI, schemas, templates and examples. For what these terms mean, see [Core Model](). --- ## Sources - [context/CHANGELOG.md L1–L3 · 3b0ce0a]() - [context/CHANGELOG.md L53–L58 · 3b0ce0a]() - [context/README.md L45–L53 · 3b0ce0a]() - [context/CHANGELOG.md L5–L8 · 3b0ce0a]() - [context/CHANGELOG.md L10–L16 · 3b0ce0a]() - [context/CHANGELOG.md L18–L23 · 3b0ce0a]() - [context/CHANGELOG.md L25–L31 · 3b0ce0a]() - [context/CHANGELOG.md L33–L51 · 3b0ce0a]() - [context/CHANGELOG.md L53–L75 · 3b0ce0a]() - [agent-graph/CHANGELOG.md L1–L16 · 9e8b98a]() - [agent-graph/CHANGELOG.md L18–L65 · 9e8b98a]() - [agent-graph/CHANGELOG.md L67–L74 · 9e8b98a]() --- ## Support # Support Pick the channel that matches the request: | Need | Context | Agent Graph | | --- | --- | --- | | Usage, integration or design question | [Discussions](https://github.com/context4ai/context/discussions) | [Discussions](https://github.com/context4ai/agent-graph/discussions) | | Reproducible defect | [Bug report](https://github.com/context4ai/context/issues/new/choose) | [Bug report](https://github.com/context4ai/agent-graph/issues/new/choose) | | Suspected vulnerability | [Private report](https://github.com/context4ai/context/security/advisories/new) | [Private report](https://github.com/context4ai/agent-graph/security/advisories/new) | Agent Graph Discussions also take ideas that are not yet actionable. Both projects point to this site first, and the answer is often already here: [Installation]() for setup checks, [Asking Questions]() for querying knowledge, and the [FAQ](). ## Check before reporting - **Installation.** `context --version` and `context plugin status` confirm the CLI and the host plugins. If an entry is present but the `context` executable is missing, the entry names the installation step to run. - **Workflow state.** `context status --format json` shows the current Route, its reason code and diagnostics. Resume from that Route rather than repeating an earlier command. - **Traces.** `context debug enable` records workspace-local traces under `.tmp/context-runtime/debug/`, and `context debug export` builds a replay you can inspect; see [CLI Commands](). - **Agent Graph.** `npx @c4a/agent-graph validate --format json` loads the whole Provider and returns a structured error without side effects, and the Graph tests replay Routes without a host, which makes a minimal reproduction easy to share; see [Testing and Publishing](). ## What to include in a bug report | Context | Agent Graph | | --- | --- | | Context version (`context --version`) and installation mode | Agent Graph version | | Node.js and Bun versions | Node.js and Bun versions | | The Agent host, such as Claude Code, Codex or Cursor | | | The command or entry you ran | The command you ran | | Sanitized diagnostic output | The complete error output, secrets removed | | | A minimal Provider or Graph, when possible | Keep private material out of public Issues. For Context, do not publish source documents, review payloads, credentials, private paths or knowledge generated from a private workspace; reduce the case to neutral content instead. ## Security Do not open a public Issue for a suspected vulnerability. Both projects use GitHub's private vulnerability reporting (links above). Include: - the affected version and component; - reproduction steps or a proof of concept; - the security impact; - any suggested mitigation; - whether the issue has been disclosed elsewhere. Context applies security fixes to its latest published release; Agent Graph, which is pre-1.0, applies them to its latest published minor line, so upgrade before reporting if you can. Agent Graph maintainers aim to acknowledge a report within five business days and, after validation, coordinate the fix, disclosure timing and credit with the reporter. In scope are unsafe file access, command execution, path traversal, credential or source disclosure, authority and trust-boundary bypasses, integrity failures of packages and build artifacts, and — for Context — review-gate bypasses. Vulnerabilities can be in any published part: the CLI, SDK, extractors, plugins, schemas or artifacts. General questions and ordinary bugs belong in Discussions or Issues. --- ## Sources - [context/SUPPORT.md L1–L13 · 3b0ce0a]() - [agent-graph/SUPPORT.md L1–L8 · 9e8b98a]() - [context/SECURITY.md L7–L9 · 3b0ce0a]() - [context/packages/context-cli/README.md L212–L219 · 3b0ce0a]() - [context/packages/context-cli/README.md L73–L76 · 3b0ce0a]() - [agent-graph/docs/en/cli.md L59–L64 · 9e8b98a]() - [context/SUPPORT.md L15–L19 · 3b0ce0a]() - [agent-graph/SUPPORT.md L10–L10 · 9e8b98a]() - [context/SECURITY.md L1–L19 · 3b0ce0a]() - [agent-graph/SECURITY.md L1–L30 · 9e8b98a]()