opencode-self-improvement 0.13.2 → 0.14.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 (2) hide show
  1. package/package.json +1 -1
  2. package/src/index.ts +113 -35
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.13.2",
3
+ "version": "0.14.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/index.ts CHANGED
@@ -186,6 +186,12 @@ function resultMeta(result: unknown): Record<string, unknown> {
186
186
 
187
187
  const PLUGIN_ID = "opencode-self-improvement";
188
188
 
189
+ // Tag on store rows captured by the COMPACTION trigger (issue #41). Rows keep
190
+ // the shared "auto-capture" provenance tag (src/inject.ts renders it) and add
191
+ // this one so decay/status can tell which trigger wrote them — the same
192
+ // distinction the auto_capture_compaction_* evidence lines carry.
193
+ const CAPTURE_COMPACT_TAG = "auto_capture_compaction";
194
+
189
195
  // The setup-time Bun-floor warning fires once per process (setup can run for
190
196
  // more than one location).
191
197
  let bunFloorChecked = false;
@@ -844,6 +850,12 @@ const impl = {
844
850
  };
845
851
 
846
852
  // ---- hooks (all fail-closed) -------------------------------------------
853
+ // Seam set by the auto-capture wiring below ONLY when the compaction
854
+ // trigger is live (autoCapture on, captureOnCompact not false, valid
855
+ // captureModel). The compaction hook calls it fire-and-forget; undefined
856
+ // means "off". Declared here because the hook registers before capture.
857
+ let onCompactCapture: ((sid: string, messages: unknown) => void) | undefined;
858
+
847
859
  // Bookkeeping: track the active session/tool/call before a tool runs.
848
860
  await ctx.tool?.hook("execute.before", (event: any) =>
849
861
  guarded("tool.execute.before", async () => {
@@ -936,7 +948,9 @@ const impl = {
936
948
  // compaction: the durable-memory anchor is pushed onto the hook's system
937
949
  // parts (visible to the summarizer model, which runs AFTER hooks) so the
938
950
  // summary preserves the facts. Never sets event.result — that would skip
939
- // the summarizer call entirely.
951
+ // the summarizer call entirely. Also fires the context-death auto-capture
952
+ // (issue #41, opt-in; see the capture section): the transcript is mined
953
+ // while it still exists, BEFORE the summarizer replaces it.
940
954
  await ctx.session?.hook("compaction", (event: any) =>
941
955
  guarded("session.compaction (onCompacting)", async () => {
942
956
  setCurrent({ sessionID: event?.sessionID });
@@ -947,6 +961,13 @@ const impl = {
947
961
  }
948
962
  const anchor = await compactionAnchor();
949
963
  if (anchor) event?.system?.push?.({ type: "text", text: anchor });
964
+ // Fire-and-forget: a capture model call must never delay the compaction
965
+ // the user is waiting for, and failures stay inside the guarded path.
966
+ // The payload's own messages ride along so the mining sees the
967
+ // pre-compaction transcript even if the store moves under it.
968
+ if (onCompactCapture && typeof event?.sessionID === "string") {
969
+ onCompactCapture(event.sessionID, event.messages);
970
+ }
950
971
  }),
951
972
  );
952
973
 
@@ -1020,22 +1041,27 @@ const impl = {
1020
1041
  })();
1021
1042
  }
1022
1043
 
1023
- // ---- opt-in auto-capture on session idle --------------------------------
1044
+ // ---- opt-in auto-capture (idle + compaction triggers) ------------------
1024
1045
  // Default OFF: capture never reads sessions and never calls a model. (The
1025
1046
  // measured-cache listener above does subscribe to the event stream by
1026
1047
  // default, but it is zero-model: pure bookkeeping of message usage.) When
1027
1048
  // enabled (options.autoCapture === true AND a valid captureModel), each
1028
- // session.idle event runs ONE cheap ctx.generate.text call whose reply is
1029
- // parsed into candidates that go through the SAME runWriteGate as
1049
+ // session.idle event — and, unless captureOnCompact === false, each
1050
+ // compaction hook call too — runs ONE cheap ctx.generate.text call whose
1051
+ // reply is parsed into candidates that go through the SAME runWriteGate as
1030
1052
  // model-authored writes — capture can never bypass the moat, and it only
1031
- // ever writes through the gate. A per-session cooldown bounds the cost.
1032
- // Every failure inside the loop is swallowed: capture must never be able
1033
- // to break a session.
1053
+ // ever writes through the gate. A per-session, per-trigger cooldown bounds
1054
+ // the cost. Compaction-triggered rows carry the CAPTURE_COMPACT_TAG tag and
1055
+ // auto_capture_compaction_* evidence lines, idle rows keep auto_capture_*,
1056
+ // so decay/status — and bench/capture-trigger-compare.ts — can measure
1057
+ // which trigger earns its tokens. Every failure is swallowed: capture must
1058
+ // never be able to break a session.
1034
1059
  let captureCleanup: Cleanup | undefined;
1035
1060
  if (ctx.options?.autoCapture === true) {
1036
1061
  const captureModel =
1037
1062
  typeof ctx.options.captureModel === "string" ? ctx.options.captureModel : "";
1038
1063
  const captureMax = Number(ctx.options.captureMax) || 3;
1064
+ const captureOnCompact = ctx.options?.captureOnCompact !== false;
1039
1065
  const modelRef = parseModelRef(captureModel);
1040
1066
  if (!modelRef) {
1041
1067
  // Invalid/missing model: skip registering the whole subscription
@@ -1058,6 +1084,63 @@ const impl = {
1058
1084
  // setup guard proves it exists, but property narrowing does not survive
1059
1085
  // into the closure, and undefined degrades safely (empty transcript).
1060
1086
  const contextFn = (input: { sessionID: string }) => ctx.session?.context?.(input);
1087
+
1088
+ // ONE capture pass, shared by both triggers. `seeded` is a transcript
1089
+ // already in hand — the compaction hook carries the PRE-compaction
1090
+ // messages, which is the whole point (Compaction Cliff: one round
1091
+ // retains 53% of exact-wording rules); when it is absent (older host
1092
+ // shapes) or too thin, the session context is read instead, the same
1093
+ // source the idle trigger mines.
1094
+ async function captureSession(
1095
+ sid: string,
1096
+ seeded: string,
1097
+ trigger: "idle" | "compaction",
1098
+ seededMsgs?: unknown,
1099
+ ): Promise<void> {
1100
+ // Bind the capturing session so captures stamp (and gate against)
1101
+ // that session's repo, not whatever tool call ran last.
1102
+ setCurrent({ sessionID: sid });
1103
+ let transcript = seeded;
1104
+ let msgs = seededMsgs;
1105
+ if (transcript.length < 200) {
1106
+ msgs = await contextFn({ sessionID: sid });
1107
+ transcript = flattenTranscript(msgs);
1108
+ }
1109
+ if (transcript.length < 200) return; // too thin to mine reliably
1110
+ // #44: how stale is a capture? Distance from the newest message of
1111
+ // the mined transcript to this instant - measured on whatever the
1112
+ // trigger actually mined (the hook payload for compaction, the
1113
+ // session context for idle), so both triggers' lag is comparable.
1114
+ const lagMs = lagSince(msgs);
1115
+ const out = await generateApi.text({
1116
+ model: modelRef,
1117
+ prompt: buildCapturePrompt(transcript.slice(-8000), captureMax),
1118
+ });
1119
+ const text = typeof out === "string" ? out : out?.text ?? "";
1120
+ const candidates = parseCandidates(text, captureMax);
1121
+ for (const c of candidates) {
1122
+ const outcome = await runWriteGate(
1123
+ {
1124
+ ...c,
1125
+ tags:
1126
+ trigger === "compaction"
1127
+ ? ["auto-capture", CAPTURE_COMPACT_TAG]
1128
+ : ["auto-capture"],
1129
+ },
1130
+ gateContext(),
1131
+ );
1132
+ await record(
1133
+ trigger === "compaction"
1134
+ ? `auto_capture_compaction_${outcome.action}`
1135
+ : `auto_capture_${outcome.action}`,
1136
+ // A blocked credential-shaped scope must not reach the evidence log either.
1137
+ { session: sid, trigger, type: c.type, scope: redactSecrets(c.scope), reason: outcome.reason ?? "" },
1138
+ false,
1139
+ );
1140
+ }
1141
+ await recordCaptureLag(sid, lagMs, candidates.length ? "candidates" : "empty");
1142
+ }
1143
+
1061
1144
  void (async () => {
1062
1145
  try {
1063
1146
  for await (const raw of eventApi.subscribe({ signal: controller.signal })) {
@@ -1065,39 +1148,12 @@ const impl = {
1065
1148
  if (event?.type !== "session.idle") continue;
1066
1149
  const sid = event.sessionID ?? event.properties?.sessionID ?? event.data?.sessionID;
1067
1150
  if (typeof sid !== "string") continue;
1068
- // Bind the idle session so captures stamp (and gate against)
1069
- // that session's repo, not whatever tool call ran last.
1070
1151
  setCurrent({ sessionID: sid });
1071
1152
  const now = Date.now();
1072
1153
  if (now - (lastRun.get(sid) ?? 0) < 5 * 60_000) continue; // 5-min cooldown
1073
1154
  lastRun.set(sid, now);
1074
1155
  try {
1075
- const msgs = await contextFn({ sessionID: sid });
1076
- const transcript = flattenTranscript(msgs);
1077
- if (transcript.length < 200) continue; // too thin to mine reliably
1078
- // #44: how stale is a capture? Distance from the last message of
1079
- // the transcript to this instant. Sessions idle for an hour
1080
- // produce an hour-old capture, and the surfaces now say so.
1081
- const lagMs = lagSince(msgs);
1082
- const out = await generateApi.text({
1083
- model: modelRef,
1084
- prompt: buildCapturePrompt(transcript.slice(-8000), captureMax),
1085
- });
1086
- const text = typeof out === "string" ? out : out?.text ?? "";
1087
- const candidates = parseCandidates(text, captureMax);
1088
- for (const c of candidates) {
1089
- const outcome = await runWriteGate(
1090
- { ...c, tags: ["auto-capture"] },
1091
- gateContext(),
1092
- );
1093
- await record(
1094
- `auto_capture_${outcome.action}`,
1095
- // A blocked credential-shaped scope must not reach the evidence log either.
1096
- { session: sid, type: c.type, scope: redactSecrets(c.scope), reason: outcome.reason ?? "" },
1097
- false,
1098
- );
1099
- }
1100
- await recordCaptureLag(sid, lagMs, candidates.length ? "candidates" : "empty");
1156
+ await captureSession(sid, "", "idle");
1101
1157
  } catch {
1102
1158
  // fail-closed: a broken capture attempt is invisible to the session
1103
1159
  }
@@ -1107,7 +1163,29 @@ const impl = {
1107
1163
  }
1108
1164
  })();
1109
1165
  captureCleanup = () => controller.abort();
1166
+
1167
+ // The compaction trigger needs no extra subscription: the session
1168
+ // compaction hook (registered above) calls through this seam. Separate
1169
+ // cooldown map from idle, so measuring a trigger is not confounded by
1170
+ // the other trigger having fired moments ago.
1171
+ if (captureOnCompact) {
1172
+ const lastCompactRun = new Map<string, number>();
1173
+ onCompactCapture = (sid, messages) => {
1174
+ if (controller.signal.aborted) return;
1175
+ const now = Date.now();
1176
+ if (now - (lastCompactRun.get(sid) ?? 0) < 5 * 60_000) return; // 5-min cooldown
1177
+ lastCompactRun.set(sid, now);
1178
+ void guarded("session.compaction (auto-capture)", () =>
1179
+ captureSession(sid, flattenTranscript(messages), "compaction", messages),
1180
+ );
1181
+ };
1182
+ }
1110
1183
  }
1184
+ } else if (ctx.options?.captureOnCompact === true) {
1185
+ // autoCapture is the master switch (zero-token default preserved).
1186
+ console.warn(
1187
+ "[opencode-self-improvement] captureOnCompact is on but autoCapture is off; compaction capture stays disabled (autoCapture is the master switch).",
1188
+ );
1111
1189
  }
1112
1190
  // Single cleanup returned by setup: tears down the measured listener and,
1113
1191
  // when enabled, the capture subscription. Future teardowns merge in here.