opencode-self-improvement 0.14.8 → 0.14.10

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 CHANGED
@@ -293,5 +293,6 @@ bun run gate:hooks # once per clone: run the gate on `git push`
293
293
  | `/repo-init` missing from the command list | The self-install couldn't write to `~/.config/opencode/commands/`. Create it and restart, or ask the model to "init memory for this repo" — the same tool. |
294
294
  | Init says `Graph: unavailable` | `codebase-memory-mcp` couldn't start. Install pinned `0.11.0` or point `OPENCODE_CBM_BIN` at the binary. Scripts are still remembered without it. |
295
295
  | Stale plugin after an update | `opencode plugin update opencode-self-improvement` (or bump the pinned `@version` in the `plugins` entry) and restart opencode. |
296
+ | `Error: Plugin is not configured` right after `plugin add` | An opencode bug ([#54654](https://github.com/anomalyco/opencode/issues/54654)), not a config problem: the first `plugin list/check/update` against a cold background service reads the plugin inventory before activation finishes. The plugin is installed and loading — just run the command again. |
296
297
  | Auto-capture does nothing | `autoCapture` needs a valid `captureModel` in `provider/id` form; a bad one disables capture with a startup warning. `captureOnCompact` alone does nothing. Rejected candidates are logged as evidence, not errors — check `memory_evidence`. |
297
298
  | Reset all memories | Delete `~/.config/opencode/memory/`. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.14.8",
3
+ "version": "0.14.10",
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/evidence.ts CHANGED
@@ -13,8 +13,18 @@ export async function record(
13
13
  ev: EvidenceEvent,
14
14
  fields: Record<string, unknown> = {},
15
15
  includeContext = true,
16
+ sessionID?: string,
16
17
  ): Promise<void> {
17
- const { sid, call } = getCurrent();
18
+ const cur = getCurrent();
19
+ // An explicitly threaded session outranks the ambient one: gate-authored
20
+ // lines must name the session the gate runs FOR, not whichever setCurrent
21
+ // fired last during the gate's own awaits (#118 review note 1 — the rows
22
+ // were fixed in #118, these lines were the residue). When the two disagree,
23
+ // the ambient call belongs to the OTHER session's flow, so it is dropped
24
+ // rather than borrowed. With sessionID undefined (tool paths — issue #121)
25
+ // this is exactly the old ambient read.
26
+ const sid = sessionID ?? cur.sid;
27
+ const call = sessionID !== undefined && sessionID !== cur.sid ? undefined : cur.call;
18
28
  const line = formatLine({
19
29
  ev,
20
30
  ts: new Date().toISOString(),
@@ -63,11 +73,17 @@ export async function recordWriteBlocked(
63
73
  reason: string,
64
74
  flags: string[],
65
75
  chain?: string,
76
+ sessionID?: string,
66
77
  ): Promise<void> {
67
- await record("write_blocked", {
68
- gate,
69
- reason,
70
- flags: `[${flags.join(",")}]`,
71
- ...(chain ? { chain } : {}),
72
- });
78
+ await record(
79
+ "write_blocked",
80
+ {
81
+ gate,
82
+ reason,
83
+ flags: `[${flags.join(",")}]`,
84
+ ...(chain ? { chain } : {}),
85
+ },
86
+ true,
87
+ sessionID,
88
+ );
73
89
  }
package/src/gates.ts CHANGED
@@ -227,16 +227,26 @@ export async function runWriteGate(
227
227
  ctx: GateContext,
228
228
  ): Promise<GateOutcome> {
229
229
  const chain = chainId();
230
+ // Gate audit lines thread the session: runWriteGate awaits (analysis, the
231
+ // locked append), and another session's dispatch can move the ambient
232
+ // current mid-gate — ambient-read lines would then name the wrong session
233
+ // (#118 review note 1; the rows were fixed in #118, these were the
234
+ // residue). Where ctx.sessionID is unset (tool paths — issue #121) record()
235
+ // keeps the ambient read, exactly as before.
236
+ const rec = (ev: string, fields: Record<string, unknown> = {}, includeContext = true) =>
237
+ record(ev, fields, includeContext, ctx.sessionID);
238
+ const recBlocked = (gate: number, reason: string, flags: string[], chain?: string) =>
239
+ recordWriteBlocked(gate, reason, flags, chain, ctx.sessionID);
230
240
 
231
241
  // Size/type floor BEFORE any scanning: gate analysis regexes
232
242
  // over megabyte content backtrack super-linearly and freeze the service
233
243
  // event loop (100KB write = 6s, 2MB = never returned).
234
244
  if (typeof candidate.content !== "string") {
235
- await recordWriteBlocked(4, "invalid_content", [`content_type=${typeof candidate.content}`], chain);
245
+ await recBlocked(4, "invalid_content", [`content_type=${typeof candidate.content}`], chain);
236
246
  return { action: "blocked", reason: "invalid_content", chain, hint: "content must be a string." };
237
247
  }
238
248
  if (candidate.content.length > MAX_CONTENT_CHARS) {
239
- await recordWriteBlocked(4, "content_too_long", [`len=${candidate.content.length}`, `max=${MAX_CONTENT_CHARS}`], chain);
249
+ await recBlocked(4, "content_too_long", [`len=${candidate.content.length}`, `max=${MAX_CONTENT_CHARS}`], chain);
240
250
  return {
241
251
  action: "blocked",
242
252
  reason: "content_too_long",
@@ -271,7 +281,7 @@ export async function runWriteGate(
271
281
  badMetadata.push("kw");
272
282
  }
273
283
  if (badMetadata.length) {
274
- await recordWriteBlocked(4, "invalid_metadata", [`fields=${badMetadata.join(",")}`], chain);
284
+ await recBlocked(4, "invalid_metadata", [`fields=${badMetadata.join(",")}`], chain);
275
285
  return {
276
286
  action: "blocked",
277
287
  reason: "invalid_metadata",
@@ -287,7 +297,7 @@ export async function runWriteGate(
287
297
  containsSecret(candidate.issue) ? "issue" : undefined,
288
298
  ].filter((field): field is string => field !== undefined);
289
299
  if (credentialMetadata.length) {
290
- await recordWriteBlocked(
300
+ await recBlocked(
291
301
  4,
292
302
  "credential_in_metadata",
293
303
  credentialMetadata.map((field) => `field=${field}`),
@@ -310,7 +320,7 @@ export async function runWriteGate(
310
320
  };
311
321
 
312
322
  const ch = contentHash(candidate.content);
313
- await record("gate_start", {
323
+ await rec("gate_start", {
314
324
  chain,
315
325
  op: "write",
316
326
  scope: candidate.scope,
@@ -331,7 +341,7 @@ export async function runWriteGate(
331
341
  tree,
332
342
  });
333
343
  if (g1.drift) {
334
- await record("graph_drift", {
344
+ await rec("graph_drift", {
335
345
  gate: 1,
336
346
  symbol: g1.drift.symbol,
337
347
  from: g1.drift.from,
@@ -341,7 +351,7 @@ export async function runWriteGate(
341
351
  chain,
342
352
  });
343
353
  } else {
344
- await record("graph_current", {
354
+ await rec("graph_current", {
345
355
  gate: 1,
346
356
  refs: g1.refs,
347
357
  resolved: g1.resolved.length ? g1.resolved.join(",") : undefined,
@@ -363,7 +373,7 @@ export async function runWriteGate(
363
373
  if (s) stale.push(s);
364
374
  }
365
375
  const bailed = scopeMems.length === 0;
366
- await record("ref_stale_scan", {
376
+ await rec("ref_stale_scan", {
367
377
  gate: 2,
368
378
  scope: candidate.scope,
369
379
  delta: bracketList(delta),
@@ -376,7 +386,7 @@ export async function runWriteGate(
376
386
  let supersededTs: string | undefined;
377
387
  const driftPlan: { s: StaleRef; target: string; fields: SupersedeFields }[] = [];
378
388
  for (const s of stale) {
379
- await record("ref_stale", {
389
+ await rec("ref_stale", {
380
390
  gate: 2,
381
391
  mem: s.memory.ts,
382
392
  scope: candidate.scope,
@@ -402,7 +412,7 @@ export async function runWriteGate(
402
412
  if (markedCount > 0) {
403
413
  for (const p of driftPlan) {
404
414
  supersededTs = p.s.memory.ts;
405
- await record("superseded_by", {
415
+ await rec("superseded_by", {
406
416
  gate: 2,
407
417
  mem: p.s.memory.ts,
408
418
  target: p.target,
@@ -417,7 +427,7 @@ export async function runWriteGate(
417
427
  }
418
428
 
419
429
  if (canon) {
420
- await record("canonical_hit", {
430
+ await rec("canonical_hit", {
421
431
  gate: 2,
422
432
  entity: canon.entry.entity,
423
433
  value: canon.entry.value,
@@ -446,7 +456,7 @@ export async function runWriteGate(
446
456
  })))) > 0) {
447
457
  for (const p of canonPlan) {
448
458
  if (!supersededTs) supersededTs = p.ts;
449
- await record("superseded_by", {
459
+ await rec("superseded_by", {
450
460
  gate: 2,
451
461
  mem: p.ts,
452
462
  target,
@@ -518,7 +528,7 @@ export async function runWriteGate(
518
528
  }
519
529
 
520
530
  if (collapseMatch) {
521
- await record("dedup_collapse", {
531
+ await rec("dedup_collapse", {
522
532
  gate: 3,
523
533
  survivors: scopeMems.length,
524
534
  match: collapseMatch.ts,
@@ -528,7 +538,7 @@ export async function runWriteGate(
528
538
  chain,
529
539
  });
530
540
  } else if (overlapMatch) {
531
- await record("dedup_overlap", {
541
+ await rec("dedup_overlap", {
532
542
  gate: 3,
533
543
  survivors: scopeMems.length,
534
544
  candidate: overlapMatch.ts,
@@ -537,7 +547,7 @@ export async function runWriteGate(
537
547
  chain,
538
548
  });
539
549
  } else {
540
- await record("dedup_clean", {
550
+ await rec("dedup_clean", {
541
551
  gate: 3,
542
552
  survivors: scopeMems.length,
543
553
  candidate: 0,
@@ -603,13 +613,13 @@ export async function runWriteGate(
603
613
  }
604
614
 
605
615
  if (blockReason) {
606
- await recordWriteBlocked(4, blockReason, blockFlags, chain);
616
+ await recBlocked(4, blockReason, blockFlags, chain);
607
617
  if (blockReason === "superseded_overlap" && overlapMatch) {
608
618
  const newest = scopeMems[scopeMems.length - 1] ?? overlapMatch;
609
619
  // Advisory, not actionable: the incoming candidate was never persisted,
610
620
  // so no memory_merge_review loser exists for it. The line is rivalry
611
621
  // telemetry and a pointer to the stored rival.
612
- await record("merge_proposal", {
622
+ await rec("merge_proposal", {
613
623
  candidate: overlapMatch.ts,
614
624
  incoming: chain,
615
625
  canonical: newest.ts,
@@ -633,14 +643,14 @@ export async function runWriteGate(
633
643
  g1.refs === 0 && !ctx.hasGateCheck &&
634
644
  ctx.hasEngagement === true && candidate.scope !== "";
635
645
  if (groundedByEngagement) {
636
- await record("gate_injected", { gate: 4, chain });
646
+ await rec("gate_injected", { gate: 4, chain });
637
647
  }
638
648
 
639
649
  const snapshot = await snapshotFiles([join(memoryRoot(), `${new Date().toISOString().split("T")[0]}.logfmt`)]);
640
650
  // The write carries the CALLER's session, not whatever current says after
641
651
  // the gate's own awaits - capture's stamp must follow the captured session.
642
652
  const ts = await appendMemory({ ...candidate, sessionID: ctx.sessionID });
643
- await record("write_promoted", {
653
+ await rec("write_promoted", {
644
654
  gate: 4,
645
655
  op: "write",
646
656
  mem: ts,
package/src/index.ts CHANGED
@@ -225,6 +225,48 @@ export function resetCaptureCooldowns(): void {
225
225
  lastCaptureRun.clear();
226
226
  }
227
227
 
228
+ // ---- capture trigger vocabulary (#136) -------------------------------------
229
+ // opencode 2.x has no `session.idle`. The subscription used to wait for exactly
230
+ // that string, so auto-capture was dead on every 2.x host with no warning
231
+ // anywhere: live proof is in the issue (45 s of the running service's own SSE
232
+ // stream over a complete turn, and zero `capture_lag` lines in the whole
233
+ // evidence history). What the host really publishes when a turn ends is the
234
+ // `session.execution.*` family; `session.status` is the ephemeral variant whose
235
+ // `status.type` says "idle".
236
+ //
237
+ // These lists are the single source of truth for what the capture subscription
238
+ // reacts to, and test/event-fidelity.test.ts asserts every name here appears in
239
+ // the installed @opencode/schema event manifest. Invented event names are the
240
+ // bug class that caused #78 and then survived a review, a merge and 480 green
241
+ // tests, because the tests fabricated the same invented payload.
242
+ // Recorded live, not guessed: `succeeded` and `interrupted` were both observed
243
+ // on a running desktop service (test/fixtures/host-events.jsonl).
244
+ export const TURN_END_EVENTS = ["session.execution.succeeded", "session.execution.interrupted"] as const;
245
+
246
+ /** Every event type the capture subscription reacts to (fidelity-tested). */
247
+ export const CAPTURE_EVENT_TYPES: readonly string[] = [...TURN_END_EVENTS];
248
+
249
+ // Deliberately NOT triggers, because a live host was never observed sending
250
+ // them, and dead branches are what caused #136 in the first place:
251
+ // • `session.idle` - declared, never emitted (the original bug).
252
+ // • `session.status` - declared, never emitted; would also need
253
+ // `data.status.type === "idle"` filtering.
254
+ // • `session.execution.failed` - declared, not reproduced here. A failed turn
255
+ // simply does not capture, which costs nothing; adding it
256
+ // later is allowed the moment a recording shows it.
257
+ // test/event-fidelity.test.ts enforces that nothing enters TURN_END_EVENTS
258
+ // without appearing in the recording.
259
+
260
+ /**
261
+ * True when a host event means "this session just went quiet". The internal
262
+ * trigger name stays "idle" (cooldown keys, `auto_capture_*` evidence lines and
263
+ * the historical idle-vs-compaction bench all use it).
264
+ */
265
+ export function captureTriggerFor(event: unknown): boolean {
266
+ const type = (event as { type?: unknown } | null)?.type;
267
+ return typeof type === "string" && (TURN_END_EVENTS as readonly string[]).includes(type);
268
+ }
269
+
228
270
  // The real setup implementation, written against the loose local PluginCtx
229
271
  // (the only members of the V2 context this plugin actually touches).
230
272
  const impl = {
@@ -1238,8 +1280,10 @@ const impl = {
1238
1280
  try {
1239
1281
  for await (const raw of eventApi.subscribe({ signal: controller.signal })) {
1240
1282
  const event = raw as Record<string, any>;
1241
- if (event?.type !== "session.idle") continue;
1242
- const sid = event.sessionID ?? event.properties?.sessionID ?? event.data?.sessionID;
1283
+ if (!captureTriggerFor(event)) continue;
1284
+ // 2.x carries the session inside `data`; the other two shapes are
1285
+ // kept because the measured listener sees both across host modes.
1286
+ const sid = event.data?.sessionID ?? event.sessionID ?? event.properties?.sessionID;
1243
1287
  if (typeof sid !== "string") continue;
1244
1288
  setCurrent({ sessionID: sid });
1245
1289
  const now = Date.now();
@@ -1279,6 +1323,52 @@ const impl = {
1279
1323
  "[opencode-self-improvement] captureOnCompact is on but autoCapture is off; compaction capture stays disabled (autoCapture is the master switch).",
1280
1324
  );
1281
1325
  }
1326
+ // ---- startup heartbeat (#138) ------------------------------------------
1327
+ // Every other evidence line is written BY something that already worked,
1328
+ // so "capture is off", "capture is misconfigured" and "capture is armed and
1329
+ // inert" were indistinguishable from anything a user could read - which is
1330
+ // exactly how a pipeline that had never run in ten days survived a review
1331
+ // and a merge. This one line makes the ABSENCE of capture activity
1332
+ // interpretable: `capture=` names why, `subscribed=` lists the event types
1333
+ // the subscription actually reacts to. Guarded like every other hook: a
1334
+ // broken store must not turn plugin load into a throw.
1335
+ await guarded("plugin_load heartbeat", async () => {
1336
+ let pluginVersion = "unknown";
1337
+ try {
1338
+ const pkg = await Bun.file(new URL("../package.json", import.meta.url)).json();
1339
+ if (typeof pkg?.version === "string") pluginVersion = pkg.version;
1340
+ } catch {
1341
+ // a heartbeat with an unknown version still beats no heartbeat
1342
+ }
1343
+ const wantCapture = ctx.options?.autoCapture === true;
1344
+ const modelOk = !!parseModelRef(
1345
+ typeof ctx.options?.captureModel === "string" ? ctx.options.captureModel : "",
1346
+ );
1347
+ const capabilities = ["event.subscribe", "generate.text", "session.context"].filter((name) => {
1348
+ const [domain, method] = name.split(".");
1349
+ return typeof (ctx as unknown as Record<string, any>)?.[domain]?.[method] === "function";
1350
+ });
1351
+ const captureState = !wantCapture
1352
+ ? "off"
1353
+ : !modelOk
1354
+ ? "invalid_model"
1355
+ : capabilities.length < 3
1356
+ ? "no_capabilities"
1357
+ : "on";
1358
+ await record(
1359
+ "plugin_load",
1360
+ {
1361
+ version: pluginVersion,
1362
+ capture: captureState,
1363
+ capture_on_compact: ctx.options?.captureOnCompact !== false,
1364
+ capabilities: `[${capabilities.join(",")}]`,
1365
+ subscribed: `[${CAPTURE_EVENT_TYPES.join(",")}]`,
1366
+ inject_budget: injectBudget(),
1367
+ store_rows: (await loadAll()).length,
1368
+ },
1369
+ false,
1370
+ );
1371
+ });
1282
1372
  // Single cleanup returned by setup: tears down the measured listener and,
1283
1373
  // when enabled, the capture subscription. Future teardowns merge in here.
1284
1374
  return () => {