opencode-self-improvement 0.31.0 → 0.32.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.
Files changed (49) hide show
  1. package/README.md +31 -171
  2. package/docs/contradiction-authority.md +9 -1
  3. package/docs/export-import.md +61 -0
  4. package/docs/flags.md +3 -2
  5. package/docs/import-quarantine.md +2 -1
  6. package/docs/injection-cost.md +1 -1
  7. package/docs/install.md +45 -0
  8. package/docs/recall-quality.md +4 -0
  9. package/docs/secret-redaction.md +51 -0
  10. package/docs/surfaces.md +39 -0
  11. package/docs/troubleshooting.md +13 -6
  12. package/docs/use-ledger.md +44 -3
  13. package/docs/write-latency.md +25 -0
  14. package/package.json +1 -1
  15. package/src/capture/runtime.ts +1 -1
  16. package/src/capture/triggers.ts +16 -1
  17. package/src/consolidate/propose.ts +1 -1
  18. package/src/core/config/paths.ts +1 -1
  19. package/src/core/state.ts +11 -0
  20. package/src/events.ts +2 -2
  21. package/src/gate/gate.ts +1 -1
  22. package/src/identity/session-context.ts +1 -1
  23. package/src/index.ts +18 -9
  24. package/src/init/run.ts +1 -1
  25. package/src/init/stamp.ts +1 -1
  26. package/src/inject/digest.ts +1 -1
  27. package/src/inject/epochs.ts +2 -2
  28. package/src/recall/gate.ts +30 -4
  29. package/src/status/payload.ts +17 -0
  30. package/src/status/report.ts +17 -0
  31. package/src/status/store-summary.ts +81 -13
  32. package/src/store/files/load.ts +1 -1
  33. package/src/store/lock.ts +1 -1
  34. package/src/store/prune.ts +1 -1
  35. package/src/store/tombstones/rejection.ts +1 -1
  36. package/src/store/tombstones/tombstone.ts +1 -1
  37. package/src/store/undo.ts +1 -1
  38. package/src/{hits → telemetry}/ledger.ts +221 -0
  39. package/src/tools/consolidate.ts +2 -2
  40. package/src/tools/decay.ts +1 -1
  41. package/src/tools/deps.ts +1 -1
  42. package/src/tools/evidence.ts +1 -1
  43. package/src/tools/merge-review.ts +1 -1
  44. package/src/tools/recall.ts +15 -6
  45. package/src/tools/status-tool.ts +21 -2
  46. package/src/tools/update.ts +1 -1
  47. package/src/viewer/mutate.ts +1 -1
  48. /package/src/{command → init}/ensure.ts +0 -0
  49. /package/src/{evidence → telemetry}/record.ts +0 -0
package/src/store/undo.ts CHANGED
@@ -36,7 +36,7 @@ import {
36
36
  writeAtomic,
37
37
  } from "../core/logfmt/publish.ts";
38
38
  import { readLines } from "../core/logfmt/read.ts";
39
- import { contentHash } from "../evidence/record.ts";
39
+ import { contentHash } from "../telemetry/record.ts";
40
40
  import { isWithin } from "./containment.ts";
41
41
  import { snapshotFiles } from "./files/snapshots.ts";
42
42
  import { LOCK_RESTORE, withStoreLock } from "./lock.ts";
@@ -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[],
@@ -4,8 +4,8 @@
4
4
  import type { ToolRegister } from "./deps.ts";
5
5
  import { proposeConsolidations } from "../consolidate/propose.ts";
6
6
  import { renderProposals } from "../consolidate/render.ts";
7
- import { captureEvidenceContext, record } from "../evidence/record.ts";
8
- import { readLedger, readReads } from "../hits/ledger.ts";
7
+ import { captureEvidenceContext, record } from "../telemetry/record.ts";
8
+ import { readLedger, readReads } from "../telemetry/ledger.ts";
9
9
  import { loadAll } from "../store/files/load.ts";
10
10
  import { isInjectable } from "../store/model/predicates.ts";
11
11
  import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
@@ -2,7 +2,7 @@
2
2
  // and handler are byte-identical to the pre-split source; closure access arrives
3
3
  // through ToolDeps.
4
4
  import type { ToolRegister } from "./deps.ts";
5
- import { captureEvidenceContext, record } from "../evidence/record.ts";
5
+ import { captureEvidenceContext, record } from "../telemetry/record.ts";
6
6
  import { snapshotFiles } from "../store/files/snapshots.ts";
7
7
  import { markManySuperseded } from "../store/files/supersede.ts";
8
8
  import { findStaleOpen } from "../portable/decay.ts";
package/src/tools/deps.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // so a tool file never reaches into the plugin setup closure.
4
4
  import type { GateContext } from "../gate/gate.ts";
5
5
  import type { createInjectionEpochs } from "../inject/epochs.ts";
6
- import type { HitSource } from "../hits/ledger.ts";
6
+ import type { HitSource } from "../telemetry/ledger.ts";
7
7
  import type { Memory } from "../store/model/memory.ts";
8
8
 
9
9
  export interface ToolDeps {
@@ -2,7 +2,7 @@
2
2
  // and handler are byte-identical to the pre-split source; closure access arrives
3
3
  // through ToolDeps.
4
4
  import type { ToolRegister } from "./deps.ts";
5
- import { evidenceFileFor } from "../evidence/record.ts";
5
+ import { evidenceFileFor } from "../telemetry/record.ts";
6
6
  import { parseLine } from "../core/logfmt/format.ts";
7
7
  import { readLines } from "../core/logfmt/read.ts";
8
8
  import { evidenceVisibleTo, readerFromSid } from "../store/model/visibility.ts";
@@ -2,7 +2,7 @@
2
2
  // Closure access arrives through ToolDeps.
3
3
  import type { ToolRegister } from "./deps.ts";
4
4
  import { memoryRoot } from "../core/config/paths.ts";
5
- import { record } from "../evidence/record.ts";
5
+ import { record } from "../telemetry/record.ts";
6
6
  import { withStoreBatch } from "../store/lock.ts";
7
7
  import { loadAll } from "../store/files/load.ts";
8
8
  import { clearSuperseded, markSuperseded } from "../store/files/supersede.ts";
@@ -2,10 +2,11 @@
2
2
  // and handler are byte-identical to the pre-split source; closure access arrives
3
3
  // through ToolDeps.
4
4
  import type { ToolRegister } from "./deps.ts";
5
- import { record } from "../evidence/record.ts";
5
+ import { record } from "../telemetry/record.ts";
6
6
  import { formatMemory } from "../inject/format.ts";
7
7
  import {
8
8
  admitsRow,
9
+ exactAliasMatches,
9
10
  gateEnabled,
10
11
  queryConcepts,
11
12
  recallHaystack,
@@ -51,14 +52,22 @@ export const register: ToolRegister = (editor, deps) => {
51
52
  results = results.filter((m) => m.scope.includes(args.scope!));
52
53
  if (args.type) results = results.filter((m) => m.type === args.type);
53
54
  if (args.query) {
54
- // Default on: a row must share two whole words of the query — the
55
- // concepts rule, not the scorer's substring test (src/recall/gate.ts,
56
- //). OPENCODE_MEMORY_QUERY_GATE=off restores the old matcher.
57
55
  const gate = gateEnabled();
58
56
  const concepts = gate ? queryConcepts(args.query) : [];
57
+ const aliases = exactAliasMatches(args.query, concepts, results);
59
58
  results = results
60
- .map((m) => ({ m, score: scoreMemory(m, args.query!) }))
61
- .filter((x) => x.score > 0 && (!gate || admitsRow(x.m, concepts)))
59
+ .map((m) => ({
60
+ m,
61
+ score: Math.max(
62
+ scoreMemory(m, args.query!),
63
+ aliases.has(m) ? 1 : 0,
64
+ ),
65
+ }))
66
+ .filter(
67
+ (x) =>
68
+ x.score > 0 &&
69
+ (!gate || aliases.has(x.m) || admitsRow(x.m, concepts)),
70
+ )
62
71
  .sort((a, b) => b.score - a.score)
63
72
  .map((x) => x.m);
64
73
  }
@@ -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 { readLedger } from "../hits/ledger.ts";
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 { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
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
@@ -5,7 +5,7 @@
5
5
  import { join } from "node:path";
6
6
  import { memoryRoot } from "../core/config/paths.ts";
7
7
  import { nonCaptureTags } from "../core/guidance.ts";
8
- import { record } from "../evidence/record.ts";
8
+ import { record } from "../telemetry/record.ts";
9
9
  import { auditCaveat, runWriteGate, sameStrList } from "../gate/gate.ts";
10
10
  import { loadAll } from "../store/files/load.ts";
11
11
  import { markSuperseded } from "../store/files/supersede.ts";
@@ -13,7 +13,7 @@ import {
13
13
  chainId,
14
14
  contentHash,
15
15
  targetRepoFields,
16
- } from "../evidence/record.ts";
16
+ } from "../telemetry/record.ts";
17
17
  import { removeTombstone, tombstone } from "../store/tombstones/tombstone.ts";
18
18
  import { redactSecrets } from "../store/secrets.ts";
19
19
  import { formatLine, parseLine } from "../core/logfmt/format.ts";
File without changes
File without changes