opencode-self-improvement 0.15.18 → 0.15.19

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 (93) hide show
  1. package/README.md +4 -0
  2. package/package.json +4 -2
  3. package/src/capture/candidates.ts +17 -6
  4. package/src/capture/lag.ts +6 -2
  5. package/src/capture/prompt.ts +1 -1
  6. package/src/capture/runtime.ts +85 -21
  7. package/src/capture/session-model.ts +2 -1
  8. package/src/capture/transcript.ts +10 -4
  9. package/src/capture/triggers.ts +48 -14
  10. package/src/command/ensure.ts +6 -1
  11. package/src/consolidate/propose.ts +47 -17
  12. package/src/consolidate/render.ts +3 -1
  13. package/src/core/cmp-ts.ts +2 -2
  14. package/src/core/config/budgets.ts +0 -1
  15. package/src/core/config/paths.ts +2 -3
  16. package/src/core/hooks.ts +8 -3
  17. package/src/core/host.ts +8 -3
  18. package/src/core/logfmt/format.ts +20 -5
  19. package/src/core/logfmt/publish.ts +21 -4
  20. package/src/core/lru.ts +20 -20
  21. package/src/core/permissions.ts +21 -5
  22. package/src/core/runtime.ts +7 -3
  23. package/src/core/state.ts +12 -2
  24. package/src/core/time.ts +0 -1
  25. package/src/core/tokenize.ts +16 -5
  26. package/src/core/types.ts +8 -1
  27. package/src/events.ts +74 -18
  28. package/src/evidence/record.ts +29 -9
  29. package/src/gate/gate.ts +208 -64
  30. package/src/gate/resolver.ts +105 -20
  31. package/src/hits/ledger.ts +35 -10
  32. package/src/identity/host-events.ts +35 -11
  33. package/src/identity/repokey.ts +27 -9
  34. package/src/identity/session-context.ts +39 -8
  35. package/src/index.ts +108 -42
  36. package/src/init/detect.ts +62 -12
  37. package/src/init/run.ts +50 -11
  38. package/src/inject/anchor.ts +11 -5
  39. package/src/inject/attribution.ts +29 -6
  40. package/src/inject/budget.ts +9 -2
  41. package/src/inject/digest.ts +16 -8
  42. package/src/inject/epochs.ts +43 -15
  43. package/src/inject/pull.ts +11 -5
  44. package/src/inject/version.ts +10 -5
  45. package/src/portable/decay.ts +20 -9
  46. package/src/portable/export.ts +30 -10
  47. package/src/portable/import.ts +43 -12
  48. package/src/recall/relevant.ts +11 -5
  49. package/src/recall/score.ts +5 -3
  50. package/src/status/format.ts +8 -2
  51. package/src/status/metrics.ts +22 -6
  52. package/src/status/payload.ts +7 -2
  53. package/src/status/report.ts +63 -18
  54. package/src/status/write.ts +21 -7
  55. package/src/store/blocklist.ts +16 -4
  56. package/src/store/containment.ts +27 -8
  57. package/src/store/files/append.ts +57 -37
  58. package/src/store/files/deletions.ts +5 -2
  59. package/src/store/files/load.ts +37 -11
  60. package/src/store/files/prune.ts +18 -5
  61. package/src/store/files/snapshots.ts +6 -2
  62. package/src/store/files/supersede.ts +32 -12
  63. package/src/store/files/target.ts +4 -1
  64. package/src/store/lock.ts +10 -2
  65. package/src/store/model/visibility.ts +26 -6
  66. package/src/store/prune.ts +1 -1
  67. package/src/store/quarantine/quarantine.ts +36 -9
  68. package/src/store/quarantine/release.ts +9 -3
  69. package/src/store/secrets.ts +4 -2
  70. package/src/store/tombstones/rejection.ts +21 -5
  71. package/src/store/tombstones/tombstone.ts +48 -11
  72. package/src/store/undo.ts +43 -18
  73. package/src/tools/consolidate.ts +18 -8
  74. package/src/tools/decay.ts +37 -9
  75. package/src/tools/deps.ts +10 -2
  76. package/src/tools/evidence.ts +7 -4
  77. package/src/tools/export.ts +10 -4
  78. package/src/tools/forget.ts +15 -5
  79. package/src/tools/import.ts +16 -5
  80. package/src/tools/init.ts +13 -4
  81. package/src/tools/list.ts +12 -6
  82. package/src/tools/merge-review.ts +52 -20
  83. package/src/tools/recall.ts +17 -9
  84. package/src/tools/registry.ts +4 -1
  85. package/src/tools/remember.ts +21 -7
  86. package/src/tools/schema.ts +55 -18
  87. package/src/tools/status-tool.ts +29 -11
  88. package/src/tools/undo.ts +23 -8
  89. package/src/tools/update.ts +116 -40
  90. package/src/tui/panel.tsx +119 -30
  91. package/src/viewer/mutate.ts +57 -20
  92. package/src/viewer/rejections.ts +1 -1
  93. package/src/viewer/server.ts +88 -28
package/README.md CHANGED
@@ -322,8 +322,12 @@ Nothing merges without the full gate; CI runs it as required checks (`lint`, `te
322
322
  ```sh
323
323
  bun run gate # typecheck + lint + unit tests + terminal smoke & BDD
324
324
  bun run gate:hooks # once per clone: run the gate on `git push`
325
+ bun run format # apply the shared two-space TypeScript/TSX style
326
+ bun run format:check # check formatting without changing files
325
327
  ```
326
328
 
329
+ `bun run lint` checks lint rules and TypeScript/TSX formatting; CI calls the same command. Lint warnings remain advisory, while formatting differences fail the check. Markdown commands, prose, JSON data and historical benchmark records are outside the formatter's scope.
330
+
327
331
  Use Bun **1.4.4** for development checks, matching CI. `bun run test` and `bun run test:e2e` run files across at most four worker processes with Bun's file isolation; cases inside each file stay sequential because fixtures share environment variables and module state. The local gate uses those same scripts. To diagnose order-dependent failures in the original shared-process mode, run `bun test ./test/` or `bun test ./e2e/ --timeout 240000` directly.
328
332
 
329
333
  **Feature order is BDD-first.** A new feature starts by adding or fixing a scenario in `e2e/` that describes the behavior as a user would observe it — before implementation code and before unit tests. Then the unit tests for the pieces, then the code until everything is green. If no scenario turns red first, the feature has no observable contract.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.15.18",
3
+ "version": "0.15.19",
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": {
@@ -70,7 +70,9 @@
70
70
  "bench:write": "bun bench/write-latency.ts",
71
71
  "sweep:test": "bun scripts/test-sweep.ts",
72
72
  "memory-view": "bun run src/viewer/server.ts",
73
- "lint": "biome lint"
73
+ "format": "biome format --write",
74
+ "format:check": "biome format",
75
+ "lint": "biome lint && bun run format:check"
74
76
  },
75
77
  "dependencies": {
76
78
  "zod": "4.6.7"
@@ -7,7 +7,11 @@
7
7
  // never a throw.
8
8
  import { TYPES } from "../core/types.ts";
9
9
  import { flattenMemoryText } from "../store/sanitize.ts";
10
- import { CAPTURE_KEYWORD_CAP, CAPTURE_KEYWORD_CHARS, type CaptureCandidate } from "./prompt.ts";
10
+ import {
11
+ CAPTURE_KEYWORD_CAP,
12
+ CAPTURE_KEYWORD_CHARS,
13
+ type CaptureCandidate,
14
+ } from "./prompt.ts";
11
15
 
12
16
  function cleanKeywords(value: unknown): string[] | undefined {
13
17
  if (!Array.isArray(value)) return undefined;
@@ -15,7 +19,8 @@ function cleanKeywords(value: unknown): string[] | undefined {
15
19
  for (const item of value) {
16
20
  if (typeof item !== "string") continue;
17
21
  const k = item.trim().toLowerCase();
18
- if (!k || k.length > CAPTURE_KEYWORD_CHARS || flattenMemoryText(k) !== k) continue;
22
+ if (!k || k.length > CAPTURE_KEYWORD_CHARS || flattenMemoryText(k) !== k)
23
+ continue;
19
24
  if (!out.includes(k)) out.push(k);
20
25
  if (out.length === CAPTURE_KEYWORD_CAP) break;
21
26
  }
@@ -79,14 +84,18 @@ export function parseCandidates(raw: string, max: number): CaptureCandidate[] {
79
84
  if (
80
85
  flattenMemoryText(rawType) !== rawType ||
81
86
  flattenMemoryText(rawScope) !== rawScope
82
- ) continue;
87
+ )
88
+ continue;
83
89
  if (!VALID_TYPES.has(type)) continue;
84
90
  if (content.length < 20 || content.length > 600) continue;
85
- const status = o.status === "open" || o.status === "settled" ? o.status : undefined;
91
+ const status =
92
+ o.status === "open" || o.status === "settled" ? o.status : undefined;
86
93
  // A bad kw list costs the row its keywords, never the row itself.
87
94
  const kw = cleanKeywords(o.kw);
88
95
  out.push({
89
- ...(status ? { type, scope, content, status } : { type, scope, content }),
96
+ ...(status
97
+ ? { type, scope, content, status }
98
+ : { type, scope, content }),
90
99
  ...(kw ? { kw } : {}),
91
100
  });
92
101
  }
@@ -99,7 +108,9 @@ export function parseCandidates(raw: string, max: number): CaptureCandidate[] {
99
108
  // "provider/id" -> { providerID, id }, splitting on the FIRST "/". Returns
100
109
  // null when the string has no slash or either half is empty — the caller then
101
110
  // skips capture entirely rather than guessing a model.
102
- export function parseModelRef(ref: unknown): { providerID: string; id: string } | null {
111
+ export function parseModelRef(
112
+ ref: unknown,
113
+ ): { providerID: string; id: string } | null {
103
114
  if (typeof ref !== "string") return null;
104
115
  const i = ref.indexOf("/");
105
116
  if (i <= 0) return null;
@@ -1,6 +1,5 @@
1
1
  // lag — split from src/capture.ts (#168 domain restructure). Declaration bodies are unchanged.
2
2
 
3
-
4
3
  /**
5
4
  * Age of the newest message in a session context, in ms, or null when no
6
5
  * message carries a timestamp. Capture uses this to say how stale a transcript
@@ -11,7 +10,12 @@ export function lagSince(messages: unknown, now = Date.now()): number | null {
11
10
  for (const raw of Array.isArray(messages) ? messages : []) {
12
11
  const m = raw as Record<string, any>;
13
12
  const at = m?.time?.updated ?? m?.createdAt ?? m?.created ?? m?.timestamp;
14
- const ms = typeof at === "number" ? at : typeof at === "string" ? Date.parse(at) : Number.NaN;
13
+ const ms =
14
+ typeof at === "number"
15
+ ? at
16
+ : typeof at === "string"
17
+ ? Date.parse(at)
18
+ : Number.NaN;
15
19
  if (Number.isFinite(ms) && ms > newest) newest = ms;
16
20
  }
17
21
  return newest ? now - newest : null;
@@ -39,7 +39,7 @@ export function buildCapturePrompt(transcript: string, max = 3): string {
39
39
  "- scope: short area name (e.g. auth, api, build).",
40
40
  '- status: "open" for a live planning thread; otherwise "settled".',
41
41
  "- content: one self-contained fact, 20-600 characters, useful in a NEW session.",
42
- '- kw: 3-5 search keywords for how a DIFFERENT session would ask for this — synonyms and alternate names, other verb forms, the literal command or file name. They are indexed for retrieval and never shown to a model. Omit (or []) when the content already uses those words.',
42
+ "- kw: 3-5 search keywords for how a DIFFERENT session would ask for this — synonyms and alternate names, other verb forms, the literal command or file name. They are indexed for retrieval and never shown to a model. Omit (or []) when the content already uses those words.",
43
43
  "- Keep: decisions made, working commands, user preferences, blockers hit, durable context, conventions.",
44
44
  "- Skip: anything derivable from the code or git history, small talk, and details that only mattered inside this conversation.",
45
45
  "- If nothing is worth remembering, output [ ].",
@@ -16,12 +16,18 @@ import { flattenTranscript } from "./transcript.ts";
16
16
 
17
17
  interface CaptureHost {
18
18
  options?: Record<string, unknown>;
19
- event?: { subscribe: (o?: { signal?: AbortSignal }) => AsyncIterable<unknown> };
19
+ event?: {
20
+ subscribe: (o?: { signal?: AbortSignal }) => AsyncIterable<unknown>;
21
+ };
20
22
  generate?: { text: (input: unknown) => Promise<{ text?: string } | string> };
21
23
  session?: { context?: (input: { sessionID: string }) => Promise<unknown> };
22
24
  // Host default model (#139): the last-resort source for an omitted
23
25
  // captureModel. Optional-call everywhere: older/fake hosts expose none.
24
- model?: { default?: { get?: () => { providerID: string; modelID: string } | undefined } };
26
+ model?: {
27
+ default?: {
28
+ get?: () => { providerID: string; modelID: string } | undefined;
29
+ };
30
+ };
25
31
  }
26
32
 
27
33
  interface CaptureDependencies {
@@ -47,13 +53,18 @@ const lastCaptureRun = new Map<string, number>();
47
53
  const CAPTURE_COOLDOWN_MS = 5 * 60_000;
48
54
 
49
55
  /** True if this trigger may fire for this session now; records the fire. */
50
- function captureCooldownPasses(trigger: "idle" | "compaction", sid: string, now: number): boolean {
56
+ function captureCooldownPasses(
57
+ trigger: "idle" | "compaction",
58
+ sid: string,
59
+ now: number,
60
+ ): boolean {
51
61
  const key = `${trigger}:${sid}`;
52
62
  if (now - (lastCaptureRun.get(key) ?? 0) < CAPTURE_COOLDOWN_MS) return false;
53
63
  // Sessions churn and a long-lived server must not grow one entry per
54
64
  // session forever; oldest-inserted go first (the ledger throttle's rule).
55
65
  if (lastCaptureRun.size > 2000) {
56
- for (const k of [...lastCaptureRun.keys()].slice(0, 1000)) lastCaptureRun.delete(k);
66
+ for (const k of [...lastCaptureRun.keys()].slice(0, 1000))
67
+ lastCaptureRun.delete(k);
57
68
  }
58
69
  lastCaptureRun.set(key, now);
59
70
  return true;
@@ -72,7 +83,10 @@ export function resetCaptureCooldowns(): void {
72
83
  // alone is insufficient evidence that the host emits it (#78, #136).
73
84
  // Identity triggers have a separate observed check in that test, combining
74
85
  // this recording with the 2.2.2 move extract in host-session-move.json (#176).
75
- export const TURN_END_EVENTS = ["session.execution.succeeded", "session.execution.interrupted"] as const;
86
+ export const TURN_END_EVENTS = [
87
+ "session.execution.succeeded",
88
+ "session.execution.interrupted",
89
+ ] as const;
76
90
 
77
91
  /** Every event type the capture subscription reacts to (fidelity-tested). */
78
92
  export const CAPTURE_EVENT_TYPES: readonly string[] = [...TURN_END_EVENTS];
@@ -88,7 +102,10 @@ export const CAPTURE_EVENT_TYPES: readonly string[] = [...TURN_END_EVENTS];
88
102
  */
89
103
  export function captureTriggerFor(event: unknown): boolean {
90
104
  const type = (event as { type?: unknown } | null)?.type;
91
- return typeof type === "string" && (TURN_END_EVENTS as readonly string[]).includes(type);
105
+ return (
106
+ typeof type === "string" &&
107
+ (TURN_END_EVENTS as readonly string[]).includes(type)
108
+ );
92
109
  }
93
110
 
94
111
  export function configureAutoCapture(
@@ -117,7 +134,11 @@ export function configureAutoCapture(
117
134
  console.warn(
118
135
  `[opencode-self-improvement] autoCapture is on but captureModel ${JSON.stringify(captureModelOpt)} is invalid (expected "provider/id"); auto-capture disabled.`,
119
136
  );
120
- } else if (!ctx.event?.subscribe || !ctx.generate?.text || !ctx.session?.context) {
137
+ } else if (
138
+ !ctx.event?.subscribe ||
139
+ !ctx.generate?.text ||
140
+ !ctx.session?.context
141
+ ) {
121
142
  console.warn(
122
143
  "[opencode-self-improvement] autoCapture is on but this OpenCode context lacks event.subscribe/generate.text/session.context; auto-capture disabled.",
123
144
  );
@@ -130,7 +151,8 @@ export function configureAutoCapture(
130
151
  // and the fail-closed catch below would hide it. Optional call: the
131
152
  // setup guard proves it exists, but property narrowing does not survive
132
153
  // into the closure, and undefined degrades safely (empty transcript).
133
- const contextFn = (input: { sessionID: string }) => ctx.session?.context?.(input);
154
+ const contextFn = (input: { sessionID: string }) =>
155
+ ctx.session?.context?.(input);
134
156
 
135
157
  // #139 model resolution: explicit option (captured above) wins; else the
136
158
  // ref this session's context hook last carried; else the host default.
@@ -140,8 +162,11 @@ export function configureAutoCapture(
140
162
  const hostDefault = (): SessionModelRef | null => {
141
163
  const d = ctx.model?.default?.get?.();
142
164
  if (
143
- d && typeof d.providerID === "string" && d.providerID &&
144
- typeof d.modelID === "string" && d.modelID
165
+ d &&
166
+ typeof d.providerID === "string" &&
167
+ d.providerID &&
168
+ typeof d.modelID === "string" &&
169
+ d.modelID
145
170
  )
146
171
  return { providerID: d.providerID, id: d.modelID };
147
172
  return null;
@@ -183,7 +208,13 @@ export function configureAutoCapture(
183
208
  // store refuses. Skip BEFORE the model call — no tokens spent on a
184
209
  // capture that cannot be stored — and leave the reason in evidence.
185
210
  if (!writeTarget(sid).ok) {
186
- await record("auto_capture_refused", { session: sid, trigger, ...(modelTag ? { model: modelTag } : {}) }, true, sid, captureGate.evidenceContext);
211
+ await record(
212
+ "auto_capture_refused",
213
+ { session: sid, trigger, ...(modelTag ? { model: modelTag } : {}) },
214
+ true,
215
+ sid,
216
+ captureGate.evidenceContext,
217
+ );
187
218
  return;
188
219
  }
189
220
  if (!model) {
@@ -194,7 +225,13 @@ export function configureAutoCapture(
194
225
  "[opencode-self-improvement] autoCapture is on but captureModel is omitted and neither session.context nor the host default names a model; capture skipped (warned once).",
195
226
  );
196
227
  }
197
- await record("auto_capture_refused", { session: sid, trigger, reason: "no_model" }, true, sid, captureGate.evidenceContext);
228
+ await record(
229
+ "auto_capture_refused",
230
+ { session: sid, trigger, reason: "no_model" },
231
+ true,
232
+ sid,
233
+ captureGate.evidenceContext,
234
+ );
198
235
  return;
199
236
  }
200
237
  let transcript = seeded;
@@ -216,9 +253,12 @@ export function configureAutoCapture(
216
253
  // a PEM body whose BEGIN marker fell off, or a token whose prefix
217
254
  // fell off, matches no pattern — buildCapturePrompt's own scrub
218
255
  // (kept, defense in depth) cannot recognize a fragment.
219
- prompt: buildCapturePrompt(redactSecrets(transcript).slice(-8000), captureMax),
256
+ prompt: buildCapturePrompt(
257
+ redactSecrets(transcript).slice(-8000),
258
+ captureMax,
259
+ ),
220
260
  });
221
- const text = typeof out === "string" ? out : out?.text ?? "";
261
+ const text = typeof out === "string" ? out : (out?.text ?? "");
222
262
  const candidates = parseCandidates(text, captureMax);
223
263
  for (const c of candidates) {
224
264
  const durable: string[] = [];
@@ -237,10 +277,21 @@ export function configureAutoCapture(
237
277
  } catch (err) {
238
278
  // A refused write must not disappear into the hook's fail-soft
239
279
  // wrapper. Preserve any earlier gate retirements in the receipt.
240
- await record(durable.length ? "auto_capture_partial" : "auto_capture_refused", {
241
- session: sid, trigger, type: c.type, scope: redactSecrets(c.scope),
242
- reason: String(err), retired: durable.join(",") || undefined, model: modelTag,
243
- }, false, sid, captureGate.evidenceContext);
280
+ await record(
281
+ durable.length ? "auto_capture_partial" : "auto_capture_refused",
282
+ {
283
+ session: sid,
284
+ trigger,
285
+ type: c.type,
286
+ scope: redactSecrets(c.scope),
287
+ reason: String(err),
288
+ retired: durable.join(",") || undefined,
289
+ model: modelTag,
290
+ },
291
+ false,
292
+ sid,
293
+ captureGate.evidenceContext,
294
+ );
244
295
  continue;
245
296
  }
246
297
  await record(
@@ -265,12 +316,20 @@ export function configureAutoCapture(
265
316
  captureGate.evidenceContext,
266
317
  );
267
318
  }
268
- await recordCaptureLag(sid, lagMs, candidates.length ? "candidates" : "empty", captureGate.evidenceContext, modelTag);
319
+ await recordCaptureLag(
320
+ sid,
321
+ lagMs,
322
+ candidates.length ? "candidates" : "empty",
323
+ captureGate.evidenceContext,
324
+ modelTag,
325
+ );
269
326
  }
270
327
 
271
328
  void (async () => {
272
329
  try {
273
- for await (const raw of eventApi.subscribe({ signal: controller.signal })) {
330
+ for await (const raw of eventApi.subscribe({
331
+ signal: controller.signal,
332
+ })) {
274
333
  if (!captureTriggerFor(raw)) continue;
275
334
  const sid = captureSessionID(raw);
276
335
  if (sid === undefined) continue;
@@ -301,7 +360,12 @@ export function configureAutoCapture(
301
360
  const now = Date.now();
302
361
  if (!captureCooldownPasses("compaction", sid, now)) return; // 5-min cooldown
303
362
  void guarded("session.compaction (auto-capture)", () =>
304
- captureSession(sid, flattenTranscript(messages), "compaction", messages),
363
+ captureSession(
364
+ sid,
365
+ flattenTranscript(messages),
366
+ "compaction",
367
+ messages,
368
+ ),
305
369
  );
306
370
  };
307
371
  }
@@ -23,7 +23,8 @@ const lastModel = new Map<string, SessionModelRef>();
23
23
  export function recordSessionModel(sid: string, model: unknown): void {
24
24
  if (!model || typeof model !== "object") return;
25
25
  const m = model as Record<string, unknown>;
26
- const providerID = typeof m.providerID === "string" ? m.providerID.trim() : "";
26
+ const providerID =
27
+ typeof m.providerID === "string" ? m.providerID.trim() : "";
27
28
  const id = typeof m.id === "string" ? m.id.trim() : "";
28
29
  if (!providerID || !id) return;
29
30
  // Sessions churn and a long-lived server must not grow one entry per
@@ -1,6 +1,5 @@
1
1
  // transcript — split from src/capture.ts (#168 domain restructure). Declaration bodies are unchanged.
2
2
 
3
-
4
3
  // Render an array of session-context messages of unknown shape into
5
4
  // "role: text" lines. Defensive by construction (the API shape varies and is
6
5
  // not ours to trust): non-arrays and junk entries are skipped; role comes
@@ -17,9 +16,15 @@ export function flattenTranscript(msgs: unknown): string {
17
16
  if (!msg || typeof msg !== "object") continue;
18
17
  const m = msg as Record<string, unknown>;
19
18
  const info =
20
- m.info && typeof m.info === "object" ? (m.info as Record<string, unknown>) : undefined;
19
+ m.info && typeof m.info === "object"
20
+ ? (m.info as Record<string, unknown>)
21
+ : undefined;
21
22
  const role =
22
- typeof info?.role === "string" ? info.role : typeof m.role === "string" ? m.role : "";
23
+ typeof info?.role === "string"
24
+ ? info.role
25
+ : typeof m.role === "string"
26
+ ? m.role
27
+ : "";
23
28
  let text = "";
24
29
  let hadPrivatePart = false;
25
30
  if (Array.isArray(m.parts)) {
@@ -27,7 +32,8 @@ export function flattenTranscript(msgs: unknown): string {
27
32
  .map((p) => {
28
33
  if (!p || typeof p !== "object") return undefined;
29
34
  const part = p as Record<string, unknown>;
30
- const partType = typeof part.type === "string" ? part.type.toLowerCase() : "";
35
+ const partType =
36
+ typeof part.type === "string" ? part.type.toLowerCase() : "";
31
37
  if (partType === "reasoning" || partType === "thinking") {
32
38
  hadPrivatePart = true;
33
39
  return undefined;
@@ -4,7 +4,7 @@ import { existsSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { record } from "../evidence/record.ts";
6
6
  import { evidenceDir } from "../core/config/paths.ts";
7
- import { parseLine } from "../core/logfmt/format.ts"
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
10
  import {
@@ -31,7 +31,15 @@ export interface AfterOutput {
31
31
  // actually engaged with the code it later writes about (GATE-4's behavior-
32
32
  // grounded injection): reading/grepping a shot of live code, editing it, or
33
33
  // running commands. Empirical behavior substitutes for hand-copied refs.
34
- const ENGAGEMENT_TOOLS = new Set(["grep", "glob", "read", "edit", "write", "bash", "shell"]);
34
+ const ENGAGEMENT_TOOLS = new Set([
35
+ "grep",
36
+ "glob",
37
+ "read",
38
+ "edit",
39
+ "write",
40
+ "bash",
41
+ "shell",
42
+ ]);
35
43
 
36
44
  const RECENT_EVIDENCE_CALLS = 10;
37
45
  // Pending recovery stores IDs only; the full attribution ledger stays in calls.
@@ -97,11 +105,13 @@ function classify(tool: string, out: AfterOutput): "FAIL" | "PASS" {
97
105
  if (tool === "bash" || tool === "shell") {
98
106
  const code = exitCode(out);
99
107
  if (typeof code === "number") return code === 0 ? "PASS" : "FAIL";
100
- if (/\b(failed|failure|error|not found|command failed)\b/i.test(text)) return "FAIL";
108
+ if (/\b(failed|failure|error|not found|command failed)\b/i.test(text))
109
+ return "FAIL";
101
110
  return "PASS";
102
111
  }
103
112
  if (tool === "grep" || tool === "glob") {
104
- if (/no (matches|files|results)|no output found|did not match/i.test(text)) return "FAIL";
113
+ if (/no (matches|files|results)|no output found|did not match/i.test(text))
114
+ return "FAIL";
105
115
  if (/\d+\s+match/i.test(text)) return "PASS";
106
116
  return text.trim() ? "PASS" : "FAIL";
107
117
  }
@@ -113,7 +123,10 @@ function summarize(text: string, n = 80): string {
113
123
  return one.length > n ? one.slice(0, n) + "…" : one;
114
124
  }
115
125
 
116
- export async function afterTool(input: AfterInput, out: AfterOutput): Promise<void> {
126
+ export async function afterTool(
127
+ input: AfterInput,
128
+ out: AfterOutput,
129
+ ): Promise<void> {
117
130
  const tool = typeof input.tool === "string" ? input.tool : "?";
118
131
  const sid = typeof input.sessionID === "string" ? input.sessionID : undefined;
119
132
  const call = typeof input.callID === "string" ? input.callID : "?";
@@ -141,7 +154,9 @@ export async function afterTool(input: AfterInput, out: AfterOutput): Promise<vo
141
154
  // Generic capture (data, not chat). The output_summary is telemetry about
142
155
  // the call (tool name + a short, redacted glimpse); the session/repo scoping
143
156
  // of evidence reads is tracked separately (#128 acceptance, #130).
144
- if (["grep", "glob", "read", "edit", "write", "bash", "shell"].includes(tool)) {
157
+ if (
158
+ ["grep", "glob", "read", "edit", "write", "bash", "shell"].includes(tool)
159
+ ) {
145
160
  await record(
146
161
  "tool_result",
147
162
  {
@@ -165,8 +180,14 @@ export async function afterTool(input: AfterInput, out: AfterOutput): Promise<vo
165
180
  } else if (s.pendingGate && s.pendingGate.cmd === family) {
166
181
  const pend = s.pendingGate;
167
182
  const fix = pend.fix?.call ?? call;
168
- const oldFix = pend.fix && pend.fix.index <= pend.count - pend.chain.length;
169
- const chainCalls = [pend.call, ...(oldFix ? [fix] : []), ...pend.chain, call];
183
+ const oldFix =
184
+ pend.fix && pend.fix.index <= pend.count - pend.chain.length;
185
+ const chainCalls = [
186
+ pend.call,
187
+ ...(oldFix ? [fix] : []),
188
+ ...pend.chain,
189
+ call,
190
+ ];
170
191
  await record(
171
192
  "t4_learning",
172
193
  {
@@ -244,7 +265,10 @@ export function evidenceCalls(sid: string): string[] {
244
265
  // on each write: it grows throughout the session. Pin the actual trigger
245
266
  // witnesses when recorded rather than trying to reconstruct a FAIL->PASS
246
267
  // pairing from a cropped tail. The full ledger remains available above.
247
- export function writeEvidence(sid: string): { evidenceCalls: string[]; evidenceCallsCount: number } {
268
+ export function writeEvidence(sid: string): {
269
+ evidenceCalls: string[];
270
+ evidenceCallsCount: number;
271
+ } {
248
272
  const s = session(sid);
249
273
  const evidence = s.writeEvidence;
250
274
  const refs = new Set([
@@ -285,7 +309,9 @@ export function markFrontierTap(sid: string, call: string): void {
285
309
  s.firstTap = { call, turn: s.turns, ts: new Date().toISOString() };
286
310
  }
287
311
 
288
- export function firstFrontierTap(sid: string): { call: string; turn: number; ts: string } | undefined {
312
+ export function firstFrontierTap(
313
+ sid: string,
314
+ ): { call: string; turn: number; ts: string } | undefined {
289
315
  return session(sid).firstTap;
290
316
  }
291
317
 
@@ -299,7 +325,9 @@ export async function finalizeSession(sid: string): Promise<void> {
299
325
  const tap = s.firstTap;
300
326
  const start = s.firstActivityTs ?? s.calls[0]?.ts;
301
327
  const ms =
302
- tap && start ? Math.max(0, Date.parse(tap.ts) - Date.parse(start)) : undefined;
328
+ tap && start
329
+ ? Math.max(0, Date.parse(tap.ts) - Date.parse(start))
330
+ : undefined;
303
331
  await record(
304
332
  "session_convergence",
305
333
  {
@@ -307,7 +335,9 @@ export async function finalizeSession(sid: string): Promise<void> {
307
335
  turns: s.turns,
308
336
  tap_at: tap ? tap.call : "-",
309
337
  turns_to_tap: tap ? tap.turn : undefined,
310
- re_derives: s.calls.filter((c) => ["grep", "glob", "read"].includes(c.tool)).length,
338
+ re_derives: s.calls.filter((c) =>
339
+ ["grep", "glob", "read"].includes(c.tool),
340
+ ).length,
311
341
  ms_to_tap: ms,
312
342
  calls: s.calls.length,
313
343
  },
@@ -335,7 +365,8 @@ export async function recentConvergenceSummary(limit = 6): Promise<string> {
335
365
  const dir = evidenceDir();
336
366
  if (!existsSync(dir)) return "";
337
367
  const files: string[] = [];
338
- for await (const f of new Bun.Glob("*.logfmt").scan(dir)) files.push(join(dir, f));
368
+ for await (const f of new Bun.Glob("*.logfmt").scan(dir))
369
+ files.push(join(dir, f));
339
370
  files.sort();
340
371
  // sid -> tap turn from frontier_tapped rows (late taps lost from rollups).
341
372
  const lateTaps = new Map<string, number>();
@@ -364,7 +395,10 @@ export async function recentConvergenceSummary(limit = 6): Promise<string> {
364
395
  (r) => r.turn !== null || lateTaps.has(r.session),
365
396
  );
366
397
  if (!recent.length || !tapped.length) return "";
367
- const sum = tapped.reduce((a, r) => a + (r.turn ?? lateTaps.get(r.session) ?? 0), 0);
398
+ const sum = tapped.reduce(
399
+ (a, r) => a + (r.turn ?? lateTaps.get(r.session) ?? 0),
400
+ 0,
401
+ );
368
402
  const avg = sum / tapped.length;
369
403
  const label = avg % 1 === 0 ? String(avg) : avg.toFixed(1);
370
404
  return `${recent.length} sessions tracked, ${tapped.length} reached the frontier (first tap ~${label} turns)`;
@@ -9,7 +9,12 @@ import { dirname, join } from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { commandsDir } from "../core/config/paths.ts";
11
11
 
12
- const PKG_COMMANDS = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "command");
12
+ const PKG_COMMANDS = join(
13
+ dirname(fileURLToPath(import.meta.url)),
14
+ "..",
15
+ "..",
16
+ "command",
17
+ );
13
18
 
14
19
  export async function ensureCommand(name: string): Promise<string | null> {
15
20
  try {