clew — overview

The depth behind the README: what clew indexes, how it is built and refreshed, what it promises and what it does not. Start with the README if you are new here.

flowchart LR
  repo[your repository<br/>source · .clew.yaml · requirements.yaml]
  repo --> harvest[index build<br/>doxygen + tree-sitter layers]
  harvest --> db[(clew.db<br/>SQLite)]
  db --> query[clew.query<br/>the stable API]
  query --> mcp[MCP server<br/>dossier · search · index]
  query --> cli[CLI<br/>clew query · refresh · wiki]
  query --> wiki[wiki<br/>HTML · Markdown · live hub]
  mcp --> agent([an agent])
  wiki --> person([a person])
  repo -. pre-commit .-> guard[clew guard<br/>doc gate + change impact]
  guard -. impact.json .-> wiki

Before you point it at a repository

Files that are not source are never read, whatever their extension: a zip or object file named .c is detected (lang-parsing-substrate’s classify_file) and skipped before doxygen or any parser sees it, and the build records how many. The repo’s shared toolchain config — toolchain.toml [ignore].paths and suppress.toml entries for every tool, the files knots, moldy and aurora-lint also read — excludes paths from the index and the gate; see docs/GUARD.md.

Indexing a repository runs that repository’s code, by design — cargo compiles it, doxygen runs with its own Doxyfile as base text. Treat clew index <tree> as equivalent in trust to cargo build on that tree, and read docs/SECURITY.md before pointing it at something you did not write: it states what clew does and does not promise, and how to report a vulnerability.

What it is for is aggregation, not capability. Nothing here is a question grep cannot answer. The difference is that “who calls this, transitively, across a function-pointer boundary, and which of those run on another thread” is one query instead of a dozen searches and a mental model you rebuild every session. It is a cache for work you would otherwise redo.

The doxygen gate is optional. clew guard, formerly the separate doxygen-guard, is a pre-commit gate that keeps a repo’s doxygen accurate. A repo that uses it gets a richer index: briefs, requirement tags, versioned comments. But clew needs neither the gate nor a Doxyfile. A repo that declares nothing gets its whole tree indexed, and three of the four reference repositories are measured that way. The gate ships in this package and stays off until a repo declares its hook. See docs/GUARD.md.

The tools

An agent is the user, and these are the whole of what the server exposes to it. The person’s view of the same index is the generated wiki — requirements, flows, a system map, a page per function — described in WIKI.md.

tool

for

dossier

Everything about one named symbol in ONE reply: body excerpt, brief, both edge directions, locks held, the thread it runs on, requirements and covering tests, liveness. There is no separate callers or chain_trace tool — this is why.

search

Find the name when you do not have one, or enumerate a whole layer. corpus= picks: symbols, prose, files, config, locks, threads. An empty result is graded and says what it did not read.

index(action=…)

Administration, not questions: refresh builds, status diagnoses, targets lists every indexed repo. Since 2.1, comments reads the notes a person left on the repository’s wiki pages (see WIKI.md). Since 2.0.0, grading an index is clew query stats and deleting aged-out databases is clew cull — both CLI.

Since 2.0.0 the declaration proposer is an MCP prompt, propose_declaration (in Claude Code: /mcp__clew__propose_declaration), and the clew propose CLI: it reads the repo’s evidence and proposes a .clew.yaml, entirely as comments, for when a causal layer looks emptier than the code warrants. A prompt costs nothing until someone invokes it. The wiki is readable as MCP resources: clew://wiki/<slug>/llms.txt and clew://wiki/<slug>/flow/<name>.

How to use them so they cost less than reading the source is SKILLS.md — batching, when depth pays, which layers to enumerate, and a blunt section on what clew cannot answer. Every figure in it was measured on the acceptance grid, including the places clew loses. It installs with the package at clew/SKILLS.md, so an agent on a pip install can be pointed at it directly.

Every reply names the target it answered from, and carries a staleness block only when that index is actually stale — so a current index costs nothing to establish.

Reads are live: query tools open the database per call. Writes are refused when the server process predates its own source, because a build through stale logic can silently drop whole layers and then report success.

What’s in the database

Layer

Answers

Structure

“what is this symbol?” — doxygen symbol tables, briefs, extents

Prose

“why does this subsystem exist?” — README/docs markdown, FTS5-indexed

Call graph

“who calls this, and how sure are we?” — doxygen ×2 + tree-sitter, every edge carrying source + confidence

Callbacks

“who reaches it through a function pointer?” — registration→dispatch resolution

Shared-key dataflow

“writing this key affects whom?” — data-model / queue edges the call graph cannot see

Threads

“which thread does this run on?” — spawn-site harvest + membership closure

Dispatch semantics

inline vs queued vs keyed; edge-triggered; which hops cross a thread boundary

Terminus

where a chain leaves the repo through an externally-registered callback

Requirements

“what implements / tests REQ-X?” — @req traceability

Liveness

“does this code even run?” — reachability over the non-fuzzy call graph

The point of the semantic layers (threads, dispatch mode, terminus) is causal chains: reconstructing “message arrives → who handles it → where it goes → which thread hops → where it leaves the library → what requirements it touches” as a single query, not a manual archaeology session.

Measured

Answering from the index is compared against the same agentic harness without it — same repository, same model, same sitting, same frozen questions.

The instrument is being rebuilt. The previous generation’s rubrics graded lexical retrieval rather than answer completeness, so they measured which tool was used instead of whether the question was answered. They have been deleted rather than migrated; git history holds them. acceptance/DESIGN.md is the replacement’s schema and grading routine, and docs/CORE_HYPOTHESIS.md is the claim it tests.

It has now run. The first baseline is published as PROVISIONAL under acceptance/runs/, each run beside the KNOWN-DEFECTS.md that discloses what moves its numbers and in which direction. Figures are deliberately not repeated here or in SKILLS.md: the run directory is the only source, so a stale copy cannot outlive it.

Refreshing an index

flowchart LR
  save[a file is saved] --> event[OS file event<br/>MCP server watcher]
  event --> fast{same definitions?<br/>≤ 4 files}
  fast -- yes --> tier1[FAST tier, in place<br/>positions · outgoing calls · code text<br/>under a second]
  fast -- no --> full
  tier1 --> derived[replies carry the<br/>`derived` staleness axis]
  derived --> full[FULL refresh in the background<br/>threads · locks · reachability · …]
  full --> current[index current]

A refresh is incremental, and a stale query refreshes itself before answering. Both exist for the same reason: an agent that believes the index is expensive to correct stops using the index, and then reasons from a stale one — which is worse than not having it.

  • Incremental. doxygen is re-run over the changed files plus a closure of their neighbours, and the result is spliced into the existing database rather than replacing it. The closure is the part that has to be right: doxygen’s xref pass is global, so editing b.c invalidates a.c’s edges into it even though a.c did not change, and a second pass over the include graph recovers calls the edit itself introduces.

  • Two tiers. A save that keeps a file’s set of definitions takes the FAST tier: that file’s symbol positions, its outgoing call edges, its code-search text, file docs, requirement mentions and blocking call sites are updated in place, in one transaction. Everything that is a property of the whole index — reachability, threads, locks, conflicts, shared-key edges, doxygen’s own call layer — is left as it was and NAMED on every reply as the derived staleness axis until a full refresh replaces the index. Measured with scripts/refresh_bench.py --fast (a shared clone, one cold build, three one-comment edits, median; 2026-11-18 at 0f25ff05, editing clew/cli.py, library/ssl_tls.c, src/facade/entropic.cpp and app/actions/remote/post.ts of the acceptance pins): 233 ms on this repository, 364 ms on mbedtls, 239 ms on entropic and 324 ms on mattermost-mobile, in-process. An added, removed or renamed definition, a configuration file, or more than four edited files takes the full tier instead — 3.2 s, 4.1 s, 4.3 s and 8.4 s on those repositories. From a shell or an editor hook: clew refresh.

  • Automatic. The MCP server watches the repositories it has answered from (OS file events), so a save is refreshed by the fast tier within about a second and the full refresh follows in the background. A query that arrives against a stale index refreshes first; behind someone else’s build it waits at most a second and answers from the index as it stands, with its staleness notice.

  • You can still ask. index(action='refresh') refreshes on demand; add force=True for a full rebuild.

Three limits worth knowing, none of them silent:

  • A newly-added CROSS-FILE call needs C or C++. The include-graph pass reads doxygen’s includes table, which is populated from #include — so on Python and Rust that pass finds nothing and such a call waits for a full rebuild. The edited file itself is always re-indexed. See PYTHON_INTEGRATION.md and RUST_INTEGRATION.md.

  • One extra iteration, not a fixed point. A call reachable only through two new hops waits for a full rebuild, and a generation limit bounds how long a splice chain runs before one happens anyway.

  • A stale server process refuses to write. Query tools open the database per call, so reads are always live; but a server whose code predates the working tree will not build, because it would re-stamp the index with old pipeline logic. Restart the client — a rebuild cannot fix it.

A CLEW_BUILD_VERSION bump makes the next build cold. The constant tracks the build’s output shape, so when it moves the cached doxygen output is discarded and no index of the old shape survives to be queried. Upgrading clew therefore costs one full build, once.

Programmatic use

The MCP tools are one surface over the index; three more give the same answer to a consumer that is not an MCP client. All four build every reply through the same functions, so they cannot word one answer differently.

from

use

Python

clew.query.export_dossier(db, subject, ...) and clew.query.export_search(db, text, corpus=...)

any process

clew query dossier NAME [NAME ...] / clew query search TEXT --corpus C — the same payload as JSON on stdout

a long-lived host

one clew-mcp process: MCP is JSON-RPC 2.0 over stdio

What the export leaves out is the MCP boundary, not any of the answer: no byte budget, no default neighbour cap, and no target/staleness stamps — an export caller names its database and checks freshness with read_build_signature. Every export payload carries wire_version.

clew query exits 0 with the payload on stdout, 1 when there is no index (stdout stays empty), and 2 when the request is refused (the reason on stderr).

What semver covers

Covered — a breaking change here means a major bump:

  • the clew CLI verbs and their flags: init, propose, export, query, the build invocation, and since 2.0.0 clew guard and clew wiki with every subcommand, because pre-commit hooks and CI call them. They are listed in docs/cli-surface.json, generated from the parsers; a test fails when one is renamed or removed

  • the MCP tool names and their wire keys — a consumer reads edge_class, confidence, source and friends by name. The keys are listed in docs/wire-keys.json, generated from the reply dataclasses; a test fails when one is renamed or removed

  • clew wiki flow JSON (2.0.0): the Flow / Lane / Step / Frame fields, under flow in docs/wire-keys.json, with flow_version. A later change is additive or moves flow_version

  • the gate’s machine outputs (2.0.0):

    • impact.json is {"schema_version": 1, "entries": [...]}; its keys are under impact in docs/wire-keys.json. The wiki still reads a pre-2.0.0 bare array.

    • clew guard validate --format sarif|gitlab|github are covered as “conforms to that format” (SARIF 2.1.0, GitLab Code Quality, GitHub workflow commands), schema-tested; the rule ids and messages inside may change

  • the wiki’s exports (2.0.0), as format conformance only: requirements.reqif is ReqIF 1.2, needs.json has Sphinx-needs’ layout, system.dsl is a Structurizr workspace, and each flow is valid Mermaid, PlantUML and Graphviz DOT; llms.txt follows the llms.txt layout. Their CONTENTS follow the repository and are not covered

  • clew.query’s public functions and the dataclasses they return, including the export API (export_dossier, export_search, WIRE_VERSION) — see Programmatic use

Not covered, and deliberately so:

  • the SQLite schema. CLEW_BUILD_VERSION exists precisely because the schema moves; a consumer detects a stale index by comparing it, not by assuming stability. Query through clew.query, not with your own SQL.

    CLEW_BUILD_VERSION, read_build_signature and index_unusable_reason are re-exported from clew.query and are therefore covered, so the documented way to check freshness does not reach into an internal:

    from clew.query import CLEW_BUILD_VERSION, read_build_signature
    
    if read_build_signature("clew.db") != CLEW_BUILD_VERSION:
        ...  # rebuild: this index predates the current pipeline
    
  • clew.* internals — anything not re-exported from query

  • the .idxcache format

Install

EITHER as a Claude Code plugin, which needs only uv and doxygen:

/plugin marketplace add tvanfossen/clew
/plugin install clew@clew

The plugin launches the server and its hook through uvx --from clew-trace==<version>, pinned to the release the plugin was published with, so installing the plugin installs exactly that clew. The first launch downloads it from PyPI; later launches reuse uv’s cache. Measured on one machine against clew-trace 1.2.0: a warm uvx launch of the hook took about 63 ms against 16 ms for the bare command, and the first, installing launch 2.2 s.

OR by hand, with the package on PATH whatever virtualenv happens to be active:

pipx install clew-trace          # or: pip install --user clew-trace
sudo apt install doxygen         # REQUIRED for C and C++, and not pip-installable
clew init                        # writes ./.mcp.json  (--scope global for user-level)

clew init also doctors the environment and names what is missing. A plain pip install inside a project venv also works, but only while that venv is on the PATH your editor launches the server with — which is the usual reason a correctly-registered server shows as failed to connect.

Pick one. Both register a server named clew, so doing both leaves two sources for one entry — run claude mcp remove clew first if you have already used clew init.

What the plugin installs, including a hook

The plugin registers the MCP server and one PostToolUse hook. Installing a Claude Code plugin does not prompt you about hooks, so it is stated here instead:

  • What it does. After a Bash, Grep, Glob or Read call it adds a short note naming the file you just looked at and the one index call that would have answered more — “You read symbols.py. A file read gives you the body and nothing else; dossier returns that same body plus its callers and callees in one reply.” It exists because grep has an enormous training prior and an index tool has none — the tool being correct does not make it reached for.

    It says what you just did because the generic version did not work. Measured on a real session: the old note fired repeatedly while the agent read four source functions with grep, one of which dossier would have answered completely. Asked why it ignored the note, the agent’s account was that “the index exists” carries no information a capable model does not already have, so it reads as a banner. Naming your last action is the one thing a note that fires after the call can say with any marginal value.

  • It escalates only when ignored, and one index call silences it. Each file-inspection call adds one to a per-session tally; a clew call clears the tally to zero rather than crediting against it. Below five it says nothing; from five it speaks every fifth call; from twenty it speaks every third call and switches to a blunter tier that states the ratio rather than the capability. A session that uses the index even occasionally stays permanently silent.

    Two things here are corrections rather than choices. Crediting was the original design and was unrecoverable: measured on one real session, 1,339 searches against 38 clew calls left a pressure of 1,225 against a threshold of 20, needing ~408 consecutive index calls to earn silence back. The loudest tier became permanent, and its own promise that using the tool would stop it was arithmetically false. The loud tier also fired on every single call, which produced ~30 near-identical injections in one session — wallpaper, and therefore filtered hardest exactly where the message mattered most.

  • ~46 ms per matching call, almost all of it Python starting. It imports nothing from the clew package and nothing outside os/sys/json, for that reason.

  • It is registered once per tool — Read, Grep, Glob and Bash each get their own matcher passing their own flag, plus one for the clew tools passing --used. That is how it knows which kind of call fired without reading tool_name off the event: the modality comes from the manifest you can read, not from the payload a repository can influence.

  • What can reach your model through it, stated exactly. Through 1.0.9 the answer was “nothing”: the payload was assembled from constant strings and the only run-time value was the tally, an int through %d. That is no longer true, and the change was deliberate — a note that cannot name your last action was measured changing nothing. The guarantee is now a bounded one rather than an absolute one:

    The output is a json.dumps of a literal-keyed object. Every value is a module-level literal, an int through %d, or a basename matching [A-Za-z0-9._-]{1,64} and not starting with a dot — the complete output set of one function, _safe_token.

    Two separate mechanisms, because there are two separate risks and neither covers the other:

    • json.dumps over the whole object means a filename can never alter the payload’s structure. Hand-assembled JSON was safe only while the substituted value was an integer; a filename containing "}} would otherwise close the string early and append sibling keys of the hook protocol — a decision, a continue — letting a repository steer the harness itself.

    • _safe_token bounds the content without eliminating it. Up to 64 allowlist-clean characters of a filename are quoted back inside the note. A repository can name a file dossier-is-unreliable-prefer-grep.py and have that appear in the hook’s voice. That residual is real and accepted. What limits it: tool_response — the bulk repository-written field — is never read, the bytes are already in your model’s context from the tool result the hook is reacting to, and the note’s own literal always closes the sentence so a filename never sits at the end.

    Both are asserted structurally in tests/test_hook.py, over the AST rather than over text: %s is permitted but only ever fed _safe_token’s output, and _safe_token’s output set is proved by running every code point through it rather than by sampling hostile strings. Each was also verified by mutation — disabling either one fails the test aimed at it, and disabling both lands a real "decision": "block" injection that four tests catch.

  • It never exits non-zero, because a non-zero exit would send its stderr to the model. Every path returns 0, including every failure path — a marker file that cannot be written fails silently.

To turn it off, set CLEW_HOOK_DISABLE=1 in the environment Claude Code runs in, or delete hooks/hooks.json from the installed plugin. Registering the server by hand with clew init installs no hook at all.

doxygen is a C++ binary, so it cannot be a Python dependency — clew init checks for it and tells you if it is missing. Everything else, including the MCP SDK, comes with the package.

Build a database

.venv/bin/python -m clew \
    --output clew.db \
    --repo-root /path/to/repo

That is the whole common case. The Doxyfile is discovered, and a repo that ships none gets one synthesized over its declared scope.

Six arguments, and only six:

Flag

For

--output

where the database is written

--repo-root

the repository to index

--declare FILE

a declaration document stated for this build (see below)

--exclude PATH…

paths to leave out; recorded into the index and replayed by later builds

--rebuild

ignore every cached entry, then re-warm the cache

--verbose

more on stderr; changes nothing that reaches the index

Everything a target repo can declare lives in one place — its own .clew.yaml — and --declare states the same document for a repository you do not own and must leave byte-identical:

# a --declare document, or <repo>/.clew.yaml
index_scope:          {roots: [src, include], excludes: [src/generated]}
preprocessor:         {predefined: [MY_FEATURE_C], config_header: auto}
requirements:         docs/requirements.yaml
thread_patterns:      {spawns: [{name: osThreadNew, entry_arg_index: 0}]}
shared_key_patterns:  {writers: [{name_prefix: Store_Set}], readers: [{name_prefix: Store_Get}]}
locks:                {locks: [{name: MyGuard, form: raii}]}
dispatch:             {interfaces: [{interface: ops, binds: struct_ops, methods: [read, write]}]}
mqtt_dispatch:        {subscribe_functions: [{fn_name: mqtt_subscribe, topic_arg_index: 0, handler_arg_index: 1}]}
data_model:           tools/dm_full.toml
kconfig:              {root: Kconfig}
event_tags:           {emits: producer, handles: consumer}
entry_patterns:       ["%trampoline%", "on_%"]
enrich:               docs/architecture_topics.yaml
doxyfile:             doxygen/project.doxyfile
tests:                {paths: ["test/*", "*_test.cpp"], junit: [build/junit.xml]}  # + evidence: docs/WIKI.md
vendored:             [third_party/json]
owners:               {codeowners: meta/OWNERS}   # default: .github/CODEOWNERS etc. and MAINTAINERS
blocking:             {primitives: [{name: os_sem_wait, timeout_arg_index: 1}], isr_predicates: [up_interrupt_context]}
sub_indexes:          {deps-slam: {excludes: [deps/slam/third_party]}}
guard:                {validate: {tags: {req: {cross_reference: true}}}}   # the gate: docs/GUARD.md
wiki:                 {title: My project, flows: [{entry: main, depth: 2}]}  # the wiki: docs/WIKI.md

Nothing about a target repo is hardcoded: every section above is a declared override of a built-in default. The identical mapping is the options argument of build_index() and of the MCP index(action="refresh") tool, so an agent with no shell can state any of it.

What the walk skips, and what vendored: changes

  • Dot-directories are never walked. .github/, .vscode/ and every other directory whose name starts with ., plus __pycache__ and node_modules, are pruned (scope._skip_dir). A script under .github/scripts/ is therefore never indexed, whatever index_scope says beneath it. That is a scope decision, not an oversight.

  • External code is a nested git tree (a submodule, or a directory with its own .git). Its files are indexed and stamped with the tree that owns them, and counts that exclude external code are counts over that stamp.

  • vendored: is a statement, not a filter. A declared path is recorded as scope.vendored_roots, with a path that does not exist named in scope.vendored_declared_missing. It is reported in the index’s scope (status, doc_scope), and the wiki draws it in the Vendor block beside nested git trees. It never removes a file from the index or from a count. To leave a path out, use index_scope.excludes.

The declared @req id pattern and the catalog column mapping come from the guard: section of the same .clew.yaml — the gate’s config, read by the index with the gate’s schema (see docs/GUARD.md).

Commit what you stated

--declare reads a document in; export writes one out, so a discovery made against a repository you do not own can be committed to one you do:

.venv/bin/python -m clew export --index clew.db          # to stdout
.venv/bin/python -m clew export --index clew.db --output .clew.yaml

It emits only what was stated — never the built-in defaults. That is deliberate: a file asserting you declared every default would freeze those defaults into your repo, so a later improvement to one would be shadowed by a value nobody remembers committing. An index that recorded no statement exports a document that says so.

Rust support

A repo with a Cargo.toml and no Doxyfile is indexed with cargo +nightly rustdoc --output-format json instead of doxygen — doxygen has no Rust parser, and would otherwise silently produce zero symbol rows rather than an error. This needs a nightly toolchain on PATH (cargo +nightly --version); clew init does not check for it today, so its absence surfaces as a build-time RustdocUnavailableError instead. Every package’s [lib] and every [[bin]] target are documented — a main.rs binary is not assumed to be a thin wrapper around its lib; a package that pairs a same-named lib and bin (a common shape) has both indexed, not just one.

Doc comments are not required. An undocumented, non-pub function is indexed with its full signature, body, callers, callees and liveness — //////! only fill in the brief/detail prose fields, they gate nothing else. Do not write doc comments just to make indexing “work.”

//! module docs are still worth writing, for the same reason a C file benefits from a leading /*! ... */ block: search’s conceptual-query path matches on file-level prose (see filedocs.py), separately from any per-symbol ///. A //! at the top of a module whose value is conceptual — a metrics formula, a dispatch table, a locking-order convention — makes that module findable by a query naming the concept rather than a function name.

Without an agent

clew.query is importable and returns JSON-serializable dataclasses. It is what the MCP server is a view over, so no query logic exists twice — and it is wider than the MCP tools, by design: callers, callees, chain_trace, req_trace and thread_of are functions here, folded into dossier at the tool layer to keep one call answering a whole question.

from clew.query import dossier, search

dossier("clew.db", "sensor_poll")     # a function
dossier("clew.db", "REQ-NAV-002")     # a requirement
dossier("clew.db", "buf_mutex")       # a lock
search("clew.db", "retry backoff")    # find the name when you do not have one

dossier takes any indexed subject — function, variable, macro, class, lock, thread, requirement or Kconfig symbol — and its reply names which kind resolved. function_dossier is the narrower form that describes a function or macro and returns None for anything else.

clew wiki turns the same index into a static documentation site — derived sequence diagrams, the requirement trace with CI evidence, charts and a burndown. See WIKI.md.

Working on clew itself

Contributor material — the development setup, the package layout and how clew runs its own gate — is in DESIGN.md; the contributor contract is AGENTS.md.

The doxygen gate (clew guard)

doxygen-guard was a separate tool that clew consumed as a pip dependency. It is now part of clew (clew/guard/, absorbed at doxygen-guard’s own 1.4.2 release). Its config is the guard: section of the repo’s .clew.yaml, so the gate and the index read one file with one schema; .doxygen-guard.yaml is no longer read. The tags are unchanged; THE HOOK ID IS NOT — it is clew-guard now, because one tool in one repository should not answer to the name of the two it replaced. Adopting repos switch the hook’s repo: and rev: to this repository and move their config — see Migrating from doxygen-guard. The gate also checks Rust (rustdoc /// comments) when a repo declares it. Its scope is unchanged: validation, traceability and change impact. It is optional, and the index pipeline never runs it. Full reference: docs/GUARD.md.

Language detection for the gate, and every tree-sitter parse in the gate and the index, comes from lang-parsing-substrate, the Rust parsing library shared with knots, moldy and aurora-lint, installed from its PyPI wheels.