opencode-self-improvement 0.15.12 → 0.15.14

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
@@ -120,6 +120,8 @@ Nothing is deleted: `memory_update` supersedes the previous row, `memory_forget`
120
120
 
121
121
  Rows are stamped with your git origin (an id that survives re-clones and moves between machines) or, without an origin, a hash of the normalized directory path. `repoPath` keeps the human-readable path, so rows written before hashing keep matching.
122
122
 
123
+ Legacy whole-path-lowercased hashes accompanied by `repoPath` are matched to that directory (including real aliases), so a distinct case-sensitive sibling cannot inherit its memories or evidence. Remote-derived identities still share across clones. Stamps without `repoPath` retain key-only matching; their historical identity source cannot be recovered from the key alone.
124
+
123
125
  Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows, resolved from the calling session's identity at flow entry. A session that reaches a plugin instance is bound to that instance's own workspace on first contact — in a process hosting several workspaces, one session never borrows the repository some other workspace's setup left behind. A session whose repository cannot be resolved at all sees global rows only; "unknown" is never "everything". Writes follow that rule in the stricter direction: a named session with no resolved repository has **no write target**, so `memory_remember`, `memory_update`, `memory_import` and auto-capture refuse it (evidence `write_refused`) and store nothing — the alternatives were stamping your private content into whichever workspace's `setup()` ran last, or publishing it to every project as an unstamped row. A caller that names no session at all (the viewer process, a restore, a script) keeps the process scope, and an explicit `global: true` is a deliberate owner. Evidence lines carry the same stamp, so `memory_evidence` answers from the caller's repo plus global lines; a line a named session wrote while its repository was unresolvable is private to that session, and only an explicitly global (or predating-stamps) line reads as global. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed are global, and the viewer (an admin surface over every repo) edits and restores a row with its own repo stamp — the viewer's missing session scope never decides a row's visibility. `memory_merge_review` applies the same rule to its inputs: a session may merge exactly the rows it may read — global rows plus its own repo's, from either seat — and a row id it merely knows is not authority to retire another repo's memory. Upgrading changes nothing.
124
126
 
125
127
  Gate-authored evidence and its init/capture lifecycle records capture attribution at operation entry: if a session moves repositories while the operation runs, its audit lines remain in the starting repository's partition and can be read with `memory_evidence` from a session bound there. Init start/complete/skip, capture outcomes/refusals, and capture lag share that captured owner. A captured named session with no resolved repository keeps a session-private `sid` label even on lifecycle records that suppress call metadata; otherwise an unstamped line would appear global. Viewer audit attribution and cancellation of in-flight capture are separate boundaries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.15.12",
3
+ "version": "0.15.14",
4
4
  "description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
5
5
  "main": "index.ts",
6
6
  "exports": {
@@ -0,0 +1,271 @@
1
+ // Opt-in capture configuration and dispatch (#168). Cooldowns remain process-wide;
2
+ // subscriptions and dispatch closures belong to one setup instance.
3
+ import type { Cleanup } from "@opencode/plugin/promise/plugin";
4
+ import { runWriteGate, type GateContext } from "../gate/gate.ts";
5
+ import { record, recordCaptureLag } from "../evidence/record.ts";
6
+ import { setCurrent } from "../core/state.ts";
7
+ import { bindSessionProvisional, writeTarget } from "../identity/repokey.ts";
8
+ import { captureSessionID } from "../identity/host-events.ts";
9
+ import { quarantineCandidate } from "../store/quarantine/quarantine.ts";
10
+ import { redactSecrets } from "../store/secrets.ts";
11
+ import { parseCandidates, parseModelRef } from "./candidates.ts";
12
+ import { lagSince } from "./lag.ts";
13
+ import { buildCapturePrompt } from "./prompt.ts";
14
+ import { flattenTranscript } from "./transcript.ts";
15
+
16
+ interface CaptureHost {
17
+ options?: Record<string, unknown>;
18
+ event?: { subscribe: (o?: { signal?: AbortSignal }) => AsyncIterable<unknown> };
19
+ generate?: { text: (input: unknown) => Promise<{ text?: string } | string> };
20
+ session?: { context?: (input: { sessionID: string }) => Promise<unknown> };
21
+ }
22
+
23
+ interface CaptureDependencies {
24
+ instanceDir: string | undefined;
25
+ gateContext: (sid?: string) => GateContext;
26
+ guarded: (name: string, fn: () => Promise<void>) => Promise<void>;
27
+ }
28
+
29
+ // Tag on store rows captured by the COMPACTION trigger (issue #41). Rows keep
30
+ // the shared "auto-capture" provenance tag (src/inject.ts renders it) and add
31
+ // this one so decay/status can tell which trigger wrote them — the same
32
+ // distinction the auto_capture_compaction_* evidence lines carry.
33
+ const CAPTURE_COMPACT_TAG = "auto_capture_compaction";
34
+
35
+ // Auto-capture cooldown, shared by EVERY setup() registration (#108): setup
36
+ // runs for more than one location, and per-closure cooldown maps made those
37
+ // registrations strangers - one compaction could pay for two model calls on
38
+ // one transcript. Same module-level shape as `turns` in src/lock.ts; the key
39
+ // names the trigger, so measuring one trigger is still not confounded by the
40
+ // other having fired moments ago.
41
+ const lastCaptureRun = new Map<string, number>();
42
+
43
+ const CAPTURE_COOLDOWN_MS = 5 * 60_000;
44
+
45
+ /** True if this trigger may fire for this session now; records the fire. */
46
+ function captureCooldownPasses(trigger: "idle" | "compaction", sid: string, now: number): boolean {
47
+ const key = `${trigger}:${sid}`;
48
+ if (now - (lastCaptureRun.get(key) ?? 0) < CAPTURE_COOLDOWN_MS) return false;
49
+ // Sessions churn and a long-lived server must not grow one entry per
50
+ // session forever; oldest-inserted go first (the ledger throttle's rule).
51
+ if (lastCaptureRun.size > 2000) {
52
+ for (const k of [...lastCaptureRun.keys()].slice(0, 1000)) lastCaptureRun.delete(k);
53
+ }
54
+ lastCaptureRun.set(key, now);
55
+ return true;
56
+ }
57
+
58
+ /** Clear the cooldown windows (tests; also what a process restart does). */
59
+ export function resetCaptureCooldowns(): void {
60
+ lastCaptureRun.clear();
61
+ }
62
+
63
+ // ---- capture trigger vocabulary (#136) -------------------------------------
64
+ // Single source of truth for capture subscriptions. Both turn-end events were
65
+ // observed on the desktop service (test/fixtures/host-events.jsonl).
66
+ // test/event-fidelity.test.ts requires every trigger to appear in both that
67
+ // recording and the installed @opencode/schema manifest: a declared event
68
+ // alone is insufficient evidence that the host emits it (#78, #136).
69
+ // Identity triggers have a separate observed check in that test, combining
70
+ // this recording with the 2.2.2 move extract in host-session-move.json (#176).
71
+ export const TURN_END_EVENTS = ["session.execution.succeeded", "session.execution.interrupted"] as const;
72
+
73
+ /** Every event type the capture subscription reacts to (fidelity-tested). */
74
+ export const CAPTURE_EVENT_TYPES: readonly string[] = [...TURN_END_EVENTS];
75
+
76
+ // `session.idle`, `session.status`, and `session.execution.failed` are declared
77
+ // but absent from that recording, so they deliberately do not trigger capture.
78
+ // Adding a trigger requires a recording; status would also need idle filtering.
79
+
80
+ /**
81
+ * True when a host event means "this session just went quiet". The internal
82
+ * trigger name stays "idle" (cooldown keys, `auto_capture_*` evidence lines and
83
+ * the historical idle-vs-compaction bench all use it).
84
+ */
85
+ export function captureTriggerFor(event: unknown): boolean {
86
+ const type = (event as { type?: unknown } | null)?.type;
87
+ return typeof type === "string" && (TURN_END_EVENTS as readonly string[]).includes(type);
88
+ }
89
+
90
+ export function configureAutoCapture(
91
+ ctx: CaptureHost,
92
+ { instanceDir, gateContext, guarded }: CaptureDependencies,
93
+ ) {
94
+ let onCompactCapture: ((sid: string, messages: unknown) => void) | undefined;
95
+ let captureCleanup: Cleanup | undefined;
96
+ if (ctx.options?.autoCapture === true) {
97
+ const captureModel =
98
+ typeof ctx.options.captureModel === "string" ? ctx.options.captureModel : "";
99
+ const captureMax = Number(ctx.options.captureMax) || 3;
100
+ const captureOnCompact = ctx.options?.captureOnCompact !== false;
101
+ const modelRef = parseModelRef(captureModel);
102
+ if (!modelRef) {
103
+ // Invalid/missing model: skip registering the whole subscription
104
+ // rather than guess (and warn once, at setup).
105
+ console.warn(
106
+ `[opencode-self-improvement] autoCapture is on but captureModel ${JSON.stringify(captureModel)} is invalid (expected "provider/id"); auto-capture disabled.`,
107
+ );
108
+ } else if (!ctx.event?.subscribe || !ctx.generate?.text || !ctx.session?.context) {
109
+ console.warn(
110
+ "[opencode-self-improvement] autoCapture is on but this OpenCode context lacks event.subscribe/generate.text/session.context; auto-capture disabled.",
111
+ );
112
+ } else {
113
+ const controller = new AbortController();
114
+ const eventApi = ctx.event;
115
+ const generateApi = ctx.generate;
116
+ // Arrow wrapper: keep the receiver bound. The harness fakes are closures,
117
+ // but a real client method that reads `this` would break if detached —
118
+ // and the fail-closed catch below would hide it. Optional call: the
119
+ // setup guard proves it exists, but property narrowing does not survive
120
+ // into the closure, and undefined degrades safely (empty transcript).
121
+ const contextFn = (input: { sessionID: string }) => ctx.session?.context?.(input);
122
+
123
+ // ONE capture pass, shared by both triggers. `seeded` is a transcript
124
+ // already in hand — the compaction hook carries the PRE-compaction
125
+ // messages, which is the whole point (Compaction Cliff: one round
126
+ // retains 53% of exact-wording rules); when it is absent (older host
127
+ // shapes) or too thin, the session context is read instead, the same
128
+ // source the idle trigger mines.
129
+ async function captureSession(
130
+ sid: string,
131
+ seeded: string,
132
+ trigger: "idle" | "compaction",
133
+ seededMsgs?: unknown,
134
+ ): Promise<void> {
135
+ // Bind the capturing session for the synchronous stretches of this
136
+ // path - but NOT as a promise: the awaits below let another session
137
+ // move current, so the gate context and the persisted rows thread
138
+ // `sid` explicitly instead of reading it back from the global (#116).
139
+ setCurrent({ sessionID: sid });
140
+ // The capture's dedup reads and the rows it writes partition by the
141
+ // CAPTURED session's repository — an unbound sid would otherwise
142
+ // read global-only and mine duplicates into the store (#127; in
143
+ // production the prompt hook already bound it firmly, so this is a
144
+ // no-op there). SYNC only: a lookup call here would break the
145
+ // zero-token promise of the capture tests.
146
+ bindSessionProvisional(sid, instanceDir);
147
+ const captureGate = gateContext(sid);
148
+ // #152: an instance with no workspace cannot say which repository the
149
+ // mined rows belong to, and rows with no owner are exactly what the
150
+ // store refuses. Skip BEFORE the model call — no tokens spent on a
151
+ // capture that cannot be stored — and leave the reason in evidence.
152
+ if (!writeTarget(sid).ok) {
153
+ await record("auto_capture_refused", { session: sid, trigger }, true, sid, captureGate.evidenceContext);
154
+ return;
155
+ }
156
+ let transcript = seeded;
157
+ let msgs = seededMsgs;
158
+ if (transcript.length < 200) {
159
+ msgs = await contextFn({ sessionID: sid });
160
+ transcript = flattenTranscript(msgs);
161
+ }
162
+ if (transcript.length < 200) return; // too thin to mine reliably
163
+ // #44: how stale is a capture? Distance from the newest message of
164
+ // the mined transcript to this instant - measured on whatever the
165
+ // trigger actually mined (the hook payload for compaction, the
166
+ // session context for idle), so both triggers' lag is comparable.
167
+ const lagMs = lagSince(msgs);
168
+ const out = await generateApi.text({
169
+ model: modelRef,
170
+ // Redact the COMPLETE transcript, THEN apply the character budget
171
+ // (#132). Cropping first can start the window INSIDE a credential:
172
+ // a PEM body whose BEGIN marker fell off, or a token whose prefix
173
+ // fell off, matches no pattern — buildCapturePrompt's own scrub
174
+ // (kept, defense in depth) cannot recognize a fragment.
175
+ prompt: buildCapturePrompt(redactSecrets(transcript).slice(-8000), captureMax),
176
+ });
177
+ const text = typeof out === "string" ? out : out?.text ?? "";
178
+ const candidates = parseCandidates(text, captureMax);
179
+ for (const c of candidates) {
180
+ const durable: string[] = [];
181
+ let outcome: Awaited<ReturnType<typeof runWriteGate>>;
182
+ try {
183
+ outcome = await runWriteGate(
184
+ quarantineCandidate({
185
+ ...c,
186
+ tags:
187
+ trigger === "compaction"
188
+ ? ["auto-capture", CAPTURE_COMPACT_TAG]
189
+ : ["auto-capture"],
190
+ }),
191
+ { ...captureGate, durable },
192
+ );
193
+ } catch (err) {
194
+ // A refused write must not disappear into the hook's fail-soft
195
+ // wrapper. Preserve any earlier gate retirements in the receipt.
196
+ await record(durable.length ? "auto_capture_partial" : "auto_capture_refused", {
197
+ session: sid, trigger, type: c.type, scope: redactSecrets(c.scope),
198
+ reason: String(err), retired: durable.join(",") || undefined,
199
+ }, false, sid, captureGate.evidenceContext);
200
+ continue;
201
+ }
202
+ await record(
203
+ trigger === "compaction"
204
+ ? `auto_capture_compaction_${outcome.action}`
205
+ : `auto_capture_${outcome.action}`,
206
+ // A blocked credential-shaped scope must not reach the evidence log either.
207
+ // The promoted line also carries the audit fault when the
208
+ // write_promoted line fell (#155 review — capture has no
209
+ // reply to caveat, so this line is the trail's only note).
210
+ {
211
+ session: sid,
212
+ trigger,
213
+ type: c.type,
214
+ scope: redactSecrets(c.scope),
215
+ reason: outcome.reason ?? "",
216
+ audit_error: outcome.evidenceError,
217
+ },
218
+ false,
219
+ sid,
220
+ captureGate.evidenceContext,
221
+ );
222
+ }
223
+ await recordCaptureLag(sid, lagMs, candidates.length ? "candidates" : "empty", captureGate.evidenceContext);
224
+ }
225
+
226
+ void (async () => {
227
+ try {
228
+ for await (const raw of eventApi.subscribe({ signal: controller.signal })) {
229
+ if (!captureTriggerFor(raw)) continue;
230
+ const sid = captureSessionID(raw);
231
+ if (sid === undefined) continue;
232
+ setCurrent({ sessionID: sid });
233
+ const now = Date.now();
234
+ if (!captureCooldownPasses("idle", sid, now)) continue; // 5-min cooldown, shared across setups
235
+ try {
236
+ await captureSession(sid, "", "idle");
237
+ } catch {
238
+ // fail-closed: a broken capture attempt is invisible to the session
239
+ }
240
+ }
241
+ } catch {
242
+ // the subscription itself ended (abort or host error); nothing to do
243
+ }
244
+ })();
245
+ captureCleanup = () => controller.abort();
246
+
247
+ // The compaction trigger needs no extra subscription: the session
248
+ // compaction hook (registered above) calls through this seam. The
249
+ // cooldown names the trigger, so measuring a compaction capture is
250
+ // not confounded by an idle fire moments before - and lives at
251
+ // module level, so a second setup() cannot double-pay one
252
+ // compaction (#108).
253
+ if (captureOnCompact) {
254
+ onCompactCapture = (sid, messages) => {
255
+ if (controller.signal.aborted) return;
256
+ const now = Date.now();
257
+ if (!captureCooldownPasses("compaction", sid, now)) return; // 5-min cooldown
258
+ void guarded("session.compaction (auto-capture)", () =>
259
+ captureSession(sid, flattenTranscript(messages), "compaction", messages),
260
+ );
261
+ };
262
+ }
263
+ }
264
+ } else if (ctx.options?.captureOnCompact === true) {
265
+ // autoCapture is the master switch (zero-token default preserved).
266
+ console.warn(
267
+ "[opencode-self-improvement] captureOnCompact is on but autoCapture is off; compaction capture stays disabled (autoCapture is the master switch).",
268
+ );
269
+ }
270
+ return { onCompactCapture, cleanup: captureCleanup };
271
+ }
@@ -0,0 +1,9 @@
1
+ // Fail-soft wrapper for plugin bookkeeping hooks (#168).
2
+ export async function guarded(name: string, fn: () => Promise<void>): Promise<void> {
3
+ try {
4
+ await fn();
5
+ } catch (err) {
6
+ console.warn(`[opencode-self-improvement] ${name} hook failed (ignored):`, err);
7
+ }
8
+ }
9
+
@@ -0,0 +1,34 @@
1
+ // Structural subset of the OpenCode host used by setup and hook wiring (#168).
2
+ interface ToolDef {
3
+ name: string;
4
+ description: string;
5
+ input: Record<string, unknown>;
6
+ options?: { codemode?: boolean; namespace?: string };
7
+ execute: (args: any, context: any) => Promise<{ content: string }>;
8
+ }
9
+ interface ToolEditorLike {
10
+ add: (tool: ToolDef) => void;
11
+ }
12
+ interface HookReg {
13
+ dispose?: () => Promise<void> | void;
14
+ }
15
+ export interface PluginCtx {
16
+ location?: { directory?: string };
17
+ options?: Record<string, unknown>;
18
+ tool?: {
19
+ transform: (cb: (editor: ToolEditorLike) => void) => Promise<unknown>;
20
+ hook: (name: string, cb: (event: any) => Promise<void> | void) => Promise<HookReg | void>;
21
+ };
22
+ session?: {
23
+ hook: (name: string, cb: (event: any) => Promise<void> | void) => Promise<HookReg | void>;
24
+ context?: (input: { sessionID: string }) => Promise<unknown>;
25
+ get?: (input: { sessionID: string }) => Promise<unknown>;
26
+ };
27
+ event?: {
28
+ subscribe: (o?: { signal?: AbortSignal }) => AsyncIterable<unknown>;
29
+ };
30
+ generate?: {
31
+ text: (input: unknown) => Promise<{ text?: string } | string>;
32
+ };
33
+ }
34
+
package/src/events.ts ADDED
@@ -0,0 +1,223 @@
1
+ // Host hook registration and measured-usage listener (#168). Setup owns the
2
+ // returned controller and supplies the live compaction-capture callback.
3
+ import type { PluginCtx } from "./core/host.ts";
4
+ import type { guarded as Guarded } from "./core/hooks.ts";
5
+ import type { createInjectionEpochs } from "./inject/epochs.ts";
6
+ import type { Measured } from "./status/payload.ts";
7
+ import type { HitSource } from "./hits/ledger.ts";
8
+ import type { Memory } from "./store/model/memory.ts";
9
+ import { useSignals } from "./hits/ledger.ts";
10
+ import { setCurrent } from "./core/state.ts";
11
+ import { bindSessionProvisional, rememberSessionDir } from "./identity/repokey.ts";
12
+ import { sessionIdentityEvent, sessionUsageEvent } from "./identity/host-events.ts";
13
+ import { afterTool, markTurn, checkNewSession, onCompacting } from "./capture/triggers.ts";
14
+ import { contextualPull } from "./inject/pull.ts";
15
+ import { pullQuery } from "./recall/relevant.ts";
16
+ import { compactionAnchor } from "./inject/anchor.ts";
17
+
18
+ interface HookDependencies {
19
+ guarded: typeof Guarded;
20
+ sessions: ReturnType<typeof createInjectionEpochs>;
21
+ instanceDir: string | undefined;
22
+ budget: number;
23
+ noteHits: (src: HitSource, sid: string, rows: Memory[], query: string) => Promise<void>;
24
+ bindSessionIdentity: (sid: string | undefined) => Promise<void>;
25
+ bindSessionFromApi: (sid: string | undefined) => Promise<void>;
26
+ measuredTurns: Map<string, Measured>;
27
+ flushStatus: (sid: string) => Promise<void>;
28
+ getCompactCapture: () => ((sid: string, messages: unknown) => void) | undefined;
29
+ }
30
+
31
+ // Best-effort extraction of a tool's textual output + metadata from the V2
32
+ // execute.after `result` payload, whose exact encoding varies by tool.
33
+ function resultText(result: unknown): string {
34
+ if (typeof result === "string") return result;
35
+ if (!result || typeof result !== "object") return "";
36
+ const r = result as Record<string, unknown>;
37
+ for (const k of ["output", "text", "content", "stdout"]) {
38
+ const v = r[k];
39
+ if (typeof v === "string") return v;
40
+ }
41
+ if (Array.isArray(r.content)) {
42
+ return (r.content as Array<Record<string, unknown>>)
43
+ .map((c) => (typeof c?.text === "string" ? c.text : ""))
44
+ .filter(Boolean)
45
+ .join("\n");
46
+ }
47
+ return "";
48
+ }
49
+ function resultMeta(result: unknown): Record<string, unknown> {
50
+ if (result && typeof result === "object") {
51
+ const m = (result as Record<string, unknown>).metadata;
52
+ if (m && typeof m === "object") return m as Record<string, unknown>;
53
+ }
54
+ return {};
55
+ }
56
+
57
+ export async function registerHooks(
58
+ ctx: PluginCtx,
59
+ { guarded, sessions, instanceDir, budget, noteHits, bindSessionIdentity,
60
+ bindSessionFromApi, measuredTurns, flushStatus, getCompactCapture }: HookDependencies,
61
+ ) {
62
+ // Bookkeeping: track the active session/tool/call before a tool runs.
63
+ await ctx.tool?.hook("execute.before", (event: any) =>
64
+ guarded("tool.execute.before", async () => {
65
+ setCurrent({
66
+ sessionID: event?.sessionID,
67
+ callID: event?.callID ?? event?.id,
68
+ tool: event?.tool,
69
+ });
70
+ }),
71
+ );
72
+
73
+ await ctx.tool?.hook("execute.after", (event: any) =>
74
+ guarded("tool.execute.after", async () => {
75
+ const input = {
76
+ tool: event?.tool,
77
+ sessionID: event?.sessionID,
78
+ callID: event?.callID ?? event?.id,
79
+ args: event?.input,
80
+ };
81
+ setCurrent(input);
82
+ // Evidence lines written below stamp the RECORDING repository. Bind
83
+ // an unbound caller to this instance first (SYNC provisional; the
84
+ // prompt hook / events bind firmly in production) so a tool_result
85
+ // can never carry another instance's stamp (#127).
86
+ if (typeof event?.sessionID === "string") {
87
+ bindSessionProvisional(event.sessionID, instanceDir);
88
+ }
89
+ const out = { output: resultText(event?.result), metadata: resultMeta(event?.result) };
90
+ await afterTool(input, out);
91
+ const pulled = await contextualPull(input, out as { output?: unknown }, budget, await useSignals());
92
+ if (pulled.length) await noteHits("pull", String(event?.sessionID ?? ""), pulled, pullQuery(input.args));
93
+ // Write a contextual-pull append back when the tool result is text we own.
94
+ if (event?.result && typeof event.result === "object" && typeof event.result.content === "string") {
95
+ const text = resultText(event.result);
96
+ if (out.output && out.output !== text) event.result.content = out.output;
97
+ }
98
+ }),
99
+ );
100
+
101
+ // Tiny system digest + open-thread frontier block, injected into the system prompt.
102
+ await ctx.session?.hook("context", (event: any) =>
103
+ guarded("session.context (systemDigest)", async () => {
104
+ // Route store reads in this hook through the right session's scope:
105
+ // the sid is captured from the event BEFORE any await and carried
106
+ // explicitly — the global current set here is legacy bookkeeping
107
+ // only, never the identity this flow filters with (#127).
108
+ const sid = typeof event?.sessionID === "string" ? event.sessionID : undefined;
109
+ setCurrent({ sessionID: event?.sessionID });
110
+ if (typeof sid === "string") sessions.touch(sid);
111
+ // Resolve WHOSE repository this injection reads before the store
112
+ // read below: an unbound session would otherwise fall to global-only
113
+ // and silently lose its own frontier rows. SYNC provisional bind to
114
+ // this instance's workspace — the prompt hook (or an event) has
115
+ // already bound firmly in production, so no host lookup belongs in
116
+ // this hot path (#127).
117
+ if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
118
+ await sessions.deliver(sid, (text) => event?.system?.push?.({ type: "text", text }));
119
+ }),
120
+ );
121
+
122
+ // Memory-first injection, frozen per epoch (cache-safe). Remember the
123
+ // latest user prompt here; the request-time context hook builds or
124
+ // invalidates the epoch immediately before delivery. Relevance staleness
125
+ // is accepted while the injectable rows stay unchanged, preserving a
126
+ // stable system prefix across ordinary turns.
127
+ // Never mutate event.prompt.text — it is stored verbatim and rendered in
128
+ // the UI.
129
+ await ctx.session?.hook("prompt", (event: any) =>
130
+ guarded("session.prompt (inject)", async () => {
131
+ setCurrent({ sessionID: event?.sessionID });
132
+ const sid = event?.sessionID;
133
+ if (typeof sid === "string") {
134
+ sessions.touch(sid);
135
+ markTurn(sid);
136
+ await checkNewSession(sid);
137
+ await bindSessionIdentity(sid);
138
+ await sessions.prompt(sid, event?.prompt?.text ?? "");
139
+ }
140
+ }),
141
+ );
142
+
143
+ // Session-convergence rollup at compaction. The epoch is dropped so the
144
+ // next prompt re-scores against the post-compaction store. Memory-aware
145
+ // compaction: the durable-memory anchor is pushed onto the hook's system
146
+ // parts (visible to the summarizer model, which runs AFTER hooks) so the
147
+ // summary preserves the facts. Never sets event.result — that would skip
148
+ // the summarizer call entirely. Also fires the context-death auto-capture
149
+ // (issue #41, opt-in; see the capture section): the transcript is mined
150
+ // while it still exists, BEFORE the summarizer replaces it.
151
+ await ctx.session?.hook("compaction", (event: any) =>
152
+ guarded("session.compaction (onCompacting)", async () => {
153
+ const sid = typeof event?.sessionID === "string" ? event.sessionID : undefined;
154
+ setCurrent({ sessionID: event?.sessionID });
155
+ // The anchor read and the capture pass below partition by the session's
156
+ // repository; SYNC provisional bind only — a host lookup from this
157
+ // hook would violate the zero-token promise (#127, see capture).
158
+ if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
159
+ await onCompacting({ sessionID: event?.sessionID });
160
+ if (typeof event?.sessionID === "string") {
161
+ sessions.invalidate(event.sessionID);
162
+ }
163
+ const anchor = await compactionAnchor(12, sid);
164
+ if (anchor) event?.system?.push?.({ type: "text", text: anchor });
165
+ // Fire-and-forget: a capture model call must never delay the compaction
166
+ // the user is waiting for, and failures stay inside the guarded path.
167
+ // The payload's own messages ride along so the mining sees the
168
+ // pre-compaction transcript even if the store moves under it.
169
+ const onCompactCapture = getCompactCapture();
170
+ if (onCompactCapture && sid) {
171
+ onCompactCapture(sid, event.messages);
172
+ }
173
+ }),
174
+ );
175
+
176
+ // ---- measured prompt-cache health (usage events) -----------------------
177
+ // Zero-model by design: usage arrives on `session.usage.updated` (v2 hosts)
178
+ // or `message.updated` assistant info (older hosts), carrying tokens
179
+ // {input, output, reasoning, cache.read/write}; the session-wide
180
+ // read/(read+input+write) share is the honest receipt behind the
181
+ // byte-stability proxy. Streaming updates arrive repeatedly — overwriting
182
+ // with the latest is correct because the final update carries the complete
183
+ // usage. Flushes the per-session status file so the TUI badge refreshes
184
+ // once per turn instead of per step. Degrades to "not measured" when the
185
+ // host exposes no event stream.
186
+ const measuredController = new AbortController();
187
+ if (ctx.event?.subscribe) {
188
+ const eventApi = ctx.event;
189
+ void (async () => {
190
+ try {
191
+ for await (const raw of eventApi.subscribe({ signal: measuredController.signal })) {
192
+ // Session identity: created fires for new sessions, execution.started
193
+ // every turn (covers sessions resumed across a restart), moved on a
194
+ // workspace change. Stamps and visibility resolve through this.
195
+ const identity = sessionIdentityEvent(raw);
196
+ if (identity) {
197
+ const { sessionID: sid, directory: dir } = identity;
198
+ if (dir !== undefined) rememberSessionDir(sid, dir);
199
+ // 2.1.4 serve sends execution.started with no location at all:
200
+ // resolve the session row instead of leaving the session unbound.
201
+ else void guarded("session bind (api)", () => bindSessionFromApi(sid));
202
+ continue;
203
+ }
204
+ const usage = sessionUsageEvent(raw);
205
+ if (!usage) continue;
206
+ const { sessionID, input, read, write } = usage;
207
+ sessions.touch(sessionID);
208
+ measuredTurns.set(sessionID, {
209
+ at: new Date().toISOString(),
210
+ input,
211
+ read,
212
+ write,
213
+ });
214
+ await guarded("status flush (measured)", () => flushStatus(sessionID));
215
+ }
216
+ } catch {
217
+ // the subscription ended (abort or host error); nothing to do
218
+ }
219
+ })();
220
+ }
221
+
222
+ return measuredController;
223
+ }