opencode-self-improvement 0.21.0 → 0.22.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.21.0",
3
+ "version": "0.22.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": {
@@ -0,0 +1,254 @@
1
+ // Capture policy: WHEN a capture is worth paying for (#334).
2
+ //
3
+ // Today every turn end triggers a capture (throttled by a fixed cooldown), and
4
+ // every capture re-mines the WHOLE transcript. Two costs follow. The first is
5
+ // the number of passes: a two-hour session with a turn every six minutes is
6
+ // ~20 passes. The second is worse — each pass re-reads everything mined before,
7
+ // pays full generation price for it, and the gate then dedups most of the
8
+ // result away. You pay to produce rows you throw away.
9
+ //
10
+ // Both are fixable with facts the plugin already holds in-process at zero token
11
+ // cost, so neither gate needs a model call to decide.
12
+ import type { SessionState } from "../core/state.ts";
13
+ import { conversationTurns, flattenTranscript } from "./transcript.ts";
14
+
15
+ /**
16
+ * How many messages of a session's context a capture has already mined. The
17
+ * delta window is everything after this index; a session that has never been
18
+ * captured starts at 0 and mines the whole context, which is correct.
19
+ */
20
+ interface Cursor {
21
+ /** Message count at the last completed capture. */
22
+ msgs: number;
23
+ /** Turn index at that capture; the signal window is turns after this. */
24
+ turn: number;
25
+ /**
26
+ * Identity of the messages that capture consumed — the flattened prefix, not
27
+ * its last message (#366 review, round 4). A count says how many messages were
28
+ * consumed; it cannot say WHICH ones, and a host that replaces the transcript
29
+ * and then lets it grow again hands back an array longer than the cursor that
30
+ * shares nothing with it.
31
+ */
32
+ fp?: string;
33
+ }
34
+
35
+ // Two 32-bit accumulators plus the length: FNV-1a and a djb2-style rolling
36
+ // hash. Deterministic across restarts (a cursor is only ever compared with the
37
+ // store of the same process family), allocation-light, and strong enough for
38
+ // what it is: an equality test on the text of messages already read, never a
39
+ // security decision. Length is in the digest so two different-length prefixes
40
+ // can never agree even if both accumulators did.
41
+ function fingerprintOf(text: string): string {
42
+ let fnv = 0x811c9dc5;
43
+ let djb = 0x811c9dc5;
44
+ for (let i = 0; i < text.length; i++) {
45
+ const c = text.charCodeAt(i);
46
+ fnv = Math.imul(fnv ^ c, 0x01000193);
47
+ djb = (Math.imul(djb, 33) + c) | 0;
48
+ }
49
+ return `${text.length}:${(fnv >>> 0).toString(36)}:${(djb >>> 0).toString(36)}`;
50
+ }
51
+
52
+ /**
53
+ * Identity of the FIRST `count` messages — everything the cursor claims to have
54
+ * consumed. Undefined when there is nothing to fingerprint: not an array, a
55
+ * count this array cannot supply, or messages that decode to no text at all.
56
+ *
57
+ * The WHOLE prefix, not its last message (round 4 [P2]): an ordinary assistant
58
+ * reply repeated at the boundary position makes a replaced transcript look
59
+ * unchanged, and no hash collision is required for that.
60
+ *
61
+ * Cost is one flatten of text the pass has already flattened once, in-process.
62
+ * What the delta exists to avoid paying is the capture MODEL call, not this.
63
+ */
64
+ export function prefixFingerprint(
65
+ msgs: unknown,
66
+ count: number,
67
+ ): string | undefined {
68
+ if (!Array.isArray(msgs) || count <= 0 || msgs.length < count)
69
+ return undefined;
70
+ const text = flattenTranscript(msgs.slice(0, count));
71
+ return text ? fingerprintOf(text) : undefined;
72
+ }
73
+
74
+ // Bounded like every other session-keyed ledger, so a resident server cannot
75
+ // grow it. A lost cursor costs one wider capture, never a wrong row.
76
+ const MAX_CURSORS = 500;
77
+ const cursors = new Map<string, Cursor>();
78
+
79
+ export function captureCursor(sid: string): Cursor {
80
+ return cursors.get(sid) ?? { msgs: 0, turn: 0 };
81
+ }
82
+
83
+ export function advanceCaptureCursor(
84
+ sid: string,
85
+ msgs: number,
86
+ turn: number,
87
+ fp?: string,
88
+ ): void {
89
+ if (cursors.size >= MAX_CURSORS && !cursors.has(sid)) {
90
+ const oldest = cursors.keys().next().value;
91
+ if (oldest !== undefined) cursors.delete(oldest);
92
+ }
93
+ cursors.set(sid, { msgs, turn, fp });
94
+ }
95
+
96
+ export function resetCaptureCursors(): void {
97
+ cursors.clear();
98
+ }
99
+
100
+ /**
101
+ * Is this array still the transcript the cursor was counting (#366 review)?
102
+ *
103
+ * Two shapes say it is not. SHORTER than the count: compaction replaced the
104
+ * transcript, so `since` names an index that no longer exists — a normal event,
105
+ * not a corrupted store. LONG ENOUGH BUT A DIFFERENT PREFIX: the transcript was
106
+ * replaced and then grew past the old count before the next capture observed the
107
+ * swap, which a length check reads as an ordinary append while the new user rule
108
+ * sits below the cursor at index 0.
109
+ *
110
+ * The prefix, message for message, is the invariant: if the first `msgs` entries
111
+ * are the ones the last pass mined, then mining from `msgs` is correct, whatever
112
+ * has been appended after it. Told apart from "nothing new was appended"
113
+ * (`since` equal to the length and an unchanged prefix), which stays an empty
114
+ * window. A cursor with no fingerprint — written before this existed, or left by
115
+ * a pass that mined a payload with no message array behind it — falls back to the
116
+ * length check, so an upgrade never restarts a window on its own.
117
+ */
118
+ export function transcriptReplaced(
119
+ msgs: unknown,
120
+ cursor: { msgs: number; fp?: string },
121
+ ): boolean {
122
+ if (!Array.isArray(msgs)) return false;
123
+ if (cursor.msgs === 0) return false;
124
+ if (msgs.length < cursor.msgs) return true;
125
+ if (cursor.fp === undefined) return false;
126
+ return prefixFingerprint(msgs, cursor.msgs) !== cursor.fp;
127
+ }
128
+
129
+ /**
130
+ * Slice the message array down to what has not been mined yet. Returns the
131
+ * input unchanged when it is not an array (a seeded compaction payload of
132
+ * unknown shape) or when nothing was consumed, so the caller's existing
133
+ * thin-check still applies.
134
+ */
135
+ export function deltaMessages(msgs: unknown, since: number): unknown {
136
+ if (!Array.isArray(msgs) || since <= 0) return msgs;
137
+ // A context that shrank past the cursor is a REPLACED transcript (compaction),
138
+ // not a window that has been fully mined (#366 review). Mine what is there:
139
+ // an empty window here was skipped by the thin-check WITHOUT advancing the
140
+ // cursor, so every later turn was skipped as well until the array grew past
141
+ // the stale count.
142
+ if (since > msgs.length) return msgs;
143
+ return msgs.slice(since);
144
+ }
145
+
146
+ /**
147
+ * Did the USER state a rule or spec in the window? The signal gate reads the
148
+ * tool ledger, so a session that only talks — "TAX_RATE must be 0.0825", no
149
+ * edits, no gate commands — would skip the capture and lose the hint channel
150
+ * (#339) for good when the session ends. A declarative marker in a user
151
+ * message is the cheap stand-in for "this window can hold a durable fact".
152
+ *
153
+ * Deliberately loose in the SAFE direction: a false positive costs one
154
+ * capture we would have paid for anyway; a false negative loses the user's
155
+ * stated spec. Unknown message shapes fire.
156
+ */
157
+ const GUIDED_MARKER =
158
+ /\b(must|never|always|shall|rule|spec|requirement|mandatory|forbidden)\b/i;
159
+
160
+ export function guidedStatementInWindow(
161
+ msgs: unknown,
162
+ sinceMsgs: number,
163
+ ): boolean {
164
+ if (!Array.isArray(msgs)) return true;
165
+ const window = msgs.slice(Math.max(0, sinceMsgs));
166
+ if (window.length === 0) return false;
167
+ // The SAME decode the transcript uses (#366 review): roles come from
168
+ // `info.role` / `role` / `type`, text from `parts[]` / `content[]` / `text` /
169
+ // a string `content`. Reading one narrow shape here meant a genuine user rule
170
+ // in any other accepted shape got a no-signal skip before generation — the
171
+ // exact loss this guard exists to prevent.
172
+ const turns = conversationTurns(window);
173
+ if (turns.length === 0) {
174
+ // Nothing in the window decoded to a conversation turn. That is either a
175
+ // window of non-conversation records or a message shape this build has
176
+ // never seen, and the two are indistinguishable from here — so it fires.
177
+ return true;
178
+ }
179
+ return turns.some((t) => t.role === "user" && GUIDED_MARKER.test(t.text));
180
+ }
181
+
182
+ export interface SignalVerdict {
183
+ ok: boolean;
184
+ /** What justified the capture, or why it did not. Logged, never injected. */
185
+ why: string;
186
+ }
187
+
188
+ const EDIT_TOOLS = new Set(["edit", "write", "patch", "multiedit"]);
189
+
190
+ /**
191
+ * Did this session produce anything durable since the last capture?
192
+ *
193
+ * Three signals, all read off the tool ledger the plugin already keeps:
194
+ *
195
+ * - `edited` — a file was written. Most durable rows describe a
196
+ * change; a turn that only read has never produced one.
197
+ * - `gateRecovered` — a gate command (build/test/lint/typecheck) failed and
198
+ * a later one of the same kind passed. This is the
199
+ * FAIL->PASS pair `t4_learning` already records, and it
200
+ * is the single most lesson-shaped event available.
201
+ * - `newCommandPassed`— a command passed that had never passed in this
202
+ * session. The first `bun test ./src` is a fact worth
203
+ * keeping; the tenth is not.
204
+ *
205
+ * Deliberately conservative in the SAFE direction: an unknown tool name or a
206
+ * trimmed ledger tail can only cause a MISSED capture, and a missed capture
207
+ * costs nothing the next signal-bearing turn cannot recover, because the
208
+ * cursor does not advance on a skip.
209
+ */
210
+ export function captureSignalSince(
211
+ s: SessionState,
212
+ sinceTurn: number,
213
+ ): SignalVerdict {
214
+ // Turn tracking never ran (no session.prompt observed), so the window is
215
+ // meaningless rather than empty. Capture: a policy that silently stops
216
+ // storing is the failure mode this file exists to avoid, and this is the
217
+ // one case where "no evidence" does not mean "nothing happened".
218
+ if (s.turns === 0) return { ok: true, why: "no-turn-tracking" };
219
+ const inWindow = s.calls.filter((c) => (c.turn ?? 0) > sinceTurn);
220
+ if (inWindow.some((c) => EDIT_TOOLS.has(c.tool)))
221
+ return { ok: true, why: "edited" };
222
+ const gates = inWindow.filter((c) => c.gateCheck);
223
+ const failed = new Set(
224
+ gates.filter((c) => c.status === "FAIL").map((c) => c.cmd),
225
+ );
226
+ if (
227
+ failed.size &&
228
+ gates.some((c) => c.status === "PASS" && failed.has(c.cmd))
229
+ )
230
+ return { ok: true, why: "gateRecovered" };
231
+ const passedBefore = new Set(
232
+ s.calls
233
+ .filter(
234
+ (c) =>
235
+ (c.turn ?? 0) <= sinceTurn &&
236
+ c.status === "PASS" &&
237
+ (c.tool === "bash" || c.tool === "shell"),
238
+ )
239
+ .map((c) => c.cmd ?? c.arg ?? ""),
240
+ );
241
+ if (
242
+ inWindow.some(
243
+ (c) =>
244
+ (c.tool === "bash" || c.tool === "shell") &&
245
+ c.status === "PASS" &&
246
+ !passedBefore.has(c.cmd ?? c.arg ?? ""),
247
+ )
248
+ )
249
+ return { ok: true, why: "newCommandPassed" };
250
+ // The window is real and held tool calls, none of them durable: reads,
251
+ // greps, a repeated command. Skip, and leave the cursor alone so the next
252
+ // signal-bearing turn still mines this one too.
253
+ return { ok: false, why: "no-signal" };
254
+ }
@@ -2,7 +2,7 @@
2
2
  // subscriptions and dispatch closures belong to one setup instance.
3
3
  import type { Cleanup } from "@opencode/plugin/promise/plugin";
4
4
  import { cmpTs } from "../core/cmp-ts.ts";
5
- import { setCurrent } from "../core/state.ts";
5
+ import { session, setCurrent } from "../core/state.ts";
6
6
  import { AUTO_CAPTURE_TAG, USER_GUIDED_TAG } from "../core/tags.ts";
7
7
  import { record, recordCaptureLag } from "../evidence/record.ts";
8
8
  import { type GateContext, runWriteGate } from "../gate/gate.ts";
@@ -26,6 +26,15 @@ import {
26
26
  validateGuidedQuotes,
27
27
  } from "./guided-rules.ts";
28
28
  import { lagSince } from "./lag.ts";
29
+ import {
30
+ advanceCaptureCursor,
31
+ captureCursor,
32
+ captureSignalSince,
33
+ deltaMessages,
34
+ guidedStatementInWindow,
35
+ prefixFingerprint,
36
+ transcriptReplaced,
37
+ } from "./policy.ts";
29
38
  import { buildCapturePrompt } from "./prompt.ts";
30
39
  import { type SessionModelRef, sessionModel } from "./session-model.ts";
31
40
  import {
@@ -189,6 +198,12 @@ export function configureAutoCapture(
189
198
  // picks the default-on arm (FINDINGS 2026-11-08 §4.4).
190
199
  const guidedRules = ctx.options?.captureGuidedRules === true;
191
200
  const captureOnCompact = ctx.options?.captureOnCompact !== false;
201
+ // #334: two cost levers, both OFF by default until the benchmark says which
202
+ // way to set them. `captureOnSignal` skips a capture whose turn produced
203
+ // nothing durable; `captureDelta` mines only the turns since the last
204
+ // capture instead of re-reading the whole session every time.
205
+ const captureOnSignal = ctx.options?.captureOnSignal === true;
206
+ const captureDelta = ctx.options?.captureDelta === true;
192
207
  const modelRef = omitted ? null : parseModelRef(captureModelOpt);
193
208
  if (!omitted && !modelRef) {
194
209
  // Invalid explicit model: skip registering the whole subscription
@@ -347,8 +362,34 @@ export function configureAutoCapture(
347
362
  );
348
363
  return;
349
364
  }
365
+ // #334: the signal gate. The PORT moved it AFTER the context read
366
+ // (the POC ran it before): a user-stated spec with no tool activity
367
+ // is exactly the hint channel (#339) and must not be skipped, and
368
+ // detecting it needs the messages. The read is a local host call;
369
+ // the expensive artifact the gate saves — the capture model call —
370
+ // is still saved.
371
+ const cursor = captureCursor(sid);
372
+ // The turn this pass DESCRIBES. Completion must advance to this number,
373
+ // not to whatever the session has reached by then: a turn delivered
374
+ // while the model call is in flight was never in the prompt, and
375
+ // consuming it leaves that work unmined with nothing left to ask for it
376
+ // (#366 review).
377
+ const turnAtStart = session(sid).turns;
350
378
  let transcript = seeded;
351
379
  let msgs = seededMsgs;
380
+ // The array AS READ, before any delta slice: the cursor's fingerprint
381
+ // covers the consumed prefix of that array, not of the window.
382
+ let readMsgs = seededMsgs;
383
+ // A seeded compaction payload is the pre-compaction window the hook
384
+ // deliberately handed over (the Compaction Cliff: one round retains 53%
385
+ // of exact-wording rules), so it is mined whole and the cursor is not
386
+ // consulted — which also means the cursor advances TO its length, never
387
+ // past it by the old count.
388
+ const minedWhole = seededMsgs !== undefined;
389
+ // True when the context is no longer the array the cursor counted
390
+ // (#366 review): the offset names a transcript that does not exist, so
391
+ // the window below is the whole context, mined from the beginning.
392
+ let deltaRestart = false;
352
393
  if (transcript.length < 200) {
353
394
  msgs = await contextFn({ sessionID: sid });
354
395
  // #211: disposed while the host was answering. The drain in cleanup()
@@ -357,7 +398,44 @@ export function configureAutoCapture(
357
398
  // the thin-transcript receipt below, then the model call. Silent, for
358
399
  // the same reason the post-model check is.
359
400
  if (controller.signal.aborted) return;
401
+ readMsgs = msgs;
360
402
  transcript = flattenTranscript(msgs);
403
+ // Told in BOTH modes. With the delta off the pass mines the whole
404
+ // context anyway, and the guidance window further down has to follow
405
+ // the same array the pass reads.
406
+ deltaRestart = transcriptReplaced(msgs, cursor);
407
+ if (captureDelta && !deltaRestart) {
408
+ const before = msgs;
409
+ msgs = deltaMessages(msgs, cursor.msgs);
410
+ if (msgs !== before) transcript = flattenTranscript(msgs);
411
+ }
412
+ }
413
+ if (captureOnSignal) {
414
+ let verdict = captureSignalSince(session(sid), cursor.turn);
415
+ if (
416
+ !verdict.ok &&
417
+ guidedStatementInWindow(
418
+ msgs,
419
+ captureDelta || deltaRestart ? 0 : cursor.msgs,
420
+ )
421
+ )
422
+ verdict = { ok: true, why: "guidedStatement" };
423
+ if (!verdict.ok) {
424
+ await record(
425
+ "auto_capture_skipped",
426
+ {
427
+ session: sid,
428
+ trigger,
429
+ reason: verdict.why,
430
+ since_turn: cursor.turn,
431
+ ...(modelTag ? { model: modelTag } : {}),
432
+ },
433
+ true,
434
+ sid,
435
+ captureGate.evidenceContext,
436
+ );
437
+ return; // nothing durable this window; the cursor does NOT advance
438
+ }
361
439
  }
362
440
  if (transcript.length < 200) {
363
441
  // This return used to be silent, and that silence is why a dead
@@ -618,6 +696,27 @@ export function configureAutoCapture(
618
696
  captureGate.evidenceContext,
619
697
  modelTag,
620
698
  );
699
+ // #334: the window is consumed. Advance when a capture RAN, whatever it
700
+ // found — zero candidates is an answer, and re-mining an answered
701
+ // window every turn is precisely the cost this cursor exists to remove.
702
+ // A skip returns early and leaves the cursor where it was, so the next
703
+ // signal-bearing turn still mines everything since the last real pass.
704
+ if (captureDelta || captureOnSignal) {
705
+ // A window is consumed by the pass that mined it. A seeded payload or
706
+ // a replaced transcript IS the whole window, so the cursor becomes its
707
+ // length; an ordinary delta window sits AFTER what was mined before.
708
+ const total = !Array.isArray(msgs)
709
+ ? cursor.msgs
710
+ : minedWhole || deltaRestart || !captureDelta
711
+ ? msgs.length
712
+ : cursor.msgs + msgs.length;
713
+ advanceCaptureCursor(
714
+ sid,
715
+ total,
716
+ turnAtStart,
717
+ prefixFingerprint(readMsgs, total),
718
+ );
719
+ }
621
720
  }
622
721
 
623
722
  void (async () => {
@@ -102,6 +102,24 @@ export function flattenTranscript(msgs: unknown): string {
102
102
  .join("\n");
103
103
  }
104
104
 
105
+ /**
106
+ * The decoder itself, for a caller that needs the ROLES rather than a rendered
107
+ * block (#366 review). Anything that decides "the user said this" has to read
108
+ * roles the way the transcript does, or the two disagree about who owns a line:
109
+ * the capture parser accepts `info.role` / `role` / `type` for the role and
110
+ * `parts[]` / `content[]` / `text` / string `content` for the text, and a
111
+ * hand-rolled reader that misses one of them silently reports "no user rule
112
+ * here" for a shape that is perfectly readable.
113
+ *
114
+ * Total, like `parseTurns`: junk yields [], never a throw. An empty result
115
+ * means "no conversation turn was recognised" — which covers both a window of
116
+ * non-conversation records and a message shape this build has never seen, so a
117
+ * caller that cannot tell the two apart must fail toward acting.
118
+ */
119
+ export function conversationTurns(msgs: unknown): ParsedTurn[] {
120
+ return parseTurns(msgs);
121
+ }
122
+
105
123
  /**
106
124
  * The same turns, partitioned (#333).
107
125
  *