@os-eco/overstory-cli 0.8.4 → 0.8.5

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.
@@ -0,0 +1,461 @@
1
+ /**
2
+ * Tests for the NDJSON event tailer (src/events/tailer.ts).
3
+ *
4
+ * Uses real filesystem (temp directories via mkdtemp) and real EventStore
5
+ * (bun:sqlite in-memory or temp file) per the project's "never mock what you
6
+ * can use for real" philosophy.
7
+ *
8
+ * The tailer uses setTimeout-based polling, which is exercised by letting
9
+ * timers fire naturally in async tests rather than using fake timers.
10
+ */
11
+
12
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
13
+ import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
14
+ import { tmpdir } from "node:os";
15
+ import { join } from "node:path";
16
+ import { cleanupTempDir } from "../test-helpers.ts";
17
+ import type { EventStore } from "../types.ts";
18
+ import { createEventStore } from "./store.ts";
19
+ import type { TailerHandle, TailerOptions } from "./tailer.ts";
20
+ import { findLatestStdoutLog, startEventTailer } from "./tailer.ts";
21
+
22
+ // === Helpers ===
23
+
24
+ /** Create a temp directory to use as a fake .overstory/ root. */
25
+ async function createTempDir(): Promise<string> {
26
+ return mkdtemp(join(tmpdir(), "overstory-tailer-test-"));
27
+ }
28
+
29
+ /**
30
+ * Create a fake agent log directory structure:
31
+ * <overstoryDir>/logs/<agentName>/<timestamp>/stdout.log
32
+ * Returns the path to stdout.log.
33
+ */
34
+ async function createAgentLogDir(
35
+ overstoryDir: string,
36
+ agentName: string,
37
+ timestamp = "2026-03-05T14-52-26-089Z",
38
+ ): Promise<string> {
39
+ const logDir = join(overstoryDir, "logs", agentName, timestamp);
40
+ await mkdir(logDir, { recursive: true });
41
+ const logPath = join(logDir, "stdout.log");
42
+ // Create an empty file so Bun.file().exists() returns true.
43
+ await writeFile(logPath, "");
44
+ return logPath;
45
+ }
46
+
47
+ /** Wait at most maxMs for a condition to become true, polling every pollMs. */
48
+ async function waitFor(
49
+ condition: () => boolean | Promise<boolean>,
50
+ maxMs = 3000,
51
+ pollMs = 50,
52
+ ): Promise<void> {
53
+ const deadline = Date.now() + maxMs;
54
+ while (Date.now() < deadline) {
55
+ if (await condition()) return;
56
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
57
+ }
58
+ throw new Error(`waitFor timed out after ${maxMs}ms`);
59
+ }
60
+
61
+ // === Tests ===
62
+
63
+ describe("findLatestStdoutLog", () => {
64
+ let tmpDir: string;
65
+
66
+ beforeEach(async () => {
67
+ tmpDir = await createTempDir();
68
+ });
69
+
70
+ afterEach(async () => {
71
+ await cleanupTempDir(tmpDir);
72
+ });
73
+
74
+ test("returns null when agent log directory does not exist", async () => {
75
+ const result = await findLatestStdoutLog(tmpDir, "no-such-agent");
76
+ expect(result).toBeNull();
77
+ });
78
+
79
+ test("returns null when agent log directory is empty", async () => {
80
+ const agentLogsDir = join(tmpDir, "logs", "my-agent");
81
+ await mkdir(agentLogsDir, { recursive: true });
82
+ const result = await findLatestStdoutLog(tmpDir, "my-agent");
83
+ expect(result).toBeNull();
84
+ });
85
+
86
+ test("returns null when latest dir has no stdout.log", async () => {
87
+ const logDir = join(tmpDir, "logs", "my-agent", "2026-03-05T14-52-26-089Z");
88
+ await mkdir(logDir, { recursive: true });
89
+ // Directory exists but no stdout.log inside.
90
+ const result = await findLatestStdoutLog(tmpDir, "my-agent");
91
+ expect(result).toBeNull();
92
+ });
93
+
94
+ test("returns path to stdout.log in the only session directory", async () => {
95
+ const logPath = await createAgentLogDir(tmpDir, "my-agent");
96
+ const result = await findLatestStdoutLog(tmpDir, "my-agent");
97
+ expect(result).toBe(logPath);
98
+ });
99
+
100
+ test("returns the lexicographically latest session directory", async () => {
101
+ // Create three session dirs — the last in sorted order should win.
102
+ await createAgentLogDir(tmpDir, "my-agent", "2026-03-04T10-00-00-000Z");
103
+ await createAgentLogDir(tmpDir, "my-agent", "2026-03-05T08-00-00-000Z");
104
+ const latest = await createAgentLogDir(tmpDir, "my-agent", "2026-03-05T14-52-26-089Z");
105
+ const result = await findLatestStdoutLog(tmpDir, "my-agent");
106
+ expect(result).toBe(latest);
107
+ });
108
+ });
109
+
110
+ describe("startEventTailer", () => {
111
+ let tmpDir: string;
112
+ let eventStore: EventStore;
113
+ let eventsDbPath: string;
114
+
115
+ beforeEach(async () => {
116
+ tmpDir = await createTempDir();
117
+ eventsDbPath = join(tmpDir, "events.db");
118
+ eventStore = createEventStore(eventsDbPath);
119
+ });
120
+
121
+ afterEach(async () => {
122
+ eventStore.close();
123
+ await cleanupTempDir(tmpDir);
124
+ });
125
+
126
+ test("stop() is idempotent — calling twice does not throw", async () => {
127
+ const logPath = await createAgentLogDir(tmpDir, "agent-a");
128
+ const handle = startEventTailer({
129
+ stdoutLogPath: logPath,
130
+ agentName: "agent-a",
131
+ runId: null,
132
+ eventsDbPath,
133
+ _eventStore: eventStore,
134
+ });
135
+ handle.stop();
136
+ handle.stop(); // Should not throw.
137
+ });
138
+
139
+ test("handle exposes agentName and logPath", async () => {
140
+ const logPath = await createAgentLogDir(tmpDir, "agent-b");
141
+ const handle = startEventTailer({
142
+ stdoutLogPath: logPath,
143
+ agentName: "agent-b",
144
+ runId: null,
145
+ eventsDbPath,
146
+ _eventStore: eventStore,
147
+ });
148
+ try {
149
+ expect(handle.agentName).toBe("agent-b");
150
+ expect(handle.logPath).toBe(logPath);
151
+ } finally {
152
+ handle.stop();
153
+ }
154
+ });
155
+
156
+ test("parses NDJSON lines and writes events to EventStore", async () => {
157
+ const logPath = await createAgentLogDir(tmpDir, "agent-c");
158
+
159
+ // Write some NDJSON events to the log file.
160
+ const lines = `${[
161
+ JSON.stringify({ type: "turn_start", timestamp: new Date().toISOString() }),
162
+ JSON.stringify({
163
+ type: "tool_start",
164
+ tool: "Read",
165
+ timestamp: new Date().toISOString(),
166
+ }),
167
+ JSON.stringify({
168
+ type: "tool_end",
169
+ tool: "Read",
170
+ duration_ms: 42,
171
+ timestamp: new Date().toISOString(),
172
+ }),
173
+ JSON.stringify({ type: "turn_end", timestamp: new Date().toISOString() }),
174
+ ].join("\n")}\n`;
175
+
176
+ await writeFile(logPath, lines);
177
+
178
+ const handle = startEventTailer({
179
+ stdoutLogPath: logPath,
180
+ agentName: "agent-c",
181
+ runId: "run-1",
182
+ eventsDbPath,
183
+ pollIntervalMs: 50,
184
+ _eventStore: eventStore,
185
+ });
186
+
187
+ try {
188
+ // Wait until all 4 events appear in the store.
189
+ await waitFor(() => {
190
+ const events = eventStore.getByAgent("agent-c");
191
+ return events.length >= 4;
192
+ });
193
+
194
+ const events = eventStore.getByAgent("agent-c");
195
+ const types = events.map((e) => e.eventType);
196
+ expect(types).toContain("turn_start");
197
+ expect(types).toContain("tool_start");
198
+ expect(types).toContain("tool_end");
199
+ expect(types).toContain("turn_end");
200
+
201
+ // Verify tool_end carries duration_ms.
202
+ const toolEnd = events.find((e) => e.eventType === "tool_end");
203
+ expect(toolEnd?.toolDurationMs).toBe(42);
204
+
205
+ // Verify tool_start carries toolName.
206
+ const toolStart = events.find((e) => e.eventType === "tool_start");
207
+ expect(toolStart?.toolName).toBe("Read");
208
+
209
+ // Verify runId propagation.
210
+ for (const event of events) {
211
+ expect(event.runId).toBe("run-1");
212
+ expect(event.agentName).toBe("agent-c");
213
+ }
214
+ } finally {
215
+ handle.stop();
216
+ }
217
+ });
218
+
219
+ test("tails new content appended after tailer starts", async () => {
220
+ const logPath = await createAgentLogDir(tmpDir, "agent-d");
221
+
222
+ // Start with an empty file.
223
+ const handle = startEventTailer({
224
+ stdoutLogPath: logPath,
225
+ agentName: "agent-d",
226
+ runId: null,
227
+ eventsDbPath,
228
+ pollIntervalMs: 50,
229
+ _eventStore: eventStore,
230
+ });
231
+
232
+ try {
233
+ // Append a first event.
234
+ const event1 = `${JSON.stringify({ type: "turn_start", timestamp: new Date().toISOString() })}\n`;
235
+ await writeFile(logPath, event1);
236
+
237
+ await waitFor(() => eventStore.getByAgent("agent-d").length >= 1);
238
+ expect(eventStore.getByAgent("agent-d")).toHaveLength(1);
239
+
240
+ // Append a second event to the same file (simulate ongoing output).
241
+ const event2 = `${JSON.stringify({ type: "turn_end", timestamp: new Date().toISOString() })}\n`;
242
+ // BunFile.size updates on disk; we must append to get new bytes.
243
+ const existing = await Bun.file(logPath).text();
244
+ await writeFile(logPath, existing + event2);
245
+
246
+ await waitFor(() => eventStore.getByAgent("agent-d").length >= 2);
247
+ expect(eventStore.getByAgent("agent-d")).toHaveLength(2);
248
+ } finally {
249
+ handle.stop();
250
+ }
251
+ });
252
+
253
+ test("silently skips malformed (non-JSON) lines", async () => {
254
+ const logPath = await createAgentLogDir(tmpDir, "agent-e");
255
+
256
+ const content = `${[
257
+ "not json at all",
258
+ JSON.stringify({ type: "result", timestamp: new Date().toISOString() }),
259
+ "{incomplete",
260
+ ].join("\n")}\n`;
261
+
262
+ await writeFile(logPath, content);
263
+
264
+ const handle = startEventTailer({
265
+ stdoutLogPath: logPath,
266
+ agentName: "agent-e",
267
+ runId: null,
268
+ eventsDbPath,
269
+ pollIntervalMs: 50,
270
+ _eventStore: eventStore,
271
+ });
272
+
273
+ try {
274
+ // Only the valid JSON line should appear.
275
+ await waitFor(() => eventStore.getByAgent("agent-e").length >= 1);
276
+ const events = eventStore.getByAgent("agent-e");
277
+ expect(events).toHaveLength(1);
278
+ expect(events[0]?.eventType).toBe("result");
279
+ } finally {
280
+ handle.stop();
281
+ }
282
+ });
283
+
284
+ test("maps error events to error level", async () => {
285
+ const logPath = await createAgentLogDir(tmpDir, "agent-f");
286
+
287
+ const content = `${JSON.stringify({ type: "error", message: "boom", timestamp: new Date().toISOString() })}\n`;
288
+ await writeFile(logPath, content);
289
+
290
+ const handle = startEventTailer({
291
+ stdoutLogPath: logPath,
292
+ agentName: "agent-f",
293
+ runId: null,
294
+ eventsDbPath,
295
+ pollIntervalMs: 50,
296
+ _eventStore: eventStore,
297
+ });
298
+
299
+ try {
300
+ await waitFor(() => eventStore.getByAgent("agent-f").length >= 1);
301
+ const events = eventStore.getByAgent("agent-f");
302
+ expect(events[0]?.level).toBe("error");
303
+ expect(events[0]?.eventType).toBe("error");
304
+ } finally {
305
+ handle.stop();
306
+ }
307
+ });
308
+
309
+ test("unknown event types map to 'custom'", async () => {
310
+ const logPath = await createAgentLogDir(tmpDir, "agent-g");
311
+
312
+ const content = `${JSON.stringify({ type: "some_future_type", timestamp: new Date().toISOString() })}\n`;
313
+ await writeFile(logPath, content);
314
+
315
+ const handle = startEventTailer({
316
+ stdoutLogPath: logPath,
317
+ agentName: "agent-g",
318
+ runId: null,
319
+ eventsDbPath,
320
+ pollIntervalMs: 50,
321
+ _eventStore: eventStore,
322
+ });
323
+
324
+ try {
325
+ await waitFor(() => eventStore.getByAgent("agent-g").length >= 1);
326
+ const events = eventStore.getByAgent("agent-g");
327
+ expect(events[0]?.eventType).toBe("custom");
328
+ } finally {
329
+ handle.stop();
330
+ }
331
+ });
332
+
333
+ test("does not crash when log file does not exist yet", async () => {
334
+ // Non-existent log path — tailer should silently poll without errors.
335
+ const logPath = join(tmpDir, "logs", "agent-h", "2026-03-05T00-00-00-000Z", "stdout.log");
336
+
337
+ const handle = startEventTailer({
338
+ stdoutLogPath: logPath,
339
+ agentName: "agent-h",
340
+ runId: null,
341
+ eventsDbPath,
342
+ pollIntervalMs: 50,
343
+ _eventStore: eventStore,
344
+ });
345
+
346
+ // Wait a couple poll cycles to ensure no crash.
347
+ await new Promise((resolve) => setTimeout(resolve, 150));
348
+ handle.stop();
349
+
350
+ // No events should have been written.
351
+ expect(eventStore.getByAgent("agent-h")).toHaveLength(0);
352
+ });
353
+ });
354
+
355
+ describe("daemon tailer integration", () => {
356
+ /**
357
+ * Verify that the daemon wires tailer start/stop correctly using DI.
358
+ * This test exercises the daemon's tailer management logic with injected
359
+ * mocks rather than actual polling — the tailer behaviour itself is tested
360
+ * above in the startEventTailer suite.
361
+ */
362
+ test("daemon starts a tailer for headless sessions and stops it when completed", async () => {
363
+ const tmpDir = await createTempDir();
364
+ const overstoryDir = join(tmpDir, ".overstory");
365
+ await mkdir(overstoryDir, { recursive: true });
366
+
367
+ // Create a minimal log structure so findLatestStdoutLog succeeds.
368
+ const agentName = "headless-agent";
369
+ const logPath = await createAgentLogDir(overstoryDir, agentName);
370
+
371
+ // Use a registry we control.
372
+ const registry = new Map<string, { agentName: string; logPath: string; stop: () => void }>();
373
+ const stopped: string[] = [];
374
+
375
+ const tailerFactory = (opts: {
376
+ stdoutLogPath: string;
377
+ agentName: string;
378
+ runId: string | null;
379
+ eventsDbPath: string;
380
+ }) => {
381
+ const handle = {
382
+ agentName: opts.agentName,
383
+ logPath: opts.stdoutLogPath,
384
+ stop: () => {
385
+ stopped.push(opts.agentName);
386
+ registry.delete(opts.agentName);
387
+ },
388
+ };
389
+ return handle;
390
+ };
391
+
392
+ // Write a headless session.
393
+ const { createSessionStore } = await import("../sessions/store.ts");
394
+ const sessionStore = createSessionStore(join(overstoryDir, "sessions.db"));
395
+ sessionStore.upsert({
396
+ id: "sess-1",
397
+ agentName,
398
+ capability: "builder",
399
+ worktreePath: tmpDir,
400
+ branchName: "test-branch",
401
+ taskId: "task-1",
402
+ tmuxSession: "", // headless
403
+ state: "working",
404
+ pid: process.pid,
405
+ parentAgent: null,
406
+ depth: 0,
407
+ runId: null,
408
+ startedAt: new Date().toISOString(),
409
+ lastActivity: new Date().toISOString(),
410
+ escalationLevel: 0,
411
+ stalledSince: null,
412
+ transcriptPath: null,
413
+ });
414
+ sessionStore.close();
415
+
416
+ const { runDaemonTick } = await import("../watchdog/daemon.ts");
417
+
418
+ // First tick: should start a tailer for the headless session.
419
+ await runDaemonTick({
420
+ root: tmpDir,
421
+ staleThresholdMs: 300_000,
422
+ zombieThresholdMs: 600_000,
423
+ _tmux: { isSessionAlive: async () => false, killSession: async () => {} },
424
+ _triage: async () => "extend",
425
+ _nudge: async () => ({ delivered: false }),
426
+ _eventStore: null,
427
+ _recordFailure: async () => {},
428
+ _tailerRegistry: registry as unknown as Map<string, TailerHandle>,
429
+ _tailerFactory: tailerFactory as unknown as (opts: TailerOptions) => TailerHandle,
430
+ _findLatestStdoutLog: async () => logPath,
431
+ });
432
+
433
+ expect(registry.has(agentName)).toBe(true);
434
+ expect(stopped).toHaveLength(0);
435
+
436
+ // Mark session as completed.
437
+ const store2 = createSessionStore(join(overstoryDir, "sessions.db"));
438
+ store2.updateState(agentName, "completed");
439
+ store2.close();
440
+
441
+ // Second tick: completed session is skipped, tailer should be stopped.
442
+ await runDaemonTick({
443
+ root: tmpDir,
444
+ staleThresholdMs: 300_000,
445
+ zombieThresholdMs: 600_000,
446
+ _tmux: { isSessionAlive: async () => false, killSession: async () => {} },
447
+ _triage: async () => "extend",
448
+ _nudge: async () => ({ delivered: false }),
449
+ _eventStore: null,
450
+ _recordFailure: async () => {},
451
+ _tailerRegistry: registry as unknown as Map<string, TailerHandle>,
452
+ _tailerFactory: tailerFactory as unknown as (opts: TailerOptions) => TailerHandle,
453
+ _findLatestStdoutLog: async () => logPath,
454
+ });
455
+
456
+ expect(stopped).toContain(agentName);
457
+ expect(registry.has(agentName)).toBe(false);
458
+
459
+ await cleanupTempDir(tmpDir);
460
+ });
461
+ });
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Background NDJSON event tailer for headless agent stdout logs.
3
+ *
4
+ * Headless agents (e.g. Sapling) write NDJSON events to a stdout.log file
5
+ * in .overstory/logs/{agentName}/{timestamp}/stdout.log. After ov sling exits,
6
+ * nobody reads this stream — so ov status, ov dashboard, and ov feed cannot
7
+ * show live progress for headless agents.
8
+ *
9
+ * This module provides startEventTailer(), which polls the log file on a
10
+ * configurable interval, parses new NDJSON lines, and writes them into events.db
11
+ * via EventStore. The watchdog daemon starts a tailer for each headless agent
12
+ * session and stops it when the session completes or terminates.
13
+ */
14
+
15
+ import { readdir } from "node:fs/promises";
16
+ import { join } from "node:path";
17
+ import type { EventStore, EventType } from "../types.ts";
18
+ import { createEventStore } from "./store.ts";
19
+
20
+ /**
21
+ * Handle to a running event tailer.
22
+ * Call stop() to halt polling and close the database connection.
23
+ */
24
+ export interface TailerHandle {
25
+ /** Agent name being tailed. */
26
+ readonly agentName: string;
27
+ /** Absolute path to the stdout.log file being tailed. */
28
+ readonly logPath: string;
29
+ /** Stop polling and release all resources. */
30
+ stop(): void;
31
+ }
32
+
33
+ /** Map NDJSON event type strings to EventStore EventType. */
34
+ function mapEventType(type: string): EventType {
35
+ switch (type) {
36
+ case "tool_start":
37
+ return "tool_start";
38
+ case "tool_end":
39
+ return "tool_end";
40
+ case "session_start":
41
+ return "session_start";
42
+ case "session_end":
43
+ return "session_end";
44
+ case "turn_start":
45
+ return "turn_start";
46
+ case "turn_end":
47
+ return "turn_end";
48
+ case "progress":
49
+ return "progress";
50
+ case "result":
51
+ return "result";
52
+ case "error":
53
+ return "error";
54
+ default:
55
+ return "custom";
56
+ }
57
+ }
58
+
59
+ /** Options for startEventTailer. */
60
+ export interface TailerOptions {
61
+ /** Absolute path to the stdout.log file to tail. */
62
+ stdoutLogPath: string;
63
+ /** Agent name for event attribution in events.db. */
64
+ agentName: string;
65
+ /** Run ID to associate events with, or null. */
66
+ runId: string | null;
67
+ /** Absolute path to events.db. The tailer opens its own connection. */
68
+ eventsDbPath: string;
69
+ /** Poll interval in milliseconds (default: 500). */
70
+ pollIntervalMs?: number;
71
+ /** DI: injected EventStore for testing (overrides eventsDbPath). */
72
+ _eventStore?: EventStore;
73
+ }
74
+
75
+ /**
76
+ * Start a background event tailer for a headless agent's stdout.log.
77
+ *
78
+ * Polls the log file on a configurable interval, reads new bytes since the
79
+ * last poll using file.size as a byte cursor, parses NDJSON lines, and writes
80
+ * normalized events to events.db. Maintains its own SQLite connection so it
81
+ * can outlive the daemon tick that created it.
82
+ *
83
+ * All errors (file not found, parse failures, DB write failures) are swallowed
84
+ * silently — the tailer must never crash the watchdog daemon.
85
+ *
86
+ * @param opts - Tailer configuration (log path, agent, run, db path)
87
+ * @returns TailerHandle with stop() to halt polling and close resources
88
+ */
89
+ export function startEventTailer(opts: TailerOptions): TailerHandle {
90
+ const { stdoutLogPath, agentName, runId, eventsDbPath, pollIntervalMs = 500 } = opts;
91
+
92
+ // Open a dedicated EventStore for this tailer's lifetime (not tick-scoped).
93
+ // Injected _eventStore is used for testing without an actual DB file.
94
+ let eventStore: EventStore | null = opts._eventStore ?? null;
95
+ let ownedEventStore = false;
96
+ if (!eventStore) {
97
+ try {
98
+ eventStore = createEventStore(eventsDbPath);
99
+ ownedEventStore = true;
100
+ } catch {
101
+ // If we can't open the event store, the tailer becomes a no-op.
102
+ }
103
+ }
104
+
105
+ let stopped = false;
106
+ let byteOffset = 0;
107
+ let timer: ReturnType<typeof setTimeout> | null = null;
108
+
109
+ const poll = async (): Promise<void> => {
110
+ if (stopped) return;
111
+
112
+ try {
113
+ const file = Bun.file(stdoutLogPath);
114
+ const size = file.size;
115
+
116
+ if (size > byteOffset) {
117
+ // Read only new bytes since last poll — avoids re-processing old lines.
118
+ const newContent = await file.slice(byteOffset, size).text();
119
+ byteOffset = size;
120
+
121
+ const lines = newContent.split("\n");
122
+ for (const line of lines) {
123
+ const trimmed = line.trim();
124
+ if (!trimmed) continue;
125
+
126
+ let event: Record<string, unknown>;
127
+ try {
128
+ event = JSON.parse(trimmed) as Record<string, unknown>;
129
+ } catch {
130
+ // Skip malformed lines — partial writes or debug output.
131
+ continue;
132
+ }
133
+
134
+ const type = typeof event.type === "string" ? event.type : "custom";
135
+ const eventType = mapEventType(type);
136
+ const level = type === "error" ? "error" : "info";
137
+
138
+ // Extract tool name from various field names runtimes may use.
139
+ let toolName: string | null = null;
140
+ if (typeof event.tool === "string") {
141
+ toolName = event.tool;
142
+ } else if (typeof event.tool_name === "string") {
143
+ toolName = event.tool_name;
144
+ } else if (typeof event.toolName === "string") {
145
+ toolName = event.toolName;
146
+ }
147
+
148
+ const toolDurationMs = typeof event.duration_ms === "number" ? event.duration_ms : null;
149
+
150
+ try {
151
+ eventStore?.insert({
152
+ runId,
153
+ agentName,
154
+ sessionId: null,
155
+ eventType,
156
+ toolName,
157
+ toolArgs: null,
158
+ toolDurationMs,
159
+ level,
160
+ data: JSON.stringify(event),
161
+ });
162
+ } catch {
163
+ // DB write failure is non-fatal.
164
+ }
165
+ }
166
+ }
167
+ } catch {
168
+ // File read failure is non-fatal — agent may not have started writing yet.
169
+ }
170
+
171
+ if (!stopped) {
172
+ timer = setTimeout(poll, pollIntervalMs);
173
+ }
174
+ };
175
+
176
+ // Schedule first poll.
177
+ timer = setTimeout(poll, pollIntervalMs);
178
+
179
+ return {
180
+ agentName,
181
+ logPath: stdoutLogPath,
182
+ stop() {
183
+ stopped = true;
184
+ if (timer !== null) {
185
+ clearTimeout(timer);
186
+ timer = null;
187
+ }
188
+ // Close only the EventStore this tailer owns (not the injected one).
189
+ if (ownedEventStore && eventStore) {
190
+ try {
191
+ eventStore.close();
192
+ } catch {
193
+ // Non-fatal.
194
+ }
195
+ eventStore = null;
196
+ }
197
+ },
198
+ };
199
+ }
200
+
201
+ /**
202
+ * Discover the most recent stdout.log path for a headless agent.
203
+ *
204
+ * Scans .overstory/logs/{agentName}/ for timestamped session directories and
205
+ * returns the stdout.log path from the lexicographically last directory.
206
+ * Directories use ISO timestamps with `-` replacing `.` and `:`, which sort
207
+ * correctly in lexicographic order (e.g. 2026-03-05T14-52-26-089Z).
208
+ *
209
+ * Returns null if no log directory exists or no stdout.log is found.
210
+ *
211
+ * @param overstoryDir - Absolute path to .overstory/
212
+ * @param agentName - Agent name to look up (matches .overstory/logs/{agentName}/)
213
+ */
214
+ export async function findLatestStdoutLog(
215
+ overstoryDir: string,
216
+ agentName: string,
217
+ ): Promise<string | null> {
218
+ const agentLogsDir = join(overstoryDir, "logs", agentName);
219
+ try {
220
+ const entries = await readdir(agentLogsDir);
221
+ if (entries.length === 0) return null;
222
+
223
+ // Lexicographic sort: ISO timestamps sort correctly without parsing.
224
+ const sorted = entries.sort();
225
+ const latest = sorted[sorted.length - 1];
226
+ if (!latest) return null;
227
+
228
+ const logPath = join(agentLogsDir, latest, "stdout.log");
229
+ const file = Bun.file(logPath);
230
+ if (await file.exists()) return logPath;
231
+ return null;
232
+ } catch {
233
+ return null;
234
+ }
235
+ }
package/src/index.ts CHANGED
@@ -49,7 +49,7 @@ import { ConfigError, OverstoryError, WorktreeError } from "./errors.ts";
49
49
  import { jsonError } from "./json.ts";
50
50
  import { brand, chalk, muted, setQuiet } from "./logging/color.ts";
51
51
 
52
- export const VERSION = "0.8.4";
52
+ export const VERSION = "0.8.5";
53
53
 
54
54
  const rawArgs = process.argv.slice(2);
55
55