Skip to main content
Glama
README.md
# ContextForge

ContextForge is a local-first context retrieval and optimization engine for AI coding agents. It searches Markdown and returns exact excerpts with citations. The CLI and MCP server work independently of Obsidian. Keyword search runs offline after installation, and optional semantic and hybrid search run offline after a one-time model download.

## Get started

Use Node.js 22.20 or newer with npm. Extract the source archive or clone the repository, then run these commands from its root.

```sh
npm ci --ignore-scripts
npm run build
node packages/cli/bin/contextforge.js search "deployment checklist" --vault "./notes"
```

`--ignore-scripts` skips ONNX Runtime's optional CUDA download. The CPU runtime comes with the npm packages. Replace `./notes` with your Markdown directory.

## Install the Obsidian desktop plugin

1. Use Obsidian Desktop 1.15.0 or newer. Download the three plugin assets from the release, or build them from source.
2. In your chosen vault, create `.obsidian/plugins/contextforge/`. If your vault has a custom configuration folder, use it in place of `.obsidian`.
3. Copy `main.js`, `manifest.json`, and `styles.css` into that folder. A source build puts them in `packages/obsidian/dist/`. The installed plugin needs no separate Node.js or npm installation.
4. Open **Settings → Community plugins**, turn on community plugins if needed, reload the list, and enable **ContextForge**. Use **ContextForge → Open sidebar** in the command palette or the ContextForge ribbon button.

Enter a task and choose a budget, retrieval mode, and context preset. Open an excerpt to see the original Markdown and why it was chosen. Select a citation to open the source note at its cited line. Conflicts show both sources, and the budget can overflow to keep required notes and protected conflict evidence. **Copy context** and **Export Markdown** recheck the current vault before producing cited Markdown. Markdown export uses the desktop download flow.

The original token count sums eligible full note bodies. The optimized count includes exported citations and warnings. Both use the local `o200k_base` tokenizer. Actual agent token usage depends on its tokenizer and message format.

In **Settings → ContextForge**, list exact root-relative paths for mandatory notes and authorized project rules. Ordinary excerpts and mandatory notes remain untrusted. Set folder globs, file globs, and extra sensitive-file exclusions before building the index. The engine always excludes notes marked with front-matter `sensitive: true` or a `#sensitive` tag. The plugin also excludes vault configuration and Git folders. Exact excerpts can still contain references to excluded notes when the references are written in an eligible note. Indexing and the two cache-clearing controls leave source notes untouched.

Keyword mode is the default. To enable Semantic or Hybrid, use **Install model** in ContextForge settings. It downloads and verifies about 35 MB of pinned BGE-small assets from Hugging Face without sending vault text. The worker runs subsequent inference locally with bundled CPU WebAssembly. Indexes and model assets live under `~/.contextforge/obsidian/` outside the vault. The plugin stores settings in the vault plugin's `data.json`. Syncing or sharing that configuration may share the paths and exclusion patterns it contains.

To connect an agent, expand **Connect an AI agent through MCP** and use **Copy vault MCP settings**. Save the JSON yourself and follow the client steps below using the built MCP launcher. The plugin leaves client configuration untouched. [Obsidian Community Plugin requirements](https://docs.obsidian.md/community-directory/submission-requirements-for-plugins)

To reproduce the desktop smoke test on Windows, build the plugin, then run the following command with Obsidian closed. The harness creates a temporary profile, cache and synthetic vault. The optional `--model-dir` argument points to an existing verified model and adds semantic and hybrid verification.

```powershell
node packages/obsidian/test/desktop.mjs --exe "C:/Program Files/Obsidian/Obsidian.exe" --screenshots .contextforge/obsidian-screenshots
```

## Connect an MCP client

Save a server settings file at a location you control, for example `contextforge-mcp.json`. Replace the vault path with the folder you intend to expose to the client. Relative paths resolve from the settings file's directory. Keep an existing MCP client configuration and add just the ContextForge entry when you are ready to enable it.

```json
{
  "toolProfile": "task",
  "vaults": [
    {
      "id": "project",
      "path": "/absolute/path/to/notes",
      "mode": "keyword",
      "context": "balanced",
      "tokenBudget": 1200,
      "maxTokenBudget": 4096,
      "excludeFolders": [".obsidian", "private"],
      "excludeFiles": ["**/*.secret.md"],
      "projectRules": ["policies/release.md"]
    }
  ]
}
```

Adjust `projectRules` to the exact root-relative Markdown files you explicitly authorize, or omit it. Use `mandatoryNotes` for required documents that should remain untrusted. Optional `sourcePriorities` accept `{ "pattern": "decisions/**", "weight": 2 }`. Omit the token budget to follow the preset. With multiple disjoint roots, use their distinct `id` values as the `vault` tool argument.

For **Codex**, add this entry to the applicable Codex `config.toml`. Restart the client session and check `codex mcp list` or `/mcp`. [Codex MCP setup](https://learn.chatgpt.com/docs/extend/mcp?surface=cli)

```toml
[mcp_servers.contextforge]
command = "node"
args = ["/absolute/path/to/ContextForge/packages/mcp/bin/contextforge-mcp.js", "--config", "/absolute/path/to/contextforge-mcp.json"]
```

For **Claude Code**, run the following from the project you want to configure. Use `claude mcp get contextforge` to check the connection. [Claude Code MCP setup](https://code.claude.com/docs/en/mcp#option-3-add-a-local-stdio-server)

```sh
claude mcp add --transport stdio --scope local contextforge -- node "/absolute/path/to/ContextForge/packages/mcp/bin/contextforge-mcp.js" --config "/absolute/path/to/contextforge-mcp.json"
```

For **Cursor**, merge this entry into the project's `.cursor/mcp.json` or your user MCP configuration. The same command and arguments work in other stdio hosts.

```json
{
  "mcpServers": {
    "contextforge": {
      "command": "node",
      "args": ["/absolute/path/to/ContextForge/packages/mcp/bin/contextforge-mcp.js", "--config", "/absolute/path/to/contextforge-mcp.json"]
    }
  }
}
```

On Windows, use absolute paths such as `C:/work/ContextForge/packages/mcp/bin/contextforge-mcp.js`. Use an absolute Node executable path for hosts launched without Node on their PATH. Point hosts at the built JavaScript launcher directly so npm and build logs stay off the protocol stream.

After connecting, try asking your agent to use ContextForge to find a phrase from a known note and cite its source. Indexing and retrieval run locally. Your MCP client controls whether the returned excerpts are sent to a model provider.

### MCP tools and limits

For coding sessions focused on project evidence, use top-level `"toolProfile": "task"` in the server configuration. Start with one `search_context` call. It already includes eligible authorized rules and mandatory evidence. Its `notes` map labels each cited path `complete` or `partial`. Reuse complete notes unless you need to verify or refresh them. Use `expand_context` or `get_note` for missing evidence or surrounding text. The task profile uses the configured retrieval mode and preset, with an optional per-call token target. Use the default `"full"` profile for index administration or the separate change and rules tools.

Optional client-side guidance helps when a host ignores the server's instruction field. For project documentation, use ContextForge once, reuse cited evidence already retrieved, and open files or expand when a specific gap remains. Use normal tools for source code and tests.

For an operator-enforced per-call target, set the vault's `tokenBudget` and `maxTokenBudget` to the same value. Higher search or expansion requests return `budget_exceeded`. Required evidence can still overflow, and direct note access has its own size limit. [Budget behavior and local replay](benchmarks/README.md#evidence-budget-override)

- For a task-profile update, pass `contextId` and `retained`, listing only excerpt IDs whose full text is still accessible. Apply `removed` to discard withdrawn blocks. When `order` is present, use it to merge the returned excerpts with retained excerpts. The `notes` map describes that merged result.
- To recover after compaction, a reset, or any uncertainty about retained text, call `search_context` with the original query and omit `retained`. You may also omit the receipt to start fresh. An expired receipt with a query returns a full result. The server does not infer retention from a receipt alone. Use `get_note` for a fresh complete permitted note, subject to the existing note size limit and line-range fallback.
- In the task profile, `expand_context` with a valid receipt and retained blocks adds optional evidence within its per-call budget. Omit `retained` for a self-contained expanded result. Raise the token target if necessary. Coverage labels and delta ordering count toward response overhead outside the evidence budget.

The following tools and overrides are available in the full profile.

- `search_context` takes a `query` and optional `tokenBudget`, `context` or `mode`. It returns excerpts, exact root-relative citations, conflicts, a budget summary and a `contextId`. When keyword evidence has no non-filler overlap, it returns `no_relevant_context` and still includes eligible required material. Retry with different terms, use `includeWeak: true`, or choose a configured embedding mode.
- `expand_context` takes a `contextId` to find new evidence. `get_changes` takes a `contextId` to return added blocks and opaque withdrawn IDs. Apply withdrawals before reusing prior context and follow the returned `order` for changes. IDs expire after 30 minutes or after a restart. Supply the original `query` to `get_changes` for a full reset when a receipt is lost.
- `get_note` takes a root-relative `path` and optionally an exact `heading` or inclusive `startLine` and `endLine`. Large notes return `range_required`; specify a narrower range or configure `maxNoteBytes`. `get_project_rules` returns only eligible notes from the explicit authorization list.
- `get_index_stats` reports aggregate counts, settings, generation and refresh count. `refresh_index` forces a complete byte check and updates the managed cache. It leaves source files untouched.
- The default wire format is one compact JSON text block. Set top-level `"responseFormat": "structured"` for hosts that consume MCP `structuredContent`. Budget usage counts serialized evidence and citations. Request and response framing adds a small overhead. Required rules and conflict pairs can exceed the target and report overflow.
- For offline embeddings, provision the pinned model as described below, then add `"embeddings": { "modelDirectory": "/absolute/path/to/model" }` to the vault settings. Choose `semantic` or `hybrid` per call or as the vault default. Standard BGE inference stays local. A host may transmit tool results to the model provider it uses.

## Use the CLI

Run these commands from the repository root. Replace `./notes` with the source directory.

```sh
npm exec --offline -- contextforge index --vault ./notes --exclude-folder .obsidian
npm exec --offline -- contextforge stats --vault ./notes --exclude-folder .obsidian
npm exec --offline -- contextforge search "queue failover" --vault ./notes --limit 10
npm exec --offline -- contextforge export "queue failover" --vault ./notes --budget 800 --mandatory policies/release.md
npm exec --offline -- contextforge inspect runbooks/queue.md --vault ./notes
```

- `index` and `stats` refresh the snapshot and report file counts, section counts, bytes and cache activity. The CLI keeps one cache per source root under `~/.contextforge/indexes` by default. Override it with `--cache`.
- `search` returns JSON with exact excerpts, citations, document status, trust labels, conflict warnings, expansion signals and omission reasons. Search has no token cap unless supplied. Use `--limit` or `--budget` to override the preset for optional context.
- `export` writes rendered context to standard output and the JSON report to standard error. The default token target comes from the context mode. Counts include trust labels, citations, warnings and separators.
- Repeat `--mandatory` to require whole eligible notes as data. Repeat `--project-rule` to require and explicitly authorize eligible rules. Missing or excluded required notes and token overflow return status 2 while available required content is returned.
- `inspect` outputs a complete eligible note, including original line endings and any BOM. Pass the same global exclusions used for indexing. It rejects excluded and sensitive sources, path traversal, symlinks, junctions and hard-linked files.
- `--exclude-folder` and `--exclude-file` accept repeatable root-relative literal paths or Node glob patterns using forward slashes. Pass the same exclusions to each command that uses the index. The engine includes `.md` and `.markdown` files recursively, including uppercase extensions.

## Choose a context mode

The context mode controls breadth independently of `--mode keyword|semantic|hybrid`. BM25 and balanced context are the defaults.

- **Efficiency** defaults to a 1,024-token export target, 5 optional selection slots before expansion to 7, and up to 2 linked candidates over 1 hop.
- **Balanced** defaults to 2,048 tokens, 10 slots before expansion to 15, and up to 6 linked candidates over 2 hops when signals warrant it.
- **Thorough** defaults to 4,096 tokens, 18 slots before expansion to 28, and up to 12 linked candidates over 3 hops.

The slot limits apply to total selected sections when fitting optional excerpts. Mandatory notes and selected conflict evidence may exceed a limit. Use `--linked-limit`, `--link-depth`, or `--no-links` for tighter control. The report names signals such as weak literal coverage or competing sources. Scores and signals describe the retrieval evidence and have no probability interpretation.

Use YAML frontmatter `status: active`, `deprecated`, `archived` or `superseded`. Set `topic` and `decision` when multiple notes discuss the same decision. Use `supersedes` or `superseded-by` with root-relative note paths. A potential conflict returns both citations and protects the first 1, 2 or 4 pairs respectively. Ordering by declared lifecycle or supersession is a review aid. The excerpts remain evidence for the reader to evaluate.

```sh
npm exec --offline -- contextforge export "queue failover" --vault ./notes --context thorough --source-priority "decisions/**=2" --project-rule policies/release.md --exclude-folder private
```

Source priorities use the first matching pattern with a weight from −3 to 3. Ordinary indexed text stays untrusted, even when marked mandatory or when it resembles project instructions. Consumers that distinguish trust programmatically should use the structured `search` output and its `trust` field. Ordinary Markdown cannot authorize itself.

## Export changes

```sh
npm exec --offline -- contextforge export "queue failover" --vault ./notes > context.txt 2> receipt.json
npm exec --offline -- contextforge export "queue failover" --vault ./notes --since receipt.json > changes.txt 2> next-receipt.json
```

The report records a vault-scoped manifest of ordered content hashes, the additions in output order with their UTF-8 byte lengths, and opaque IDs to remove. Apply removals before reusing prior context. Missing, invalid or foreign receipts produce a full export. Use `--full` whenever the receiving system may have lost prior blocks. Receipts store hashes only in the manifest. The surrounding report contains citations from the invocation that produced it and remains caller-owned.

## Enable offline semantic search

Keyword BM25 is the default. Choose `--mode semantic` for cosine ranking or `--mode hybrid` for reciprocal rank fusion. The model setup command downloads four pinned artifacts totaling about 35 MB into a dedicated model directory and verifies their checksums. Only model setup needs network access.

```sh
npm exec --offline -- contextforge model download --model-dir ./.contextforge/model
npm exec --offline -- contextforge index --vault ./notes --mode hybrid --model-dir ./.contextforge/model --exclude-folder private
npm exec --offline -- contextforge export "recover from a poisoned job" --vault ./notes --mode hybrid --model-dir ./.contextforge/model --exclude-folder private --budget 800
```

- The default model directory is `~/.contextforge/models/bge-small-en-v1.5`. A verified directory can be copied to an offline machine. Repeat downloads reuse verified files. Use an empty model directory if an existing file fails verification.
- `--embedding-exclude-folder`, `--embedding-exclude-file`, and `#no-embed` apply to vector indexing. Global path exclusions, `sensitive: true`, and `#sensitive` tags including nested tags exclude the whole note from all ContextForge access paths. Repeat configured path exclusions on each invocation. Sensitive classifications and missing notes are checked on refresh before serving current context.
- Retrieval chunks default to 900 UTF-16 code units at paragraph or line boundaries where possible. Use `--chunk-chars` to adjust the cap. A split physical line has column citations. Embedding windows use the smaller of the configured character cap and BGE's 440-code-unit cap. A tokenizer check rejects oversized windows rather than silently dropping their tails.
- Tunable defaults are 5,000 retrieval chunks, 32 MiB of Float32 vector payload, eight inputs per batch, and two CPU threads. Use `--embedding-max-sections`, `--embedding-memory-mib`, `--embedding-input-chars`, `--embedding-batch-size`, and `--embedding-threads`. Batches that cannot fully cover a chunk are reported as skipped. Native inference uses additional RAM.
- Semantic and hybrid commands report embedded, reused, split and skipped entries. A vault refresh drops the old vector snapshot if files are revoked by global policy or receive a new embedding opt-out. Exclusion changes cannot erase an export or a copy already held by a caller.

## Use the engine

```js
import { createRetrievalIndex, indexMarkdown, readSourceNote } from "@contextforge/engine";

const { sourceRoot, files } = await indexMarkdown("./notes", {
  cacheDirectory: "./.contextforge",
  excludeFolders: [".obsidian", "**/archive"],
  excludeFiles: ["private.md", "**/*.draft.md"],
});
const index = createRetrievalIndex(files);
const result = index.search("queue failover", { tokenBudget: 800, maxSections: 10 });
const original = await readSourceNote(sourceRoot, "runbooks/queue.md");
```

The engine also exports `discoverMarkdown`, `extractSections`, `chunkSections`, `renderContext`, `countContextTokens`, and `incrementalExport`. The in-memory retrieval index can serve multiple queries over an admitted snapshot. Rebuild it after source or policy changes. Pass the same exclusions to direct `readSourceNote` calls.

For semantic ranking, use `createBgeEncoder(modelDirectory)` and `buildSemanticIndex(snapshot, encoder, options)`. Pass `{ mode: "hybrid", similarities: await semantic.similarities(query) }` as the optional third argument to `index.search`, using the same snapshot for both indexes. Call `await encoder.dispose()` when finished.

## Reproduce the benchmark

```sh
npm run benchmark -- --projects=12 --rounds=5 --budget=240
npm run benchmark -- --projects=3 --rounds=5 --budget=240
npm run benchmark:semantic -- --model-dir ./.contextforge/model --rounds 5 --budget 190
npm run benchmark:semantic -- --corpus held-out --model-dir ./.contextforge/model --rounds 5 --budget 280
npm run benchmark:mcp -- --model-dir ./.contextforge/model
```

The benchmarks generate temporary vaults and emit per-query results. The held-out benchmark runs all three context presets and three rankers. Add `--baseline-engine <Phase-3-dist/index.js>` to compare with a built Phase 3 engine that can resolve its dependencies. The semantic harness measures each variant in a separate process with network fetches blocked. To run the real-model regression test, set `CONTEXTFORGE_TEST_MODEL_DIR` to a verified model directory before running `npm test`.

To repeat the isolated Codex verification after building, run `node packages/mcp/bench/codex-smoke.mjs`. Pass the path to the Codex executable as the first argument when it is off PATH. The script starts a temporary Codex app-server session, lists the tools, calls `search_context`, and uses a synthetic vault.

For Phase 7, run `node benchmarks/scale.mjs --model-dir .contextforge/model` after building to measure vaults with 100 through 10,000 notes. Run `node benchmarks/pilot.mjs --self-check` to validate the acceptance tests and estimate the proposed six-session pilot. Add `--prepare` to generate fresh workspaces. These commands make no coding-agent model calls. See the [benchmark protocol](benchmarks/README.md) and the [observed results of the approved two-session pilot](benchmarks/README.md#approved-two-session-pilot).

## Project documents

- [Architecture](ARCHITECTURE.md)
- [Roadmap](ROADMAP.md)
- [Progress and benchmark results](PROGRESS.md)
- [Repository guidance](AGENTS.md)

Licensed under the [MIT License](LICENSE).