opencode-self-improvement 0.14.18 → 0.14.20

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/src/index.ts CHANGED
@@ -3,22 +3,17 @@
3
3
  // tiny-digest injection with deterministic memory-first context and
4
4
  // contextual pull, and snapshot/rollback.
5
5
  //
6
- // V2 port: registers tools via `ctx.tool.transform` (JSON Schema), mirrors the
7
- // V1 hooks onto the OpenCode V2 session/tool hook API, and registers the
8
- // /repo-init command via `ctx.command.transform`. The plugin contract is a
9
- // default export object `{ id, setup(ctx) }` (OpenCode >= 2.0), pinned at
10
- // compile time against the real SDK type (`@opencode/plugin`, type-only — see
11
- // the note on `plugin` below). All business logic still lives in the decoupled
12
- // helper modules.
6
+ // Registers tools via `ctx.tool.transform` (JSON Schema) and hooks via the
7
+ // OpenCode V2 session/tool API. Slash commands are installed as markdown by
8
+ // src/command.ts. The default export `{ id, setup(ctx) }` is checked against
9
+ // the SDK's Plugin type using a type-only import (see the note on `plugin`).
13
10
  import type { Cleanup, Plugin } from "@opencode/plugin/promise/plugin";
14
11
  import { basename, join } from "node:path";
15
12
  import { frontierBudget, injectBudget, memoryRoot } from "./config.ts";
16
- import { STATUSES, TYPES } from "./types.ts";
17
13
  import {
18
14
  clearSuperseded,
19
15
  evidenceVisibleTo,
20
16
  isActive,
21
- isVisibleHere,
22
17
  isVisibleTo,
23
18
  loadAll,
24
19
  malformedCount,
@@ -28,7 +23,6 @@ import {
28
23
  resolveMemoryTarget,
29
24
  snapshotFiles,
30
25
  unresolvedWriteMessage,
31
- visibleTo,
32
26
  type Memory,
33
27
  } from "./memory.ts";
34
28
  import { auditCaveat, runWriteGate, sameStrList, type GateContext, type WriteCandidate } from "./gates.ts";
@@ -41,39 +35,29 @@ import { evidenceFileFor, record, recordCaptureLag } from "./evidence.ts";
41
35
  import { proposeConsolidations, renderProposals } from "./consolidate.ts";
42
36
  import { readReads } from "./hits.ts";
43
37
  import {
44
- capToBudget,
45
38
  compactionAnchor,
46
39
  contextualPull,
47
40
  formatMemory,
48
- injectedRows,
49
41
  pullQuery,
50
- selectRelevant,
51
42
  sharedTerms,
52
- storeVersion,
53
- systemDigest,
54
43
  } from "./inject.ts";
55
- import { attributeSession, deriveMemoryRefs, type MemoryRefs } from "./attribution.ts";
44
+ import { createInjectionEpochs } from "./injection-epochs.ts";
56
45
  import { readLedger, neverRetrieved, recordHits, useSignals, type HitSource } from "./hits.ts";
57
46
  import { formatInit, runInit } from "./init.ts";
58
47
  import { ensureInitCommand, ensureMemoryReportCommand } from "./command.ts";
59
48
  import {
60
49
  blockedRecent,
61
- emptyStats,
62
50
  renderMemoryReport,
63
- writeStatus,
64
51
  type Measured,
65
- type SessionStats,
66
52
  captureLag,
67
53
  captureLagLines,
68
54
  rowsPerDay,
69
- type StatusPayload,
70
55
  type StoreCounts,
71
56
  } from "./status.ts";
72
57
  import {
73
58
  afterTool,
74
- callsFor,
75
59
  checkNewSession,
76
- evidenceCalls,
60
+ writeEvidence,
77
61
  firstFrontierTap,
78
62
  hasEngagement,
79
63
  hasGateCheck,
@@ -81,13 +65,21 @@ import {
81
65
  markTurn,
82
66
  onCompacting,
83
67
  } from "./triggers.ts";
84
- import { authoredFor, getCurrent, setCurrent } from "./state.ts";
68
+ import { getCurrent, setCurrent } from "./state.ts";
85
69
  import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional, writeTarget } from "./repokey.ts";
86
70
  import { parseLine, readLines } from "./logfmt.ts";
87
71
  import { buildCapturePrompt, flattenTranscript, lagSince, parseCandidates, parseModelRef } from "./capture.ts";
88
72
  import { redactSecrets } from "./secrets.ts";
89
73
  import { flattenMemoryText } from "./sanitize.ts";
90
74
  import { bunFloorWarning } from "./runtime.ts";
75
+ import {
76
+ captureSessionID,
77
+ sessionDirectoryFromMessages,
78
+ sessionDirectoryFromRow,
79
+ sessionIdentityEvent,
80
+ sessionUsageEvent,
81
+ toolIdentity,
82
+ } from "./host.ts";
91
83
 
92
84
  // Tool/input boundaries are zod schemas (src/schema.ts): the JSON Schema the
93
85
  // host sees is GENERATED from them, and raw args are re-parsed at execution.
@@ -143,16 +135,8 @@ interface PluginCtx {
143
135
  transform: (cb: (editor: ToolEditorLike) => void) => Promise<unknown>;
144
136
  hook: (name: string, cb: (event: any) => Promise<void> | void) => Promise<HookReg | void>;
145
137
  };
146
- command?: {
147
- transform: (cb: (editor: { add: (cmd: Record<string, unknown>) => void }) => void) => Promise<unknown>;
148
- };
149
138
  session?: {
150
139
  hook: (name: string, cb: (event: any) => Promise<void> | void) => Promise<HookReg | void>;
151
- prompt: (input: {
152
- sessionID: string;
153
- text: string;
154
- delivery?: "steer" | "queue";
155
- }) => Promise<unknown>;
156
140
  context?: (input: { sessionID: string }) => Promise<unknown>;
157
141
  get?: (input: { sessionID: string }) => Promise<unknown>;
158
142
  };
@@ -231,36 +215,19 @@ export function resetCaptureCooldowns(): void {
231
215
  }
232
216
 
233
217
  // ---- capture trigger vocabulary (#136) -------------------------------------
234
- // opencode 2.x has no `session.idle`. The subscription used to wait for exactly
235
- // that string, so auto-capture was dead on every 2.x host with no warning
236
- // anywhere: live proof is in the issue (45 s of the running service's own SSE
237
- // stream over a complete turn, and zero `capture_lag` lines in the whole
238
- // evidence history). What the host really publishes when a turn ends is the
239
- // `session.execution.*` family; `session.status` is the ephemeral variant whose
240
- // `status.type` says "idle".
241
- //
242
- // These lists are the single source of truth for what the capture subscription
243
- // reacts to, and test/event-fidelity.test.ts asserts every name here appears in
244
- // the installed @opencode/schema event manifest. Invented event names are the
245
- // bug class that caused #78 and then survived a review, a merge and 480 green
246
- // tests, because the tests fabricated the same invented payload.
247
- // Recorded live, not guessed: `succeeded` and `interrupted` were both observed
248
- // on a running desktop service (test/fixtures/host-events.jsonl).
218
+ // Single source of truth for capture subscriptions. Both turn-end events were
219
+ // observed on the desktop service (test/fixtures/host-events.jsonl).
220
+ // test/event-fidelity.test.ts requires every trigger to appear in both that
221
+ // recording and the installed @opencode/schema manifest: a declared event
222
+ // alone is insufficient evidence that the host emits it (#78, #136).
249
223
  export const TURN_END_EVENTS = ["session.execution.succeeded", "session.execution.interrupted"] as const;
250
224
 
251
225
  /** Every event type the capture subscription reacts to (fidelity-tested). */
252
226
  export const CAPTURE_EVENT_TYPES: readonly string[] = [...TURN_END_EVENTS];
253
227
 
254
- // Deliberately NOT triggers, because a live host was never observed sending
255
- // them, and dead branches are what caused #136 in the first place:
256
- // • `session.idle` - declared, never emitted (the original bug).
257
- // • `session.status` - declared, never emitted; would also need
258
- // `data.status.type === "idle"` filtering.
259
- // • `session.execution.failed` - declared, not reproduced here. A failed turn
260
- // simply does not capture, which costs nothing; adding it
261
- // later is allowed the moment a recording shows it.
262
- // test/event-fidelity.test.ts enforces that nothing enters TURN_END_EVENTS
263
- // without appearing in the recording.
228
+ // `session.idle`, `session.status`, and `session.execution.failed` are declared
229
+ // but absent from that recording, so they deliberately do not trigger capture.
230
+ // Adding a trigger requires a recording; status would also need idle filtering.
264
231
 
265
232
  /**
266
233
  * True when a host event means "this session just went quiet". The internal
@@ -338,7 +305,7 @@ const impl = {
338
305
  // through here (readers and stamps use the firm-or-provisional split
339
306
  // in repokey/memory); do not mistake this for one.
340
307
  liveRoot: sessionDir(bound) ?? liveRoot,
341
- evidenceCalls: evidenceCalls(bound),
308
+ ...writeEvidence(bound),
342
309
  hasGateCheck: hasGateCheck(bound),
343
310
  hasEngagement: hasEngagement(bound),
344
311
  };
@@ -370,19 +337,17 @@ const impl = {
370
337
  // no await between (#116's documented fallback). Never re-read the global
371
338
  // after an await to learn who is calling (#127).
372
339
  const toolIds = (context?: unknown): { sid: string; call: string } => {
373
- const fromCtx = (context as { sessionID?: unknown; id?: unknown } | undefined)
374
- ?.sessionID;
375
- const call = (context as { id?: unknown } | undefined)?.id;
340
+ const { sessionID: fromCtx, callID: call } = toolIdentity(context);
376
341
  // Entry binding: a session this instance has never seen is resolved to
377
342
  // THIS workspace (provisional — a firm event/API identity still
378
343
  // replaces it), so the tool's reader partitions by the repository the
379
344
  // call reached, not by the last setup's module scope (#127).
380
- if (typeof fromCtx === "string" && fromCtx && fromCtx !== "?") {
345
+ if (fromCtx && fromCtx !== "?") {
381
346
  bindSessionProvisional(fromCtx, instanceDir);
382
347
  }
383
348
  return {
384
- sid: typeof fromCtx === "string" && fromCtx ? fromCtx : getCurrent().sid,
385
- call: typeof call === "string" && call ? call : getCurrent().call,
349
+ sid: fromCtx ?? getCurrent().sid,
350
+ call: call ?? getCurrent().call,
386
351
  };
387
352
  };
388
353
 
@@ -400,17 +365,8 @@ const impl = {
400
365
  bindingSids.add(sid);
401
366
  try {
402
367
  const msgs = await ctx.session?.context?.({ sessionID: sid });
403
- if (Array.isArray(msgs)) {
404
- for (const m of msgs) {
405
- if (!m || typeof m !== "object") continue;
406
- const r = m as Record<string, any>;
407
- const dir = r.location?.directory ?? r.info?.location?.directory;
408
- if (typeof dir === "string" && dir) {
409
- rememberSessionDir(sid, dir);
410
- break;
411
- }
412
- }
413
- }
368
+ const dir = sessionDirectoryFromMessages(msgs);
369
+ if (dir !== undefined) rememberSessionDir(sid, dir);
414
370
  } catch {
415
371
  // no context access or host error: the event stream still binds later
416
372
  } finally {
@@ -432,10 +388,9 @@ const impl = {
432
388
  apiBindTried.add(sid);
433
389
  apiBindOrder.touch(sid);
434
390
  try {
435
- const got = (await ctx.session?.get?.({ sessionID: sid })) as Record<string, any> | undefined;
436
- const row = (got?.data ?? got) as Record<string, any> | undefined;
437
- const dir = row?.location?.directory ?? row?.directory;
438
- if (typeof dir === "string" && dir) rememberSessionDir(sid, dir);
391
+ const got = await ctx.session?.get?.({ sessionID: sid });
392
+ const dir = sessionDirectoryFromRow(got);
393
+ if (dir !== undefined) rememberSessionDir(sid, dir);
439
394
  } catch {
440
395
  // no session.get on this host (or unknown session): stay unbound
441
396
  }
@@ -1268,7 +1223,7 @@ const impl = {
1268
1223
  async execute(_args, context): Promise<{ content: string }> {
1269
1224
  // In-process truth: the live epoch + ledger, fresher than any file.
1270
1225
  const sid = toolIds(context).sid;
1271
- const status = sid === "?" ? null : await buildPayload(sid);
1226
+ const status = sid === "?" ? null : await sessions.buildPayload(sid);
1272
1227
  const all = await loadAll();
1273
1228
  const act = all.filter(isActive);
1274
1229
  const store: StoreCounts = {
@@ -1297,121 +1252,6 @@ const impl = {
1297
1252
  }));
1298
1253
  });
1299
1254
 
1300
- // Per-session frozen injection epochs: the whole memory section (digest +
1301
- // frontier + relevance) plus the store fingerprint it was rendered from.
1302
- // Recomputed on the first prompt of a tracked session, when injectable rows
1303
- // change, or after a compaction (see the prompt/context/compaction hooks).
1304
- // The RENDERED BYTES, not the fingerprint, decide whether the epoch moved
1305
- // (issue #162): a write that changes nothing the model is shown must not
1306
- // cost the next request a full re-prefill. And a pure addition the session
1307
- // wrote itself does not move them either (#165) — see refreshEpoch. The
1308
- // shared LRU below may evict the whole session state; a later prompt starts
1309
- // it fresh.
1310
- const epoch = new Map<
1311
- string,
1312
- {
1313
- version: string;
1314
- /** Frozen standing digest + frontier + convergence parts, in push order. */
1315
- parts: string[];
1316
- /** The budgeted relevance block the surfaces report against injectBudget. */
1317
- block: string;
1318
- /** Comparison key: every byte of the memory section, joined. */
1319
- prefix: string;
1320
- /**
1321
- * Rows THIS session had already authored when these bytes were rendered
1322
- * (#165). The riding-bytes test subtracts everything authored after this
1323
- * snapshot; if what remains renders identically, the whole difference is
1324
- * the session's own additions and the bytes keep riding.
1325
- */
1326
- ownRows: Set<string>;
1327
- /**
1328
- * The prompt these bytes were scored against. The counterfactual below
1329
- * has to re-score the SAME inputs, or a topic change between the freeze
1330
- * and the next write would look like a content change — and the epoch
1331
- * would pay for a refresh it deliberately refuses to do on a prompt.
1332
- */
1333
- prompt: string;
1334
- at: string;
1335
- reason: "first" | "store_changed";
1336
- refs: MemoryRefs;
1337
- }
1338
- >();
1339
- // Latest user prompt per tracked session. A changed store is re-scored
1340
- // against it even when the change happened during a tool loop with no new
1341
- // prompt. It is evicted together with the epoch and session ledgers.
1342
- const latestPrompt = new Map<string, string>();
1343
- // Recomputes since server start: every one invalidated a prompt cache, so
1344
- // it is the honest cost number the surfaces show (status files / tools).
1345
- let epochRecomputes = 0;
1346
-
1347
- // Per-session ledger, incremented at the injection decision below, and the
1348
- // last measured prompt-cache usage per session (message.updated). The
1349
- // surfaces read these through flushed status files (TUI) or directly
1350
- // (memory_status, in-process).
1351
- const sessionStats = new Map<string, SessionStats>();
1352
- const measuredTurns = new Map<string, Measured>();
1353
- // Every map above is keyed by session and dropped together on eviction.
1354
- const sessions = new SessionLru(SESSION_CAP, (sid) => {
1355
- epoch.delete(sid);
1356
- latestPrompt.delete(sid);
1357
- sessionStats.delete(sid);
1358
- measuredTurns.delete(sid);
1359
- });
1360
- const statsFor = (sid: string): SessionStats => {
1361
- let st = sessionStats.get(sid);
1362
- if (!st) {
1363
- st = emptyStats();
1364
- sessionStats.set(sid, st);
1365
- }
1366
- return st;
1367
- };
1368
-
1369
- // Build the full status snapshot for one session, or null before its first
1370
- // epoch. Store counts are computed fresh so every flush is current.
1371
- const buildPayload = async (sid: string): Promise<StatusPayload | null> => {
1372
- const ep = epoch.get(sid);
1373
- if (!ep) return null;
1374
- const all = await loadAll();
1375
- const act = all.filter(isActive);
1376
- const led = await readLedger();
1377
- return {
1378
- at: ep.at,
1379
- sessionID: sid,
1380
- reason: ep.reason,
1381
- recomputes: epochRecomputes,
1382
- block: ep.block,
1383
- blockChars: ep.block.length,
1384
- sectionChars: ep.prefix.length,
1385
- budget,
1386
- store: {
1387
- active: act.length,
1388
- superseded: all.length - act.length,
1389
- open: act.filter((m) => m.status === "open").length,
1390
- scopes: new Set(act.map((m) => m.scope)).size,
1391
- malformed: malformedCount(),
1392
- neverRetrieved: neverRetrieved(act, led).length,
1393
- ledgerSince: led.since,
1394
- },
1395
- stats: statsFor(sid),
1396
- measured: measuredTurns.get(sid) ?? null,
1397
- attribution: attributeSession(callsFor(sid), ep.refs),
1398
- };
1399
- };
1400
- const flushStatus = (sid: string): Promise<void> =>
1401
- buildPayload(sid).then((p) => (p ? writeStatus(p) : undefined));
1402
-
1403
- // Called when a prompt arrives (to keep status surfaces current) and again
1404
- // at the injection decision on every model request. The latter keeps
1405
- // removals fail-closed: an out-of-band redaction or a block during a tool
1406
- // loop cannot ride one more request waiting for another user prompt.
1407
- // The caller's sid is resolved to an immutable Reader BEFORE the store
1408
- // read (#127): while loadAll awaits, another session's hooks may dispatch
1409
- // and move the ambient current; filtering with THAT leaks the other
1410
- // session's repo into this one's system prompt.
1411
- const injectableRows = async (sid?: string): Promise<Memory[]> => {
1412
- const reader = readerFromSid(sid);
1413
- return (await loadAll()).filter((m) => isActive(m) && isVisibleTo(m, reader));
1414
- };
1415
1255
  // Use ledger (#42). `query` is what retrieval was asked with; what gets
1416
1256
  // stored is the vocabulary the answer SHARES with the query, taken from the
1417
1257
  // memory side, so the ledger can never become a copy of user prompts.
@@ -1422,118 +1262,16 @@ const impl = {
1422
1262
  for (const m of rows) for (const t of sharedTerms(query, m)) if (!terms.includes(t)) terms.push(t);
1423
1263
  await recordHits(src, sid, rows, terms);
1424
1264
  };
1425
- // Render the COMPLETE memory section for one request: the standing digest,
1426
- // the open-thread frontier and the convergence line (all from systemDigest),
1427
- // followed by this epoch's relevance block. The parts are exactly what gets
1428
- // pushed onto `event.system`; their join is the byte key the epoch compares
1429
- // against, so "did the cache-critical prefix change?" is answered by the
1430
- // bytes the model would actually see and never by a proxy (issue #162).
1431
- const buildMemorySection = async (
1432
- sid: string | undefined,
1433
- mems: Memory[],
1434
- promptOverride?: string,
1435
- ): Promise<{ parts: string[]; block: string; prefix: string; rode: Memory[]; refs: MemoryRefs }> => {
1436
- const parts: string[] = [];
1437
- await systemDigest(
1438
- { sessionID: sid },
1439
- { system: parts },
1440
- { rows: mems, frontierBudget: openBudget },
1441
- );
1442
- const prompt = promptOverride ?? (sid === undefined ? "" : latestPrompt.get(sid) ?? "");
1443
- // Widen the candidate pool, then cap: the budget decides what rides.
1444
- const sel = await selectRelevant(prompt, 5, mems, await useSignals());
1445
- const block = sel.block ? capToBudget(sel.block, budget) : "";
1446
- // Refs the ACTUALLY-injected rows assert (paths + commands), the join key
1447
- // for attribution. Derived from the budget-surviving rows, not the wider
1448
- // candidate pool — crediting paths the model never saw would overclaim.
1449
- const rode = injectedRows(block, sel.selected);
1450
- const prefix = [...parts, block].join("\u0000");
1451
- return { parts, block, prefix, rode, refs: deriveMemoryRefs(rode) };
1452
- };
1453
- const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
1454
- if (!latestPrompt.has(sid)) return;
1455
- const mems = rows ?? (await injectableRows(sid));
1456
- const version = await storeVersion(mems);
1457
- const cached = epoch.get(sid);
1458
- // Cheap pre-check: no injectable row moved, so the frozen bytes still
1459
- // stand. Skips re-scoring and the use-ledger write on ordinary turns.
1460
- if (cached?.version === version) return;
1461
- const built = await buildMemorySection(sid, mems);
1462
- // The store moved. A write that changes nothing RENDERED — a row that is
1463
- // not relevant to this prompt, supersession elsewhere, a scope the reader
1464
- // never sees rendered identically — must not cost this session a prompt
1465
- // cache. Adopt the new fingerprint, keep riding the same bytes, emit
1466
- // nothing: an invalidation has to mean bytes actually moved.
1467
- if (cached && cached.prefix === built.prefix) {
1468
- epoch.set(sid, { ...cached, version });
1469
- return;
1470
- }
1471
- // Riding bytes (#165): a pure addition this session wrote itself is
1472
- // information it already has — the model produced it, it is in the
1473
- // transcript. Re-render the section with every row authored SINCE these
1474
- // bytes were frozen taken back out: if it comes back byte-identical, the
1475
- // entire difference is attributable to the session's own additions and
1476
- // the frozen bytes keep riding. Everything else survives into that render
1477
- // and still busts — a riding row removed or rewritten (blocklist,
1478
- // hand-redaction, forget, supersession, decay), another session's row, a
1479
- // viewer edit, an import, a moved convergence line.
1480
- if (cached) {
1481
- const mine = authoredFor(sid);
1482
- const extra = mems.filter((m) => mine.has(m.ts) && !cached.ownRows.has(m.ts));
1483
- if (extra.length) {
1484
- const back = await buildMemorySection(
1485
- sid,
1486
- mems.filter((m) => !extra.some((e) => e.ts === m.ts)),
1487
- cached.prompt,
1488
- );
1489
- if (back.prefix === cached.prefix) {
1490
- epoch.set(sid, { ...cached, version });
1491
- return;
1492
- }
1493
- }
1494
- }
1495
- const prompt = latestPrompt.get(sid) ?? "";
1496
- // Use ledger (#42): the rows that actually rode the block, credited with
1497
- // the terms the prompt and those rows shared (never the prompt itself).
1498
- // Only once the build is ADOPTED — a discarded rebuild must not credit
1499
- // rows that were already offered under the frozen epoch.
1500
- await noteHits("inject", sid, built.rode, prompt);
1501
- const at = new Date().toISOString();
1502
- const reason: "first" | "store_changed" = cached ? "store_changed" : "first";
1503
- epoch.set(sid, {
1504
- version,
1505
- parts: built.parts,
1506
- block: built.block,
1507
- prefix: built.prefix,
1508
- ownRows: new Set(mems.filter((m) => authoredFor(sid).has(m.ts)).map((m) => m.ts)),
1509
- prompt,
1510
- at,
1511
- reason,
1512
- refs: built.refs,
1513
- });
1514
- await record(
1515
- "epoch_recompute",
1516
- {
1517
- session: sid,
1518
- reason,
1519
- chars: built.block.length,
1520
- },
1521
- false,
1522
- );
1523
- epochRecomputes++;
1524
- // Ledger: a store_changed recompute of a live epoch is an
1525
- // invalidation (the first epoch of a session busts nothing). The
1526
- // epoch request count restarts with the new block.
1527
- const st = statsFor(sid);
1528
- st.epochRequests = 0;
1529
- if (reason === "store_changed") {
1530
- st.invalidations++;
1531
- st.lastInvalidation = { at, reason };
1532
- }
1533
- // Status hand-off for the terminal panel (src/tui.tsx) and any
1534
- // out-of-process surface. Best-effort; never breaks injection.
1535
- await flushStatus(sid);
1536
- };
1265
+ // The host listener owns measured usage; the epoch controller drops it
1266
+ // alongside its own maps when the shared session LRU evicts an entry.
1267
+ const measuredTurns = new Map<string, Measured>();
1268
+ const sessions = createInjectionEpochs({
1269
+ budget,
1270
+ frontierBudget: openBudget,
1271
+ measuredTurns,
1272
+ noteHits: (sid, rows, query) => noteHits("inject", sid, rows, query),
1273
+ });
1274
+ const flushStatus = sessions.flushStatus;
1537
1275
 
1538
1276
  // ---- hooks (all fail-closed) -------------------------------------------
1539
1277
  // Seam set by the auto-capture wiring below ONLY when the compaction
@@ -1598,39 +1336,7 @@ const impl = {
1598
1336
  // already bound firmly in production, so no host lookup belongs in
1599
1337
  // this hot path (#127).
1600
1338
  if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
1601
- const mems = await injectableRows(sid);
1602
- if (typeof sid === "string") await refreshEpoch(sid, mems);
1603
- // Deliver the FROZEN memory section. Every byte pushed onto the system
1604
- // prompt comes from the epoch, so between busts the provider sees an
1605
- // identical prefix and serves the conversation from cache (issue #162).
1606
- // A session with no epoch yet (no prompt recorded, or evicted from the
1607
- // LRU) still gets the standing digest, built fresh and uncached.
1608
- const ep = typeof sid === "string" ? epoch.get(sid) : undefined;
1609
- if (ep) {
1610
- for (const text of ep.parts) event?.system?.push?.({ type: "text", text });
1611
- } else {
1612
- const parts: string[] = [];
1613
- await systemDigest(
1614
- { sessionID: event?.sessionID },
1615
- { system: parts },
1616
- { rows: mems, frontierBudget: openBudget },
1617
- );
1618
- for (const text of parts) event?.system?.push?.({ type: "text", text });
1619
- }
1620
- // This epoch's relevance-ranked memory, also on the system channel —
1621
- // the UI never renders system parts, unlike appended prompt text.
1622
- const knowledge = ep?.block;
1623
- if (knowledge) event?.system?.push?.({ type: "text", text: knowledge });
1624
- // Count AT THE INJECTION DECISION so badge/panel numbers match exactly
1625
- // what rode this request (a later abort still rode the bytes — known
1626
- // and documented). Abstained = the epoch exists but its block is empty.
1627
- if (typeof sid === "string") {
1628
- const st = statsFor(sid);
1629
- st.requests++;
1630
- st.epochRequests++;
1631
- if (knowledge) st.cumChars += knowledge.length;
1632
- else if (epoch.has(sid)) st.abstained++;
1633
- }
1339
+ await sessions.deliver(sid, (text) => event?.system?.push?.({ type: "text", text }));
1634
1340
  }),
1635
1341
  );
1636
1342
 
@@ -1650,8 +1356,7 @@ const impl = {
1650
1356
  markTurn(sid);
1651
1357
  await checkNewSession(sid);
1652
1358
  await bindSessionIdentity(sid);
1653
- latestPrompt.set(sid, event?.prompt?.text ?? "");
1654
- await refreshEpoch(sid);
1359
+ await sessions.prompt(sid, event?.prompt?.text ?? "");
1655
1360
  }
1656
1361
  }),
1657
1362
  );
@@ -1674,8 +1379,7 @@ const impl = {
1674
1379
  if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
1675
1380
  await onCompacting({ sessionID: event?.sessionID });
1676
1381
  if (typeof event?.sessionID === "string") {
1677
- epoch.delete(event.sessionID);
1678
- latestPrompt.delete(event.sessionID);
1382
+ sessions.invalidate(event.sessionID);
1679
1383
  }
1680
1384
  const anchor = await compactionAnchor(12, sid);
1681
1385
  if (anchor) event?.system?.push?.({ type: "text", text: anchor });
@@ -1705,53 +1409,29 @@ const impl = {
1705
1409
  void (async () => {
1706
1410
  try {
1707
1411
  for await (const raw of eventApi.subscribe({ signal: measuredController.signal })) {
1708
- const ev = raw as Record<string, any>;
1709
1412
  // Session identity: created fires for new sessions, execution.started
1710
1413
  // every turn (covers sessions resumed across a restart), moved on a
1711
1414
  // workspace change. Stamps and visibility resolve through this.
1712
- if (
1713
- ev?.type === "session.created" ||
1714
- ev?.type === "session.execution.started" ||
1715
- ev?.type === "session.moved"
1716
- ) {
1717
- const d = ev.data ?? ev.properties ?? {};
1718
- const info = d.info ?? d;
1719
- const sid = info.sessionID ?? d.sessionID;
1720
- const dir =
1721
- info.location?.directory ?? d.location?.directory ?? ev.location?.directory ?? info.directory;
1722
- if (typeof sid === "string" && typeof dir === "string") rememberSessionDir(sid, dir);
1415
+ const identity = sessionIdentityEvent(raw);
1416
+ if (identity) {
1417
+ const { sessionID: sid, directory: dir } = identity;
1418
+ if (dir !== undefined) rememberSessionDir(sid, dir);
1723
1419
  // 2.1.4 serve sends execution.started with no location at all:
1724
1420
  // resolve the session row instead of leaving the session unbound.
1725
- else if (typeof sid === "string") void guarded("session bind (api)", () => bindSessionFromApi(sid));
1726
- continue;
1727
- }
1728
- // Token usage: v2 hosts (>=2.0.x) emit `session.usage.updated` with
1729
- // data.{sessionID, tokens}; older hosts carried the same TokenUsage
1730
- // on message.updated's assistant info. Accept both so `measured`
1731
- // populates regardless of host version.
1732
- let usid: unknown;
1733
- let ut: { input?: number; cache?: { read?: number; write?: number } } | undefined;
1734
- if (ev?.type === "session.usage.updated") {
1735
- usid = ev.data?.sessionID;
1736
- ut = ev.data?.tokens;
1737
- } else if (ev?.type === "message.updated") {
1738
- const info = ev.properties?.info ?? ev.info ?? ev.data?.info;
1739
- if (info && info.role === "assistant") {
1740
- usid = info.sessionID;
1741
- ut = info.tokens;
1742
- }
1743
- } else {
1421
+ else void guarded("session bind (api)", () => bindSessionFromApi(sid));
1744
1422
  continue;
1745
1423
  }
1746
- if (typeof usid !== "string" || !ut) continue;
1747
- sessions.touch(usid);
1748
- measuredTurns.set(usid, {
1424
+ const usage = sessionUsageEvent(raw);
1425
+ if (!usage) continue;
1426
+ const { sessionID, input, read, write } = usage;
1427
+ sessions.touch(sessionID);
1428
+ measuredTurns.set(sessionID, {
1749
1429
  at: new Date().toISOString(),
1750
- input: Number(ut.input) || 0,
1751
- read: Number(ut.cache?.read) || 0,
1752
- write: Number(ut.cache?.write) || 0,
1430
+ input,
1431
+ read,
1432
+ write,
1753
1433
  });
1754
- await guarded("status flush (measured)", () => flushStatus(usid));
1434
+ await guarded("status flush (measured)", () => flushStatus(sessionID));
1755
1435
  }
1756
1436
  } catch {
1757
1437
  // the subscription ended (abort or host error); nothing to do
@@ -1764,7 +1444,7 @@ const impl = {
1764
1444
  // measured-cache listener above does subscribe to the event stream by
1765
1445
  // default, but it is zero-model: pure bookkeeping of message usage.) When
1766
1446
  // enabled (options.autoCapture === true AND a valid captureModel), each
1767
- // session.idle event — and, unless captureOnCompact === false, each
1447
+ // supported turn-end event — and, unless captureOnCompact === false, each
1768
1448
  // compaction hook call too — runs ONE cheap ctx.generate.text call whose
1769
1449
  // reply is parsed into candidates that go through the SAME runWriteGate as
1770
1450
  // model-authored writes — capture can never bypass the moat, and it only
@@ -1893,12 +1573,9 @@ const impl = {
1893
1573
  void (async () => {
1894
1574
  try {
1895
1575
  for await (const raw of eventApi.subscribe({ signal: controller.signal })) {
1896
- const event = raw as Record<string, any>;
1897
- if (!captureTriggerFor(event)) continue;
1898
- // 2.x carries the session inside `data`; the other two shapes are
1899
- // kept because the measured listener sees both across host modes.
1900
- const sid = event.data?.sessionID ?? event.sessionID ?? event.properties?.sessionID;
1901
- if (typeof sid !== "string") continue;
1576
+ if (!captureTriggerFor(raw)) continue;
1577
+ const sid = captureSessionID(raw);
1578
+ if (sid === undefined) continue;
1902
1579
  setCurrent({ sessionID: sid });
1903
1580
  const now = Date.now();
1904
1581
  if (!captureCooldownPasses("idle", sid, now)) continue; // 5-min cooldown, shared across setups
package/src/init.ts CHANGED
@@ -11,7 +11,7 @@ import { cbmBin } from "./config.ts";
11
11
  import { isVisibleTo, loadAll, markSuperseded, readerFromSid } from "./memory.ts";
12
12
  import { runWriteGate, type GateContext } from "./gates.ts";
13
13
  import { record } from "./evidence.ts";
14
- import { evidenceCalls, hasGateCheck } from "./triggers.ts";
14
+ import { writeEvidence, hasGateCheck } from "./triggers.ts";
15
15
  import { getCurrent } from "./state.ts";
16
16
 
17
17
  export interface ScriptRecord {
@@ -216,7 +216,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
216
216
 
217
217
  const gateCtx: GateContext = {
218
218
  liveRoot: root,
219
- evidenceCalls: evidenceCalls(args.sessionID ?? getCurrent().sid),
219
+ ...writeEvidence(args.sessionID ?? getCurrent().sid),
220
220
  hasGateCheck: hasGateCheck(args.sessionID ?? getCurrent().sid),
221
221
  // Stamps land on the caller's session even though runInit awaits git
222
222
  // probing before the gate writes (#127 / #121's write-side root cause).
@@ -322,4 +322,4 @@ export function formatInit(s: InitSummary): string {
322
322
  (s.unaudited ? `, ${s.unaudited} without an audit line` : "") +
323
323
  `; stamp=${s.stampTs ?? "-"}`,
324
324
  ].join("\n");
325
- }
325
+ }