@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 158 lines 5.78 KB
Raw
1 import { closeSync, constants, openSync, writeSync } from "node:fs";
2 /**
3 * Persistent run log: every test's pass/failure followed by its captured
4 * output, appended to `.alchemy/log/test.log` as the run progresses —
5 * color-free so agents and tooling can read it directly.
6 */
7 import * as Effect from "effect/Effect";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Option from "effect/Option";
10 import * as Path from "effect/Path";
11 import type { LogEntry } from "./Model.ts";
12 import { formatPlanPreview } from "./Plan.ts";
13 import type { TestEvent } from "./Reporter.ts";
14
15 const formatDuration = (ms: number): string =>
16 ms >= 1000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.round(ms)}ms`;
17
18 const formatLogs = (logs: ReadonlyArray<LogEntry>): string =>
19 logs.map((log) => log.message).join("\n");
20
21 const GLYPH = {
22 pass: "PASS",
23 fail: "FAIL",
24 skip: "SKIP",
25 todo: "TODO",
26 } as const;
27
28 /** Render an event as a log chunk; `undefined` = nothing to write. */
29 export const formatEvent = (event: TestEvent): string | undefined => {
30 switch (event._tag) {
31 case "PlanPreview":
32 return `${formatPlanPreview(event.phases)}\n`;
33 case "PlanPhaseStart":
34 return `Plan phase ${event.phase}/${event.phases}: ${event.tests} tests\n`;
35 case "RunStart":
36 return `running ${event.tests.length} tests from ${event.files} files (${new Date().toISOString()})\n\n`;
37 case "TestEnd": {
38 const title = `${event.test.file} > ${event.test.titlePath.join(" > ")}`;
39 const retries = event.result.retries > 0 ? ` [retried x${event.result.retries}]` : "";
40 const lines = [
41 `${GLYPH[event.result.status]} ${title} (${formatDuration(event.result.durationMs)})${retries}`,
42 ];
43 if (event.result.error !== undefined) {
44 lines.push(event.result.error);
45 }
46 if (event.result.logs.length > 0) {
47 lines.push("--- captured output ---");
48 lines.push(formatLogs(event.result.logs));
49 lines.push("--- end output ---");
50 }
51 // One line per plain result; a blank separator only after multi-line
52 // entries (error/output blocks) so they don't run into the next entry.
53 return lines.length === 1 ? `${lines[0]}\n` : `${lines.join("\n")}\n\n`;
54 }
55 case "FileEnd": {
56 const lines: Array<string> = [];
57 if (event.error !== undefined) {
58 lines.push(`FAIL ${event.file} failed to run`, event.error);
59 }
60 if (event.logs.length > 0) {
61 lines.push(`--- file hook output (${event.file}) ---`);
62 lines.push(formatLogs(event.logs));
63 lines.push("--- end output ---");
64 }
65 return lines.length === 0 ? undefined : `${lines.join("\n")}\n\n`;
66 }
67 case "RunEnd": {
68 const s = event.summary;
69 return (
70 `Tests: ${s.failed} failed | ${s.passed} passed` +
71 (s.skipped > 0 ? ` | ${s.skipped} skipped` : "") +
72 (s.todo > 0 ? ` | ${s.todo} todo` : "") +
73 (s.plan
74 ? ` | ${s.plan.found} found | ${s.plan.selected} selected by plan | ${s.plan.excluded} excluded by plan`
75 : "") +
76 ` (${s.files} files, ${formatDuration(s.durationMs)})\n`
77 );
78 }
79 default:
80 return undefined;
81 }
82 };
83
84 export interface FileLog {
85 readonly append: (event: TestEvent) => Effect.Effect<void>;
86 /** Synchronous persistence applies backpressure to synchronous logger callbacks. */
87 readonly appendHookLine: (file: string, entry: LogEntry) => void;
88 readonly appendTestLine: (id: string, entry: LogEntry) => void;
89 readonly close: Effect.Effect<void>;
90 }
91
92 const LOG_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
93
94 /**
95 * Delete sibling run logs whose mtime (from stat — file names are never
96 * trusted) is older than a week, so the per-run log directory can't grow
97 * unboundedly. Best-effort: failures are ignored.
98 */
99 const pruneOldLogs = Effect.fn(function* (dir: string) {
100 const fs = yield* FileSystem.FileSystem;
101 const path = yield* Path.Path;
102 const entries = yield* fs
103 .readDirectory(dir)
104 .pipe(Effect.orElseSucceed(() => [] as Array<string>));
105 const cutoff = Date.now() - LOG_RETENTION_MS;
106 for (const entry of entries) {
107 if (!entry.endsWith(".log")) continue;
108 const file = path.join(dir, entry);
109 const info = yield* fs.stat(file).pipe(Effect.orElseSucceed(() => undefined));
110 const mtime = info === undefined ? undefined : Option.getOrUndefined(info.mtime);
111 if (mtime !== undefined && mtime.getTime() < cutoff) {
112 yield* fs.remove(file).pipe(Effect.ignore);
113 }
114 }
115 });
116
117 /** Create (truncate) the log file and return an event appender. */
118 export const makeFileLog = Effect.fn(function* (logFile: string) {
119 const fs = yield* FileSystem.FileSystem;
120 const path = yield* Path.Path;
121 yield* fs.makeDirectory(path.dirname(logFile), { recursive: true }).pipe(Effect.ignore);
122 yield* pruneOldLogs(path.dirname(logFile));
123 const fd = yield* Effect.sync(() =>
124 openSync(
125 logFile,
126 constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_APPEND,
127 ),
128 );
129 let closed = false;
130 const write = (text: string): void => {
131 if (closed) return;
132 const bytes = Buffer.from(text);
133 let offset = 0;
134 while (offset < bytes.length) {
135 offset += writeSync(fd, bytes, offset, bytes.length - offset);
136 }
137 };
138 const append: FileLog["append"] = (event) =>
139 Effect.sync(() => {
140 const chunk = formatEvent(event);
141 if (chunk !== undefined) write(chunk);
142 });
143 const appendLine = (label: string, entry: LogEntry): void => {
144 write(`[${label}] ${entry.message}\n`);
145 };
146 const close = Effect.sync(() => {
147 if (closed) return;
148 closed = true;
149 closeSync(fd);
150 });
151 yield* Effect.addFinalizer(() => close);
152 return {
153 append,
154 appendHookLine: (file, entry) => appendLine(`hook ${file}`, entry),
155 appendTestLine: (id, entry) => appendLine(`test ${id}`, entry),
156 close,
157 } satisfies FileLog;
158 });