Retrieval tools for coding agents, no model in the loop: files, search, read, code_pack and write_note over the folder the session is opened in, served over…

<img src="https://raw.githubusercontent.com/kiycoh/silica-core/main/assets/banner-light.svg" alt="Silica Core" width="590" />
Lightweight, local evidence retrieval tools for code and research
Silica locates the source, symbol, page, or passage you and your agents need. Maximum signal, minimum machinery.
<a href="https://pypi.org/project/silica-core/"><img src="https://img.shields.io/pypi/v/silica-core?style=flat&labelColor=000000&color=000000" alt="PyPI" /></a> <a href="https://github.com/kiycoh/silica-core/blob/main/LICENSE"><img src="https://img.shields.io/github/license/kiycoh/silica-core?style=flat&labelColor=000000&color=000000" alt="License" /></a>
<!-- The MCP registry proves ownership of the PyPI package by finding this string in the description PyPI renders, which is this file. --> <!-- mcp-name: io.github.kiycoh/silica-core -->
Silica indexes the markdown, code, PDFs and office files under one root and serves them to Claude Code, Cursor, Hermes, Codex, OpenCode and every other popular harness, as MCP tools or as shell commands that print the same JSON. A hit is a path, a section, a line, a window of text and the numbers to judge it by. The harness owns the loop.
<img src="https://raw.githubusercontent.com/kiycoh/silica-core/main/assets/quickstart.gif" alt="the quickstart recorded end to end: uv tool install, silica-core init reporting nine indexed documents, silica-core setup claude registering the MCP server, then Claude Code answering a question about the LSM compaction design space by calling silica-core and citing the PDF with its page and its line" width="900" />
Three commands, then a question asked the way you would ask any other. The harness calls silica_search, and the answer carries the file, the page and the line it came from.
In Claude Code, install the plugin instead: it brings its own server, dense leg included.
uv tool install 'silica-core[mcp]' # BM25 over documents and their sections (faster, lighter)
uv tool install 'silica-core[mcp,dense]' # in addition the dense leg: numpy, a static model (still fast, more precise)
The second line adds the dense leg: numpy and a static model2vec model, no torch and no GPU. It stays inert until the model is named and the sections are embedded — the last stanza of the Quickstart. Take it when the questions are paraphrases that share no words with the text; an exact term or an identifier is answered by the lexical leg either way, and only that leg reports terms_absent.
pipx works the same. The package and the command are silica-core, the tools are silica_*.
Upgrading from 0.9 or older: the silica command is silica-core since 0.10.0 (silica belongs to silica-harness). A client registered by an older silica setup still launches silica mcp, which stops starting once uvx fetches 0.10.0. Run silica-core setup <client> once and it rewrites that entry.
In any folder of markdown, code, PDFs or office files:
silica-core init # adopt the folder: ignore file, vault.yaml, first index; the MCP server serves adopted folders only
silica-core search "leveled compaction" -k 5 # the best located passages
silica-core setup claude # register the MCP server, write the guidance block into ~/.claude/CLAUDE.md
# optional, with the [dense] extra: the dense leg, a static model, nothing leaves the machine
export SILICA_EMBEDDING_MODEL=model2vec/minishlab/potion-retrieval-32M
silica-core index --embed
<img src="https://raw.githubusercontent.com/kiycoh/silica-core/main/assets/search-hit.png" alt="silica-core search "leveled compaction" over nine LSM papers: the hit carries the file, p. 5 and the passage; beside it the PDF is open on that page with the same passage highlighted" width="900" />
Nine arXiv papers, indexed in 2.1 s. The hit names the file, the page and the passage; the page beside it is the check.
| Tool | Shell | Returns |
|---|---|---|
silica_files | silica-core files | the inventory and what the index did with each file: indexed, changed, excluded, failed, unconverted |
silica_search | silica-core search | ranked passages: path, section, line, BM25, matched terms, coverage, and the query terms absent from the corpus |
silica_read | silica-core read | a slice by lines or by heading (a page, in a PDF), the outline, and a version to carry forward |
silica_code_pack | silica-core code-pack | an AST context pack for one source file inside a character budget |
silica_write_note | silica-core write-note | one atomic write, linted for structure and unresolved wikilinks |
In a source tree every function, method, class and constant is its own unit: a hit's section is the symbol, span its lines, and silica_read(path, section=…) serves the body. For a symbol whose name is known, grep wins; for a question that names none, the search comes first: the tool description and the block silica-core setup claude writes say so. The contract, the reply shapes and the acceptance checks are in TOOLS.md. Nothing needs an API key or a network.
A ranked list always has a top, even when the corpus does not answer. Three fields say how much the result is worth:
coverage: the share of the query's idf mass the hit's matched terms carry. Near 1, every rare term matched; near 0, only common words did.terms_absent: query terms that occur nowhere in the corpus.matched_terms: the words this hit actually contains.<img src="https://raw.githubusercontent.com/kiycoh/silica-core/main/assets/search-says-no.png" alt="silica-core search "raft consensus log replication" over the same nine papers: terms_absent lists raft and consensus, coverage falls to 0.19, and the top hit is a passage about data replication rather than Raft" width="900" />
raft consensus log replication over the same nine papers: raft and consensus occur in none of them, coverage falls to 0.19, and the top hit is about data replication. On 254 papers the top hit of an answered question carries 0.69 to 1.00; a question the corpus does not cover, 0.44. Silica exposes the signals; the harness decides whether to stop, read or rephrase.
nDCG@10 on BEIR SciFact · NFCorpus, the same documents and queries for every arm. BEIR's published BM25 baselines are 0.665 · 0.325. Silica's lexical index needs no model; the others serve lexical search from an index that also holds embeddings.
| Mode | Silica | zvec-grep 0.2.2 | ck 0.7.11 |
|---|---|---|---|
| Lexical | 0.662 · 0.311 | 0.649 · 0.297 | 0.630 · 0.289 |
Hybrid, same potion-retrieval-32M embedder | 0.675 · 0.328 | 0.672 · 0.330 |
Code, on the twenty SWE-QA questions zvec-grep publishes for its own benchmark, same embedder, k = 10, scored on the files and symbols the reference answer rests on.
| Arm | file hit@5 · @10 | file MRR | symbol hit@10 | symbol recall | chars returned |
|---|---|---|---|---|---|
| Silica, hybrid | 0.85 · 0.90 | 0.68 | 0.75 | 0.24 | 8,266 |
| Silica, vectors | 0.80 · 0.85 | 0.67 | 0.65 | 0.21 | 6,225 |
| Silica, lexical | 0.65 · 0.75 | 0.47 | 0.45 | 0.14 | 8,194 |
| zvec-grep 0.2.2, hybrid | 0.65 · 0.75 | 0.54 | 0.55 | 0.17 | 7,326 |
| zvec-grep 0.2.2, vector | 0.60 · 0.80 | 0.61 | 0.55 | 0.18 | 6,821 |
| zvec-grep 0.2.2, FTS | 0.45 · 0.60 | 0.36 | 0.45 | 0.11 | 6,690 |
On BEIR the two hybrids tie at the 95% interval: the same vectors rank the same, with no daemon and no vector store. On code, Silica's hybrid file MRR is +0.135 over zvec-grep's hybrid (95% interval +0.01 to +0.27), paired per question. The fusion also gains +0.21 MRR and +0.30 symbol hit over Silica's lexical arm; no reranker or graph expansion is involved.
On this measured scope, Silica is a compact, local, SOTA-competitive retriever: it matches zvec-grep on BEIR and leads the paired SWE-QA code-localization replay with the same embedder.
Retrieval matters only if the agent does less work without losing the answer. These are separate experiments and are not pooled:
| Workload and arm | Runs | Quality | Search used | Turns | Tool calls | Seconds | Warm cost |
|---|---|---|---|---|---|---|---|
| Repository, search-first contract | 20 | Judge 59.7 | 17/20 | 4.7 | — | 24 | $0.197 |
| Repository, same plugin without contract | 20 | Judge 50.6 | 0/20 | 6.5 | — | 28 | $0.180 |
| Documents, resident Silica tools | 12 tasks | 12/12 correct | 12/12 | 3.9 | 2.9 | — | $0.20 |
| Documents, no plugin | 12 tasks | 12/12 correct | — | 5.0 | 4.0 | — | $0.22 |
The repository result is one repetition: turns improve by 1.75 (95% interval 0.55 to 3.05 fewer), while Judge and cost remain inconclusive. The document rows belong to a 144-run study over twelve questions and a 5.5M-token corpus. They establish less work on that workload, not a universal agent claim.
Corpora, intervals, per-task exceptions and reproduction commands are in benchmarks.
silica-core setup <client> writes the registration into the client's own config and backs up what was there; for claude it also puts a guidance block, when to search before grep, into ~/.claude/CLAUDE.md. silica-core setup --list names the clients: claude, codex, cursor, windsurf, zed, cline, roo, continue, goose, opencode, openhands, gemini, antigravity, dsh, hermes, openclaw, agent-zero, claude-desktop, lmstudio, anythingllm and librechat; shell, python and generic print recipes for anything else. The server serves the folder the client opens in; --vault DIR or SILICA_VAULT fixes the root.
Every written block, and the Claude Code plugin, run silica-core mcp --retrieval local-hybrid: potion-retrieval-32M in the server process, index and vectors built in the background at start, the search lexical and dense: warming until they land. Nothing leaves the machine; the one download is the model, once. npx skills add kiycoh/silica-core installs the skills (the one that tells an agent when to reach for the tools, and five that explain, summarize, compare, schematize and diagram from the indexed documents), and nothing else. Shell recipes, Docker and the REPL are in public/harnesses.md.
In Claude Code the plugin is all you need: it brings its own server and the skills. The Install section above and silica-core setup claude are for other clients; with both, two servers serve the same folder.
It needs uv on PATH, which starts the server.
claude plugin install silica-core --marketplace kiycoh/silica-core
That one step works on Claude Code 2.1.275 or later, and /plugin install silica-core --marketplace kiycoh/silica-core does the same inside a session. On an older client, add the marketplace first: claude plugin marketplace add kiycoh/silica-core, then claude plugin install silica-core@silica-core.
/silica-init. Nothing is indexed until you do.silica_search. Until the vectors are built the search is lexical, and its replies say dense: warming.Refresh the marketplace, then the plugin. The new version loads in the next session.
claude plugin marketplace update silica-core
claude plugin update silica-core@silica-core
The plugin is an MCP server plus a small mod in hooks/. Neither one sends your files, prompts or conversation anywhere.
uv run --frozen --project <plugin folder>. The plugin folder is ~/.claude/plugins/cache/silica-core/silica-core/<version>, with the version claude plugin list shows. The first time, uv installs the packages pinned in uv.lock from PyPI (and a Python build if the machine has no Python 3.11 or newer), and the server downloads the potion-retrieval-32M model from Hugging Face. Nothing else is downloaded./silica-init does the same. Either one runs uv run --frozen --project <plugin folder> --extra mcp --extra dense silica-core init in that folder, which writes vault.yaml there (plus .silicaignore in a code repository) and builds the index under ~/.silica. Not here hides the button for that folder. Nothing is indexed until you ask.silica_search before grep. It also adds the search guidance to the system prompt, unless your CLAUDE.md already has it. The mod reads three environment variables, CLAUDE_CONFIG_DIR, HOME and USERPROFILE, only to find that CLAUDE.md and to skip your home folder.docs/ folder, the mod helps Claude keep the docs in step with the code. It asks; Claude decides, and no write is ever refused.docs/ up to date, or say there is nothing to record.docs/ ends, the mod checks those files for links and code paths that lead nowhere, two ADRs with one number, and an accepted ADR whose Decision changed. Claude fixes what it agrees is a defect or says why it is not; the check asks at most twice a turn.docs/adr/ and docs/specs/ and runs git, then shows above the prompt how many records name what is not there and how many have files that changed since. /silica-docs lists them.implementation: (implemented, partial, pending, draft, dropped or n/a) is held to it: implemented and partial name a commit or a path in implemented_in, pending and draft name none, partial and dropped carry an implementation_note.The Index button, /silica-init, the search hints and the docs upkeep come from the mod, which needs Claude Code 2.1.293 or later. An older client still runs the server and the skills. Index a folder from a terminal opened in it instead:
uv run --frozen --project <plugin folder> --extra mcp --extra dense silica-core init
plugin:silica-core:silica-core. The server did not start; /mcp shows its state. The usual causes are uv missing from PATH and a first install that failed. Start the server by hand in the folder to read the error: uv run --frozen --project <plugin folder> --extra mcp --extra dense silica-core mcp --retrieval local-hybrid
When all is well it prints serving 5 tools on stdio, waiting for a client; Ctrl+C ends it.
/, which are too large to index whole. After Not here it stays hidden in that folder, and /silica-init still indexes it. On a client older than 2.1.293, see above.silica-core doctor checks the install and the folder: uv run --frozen --project <plugin folder> --extra mcp --extra dense silica-core doctor
claude plugin uninstall silica-core@silica-core
The plugin leaves two things behind:
vault.yaml, and .silicaignore in a code repository, in each folder you indexed;~/.silica/index/, one folder each.Delete them by hand. An index deleted while the plugin is still installed is rebuilt the next time its folder is searched.
.txt, .rst and PDFs with a text layer directly, one PDF page per section; DOCX, EPUB, FB2, RTF, XLS and ODF converted with no extra; scanned PDFs, images, PPTX and XLSX through silica-core import with MinerU; audio and video with ffmpeg plus SILICA_STT_BASE_URL; CSV readable by line, excluded from search. In a source tree the code lane adds source files and their json, yaml, toml, cfg and ini. silica-core doctor says which lanes this machine has.uv tool install stays lexical until silica-core index --embed, with the [dense] extra's local model or any OpenAI-compatible /v1/embeddings endpoint. Text leaves the machine only for a remote endpoint, and only after silica-core index --embed --allow-remote grants that host once. Variables and reply states in TOOLS.md, the ollama recipe in public/harnesses.md.silica-core mcp --extended adds the wikilink tools; silica-core connect (extra [connect]) hosts the bridge the Obsidian plugin dials into, so writes land through the vault API while the app is open; silica-core repl runs a small reference agent over the same tools, the one surface that needs a model (SILICA_MODEL).MIT. See LICENSE.
hooks/register.ts 340 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement } from 'claude-code'
3import {
4 codePaths, covers, decision, describe, frontmatter, HUB, isAccepted, isRecord, listOf, mdLinks, normalize, parseLog,
5 paths, reminder, SHA, stateProblems, supersedes,
6} from './docs.ts'
7import type { Front } from './docs.ts'
8import type { DocsReport } from './types.d.ts'
9import { GUIDANCE, START } from './guidance.ts'
10
11// The ask of docs/adr/0001, lever 1: the UserPromptSubmit hook removed in
12// 0573f2e, back in-process and only where `silica-core init` left vault.yaml.
13// QUESTION and IDENTIFIER are its two regexes as measured on 2026-09-10.
14const QUESTION = /\?|^\s*(what|where|how|why|which|when|who|does|do|is|are|can|list|explain|describe|find)\b/i
15// a backtick, snake_case, camelCase, a path or an extension, `::`, `#L`: the
16// prompt names something grep can look for
17const IDENTIFIER = /`|\b[A-Za-z]\w*_\w+\b|\b[A-Za-z]*[a-z][A-Z]\w*\b|\/\w|\.\w{1,4}\b|::|#L\d/
18
19export const NUDGE = 'silica-core: this question names no identifier. Before any grep (a Grep tool, or grep or rg in a shell), Glob or Read, state whether silica_search applies (yes or no); if yes, call it first with the question as `query`.'
20
21// ponytail: the folder the session started in; SILICA_VAULT pointing elsewhere is not seen (ADR-0001)
22async function adopted($: EngineInterface): Promise<boolean> {
23 const root = await $.session.root()
24 return $.fs.exists(`${root}/vault.yaml`)
25}
26
27// Where `silica-core setup claude` writes its block: guidance.claude_md_path().
28async function claudeMdHoldsTheBlock($: EngineInterface): Promise<boolean> {
29 const dir = (await $.env.get('CLAUDE_CONFIG_DIR'))
30 || `${(await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))}/.claude`
31 const text = await $.fs.read(`${dir}/CLAUDE.md`).catch(() => '')
32 return String(text).includes(START)
33}
34
35// Lever 5: the folder that holds hooks/ is the plugin root (the module does not
36// see CLAUDE_PLUGIN_ROOT), and init runs through mcp.json's own launch, extras
37// and --frozen included, so uv never re-syncs the environment the server shares
38const PLUGIN_ROOT = decodeURIComponent(new URL('..', (import.meta as { url: string }).url).pathname).replace(/\/$/, '').replace(/^\/([A-Za-z]:)/, '$1')
39const INIT = ['uv', 'run', '--frozen', '--project', PLUGIN_ROOT, '--extra', 'mcp', '--extra', 'dense', 'silica-core', 'init']
40const offer = atom({ plugin: 'silica-core', key: 'offer' } as const, 'hidden')
41
42// The docs upkeep of docs/adr/0004
43const docs = atom({ plugin: 'silica-core', key: 'docs' } as const, null)
44const isDocsHidden = atom({ plugin: 'silica-core', key: 'isDocsHidden' } as const, false)
45// ponytail: 30 changed lines is a guess at where a small turn ends; move it after some use
46const THRESHOLD = 30
47const TEST = /(^|\/)(tests?|__tests__)\/|\.test\.|_test\.|(^|\/)test_[^/]*$/
48const MANIFEST = /(^|\/)(pyproject\.toml|package\.json|Cargo\.toml|go\.mod|plugin\.json|hooks\.json|Dockerfile)$/
49const WRITES = new Set(['Edit', 'Write', 'NotebookEdit'])
50
51// ponytail: one turn of the main loop at a time, in module state; a reload
52// forgets the turn, and writes made by subagents or through Bash are not seen.
53// `docs` holds each doc the turn wrote, with its text before the first write.
54const fresh = () => ({ lines: 0, files: new Set<string>(), isDone: false, docs: new Map<string, string | null>(),
55 records: undefined as Map<string, string[]> | undefined })
56let turn = fresh()
57// the lint's blocks since the turn first tried to end: a fix that leaves new
58// problems gets a second, the same problems again end the turn. Kept apart
59// from `turn` in case the continuation a block causes raises turn.start.
60let stops = { blocks: 0, last: '' }
61
62// the + and - lines of a Write's or an Edit's structuredPatch
63const changed = (result: any): number =>
64 (result?.structuredPatch ?? []).reduce((n: number, h: any) =>
65 n + (h.lines ?? []).filter((l: string) => l.startsWith('+') || l.startsWith('-')).length, 0)
66
67// The docs upkeep's reading through the engine, git and the files
68// (docs/adr/0004); what reads text alone is in docs.ts
69
70async function git($: EngineInterface, root: string, args: string[]): Promise<string> {
71 const r = await $.process.run(['git', '-C', root, ...args], { timeoutMs: 30_000 }).catch(() => undefined)
72 return r && r.exitCode === 0 ? r.stdout : ''
73}
74
75// every commit reachable from HEAD, or null where that cannot be known (not a repo, a shallow clone)
76async function commits($: EngineInterface, root: string): Promise<string[] | null> {
77 const shallow = await git($, root, ['rev-parse', '--is-shallow-repository'])
78 if (shallow.trim() !== 'false') return null
79 const all = await git($, root, ['rev-list', 'HEAD'])
80 return all.split('\n').filter(Boolean)
81}
82
83// a file's text, undefined when it cannot be read
84async function readText($: EngineInterface, path: string): Promise<string | undefined> {
85 const t = await $.fs.read(path).catch(() => undefined)
86 return t === undefined ? undefined : String(t)
87}
88
89// whether a root-relative path, a folder with its trailing slash or without, is in the tree
90async function isThere($: EngineInterface, root: string, rel: string): Promise<boolean> {
91 return $.fs.exists(`${root}/${rel.replace(/\/$/, '')}`)
92}
93
94// the records under docs/adr/ and docs/specs/, root-relative
95async function records($: EngineInterface, root: string): Promise<string[]> {
96 const adr = await $.fs.list(`${root}/docs/adr`).catch(() => [])
97 const specs = await $.fs.list(`${root}/docs/specs`).catch(() => [])
98 const out = adr.map(x => `docs/adr/${x.name}`)
99 for (const x of specs) out.push(x.kind === 'dir' ? `docs/specs/${x.name}/spec.md` : `docs/specs/${x.name}`)
100 return out.filter(isRecord)
101}
102
103// what a record names that is not there: a SHA that is not one commit
104// reachable from HEAD, a path of implemented_in or documents not in the tree
105async function evidence($: EngineInterface, root: string, fm: Front, known: string[] | null): Promise<string[]> {
106 const out: string[] = []
107 for (const ref of listOf(fm.implemented_in)) {
108 if (SHA.test(ref)) {
109 if (known && known.filter(c => c.startsWith(ref)).length !== 1) out.push(`${ref} is not one commit reachable from HEAD`)
110 } else if (!(await isThere($, root, ref))) out.push(`${ref} is neither a commit nor a path in the tree`)
111 }
112 for (const ref of listOf(fm.documents)) {
113 if (!SHA.test(ref) && !(await isThere($, root, ref))) out.push(`documents names ${ref}, which is not in the tree`)
114 }
115 return out
116}
117
118// each record by its path, with the paths its implemented_in and documents name
119async function listed($: EngineInterface, root: string): Promise<Map<string, string[]>> {
120 const out = new Map<string, string[]>()
121 for (const rec of await records($, root)) {
122 const names = paths(frontmatter((await readText($, `${root}/${rec}`)) ?? ''))
123 if (names.length) out.set(rec, names)
124 }
125 return out
126}
127
128async function scan($: EngineInterface, root: string): Promise<DocsReport> {
129 const recs = await records($, root)
130 if (!recs.length) return { problems: [], drift: [] }
131 const fms = new Map<string, Front>()
132 for (const rec of recs) fms.set(rec, frontmatter((await readText($, `${root}/${rec}`)) ?? ''))
133
134 const known = await commits($, root)
135 const problems: string[] = []
136 for (const [rec, fm] of fms) {
137 if (fm.implementation === undefined) continue
138 for (const p of [...stateProblems(fm), ...(await evidence($, root, fm, known))]) problems.push(`${rec}: ${p}`)
139 }
140
141 // drift: commits to a record's files after the record's last commit (its mtime when git does not track it)
142 const hubs = new Map<string, number>()
143 for (const fm of fms.values()) for (const p of paths(fm)) hubs.set(p, (hubs.get(p) ?? 0) + 1)
144 const last = new Map<string, number>()
145 for (const c of parseLog(await git($, root, ['log', '--format=@%ct', '--name-only', '--', 'docs/adr', 'docs/specs'])))
146 for (const f of c.files) if (!last.has(f)) last.set(f, c.t)
147 const anchors = new Map<string, number>()
148 for (const rec of recs) {
149 const at = last.get(rec)
150 if (at !== undefined) { anchors.set(rec, at); continue }
151 const st = await $.fs.stat(`${root}/${rec}`).catch(() => undefined)
152 anchors.set(rec, Math.floor((st?.mtimeMs ?? 0) / 1000))
153 }
154 const since = Math.min(...anchors.values())
155 const log = parseLog(await git($, root, ['log', `--since=@${since}`, '--format=@%ct', '--name-only']))
156 const drift: DocsReport['drift'] = []
157 for (const [rec, fm] of fms) {
158 if (fm.implementation !== 'implemented' && fm.implementation !== 'partial') continue
159 const own = paths(fm).filter(p => (hubs.get(p) ?? 0) < HUB)
160 const anchor = anchors.get(rec)!
161 const n = own.length ? log.filter(c => c.t > anchor && c.files.some(f => own.some(p => covers(p, f)))).length : 0
162 if (n) drift.push({ rec, commits: n })
163 }
164 drift.sort((a, b) => b.commits - a.commits)
165 return { problems, drift }
166}
167
168// what the docs this turn wrote get wrong, one line each; `docs` holds each
169// with its text before the turn's first write (null for a new one)
170async function lint($: EngineInterface, root: string, docs: Map<string, string | null>): Promise<string[]> {
171 const out: string[] = []
172 const entries = await $.fs.list(root).catch(() => [])
173 const top = new Set(entries.filter(x => x.kind === 'dir').map(x => x.name))
174 const adrEntries = await $.fs.list(`${root}/docs/adr`).catch(() => [])
175 const adrs = adrEntries.map(x => x.name)
176 let known: string[] | null | undefined
177 for (const [rel, before] of docs) {
178 const text = await readText($, `${root}/${rel}`)
179 if (text === undefined) continue
180 const dir = rel.split('/').slice(0, -1).join('/')
181 for (const target of mdLinks(text)) {
182 const to = normalize(`${dir}/${target}`)
183 if (to === undefined || !(await isThere($, root, to))) out.push(`${rel}: the link to ${target} leads nowhere`)
184 }
185 for (const p of codePaths(text)) {
186 if (top.has(p.split('/')[0]!) && !(await isThere($, root, p))) out.push(`${rel}: \`${p}\` is not in the repo`)
187 }
188 if (isRecord(rel)) {
189 const fm = frontmatter(text)
190 if (fm.implementation !== undefined) {
191 known ??= await commits($, root)
192 for (const p of [...stateProblems(fm), ...(await evidence($, root, fm, known))]) out.push(`${rel}: ${p}`)
193 }
194 for (const n of supersedes(text)) {
195 if (!adrs.some(x => x.startsWith(`${n}-`))) out.push(`${rel}: it names ADR-${n}, which docs/adr/ does not hold`)
196 }
197 }
198 const num = rel.match(/^docs\/adr\/(\d{4})-/)?.[1]
199 const same = num ? adrs.filter(x => x.startsWith(`${num}-`)) : []
200 if (same.length > 1) out.push(`${rel}: ADR number ${num} is taken by ${same.length} files: ${same.join(', ')}`)
201 const was = before != null && rel.startsWith('docs/adr/') && isAccepted(before) ? decision(before) : undefined
202 if (was !== undefined && was.trim() !== (decision(text) ?? '').trim()) {
203 out.push(`${rel}: the Decision of an accepted ADR changed this turn. If the decision was reversed or replaced, ` +
204 'put it back, write a new ADR that supersedes this one and mark this one "Superseded by" it; if the change only clarifies it, say so')
205 }
206 }
207 return out
208}
209
210async function adopt($: EngineInterface): Promise<{ isIndexed: boolean; text: string }> {
211 const root = await $.session.root()
212 const r = await $.process.run(INIT, { cwd: root, timeoutMs: 600_000 })
213 .catch(err => ({ exitCode: 1, stderr: String(err) }))
214 return r.exitCode === 0
215 ? { isIndexed: true, text: `${root} is indexed; silica_search serves it from its next call.` }
216 : { isIndexed: false, text: `silica-core init failed in ${root}: ${r.stderr.trim().split('\n').at(-1) ?? ''}` }
217}
218
219export const register: Register = (on) => {
220 on('session.start', async ($, e, next) => {
221 await $.command.register({ name: 'silica-init', description: 'Index this folder for silica-core (runs silica-core init)' })
222 await $.command.register({ name: 'silica-docs', description: 'List the docs/ records that break their implementation state or drift from their code' })
223 const root = await $.session.root()
224 const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
225 const isAdopted = await adopted($)
226 const isAsked = e.isInteractive && root !== '/' && root !== home
227 && !isAdopted && !(await $.store.get(`dismissed:${root}`))
228 await update($, offer, () => (isAsked ? 'offer' : 'hidden'))
229 // after the session is up, so a large repo's git log never delays the first prompt
230 if (e.isInteractive && isAdopted) $.clock.after(0, () => { void scan($, root).then(r => update($, docs, () => r)).catch(() => {}) })
231 return next(e)
232 })
233
234 on('command.run', { command: 'silica-init' }, async ($) => {
235 const r = await adopt($)
236 if (r.isIndexed) await update($, offer, () => 'hidden')
237 return { text: r.text }
238 })
239
240 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
241 const phase = await read($, offer)
242 if (phase === 'hidden' || e.props.hasSurvey) return next(e)
243 const { Box, Button, Text } = $.ui.resolve(e)
244 if (phase === 'indexing') return h(Box, {}, h(Text, { dimColor: true }, 'silica-core: indexing this folder…')) as RenderElement
245 return h(Box, {},
246 h(Text, {}, 'silica-core: this folder is not indexed. '),
247 h(Button, { key: 'index', label: 'Index', variant: 'primary', onPress: async () => {
248 await update($, offer, () => 'indexing')
249 const r = await adopt($)
250 $.ui.toast(r.text) // the engine names the plugin in front of it
251 await update($, offer, () => (r.isIndexed ? 'hidden' : 'offer'))
252 } }),
253 h(Button, { key: 'dismiss', label: 'Not here', onPress: async () => {
254 await $.store.set(`dismissed:${await $.session.root()}`, true)
255 await update($, offer, () => 'hidden')
256 } })) as RenderElement
257 })
258
259 on('command.run', { command: 'silica-docs' }, async ($) => {
260 const r = await scan($, await $.session.root())
261 await update($, docs, () => r)
262 const text = describe(r)
263 return r.problems.length || r.drift.length ? { text, context: [text] } : { text }
264 })
265
266 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
267 const r = await read($, docs)
268 if (e.props.hasSurvey || !r || (!r.problems.length && !r.drift.length) || (await read($, isDocsHidden))) return next(e)
269 const { Box, Button, Text } = $.ui.resolve(e)
270 return h(Box, {},
271 h(Text, { dimColor: true }, `docs: ${r.problems.length} problems · ${r.drift.length} drifting — /silica-docs for the list `),
272 h(Button, { key: 'hide-docs', label: 'Hide', onPress: () => update($, isDocsHidden, () => true) })) as RenderElement
273 })
274
275 on('turn.start', async ($, e, next) => {
276 if (!e.agentId) turn = fresh()
277 return next(e)
278 })
279
280 // A reminder after a write worth recording, once a turn; the write's result stands as it was
281 on('tool.call', async ($, e, next) => {
282 const ran = await next(e)
283 if (!WRITES.has(e.tool) || e.agentId || ran.deny !== undefined || ran.isError) return ran
284 const path: string = (e as any).file_path ?? (e as any).notebook_path ?? ''
285 const root = await $.session.root()
286 if (!path.startsWith(`${root}/`) || !(await adopted($))) return ran
287 const rel = path.slice(root.length + 1)
288 if (rel.startsWith('docs/')) {
289 if (rel.endsWith('.md') && !turn.docs.has(rel)) turn.docs.set(rel, (ran.result as any)?.originalFile ?? null)
290 turn.isDone = true
291 return ran
292 }
293 if (turn.isDone || TEST.test(rel) || !(await $.fs.exists(`${root}/docs`))) return ran
294
295 turn.files.add(rel)
296 turn.lines += changed(ran.result)
297 turn.records ??= await listed($, root)
298 const adrs = [...turn.records].filter(([, entries]) => entries.some(x => covers(x, rel))).map(([adr]) => adr)
299 const why = adrs.length ? `${rel} is listed by a record`
300 : (ran.result as any)?.type === 'create' ? `${rel} is new`
301 : MANIFEST.test(rel) ? `${rel} is a manifest`
302 : turn.lines >= THRESHOLD ? `${turn.lines} lines changed`
303 : undefined
304 if (!why) return ran
305
306 turn.isDone = true
307 return { ...ran, context: [...(ran.context ?? []), reminder(why, [...turn.files], adrs)] }
308 })
309
310 // The lint of the docs the turn wrote. It asks, it never refuses: the model
311 // fixes what it agrees is a defect or says why one is not, and at most two
312 // blocks a turn come; what is left after them stays
313 on('classic.Stop', async ($, e, next) => {
314 const r = await next(e)
315 if (!e.stop_hook_active) stops = { blocks: 0, last: '' }
316 if (stops.blocks >= 2 || !turn.docs.size) return r
317 const found = await lint($, await $.session.root(), turn.docs)
318 if (!found.length || found.join('\n') === stops.last) return r
319 stops = { blocks: stops.blocks + 1, last: found.join('\n') }
320 return { ...r, block: `silica-core: the docs this turn wrote have ${found.length} problem${found.length > 1 ? 's' : ''}:\n` +
321 found.map(f => `- ${f}`).join('\n') + '\nFix them before you end the turn, or say in one line why one is not a defect.' }
322 })
323
324 on('prompt.submit', async ($, e, next) => {
325 const text = e.text.trim()
326 if (!text || !QUESTION.test(text) || IDENTIFIER.test(text)) return next(e)
327 if (!(await adopted($))) return next(e)
328 return next({ ...e, context: [...(e.context ?? []), NUDGE] })
329 })
330
331 // Lever 3: the block the bench measured through --append-system-prompt-file,
332 // last in the system prompt, where the request offers silica_search
333 on('prompt.compose', async ($, e, next) => {
334 const composed = await next(e)
335 if (!e.tools.some(t => t.endsWith('__silica_search'))) return composed
336 if (!(await adopted($)) || (await claudeMdHoldsTheBlock($))) return composed
337 return { sections: [...composed.sections, { id: 'silica-core:guidance', text: GUIDANCE, scope: 'session' }] }
338 })
339}
340hooks/docs.ts 153 lines1import type { DocsReport } from './types.d.ts'
2
3// The docs upkeep of docs/adr/0004, the part that reads text alone: what a
4// doc says about itself and what it points at. What goes through the engine
5// (git, the files) is in register.ts, the one file the plugin directory lets
6// hold calls on the engine's interface.
7// The implementation contract is silica-internal ADR-0056's, as its
8// scripts/docs_status.py held it before 544963a5 removed it.
9
10export type Front = Record<string, string | string[]>
11
12export const SHA = /^[0-9a-f]{7,40}$/
13const STATES = ['implemented', 'partial', 'pending', 'draft', 'dropped', 'n/a']
14// ponytail: a file three records list (cli.py, plugin.json) changes with every feature, so its commits are not drift; measured on silica-internal 2026-10-14, 85 drifting records became 37
15export const HUB = 3
16
17const unquote = (s: string) => s.trim().replace(/^(["'])(.*)\1$/, '$2')
18
19// ponytail: the YAML records use, not YAML: `k: v`, `k: [a, "b"]` and a `- x`
20// block list under an empty `k:`; a folded or nested value reads as its first line
21export function frontmatter(text: string): Front {
22 const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\s*(\r?\n|$)/)
23 if (!m) return {}
24 const out: Front = {}
25 let list: string[] | undefined
26 for (const line of m[1]!.split(/\r?\n/)) {
27 const item = line.match(/^\s*-\s+(.*)$/)
28 if (item && list) { list.push(unquote(item[1]!)); continue }
29 const kv = line.match(/^([A-Za-z_][\w-]*):\s*(.*)$/)
30 if (!kv) continue
31 const [, key, value] = kv as unknown as [string, string, string]
32 list = undefined
33 if (value === '') out[key] = list = []
34 else if (value.startsWith('[') && value.endsWith(']')) out[key] = value.slice(1, -1).split(',').map(unquote).filter(Boolean)
35 else out[key] = unquote(value)
36 }
37 return out
38}
39
40export const listOf = (v: string | string[] | undefined): string[] => (v === undefined ? [] : Array.isArray(v) ? v : [v])
41
42// the path entries of implemented_in and documents; a SHA is evidence, not a path
43export const paths = (fm: Front): string[] =>
44 [...listOf(fm.implemented_in), ...listOf(fm.documents)].filter(r => !SHA.test(r))
45
46export const isRecord = (rel: string) =>
47 /^docs\/adr\/\d{4}-[^/]+\.md$/.test(rel)
48 || (/^docs\/specs\/[^/]+\.md$/.test(rel) && !rel.endsWith('/README.md'))
49 || /^docs\/specs\/[^/]+\/spec\.md$/.test(rel)
50
51// the rules of the state that need nothing but the frontmatter; a record
52// with no `implementation` is not under the contract and is left alone
53export function stateProblems(fm: Front): string[] {
54 const state = fm.implementation
55 if (state === undefined) return []
56 if (typeof state !== 'string' || !STATES.includes(state)) return [`implementation: '${state}' is not one of ${STATES.join(', ')}`]
57 const refs = listOf(fm.implemented_in)
58 const note = String(fm.implementation_note ?? '').trim()
59 const out: string[] = []
60 if ((state === 'implemented' || state === 'partial') && !refs.length) out.push(`${state} names no evidence in implemented_in`)
61 if ((state === 'pending' || state === 'draft') && refs.length) out.push(`${state} cannot name evidence; implemented_in is for what was built`)
62 if ((state === 'partial' || state === 'dropped') && !note) out.push(`${state} needs an implementation_note`)
63 return out
64}
65
66const FENCE = /^(```|~~~)[^\n]*\n[\s\S]*?^\1[^\n]*$/gm
67const withoutFences = (text: string) => text.replace(FENCE, '')
68
69// relative markdown link targets outside code: no scheme, no bare anchor, no absolute path
70export function mdLinks(text: string): string[] {
71 const prose = withoutFences(text).replace(/`[^`\n]*`/g, '')
72 const out: string[] = []
73 for (const m of prose.matchAll(/\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g)) {
74 const target = m[1]!.split('#')[0]!.split('?')[0]!
75 if (!target || target.startsWith('/') || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue
76 try { out.push(decodeURI(target)) } catch { out.push(target) }
77 }
78 return out
79}
80
81// code spans outside fences that read as relative paths with a folder in
82// them, a line suffix (`:12`, `:3-9`, `#L12`) cut; the caller keeps only the
83// ones whose first folder is in the repo
84export function codePaths(text: string): string[] {
85 const out: string[] = []
86 for (const m of withoutFences(text).matchAll(/`([^`\s]+)`/g)) {
87 const token = m[1]!.replace(/(:\d+(-\d+)?|#L\d+(-L?\d+)?)$/, '')
88 if (!token.includes('/') || /^[/~.$-]/.test(token) || /[*<>{}()@=:\[\]]/.test(token)) continue
89 out.push(token)
90 }
91 return out
92}
93
94// the body under `## Decision`, up to the next heading of level 1 or 2
95export function decision(text: string): string | undefined {
96 const m = text.match(/^##\s+Decision\b[^\n]*\n([\s\S]*?)(?=^#{1,2}\s|(?![\s\S]))/m)
97 return m ? m[1] : undefined
98}
99
100// `**Status:** Accepted`, `- **Status:** accepted (date)`, or `status: accepted` in the frontmatter
101export const isAccepted = (text: string) => /\bstatus:?\**\s*:?\s*\**\s*accepted\b/i.test(text)
102
103// the ADR numbers a record supersedes or is superseded by
104export const supersedes = (text: string): string[] =>
105 [...text.matchAll(/supersed(?:ed by|es)\s+\[?ADR-(\d{4})/gi)].map(m => m[1]!)
106
107export const covers = (entry: string, rel: string) => rel === entry || rel.startsWith(`${entry.replace(/\/$/, '')}/`)
108
109// `a/../b` and `./` resolved; undefined when it climbs out of the root
110export function normalize(rel: string): string | undefined {
111 const out: string[] = []
112 for (const part of rel.split('/')) {
113 if (part === '..') { if (!out.length) return undefined; out.pop() }
114 else if (part && part !== '.') out.push(part)
115 }
116 return out.join('/')
117}
118
119// a `--format=@%ct --name-only` log, newest first
120export const parseLog = (out: string) => {
121 const log: { t: number; files: string[] }[] = []
122 for (const line of out.split('\n')) {
123 if (line.startsWith('@')) log.push({ t: Number(line.slice(1)), files: [] })
124 else if (line.trim() && log.length) log.at(-1)!.files.push(line.trim())
125 }
126 return log
127}
128
129export function describe(r: DocsReport): string {
130 if (!r.problems.length && !r.drift.length) return 'docs: nothing to report'
131 const lines = [`docs: ${r.problems.length} problems · ${r.drift.length} drifting`]
132 if (r.problems.length) {
133 lines.push('', 'Problems (a record whose implementation state breaks its rules, or that names what is not there):',
134 ...r.problems.map(p => `- ${p}`))
135 }
136 if (r.drift.length) {
137 lines.push('', `Drift (commits to the files a record lists since the record was last written; files ${HUB} or more records list are left out):`,
138 ...r.drift.map(d => `- ${d.rec}: ${d.commits} commit${d.commits > 1 ? 's' : ''}`))
139 }
140 return lines.join('\n')
141}
142
143export function reminder(why: string, files: string[], adrs: string[]): string {
144 const shown = files.length > 8 ? [...files.slice(0, 8), `${files.length - 8} more`] : files
145 return `silica-core: this turn's writes are worth recording (${why}): ${shown.join(', ')}. ` +
146 'Before you end the turn, bring docs/ up to date with what a later session would need: ' +
147 'a decision that had alternatives goes in an ADR under docs/adr/; ' +
148 (adrs.length ? `${adrs.join(', ')} list${adrs.length > 1 ? '' : 's'} these files in implemented_in or documents: if its decision still stands, update its implementation_note; ` +
149 'if this change reverses or replaces that decision, write a new ADR that supersedes it and mark the old one "Superseded by", never rewriting its Decision; ' : '') +
150 'a finding you measured or verified goes in the doc it belongs to; say whether a security check ran on this change, and which. ' +
151 'A routine change gets no doc: say "docs: nothing to record" in one line instead.'
152}
153hooks/types.d.ts 14 lines1// The values the module keeps in $.state (claude plugin validate holds it to this).
2export type SilicaCoreOffer = 'hidden' | 'offer' | 'indexing'
3
4// A scan of the folder's records: what breaks the implementation contract or
5// points nowhere, and the records whose files took commits since the record
6// was last written (docs/adr/0004).
7export type DocsReport = { problems: string[]; drift: { rec: string; commits: number }[] }
8
9declare module 'claude-code' {
10 interface PluginState {
11 'silica-core': { offer: SilicaCoreOffer; docs: DocsReport | null; isDocsHidden: boolean }
12 }
13}
14hooks/guidance.ts 4 lines1// Generated from silica_core/onboarding/guidance.py; tests/test_contract_nudges.py fails when they differ.
2export const START = "<!-- SILICA_START -->"
3export const GUIDANCE = "## silica-core\n\n- For a question about what the files in the current folder say, or how a behaviour is implemented, when no identifier is known: call `silica_search` with the question before any grep (a Grep tool, or grep or rg in a shell), Glob or Read. It ranks passages and, with the code index on, the functions, methods, classes and constants themselves, by the question's words and their vectors; a hit's `section` is the symbol, `span` its lines.\n- Grep for an exact string or a symbol name you already know; read a file directly when its path and section are already known.\n- Cite a hit's passage by path and line when it answers; read with `silica_read(path, section=\u2026)` only for missing context, carrying the hit's `version` as `expect_version`.\n- `terms_absent` and `coverage` are lexical diagnostics, not verdicts: a dense hit can answer with coverage 0. If the passages give no evidence, rephrase once keeping names and identifiers; then report what remains unfound."
4