opencode-self-improvement 0.30.1 → 0.30.3

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.
Files changed (104) hide show
  1. package/package.json +3 -2
  2. package/src/capture/available.ts +30 -31
  3. package/src/capture/candidates.ts +2 -2
  4. package/src/capture/checked.ts +3 -3
  5. package/src/capture/guided-rules.ts +1 -1
  6. package/src/capture/lag.ts +2 -2
  7. package/src/capture/policy.ts +7 -7
  8. package/src/capture/prompt.ts +4 -4
  9. package/src/capture/runtime.ts +86 -90
  10. package/src/capture/session-model.ts +2 -2
  11. package/src/capture/transcript.ts +5 -5
  12. package/src/capture/triggers.ts +7 -7
  13. package/src/consolidate/propose.ts +4 -4
  14. package/src/consolidate/render.ts +2 -2
  15. package/src/core/cmp-ts.ts +1 -1
  16. package/src/core/config/budgets.ts +1 -1
  17. package/src/core/config/paths.ts +1 -1
  18. package/src/core/guidance.ts +1 -1
  19. package/src/core/hooks.ts +4 -4
  20. package/src/core/host.ts +1 -1
  21. package/src/core/logfmt/format.ts +1 -1
  22. package/src/core/logfmt/publish.ts +1 -1
  23. package/src/core/logfmt/read.ts +1 -1
  24. package/src/core/lru.ts +1 -1
  25. package/src/core/state.ts +4 -4
  26. package/src/core/tags.ts +9 -10
  27. package/src/core/time.ts +1 -1
  28. package/src/core/tokenize.ts +1 -1
  29. package/src/events.ts +8 -8
  30. package/src/evidence/record.ts +10 -11
  31. package/src/gate/gate.ts +25 -25
  32. package/src/gate/value-conflict.ts +7 -8
  33. package/src/hits/ledger.ts +4 -4
  34. package/src/identity/host-events.ts +3 -3
  35. package/src/identity/repokey.ts +7 -7
  36. package/src/identity/session-context.ts +7 -7
  37. package/src/index.ts +6 -6
  38. package/src/init/detect.ts +3 -3
  39. package/src/init/format.ts +6 -6
  40. package/src/init/retag.ts +7 -7
  41. package/src/init/run.ts +18 -18
  42. package/src/init/stamp.ts +17 -17
  43. package/src/inject/anchor.ts +1 -1
  44. package/src/inject/budget.ts +1 -1
  45. package/src/inject/digest.ts +5 -5
  46. package/src/inject/epochs.ts +15 -15
  47. package/src/inject/format.ts +2 -2
  48. package/src/inject/pull.ts +3 -3
  49. package/src/inject/version.ts +1 -1
  50. package/src/portable/decay.ts +1 -1
  51. package/src/portable/export.ts +7 -7
  52. package/src/portable/import.ts +5 -5
  53. package/src/recall/conflicts.ts +1 -1
  54. package/src/recall/dedupe.ts +31 -55
  55. package/src/recall/gate.ts +19 -40
  56. package/src/recall/relevant.ts +11 -11
  57. package/src/recall/score.ts +14 -23
  58. package/src/recall/shared-terms.ts +1 -1
  59. package/src/status/format.ts +1 -1
  60. package/src/status/metrics.ts +5 -5
  61. package/src/status/payload.ts +4 -4
  62. package/src/status/report.ts +5 -5
  63. package/src/status/store-summary.ts +1 -1
  64. package/src/status/write.ts +3 -4
  65. package/src/store/blocklist.ts +1 -1
  66. package/src/store/files/append.ts +8 -8
  67. package/src/store/files/deletions.ts +3 -3
  68. package/src/store/files/load.ts +5 -5
  69. package/src/store/files/prune.ts +8 -8
  70. package/src/store/files/snapshots.ts +1 -1
  71. package/src/store/files/supersede.ts +11 -12
  72. package/src/store/files/target.ts +1 -1
  73. package/src/store/lock.ts +12 -12
  74. package/src/store/model/memory.ts +4 -4
  75. package/src/store/model/predicates.ts +2 -2
  76. package/src/store/model/provenance.ts +1 -1
  77. package/src/store/model/visibility.ts +4 -4
  78. package/src/store/prune.ts +1 -1
  79. package/src/store/quarantine/quarantine.ts +2 -2
  80. package/src/store/quarantine/release.ts +2 -2
  81. package/src/store/secrets.ts +1 -1
  82. package/src/store/tombstones/rejection.ts +1 -1
  83. package/src/store/tombstones/tombstone.ts +5 -5
  84. package/src/store/undo.ts +12 -12
  85. package/src/tools/consolidate.ts +1 -1
  86. package/src/tools/decay.ts +2 -2
  87. package/src/tools/deps.ts +1 -1
  88. package/src/tools/evidence.ts +4 -4
  89. package/src/tools/export.ts +1 -1
  90. package/src/tools/forget.ts +2 -2
  91. package/src/tools/import.ts +3 -3
  92. package/src/tools/init.ts +1 -1
  93. package/src/tools/list.ts +1 -1
  94. package/src/tools/merge-review.ts +11 -11
  95. package/src/tools/recall.ts +5 -5
  96. package/src/tools/registry.ts +2 -2
  97. package/src/tools/remember.ts +4 -4
  98. package/src/tools/schema.ts +4 -4
  99. package/src/tools/status-tool.ts +5 -5
  100. package/src/tools/undo.ts +4 -4
  101. package/src/tools/update.ts +18 -19
  102. package/src/viewer/mutate.ts +13 -13
  103. package/src/viewer/rejections.ts +1 -1
  104. package/src/viewer/server.ts +47 -49
@@ -38,7 +38,7 @@ interface InjectionEpochOptions {
38
38
  // The host listener records usage. Eviction must still drop it with the
39
39
  // epoch and request counters, so no measurement outlives its tracked session.
40
40
  measuredTurns: Pick<Map<string, Measured>, "get" | "delete">;
41
- /** Evict the per-message usage ledger (#394) with the session. */
41
+ /** Evict the per-message usage ledger with the session. */
42
42
  forgetUsage?: (sid: string) => void;
43
43
  noteHits: (sid: string, rows: Memory[], query: string) => Promise<void>;
44
44
  }
@@ -54,12 +54,12 @@ export function createInjectionEpochs({
54
54
  // Per-session frozen injection epochs: the whole memory section (digest +
55
55
  // frontier + relevance) plus the store fingerprint it was rendered from.
56
56
  // Recomputed on the first prompt of a tracked session, when injectable rows
57
- // change, when a new prompt re-scores the block (#335), or after a
57
+ // change, when a new prompt re-scores the block, or after a
58
58
  // compaction (see the prompt/context/compaction hooks).
59
59
  // The RENDERED BYTES, not the fingerprint, decide whether the epoch moved
60
- // (issue #162): a write that changes nothing the model is shown must not
60
+ // (issue): a write that changes nothing the model is shown must not
61
61
  // cost the next request a full re-prefill. And a pure addition the session
62
- // wrote itself does not move them either (#165) — see refreshEpoch. The
62
+ // wrote itself does not move them either — see refreshEpoch. The
63
63
  // shared LRU below may evict the whole session state; a later prompt starts
64
64
  // it fresh.
65
65
  const epoch = new Map<
@@ -74,7 +74,7 @@ export function createInjectionEpochs({
74
74
  prefix: string;
75
75
  /**
76
76
  * Rows THIS session had already authored when these bytes were rendered
77
- * (#165). The riding-bytes test subtracts everything authored after this
77
+ *. The riding-bytes test subtracts everything authored after this
78
78
  * snapshot; if what remains renders identically, the whole difference is
79
79
  * the session's own additions and the bytes keep riding.
80
80
  */
@@ -150,7 +150,7 @@ export function createInjectionEpochs({
150
150
  // removals fail-closed: an out-of-band redaction or a block during a tool
151
151
  // loop cannot ride one more request waiting for another user prompt.
152
152
  // The caller's sid is resolved to an immutable Reader BEFORE the store
153
- // read (#127): while loadAll awaits, another session's hooks may dispatch
153
+ // read: while loadAll awaits, another session's hooks may dispatch
154
154
  // and move the ambient current; filtering with THAT leaks the other
155
155
  // session's repo into this one's system prompt.
156
156
  const injectableRows = async (sid?: string): Promise<Memory[]> => {
@@ -164,7 +164,7 @@ export function createInjectionEpochs({
164
164
  // followed by this epoch's relevance block. The parts are exactly what gets
165
165
  // pushed onto `event.system`; their join is the byte key the epoch compares
166
166
  // against, so "did the cache-critical prefix change?" is answered by the
167
- // bytes the model would actually see and never by a proxy (issue #162).
167
+ // bytes the model would actually see and never by a proxy (issue).
168
168
  const buildMemorySection = async (
169
169
  sid: string | undefined,
170
170
  mems: Memory[],
@@ -194,10 +194,10 @@ export function createInjectionEpochs({
194
194
  promptOverride ??
195
195
  (sid === undefined ? "" : (latestPrompt.get(sid) ?? ""));
196
196
  // Widen the candidate pool, then cap: the budget decides what rides.
197
- // The guided cap (#335) rides user-stated rows ahead of the lexical picks;
197
+ // The guided cap rides user-stated rows ahead of the lexical picks;
198
198
  // the char budget below still bounds the whole block. The conflict check
199
199
  // reads the session's OWN repo directory (its reader's scope) — never an
200
- // ambient one (#127's rule applies to code reads too).
200
+ // ambient one (the rule applies to code reads too).
201
201
  const reader = readerFromSid(sid);
202
202
  const sel = await selectRelevant(
203
203
  prompt,
@@ -207,7 +207,7 @@ export function createInjectionEpochs({
207
207
  undefined,
208
208
  {
209
209
  guidedCap: 3,
210
- // #388: budget the RIDING set by priority here, before the block is
210
+ // budget the RIDING set by priority here, before the block is
211
211
  // rendered in canonical order. Capping the rendered string (the old
212
212
  // path) made recency decide who got dropped, because the newest row is
213
213
  // now always first.
@@ -266,7 +266,7 @@ export function createInjectionEpochs({
266
266
  // Cheap pre-check: no injectable row moved AND the frozen bytes were
267
267
  // already scored against THIS prompt. Skips re-scoring and the use-ledger
268
268
  // write on ordinary turns and on every tool-loop request within a turn.
269
- // A new prompt does re-score (#335, the epoch-freeze flaw): a block
269
+ // A new prompt does re-score (the epoch-freeze flaw): a block
270
270
  // frozen at the first request carried the first topic's rows for the
271
271
  // whole session and never picked up the rows a later prompt genuinely
272
272
  // matches. Cache is still safe — the epoch only MOVES when the rendered
@@ -284,7 +284,7 @@ export function createInjectionEpochs({
284
284
  epoch.set(sid, { ...cached, version, prompt });
285
285
  return;
286
286
  }
287
- // Riding bytes (#165): a pure addition this session wrote itself is
287
+ // Riding bytes: a pure addition this session wrote itself is
288
288
  // information it already has — the model produced it, it is in the
289
289
  // transcript. Re-render the section with every row authored SINCE these
290
290
  // bytes were frozen taken back out: if it comes back byte-identical, the
@@ -310,7 +310,7 @@ export function createInjectionEpochs({
310
310
  }
311
311
  }
312
312
  }
313
- // Use ledger (#42): the rows that actually rode the block, credited with
313
+ // Use ledger: the rows that actually rode the block, credited with
314
314
  // the terms the prompt and those rows shared (never the prompt itself).
315
315
  // Only once the build is ADOPTED — a discarded rebuild must not credit
316
316
  // rows that were already offered under the frozen epoch.
@@ -346,7 +346,7 @@ export function createInjectionEpochs({
346
346
  // guidedSeen=0 -> capture never wrote the row. guidedSeen>0 with the
347
347
  // id absent from `guided` -> the cap (newest-first, 3) dropped it.
348
348
  // In `guided` but absent from `guidedRode` -> the budget inside
349
- // selectRelevant dropped it (#388 moved the cap there from capToBudget).
349
+ // selectRelevant dropped it (cap moved here from capToBudget).
350
350
  // In `guidedRode` yet absent from the wire -> render/transport, or a
351
351
  // paraphrased needle (now impossible for rows carrying `orig=true`).
352
352
  ...(built.guidedSeen ? { guidedSeen: built.guidedSeen } : {}),
@@ -388,7 +388,7 @@ export function createInjectionEpochs({
388
388
  if (typeof sid === "string") await refreshEpoch(sid, mems);
389
389
  // Deliver the FROZEN memory section. Every byte pushed onto the system
390
390
  // prompt comes from the epoch, so between busts the provider sees an
391
- // identical prefix and serves the conversation from cache (issue #162).
391
+ // identical prefix and serves the conversation from cache (issue).
392
392
  // A session with no epoch yet (no prompt recorded, or evicted from the
393
393
  // LRU) still gets the standing digest, built fresh and uncached.
394
394
  const ep = typeof sid === "string" ? epoch.get(sid) : undefined;
@@ -1,4 +1,4 @@
1
- // format — split from src/inject.ts (#168 domain restructure). Declaration bodies are unchanged.
1
+ // format — split from src/inject.ts. Declaration bodies are unchanged.
2
2
  import { type Memory } from "../store/model/memory.ts";
3
3
  import { provenanceMarker, provenanceOf } from "../store/model/provenance.ts";
4
4
  import { flattenMemoryText } from "../store/sanitize.ts";
@@ -21,7 +21,7 @@ export function formatMemory(m: Memory): string {
21
21
  const tag = m.status === "open" ? " [open]" : "";
22
22
  const via = PROVENANCE_TAGS.filter((t) => m.tags?.includes(t));
23
23
  const src = via.length ? ` [via ${via.join("+")}]` : "";
24
- // #393: the discount the reader needs. `[via auto-capture]` says where a row
24
+ // the discount the reader needs. `[via auto-capture]` says where a row
25
25
  // came from; this says whether anything OUTSIDE that source ever agreed with
26
26
  // it. R4 measured the cost of not saying so: one plausible wrong row shipped a
27
27
  // wrong artifact in 4/5 runs with no uncertainty flagged, while an empty store
@@ -1,4 +1,4 @@
1
- // pull — split from src/inject.ts (#168 domain restructure). Declaration bodies are unchanged.
1
+ // pull — split from src/inject.ts. Declaration bodies are unchanged.
2
2
  import { loadAll } from "../store/files/load.ts";
3
3
  import { type Memory } from "../store/model/memory.ts";
4
4
  import { isInjectable } from "../store/model/predicates.ts";
@@ -16,7 +16,7 @@ export interface TransformOutput {
16
16
  export interface PullInput {
17
17
  tool?: unknown;
18
18
  args?: unknown;
19
- // The session the pull runs FOR (#127): resolved to an immutable Reader at
19
+ // The session the pull runs FOR: resolved to an immutable Reader at
20
20
  // entry so the loadAll await below cannot drift into another session's repo.
21
21
  sessionID?: unknown;
22
22
  }
@@ -36,7 +36,7 @@ export async function contextualPull(
36
36
  const term = argText(input.args);
37
37
  if (!term) return [];
38
38
  // Repo-scoped: model-facing reads see the CALLER's repo + global rows —
39
- // the pull's own sessionID, resolved before the store read (#127).
39
+ // the pull's own sessionID, resolved before the store read.
40
40
  const mems = visibleTo(
41
41
  (await loadAll()).filter(isInjectable),
42
42
  readerFromSid(input.sessionID),
@@ -1,4 +1,4 @@
1
- // version — split from src/inject.ts (#168 domain restructure). Declaration bodies are unchanged.
1
+ // version — split from src/inject.ts. Declaration bodies are unchanged.
2
2
  // Context surfaces: a small system digest, a capped open-thread frontier, and
3
3
  // relevance-ranked memory frozen per epoch by src/index.ts. These ride the
4
4
  // session context hook's system parts. Contextual pull appends relevant memory
@@ -1,4 +1,4 @@
1
- // decay — split from src/portable.ts (#168 domain restructure). Declaration bodies are unchanged.
1
+ // decay — split from src/portable.ts. Declaration bodies are unchanged.
2
2
  import { open } from "node:fs/promises";
3
3
  import { loadAll } from "../store/files/load.ts";
4
4
  import { type Memory } from "../store/model/memory.ts";
@@ -1,4 +1,4 @@
1
- // export — split from src/portable.ts (#168 domain restructure). Declaration bodies are unchanged.
1
+ // export — split from src/portable.ts. Declaration bodies are unchanged.
2
2
  // Portability: JSONL export/import of the durable store, plus the
3
3
  // stale-open-thread query that backs memory_decay. Import NEVER writes: every
4
4
  // row flows through the caller-provided gate callback (index.ts wires it to
@@ -39,12 +39,12 @@ export interface ExportOptions {
39
39
  * Destination, confined to <memory-root>/exports/ (see containment.ts).
40
40
  * Defaults to <memory-root>/exports/<stamp>-<unique>.jsonl: a UNIQUE name,
41
41
  * created exclusively, so two exports in the same second can never replace
42
- * each other's artifact (#143's review). An explicit `file` keeps the
42
+ * each other's artifact. An explicit `file` keeps the
43
43
  * historical replace semantics backups rely on.
44
44
  */
45
45
  file?: string;
46
46
  /**
47
- * The calling session's identity (#143): an export carries exactly the rows
47
+ * The calling session's identity: an export carries exactly the rows
48
48
  * its reader can read — own repo plus global. "?" or absent resolves the
49
49
  * AMBIENT reader: out-of-plugin callers (viewer, CLI maintenance) keep the
50
50
  * full-store breadth; breadth stays a property of the entry point.
@@ -60,7 +60,7 @@ export interface ExportResult {
60
60
  // Filesystem-safe YYYY-MM-DDTHHMMSS (no colons) plus a unique suffix for each
61
61
  // default export. The timestamp alone was second-granular: two sessions
62
62
  // exporting in the same second got the SAME path, and O_TRUNC let the later
63
- // one destroy the earlier one's artifact AND its returned path (#143 review).
63
+ // one destroy the earlier one's artifact AND its returned path.
64
64
  // Milliseconds would still collide; uniqueness comes from the name, not the
65
65
  // clock.
66
66
  export function stamp(d: Date = new Date()): string {
@@ -139,7 +139,7 @@ export async function writeExport(
139
139
  // where it lives (the original logfmt files + snapshots). The header is always
140
140
  // written, even for an empty store, so "has header" is a format invariant.
141
141
  //
142
- // "the live store" means the store AS THE CALLER CAN READ IT (#143): rows are
142
+ // "the live store" means the store AS THE CALLER CAN READ IT: rows are
143
143
  // filtered through the caller's Reader, exactly as recall and injection do.
144
144
  // Full breadth remains the ambient/admin entry point's, never a missing
145
145
  // session's.
@@ -163,10 +163,10 @@ export async function exportMemories(
163
163
  count: mems.length,
164
164
  });
165
165
  // An export is a copy at rest, so it must not carry credentials that were
166
- // stored before the write-side redaction existed (#74 slice 1). Redaction is
166
+ // stored before the write-side redaction existed. Redaction is
167
167
  // applied to the value being serialised, never to the row: export stays a
168
168
  // read path, and the store remains the byte-of-record for memory_undo.
169
- // #300 extends the same rule to the metadata fields: `scope`, `tags` and `kw`
169
+ // extends the same rule to the metadata fields: `scope`, `tags` and `kw`
170
170
  // are free prose a row can carry, and a legacy or hand-edited row can hold a
171
171
  // credential in them even though new writes refuse it. `repo`/`repoPath` stay
172
172
  // as stored — they are derived stamps, not prose, and rewriting them would
@@ -1,4 +1,4 @@
1
- // import — split from src/portable.ts (#168 domain restructure). Declaration bodies are unchanged.
1
+ // import — split from src/portable.ts. Declaration bodies are unchanged.
2
2
  import { open, readFile } from "node:fs/promises";
3
3
  import { allowOutsideStorePaths, memoryRoot } from "../core/config/paths.ts";
4
4
  import { resolveContained } from "../store/containment.ts";
@@ -25,7 +25,7 @@ export interface ImportTally {
25
25
  skipped: number;
26
26
  /** Open rows downgraded because the file cannot grant that frontier scope. */
27
27
  downgraded: number;
28
- /** Promoted rows whose write_promoted audit line failed to land (#155 review). */
28
+ /** Promoted rows whose write_promoted audit line failed to land. */
29
29
  unaudited: number;
30
30
  /** First audit-fault message, so the reply can name what went wrong. */
31
31
  auditError?: string;
@@ -114,15 +114,15 @@ export async function importMemories(
114
114
  gate: (
115
115
  c: WriteCandidate,
116
116
  ) => Promise<{ action: string; evidenceError?: string }>,
117
- // The importing session, captured at tool entry (#127): "the importing
117
+ // The importing session, captured at tool entry: "the importing
118
118
  // session's current repo" must be the CALLER's repo even though this loop
119
119
  // awaits the gate on every row, during which a concurrent session can move
120
120
  // the ambient current.
121
121
  sessionID?: string,
122
122
  ): Promise<ImportTally> {
123
123
  // Capture the importing owner before file I/O: later session moves must not
124
- // re-home rows partway through the import (#183). Resolve with the writer
125
- // rule so an unresolved named session never borrows the ambient repo (#152).
124
+ // re-home rows partway through the import. Resolve with the writer
125
+ // rule so an unresolved named session never borrows the ambient repo.
126
126
  const writeAt = writeTarget(sessionID ?? getCurrent().sid);
127
127
  const target = await resolveContained(path, memoryRoot(), {
128
128
  label: "memory_import file",
@@ -3,7 +3,7 @@
3
3
  // and klass (who holds authority). At render time the plugin reads the code —
4
4
  // bounded, deterministic, NO model call — and a collision renders ONE flagged
5
5
  // CONFLICT line whose Action is fixed by the class: behavior class trusts the
6
- // code, spec class fixes it. #345 measured the alternative twice: a wrong
6
+ // code, spec class fixes it. Measured twice: a wrong
7
7
  // guided row made the agent rewrite a correct constant (raw row) and the
8
8
  // framing-only fix stayed a coin flip (2 harms in 5). The class rule held 6/6.
9
9
  import {
@@ -1,52 +1,28 @@
1
- // Near-duplicate suppression inside a returned window (#409, RESULTS §17).
1
+ // Near-duplicate suppression inside a returned window: one deterministic pass
2
+ // AFTER ranking.
2
3
  //
3
- // The live store carries repeated rows — superseded snapshots, cursor rows that
4
- // differ only by a timestamp, the same decision restated after a compaction —
5
- // and the matcher scores them all the same. With a fixed window they crowd out
6
- // distinct facts, which is what breaks composition: two memories a later task
7
- // needs together rarely fit side by side because the first one's copies take
8
- // the slots.
4
+ // Skip a candidate whose content-token Jaccard against an already-kept row of
5
+ // the same scope reaches the threshold; the NEWEST copy of a clash takes the
6
+ // slot, because the duplicates in a live store are stale cursors and
7
+ // superseded snapshots. ON by default at 0.8; OPENCODE_MEMORY_DEDUP=0 returns
8
+ // the plain top-limit slice, byte-identical to no pass. A value below 0.5 or
9
+ // above 1, or one that is not a number, is a misconfiguration and turns the
10
+ // pass off.
9
11
  //
10
- // The fix is one deterministic pass AFTER ranking: skip any candidate whose
11
- // content-token Jaccard against an already-kept row of the same scope reaches
12
- // the threshold, keeping the NEWEST copy of a clash (§17's adoption rule: the
13
- // live duplicates are stale cursors and superseded snapshots, so the row that
14
- // survives is the one written last, not the one that ranked highest). No model,
15
- // no new index, and ON by default — a window padded with near-copies of the top
16
- // hit is paid-for context nobody reads, and a quality fix behind an opt-in flag
17
- // is not a fix. Explicit opt-out:
12
+ // Guards, each pinned by a test:
13
+ // - Compare content tokens only. Type and scope are not tokens: same-scope
14
+ // rows would share two free tokens and short rows would look alike.
15
+ // - A pair where exactly one row carries a negation word is never a copy:
16
+ // "force push main" inside "never force push main" reaches Jaccard 0.833 and
17
+ // the wrong copy would survive.
18
+ // - A row under MIN_CONTENT content tokens is never suppressed; non-Latin
19
+ // prose tokenises to nothing and there is nothing to compare.
20
+ // - A pair whose numeric literals differ is never a copy: short tokens are
21
+ // dropped, so "DB 3" and "DB 4" otherwise share identical token sets.
18
22
  //
19
- // OPENCODE_MEMORY_DEDUP=0 (the plain top-limit slice, byte-identical)
20
- //
21
- // Threshold guidance from the live replay (§17): 0.5-0.7 suppresses rows that
22
- // are merely related (92% of them at 0.5) and forces the window deep into the
23
- // ranking; 0.8 suppresses only near-identical copies. Values below 0.5 are a
24
- // misconfiguration, not an aggressive setting: at Jaccard 1e-9 a single shared
25
- // fragment suppressed rows, so anything under 0.5 turns the pass off.
26
- //
27
- // WHAT COUNTS AS A NEAR-COPY — the first version's three mistakes, each pinned
28
- // by a test:
29
- //
30
- // 1. It scored `type` and `scope` as tokens. Same-scope rows then shared two
31
- // free tokens, so short rows looked like copies of each other. Comparison is
32
- // content-only.
33
- // 2. It compared whole token sets, so a prohibition read as a copy of the
34
- // permission it denies: "force push main" inside "never force push main"
35
- // reaches Jaccard 0.833, and at threshold 0.8 the WRONG copy survived. If
36
- // exactly one row of a pair carries a negation word, it is not a copy.
37
- // 3. It had no floor. Non-Latin prose tokenises to nothing under `words()`
38
- // (which splits on [^a-z0-9_]+), so two unrelated Chinese rows in one scope
39
- // both reduced to the empty content set — Jaccard over empty sets is
40
- // defined here as 0, but the pre-floor version scored them on type and
41
- // scope alone at 1.0 and deleted the second row. A row with fewer than
42
- // MIN_CONTENT content tokens is never suppressed: there is nothing to
43
- // compare.
44
- // 4. It treated differing numeric facts as duplicates. `words()` drops tokens
45
- // of length <= 2, so "Rate limiter reads Redis DB 3." and "...DB 4." have
46
- // identical token sets (Jaccard 1) and the older row was suppressed even at
47
- // threshold 1 (review #415, reproduced through the handler). Numbers are
48
- // compared as a sorted multiset of literals and a pair that disagrees on
49
- // them is never a copy.
23
+ // Threshold guidance: 0.5-0.7 suppresses merely-related rows and forces the
24
+ // window deep into the ranking; 0.8 suppresses near-identical copies only.
25
+ // History and measurements: docs/adr/0002.
50
26
  import type { Memory } from "../store/model/memory.ts";
51
27
  import { words } from "./score.ts";
52
28
 
@@ -111,7 +87,7 @@ export function jaccard(a: Set<string>, b: Set<string>): number {
111
87
  /**
112
88
  * The short tokens `words()` drops (chunks of length <= 2). They are where
113
89
  * single-digit facts hide: "Rate limiter reads Redis DB 3." and "...DB 4."
114
- * have identical token sets and reach Jaccard 1 (review #415). Timestamped
90
+ * have identical token sets and reach Jaccard 1. Timestamped
115
91
  * cursor rows — the rows this pass exists to suppress — keep their digit
116
92
  * groups inside longer tokens ("15z"), so comparing the dropped chunks only
117
93
  * guards real fact changes without touching the cursor case. A pair whose
@@ -136,12 +112,12 @@ function sameDroppedChunks(a: Memory, b: Memory): boolean {
136
112
 
137
113
  /**
138
114
  * A row's own tokens: built DIRECTLY from the content and keyword fields.
139
- * Never from `haystack()` — the identifier tokenizer (#417) splits a
140
- * snake_case scope like `auth_token_refresh_policy` into auth/token/refresh/
141
- * policy, and deleting only the whole scope/type strings left those words
142
- * standing in for content: two unrelated non-Latin rows in one scope shared
143
- * a Jaccard-1 metadata vocabulary, cleared MIN_CONTENT on scope tokens alone,
144
- * and dedup hid one (#421, post-merge report on #417).
115
+ * Never from `haystack()` — the identifier tokenizer splits a snake_case
116
+ * scope like `auth_token_refresh_policy` into auth/token/refresh/policy, and
117
+ * deleting only the whole scope/type strings leaves those words standing in
118
+ * for content: two unrelated non-Latin rows in one scope then share a
119
+ * Jaccard-1 metadata vocabulary, clear MIN_CONTENT on scope tokens alone,
120
+ * and dedup hides one.
145
121
  */
146
122
  export function contentTokens(m: Memory): Set<string> {
147
123
  const text = m.content + (m.kw?.length ? ` ${m.kw.join(" ")}` : "");
@@ -171,8 +147,8 @@ export function dedupeWindow(
171
147
  if (threshold <= 0 || ranked.length <= 1) return ranked.slice(0, limit);
172
148
  // Token sets are built lazily and cached per index: the loop stops once
173
149
  // `limit` rows are kept, so eager tokenization of every candidate costs
174
- // 1.7ms/12.5ms/96.4ms at 200/2k/10k candidates on every query recall
175
- // (review #426). Lazy cost is window-sized.
150
+ // 1.7ms/12.5ms/96.4ms at 200/2k/10k candidates on every query recall.
151
+ // Lazy cost is window-sized.
176
152
  const tokenCache = new Map<number, Set<string>>();
177
153
  const tokensOf = (i: number): Set<string> => {
178
154
  let t = tokenCache.get(i);
@@ -1,44 +1,23 @@
1
- // Two-concept admission for the recall tool's matcher (#409, case bank).
1
+ // Two-concept admission for the recall tool's matcher.
2
2
  //
3
- // The tool scores a row by counting how many of the query's words appear in it
4
- // as substrings, and returns anything that scores above zero. One shared word is
5
- // enough, so `watermark 283 287 head` returns every row that mentions a head,
6
- // and `fixer ready tickets queue blocked` returns rows about the GitHub CLI and
7
- // about npm publishing. Measured on 404 real recall queries taken from 30 days of
8
- // session transcripts and labelled by two independent readers,
9
- // a large share of what the tool returned was judged irrelevant rather than
10
- // answering.
3
+ // A query of LONG_QUERY_TOKENS concepts or more is a deliberate search: a row
4
+ // must share two whole-word concepts with it to be returned. Shorter queries
5
+ // keep the matcher's permissive one-concept admission. This is the rule the
6
+ // injection path already applies (LONG_QUERY_TOKENS in score.ts); the two
7
+ // paths must agree on when nothing is a good enough answer. Admission only:
8
+ // ranking, scoring and window size are untouched.
11
9
  //
12
- // The injection path already refuses single-concept matches once a query is long
13
- // enough to be a deliberate search (LONG_QUERY_TOKENS in score.ts). This applies
14
- // that rule to the tool, so the two paths agree on when nothing is a good enough
15
- // answer. It changes admission only: ranking, scoring and the window size are
16
- // untouched. ON by default — the two paths disagreeing was the bug, and a
17
- // quality fix that nobody flips on is not a fix. Explicit opt-out:
10
+ // ON by default. Off only for an explicit negative (see gateEnabled): a
11
+ // quality fix that nobody flips on is not a fix, and a typo must not disable
12
+ // it.
18
13
  //
19
- // OPENCODE_MEMORY_QUERY_GATE=off (also 0 / no / n / false)
14
+ // TRAP: admission counts whole words; the scorer counts substrings on
15
+ // purpose. A substring is not a concept — `on` occurs inside `context`, `pr`
16
+ // inside `preference`, `283` inside `build2837` — so the gate must not reuse
17
+ // the matcher's own substring test. Whole words keep number queries exact:
18
+ // the concept `277` matches a row citing that number and not `2830`.
20
19
  //
21
- // WHY THE GATE COUNTS WORDS AND THE SCORER COUNTS SUBSTRINGS
22
- //
23
- // These are different questions, and using the tool's own substring test here was
24
- // the first version's mistake. Scoring asks how strongly a row matches, and
25
- // substring matching is deliberate there: it is how `getUserAccount` finds a row
26
- // written `get_user_account`. Admission asks how many DISTINCT CONCEPTS the query
27
- // and the row share, and a substring is not a concept. Counting substrings made
28
- // the gate satisfiable by two accidents: `on` occurs inside `context` and inside
29
- // `decision`, so every row of those types shared it; `pr` occurs inside
30
- // `preference`; and `283` occurs inside `build2837`, so the query that motivated
31
- // this change, `watermark 283 287 head`, still admitted the row it was supposed to
32
- // refuse. The gate therefore compares whole words, and drops the query's stopwords
33
- // and fragments, which is exactly the vocabulary the injection scorer counts.
34
- //
35
- // Whole words are also what makes the number queries work. `#277` tokenises to
36
- // `277`, so a PR-number search still matches the row that cites it, while `283` no
37
- // longer matches `#2830`.
38
- //
39
- // STATUS: measured on the case bank; see the PR for the current numbers. The
40
- // first version's numbers were measured with substring counting and are void.
41
- // See https://github.com/abogartz/opencode-self-improvement/issues/409.
20
+ // History and measurements: docs/adr/0001.
42
21
  import type { Memory } from "../store/model/memory.ts";
43
22
  import { LONG_QUERY_TOKENS, QUERY_STOPWORDS, words } from "./score.ts";
44
23
 
@@ -80,8 +59,8 @@ export function recallHaystack(m: Memory): string {
80
59
 
81
60
  // Split into whole words at whitespace and punctuation. Underscore stays inside a
82
61
  // word so the identifier a user searches for — `db_id`, `OPENCODE_MEMORY_DIR` —
83
- // survives as the single concept it is (splitting it is the regression that
84
- // blocked PR #417); a dash separates, because prose writes `get-user-account` as
62
+ // survives as the single concept it is (splitting it breaks exact identifier
63
+ // queries); a dash separates, because prose writes `get-user-account` as
85
64
  // the three words it means. `build2837` stays one word, which is why `283` can no
86
65
  // longer match it.
87
66
  const WORD = /[^a-z0-9_]+/;
@@ -101,7 +80,7 @@ export function queryConcepts(query: string): string[] {
101
80
 
102
81
  /** The row's concepts, as a set for whole-word membership tests. */
103
82
  export function rowConcepts(m: Memory): Set<string> {
104
- // Union of two vocabularies (#426 review). The #417 scorer tokenizer over
83
+ // Union of two vocabularies. The scorer tokenizer over
105
84
  // the ORIGINAL-case haystack carries whole identifiers plus camel/separator
106
85
  // segments, so a prose query is admitted against an identifier written in
107
86
  // any style. But words() segments at EVERY separator: `table.db_id` yields
@@ -1,4 +1,4 @@
1
- // relevant — split from src/inject.ts (#168 domain restructure). Declaration bodies are unchanged.
1
+ // Injection ranking: scoring inputs, the use ledger, and the hint channel.
2
2
  import { loadAll } from "../store/files/load.ts";
3
3
  import { type Memory } from "../store/model/memory.ts";
4
4
  import { isInjectable } from "../store/model/predicates.ts";
@@ -22,17 +22,17 @@ export function argText(args: unknown): string {
22
22
 
23
23
  /**
24
24
  * The content concepts a query and a row actually share (stopwords dropped,
25
- * capped, `ts` never included). This is what the use ledger records (#42):
25
+ * capped, `ts` never included). This is what the use ledger records:
26
26
  * every term in it already exists inside the row, so a hit line reveals
27
27
  * nothing about the prompt beyond the memory it points at — and it is enough
28
- * for #45 to replay a merge and prove the same reads would still land.
28
+ * to replay a merge and prove the same reads would still land.
29
29
  */
30
30
  /** The text a contextual pull actually searched with, for hit bookkeeping. */
31
31
  export function pullQuery(args: unknown): string {
32
32
  return argText(args);
33
33
  }
34
34
 
35
- // Reinforcement (#42): a row the ledger has seen used breaks a tie over a row
35
+ // Reinforcement: a row the ledger has seen used breaks a tie over a row
36
36
  // nobody ever read, and the more recently used one breaks it first. A TIE-BREAK
37
37
  // only — the two-concept gate and IDF score still decide relevance, because
38
38
  // popularity is not truth: reinforcement without evidence just amplifies
@@ -52,7 +52,7 @@ export function useBoost(a: Memory | undefined, use?: UseSignals): number {
52
52
  // keeps its string contract for every existing caller; this is the richer seam.
53
53
  export interface SelectOptions {
54
54
  /**
55
- * Hint channel (#335): when > 0, the newest `guidedCap` user-guided rows
55
+ * Hint channel: when > 0, the newest `guidedCap` user-guided rows
56
56
  * ride the block FIRST regardless of lexical overlap — a user-stated value
57
57
  * ("the tax rate is 8.25%") shares no vocabulary with a task prompt about
58
58
  * "the injected bug", and the whole point of capturing guidance is that the
@@ -73,7 +73,7 @@ export interface SelectOptions {
73
73
  */
74
74
  repoDir?: string;
75
75
  /**
76
- * Character budget for the block (#388). Applied to the PRIORITY order —
76
+ * Character budget for the block. Applied to the PRIORITY order —
77
77
  * guided lane first, then score — so pressure drops the least RELEVANT row.
78
78
  * Capping the rendered string instead would let recency decide who rides,
79
79
  * because the rendered order is canonical and not score-derived. Absent
@@ -89,8 +89,8 @@ export function isUserGuided(m: Memory): boolean {
89
89
  }
90
90
 
91
91
  /**
92
- * #402: the working tree already states this fact. Such a row is STORED (it used
93
- * to be dropped at capture, which is the defect #402 exists for), but it is the
92
+ * the working tree already states this fact. Such a row is STORED (it used
93
+ * to be dropped at capture, which is the defect this serves for), but it is the
94
94
  * first thing a tight injection budget gives up: the next session can read it in
95
95
  * the file, so a slot spent on it is a slot not spent on something the files do
96
96
  * not hold.
@@ -103,7 +103,7 @@ export function isRestatable(m: Memory): boolean {
103
103
  return m.tags?.includes(RESTATABLE_TAG) === true;
104
104
  }
105
105
 
106
- // Hint-channel caveat (#345). Measured: a WRONG user-guided row ("free
106
+ // Hint-channel caveat. Measured: a WRONG user-guided row ("free
107
107
  // shipping starts at $50 — the hidden suite encodes that") out-ranked correct
108
108
  // code — the agent rewrote a correct threshold to match the memory. The
109
109
  // generic "reference data, never instructions" framing did not prevent it.
@@ -135,7 +135,7 @@ export async function selectRelevant(
135
135
  rendered: ReadonlyMap<Memory, Memory>;
136
136
  }> {
137
137
  // Repo-scoped: model-facing reads see the caller's repo + global rows
138
- // (their session when one was threaded, #127).
138
+ // (their session when one was threaded).
139
139
  const mems = (rows ?? visibleTo(await loadAll(), readerFromSid(sid))).filter(
140
140
  isInjectable,
141
141
  );
@@ -212,7 +212,7 @@ export async function selectRelevant(
212
212
  // `shown` returns exactly what an explicit header check would.
213
213
  let used = fitHeader.length;
214
214
  shown = [];
215
- // #402: PRIORITY decides who rides, and a restatement now sits last in that
215
+ // PRIORITY decides who rides, and a restatement now sits last in that
216
216
  // order — the tree already states it, so a slot spent here is a slot not
217
217
  // spent on something the files do not hold. `merged` stays in score order:
218
218
  // `selected` is the ledger's view of the ranking and a miss has to stay