@eocrm/cli 0.0.1-bootstrap.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/run.mjs ADDED
@@ -0,0 +1,560 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { appendFileSync, closeSync, fstatSync, openSync, readSync, readdirSync, renameSync, statSync } from 'node:fs';
3
+ import { basename, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { createHash } from 'node:crypto';
6
+ import { withLock, git, worktreeOf, stampHook, loadWorktree, saveWorktree, loadRun, saveRun, remove, readJson, writeJsonAtomic, LockTimeout, liveDirOf, markLive, clearLive } from './state.mjs';
7
+ import { append, enqueue, rewrite } from './outbox.mjs';
8
+ import { clientRunId } from './flush.mjs';
9
+ import { resolveWorkspace, committedLine } from './workspace.mjs';
10
+ import { budget, repoSlug } from './git.mjs';
11
+ import { detector, subagentFinish, taskFor, TASK_KEY } from './detect.mjs';
12
+ import { clean } from './scrub.mjs';
13
+ import { endpoints } from './endpoints.mjs';
14
+ import { createClient } from './api.mjs';
15
+ import { storeFor } from './credentials.mjs';
16
+ import { reconcile } from './reconcile.mjs';
17
+ import { parseTodos, relPath } from './plans.mjs';
18
+ import { stopGate } from './gate.mjs';
19
+ import { eventId } from './ids.mjs';
20
+ import { fileCwd, readSession, sizesOf, transcriptFiles } from './usage.mjs';
21
+ import { codexEvents, addModelUsage } from './codex.mjs';
22
+ import { remind, linkedLine } from './remind.mjs';
23
+
24
+ export const LINK_ASK = 'eocrm: this session isn\'t linked to a task. Ask the member once which task key it is for (or "none"), then use the eocrm link-run skill.';
25
+ const HEARTBEAT_MS = 120000;
26
+ const LOG_MAX = 256 * 1024;
27
+ const TRANSCRIPT_TAIL = 256 * 1024;
28
+ const SESSION_END_LOCK_MS = 500;
29
+ // Under SessionStart's 10 s hook timeout.
30
+ const SESSION_START_MS = 8000;
31
+ const LOCK_MS = 1500;
32
+ const PRUNE_MS = 7 * 24 * 3600 * 1000;
33
+ const TOMBSTONE_MS = 90 * 24 * 3600 * 1000;
34
+ const MAX_RUNS_READ = 50;
35
+ export const TEST_HINT = 'When a shell command runs tests, start its description with `test:` (Codex: end the command with `# eocrm:test`).';
36
+ const NEW_SESSION = new Set(['startup', 'clear']);
37
+ const LINKED_LINE_SOURCES = new Set(['startup', 'resume', 'clear']);
38
+ const TOOL_EVENTS = new Set(['PreToolUse', 'PostToolUse', 'PostToolUseFailure']);
39
+ const RECONCILE_EVERY_MS = 5 * 60 * 1000;
40
+ const RECONCILE_MS = { SessionStart: 3000, Stop: 10000, PostToolUse: 10000 };
41
+ const KEEP_WRITTEN = 50;
42
+ const KEEP_ACKED_BEFORE = 5000;
43
+ const WRITES = new Set(['Write', 'Edit', 'MultiEdit']);
44
+ const TODOS = new Set(['TodoWrite', 'TaskCreate', 'TaskUpdate']);
45
+ const LEDGER_FILE = /^\.superpowers\/sdd\/[^/]+\/progress\.md$/;
46
+ const WAITING = { permission_prompt: 'permission', idle_prompt: 'idle' };
47
+ const DISPATCH = fileURLToPath(new URL('../hooks/dispatch.mjs', import.meta.url));
48
+
49
+ export function logError(data, error) {
50
+ try {
51
+ const file = join(data, 'plugin.log');
52
+ try {
53
+ if (statSync(file).size > LOG_MAX) renameSync(file, `${file}.1`);
54
+ } catch {
55
+ // no log yet
56
+ }
57
+ appendFileSync(file, `${new Date().toISOString()} ${clean(String(error?.stack ?? error), 4000)}\n`);
58
+ } catch {
59
+ // nowhere left to report
60
+ }
61
+ }
62
+
63
+ export function spawnFlush(ctx) {
64
+ try {
65
+ (ctx.spawn ?? spawn)(process.execPath, [DISPATCH, 'flush', '--data', ctx.data, ...(ctx.harness === 'codex' || ctx.harness === 'cli' ? ['--harness', ctx.harness] : [])], { detached: true, stdio: 'ignore', windowsHide: true, env: ctx.env })
66
+ .on('error', (e) => logError(ctx.data, e))
67
+ .unref();
68
+ } catch (e) {
69
+ logError(ctx.data, e);
70
+ }
71
+ }
72
+
73
+ export const waitMs = (cap, end) => (end === undefined ? cap : Math.max(1, Math.min(cap, end - Date.now())));
74
+
75
+ export function runClient(ctx, { timeoutMs, end } = {}) {
76
+ const store = ctx.store ?? storeFor(ctx.data, ctx.harness);
77
+ const hookStore = { get: (key) => store.get(key, { timeoutMs: waitMs(2500, end) }), update: (key, fn) => store.update(key, fn, { timeoutMs: waitMs(2500, end) }) };
78
+ return (run) => createClient({ endpoints: endpoints({ region: run.region, env: ctx.env }), workspace: run.workspace, store: hookStore, harness: ctx.harness, agent: run.start?.agent_kind, lockTimeoutMs: waitMs(2500, end), ...(timeoutMs ? { timeoutMs } : {}) });
79
+ }
80
+
81
+ function transcriptModel(path) {
82
+ if (typeof path !== 'string' || !path) return null;
83
+ let text;
84
+ try {
85
+ const fd = openSync(path, 'r');
86
+ try {
87
+ const size = fstatSync(fd).size;
88
+ const buf = Buffer.alloc(Math.min(size, TRANSCRIPT_TAIL));
89
+ readSync(fd, buf, 0, buf.length, size - buf.length);
90
+ text = buf.toString('utf8');
91
+ } finally {
92
+ closeSync(fd);
93
+ }
94
+ } catch {
95
+ return null;
96
+ }
97
+ const lines = text.split('\n');
98
+ for (let i = lines.length - 1; i >= 0; i--) {
99
+ if (!lines[i].includes('"assistant"')) continue;
100
+ try {
101
+ const o = JSON.parse(lines[i]);
102
+ const model = o?.message?.model;
103
+ // <synthetic> marks Claude Code's own error/placeholder turns, not a model.
104
+ if (o.type === 'assistant' && !o.isSidechain && typeof model === 'string' && model && model !== '<synthetic>') return model;
105
+ } catch {
106
+ // a partial first line of the tail
107
+ }
108
+ }
109
+ return null;
110
+ }
111
+
112
+ export function linkContext(worktree, branch, worktreeRoot) {
113
+ if (worktree.taskKey || worktree.linkAnswered) return null;
114
+ if (TASK_KEY.test(branch ?? '') || TASK_KEY.test(basename(worktreeRoot ?? ''))) return null;
115
+ return LINK_ASK;
116
+ }
117
+
118
+ // Reads only the newest runs; a sweep also finishes runs idle past PRUNE_MS and deletes them once settled.
119
+ export function runsOf(data, worktreeKey, sweep) {
120
+ const dir = join(data, 'runs');
121
+ let files;
122
+ try {
123
+ files = readdirSync(dir).filter((n) => n.endsWith('.json')).flatMap((n) => {
124
+ try {
125
+ return [{ sid: n.slice(0, -5), mtime: statSync(join(dir, n)).mtimeMs }];
126
+ } catch {
127
+ return [];
128
+ }
129
+ });
130
+ } catch {
131
+ return [];
132
+ }
133
+ files.sort((a, b) => b.mtime - a.mtime);
134
+ const runs = [];
135
+ for (const [i, f] of files.entries()) {
136
+ const old = sweep && f.sid !== sweep.sid && sweep.at - f.mtime > PRUNE_MS;
137
+ if (i >= MAX_RUNS_READ && !old) continue;
138
+ let run;
139
+ try {
140
+ run = loadRun(data, f.sid);
141
+ } catch {
142
+ continue;
143
+ }
144
+ if (old && !run.ended) {
145
+ saveRun(data, f.sid, { ended: true });
146
+ append(data, { kind: 'finish', sessionId: f.sid });
147
+ } else if (old && !sweep.busy.has(f.sid)) {
148
+ tombstone(data, f.sid, run.generation ?? 0, sweep.at);
149
+ remove(join(dir, `${f.sid}.json`));
150
+ remove(join(data, 'paths', `${f.sid}.json`));
151
+ }
152
+ else if (!old && run.worktreeKey === worktreeKey) runs.push(run);
153
+ }
154
+ return runs;
155
+ }
156
+
157
+ const tombstones = (data) => join(data, 'generations.json');
158
+
159
+ // A pruned run's generation outlives its file, so a later resume never reuses an ended client_run_id.
160
+ function tombstone(data, sid, generation, at) {
161
+ const kept = Object.entries(readJson(tombstones(data), {})).filter(([, t]) => at - t.at <= TOMBSTONE_MS);
162
+ writeJsonAtomic(tombstones(data), { ...Object.fromEntries(kept), [sid]: { generation, at } });
163
+ }
164
+
165
+ export function gather(data, cwd) {
166
+ const wt = worktreeOf(cwd);
167
+ const origin = git(cwd, ['remote', 'get-url', 'origin']);
168
+ const branch = git(cwd, ['symbolic-ref', '--short', '-q', 'HEAD']);
169
+ return { wt, origin, branch, ws: resolveWorkspace({ data, cwd, wt, origin }) };
170
+ }
171
+
172
+ const isFinishOf = (sid) => (e) => e.sessionId === sid && e.kind === 'finish';
173
+ const placeOf = (ws) => `${ws.region} ${ws.workspace}`;
174
+ const elsewhere = (run, ws) => Boolean(run.workspace && ws.workspace) && placeOf(run) !== placeOf(ws);
175
+
176
+ export async function ensureRun(ctx, input, facts = gather(ctx.data, input.cwd)) {
177
+ const { data } = ctx;
178
+ const sid = input.session_id;
179
+ loadRun(data, sid);
180
+ const { wt, origin, branch, ws } = facts;
181
+ if (!ws.workspace || !ws.region) return null;
182
+ const repo = repoSlug(input.cwd, origin);
183
+ const { taskKey } = loadWorktree(data, wt.key);
184
+ const place = { ...(branch ? { branch } : {}), worktree: basename(wt.root), ...(repo ? { repo } : {}), ...(ctx.agent ? { agent_kind: ctx.agent } : {}) };
185
+ const at = ctx.now();
186
+ const liveDir = ctx.harness === 'cli' ? null : liveDirOf(input.cwd);
187
+ let left = null;
188
+ const run = await withLock(data, async () => {
189
+ let pending = [];
190
+ rewrite(data, (entries) => {
191
+ pending = entries;
192
+ return entries.filter((e) => !isFinishOf(sid)(e));
193
+ });
194
+ const busy = new Set(pending.map((e) => e.sessionId));
195
+ for (const other of runsOf(data, wt.key, { sid, at, busy })) {
196
+ if (other.sessionId === sid || other.ended || !facts.newSession) continue;
197
+ if (other.liveDir) clearLive(other.liveDir, other.sessionId);
198
+ saveRun(data, other.sessionId, { ended: true });
199
+ append(data, { kind: 'finish', sessionId: other.sessionId });
200
+ }
201
+ const prev = loadRun(data, sid);
202
+ const where = placeOf(ws);
203
+ const moved = Boolean(prev.startedAt) && (prev.workspace !== ws.workspace || prev.region !== ws.region);
204
+ const finished = prev.ended && !pending.some(isFinishOf(sid));
205
+ const linked = (prev.linkedFor ?? (prev.workspace ? placeOf(prev) : where)) !== where ? undefined : prev.linkedTask;
206
+ const task = linked !== undefined ? linked : prev.startedAt && !moved ? (prev.start?.task ?? null) : taskKey;
207
+ const start = { ...(task ? { task } : {}), ...place };
208
+ let patch = {};
209
+ const reopened = prev.ended && (finished || Boolean(prev.runId));
210
+ if ((moved || reopened) && prev.startedAt && !finished) {
211
+ const old = `${sid}--w${prev.generation ?? 0}`;
212
+ saveRun(data, old, { ...prev, sessionId: old, owner: sid, ended: true });
213
+ rewrite(data, (entries) => entries.map((e) => (e.sessionId === sid ? { ...e, sessionId: old } : e)));
214
+ append(data, { ...pending.find(isFinishOf(sid)), kind: 'finish', sessionId: old });
215
+ }
216
+ if (!prev.startedAt) {
217
+ const buried = readJson(tombstones(data), {})[sid];
218
+ const generation = Number.isInteger(buried?.generation) ? buried.generation + 1 : 0;
219
+ patch = { generation, clientRunId: clientRunId(sid, generation), startedAt: at, activeSince: at };
220
+ if (buried && typeof input.transcript_path === 'string') patch.usageOffsets = sizesOf(input.transcript_path);
221
+ }
222
+ else if (moved || reopened) {
223
+ const generation = (prev.generation ?? 0) + 1;
224
+ const ackedBefore = moved ? {} : Object.fromEntries(Object.entries({ ...prev.ackedBefore, ...prev.acked }).slice(-KEEP_ACKED_BEFORE));
225
+ patch = { generation, clientRunId: clientRunId(sid, generation), activeSince: at, runId: null, acked: {}, ackedBefore, serverEventsRead: false, conventions: null, conventionsAt: null, startHead: null, ownCommits: [], model: null, modelChanges: 0, waiting: false, ...(moved ? { ackPending: [] } : {}) };
226
+ }
227
+ if (moved || prev.linkedTask === undefined) Object.assign(patch, { linkedTask: task ?? null, linkedFor: where });
228
+ if (input.source === 'resume') patch.activeSince = at;
229
+ if (prev.liveDir && prev.liveDir !== liveDir) left = prev.liveDir;
230
+ const next = saveRun(data, sid, { ...patch, ended: false, startBlocked: null, start, workspace: ws.workspace, region: ws.region, worktreeKey: wt.key, cwd: input.cwd, ...(liveDir ? { liveDir } : {}) });
231
+ if (next.runId) return next;
232
+ append(data, { kind: 'start', sessionId: sid });
233
+ return saveRun(data, sid, { lastHeartbeatAt: at });
234
+ }, { giveUpMs: LOCK_MS });
235
+ try {
236
+ if (left) clearLive(left, sid);
237
+ if (liveDir) markLive(liveDir, sid, at);
238
+ } catch (e) {
239
+ logError(data, e);
240
+ }
241
+ (ctx.spawnFlush ?? spawnFlush)(ctx);
242
+ return run;
243
+ }
244
+
245
+ function modelOf(input) {
246
+ return transcriptModel(input.transcript_path) ?? (typeof input.model === 'string' && input.model ? input.model : null);
247
+ }
248
+
249
+ async function tick(ctx, input, detected = () => false, { spawn = true, end } = {}) {
250
+ const { data } = ctx;
251
+ const sid = input.session_id;
252
+ const model = modelOf(input);
253
+ const at = ctx.now();
254
+ const task = taskFor(ctx, input);
255
+ const queued = await withLock(data, async () => {
256
+ const current = loadRun(data, sid);
257
+ if (current.ended) return false;
258
+ const task_key = task(current);
259
+ const found = detected(current, at, task_key);
260
+ const patch = {};
261
+ if (model && model !== current.model) {
262
+ const n = current.modelChanges ?? 0;
263
+ const id = `model-${createHash('sha256').update(model).digest('base64url').slice(0, 22)}-${current.generation ?? 0}-${n}`;
264
+ append(data, { kind: 'event', sessionId: sid, event: { id, type: 'usage', occurred_at: new Date(at).toISOString(), model: clean(model, 100), task_key } });
265
+ Object.assign(patch, { model, modelChanges: n + 1 });
266
+ }
267
+ if (at - (current.lastHeartbeatAt ?? 0) >= HEARTBEAT_MS) {
268
+ append(data, { kind: 'heartbeat', sessionId: sid });
269
+ patch.lastHeartbeatAt = at;
270
+ try {
271
+ if (current.liveDir) markLive(current.liveDir, sid, at);
272
+ } catch (e) {
273
+ logError(data, e);
274
+ }
275
+ }
276
+ if (!Object.keys(patch).length) return found;
277
+ saveRun(data, sid, patch);
278
+ return true;
279
+ }, { giveUpMs: waitMs(LOCK_MS, end) });
280
+ if (queued && spawn) (ctx.spawnFlush ?? spawnFlush)(ctx);
281
+ }
282
+
283
+ async function sessionStart(ctx, input) {
284
+ const end = Date.now() + SESSION_START_MS;
285
+ const facts = { ...gather(ctx.data, input.cwd), newSession: NEW_SESSION.has(input.source) };
286
+ const tracked = Boolean(facts.ws.workspace && facts.ws.region);
287
+ try {
288
+ if (await ensureRun(ctx, input, facts)) {
289
+ await tick(ctx, input, undefined, { end });
290
+ await reconcileNow(ctx, input, 'SessionStart', end);
291
+ }
292
+ } catch (e) {
293
+ if (!(e instanceof LockTimeout)) throw e;
294
+ logError(ctx.data, e);
295
+ }
296
+ const lines = [];
297
+ const worktree = loadWorktree(ctx.data, facts.wt.key);
298
+ const task = tracked ? loadRun(ctx.data, input.session_id).start?.task : null;
299
+ if (task && LINKED_LINE_SOURCES.has(input.source)) lines.push(linkedLine(task));
300
+ if (tracked && facts.branch) {
301
+ const ask = linkContext(worktree, facts.branch, facts.wt.root);
302
+ if (ask) lines.push(ask);
303
+ }
304
+ const { pending } = facts.ws;
305
+ const asked = pending && `${pending.workspace} ${pending.region}`;
306
+ if (asked && worktree.committedAsked !== asked) {
307
+ lines.push(committedLine(pending));
308
+ saveWorktree(ctx.data, facts.wt.key, { committedAsked: asked });
309
+ }
310
+ if (tracked) lines.push(TEST_HINT);
311
+ return lines.length ? { stdout: JSON.stringify({ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: lines.join('\n') } }) } : {};
312
+ }
313
+
314
+ async function endRun(ctx, input) {
315
+ const { data } = ctx;
316
+ const sid = input.session_id;
317
+ const { startedAt, liveDir } = loadRun(data, sid);
318
+ if (!startedAt) return {};
319
+ if (liveDir) clearLive(liveDir, sid);
320
+ const stamp = ctx.endedAt ? { endedAt: ctx.endedAt } : {};
321
+ let queued;
322
+ const task = ctx.harness === 'codex' ? taskFor(ctx, input) : () => null;
323
+ try {
324
+ queued = await withLock(data, async () => {
325
+ const run = loadRun(data, sid);
326
+ if (!run.startedAt || run.ended) return false;
327
+ const left = codexUsageEvents(run, input);
328
+ const occurred_at = new Date(ctx.now()).toISOString();
329
+ if (left.events.length) append(data, ...left.events.map((event) => ({ kind: 'event', sessionId: sid, event: { ...event, occurred_at, task_key: task(run) } })));
330
+ saveRun(data, sid, { ended: true, ...left.patch });
331
+ append(data, { kind: 'finish', sessionId: sid, ...stamp });
332
+ return true;
333
+ }, { giveUpMs: SESSION_END_LOCK_MS });
334
+ } catch (e) {
335
+ if (!(e instanceof LockTimeout)) throw e;
336
+ if (!loadRun(data, sid).startedAt) return {};
337
+ await enqueue(data, { kind: 'finish', sessionId: sid, ...stamp }, { giveUpMs: 0 });
338
+ queued = true;
339
+ }
340
+ if (queued) (ctx.spawnFlush ?? spawnFlush)(ctx);
341
+ return {};
342
+ }
343
+
344
+ // Records Write/Edit paths and todo state; true when the change moves the plan or ledger.
345
+ async function track(ctx, input) {
346
+ const tool = input.tool_name;
347
+ const ti = input.tool_input ?? {};
348
+ const files = (Array.isArray(ti.file_paths) ? ti.file_paths : [ti.file_path]).filter((f) => typeof f === 'string' && f !== '');
349
+ const write = WRITES.has(tool) && files.length > 0;
350
+ if (!write && !TODOS.has(tool)) return false;
351
+ const root = write ? worktreeOf(input.cwd).root : null;
352
+ return withLock(ctx.data, async () => {
353
+ const cur = loadRun(ctx.data, input.session_id);
354
+ if (!write) {
355
+ saveRun(ctx.data, input.session_id, { todos: parseTodos(input, cur.todos).todos });
356
+ return true;
357
+ }
358
+ const written = Array.isArray(cur.written) ? cur.written.filter((f) => !files.includes(f)) : [];
359
+ saveRun(ctx.data, input.session_id, { written: [...written, ...files].slice(-KEEP_WRITTEN) });
360
+ return files.some((f) => {
361
+ const rel = relPath(root, f);
362
+ return rel !== null && (LEDGER_FILE.test(rel) || rel === cur.planPath);
363
+ });
364
+ }, { giveUpMs: LOCK_MS });
365
+ }
366
+
367
+ export async function reconcileNow(ctx, input, event, end) {
368
+ const { data } = ctx;
369
+ try {
370
+ const run = await withLock(data, async () => {
371
+ const cur = loadRun(data, input.session_id);
372
+ return cur.startedAt && !cur.ended ? saveRun(data, input.session_id, { reconciledAt: ctx.now() }) : null;
373
+ }, { giveUpMs: waitMs(LOCK_MS, end) });
374
+ if (!run) return;
375
+ const deadlineMs = waitMs(RECONCILE_MS[event], end);
376
+ const clientFor = ctx.clientFor ?? runClient(ctx, { timeoutMs: Math.min(3000, deadlineMs / 2), end });
377
+ const { enqueued } = await (ctx.reconcile ?? reconcile)({ ...ctx, cwd: input.cwd, clientFor }, run, { deadlineMs });
378
+ if (enqueued && event !== 'Stop') (ctx.spawnFlush ?? spawnFlush)(ctx);
379
+ } catch (e) {
380
+ logError(data, e);
381
+ }
382
+ }
383
+
384
+ function codexUsageEvents(run, input) {
385
+ const stops = run.codexStops ?? 0;
386
+ const turnId = input.turn_id ?? (run.turns ?? 0) - 1;
387
+ const events = Object.entries(run.codexUsage ?? {})
388
+ .filter(([, c]) => Object.values(c).some((v) => v > 0))
389
+ .map(([model, c]) => ({ id: eventId('usage', `${run.sessionId}:${run.generation ?? 0}:codex:${turnId}:${stops}:${model}`), type: 'usage', model: clean(model, 100), ...c }));
390
+ return { events, patch: { codexUsage: {}, codexStops: stops + (events.length ? 1 : 0) } };
391
+ }
392
+
393
+ // Only fixed fields: the hook's message and title never leave.
394
+ // taskOf(file) is the task a transcript file's usage counts for.
395
+ export function signals(event, run, input, harness, taskOf = () => null) {
396
+ const key = `${run.sessionId}:${run.generation ?? 0}`;
397
+ const waits = run.waits ?? 0;
398
+ const turns = run.turns ?? 0;
399
+ const resumed = run.waiting ? [{ id: eventId('resumed', `${key}:${waits - 1}`), type: 'resumed' }] : [];
400
+ if (event === 'Notification') return run.waiting ? null : { events: [{ id: eventId('waiting', `${key}:${waits}`), type: 'waiting', kind: WAITING[input.notification_type] ?? 'question' }], patch: { waiting: true, waits: waits + 1 } };
401
+ if (event === 'Resume') return resumed.length ? { events: resumed, patch: { waiting: false } } : null;
402
+ if (event === 'UserPromptSubmit') return { events: [...resumed, { id: eventId('turn', `${key}:${turns}:started`), type: 'turn', phase: 'started' }], patch: { waiting: false, turns: turns + 1, codexStops: 0 } };
403
+ if (event === 'Stop' && harness === 'codex') {
404
+ const usage = codexUsageEvents(run, input);
405
+ return { events: [...resumed, { id: eventId('turn', `${key}:${turns - 1}:ended`), type: 'turn', phase: 'ended' }, ...usage.events], patch: { waiting: false, ...usage.patch } };
406
+ }
407
+ if (event === 'Stop') {
408
+ const read = typeof input.transcript_path === 'string' && input.transcript_path ? readSession(input.transcript_path, run.usageOffsets, run.usageSeen, undefined, run.usageEpochs) : { offsets: run.usageOffsets ?? {}, epochs: run.usageEpochs ?? {}, ids: [], reads: [] };
409
+ const groups = new Map();
410
+ for (const { file, from, epoch, models } of read.reads) {
411
+ for (const [model, c] of Object.entries(models)) {
412
+ if (!Object.values(c).some((n) => n > 0)) continue;
413
+ const task_key = taskOf(file);
414
+ const k = JSON.stringify([model, task_key]);
415
+ if (!groups.has(k)) groups.set(k, { model, task_key, at: [], sum: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0 } });
416
+ const g = groups.get(k);
417
+ g.at.push(`${file}:${epoch}:${from}`);
418
+ for (const n of Object.keys(g.sum)) g.sum[n] += c[n];
419
+ }
420
+ }
421
+ const usage = [...groups.values()].map((g) => ({ id: eventId('usage', `${key}:${g.at.join('|')}:${g.model}`), type: 'usage', model: clean(g.model, 100), ...g.sum, task_key: g.task_key }));
422
+ return { events: [...resumed, { id: eventId('turn', `${key}:${turns - 1}:ended`), type: 'turn', phase: 'ended' }, ...usage], patch: { waiting: false, usageOffsets: read.offsets, usageEpochs: read.epochs, usageSeen: [...(run.usageSeen ?? []), ...read.ids].slice(-200) } };
423
+ }
424
+ return null;
425
+ }
426
+
427
+ // Subagent files' tasks resolve here, outside the lock; one whose cwd is unknown counts for the session's task.
428
+ function subagentTasks(ctx, input, run) {
429
+ if (input.hook_event_name !== 'Stop' || ctx.harness === 'codex' || typeof input.transcript_path !== 'string' || !input.transcript_path) return {};
430
+ const exec = budget(4000, ctx.git);
431
+ const sizes = sizesOf(input.transcript_path);
432
+ return Object.fromEntries(transcriptFiles(input.transcript_path).slice(1).filter((f) => f in sizes && sizes[f] !== run.usageOffsets?.[f]).map((f) => {
433
+ const cwd = fileCwd(f);
434
+ return [f, cwd ? taskFor(ctx, { cwd, session_id: input.session_id }, exec) : (s) => s?.start?.task ?? null];
435
+ }));
436
+ }
437
+
438
+ function queueSignals(data, event, input, harness, subs = {}) {
439
+ return (current, at, task_key = null) => {
440
+ const s = signals(event, current, input, harness, (file) => (file === input.transcript_path ? task_key : subs[file]?.(current) ?? current.start?.task ?? null));
441
+ if (!s) return false;
442
+ const occurred_at = new Date(at).toISOString();
443
+ append(data, ...s.events.map((e) => ({ kind: 'event', sessionId: current.sessionId, event: { occurred_at, task_key, ...e } })));
444
+ saveRun(data, current.sessionId, event === 'Stop' ? { ...s.patch, lastStopAt: at } : s.patch);
445
+ return true;
446
+ };
447
+ }
448
+
449
+ async function signal(ctx, event, input) {
450
+ const run = loadRun(ctx.data, input.session_id);
451
+ if (!run.startedAt || (event === 'Resume' && !run.waiting)) return {};
452
+ const task = taskFor(ctx, input);
453
+ const queued = await withLock(ctx.data, async () => {
454
+ const run = loadRun(ctx.data, input.session_id);
455
+ return run.startedAt && !run.ended && queueSignals(ctx.data, event, input)(run, ctx.now(), task(run));
456
+ }, { giveUpMs: LOCK_MS });
457
+ if (queued) (ctx.spawnFlush ?? spawnFlush)(ctx);
458
+ return {};
459
+ }
460
+
461
+ export async function handle(event, input, ctx) {
462
+ if (ctx.harness !== 'codex') return core(event, input, ctx);
463
+ try {
464
+ stampHook(ctx.data, worktreeOf(input.cwd).key, ctx.now());
465
+ } catch (e) {
466
+ logError(ctx.data, e);
467
+ }
468
+ let out = {};
469
+ for (const c of codexEvents(event, input)) {
470
+ const r = await (ctx.core ?? core)(c.event, c.input, ctx);
471
+ if (r.stdout && !(out.stdout && JSON.parse(out.stdout).decision)) out = r;
472
+ }
473
+ return out;
474
+ }
475
+
476
+ async function core(event, input, ctx) {
477
+ if (typeof input?.cwd !== 'string') throw new Error('eocrm: hook input lacks cwd');
478
+ if (event === 'Resume' || event === 'Notification') return signal(ctx, event, input);
479
+ if (event === 'SessionEnd') return endRun(ctx, input);
480
+ if (event === 'Remind') return remind(ctx, input.hook_event_name, input);
481
+ if (event === 'SessionStart') return sessionStart(ctx, input);
482
+ if (event === 'SubagentStop') return subagentStop(ctx, input);
483
+ if (event === 'PostModelRequest') return modelUsage(ctx, input);
484
+ if (event === 'Stop') {
485
+ const out = await stopGate(ctx, input, (end) => turn(event, input, ctx, end));
486
+ if (ctx.harness === 'codex' && !out.stdout) await signal(ctx, 'Notification', { ...input, notification_type: 'idle_prompt' });
487
+ return out;
488
+ }
489
+ const t = await turn(event, input, ctx);
490
+ const due = t && event === 'PostToolUse' && ctx.now() - (loadRun(ctx.data, input.session_id).reconciledAt ?? 0) >= RECONCILE_EVERY_MS;
491
+ if (t && (t.urgent || due)) await reconcileNow(ctx, input, 'PostToolUse');
492
+ return {};
493
+ }
494
+
495
+ // Records the finish only: a subagent's stop never starts or moves the run.
496
+ async function subagentStop(ctx, input) {
497
+ const run = loadRun(ctx.data, input.session_id);
498
+ const done = run.startedAt && !run.ended && subagentFinish(input);
499
+ if (!done) return {};
500
+ const at = { ...done, cwd: run.cwd ?? input.cwd };
501
+ await tick(ctx, at, detector(ctx, at));
502
+ return {};
503
+ }
504
+
505
+ async function modelUsage(ctx, input) {
506
+ await withLock(ctx.data, async () => {
507
+ const run = loadRun(ctx.data, input.session_id);
508
+ const patch = run.startedAt && !run.ended && addModelUsage(run, input);
509
+ if (patch) saveRun(ctx.data, input.session_id, patch);
510
+ }, { giveUpMs: LOCK_MS });
511
+ return {};
512
+ }
513
+
514
+ async function turn(event, input, ctx, end) {
515
+ const run = loadRun(ctx.data, input.session_id);
516
+ if (!run.startedAt || (event === 'UserPromptSubmit' && run.ended)) {
517
+ if (!(await ensureRun(ctx, input))) return null;
518
+ } else if (!run.ended && run.worktreeKey && input.cwd !== run.cwd) {
519
+ const moved = worktreeOf(input.cwd).key !== run.worktreeKey && await ensureRun(ctx, input);
520
+ if (!moved) await withLock(ctx.data, async () => saveRun(ctx.data, input.session_id, { cwd: input.cwd }), { giveUpMs: waitMs(LOCK_MS, end) }).catch((e) => logError(ctx.data, e));
521
+ }
522
+ let urgent = false;
523
+ if (event === 'PostToolUse') {
524
+ try {
525
+ urgent = await track(ctx, input);
526
+ } catch (e) {
527
+ logError(ctx.data, e);
528
+ }
529
+ }
530
+ // Stop flushes inline in the gate.
531
+ const detected = TOOL_EVENTS.has(event) ? detector(ctx, { ...input, hook_event_name: event }) : queueSignals(ctx.data, event, input, ctx.harness, subagentTasks(ctx, { ...input, hook_event_name: event }, run));
532
+ await tick(ctx, input, detected, { spawn: event !== 'Stop', end });
533
+ return { urgent };
534
+ }
535
+
536
+ // Relinks only sessionId's run.
537
+ export async function linkWorktree(ctx, cwd, taskKey, sessionId) {
538
+ const wt = worktreeOf(cwd);
539
+ const ws = resolveWorkspace({ data: ctx.data, cwd, wt, origin: git(cwd, ['remote', 'get-url', 'origin']) });
540
+ const { queued, others, pending } = await withLock(ctx.data, async () => {
541
+ saveWorktree(ctx.data, wt.key, { root: wt.root, taskKey, linkAnswered: true });
542
+ const live = runsOf(ctx.data, wt.key).filter((r) => !r.ended);
543
+ const mine = sessionId ? loadRun(ctx.data, sessionId) : {};
544
+ let queued = false;
545
+ if (mine.startedAt) {
546
+ const start = { ...mine.start };
547
+ delete start.task;
548
+ const patch = { linkedTask: taskKey, linkedFor: placeOf(ws) };
549
+ if (!mine.ended && !elsewhere(mine, ws)) {
550
+ Object.assign(patch, { startBlocked: null, start: taskKey ? { task: taskKey, ...start } : start });
551
+ append(ctx.data, { kind: 'task', sessionId, task: taskKey });
552
+ queued = true;
553
+ }
554
+ saveRun(ctx.data, sessionId, patch);
555
+ }
556
+ return { queued, pending: mine.startedAt && elsewhere(mine, ws) ? ws.workspace : null, others: live.filter((r) => r.sessionId !== sessionId).map((r) => ({ task: r.start?.task ?? null })) };
557
+ });
558
+ if (queued) (ctx.spawnFlush ?? spawnFlush)(ctx);
559
+ return { others, pending };
560
+ }