@@ -0,0 +1,55 @@
1+import { mkdirSync, readdirSync, unlinkSync } from "node:fs";
2+import { homedir } from "node:os";
3+import { join } from "node:path";
4+
5+const LOGS_DIR = join(homedir(), ".config", "mini-coder", "logs");
6+
7+/** Return the logs directory, creating it if necessary. */
8+function getLogsDir(): string {
9+ mkdirSync(LOGS_DIR, { recursive: true });
10+ return LOGS_DIR;
11+}
12+
13+/** Build a PID-scoped log file path: `<logsDir>/<prefix>-<pid>.log` */
14+export function pidLogPath(prefix: string): string {
15+ return join(getLogsDir(), `${prefix}-${process.pid}.log`);
16+}
17+
18+function isProcessAlive(pid: number): boolean {
19+ try {
20+ process.kill(pid, 0);
21+ return true;
22+ } catch {
23+ return false;
24+ }
25+}
26+
27+const LOG_FILE_RE = /^(api|errors)-(\d+)\.log$/;
28+
29+/**
30+ * Remove log files left by dead processes. Called once on startup by
31+ * non-subagent processes so the logs directory doesn't grow unbounded.
32+ */
33+export function cleanStaleLogs(): void {
34+ let entries: string[];
35+ try {
36+ entries = readdirSync(LOGS_DIR);
37+ } catch {
38+ return;
39+ }
40+
41+ for (const name of entries) {
42+ const m = LOG_FILE_RE.exec(name);
43+ if (!m) continue;
44+ const pidStr = m[2] as string;
45+ const pid = Number.parseInt(pidStr, 10);
46+ if (pid === process.pid) continue;
47+ if (!isProcessAlive(pid)) {
48+ try {
49+ unlinkSync(join(LOGS_DIR, name));
50+ } catch {
51+ /* race: another process may have already cleaned it */
52+ }
53+ }
54+ }
55+}