opencode-self-improvement 0.32.0 → 0.33.0

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.
@@ -20,3 +20,20 @@ The live store carries repeated rows — superseded snapshots, cursor rows diffe
20
20
  4. It treated differing numeric facts as duplicates: short tokens are dropped, so "DB 3" and "DB 4" share identical token sets and the older row was suppressed even at threshold 1.
21
21
  - Default-ON followed the same rule as ADR 0001: a quality fix behind an opt-in flag is not a fix.
22
22
  - Evidence: live-store replay published in the #409 record (§17) and PR #426. The replay's off-arm must set `OPENCODE_MEMORY_DEDUP=0` explicitly — with default-ON, an unset arm measures nothing.
23
+
24
+ ## Addition groups
25
+
26
+ A clash is not always a copy. `classifyPair` reads the leftover token sets and splits three cases:
27
+ `identical` (nothing left over — one row typed twice), `addition` (one side wholly contained — the
28
+ rows name different things, so both hold), `substitution` (a leftover on each side). Only `addition`
29
+ is decidable from containment, and only `addition` keeps both rows; it takes an extra slot and the
30
+ handler marks the pair with `AMBIGUOUS` rather than deciding silently. Flag:
31
+ `OPENCODE_MEMORY_AMBIGUOUS`, on by default.
32
+
33
+ `substitution` is an interpretation, not a decision, and its absence of containment is not evidence
34
+ of a correction. Two instructions naming two scripts that both exist — `bun run bench:recall` and
35
+ `bun run bench:write` — leave a leftover on each side, score 0.882, and the older is dropped. That
36
+ predates the split and the split does not fix it: the pass has no way to learn from a row's text that
37
+ both scripts are real. It is the remaining limitation of the rule, and the reason the group marker
38
+ exists at all — where the classifier can see both readings are possible, it says so instead of
39
+ choosing.
@@ -34,7 +34,7 @@ ask on purpose.
34
34
 
35
35
  ### Explicit exact-keyword lookup
36
36
 
37
- See the [transport lookup benchmark](https://github.com/abogartz/opencode-self-improvement/blob/64c494a26866851077ed2d59504c62a4f7809b56/bench/transport-lookup-results.md) for explicit recall and automatic injection on the same queries.
37
+ See the [transport lookup benchmark](https://github.com/abogartz/opencode-self-improvement/blob/main/bench/transport-lookup-results.md) for explicit recall and automatic injection on the same queries.
38
38
 
39
39
  ## Why the default window is 5 rows
40
40
 
@@ -10,6 +10,21 @@ what an update carries with it.
10
10
 
11
11
  Promotion evidence keeps a bounded sample of call IDs: the ten most recent code-engagement calls, plus the latest gate check, the latest recorded gate FAIL/fix/PASS recovery, and the latest recorded tool FAIL/PASS retry (at most 16 distinct IDs). `evidence_refs_count` is the total number of recorded session calls before sampling, including non-code tools; the sampled IDs are audit pointers, not a complete history. Grounding and memory attribution still use the full in-memory ledger. Existing evidence day-files are left unchanged: this upgrade does not backfill, compact, or delete historical audit records.
12
12
 
13
+ ## When a cited path stops existing
14
+
15
+ A settled claim about code must point at a file the repository has, so a write naming a missing path is refused with `ref_path_missing`. That check runs on writes only. A row that was correct when it was saved goes stale on its own the moment a later refactor moves the file, and nothing notices: recall keeps quoting a path the reader cannot open.
16
+
17
+ `scripts/ref-fixer.ts` repairs the mechanical cases. The default is a dry run; `--apply` writes through the same gated update path as `memory_update`, so the old row is superseded rather than edited and `memory_undo` stays the recovery path. It repoints a path under two rules, and each is narrow for a specific reason:
18
+
19
+ 1. **A scored rename.** Git records a rename scored at least `R90` whose chain ends at a file that exists today and whose basename is unchanged. The floor is measured rather than guessed: this repository's renames cluster at `R090`..`R100` — the domain restructure, where the only content change is the import lines inside the moved file — and the outliers below it (`R058`, `R072`, `R080`, `R086`, `R088`) are files git scored as renames after much of their content was rewritten. The basename matters because it is what a query matches on — `src/lock.ts` to `src/store/lock.ts` still says "lock", so the row stays findable by the words that found it before.
20
+ 2. **A loose citation.** The path never existed anywhere in git history and exactly one tracked file ends with it: `gate/gate.ts` for `src/gate/gate.ts`. Both halves are load-bearing. Without the history check, a path the gate once refused as hallucinated would be handed a verified reference; without the single-candidate check, the fixer would pick a directory on the row's behalf.
21
+
22
+ Anything else is reported, never rewritten. A path occupied by more than one generation — moved away and recreated at the same path, in either order around the move — is one of those: rows written against each generation cite the same string and describe different files, and nothing in a row's text says which generation it belongs to. None of that is visible in a rename count. A file moved away, recreated and later deleted leaves no second rename record; a file deleted, recreated and then moved has the rename as its newest touch. Both are one path with two creations, so the check counts how many times history created each path — an add, or a rename or copy landing on it — and refuses above one. The count applies to every path the chain walks, destination included: move `src/lock.ts` to `legacy/lock.ts`, delete it, and commit something unrelated at `legacy/lock.ts`, and the chain ends on a file the original component never occupied. The report names whichever path is ambiguous, which need not be the one the row cites. A rename that also renamed the file (`src/logfmt.ts` to `src/core/logfmt/publish.ts`) changes what the sentence asserts, and a path that once existed and is gone was retired on purpose — a row about it is the record that it existed, and rewording that is a decision, not a repair.
23
+
24
+ The edit itself is span-based, not a substring replace. Only the references `checkablePathRefs` reports are touched, at the offsets they occupy. That is the safety property: a replace over the whole string also hits a ref nested inside a longer one (`gate/gate.ts` inside `src/gate/gate.ts` becomes `src/src/gate/gate.ts`) and rewrites absolute paths that the checker deliberately skips — so the gate could never refuse the damage, because it never sees those.
25
+
26
+ Two limits worth knowing before trusting a clean report. Rows are selected by repository key, defaulting to the current directory: rows stamped for another repository, and rows with no stamp at all, are never scanned, because no tree here owns their paths. And a repointed row can still be refused, with a reason that is informative rather than a bug — the row cites a second path the rules will not touch, or it is a `learning` or `blocker` row where a content change brings the symptom-first rule into play. Both are no-ops, listed with their reason, and a run with refusals exits non-zero so a scripted caller cannot read them as success.
27
+
13
28
  ## What an update carries forward
14
29
 
15
30
  `memory_update` picks its row by `query`: the row's id, a clock fragment such as `00:11:22.123`, or a unique substring of its text. Omit it and the newest entry of that scope and type is the target. A query that matches nothing, or that matches several rows, writes nothing and says so — an ambiguous selector is never resolved by picking one.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.32.0",
3
+ "version": "0.33.0",
4
4
  "description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
5
5
  "main": "index.ts",
6
6
  "exports": {
@@ -170,9 +170,24 @@ export function extractPathRefs(content: string): string[] {
170
170
  // whose match starts just after `$` or `~` — env vars and home paths describe
171
171
  // another machine, e.g. in `$BUILD_ROOT/src/a.ts` the regex match is
172
172
  // `BUILD_ROOT/src/a.ts`, which the preceding-char check drops.
173
- export function checkablePathRefs(content: string): string[] {
173
+ /** A checked ref plus the exact half-open span it occupies in the content. */
174
+ export interface PathRefSpan {
175
+ ref: string;
176
+ start: number;
177
+ end: number;
178
+ }
179
+
180
+ /**
181
+ * The same refs as `checkablePathRefs`, each with its span. Tooling that
182
+ * REWRITES a ref needs the offsets: a substring replace over the whole string
183
+ * also hits the ref nested inside a longer one, so `gate/gate.ts` mangles the
184
+ * `src/gate/gate.ts` beside it into `src/src/gate/gate.ts`, and it rewrites an
185
+ * absolute path this function deliberately drops — which the gate can then
186
+ * never refuse, because it never sees it. Editing spans cannot.
187
+ */
188
+ export function checkablePathRefSpans(content: string): PathRefSpan[] {
174
189
  if (content.length > REGEX_SCAN_MAX_CHARS) return [];
175
- const out: string[] = [];
190
+ const out: PathRefSpan[] = [];
176
191
  for (const m of content.matchAll(PATH_RE)) {
177
192
  const ref = m[0].replace(/:\d+$/, "");
178
193
  const prev = m.index && m.index > 0 ? content[m.index - 1] : "";
@@ -188,11 +203,20 @@ export function checkablePathRefs(content: string): string[] {
188
203
  // a repo directory. `.` itself is the legitimate relative root prefix.
189
204
  const first = ref.split("/")[0];
190
205
  if (first.includes(".") && first !== ".") continue;
191
- if (!out.includes(ref)) out.push(ref);
206
+ // The span covers the ref only, never the `:line` suffix PATH_RE swallowed,
207
+ // so a rewrite leaves the line number attached to the new path.
208
+ out.push({ ref, start: m.index, end: m.index + ref.length });
192
209
  }
193
210
  return out;
194
211
  }
195
212
 
213
+ export function checkablePathRefs(content: string): string[] {
214
+ const out: string[] = [];
215
+ for (const s of checkablePathRefSpans(content))
216
+ if (!out.includes(s.ref)) out.push(s.ref);
217
+ return out;
218
+ }
219
+
196
220
  async function isDirectory(path: string): Promise<boolean> {
197
221
  try {
198
222
  // A listing that yields even one entry proves liveRoot is a real tree;
@@ -0,0 +1,66 @@
1
+ // The render side of an additive clash: `dedupeWindowGrouped` keeps both rows
2
+ // and reports the pair, and this names WHY the reader is seeing two rows that
3
+ // look alike. Without it the pass has silently swapped one wrong deletion for an
4
+ // unexplained duplicate, which is harder to debug than either.
5
+ //
6
+ // Shape follows `conflictLine` in ./conflicts.ts — both facts, the evidence, an
7
+ // Action — with one deliberate difference: a CONFLICT verdict is fixed by its
8
+ // class, and this one is not. The reader chooses, because the distinction that
9
+ // decided it (a second thing versus a corrected thing) is visible in the token
10
+ // sets but not in the prose.
11
+ import type { Memory } from "../store/model/memory.ts";
12
+ import { flattenMemoryText } from "../store/sanitize.ts";
13
+ import { contentTokens } from "./dedupe.ts";
14
+
15
+ /**
16
+ * Cap on each token list. A pair that reaches the threshold while differing
17
+ * widely would otherwise dump most of its vocabulary into the result; the cap
18
+ * keeps the line readable and the count tells the reader what was withheld.
19
+ */
20
+ export const MAX_MARKER_TOKENS = 6;
21
+
22
+ function list(tokens: string[]): string {
23
+ const shown = tokens.slice(0, MAX_MARKER_TOKENS);
24
+ const held = tokens.length - shown.length;
25
+ return `${shown.join(", ")}${held > 0 ? ` (+${held} more)` : ""}`;
26
+ }
27
+
28
+ /**
29
+ * One line for one additive family, naming each member by its 1-based position
30
+ * in the returned window. A family is however many rows the pass kept together,
31
+ * so the line count tracks the number of unexplained groups rather than the
32
+ * number of pairs inside them: five mutually additive rows are one line, not
33
+ * ten. The scope is store text and is flattened like every other rendered
34
+ * field: one row is one line, so a stored newline cannot forge a section here
35
+ * either.
36
+ */
37
+ export function ambiguousLine(members: Memory[], positions: number[]): string {
38
+ const sets = members.map((m) => contentTokens(m));
39
+ // Each side lists what THAT member has that none of the others have, so a
40
+ // nested chain prints one side rather than one per member: every row but the
41
+ // largest is wholly contained in the union of the rest. The line therefore
42
+ // grows with the vocabulary of the family, not with its size.
43
+ const sides: string[] = [];
44
+ sets.forEach((t, i) => {
45
+ const others = new Set<string>();
46
+ sets.forEach((o, j) => {
47
+ if (j !== i) for (const tok of o) others.add(tok);
48
+ });
49
+ const only = [...t].filter((tok) => !others.has(tok));
50
+ if (only.length) sides.push(`only in ${positions[i]}: ${list(only)}`);
51
+ });
52
+ const where =
53
+ positions.length === 2
54
+ ? `rows ${positions[0]} and ${positions[1]}`
55
+ : `rows ${positions.slice(0, -1).join(", ")} and ${positions[positions.length - 1]}`;
56
+ const rest =
57
+ positions.length === 2
58
+ ? "neither restates the other"
59
+ : "none restates the others";
60
+ return (
61
+ `AMBIGUOUS (${flattenMemoryText(members[0]!.scope)}): ${where} share ` +
62
+ `shape but ${rest}${sides.length ? ` — ${sides.join("; ")}` : ""}. ` +
63
+ `Action: neither supersedes the other. Pick by what you are actually doing; ` +
64
+ `if both apply, use both.`
65
+ );
66
+ }
@@ -20,6 +20,13 @@
20
20
  // - A pair whose numeric literals differ is never a copy: short tokens are
21
21
  // dropped, so "DB 3" and "DB 4" otherwise share identical token sets.
22
22
  //
23
+ // A clash is not one situation. Either one row corrected the other, or the two
24
+ // rows name two things that both hold, and only the first is a copy. A row
25
+ // whose tokens are wholly contained in its partner names something the partner
26
+ // does not restate, so both are kept and reported as a group; the others still
27
+ // collapse to the newest. OPENCODE_MEMORY_AMBIGUOUS=0 restores the collapse for
28
+ // every class.
29
+ //
23
30
  // Threshold guidance: 0.5-0.7 suppresses merely-related rows and forces the
24
31
  // window deep into the ranking; 0.8 suppresses near-identical copies only.
25
32
  // History and measurements: docs/adr/0002.
@@ -28,6 +35,13 @@ import { words } from "./score.ts";
28
35
 
29
36
  export const DEDUPE_ENV = "OPENCODE_MEMORY_DEDUP";
30
37
 
38
+ /**
39
+ * Keeps an additive clash instead of collapsing it. Independent of
40
+ * DEDUPE_ENV: `OPENCODE_MEMORY_DEDUP=0` turns the whole pass off, and this flag
41
+ * only chooses what a clash does when the pass is on.
42
+ */
43
+ export const AMBIGUOUS_ENV = "OPENCODE_MEMORY_AMBIGUOUS";
44
+
31
45
  /** Below this, the value is a misconfiguration and the pass stays off. */
32
46
  export const MIN_THRESHOLD = 0.5;
33
47
 
@@ -75,6 +89,20 @@ export function dedupeThreshold(
75
89
  return Number.isFinite(n) && n >= MIN_THRESHOLD && n <= 1 ? n : 0;
76
90
  }
77
91
 
92
+ /**
93
+ * Whether an additive clash keeps both rows. On unless AMBIGUOUS_ENV says
94
+ * otherwise; only `0`, `off` and `false` disable it, so a typo cannot turn the
95
+ * behavior off by accident the way an unparsable threshold does.
96
+ */
97
+ export function ambiguousEnabled(
98
+ env: Record<string, string | undefined> = process.env,
99
+ ): boolean {
100
+ const raw = env[AMBIGUOUS_ENV];
101
+ if (raw === undefined) return true;
102
+ const v = raw.trim().toLowerCase();
103
+ return !(v === "0" || v === "off" || v === "false");
104
+ }
105
+
78
106
  export function jaccard(a: Set<string>, b: Set<string>): number {
79
107
  let inter = 0;
80
108
  const small = a.size <= b.size ? a : b;
@@ -84,6 +112,39 @@ export function jaccard(a: Set<string>, b: Set<string>): number {
84
112
  return union ? inter / union : 0;
85
113
  }
86
114
 
115
+ /** What a near-duplicate clash actually is. */
116
+ export type PairClass = "identical" | "addition" | "substitution";
117
+
118
+ /**
119
+ * Whether one row restates its partner or names something the partner does not.
120
+ * The leftover token sets decide, and the two situations are opposite:
121
+ *
122
+ * - `identical` — nothing left over either way, one row typed twice.
123
+ * - `addition` — one side wholly contained. The rows name different things and
124
+ * both hold; `build:example-images` tokenises to contain `build`, which is
125
+ * how a second command reaches 0.82 against the first.
126
+ * - `substitution` — a leftover on each side, read as the same statement
127
+ * about a changed world, so the older row is stale.
128
+ *
129
+ * Only `addition` is decidable from containment. Its absence is NOT evidence
130
+ * of a correction: two instructions naming two scripts that both exist
131
+ * (`bun run bench:recall` and `bun run bench:write`) also leave a leftover on
132
+ * each side, score 0.882, and the older is dropped. That limitation predates
133
+ * this rule and is recorded in docs/adr/0002; collapsing such a pair is the
134
+ * pass's existing behavior, not something the split introduces.
135
+ *
136
+ * Only token equality, so the short-chunk guard stays load-bearing: "late 0"
137
+ * and "late 1" tokenise alike and read as `identical` here.
138
+ */
139
+ export function classifyPair(a: Set<string>, b: Set<string>): PairClass {
140
+ let onlyA = 0;
141
+ for (const t of a) if (!b.has(t)) onlyA++;
142
+ if (onlyA === 0) return a.size === b.size ? "identical" : "addition";
143
+ let onlyB = 0;
144
+ for (const t of b) if (!a.has(t)) onlyB++;
145
+ return onlyB === 0 ? "addition" : "substitution";
146
+ }
147
+
87
148
  /**
88
149
  * The short tokens `words()` drops (chunks of length <= 2). They are where
89
150
  * single-digit facts hide: "Rate limiter reads Redis DB 3." and "...DB 4."
@@ -129,6 +190,19 @@ function hasPolarity(tokens: Set<string>): boolean {
129
190
  return false;
130
191
  }
131
192
 
193
+ /**
194
+ * A window plus the additive families inside it: rows kept side by side because
195
+ * each names something the others do not restate. A family is a SET, not a pair.
196
+ * With three rows that all overlap, every pair inside them is additive, and one
197
+ * marker per pair prints ten lines for five facts — all repeating the same
198
+ * Action. One line per family says what the reader needs: these rows belong
199
+ * together and none of them supersedes another.
200
+ */
201
+ export interface GroupedWindow {
202
+ rows: Memory[];
203
+ groups: Memory[][];
204
+ }
205
+
132
206
  /**
133
207
  * Keep at most `limit` rows from `ranked`, in ranking order, skipping a row
134
208
  * when it is a near-copy (same scope, content-token Jaccard >= `threshold`) of
@@ -138,13 +212,21 @@ function hasPolarity(tokens: Set<string>): boolean {
138
212
  * and pairs whose numeric literals differ are never suppressed. `threshold <= 0`
139
213
  * returns the plain top-`limit` slice, so the flag-off path costs nothing and
140
214
  * cannot reorder.
215
+ *
216
+ * With `groupAdditions` an `addition` clash keeps both rows and is reported in
217
+ * `groups`, because the shorter row names something the longer one does not
218
+ * restate. `groups` carries the rows themselves: a later clash overwrites a
219
+ * slot in the window, and a group keyed on that slot would re-point at
220
+ * whatever landed there.
141
221
  */
142
- export function dedupeWindow(
222
+ export function dedupeWindowGrouped(
143
223
  ranked: Memory[],
144
224
  limit: number,
145
225
  threshold: number,
146
- ): Memory[] {
147
- if (threshold <= 0 || ranked.length <= 1) return ranked.slice(0, limit);
226
+ groupAdditions: boolean = ambiguousEnabled(),
227
+ ): GroupedWindow {
228
+ if (threshold <= 0 || ranked.length <= 1)
229
+ return { rows: ranked.slice(0, limit), groups: [] };
148
230
  // Token sets are built lazily and cached per index: the loop stops once
149
231
  // `limit` rows are kept, so eager tokenization of every candidate costs
150
232
  // 1.7ms/12.5ms/96.4ms at 200/2k/10k candidates on every query recall.
@@ -173,22 +255,103 @@ export function dedupeWindow(
173
255
  kept.push(i);
174
256
  continue;
175
257
  }
176
- let clash = -1; // position within `kept`, not the row index
258
+ // With grouping off this is the pre-grouping rule verbatim: stop at the
259
+ // FIRST clash and let recency decide, because a rollback flag that changes
260
+ // which facts survive is not a rollback. With grouping on the scan walks
261
+ // every kept row: an additive clash found early in the window can sit next
262
+ // to its own exact copy later in it, and grouping on the first match spends
263
+ // a slot on a duplicate while a distinct row waits outside — the exact loss
264
+ // this pass exists to prevent. A collapse therefore outranks a group.
265
+ let addition = -1; // first clash that names something new
266
+ let collapse = -1; // a clash that is a copy or a correction
177
267
  for (const pos of kept.keys()) {
178
268
  const k = kept[pos]!;
179
269
  if (
180
- ranked[k]!.scope === ranked[i]!.scope &&
181
- tokensOf(k).size >= MIN_CONTENT &&
182
- polarityOf(k) === polarityOf(i) &&
183
- sameDroppedChunks(ranked[k]!, ranked[i]!) &&
184
- jaccard(tokensOf(i), tokensOf(k)) >= threshold
270
+ ranked[k]!.scope !== ranked[i]!.scope ||
271
+ tokensOf(k).size < MIN_CONTENT ||
272
+ polarityOf(k) !== polarityOf(i) ||
273
+ !sameDroppedChunks(ranked[k]!, ranked[i]!) ||
274
+ jaccard(tokensOf(i), tokensOf(k)) < threshold
185
275
  ) {
186
- clash = pos;
187
- break;
276
+ continue;
188
277
  }
278
+ if (
279
+ groupAdditions &&
280
+ classifyPair(tokensOf(k), tokensOf(i)) === "addition"
281
+ ) {
282
+ if (addition < 0) addition = pos;
283
+ continue;
284
+ }
285
+ collapse = pos;
286
+ break;
189
287
  }
190
- if (clash === -1) kept.push(i);
191
- else if (ranked[i]!.ts > ranked[kept[clash]!]!.ts) kept[clash] = i;
288
+ if (
289
+ collapse < 0 &&
290
+ addition >= 0 &&
291
+ groupAdditions &&
292
+ kept.length < limit
293
+ ) {
294
+ kept.push(i);
295
+ } else if (collapse >= 0) {
296
+ if (ranked[i]!.ts > ranked[kept[collapse]!]!.ts) kept[collapse] = i;
297
+ } else if (addition >= 0) {
298
+ if (ranked[i]!.ts > ranked[kept[addition]!]!.ts) kept[addition] = i;
299
+ } else kept.push(i);
192
300
  }
193
- return kept.map((i) => ranked[i]!);
301
+ const rows = kept.map((i) => ranked[i]!);
302
+ // Families are recomputed from the window instead of accumulated during the
303
+ // pass. A collapse replaces a row in place, so a group recorded earlier can
304
+ // name a row that no longer rides, and a marker pointing at an absent row
305
+ // describes nothing. Recomputing also costs nothing: the window is `limit`
306
+ // rows, so this is a handful of comparisons against cached token sets.
307
+ const groups: Memory[][] = [];
308
+ if (groupAdditions) {
309
+ const additive = (x: number, y: number): boolean =>
310
+ ranked[x]!.scope === ranked[y]!.scope &&
311
+ tokensOf(x).size >= MIN_CONTENT &&
312
+ tokensOf(y).size >= MIN_CONTENT &&
313
+ polarityOf(x) === polarityOf(y) &&
314
+ sameDroppedChunks(ranked[x]!, ranked[y]!) &&
315
+ jaccard(tokensOf(x), tokensOf(y)) >= threshold &&
316
+ classifyPair(tokensOf(x), tokensOf(y)) === "addition";
317
+ const adj: number[][] = kept.map(() => []);
318
+ for (let a = 0; a < kept.length; a++)
319
+ for (let b = a + 1; b < kept.length; b++)
320
+ if (additive(kept[a]!, kept[b]!)) {
321
+ adj[a]!.push(b);
322
+ adj[b]!.push(a);
323
+ }
324
+ // Connected components, in window order. Additivity is not transitive, but
325
+ // a chain of additive rows is one explanation rather than n of them, and
326
+ // the chain is what the reader is looking at. Everything in this block is a
327
+ // POSITION within `kept`, not a row index — the last map is the only place
328
+ // that crosses back, and getting it wrong names a row that was replaced.
329
+ const seen = new Set<number>();
330
+ for (let a = 0; a < kept.length; a++) {
331
+ if (seen.has(a) || adj[a]!.length === 0) continue;
332
+ seen.add(a);
333
+ const stack = [a];
334
+ const fam: number[] = [];
335
+ while (stack.length) {
336
+ const x = stack.pop()!;
337
+ fam.push(x);
338
+ for (const y of adj[x]!)
339
+ if (!seen.has(y)) {
340
+ seen.add(y);
341
+ stack.push(y);
342
+ }
343
+ }
344
+ groups.push(fam.sort((p, q) => p - q).map((pos) => ranked[kept[pos]!]!));
345
+ }
346
+ }
347
+ return { rows, groups };
348
+ }
349
+
350
+ /** The window alone, without the groups. See `dedupeWindowGrouped`. */
351
+ export function dedupeWindow(
352
+ ranked: Memory[],
353
+ limit: number,
354
+ threshold: number,
355
+ ): Memory[] {
356
+ return dedupeWindowGrouped(ranked, limit, threshold).rows;
194
357
  }
@@ -17,7 +17,8 @@ import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
17
17
  import type { Memory } from "../store/model/memory.ts";
18
18
  import { RecallArgs, validated } from "./schema.ts";
19
19
  import { firstFrontierTap, markFrontierTap } from "../capture/triggers.ts";
20
- import { dedupeThreshold, dedupeWindow } from "../recall/dedupe.ts";
20
+ import { dedupeThreshold, dedupeWindowGrouped } from "../recall/dedupe.ts";
21
+ import { ambiguousLine } from "../recall/ambiguous.ts";
21
22
 
22
23
  function scoreMemory(m: Memory, q: string): number {
23
24
  // Same indexed fields as the injection scorer: a row recalled by one of
@@ -83,11 +84,14 @@ export const register: ToolRegister = (editor, deps) => {
83
84
  // dedup lane (RESULTS §17): default on at 0.8 — near-duplicate
84
85
  // copies are skipped so the window fills with distinct rows instead of
85
86
  // repeats of the top hit. OPENCODE_MEMORY_DEDUP=0 restores the plain
86
- // slice.
87
+ // slice. A clash where one row is wholly contained in the other names a
88
+ // second thing rather than a corrected one, so both are kept and an
89
+ // AMBIGUOUS line says so; OPENCODE_MEMORY_AMBIGUOUS=0 collapses those too.
87
90
  const dedupeAt = dedupeThreshold();
88
- const limited = args.query
89
- ? dedupeWindow(results, limit, dedupeAt)
90
- : results.slice(-limit);
91
+ const grouped = args.query
92
+ ? dedupeWindowGrouped(results, limit, dedupeAt)
93
+ : { rows: results.slice(-limit), groups: [] };
94
+ const limited = grouped.rows;
91
95
  if (!limited.length) return { content: "No matching memories" };
92
96
  const openIn = limited.filter((m) => m.status === "open").length;
93
97
  if (openIn > 0) {
@@ -104,8 +108,24 @@ export const register: ToolRegister = (editor, deps) => {
104
108
  );
105
109
  }
106
110
  if (args.query) await noteHits("recall", sid, limited, args.query);
111
+ const lines = limited.map(formatMemory);
112
+ // A kept group is named after the rows it describes, numbered to match
113
+ // the list above. Resolved by object identity rather than by position
114
+ // arithmetic: the group carries the same objects the window holds.
115
+ for (const family of grouped.groups) {
116
+ // Resolved by object identity rather than position arithmetic: the
117
+ // family carries the same objects the window holds.
118
+ const at = family.map((m) => limited.indexOf(m));
119
+ if (at.every((i) => i >= 0))
120
+ lines.push(
121
+ ambiguousLine(
122
+ family,
123
+ at.map((i) => i + 1),
124
+ ),
125
+ );
126
+ }
107
127
  return {
108
- content: `Found ${results.length} (${total} total)\n\n${limited.map(formatMemory).join("\n")}`,
128
+ content: `Found ${results.length} (${total} total)\n\n${lines.join("\n")}`,
109
129
  };
110
130
  },
111
131
  }),