opencode-self-improvement 0.31.1 → 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.
- package/README.md +6 -0
- package/docs/adr/0002-window-dedup.md +17 -0
- package/docs/recall-quality.md +1 -1
- package/docs/use-ledger.md +33 -3
- package/docs/write-gates.md +15 -0
- package/package.json +1 -1
- package/src/capture/triggers.ts +15 -0
- package/src/core/state.ts +11 -0
- package/src/gate/resolver.ts +27 -3
- package/src/index.ts +14 -2
- package/src/recall/ambiguous.ts +66 -0
- package/src/recall/dedupe.ts +177 -14
- package/src/status/payload.ts +17 -0
- package/src/status/report.ts +17 -0
- package/src/status/store-summary.ts +81 -13
- package/src/telemetry/ledger.ts +221 -0
- package/src/tools/recall.ts +26 -6
- package/src/tools/status-tool.ts +21 -2
package/README.md
CHANGED
|
@@ -157,6 +157,12 @@ The plugin keeps a use ledger — a due-date card for every row: who looked at i
|
|
|
157
157
|
- **`never retrieved` is stated, not acted on.** Pruning is your decision.
|
|
158
158
|
- **Aggregate STORE counts are machine-wide by decision (#213 B)** — they describe the store on this machine, not your slice of it. Privacy applies to the content surfaces instead: `memory_evidence` and the recent-blocked-writes list follow each reader's repository visibility (#306).
|
|
159
159
|
|
|
160
|
+
`memory_status` joins rides to later gate checks on the same turn. For example,
|
|
161
|
+
`used=5 clean=0 fail_after=2 unknown=2 (eviction candidate)` records five rides,
|
|
162
|
+
two distinct failing turns and two rides with unknown outcomes. Totals cover
|
|
163
|
+
the store; individual rows follow repository visibility. Check the underlying
|
|
164
|
+
memory before acting on a candidate. Gate failures alone cannot establish harm.
|
|
165
|
+
|
|
160
166
|
Sample `STORE` output, the credit rule and its throttle, the consolidation tie-break, and capture lag: [docs/use-ledger.md](docs/use-ledger.md).
|
|
161
167
|
|
|
162
168
|
## Consolidation
|
|
@@ -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.
|
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/use-ledger.md
CHANGED
|
@@ -15,6 +15,10 @@ Illustrative output — shape, not a measurement:
|
|
|
15
15
|
STORE
|
|
16
16
|
41 active · 12 superseded · 4 open · 6 scopes
|
|
17
17
|
retrieved 33 rows in the last 30d; never retrieved 8 (20%) — reported, not acted on
|
|
18
|
+
outcome-linked 7 rides over 3 rows: 3 clean row/turns, 2 failed row/turns (store-wide)
|
|
19
|
+
1 candidate at ≥5 rides with no clean turn — best-effort counts are floors since 2026-11-01T10:00:00.000Z; correlation on the ride's own turn, reported, never acted on
|
|
20
|
+
outcome writes dropped for this store by this process: 0
|
|
21
|
+
2026-10-31T14:05:00.000Z used=5 clean=0 fail_after=2 unknown=2 (eviction candidate)
|
|
18
22
|
24.1 KB total · 604 B per row · 1.3 rows/day (30d)
|
|
19
23
|
```
|
|
20
24
|
|
|
@@ -27,13 +31,35 @@ harness offered" are different facts:
|
|
|
27
31
|
2. `memory_recall` returned it;
|
|
28
32
|
3. a grep/read pull appended it.
|
|
29
33
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
row's standing.
|
|
34
|
+
The writer throttles identical sets of retrieved rows to one successful line
|
|
35
|
+
per session and source per hour. A row can appear in multiple sets.
|
|
33
36
|
|
|
34
37
|
**No prompt content is stored.** The ledger keeps a scan-truncated string from
|
|
35
38
|
the *memory* side, never your message.
|
|
36
39
|
|
|
40
|
+
## What happens after retrieval
|
|
41
|
+
|
|
42
|
+
Each `memory_used` line records the turn number and turn key when available.
|
|
43
|
+
Each classified gate check appends a separate `ev=gate_outcome` line with
|
|
44
|
+
the session, turn, key, timestamp, command family and `outcome=clean|fail`.
|
|
45
|
+
The chat report aggregates those observations on read. On each row, `used`
|
|
46
|
+
counts recorded rides. `clean` and `fail_after` count distinct turns with
|
|
47
|
+
a classified gate after a ride. A later failure takes precedence over passes.
|
|
48
|
+
`unknown` counts rides without a usable later gate on that turn, including
|
|
49
|
+
legacy rides without a turn key when no compatible outcome exists.
|
|
50
|
+
Multiple rides on one turn can therefore contribute one measured turn.
|
|
51
|
+
|
|
52
|
+
The ledger drops old lines at rotation and can miss writes under contention.
|
|
53
|
+
The counts describe the retained observations. The dropped-outcome counter
|
|
54
|
+
covers failed writes in the reporting process for this store. It resets on
|
|
55
|
+
restart and excludes failures in other processes. A zero cannot establish
|
|
56
|
+
complete history.
|
|
57
|
+
|
|
58
|
+
A row becomes an eviction candidate after five recorded rides if at least
|
|
59
|
+
one ride has a measured outcome and none has a clean turn. A subsequent
|
|
60
|
+
failure can be unrelated to the row. Inspect the row and its use before
|
|
61
|
+
deciding whether to retire it. The report makes no store changes.
|
|
62
|
+
|
|
37
63
|
## What use is allowed to do
|
|
38
64
|
|
|
39
65
|
Reinforcement is a tie-break only (`useBoost ≤ 1.0`): a recently used row wins a
|
|
@@ -50,6 +76,10 @@ Aggregate STORE counts are machine-wide by decision (#213 B): they count every
|
|
|
50
76
|
repository's rows in the shared store on this machine, never just the reading
|
|
51
77
|
session's repository. The numbers describe the store, not your slice of it.
|
|
52
78
|
|
|
79
|
+
Outcome totals and candidate counts also cover every repository. The chat report
|
|
80
|
+
shows up to 20 reader-visible row IDs, prioritizing candidates. The omitted
|
|
81
|
+
count covers additional visible rows.
|
|
82
|
+
|
|
53
83
|
Privacy applies to the content surfaces instead. `memory_evidence` and the
|
|
54
84
|
recent-blocked-writes list in `memory_status` and `/memory` follow each reader's
|
|
55
85
|
repository visibility (#306).
|
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.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": {
|
package/src/capture/triggers.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { evidenceDir } from "../core/config/paths.ts";
|
|
|
7
7
|
import { parseLine } from "../core/logfmt/format.ts";
|
|
8
8
|
import { readLines } from "../core/logfmt/read.ts";
|
|
9
9
|
import { redactSecrets } from "../store/secrets.ts";
|
|
10
|
+
import { recordOutcome } from "../telemetry/ledger.ts";
|
|
10
11
|
import {
|
|
11
12
|
session,
|
|
12
13
|
setLastSeenSid,
|
|
@@ -173,6 +174,7 @@ export async function afterTool(
|
|
|
173
174
|
const ts = new Date().toISOString();
|
|
174
175
|
|
|
175
176
|
const s = session(sid ?? "?");
|
|
177
|
+
const turnKey = s.turnKey;
|
|
176
178
|
const rec: ToolResult = {
|
|
177
179
|
call,
|
|
178
180
|
tool,
|
|
@@ -208,6 +210,18 @@ export async function afterTool(
|
|
|
208
210
|
rec.gateCheck = true;
|
|
209
211
|
rec.cmd = family;
|
|
210
212
|
await record("gate_check", { cmd: family, status }, true, sid);
|
|
213
|
+
// the same fact in the use ledger, where a ride recorded on this
|
|
214
|
+
// turn can be joined to it. Evidence is the audit trail — pruned and
|
|
215
|
+
// quarantined on its own schedule — so the join cannot live there.
|
|
216
|
+
if (sid && turnKey && rec.turn !== undefined)
|
|
217
|
+
await recordOutcome(
|
|
218
|
+
sid,
|
|
219
|
+
rec.turn,
|
|
220
|
+
status,
|
|
221
|
+
family,
|
|
222
|
+
Date.parse(ts),
|
|
223
|
+
turnKey,
|
|
224
|
+
);
|
|
211
225
|
if (status === "FAIL") {
|
|
212
226
|
s.pendingGate = { call, cmd: family, chain: [], count: 0 };
|
|
213
227
|
} else if (s.pendingGate && s.pendingGate.cmd === family) {
|
|
@@ -336,6 +350,7 @@ export function hasGateCheck(sid: string): boolean {
|
|
|
336
350
|
export function markTurn(sid: string): void {
|
|
337
351
|
const s = session(sid);
|
|
338
352
|
s.turns++;
|
|
353
|
+
s.turnKey = crypto.randomUUID();
|
|
339
354
|
if (!s.firstActivityTs) s.firstActivityTs = new Date().toISOString();
|
|
340
355
|
}
|
|
341
356
|
|
package/src/core/state.ts
CHANGED
|
@@ -60,6 +60,7 @@ export interface SessionState {
|
|
|
60
60
|
// first activity time, and the first memory_recall that surfaced an open
|
|
61
61
|
// thread. Deterministic: derived only from queued messages and tool results.
|
|
62
62
|
turns: number;
|
|
63
|
+
turnKey?: string;
|
|
63
64
|
firstActivityTs?: string;
|
|
64
65
|
firstTap?: FirstTap;
|
|
65
66
|
finalized: boolean;
|
|
@@ -141,6 +142,16 @@ export function session(sid: string): SessionState {
|
|
|
141
142
|
return s;
|
|
142
143
|
}
|
|
143
144
|
|
|
145
|
+
/**
|
|
146
|
+
* Turn count for a session ALREADY being tracked, or undefined. Unlike
|
|
147
|
+
* `session()` this neither creates state nor touches the LRU, so a telemetry
|
|
148
|
+
* caller can stamp a turn without extending a session's residency.
|
|
149
|
+
*/
|
|
150
|
+
export function peekTurn(sid: string) {
|
|
151
|
+
const s = sessions.get(sid);
|
|
152
|
+
return s?.turnKey ? { turn: s.turns, key: s.turnKey } : undefined;
|
|
153
|
+
}
|
|
154
|
+
|
|
144
155
|
let current: { sid: string; call: string; tool: string } = {
|
|
145
156
|
sid: "?",
|
|
146
157
|
call: "?",
|
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;
|
package/src/index.ts
CHANGED
|
@@ -71,7 +71,7 @@ import { type Measured, type StoreCounts } from "./status/payload.ts";
|
|
|
71
71
|
import { renderMemoryReport } from "./status/report.ts";
|
|
72
72
|
import { blockedRecent } from "./status/write.ts";
|
|
73
73
|
import { firstFrontierTap, markFrontierTap } from "./capture/triggers.ts";
|
|
74
|
-
import { setCurrent } from "./core/state.ts";
|
|
74
|
+
import { peekTurn, setCurrent } from "./core/state.ts";
|
|
75
75
|
import {
|
|
76
76
|
resolveRepo,
|
|
77
77
|
setRepoScope,
|
|
@@ -194,7 +194,19 @@ const impl = {
|
|
|
194
194
|
for (const m of rows)
|
|
195
195
|
for (const t of sharedTerms(query, m))
|
|
196
196
|
if (!terms.includes(t)) terms.push(t);
|
|
197
|
-
|
|
197
|
+
// the turn is what joins a ride to the outcome of that same turn.
|
|
198
|
+
// Read, never created-for: markTurn has already run for any session that
|
|
199
|
+
// can reach a read path, so this does not seed state.
|
|
200
|
+
const observed = peekTurn(sid);
|
|
201
|
+
await recordHits(
|
|
202
|
+
src,
|
|
203
|
+
sid,
|
|
204
|
+
rows,
|
|
205
|
+
terms,
|
|
206
|
+
Date.now(),
|
|
207
|
+
observed?.turn,
|
|
208
|
+
observed?.key,
|
|
209
|
+
);
|
|
198
210
|
};
|
|
199
211
|
// The host listener owns measured usage; the epoch controller drops it
|
|
200
212
|
// alongside its own maps when the shared session LRU evicts an entry.
|
|
@@ -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."
|
|
@@ -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
|
|
222
|
+
export function dedupeWindowGrouped(
|
|
143
223
|
ranked: Memory[],
|
|
144
224
|
limit: number,
|
|
145
225
|
threshold: number,
|
|
146
|
-
|
|
147
|
-
|
|
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
|
-
|
|
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
|
|
181
|
-
tokensOf(k).size
|
|
182
|
-
polarityOf(k)
|
|
183
|
-
sameDroppedChunks(ranked[k]!, ranked[i]!)
|
|
184
|
-
jaccard(tokensOf(i), tokensOf(k))
|
|
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
|
-
|
|
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 (
|
|
191
|
-
|
|
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
|
-
|
|
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
|
}
|
package/src/status/payload.ts
CHANGED
|
@@ -41,6 +41,23 @@ export interface StoreCounts {
|
|
|
41
41
|
* ledger says so instead of inflating "never" (see `ledgerIsYoung`).
|
|
42
42
|
*/
|
|
43
43
|
ledgerSince?: string | null;
|
|
44
|
+
/**
|
|
45
|
+
* Counts cover active rows across all repositories in the store. Only
|
|
46
|
+
* details are reader-scoped. A joined ride has a later classified gate on
|
|
47
|
+
* the same turn; clean and failAfter count distinct row/turn pairs.
|
|
48
|
+
*/
|
|
49
|
+
useOutcome?: {
|
|
50
|
+
/** Active rows with at least one joined ride. */
|
|
51
|
+
rowsMeasured: number;
|
|
52
|
+
details?: string[];
|
|
53
|
+
/** Outcome writes lost by this process for the current store. */
|
|
54
|
+
droppedOutcomeWrites?: number;
|
|
55
|
+
joined: number;
|
|
56
|
+
clean: number;
|
|
57
|
+
failAfter: number;
|
|
58
|
+
/** Rides >= EVICT_MIN_RIDES with zero clean turns. Reported, never acted on. */
|
|
59
|
+
evictCandidates: number;
|
|
60
|
+
};
|
|
44
61
|
/** Bytes of store the active rows occupy (canonical logfmt rendering). */
|
|
45
62
|
bytes?: number;
|
|
46
63
|
/** Per-row average of the same, the "what does a row cost" number. */
|
package/src/status/report.ts
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
type StoreCounts,
|
|
14
14
|
emptyStats,
|
|
15
15
|
} from "./payload.ts";
|
|
16
|
+
import { EVICT_MIN_RIDES } from "./store-summary.ts";
|
|
16
17
|
|
|
17
18
|
function ago(iso: string): string {
|
|
18
19
|
const ms = Date.now() - new Date(iso).getTime();
|
|
@@ -282,6 +283,22 @@ export function renderMemoryReport(input: {
|
|
|
282
283
|
` retrieved ${used} rows in the last 30d; never retrieved ${store.neverRetrieved} (${share}%)${basis} — reported, not acted on`,
|
|
283
284
|
);
|
|
284
285
|
}
|
|
286
|
+
if (store.useOutcome) {
|
|
287
|
+
const u = store.useOutcome;
|
|
288
|
+
// Every number here is a floor and a correlation. Say it in the line, not
|
|
289
|
+
// in a footnote nobody reads: only rides that landed on a turn which also
|
|
290
|
+
// ran a gate command (build/test/lint/typecheck) can be scored at all.
|
|
291
|
+
out.push(
|
|
292
|
+
` outcome-linked ${u.joined} rides over ${u.rowsMeasured} rows: ${u.clean} clean row/turns, ${u.failAfter} failed row/turns (store-wide)`,
|
|
293
|
+
` ${u.evictCandidates} candidate${u.evictCandidates === 1 ? "" : "s"} at ≥${EVICT_MIN_RIDES} rides with no clean turn — best-effort counts are floors since ${store.ledgerSince ?? "unknown"}; correlation on the ride's own turn, reported, never acted on`,
|
|
294
|
+
...(u.droppedOutcomeWrites === undefined
|
|
295
|
+
? []
|
|
296
|
+
: [
|
|
297
|
+
` outcome writes dropped for this store by this process: ${u.droppedOutcomeWrites}`,
|
|
298
|
+
]),
|
|
299
|
+
);
|
|
300
|
+
for (const detail of u.details ?? []) out.push(detail);
|
|
301
|
+
}
|
|
285
302
|
const sizing: string[] = [];
|
|
286
303
|
if (store.bytes !== undefined) {
|
|
287
304
|
sizing.push(
|
|
@@ -1,26 +1,94 @@
|
|
|
1
1
|
// Shared store counts for epoch payloads and the chat report.
|
|
2
|
-
//
|
|
3
|
-
import {
|
|
2
|
+
// Aggregates cover the supplied store. The caller scopes per-row details.
|
|
3
|
+
import {
|
|
4
|
+
joinUseWithOutcomes,
|
|
5
|
+
neverRetrieved,
|
|
6
|
+
type HitEntry,
|
|
7
|
+
type TurnOutcome,
|
|
8
|
+
type UseLedger,
|
|
9
|
+
} from "../telemetry/ledger.ts";
|
|
4
10
|
import type { Memory } from "../store/model/memory.ts";
|
|
5
11
|
import { isActive } from "../store/model/predicates.ts";
|
|
6
12
|
import type { StoreCounts } from "./payload.ts";
|
|
7
13
|
|
|
14
|
+
/**
|
|
15
|
+
* A row is an eviction CANDIDATE at this many rides with no clean turn. Five,
|
|
16
|
+
* not two: `recordHits` throttles a row-set to one line per hour, so rides
|
|
17
|
+
* accumulate slowly and a low bar would flag a row that simply rode a bad
|
|
18
|
+
* afternoon.
|
|
19
|
+
*/
|
|
20
|
+
export const EVICT_MIN_RIDES = 5;
|
|
21
|
+
|
|
8
22
|
export function summarizeStore(
|
|
9
23
|
rows: Memory[],
|
|
10
24
|
ledger: UseLedger,
|
|
11
25
|
malformed: number,
|
|
26
|
+
/**
|
|
27
|
+
* Rides and gate outcomes for the join. Omitted, the outcome block is
|
|
28
|
+
* absent rather than zero — the caller did not look, which is a different
|
|
29
|
+
* statement from "nothing helped".
|
|
30
|
+
*/
|
|
31
|
+
use?: {
|
|
32
|
+
droppedOutcomeWrites?: number;
|
|
33
|
+
rides: HitEntry[];
|
|
34
|
+
outcomes: TurnOutcome[];
|
|
35
|
+
visible?: (row: Memory) => boolean;
|
|
36
|
+
},
|
|
12
37
|
): { active: Memory[]; counts: StoreCounts } {
|
|
13
38
|
const active = rows.filter(isActive);
|
|
14
|
-
|
|
15
|
-
active,
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
neverRetrieved: neverRetrieved(active, ledger).length,
|
|
23
|
-
ledgerSince: ledger.since,
|
|
24
|
-
},
|
|
39
|
+
const counts: StoreCounts = {
|
|
40
|
+
active: active.length,
|
|
41
|
+
superseded: rows.length - active.length,
|
|
42
|
+
open: active.filter((m) => m.status === "open").length,
|
|
43
|
+
scopes: new Set(active.map((m) => m.scope)).size,
|
|
44
|
+
malformed,
|
|
45
|
+
neverRetrieved: neverRetrieved(active, ledger).length,
|
|
46
|
+
ledgerSince: ledger.since,
|
|
25
47
|
};
|
|
48
|
+
if (use) {
|
|
49
|
+
const live = new Map(active.map((m) => [m.ts, m]));
|
|
50
|
+
const candidates: string[] = [];
|
|
51
|
+
const others: string[] = [];
|
|
52
|
+
let visibleCount = 0;
|
|
53
|
+
const limit = 20;
|
|
54
|
+
const joined = joinUseWithOutcomes(use.rides, use.outcomes);
|
|
55
|
+
let rowsMeasured = 0;
|
|
56
|
+
let sumJoined = 0;
|
|
57
|
+
let clean = 0;
|
|
58
|
+
let failAfter = 0;
|
|
59
|
+
let evictCandidates = 0;
|
|
60
|
+
for (const [row, o] of joined) {
|
|
61
|
+
const memory = live.get(row);
|
|
62
|
+
if (!memory) continue;
|
|
63
|
+
const candidate =
|
|
64
|
+
o.joined > 0 && o.rides >= EVICT_MIN_RIDES && o.clean === 0;
|
|
65
|
+
const details = candidate ? candidates : others;
|
|
66
|
+
if (use.visible?.(memory)) {
|
|
67
|
+
visibleCount++;
|
|
68
|
+
if (details.length < limit)
|
|
69
|
+
details.push(
|
|
70
|
+
` ${row} used=${o.rides} clean=${o.clean} fail_after=${o.failAfter} unknown=${o.rides - o.joined}${candidate ? " (eviction candidate)" : ""}`,
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
if (o.joined === 0) continue;
|
|
74
|
+
rowsMeasured++;
|
|
75
|
+
sumJoined += o.joined;
|
|
76
|
+
clean += o.clean;
|
|
77
|
+
failAfter += o.failAfter;
|
|
78
|
+
if (candidate) evictCandidates++;
|
|
79
|
+
}
|
|
80
|
+
const details = [...candidates, ...others].slice(0, limit);
|
|
81
|
+
if (visibleCount > limit)
|
|
82
|
+
details.push(` … ${visibleCount - limit} more visible rows`);
|
|
83
|
+
counts.useOutcome = {
|
|
84
|
+
...(details.length ? { details } : {}),
|
|
85
|
+
droppedOutcomeWrites: use.droppedOutcomeWrites,
|
|
86
|
+
rowsMeasured,
|
|
87
|
+
joined: sumJoined,
|
|
88
|
+
clean,
|
|
89
|
+
failAfter,
|
|
90
|
+
evictCandidates,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
return { active, counts };
|
|
26
94
|
}
|
package/src/telemetry/ledger.ts
CHANGED
|
@@ -57,6 +57,25 @@ export interface HitEntry {
|
|
|
57
57
|
sid: string;
|
|
58
58
|
mems: string[];
|
|
59
59
|
terms: string[];
|
|
60
|
+
/** Turn the ride landed on, when the caller knew it. Absent, never zero. */
|
|
61
|
+
turn?: number;
|
|
62
|
+
turnKey?: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* One observable outcome for one turn. Recorded only for turns that ran
|
|
67
|
+
* a gate command (build/test/lint/typecheck) — the only outcomes the plugin can
|
|
68
|
+
* see without guessing. A turn with no gate command has NO line, which the
|
|
69
|
+
* surfaces report as "outcome unknown", not as "clean".
|
|
70
|
+
*/
|
|
71
|
+
export interface TurnOutcome {
|
|
72
|
+
ts: string;
|
|
73
|
+
sid: string;
|
|
74
|
+
turn: number;
|
|
75
|
+
outcome: "PASS" | "FAIL";
|
|
76
|
+
cmd: string;
|
|
77
|
+
lastFail?: string;
|
|
78
|
+
turnKey?: string;
|
|
60
79
|
}
|
|
61
80
|
|
|
62
81
|
// --- writing --------------------------------------------------------------------
|
|
@@ -115,6 +134,8 @@ export async function recordHits(
|
|
|
115
134
|
rows: Memory[],
|
|
116
135
|
terms: string[] = [],
|
|
117
136
|
now = Date.now(),
|
|
137
|
+
turn?: number,
|
|
138
|
+
turnKey?: string,
|
|
118
139
|
): Promise<boolean> {
|
|
119
140
|
if (!rows.length) return false;
|
|
120
141
|
const ids = rows.map((m) => m.ts);
|
|
@@ -131,6 +152,13 @@ export async function recordHits(
|
|
|
131
152
|
...(terms.length
|
|
132
153
|
? { terms: bracketList(terms.slice(0, MAX_LOGGED_TERMS)) }
|
|
133
154
|
: {}),
|
|
155
|
+
// the turn is what lets a ride be joined to the outcome of the same
|
|
156
|
+
// turn. The throttle key deliberately EXCLUDES it — a row-set that keeps
|
|
157
|
+
// riding is credited once per hour, so a join sees the turn of the
|
|
158
|
+
// observation that survived the throttle, not every turn it rode. Rides
|
|
159
|
+
// are therefore a floor.
|
|
160
|
+
...(typeof turn === "number" ? { turn } : {}),
|
|
161
|
+
...(turnKey ? { turnKey } : {}),
|
|
134
162
|
});
|
|
135
163
|
inFlight.add(key);
|
|
136
164
|
let cooldown = RETRY_BACKOFF_MS;
|
|
@@ -161,6 +189,171 @@ export async function recordHits(
|
|
|
161
189
|
}
|
|
162
190
|
}
|
|
163
191
|
|
|
192
|
+
// Failed outcome writes cannot report their own loss through the ledger.
|
|
193
|
+
const droppedOutcomes = new Map<string, number>();
|
|
194
|
+
|
|
195
|
+
export function getDroppedOutcomeWrites(): number {
|
|
196
|
+
return droppedOutcomes.get(hitsFile()) ?? 0;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// --- outcomes -------------------------------------------------------------
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Record the observable outcome of a turn that ran a gate command. Same file,
|
|
203
|
+
* same lock, same rotation as the rides it will be joined against — the join
|
|
204
|
+
* has to be cheap and inside one bounded window, which is why this is NOT read
|
|
205
|
+
* back out of the evidence log (evidence is the audit trail and is pruned and
|
|
206
|
+
* quarantined on its own schedule).
|
|
207
|
+
*
|
|
208
|
+
* Fail-soft for the same reason as recordHits: telemetry must never break the
|
|
209
|
+
* tool path that noticed it.
|
|
210
|
+
*/
|
|
211
|
+
export async function recordOutcome(
|
|
212
|
+
sid: string,
|
|
213
|
+
turn: number,
|
|
214
|
+
outcome: "PASS" | "FAIL",
|
|
215
|
+
cmd: string,
|
|
216
|
+
now = Date.now(),
|
|
217
|
+
turnKey?: string,
|
|
218
|
+
): Promise<boolean> {
|
|
219
|
+
if (!sid || !Number.isSafeInteger(turn) || turn < 1) return false;
|
|
220
|
+
const file = hitsFile();
|
|
221
|
+
try {
|
|
222
|
+
await withStoreLock(
|
|
223
|
+
file,
|
|
224
|
+
async () => {
|
|
225
|
+
await rotateIfNeeded();
|
|
226
|
+
const line = formatLine({
|
|
227
|
+
ev: "gate_outcome",
|
|
228
|
+
ts: new Date(now).toISOString(),
|
|
229
|
+
sid,
|
|
230
|
+
turn,
|
|
231
|
+
...(turnKey ? { turnKey } : {}),
|
|
232
|
+
outcome: outcome === "FAIL" ? "fail" : "clean",
|
|
233
|
+
cmd,
|
|
234
|
+
});
|
|
235
|
+
await appendLog(file, line);
|
|
236
|
+
},
|
|
237
|
+
LOCK_WRITE,
|
|
238
|
+
);
|
|
239
|
+
return true;
|
|
240
|
+
} catch {
|
|
241
|
+
droppedOutcomes.set(file, (droppedOutcomes.get(file) ?? 0) + 1);
|
|
242
|
+
return false;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export async function readOutcomes(): Promise<TurnOutcome[]> {
|
|
247
|
+
const out: TurnOutcome[] = [];
|
|
248
|
+
for (const line of await readLines(hitsFile())) {
|
|
249
|
+
const f = parseLine(line);
|
|
250
|
+
if (!f || (f.ev !== "gate_outcome" && f.ev !== "turn_outcome")) continue;
|
|
251
|
+
const turn = typeof f.turn === "string" ? Number(f.turn) : NaN;
|
|
252
|
+
if (!Number.isFinite(turn)) continue;
|
|
253
|
+
if (f.outcome !== "fail" && f.outcome !== "clean") continue;
|
|
254
|
+
const outcome = f.outcome === "fail" ? "FAIL" : "PASS";
|
|
255
|
+
// Older mixed summaries did not preserve the order of their failures.
|
|
256
|
+
if (
|
|
257
|
+
f.ev === "turn_outcome" &&
|
|
258
|
+
outcome === "FAIL" &&
|
|
259
|
+
!f.lastFail &&
|
|
260
|
+
f.calls !== f.fails
|
|
261
|
+
)
|
|
262
|
+
continue;
|
|
263
|
+
out.push({
|
|
264
|
+
...(typeof f.lastFail === "string" ? { lastFail: f.lastFail } : {}),
|
|
265
|
+
ts: typeof f.ts === "string" ? f.ts : "",
|
|
266
|
+
sid: typeof f.sid === "string" ? f.sid : "",
|
|
267
|
+
...(typeof f.turnKey === "string" ? { turnKey: f.turnKey } : {}),
|
|
268
|
+
turn,
|
|
269
|
+
outcome,
|
|
270
|
+
cmd: typeof f.cmd === "string" ? f.cmd : "",
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
return out;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* What the ledger can say about one row, without claiming causation.
|
|
278
|
+
*
|
|
279
|
+
* `rides` — use lines crediting the row (a floor: throttled and dropped
|
|
280
|
+
* writes are invisible).
|
|
281
|
+
* `joined` — rides that landed on a turn which ALSO recorded a gate
|
|
282
|
+
* outcome. Everything else is unmeasured, not clean.
|
|
283
|
+
* `clean` — distinct row/turns with only passes after a ride.
|
|
284
|
+
* `failAfter` — distinct row/turns with a failure after a ride.
|
|
285
|
+
*
|
|
286
|
+
* A FAIL on the ride's own turn is correlation only. The row may have been
|
|
287
|
+
* irrelevant, correct-but-out-of-scope, or right and the failure someone
|
|
288
|
+
* else's. Nothing here distinguishes those, so no caller may use this to
|
|
289
|
+
* supersede a row on its own.
|
|
290
|
+
*/
|
|
291
|
+
export interface RowOutcome {
|
|
292
|
+
rides: number;
|
|
293
|
+
joined: number;
|
|
294
|
+
clean: number;
|
|
295
|
+
failAfter: number;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Join rides to same-turn gate outcomes on (sid, turn). A ride with no turn
|
|
300
|
+
* recorded (a legacy line, or a caller that did not know the
|
|
301
|
+
* turn) can never join, and counts toward `rides` only.
|
|
302
|
+
*/
|
|
303
|
+
export function joinUseWithOutcomes(
|
|
304
|
+
rides: HitEntry[],
|
|
305
|
+
outcomes: TurnOutcome[],
|
|
306
|
+
): Map<string, RowOutcome> {
|
|
307
|
+
const byTurn = new Map<
|
|
308
|
+
string,
|
|
309
|
+
{
|
|
310
|
+
lastGate: string;
|
|
311
|
+
lastFail: string;
|
|
312
|
+
verdicts: Map<string, "PASS" | "FAIL">;
|
|
313
|
+
}
|
|
314
|
+
>();
|
|
315
|
+
for (const o of outcomes) {
|
|
316
|
+
const key = JSON.stringify([o.sid, o.turn, o.turnKey]);
|
|
317
|
+
const entry = byTurn.get(key) ?? {
|
|
318
|
+
lastGate: "",
|
|
319
|
+
lastFail: "",
|
|
320
|
+
verdicts: new Map(),
|
|
321
|
+
};
|
|
322
|
+
if (o.ts > entry.lastGate) entry.lastGate = o.ts;
|
|
323
|
+
const fail = o.lastFail ?? (o.outcome === "FAIL" ? o.ts : "");
|
|
324
|
+
if (fail > entry.lastFail) entry.lastFail = fail;
|
|
325
|
+
byTurn.set(key, entry);
|
|
326
|
+
}
|
|
327
|
+
const out = new Map<string, RowOutcome>();
|
|
328
|
+
for (const line of rides) {
|
|
329
|
+
const turn = byTurn.get(
|
|
330
|
+
JSON.stringify([line.sid, line.turn, line.turnKey]),
|
|
331
|
+
);
|
|
332
|
+
for (const row of new Set(line.mems)) {
|
|
333
|
+
const cur = out.get(row) ?? {
|
|
334
|
+
rides: 0,
|
|
335
|
+
joined: 0,
|
|
336
|
+
clean: 0,
|
|
337
|
+
failAfter: 0,
|
|
338
|
+
};
|
|
339
|
+
out.set(row, cur);
|
|
340
|
+
cur.rides++;
|
|
341
|
+
if (!line.ts || !turn || turn.lastGate <= line.ts) continue;
|
|
342
|
+
// Same-millisecond failures cannot be ordered relative to this ride.
|
|
343
|
+
if (turn.lastFail === line.ts) continue;
|
|
344
|
+
cur.joined++;
|
|
345
|
+
const verdict = turn.lastFail > line.ts ? "FAIL" : "PASS";
|
|
346
|
+
const prior = turn.verdicts.get(row);
|
|
347
|
+
if (prior === verdict || prior === "FAIL") continue;
|
|
348
|
+
if (prior === "PASS") cur.clean--;
|
|
349
|
+
if (verdict === "PASS") cur.clean++;
|
|
350
|
+
else cur.failAfter++;
|
|
351
|
+
turn.verdicts.set(row, verdict);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return out;
|
|
355
|
+
}
|
|
356
|
+
|
|
164
357
|
// --- reading --------------------------------------------------------------------
|
|
165
358
|
|
|
166
359
|
export interface UseSignal {
|
|
@@ -229,6 +422,34 @@ export async function readReads(): Promise<ReadSet[]> {
|
|
|
229
422
|
return out;
|
|
230
423
|
}
|
|
231
424
|
|
|
425
|
+
/**
|
|
426
|
+
* Every ride the ledger recorded, with the session and turn it landed on — the
|
|
427
|
+
* shape the report joins against gate outcomes. `readLedger` aggregates by row and
|
|
428
|
+
* throws the grouping away, so this reads the same file for a different
|
|
429
|
+
* question rather than widening `UseLedger`, which hot paths (consolidation,
|
|
430
|
+
* status) carry.
|
|
431
|
+
*/
|
|
432
|
+
export async function readRides(): Promise<HitEntry[]> {
|
|
433
|
+
const out: HitEntry[] = [];
|
|
434
|
+
for (const line of await readLines(hitsFile())) {
|
|
435
|
+
const f = parseLine(line);
|
|
436
|
+
if (!f || f.ev !== "memory_used") continue;
|
|
437
|
+
const mems = typeof f.mem === "string" ? parseList(f.mem) : [];
|
|
438
|
+
if (!mems.length) continue;
|
|
439
|
+
const turn = typeof f.turn === "string" ? Number(f.turn) : NaN;
|
|
440
|
+
out.push({
|
|
441
|
+
ts: typeof f.ts === "string" ? f.ts : "",
|
|
442
|
+
src: f.src === "pull" || f.src === "recall" ? f.src : "inject",
|
|
443
|
+
sid: typeof f.sid === "string" ? f.sid : "",
|
|
444
|
+
...(typeof f.turnKey === "string" ? { turnKey: f.turnKey } : {}),
|
|
445
|
+
mems,
|
|
446
|
+
terms: typeof f.terms === "string" ? parseList(f.terms) : [],
|
|
447
|
+
...(Number.isFinite(turn) ? { turn } : {}),
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
return out;
|
|
451
|
+
}
|
|
452
|
+
|
|
232
453
|
/** Rows the ledger has NEVER seen used, plus the honest since-qualifier. */
|
|
233
454
|
export function neverRetrieved(
|
|
234
455
|
rows: Memory[],
|
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
|
}),
|
package/src/tools/status-tool.ts
CHANGED
|
@@ -1,10 +1,19 @@
|
|
|
1
1
|
// The memory_status tool, extracted from index.ts.
|
|
2
2
|
// Closure access arrives through ToolDeps.
|
|
3
3
|
import type { ToolRegister } from "./deps.ts";
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
getDroppedOutcomeWrites,
|
|
6
|
+
readLedger,
|
|
7
|
+
readOutcomes,
|
|
8
|
+
readRides,
|
|
9
|
+
} from "../telemetry/ledger.ts";
|
|
5
10
|
import { formatMemory } from "../inject/format.ts";
|
|
6
11
|
import { loadAll, malformedCount } from "../store/files/load.ts";
|
|
7
|
-
import {
|
|
12
|
+
import {
|
|
13
|
+
isVisibleTo,
|
|
14
|
+
readerForSession,
|
|
15
|
+
readerFromSid,
|
|
16
|
+
} from "../store/model/visibility.ts";
|
|
8
17
|
import {
|
|
9
18
|
isQuarantined,
|
|
10
19
|
quarantineReasons,
|
|
@@ -32,6 +41,7 @@ export const register: ToolRegister = (editor, deps) => {
|
|
|
32
41
|
async execute(_args, context): Promise<{ content: string }> {
|
|
33
42
|
// In-process truth: the live epoch + ledger, fresher than any file.
|
|
34
43
|
const sid = toolIds(context).sid;
|
|
44
|
+
const detailReader = readerForSession(sid);
|
|
35
45
|
const reportReader = readerFromSid(sid);
|
|
36
46
|
if (sid !== "?") await sessions.refresh(sid);
|
|
37
47
|
const status = sid === "?" ? null : await sessions.buildPayload(sid);
|
|
@@ -40,10 +50,19 @@ export const register: ToolRegister = (editor, deps) => {
|
|
|
40
50
|
// Use ledger: how much of the store has never been surfaced.
|
|
41
51
|
// Reported, never acted on — retirement is a decision, not a metric.
|
|
42
52
|
const ledger = await readLedger();
|
|
53
|
+
// rides joined to the gate outcome of the turn they rode. Read
|
|
54
|
+
// only here — the epoch payload path deliberately skips it, so the
|
|
55
|
+
// per-request path never pays two extra ledger reads.
|
|
43
56
|
const { active: act, counts: store } = summarizeStore(
|
|
44
57
|
all,
|
|
45
58
|
ledger,
|
|
46
59
|
malformed,
|
|
60
|
+
{
|
|
61
|
+
rides: await readRides(),
|
|
62
|
+
outcomes: await readOutcomes(),
|
|
63
|
+
droppedOutcomeWrites: getDroppedOutcomeWrites(),
|
|
64
|
+
visible: (row) => isVisibleTo(row, detailReader),
|
|
65
|
+
},
|
|
47
66
|
);
|
|
48
67
|
// Self-metrics: what the store costs, how fast it grows, and how
|
|
49
68
|
// stale a capture is when it fires. Same rule as above — the numbers
|