pi-context-engine 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -116,7 +116,6 @@ embedding:
116
116
  model: local # or a specific transformers.js model id
117
117
  ollama_model: nomic-embed-text
118
118
  indexer:
119
- watch: true
120
119
  redact_secrets: true
121
120
  memory:
122
121
  redact_pii: true
@@ -131,6 +130,16 @@ Environment overrides:
131
130
  - **`PCE_EMBED_BACKEND`**: force `local` or `ollama` instead of auto-detect.
132
131
  - **`PCE_RECALL_DISPLAY_CAP`**: how many recall hits to show (default 7).
133
132
 
133
+ **Embedding backends**: two options, picked automatically per project.
134
+
135
+ - **Ollama** (default when reachable): no extra model files on disk beyond the
136
+ Ollama model itself.
137
+ - **Local ONNX** (transformers.js): works with no server. Needs the
138
+ `@huggingface/transformers` optional dependency, which plain `npm` and `pi`
139
+ installs include. If it was stripped (e.g. `--omit=optional`), indexing fails
140
+ with a clear message telling you to reinstall or switch to Ollama, instead of
141
+ a bare module error.
142
+
134
143
  ## Security
135
144
 
136
145
  Indexing is local, but the index is still a copy of your code. Two guards ship on
@@ -0,0 +1,483 @@
1
+ # Implementation plan: retrieval improvements
2
+
3
+ Full build plan for the recommendations in
4
+ [RESEARCH-RETRIEVAL.md](./RESEARCH-RETRIEVAL.md). Nothing here is started yet:
5
+ implementation is deliberately delayed, this document defines exactly what will
6
+ be built, in what order, and how each item is proven before its status changes.
7
+
8
+ **Why a plan first:** every item changes retrieval behavior, and our only
9
+ current metrics are token savings and latency. Building the measurement harness
10
+ before the changes lets us prove each improvement instead of guessing.
11
+
12
+ ## How to use this document
13
+
14
+ - **Status legend**
15
+ - **Not started**: planned, nothing built yet. All items are here today.
16
+ - **Ready**: implementation can begin (dependencies met, baseline recorded).
17
+ - **In progress**: work branch open.
18
+ - **Review**: code done, eval deltas attached to the PR.
19
+ - **Done**: merged, released, status table updated.
20
+ - **Dropped**: decided against, with the reason recorded in the item.
21
+ - **Rules for flipping a status**
22
+ 1. Typecheck and unit tests pass (`npm run check`).
23
+ 2. Eval deltas (before/after) are recorded in the PR description.
24
+ 3. README and `src/config.ts` cover any new config keys.
25
+ 4. This table is updated in the same PR.
26
+ - **Every item lists**: objective, evidence, files touched, steps, tests,
27
+ acceptance criteria, risks, dependencies, effort (S < half day, M 1-2 days,
28
+ L 3-5 days).
29
+
30
+ ---
31
+
32
+ ## Status summary
33
+
34
+ | ID | Title | Phase | Priority | Effort | Status |
35
+ |----|-------|-------|----------|--------|--------|
36
+ | R4 | Labeled retrieval eval harness | 0 | P0 | M | Not started |
37
+ | R1 | Contextual chunk headers | 1 | P0 | M | Not started |
38
+ | R2 | BM25 phrases, column weights, symbol matches | 1 | P0 | S | Not started |
39
+ | R3 | Query-aware compression | 1 | P0 | M | Not started |
40
+ | R5 | Multi-path retrieval with symbol path | 2 | P1 | M | Not started |
41
+ | R6 | Small-to-big context expansion | 2 | P1 | L | Not started |
42
+ | R7 | Graph context packs + centrality prior | 2 | P1 | M | Not started |
43
+ | R8 | Query-confidence signal + optional elaboration | 2 | P1 | M | Not started |
44
+ | R9 | Refine suggestions in search results | 2 | P1 | S | Not started |
45
+ | R10 | Opt-in local reranker | 3 | P2 | M | Not started |
46
+ | R11 | Code-specialized embedder option | 3 | P2 | S | Not started |
47
+ | R12 | AST density chunking (split-merge) | 3 | P2 | L | Not started |
48
+ | R13 | Linked memory (A-MEM style) | 3 | P2 | M | Not started |
49
+
50
+ **Blocked by nothing right now:** only R4 (phase 0). Everything else waits on
51
+ R4's baseline so its impact can be measured.
52
+
53
+ **Status history**
54
+ - 2026-10-17: plan created from the research note. Implementation delayed by
55
+ owner decision. All items set to **Not started**.
56
+
57
+ ---
58
+
59
+ ## Phase 0: measurement foundation
60
+
61
+ ### R4. Labeled retrieval eval harness
62
+
63
+ - **Objective:** measure retrieval quality (not just tokens) so every later
64
+ item has a before/after number.
65
+ - **Evidence:** CORE-Bench (arXiv:2606.11864) shows code-search scores overstate
66
+ agentic usefulness; UDCG (arXiv:2510.21440) shows distracting chunks must be
67
+ counted; Voyage reports CoSQA has ~51% bad labels, so we label our own.
68
+ - **Files:**
69
+ - new `tests/eval/queries.jsonl` (labels)
70
+ - new `scripts/eval-retrieval.mjs` (runner, tsx)
71
+ - `scripts/smoke-real-world.mjs` (add a `quality` block to its report)
72
+ - new `tests/eval/baseline.json` (recorded thresholds)
73
+ - `package.json` (`eval` script, wire into `check`)
74
+ - **Steps:**
75
+ 1. Write 60-100 labeled queries over this repo, four kinds: exact identifier
76
+ (`HybridRetriever`), natural language (`where is the retry logic`),
77
+ bug-report style (paste an error string), file-name style
78
+ (`src/retrieval/retriever.ts`). Each label lists expected file paths and,
79
+ where easy, expected chunk line ranges.
80
+ 2. Runner indexes a fixture copy of the repo, runs each query through
81
+ `HybridRetriever`, and computes: Recall@5, Recall@10, nDCG@10, distraction
82
+ ratio (share of served chunks whose file is not in the label set), served
83
+ tokens, p50/p95 latency.
84
+ 3. Implement nDCG in the script (no dependency); binary relevance is enough.
85
+ 4. Record current numbers into `baseline.json`; the runner exits non-zero on
86
+ regression beyond a small tolerance (start at 2 points on Recall@10).
87
+ 5. Add an optional external slice later (CORE-Bench level-2 sample) as a
88
+ separate non-gating script.
89
+ - **Tests:** runner produces stable output twice in a row; a deliberately
90
+ broken query (random words) scores below baseline.
91
+ - **Acceptance:** `npm run eval` reports all metrics, fails on regression, and
92
+ is documented in README's Development section.
93
+ - **Risks:** labels drift when the repo changes. Mitigation: labels point at
94
+ files/paths, not exact line numbers, except where a test pins them.
95
+ - **Dependencies:** none. **Effort:** M.
96
+
97
+ ---
98
+
99
+ ## Phase 1: quick wins (P0)
100
+
101
+ ### R1. Contextual chunk headers
102
+
103
+ - **Objective:** give every chunk its surrounding context before embedding and
104
+ indexing, so "the retrieval module" style queries find `src/retrieval/*`
105
+ code.
106
+ - **Evidence:** Anthropic Contextual Retrieval: failed retrievals −49% with
107
+ contextual embeddings + contextual BM25; late chunking (arXiv:2409.04701)
108
+ +2.7-3.6% nDCG from the same missing-context problem.
109
+ - **Files:**
110
+ - `src/indexer/chunker.ts` (`nodeToChunk`, `walk`: collect enclosing class,
111
+ imports, exported symbol names)
112
+ - `src/types.ts` (optional `metadata.contextHeader`)
113
+ - `src/indexer/pipeline.ts` (`embedChunks` currently embeds `c.content`)
114
+ - `src/indexer/manifest.ts` (index format version bump)
115
+ - `src/indexer/embedding-cache.ts` (expect full cache invalidation)
116
+ - **Steps:**
117
+ 1. Define header format, deterministic and LLM-free:
118
+ `// file: src/retrieval/retriever.ts | lang: typescript | unit: class HybridRetriever | imports: ./confidence, ./query-parser`
119
+ Header must respect `indexer.redact_secrets` (path only, no file body).
120
+ 2. Prepend the header in one place at chunk build time so embed, FTS and
121
+ `expand_chunk` all see the same text. Decision: header goes into
122
+ `content`, single source of truth, no second code path.
123
+ 3. Bump `manifest` format version so existing installs reindex automatically
124
+ (content hash change already invalidates the embedding cache).
125
+ 4. Keep header length capped (~120 tokens) so small chunks do not become
126
+ header-dominated.
127
+ - **Tests:** header contains file path and unit name; cap respected; redacted
128
+ paths behave; ids stay unique (id hashes `content.slice(0,100)`, so the
129
+ header prefix changes ids: confirm full reindex, no stale rows).
130
+ - **Acceptance:** eval shows Recall@k up or flat, no regression on identifier
131
+ queries, latency within 10% of baseline.
132
+ - **Risks:** header noise on very small chunks; path-only leakage of private
133
+ directory names (accepted, index is local and paths already go to FTS).
134
+ - **Dependencies:** R4 baseline. **Effort:** M.
135
+
136
+ ### R2. Strengthen BM25: phrases, column weights, symbol matches
137
+
138
+ - **Objective:** make the strongest code retriever work properly for quoted
139
+ phrases and path queries.
140
+ - **Evidence:** Finding 6 (BM25 strongest for code, arXiv:2605.14503);
141
+ Anthropic reports contextual BM25 as the larger single jump (35% → 49%).
142
+ - **Files:** `src/storage/fts-store.ts` (`escapeFts5`, `search`),
143
+ `src/retrieval/retriever.ts` (existing `FTS_BOOST_CODE_LOOKUP`),
144
+ tests under `tests/`.
145
+ - **Steps:**
146
+ 1. Parse quoted spans before tokenizing; emit FTS5 phrase strings
147
+ (`"foo bar"`) for them and keep OR-joining unquoted tokens.
148
+ 2. Add explicit `bm25()` column weights in `ORDER BY`: weight `file_path`
149
+ highest, then `content`, then `chunk_type`; leave `language` neutral.
150
+ 3. Exact symbol shortcut: if a query token matches a chunk's symbol name
151
+ (metadata from R1/R12, fallback regex on content), give it a deterministic
152
+ score bonus in `retriever.ts`.
153
+ 4. Keep stopword fallback and the `code_lookup` FTS weight as they are.
154
+ - **Tests:** phrase query matches only adjacent terms; path query ranks its
155
+ file top-3; OR behavior for unquoted terms unchanged; empty/stopword-only
156
+ queries still return the existing fallback.
157
+ - **Acceptance:** identifier and file-name slices of the eval improve; no
158
+ slice regresses by more than 1 point.
159
+ - **Risks:** FTS5 phrase syntax with punctuation-heavy tokens (code symbols
160
+ contain `_`, `.`); mitigate by tokenizing phrase content the same way FTS5
161
+ tokenizer does for indexed content.
162
+ - **Dependencies:** R4. **Effort:** S.
163
+
164
+ ### R3. Query-aware compression
165
+
166
+ - **Objective:** stop cutting the lines that answer the question.
167
+ - **Evidence:** Finding 12 (aggressive compression consistently harmful,
168
+ budget ≥ 8000, arXiv:2605.14503); SWE-Pruner (arXiv:2601.16746) 23-54% token
169
+ cut with task-conditioned selection; LLMLingua budget controller.
170
+ - **Files:** `src/compression/compressor.ts` (`TRUNCATION_LIMITS`, prompts),
171
+ `src/retrieval/retriever.ts` (packing uses
172
+ `chunk.compressedContent` length), `src/config.ts`, README config block.
173
+ - **Steps:**
174
+ 1. Add `compress(content, level, query?)`. With a query: keep signature
175
+ lines, import block, any line containing a query token or identifier, then
176
+ apply the cap to the remainder.
177
+ 2. Pass query terms into the Ollama summary prompt (`{query}` slot) so
178
+ summaries mention the asked-for symbols; keep the existing
179
+ `QualityChecker` identifier-ratio gate as the safety net.
180
+ 3. `full` becomes budget-driven: no fixed cap, only the retrieval token
181
+ budget trims it (aligns with the ≥ 8000 guidance).
182
+ 4. New config: `compression.query_aware: true` (default on), so users can
183
+ revert to the old fixed behavior.
184
+ - **Tests:** query tokens always survive truncation; identifier ratio stays
185
+ ≥ 0.4; without query, output is byte-identical to today (regression guard).
186
+ - **Acceptance:** at equal or lower served tokens, Recall@k does not drop; on
187
+ the bug-report slice it rises.
188
+ - **Risks:** keeping many matched lines can exceed caps; cap logic must prefer
189
+ matched lines over head lines, with a hard ceiling.
190
+ - **Dependencies:** R4. **Effort:** M.
191
+
192
+ ---
193
+
194
+ ## Phase 2: retrieval depth (P1)
195
+
196
+ ### R5. Multi-path retrieval with a structured symbol path
197
+
198
+ - **Objective:** stop relying on similarity alone for "where is X defined".
199
+ - **Evidence:** CodeRAG (arXiv:2509.16112) multi-path retrieval is a core gain;
200
+ the coding-agent preprint found production agents mix lexical, semantic and
201
+ structural signals.
202
+ - **Files:** `src/storage/graph-store.ts` (symbol lookup), `src/retrieval/
203
+ retriever.ts` (third RRF list), `src/retrieval/query-parser.ts` (extract
204
+ symbol candidates), `src/storage/local-backend.ts`.
205
+ - **Steps:**
206
+ 1. Add `findSymbol(name)`: exact then case-insensitive then prefix match
207
+ over graph node names (function/class/file nodes).
208
+ 2. Add file-path exact match as its own path using existing `fileHints`.
209
+ 3. Fuse vector, FTS and symbol results with the existing RRF (k=60); symbol
210
+ and path lists get the same weight class as `code_lookup`'s FTS boost.
211
+ 4. Keep `MAX_CHUNKS_PER_FILE` and marginal-ratio logic after fusion.
212
+ - **Tests:** exact symbol query returns its chunk in top-3; unknown symbol
213
+ falls back to current behavior; fusion does not double-count a chunk.
214
+ - **Acceptance:** identifier slice Recall@5 improves; general slice flat.
215
+ - **Risks:** symbol collisions across files (dedupe by file, prefer file hint).
216
+ **Dependencies:** R4, benefits from R1 headers. **Effort:** M.
217
+
218
+ ### R6. Small-to-big context expansion
219
+
220
+ - **Objective:** serve enough surrounding context per hit to answer without a
221
+ second tool call.
222
+ - **Evidence:** cross-file context length was the dominant parameter
223
+ (2048 → 8192 tokens = up to +4.2 points, arXiv:2605.04763); small-to-big
224
+ retrieval is the standard fix; cAST metadata retention added +2.7 on SWE-bench.
225
+ - **Files:** `src/indexer/chunker.ts` (emit module/top-level chunks),
226
+ `src/retrieval/retriever.ts` (expansion stage, packing),
227
+ `src/config.ts`.
228
+ - **Steps:**
229
+ 1. Emit, for every AST file, a `module` chunk covering top-level statements,
230
+ imports and exported names, so code outside functions is retrievable.
231
+ 2. After ranking, expand each top hit: attach the file's module chunk plus
232
+ one neighboring chunk above/below when budget allows. Mark provenance in
233
+ metadata (`served_via: self|module|neighbor`) for eval analysis.
234
+ 3. Expansion must run inside the `maxTokens` budget and must not break the
235
+ marginal-ratio stop (expanded context counts as part of the parent hit).
236
+ 4. Fix the interaction with `dedupeOverlaps`: a module chunk overlaps every
237
+ function chunk in the file and would be dropped. Exempt parent-tier chunks
238
+ from overlap dedupe, dedupe only within a tier.
239
+ - **Tests:** module chunk survives dedupe; expansion respects budget;
240
+ provenance recorded; concat property of module + function chunks still
241
+ reconstructs the file.
242
+ - **Acceptance:** cross-file and NL slices improve Recall@10 and distraction
243
+ ratio, with served tokens up by no more than the configured budget share.
244
+ - **Risks:** token creep; duplicate content between module and function chunks
245
+ wastes budget (mitigate: serve module chunk in compressed form by default).
246
+ **Dependencies:** R4, R3 (compression runs on expanded content). **Effort:** L.
247
+
248
+ ### R7. Graph context packs with a centrality prior
249
+
250
+ - **Objective:** make the repository graph a real retrieval path, not a
251
+ 2-chunk bonus.
252
+ - **Evidence:** RepoGraph (ICLR 2025) gained +2.66/+2.34 absolute on
253
+ SWE-bench-Lite across four systems at roughly constant cost; Aider's PageRank
254
+ file ranking was observed working in practice.
255
+ - **Files:** `src/storage/graph-store.ts`, `src/storage/local-backend.ts`,
256
+ `src/indexer/pipeline.ts` (compute prior at index time),
257
+ `src/retrieval/retriever.ts`, `src/extension.ts` (`related_context` output).
258
+ - **Steps:**
259
+ 1. At index time, run a small power-iteration PageRank over the file-level
260
+ import graph and store it as node `properties.pagerank`.
261
+ 2. In retrieval, build a context pack per top hit: the node's callers,
262
+ callees, importers and importees with edge types and line refs, capped at
263
+ N lines and included in the token budget.
264
+ 3. Apply centrality as a bounded prior: score multiplier in
265
+ `[1 - p, 1 + p]` with `retrieval.graph_prior` default `0.05`. Never let it
266
+ outrank a relevance gap larger than the prior.
267
+ 4. Extend `related_context` to return the same packs for manual drilling.
268
+ - **Tests:** pack contains at least one caller/importer on a fixture repo;
269
+ prior is clamped to its range; graph failures stay best-effort (existing
270
+ try/catch behavior).
271
+ - **Acceptance:** cross-file slice improves; cost per query stays within
272
+ +20 ms of baseline warm latency.
273
+ - **Risks:** dense graphs flood the pack (cap by degree, prefer higher-ranked
274
+ neighbors); PageRank staleness on incremental reindex (recompute per
275
+ full index, reuse on partial).
276
+ - **Dependencies:** R4, R6 (packs ride the same budget path). **Effort:** M.
277
+
278
+ ### R8. Query-confidence signal and optional elaboration
279
+
280
+ - **Objective:** tell the agent when a search was weak, and let it recover,
281
+ without silent query rewriting.
282
+ - **Evidence:** predicted query performance correlates with answer quality
283
+ (arXiv:2507.10411); Findings 1/2/4 (raw query wins, elaborate only when
284
+ ambiguous, LLM rewrites drift); Search-R1 for the loop framing.
285
+ - **Files:** `src/retrieval/confidence.ts`, `src/retrieval/query-parser.ts`,
286
+ `src/guidance.ts`, `src/extension.ts` (tool result shape), `src/config.ts`.
287
+ - **Steps:**
288
+ 1. Compute query-level signals: top final score, margin to the next distinct
289
+ file, vector/FTS agreement (Jaccard of their top-10), candidate count.
290
+ 2. Map to `query_confidence: high|medium|low` with thresholds calibrated
291
+ against the eval set, stored in config so they are tunable.
292
+ 3. Return the signal plus 1-3 deterministic recovery hints (add a file path,
293
+ use an exact symbol, drop vague terms) when confidence is low.
294
+ 4. Optional elaboration behind `retrieval.auto_elaborate` (default `false`):
295
+ generate a deterministic variant (stopword-stripped, file hints injected,
296
+ terms from near-miss top hits), run both, fuse with RRF, always keep the
297
+ raw query's results as primary.
298
+ 5. Document the signal and the loop in the guidance section so the agent
299
+ knows to refine instead of re-reading files.
300
+ - **Tests:** weak synthetic query gets `low` and hints; strong identifier query
301
+ gets `high`; elaboration never removes raw-query results; no network calls.
302
+ - **Acceptance:** guidance renders, config off switches everything off, eval
303
+ unchanged when elaboration is disabled.
304
+ - **Risks:** noisy confidence on tiny indexes (calibrate on the fixture, floor
305
+ the candidate count). **Dependencies:** R4. **Effort:** M.
306
+
307
+ ### R9. Refine suggestions in search results
308
+
309
+ - **Objective:** turn a one-shot tool into a guided loop at near-zero token cost.
310
+ - **Evidence:** every production coding agent in the exploratory preprint
311
+ narrows iteratively; RepoCoder's loop drives its reported gain.
312
+ - **Files:** `src/extension.ts` (result shaping), optionally
313
+ `src/engine.ts`; guidance text in `src/guidance.ts`.
314
+ - **Steps:**
315
+ 1. From the top hits, derive up to 3 next queries: a sibling symbol from the
316
+ same file (graph `defines` edges), a near-miss file ranked 11-15 that was
317
+ not served, one alternate term that appears often in top hits.
318
+ 2. Emit as a single `refine:` line in the tool result; cap length.
319
+ 3. Config `retrieval.refine_hints` (default `true`), documented in README.
320
+ - **Tests:** cap of 3; never suggests a file already served; disabled by config.
321
+ - **Acceptance:** token overhead ≤ 40 tokens per call; no eval regression.
322
+ - **Risks:** hints duplicating what the agent would do anyway (measure usage in
323
+ session telemetry later). **Dependencies:** R5, R7 for better symbol/family
324
+ hints (can ship with weaker heuristics first). **Effort:** S.
325
+
326
+ ---
327
+
328
+ ## Phase 3: gated experiments (P2)
329
+
330
+ Each phase-3 item ships **behind config, default off**, and only graduates to
331
+ default-on if the eval shows a win and latency budget holds.
332
+
333
+ ### R10. Opt-in local reranker
334
+
335
+ - **Objective:** test whether cross-encoder reranking helps *our* workloads.
336
+ - **Evidence is split, on purpose:** harmful for SE tasks with 815 ms GPU cost
337
+ (Findings 10/11), a core gain in CodeRAG, −67% failures with Anthropic's
338
+ stack. Only our eval can decide.
339
+ - **Files:** new `src/retrieval/reranker.ts`, `src/config.ts`, README.
340
+ - **Steps:**
341
+ 1. Use the already-shipped `@huggingface/transformers` for
342
+ `text-classification` with an ONNX reranker (candidate:
343
+ `Xenova/ms-marco-MiniLM-L-6-v2`), cached in the existing models dir.
344
+ 2. Rerank only the fused candidate list (cap 30), then re-apply path penalty,
345
+ file diversity and marginal stop.
346
+ 3. Config: `retrieval.rerank: off | local` (default `off`),
347
+ `retrieval.rerank_model`, `retrieval.rerank_topn`.
348
+ 4. One-time model download must be explicit (never on by default) because it
349
+ adds ~80 MB to a package that markets "one npm command".
350
+ - **Tests:** mock pipeline ordering (no model in unit tests); opt-in path
351
+ exercised in a smoke test with a stubbed model.
352
+ - **Acceptance:** measured eval delta (up or down) and p95 latency recorded in
353
+ the PR; default stays `off` unless quality wins justify the download.
354
+ - **Risks:** CPU latency; ONNX export availability for the chosen model.
355
+ **Dependencies:** R4 mandatory. **Effort:** M.
356
+
357
+ ### R11. Code-specialized embedder option
358
+
359
+ - **Objective:** offer, and only recommend, a code-trained local embedder.
360
+ - **Evidence:** Findings 7/8 say scale and code-specialization did not decide
361
+ outcomes, but CORE-Bench shows agentic retrieval is harder and in-domain
362
+ training helped a lot.
363
+ - **Files:** `src/indexer/embedder.ts` (model list), README embedding section.
364
+ - **Steps:**
365
+ 1. Document `embedding.model: <hf-id>` with one tested code-oriented model
366
+ and the existing general defaults.
367
+ 2. Run the eval for each backend; publish the table in README.
368
+ 3. Dimension change already forces full reindex; verify the migration path.
369
+ - **Tests:** backend selection unit test; reindex-on-dimension-change test
370
+ (logic exists, add a regression test if missing).
371
+ - **Acceptance:** README shows measured numbers per model, not claims.
372
+ - **Dependencies:** R4. **Effort:** S.
373
+
374
+ ### R12. AST density chunking (cAST-style split-merge)
375
+
376
+ - **Objective:** replace worst-measured strategy (whole function nodes) with
377
+ budgeted, self-contained chunks.
378
+ - **Evidence:** function chunking −3.57 to −5.64 points and never
379
+ Pareto-optimal (arXiv:2605.04763); cAST +4.3 Recall@5, +2.67 Pass@1
380
+ (arXiv:2506.15655).
381
+ - **Files:** `src/indexer/chunker.ts` (core rework), `src/types.ts`
382
+ (metadata: `symbol`, `parent`, `segment`), `src/config.ts`, chunk-id scheme
383
+ in `makeChunk`.
384
+ - **Steps:**
385
+ 1. Top-down fit: a node fits if its non-whitespace chars ≤
386
+ `indexer.chunk_budget_chars` (default ~1200, configurable).
387
+ 2. Oversized nodes split at syntactic children; only leaf-level overflow uses
388
+ line windows. Greedy-merge small adjacent siblings up to budget.
389
+ 3. Emit module/top-level chunks (shared with R6).
390
+ 4. Preserve chunk-id uniqueness for split segments (add segment index; keep
391
+ the upstream column-offset fix that the README documents).
392
+ 5. Keep the legacy chunker behind `indexer.chunking: legacy | ast-density`
393
+ (default `legacy`) for A/B on the same index format.
394
+ 6. Verify the concat property: chunks concatenated reproduce the file.
395
+ - **Tests:** concat round-trip; id uniqueness on duplicate spans; budget
396
+ respected; legacy mode byte-identical to today.
397
+ - **Acceptance:** `ast-density` wins the eval on at least Recall@10 without
398
+ inflating chunk count beyond +30%; then flip the default in its own release.
399
+ - **Risks:** more chunks = more embeddings = slower first index (content-hash
400
+ cache limits repeat cost); id scheme changes force a full reindex.
401
+ **Dependencies:** R4, R6 (module chunks shared), ideally after R1 so headers
402
+ apply to the new chunk shapes. **Effort:** L.
403
+
404
+ ### R13. Linked memory (A-MEM style)
405
+
406
+ - **Objective:** make cross-session recall improve with age instead of
407
+ degrading.
408
+ - **Evidence:** A-MEM (NeurIPS 2025): dynamic indexing, linking between
409
+ memories and memory evolution beat fixed structures on six models.
410
+ - **Files:** `src/memory/db.ts`, `decision-extractor.ts`,
411
+ `session-capture.ts`, `record_decision` tool surface in `extension.ts`.
412
+ - **Steps:**
413
+ 1. On `record_decision`: embed it, find top-3 past decisions above a
414
+ similarity threshold, store `related_to` edges (new edge type alongside
415
+ `decided`/`discussed_in`), cap links per memory.
416
+ 2. Store structured attributes on write: keywords, tags, affected files
417
+ (files already feed `record_code_area`).
418
+ 3. Memory evolution: allow a later decision to annotate an earlier one
419
+ (`relatedTo` tool parameter) instead of only appending rows; keep the
420
+ original text immutable, append annotations with timestamps.
421
+ 4. Surface links in `session_recall` output so the agent can walk them.
422
+ - **Tests:** threshold and cap behavior; no self-links; redaction still applies
423
+ before any write (PII guard must run before link text is stored).
424
+ - **Acceptance:** a seeded recall test shows linked neighbours surfacing;
425
+ latency of `record_decision` stays under +100 ms.
426
+ - **Risks:** link noise from loose thresholds (calibrate on a fixture set).
427
+ **Dependencies:** R4-style eval extended to memory recall. **Effort:** M.
428
+
429
+ ---
430
+
431
+ ## Cross-cutting work
432
+
433
+ - **Index format versioning:** R1, R6 and R12 each change on-disk content.
434
+ Add `manifest.formatVersion`; bump it per item and force a full reindex with
435
+ a logged migration line (the dimension-change path in `pipeline.ts` is the
436
+ template).
437
+ - **Config surface:** new keys land in `src/config.ts`, the README
438
+ Configuration block, and the guidance text in one PR per item. Planned keys:
439
+ - `compression.query_aware`, `retrieval.auto_elaborate`,
440
+ `retrieval.graph_prior`, `retrieval.refine_hints`,
441
+ `retrieval.rerank`, `retrieval.rerank_model`, `retrieval.rerank_topn`,
442
+ `indexer.chunk_budget_chars`, `indexer.chunking`.
443
+ - **Guidance updates:** R8 and R9 change how the agent should use the tool, so
444
+ `src/guidance.ts` must document the confidence signal and refine hints in the
445
+ same release, keeping the ~900-token budget.
446
+ - **Docs:** README tables (What you get, How it works, Configuration,
447
+ Differences from upstream) updated per release; research evidence lives in
448
+ `RESEARCH-RETRIEVAL.md`, build detail here.
449
+ - **Releases:** every item ships through a PR to `main` and a `v*.*.*` tag per
450
+ the packages AGENTS.md recipe. Suggested grouping, adjustable once baselines
451
+ exist:
452
+ - **0.2.0**: R4 + R1 + R2 + R3 (measurement + phase 1), format version bump.
453
+ - **0.3.0**: R5 + R6 + R7 (retrieval depth).
454
+ - **0.4.0**: R8 + R9 (agentic loop).
455
+ - **0.5.0+**: whichever of R10-R13 wins its experiment, one per release.
456
+ - **Definition of done (per item):** `npm run check` green, eval deltas in the
457
+ PR, README/config/guidance updated, status table in this file flipped.
458
+
459
+ ---
460
+
461
+ ## Explicit non-goals
462
+
463
+ Recorded so they are not re-litigated later:
464
+
465
+ - **No always-on LLM query rewriting** (Finding 4, +987 tokens per rewrite).
466
+ - **No default reranking** (Findings 10-11; R10 stays opt-in).
467
+ - **No aggressive compression defaults** (Finding 12).
468
+ - **No chunk overlap** by default (two evaluations found no clear benefit).
469
+ - **No bigger-embedder reflex** (Findings 7-8); R11 must win on the eval.
470
+ - **No full-file indexing** as a substitute for retrieval (Anthropic notes it
471
+ only makes sense under ~200k tokens).
472
+
473
+ ---
474
+
475
+ ## Open questions that gate work
476
+
477
+ 1. Does the function-chunking penalty transfer to our question workload?
478
+ R4 then R12 answer this with data.
479
+ 2. Which side of the reranking debate applies to pi? R10 answers it.
480
+ 3. Should confidence weights (0.5 vector / 0.4 keyword / 0.1 recency) be
481
+ fitted on the eval set instead of fixed? A cheap follow-up after R4.
482
+ 4. Do refine suggestions change agent behavior in real sessions? Needs opt-in
483
+ session telemetry after R9.