opencode-self-improvement 0.32.0 → 0.33.1
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/docs/adr/0002-window-dedup.md +22 -0
- package/docs/pre-release-ritual.md +1 -1
- package/docs/recall-quality.md +1 -1
- package/docs/write-gates.md +15 -0
- package/package.json +2 -1
- package/src/gate/resolver.ts +27 -3
- package/src/recall/ambiguous.ts +66 -0
- package/src/recall/dedupe.ts +182 -17
- package/src/tools/recall.ts +26 -6
|
@@ -20,3 +20,25 @@ 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
|
+
- Re-measured 2026-11-19 over the window a repository actually reads — its own rows plus rows carrying no repository stamp (`bun bench/runners/dedup-live-replay.ts`; written up in the [live dedup replay](https://github.com/abogartz/opencode-self-improvement/blob/main/bench/dedup-live-results.md), whose counts are a dated snapshot because the store drifts). The scan neither confirms nor refutes 0.8: among the repository's own active rows no pair reaches the threshold, and once superseded history is included every candidate has a superseded side. It found two other things, and they are the useful part. Near-identical rows can stay active together: the write gate's duplicate check is exact and keyed by type, while this pass compares across types, so identical prose filed as two types lands twice and stays active. This pass is therefore not redundant with the gate. And the pass is inert on the repository's own rows because of its guards, not because the store is clean: of the pairs the pre-`fc59b84` rule would have suppressed, the dropped-chunk guard stops nearly all and the content floor the rest.
|
|
24
|
+
- Known limitation, from that same replay: 0.8 suppresses a pair that is not a copy. Two active rows naming two different build commands in one scope score 0.824 and pass every guard. Ranking favors recency and the pass keeps the first-ranked row of a clash, so the survivor is the newer, narrower command and the plain build command is what disappears from the reader's view. The threshold trades that against crowding; where a scope holds parallel short facts, it costs real information.
|
|
25
|
+
- Raising the default was evaluated on 2026-11-19 and rejected. The pair worth releasing scores 0.8235; the changed-fact pair pinned in `test/dedupe-tool.test.ts` — the same runbook sentence with `friday` replaced by `monday` — scores 0.8333. Any threshold separating them must sit in a window one hundredth wide, which is a constant fitted to two observations, and 0.9 releases both and removes the recency rule above. The two rows have the same shape: one sentence, one long token swapped out. Whether that swap replaced a fact or added one is not visible in a token overlap, so this is not a threshold problem.
|
|
26
|
+
- The dropped-chunk guard, not the threshold, decides what this pass ever sees. Two rows differing by a timestamp have different dropped fragments and are never compared, so the cursor rows this record names as the motivation are exempt, while prose carrying no short fragments at all is compared and can be suppressed on shape alone.
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
## Addition groups
|
|
30
|
+
|
|
31
|
+
A clash is not always a copy. `classifyPair` reads the leftover token sets and splits three cases:
|
|
32
|
+
`identical` (nothing left over — one row typed twice), `addition` (one side wholly contained — the
|
|
33
|
+
rows name different things, so both hold), `substitution` (a leftover on each side). Only `addition`
|
|
34
|
+
is decidable from containment, and only `addition` keeps both rows; it takes an extra slot and the
|
|
35
|
+
handler marks the pair with `AMBIGUOUS` rather than deciding silently. Flag:
|
|
36
|
+
`OPENCODE_MEMORY_AMBIGUOUS`, on by default.
|
|
37
|
+
|
|
38
|
+
`substitution` is an interpretation, not a decision, and its absence of containment is not evidence
|
|
39
|
+
of a correction. Two instructions naming two scripts that both exist — `bun run bench:recall` and
|
|
40
|
+
`bun run bench:write` — leave a leftover on each side, score 0.882, and the older is dropped. That
|
|
41
|
+
predates the split and the split does not fix it: the pass has no way to learn from a row's text that
|
|
42
|
+
both scripts are real. It is the remaining limitation of the rule, and the reason the group marker
|
|
43
|
+
exists at all — where the classifier can see both readings are possible, it says so instead of
|
|
44
|
+
choosing.
|
|
@@ -21,7 +21,7 @@ Run it when you want to know whether the suite still has teeth — after changin
|
|
|
21
21
|
|
|
22
22
|
### Bench artifacts stay out of git
|
|
23
23
|
|
|
24
|
-
Raw sweep output is regenerable measurement data, and it was the largest tracked content in the repository. It is not committed (#232). A clone carries the published summaries — `bench/RESULTS.md
|
|
24
|
+
Raw sweep output is regenerable measurement data, and it was the largest tracked content in the repository. It is not committed (#232). A clone carries the published summaries — `bench/RESULTS.md` and the `bench/*-results.md` files — and the inputs those summaries are rebuilt from. History is not rewritten: the old blobs stay in earlier revisions, so this shrinks new checkouts, not the archive.
|
|
25
25
|
|
|
26
26
|
| Artifact | How to get it back |
|
|
27
27
|
| --- | --- |
|
package/docs/recall-quality.md
CHANGED
|
@@ -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/
|
|
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
|
|
package/docs/write-gates.md
CHANGED
|
@@ -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.
|
|
3
|
+
"version": "0.33.1",
|
|
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": {
|
|
@@ -67,6 +67,7 @@
|
|
|
67
67
|
"bench:recall": "bun bench/runners/recall-quality.ts",
|
|
68
68
|
"bench:write": "bun bench/runners/write-latency.ts",
|
|
69
69
|
"bench:availability": "bun bench/runners/availability-policy-compare.ts",
|
|
70
|
+
"bench:dedup": "bun bench/runners/dedup-live-replay.ts",
|
|
70
71
|
"sweep:test": "bun scripts/test-sweep.ts",
|
|
71
72
|
"memory-view": "bun run src/viewer/server.ts",
|
|
72
73
|
"format": "biome format --write",
|
package/src/gate/resolver.ts
CHANGED
|
@@ -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
|
-
|
|
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:
|
|
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
|
-
|
|
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
|
+
}
|
package/src/recall/dedupe.ts
CHANGED
|
@@ -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."
|
|
@@ -112,9 +173,11 @@ function sameDroppedChunks(a: Memory, b: Memory): boolean {
|
|
|
112
173
|
|
|
113
174
|
/**
|
|
114
175
|
* A row's own tokens: built DIRECTLY from the content and keyword fields.
|
|
115
|
-
* Never from `haystack()` — the identifier tokenizer splits a
|
|
116
|
-
*
|
|
117
|
-
*
|
|
176
|
+
* Never from `haystack()` — the identifier tokenizer splits a multi-word scope
|
|
177
|
+
* into its parts, and those parts stand in for content. Any delimiter does it:
|
|
178
|
+
* `auth_token_refresh_policy` and `auth-token-refresh-policy` both yield
|
|
179
|
+
* auth/token/refresh/policy, so a store holding no underscore is not exempt.
|
|
180
|
+
* Deleting only the whole scope/type strings leaves those words standing in
|
|
118
181
|
* for content: two unrelated non-Latin rows in one scope then share a
|
|
119
182
|
* Jaccard-1 metadata vocabulary, clear MIN_CONTENT on scope tokens alone,
|
|
120
183
|
* and dedup hides one.
|
|
@@ -129,6 +192,19 @@ function hasPolarity(tokens: Set<string>): boolean {
|
|
|
129
192
|
return false;
|
|
130
193
|
}
|
|
131
194
|
|
|
195
|
+
/**
|
|
196
|
+
* A window plus the additive families inside it: rows kept side by side because
|
|
197
|
+
* each names something the others do not restate. A family is a SET, not a pair.
|
|
198
|
+
* With three rows that all overlap, every pair inside them is additive, and one
|
|
199
|
+
* marker per pair prints ten lines for five facts — all repeating the same
|
|
200
|
+
* Action. One line per family says what the reader needs: these rows belong
|
|
201
|
+
* together and none of them supersedes another.
|
|
202
|
+
*/
|
|
203
|
+
export interface GroupedWindow {
|
|
204
|
+
rows: Memory[];
|
|
205
|
+
groups: Memory[][];
|
|
206
|
+
}
|
|
207
|
+
|
|
132
208
|
/**
|
|
133
209
|
* Keep at most `limit` rows from `ranked`, in ranking order, skipping a row
|
|
134
210
|
* when it is a near-copy (same scope, content-token Jaccard >= `threshold`) of
|
|
@@ -138,13 +214,21 @@ function hasPolarity(tokens: Set<string>): boolean {
|
|
|
138
214
|
* and pairs whose numeric literals differ are never suppressed. `threshold <= 0`
|
|
139
215
|
* returns the plain top-`limit` slice, so the flag-off path costs nothing and
|
|
140
216
|
* cannot reorder.
|
|
217
|
+
*
|
|
218
|
+
* With `groupAdditions` an `addition` clash keeps both rows and is reported in
|
|
219
|
+
* `groups`, because the shorter row names something the longer one does not
|
|
220
|
+
* restate. `groups` carries the rows themselves: a later clash overwrites a
|
|
221
|
+
* slot in the window, and a group keyed on that slot would re-point at
|
|
222
|
+
* whatever landed there.
|
|
141
223
|
*/
|
|
142
|
-
export function
|
|
224
|
+
export function dedupeWindowGrouped(
|
|
143
225
|
ranked: Memory[],
|
|
144
226
|
limit: number,
|
|
145
227
|
threshold: number,
|
|
146
|
-
|
|
147
|
-
|
|
228
|
+
groupAdditions: boolean = ambiguousEnabled(),
|
|
229
|
+
): GroupedWindow {
|
|
230
|
+
if (threshold <= 0 || ranked.length <= 1)
|
|
231
|
+
return { rows: ranked.slice(0, limit), groups: [] };
|
|
148
232
|
// Token sets are built lazily and cached per index: the loop stops once
|
|
149
233
|
// `limit` rows are kept, so eager tokenization of every candidate costs
|
|
150
234
|
// 1.7ms/12.5ms/96.4ms at 200/2k/10k candidates on every query recall.
|
|
@@ -173,22 +257,103 @@ export function dedupeWindow(
|
|
|
173
257
|
kept.push(i);
|
|
174
258
|
continue;
|
|
175
259
|
}
|
|
176
|
-
|
|
260
|
+
// With grouping off this is the pre-grouping rule verbatim: stop at the
|
|
261
|
+
// FIRST clash and let recency decide, because a rollback flag that changes
|
|
262
|
+
// which facts survive is not a rollback. With grouping on the scan walks
|
|
263
|
+
// every kept row: an additive clash found early in the window can sit next
|
|
264
|
+
// to its own exact copy later in it, and grouping on the first match spends
|
|
265
|
+
// a slot on a duplicate while a distinct row waits outside — the exact loss
|
|
266
|
+
// this pass exists to prevent. A collapse therefore outranks a group.
|
|
267
|
+
let addition = -1; // first clash that names something new
|
|
268
|
+
let collapse = -1; // a clash that is a copy or a correction
|
|
177
269
|
for (const pos of kept.keys()) {
|
|
178
270
|
const k = kept[pos]!;
|
|
179
271
|
if (
|
|
180
|
-
ranked[k]!.scope
|
|
181
|
-
tokensOf(k).size
|
|
182
|
-
polarityOf(k)
|
|
183
|
-
sameDroppedChunks(ranked[k]!, ranked[i]!)
|
|
184
|
-
jaccard(tokensOf(i), tokensOf(k))
|
|
272
|
+
ranked[k]!.scope !== ranked[i]!.scope ||
|
|
273
|
+
tokensOf(k).size < MIN_CONTENT ||
|
|
274
|
+
polarityOf(k) !== polarityOf(i) ||
|
|
275
|
+
!sameDroppedChunks(ranked[k]!, ranked[i]!) ||
|
|
276
|
+
jaccard(tokensOf(i), tokensOf(k)) < threshold
|
|
185
277
|
) {
|
|
186
|
-
|
|
187
|
-
break;
|
|
278
|
+
continue;
|
|
188
279
|
}
|
|
280
|
+
if (
|
|
281
|
+
groupAdditions &&
|
|
282
|
+
classifyPair(tokensOf(k), tokensOf(i)) === "addition"
|
|
283
|
+
) {
|
|
284
|
+
if (addition < 0) addition = pos;
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
collapse = pos;
|
|
288
|
+
break;
|
|
189
289
|
}
|
|
190
|
-
if (
|
|
191
|
-
|
|
290
|
+
if (
|
|
291
|
+
collapse < 0 &&
|
|
292
|
+
addition >= 0 &&
|
|
293
|
+
groupAdditions &&
|
|
294
|
+
kept.length < limit
|
|
295
|
+
) {
|
|
296
|
+
kept.push(i);
|
|
297
|
+
} else if (collapse >= 0) {
|
|
298
|
+
if (ranked[i]!.ts > ranked[kept[collapse]!]!.ts) kept[collapse] = i;
|
|
299
|
+
} else if (addition >= 0) {
|
|
300
|
+
if (ranked[i]!.ts > ranked[kept[addition]!]!.ts) kept[addition] = i;
|
|
301
|
+
} else kept.push(i);
|
|
192
302
|
}
|
|
193
|
-
|
|
303
|
+
const rows = kept.map((i) => ranked[i]!);
|
|
304
|
+
// Families are recomputed from the window instead of accumulated during the
|
|
305
|
+
// pass. A collapse replaces a row in place, so a group recorded earlier can
|
|
306
|
+
// name a row that no longer rides, and a marker pointing at an absent row
|
|
307
|
+
// describes nothing. Recomputing also costs nothing: the window is `limit`
|
|
308
|
+
// rows, so this is a handful of comparisons against cached token sets.
|
|
309
|
+
const groups: Memory[][] = [];
|
|
310
|
+
if (groupAdditions) {
|
|
311
|
+
const additive = (x: number, y: number): boolean =>
|
|
312
|
+
ranked[x]!.scope === ranked[y]!.scope &&
|
|
313
|
+
tokensOf(x).size >= MIN_CONTENT &&
|
|
314
|
+
tokensOf(y).size >= MIN_CONTENT &&
|
|
315
|
+
polarityOf(x) === polarityOf(y) &&
|
|
316
|
+
sameDroppedChunks(ranked[x]!, ranked[y]!) &&
|
|
317
|
+
jaccard(tokensOf(x), tokensOf(y)) >= threshold &&
|
|
318
|
+
classifyPair(tokensOf(x), tokensOf(y)) === "addition";
|
|
319
|
+
const adj: number[][] = kept.map(() => []);
|
|
320
|
+
for (let a = 0; a < kept.length; a++)
|
|
321
|
+
for (let b = a + 1; b < kept.length; b++)
|
|
322
|
+
if (additive(kept[a]!, kept[b]!)) {
|
|
323
|
+
adj[a]!.push(b);
|
|
324
|
+
adj[b]!.push(a);
|
|
325
|
+
}
|
|
326
|
+
// Connected components, in window order. Additivity is not transitive, but
|
|
327
|
+
// a chain of additive rows is one explanation rather than n of them, and
|
|
328
|
+
// the chain is what the reader is looking at. Everything in this block is a
|
|
329
|
+
// POSITION within `kept`, not a row index — the last map is the only place
|
|
330
|
+
// that crosses back, and getting it wrong names a row that was replaced.
|
|
331
|
+
const seen = new Set<number>();
|
|
332
|
+
for (let a = 0; a < kept.length; a++) {
|
|
333
|
+
if (seen.has(a) || adj[a]!.length === 0) continue;
|
|
334
|
+
seen.add(a);
|
|
335
|
+
const stack = [a];
|
|
336
|
+
const fam: number[] = [];
|
|
337
|
+
while (stack.length) {
|
|
338
|
+
const x = stack.pop()!;
|
|
339
|
+
fam.push(x);
|
|
340
|
+
for (const y of adj[x]!)
|
|
341
|
+
if (!seen.has(y)) {
|
|
342
|
+
seen.add(y);
|
|
343
|
+
stack.push(y);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
groups.push(fam.sort((p, q) => p - q).map((pos) => ranked[kept[pos]!]!));
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return { rows, groups };
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** The window alone, without the groups. See `dedupeWindowGrouped`. */
|
|
353
|
+
export function dedupeWindow(
|
|
354
|
+
ranked: Memory[],
|
|
355
|
+
limit: number,
|
|
356
|
+
threshold: number,
|
|
357
|
+
): Memory[] {
|
|
358
|
+
return dedupeWindowGrouped(ranked, limit, threshold).rows;
|
|
194
359
|
}
|
package/src/tools/recall.ts
CHANGED
|
@@ -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,
|
|
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
|
|
89
|
-
?
|
|
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${
|
|
128
|
+
content: `Found ${results.length} (${total} total)\n\n${lines.join("\n")}`,
|
|
109
129
|
};
|
|
110
130
|
},
|
|
111
131
|
}),
|