marmonitor 0.1.6 → 0.2.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.
Files changed (46) hide show
  1. package/README.ko.md +248 -0
  2. package/README.md +41 -5
  3. package/bin/daemon.js +2 -0
  4. package/bin/postinstall.cjs +75 -0
  5. package/bin/preuninstall.cjs +14 -0
  6. package/dist/banner/index.js +15 -7
  7. package/dist/cli.js +297 -110
  8. package/dist/config/index.d.ts +2 -0
  9. package/dist/config/index.js +5 -3
  10. package/dist/output/badge-themes.d.ts +19 -0
  11. package/dist/output/badge-themes.js +52 -0
  12. package/dist/output/index.d.ts +5 -2
  13. package/dist/output/index.js +69 -22
  14. package/dist/output/utils.d.ts +23 -9
  15. package/dist/output/utils.js +85 -48
  16. package/dist/scanner/claude.d.ts +8 -1
  17. package/dist/scanner/claude.js +156 -19
  18. package/dist/scanner/codex-sqlite.d.ts +11 -0
  19. package/dist/scanner/codex-sqlite.js +50 -0
  20. package/dist/scanner/codex.d.ts +1 -1
  21. package/dist/scanner/codex.js +42 -2
  22. package/dist/scanner/concurrency.d.ts +5 -0
  23. package/dist/scanner/concurrency.js +22 -0
  24. package/dist/scanner/daemon-entry.d.ts +5 -0
  25. package/dist/scanner/daemon-entry.js +27 -0
  26. package/dist/scanner/daemon-loop.d.ts +13 -0
  27. package/dist/scanner/daemon-loop.js +77 -0
  28. package/dist/scanner/daemon-utils.d.ts +9 -0
  29. package/dist/scanner/daemon-utils.js +56 -0
  30. package/dist/scanner/gemini.js +3 -1
  31. package/dist/scanner/index.js +51 -10
  32. package/dist/scanner/perf.d.ts +8 -0
  33. package/dist/scanner/perf.js +26 -0
  34. package/dist/scanner/session-registry.d.ts +31 -0
  35. package/dist/scanner/session-registry.js +99 -0
  36. package/dist/scanner/session-tier.d.ts +6 -0
  37. package/dist/scanner/session-tier.js +22 -0
  38. package/dist/tmux/index.js +11 -0
  39. package/dist/tmux/jump-anchor.d.ts +25 -0
  40. package/dist/tmux/jump-anchor.js +100 -0
  41. package/dist/tmux/setup.d.ts +4 -0
  42. package/dist/tmux/setup.js +41 -1
  43. package/dist/tmux/status-click.d.ts +9 -0
  44. package/dist/tmux/status-click.js +19 -0
  45. package/package.json +2 -2
  46. package/bin/postinstall.js +0 -20
@@ -394,32 +394,169 @@ export async function detectClaudePhase(sessionId, cwd, startedAt, config) {
394
394
  return {};
395
395
  }
396
396
  }
397
- /** Parse Claude Code session file for enriched data */
398
- export async function parseClaudeSession(pid, config) {
399
- const sessionFile = getClaudeSessionRoots(config)
400
- .map((root) => join(root, `${pid}.json`))
401
- .find((candidate) => existsSync(candidate));
402
- if (!sessionFile)
403
- return {};
397
+ /**
398
+ * Read the first line of a JSONL file to extract session metadata.
399
+ * Returns undefined if the file can't be read or parsed.
400
+ */
401
+ async function readJsonlFirstLine(filePath) {
402
+ let fd;
404
403
  try {
405
- const fileStat = await stat(sessionFile);
406
- const raw = await readFile(sessionFile, "utf-8");
407
- const data = JSON.parse(raw);
404
+ fd = await open(filePath, "r");
405
+ const buf = Buffer.alloc(4096);
406
+ await fd.read(buf, 0, 4096, 0);
407
+ const firstLine = buf.toString("utf-8").split("\n")[0];
408
+ if (!firstLine)
409
+ return undefined;
410
+ return JSON.parse(firstLine);
411
+ }
412
+ catch {
413
+ return undefined;
414
+ }
415
+ finally {
416
+ await fd?.close().catch(() => { });
417
+ }
418
+ }
419
+ /**
420
+ * Match a Claude session by scanning JSONL files in the project directory.
421
+ * When processStartedAt is available, matches by JSONL creation timestamp
422
+ * (first-line timestamp) proximity to process start time.
423
+ * Falls back to the most recently modified JSONL when no start time is available.
424
+ */
425
+ export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
426
+ const projectDirName = await findClaudeProjectDir(cwd, undefined, config);
427
+ if (!projectDirName)
428
+ return undefined;
429
+ const projectRoots = getClaudeProjectRoots(config);
430
+ const candidates = [];
431
+ for (const projectsDir of projectRoots) {
432
+ const projectDir = join(projectsDir, projectDirName);
433
+ if (!existsSync(projectDir))
434
+ continue;
435
+ try {
436
+ const files = await readdir(projectDir);
437
+ for (const file of files) {
438
+ if (!file.endsWith(".jsonl"))
439
+ continue;
440
+ try {
441
+ const filePath = join(projectDir, file);
442
+ const fileStat = await stat(filePath);
443
+ candidates.push({ path: filePath, mtimeMs: fileStat.mtimeMs });
444
+ }
445
+ catch {
446
+ // skip
447
+ }
448
+ }
449
+ }
450
+ catch {
451
+ // skip
452
+ }
453
+ }
454
+ if (candidates.length === 0)
455
+ return undefined;
456
+ let bestPath;
457
+ if (processStartedAt) {
458
+ const startMs = processStartedAt * 1000;
459
+ // Pre-filter: only consider JSONL files modified after process start (with tolerance)
460
+ const active = candidates.filter((c) => c.mtimeMs >= startMs - CLAUDE_SESSION_MTIME_MATCH_SEC * 1000);
461
+ const pool = active.length > 0 ? active : candidates;
462
+ // Read first lines to get creation timestamps and match by proximity
463
+ const scored = [];
464
+ for (const c of pool) {
465
+ const firstLine = await readJsonlFirstLine(c.path);
466
+ if (!firstLine?.timestamp)
467
+ continue;
468
+ const createdAt = new Date(firstLine.timestamp).getTime() / 1000;
469
+ scored.push({
470
+ path: c.path,
471
+ deltaSec: Math.abs(createdAt - processStartedAt),
472
+ mtimeMs: c.mtimeMs,
473
+ });
474
+ }
475
+ if (scored.length > 0) {
476
+ // Pick the JSONL whose creation time is closest to process start
477
+ scored.sort((a, b) => a.deltaSec - b.deltaSec);
478
+ // Only accept if within reasonable tolerance (5 minutes)
479
+ if (scored[0].deltaSec <= 300) {
480
+ bestPath = scored[0].path;
481
+ }
482
+ }
483
+ // Fallback: most recently modified
484
+ if (!bestPath) {
485
+ pool.sort((a, b) => b.mtimeMs - a.mtimeMs);
486
+ bestPath = pool[0].path;
487
+ }
488
+ }
489
+ else {
490
+ // No process start time — pick most recently modified
491
+ candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
492
+ bestPath = candidates[0].path;
493
+ }
494
+ // Read first line for session metadata
495
+ const entry = await readJsonlFirstLine(bestPath);
496
+ if (!entry?.sessionId)
497
+ return undefined;
498
+ try {
499
+ const fileStat = await stat(bestPath);
500
+ const sessionCwd = entry.cwd ?? cwd;
408
501
  const result = {
409
- cwd: data.cwd,
410
- sessionId: data.sessionId,
411
- startedAt: data.startedAt ? data.startedAt / 1000 : undefined,
502
+ cwd: sessionCwd,
503
+ sessionId: entry.sessionId,
504
+ startedAt: entry.timestamp ? new Date(entry.timestamp).getTime() / 1000 : undefined,
412
505
  lastActivityAt: fileStat.mtimeMs / 1000,
413
506
  sessionMatched: true,
414
507
  };
415
- if (data.sessionId && data.cwd) {
416
- const tokenData = await parseClaudeTokens(data.sessionId, data.cwd, data.startedAt ? data.startedAt / 1000 : undefined, config);
417
- result.tokenUsage = tokenData.tokenUsage;
418
- result.model = tokenData.model;
419
- }
508
+ // Register in session registry for subsequent lookups
509
+ upsertSessionRegistryEntry(claudeSessionRegistry, {
510
+ filePath: bestPath,
511
+ sessionId: entry.sessionId,
512
+ cwd: sessionCwd,
513
+ firstSeenOffset: 0,
514
+ startedAt: result.startedAt,
515
+ source: "claude",
516
+ });
517
+ const tokenData = await parseClaudeTokens(entry.sessionId, sessionCwd, result.startedAt, config);
518
+ result.tokenUsage = tokenData.tokenUsage;
519
+ result.model = tokenData.model;
420
520
  return result;
421
521
  }
422
522
  catch {
423
- return {};
523
+ return undefined;
524
+ }
525
+ }
526
+ /** Parse Claude Code session file for enriched data */
527
+ export async function parseClaudeSession(pid, cwd, processStartedAt, config) {
528
+ // 1st: try legacy sessions/{pid}.json
529
+ const sessionFile = getClaudeSessionRoots(config)
530
+ .map((root) => join(root, `${pid}.json`))
531
+ .find((candidate) => existsSync(candidate));
532
+ if (sessionFile) {
533
+ try {
534
+ const fileStat = await stat(sessionFile);
535
+ const raw = await readFile(sessionFile, "utf-8");
536
+ const data = JSON.parse(raw);
537
+ const result = {
538
+ cwd: data.cwd,
539
+ sessionId: data.sessionId,
540
+ startedAt: data.startedAt ? data.startedAt / 1000 : undefined,
541
+ lastActivityAt: fileStat.mtimeMs / 1000,
542
+ sessionMatched: true,
543
+ };
544
+ if (data.sessionId && data.cwd) {
545
+ const tokenData = await parseClaudeTokens(data.sessionId, data.cwd, data.startedAt ? data.startedAt / 1000 : undefined, config);
546
+ result.tokenUsage = tokenData.tokenUsage;
547
+ result.model = tokenData.model;
548
+ }
549
+ return result;
550
+ }
551
+ catch {
552
+ // fall through to mtime-based matching
553
+ }
554
+ }
555
+ // 2nd: match by JSONL mtime in project directory
556
+ if (cwd && cwd !== "unknown") {
557
+ const matched = await matchClaudeSessionByMtime(cwd, processStartedAt, config);
558
+ if (matched)
559
+ return matched;
424
560
  }
561
+ return {};
425
562
  }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Codex session indexing via SQLite threads table.
3
+ * Uses sqlite3 CLI (pre-installed on macOS/Linux) — no npm dependency.
4
+ * Falls back gracefully if sqlite3 is unavailable or DB is missing.
5
+ */
6
+ import type { CodexSessionMeta } from "./cache.js";
7
+ /**
8
+ * Query Codex state SQLite for active (non-archived) threads.
9
+ * Returns CodexSessionMeta[] compatible with existing matchCodexSession().
10
+ */
11
+ export declare function indexCodexSessionsFromSqlite(dbPath: string): Promise<CodexSessionMeta[]>;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Codex session indexing via SQLite threads table.
3
+ * Uses sqlite3 CLI (pre-installed on macOS/Linux) — no npm dependency.
4
+ * Falls back gracefully if sqlite3 is unavailable or DB is missing.
5
+ */
6
+ import { execFile } from "node:child_process";
7
+ import { promisify } from "node:util";
8
+ const execFileAsync = promisify(execFile);
9
+ /**
10
+ * Query Codex state SQLite for active (non-archived) threads.
11
+ * Returns CodexSessionMeta[] compatible with existing matchCodexSession().
12
+ */
13
+ export async function indexCodexSessionsFromSqlite(dbPath) {
14
+ try {
15
+ const { stdout } = await execFileAsync("sqlite3", [
16
+ dbPath,
17
+ "-separator",
18
+ "\t",
19
+ "SELECT id, cwd, rollout_path, tokens_used, model, updated_at, created_at FROM threads WHERE archived = 0 ORDER BY updated_at DESC;",
20
+ ]);
21
+ const lines = stdout.trim().split("\n").filter(Boolean);
22
+ const sessions = [];
23
+ for (const line of lines) {
24
+ const [id, cwd, rolloutPath, tokensUsed, model, updatedAt, createdAt] = line.split("\t");
25
+ if (!id || !cwd)
26
+ continue;
27
+ sessions.push({
28
+ filePath: rolloutPath ?? "",
29
+ id,
30
+ cwd,
31
+ timestamp: Number(createdAt) || 0,
32
+ lastActivityAt: Number(updatedAt) || undefined,
33
+ totalTokenUsage: tokensUsed
34
+ ? {
35
+ input_tokens: 0,
36
+ cached_input_tokens: 0,
37
+ output_tokens: 0,
38
+ total_tokens: Number(tokensUsed) || 0,
39
+ }
40
+ : undefined,
41
+ model: model || undefined,
42
+ });
43
+ }
44
+ return sessions;
45
+ }
46
+ catch {
47
+ // sqlite3 not available, DB missing, or query failed — return empty
48
+ return [];
49
+ }
50
+ }
@@ -8,7 +8,7 @@ export type { CodexSessionMeta } from "./cache.js";
8
8
  export declare function getCodexSessionRoots(config?: MarmonitorConfig): string[];
9
9
  /** Detect Codex session phase from session JSONL */
10
10
  export declare function detectCodexPhase(sessionFilePath: string | undefined, config?: MarmonitorConfig): Promise<SessionPhase>;
11
- /** Build index of recent Codex sessions (last 7 days) */
11
+ /** Build index of Codex sessions (SQLite primary, JSONL fallback) */
12
12
  export declare function indexCodexSessions(config?: MarmonitorConfig): Promise<CodexSessionMeta[]>;
13
13
  /** Match a Codex process to a session by cwd + closest timestamp */
14
14
  export declare function matchCodexSession(processCwd: string, processStartTime: number | undefined, sessions: CodexSessionMeta[]): CodexSessionMeta | undefined;
@@ -1,9 +1,11 @@
1
1
  /**
2
2
  * Codex session parsing, indexing, and phase detection.
3
3
  */
4
- import { existsSync } from "node:fs";
4
+ import { existsSync, readdirSync } from "node:fs";
5
5
  import { open, readFile, readdir, stat } from "node:fs/promises";
6
+ import { homedir } from "node:os";
6
7
  import { join } from "node:path";
8
+ import { indexCodexSessionsFromSqlite } from "./codex-sqlite.js";
7
9
  import { resolveRuntimeDataPaths } from "../config/index.js";
8
10
  import { advanceJsonlCursor, resolvePhaseFromHistory, resolvePhaseWithDecay, selectCodexSession, updatePhaseHistory, upsertSessionRegistryEntry, } from "../output/utils.js";
9
11
  import { CODEX_INDEX_TTL_MS, CODEX_PHASE_RECENT_LINES, HOME, codexIndexCache, codexPhaseCache, codexSessionFileCache, codexSessionRegistry, setCodexIndexCache, } from "./cache.js";
@@ -86,11 +88,49 @@ export async function detectCodexPhase(sessionFilePath, config) {
86
88
  return undefined;
87
89
  }
88
90
  }
89
- /** Build index of recent Codex sessions (last 7 days) */
91
+ /** Find the latest Codex state SQLite DB path */
92
+ function findCodexStateDb() {
93
+ const codexDir = join(homedir(), ".codex");
94
+ try {
95
+ const files = readdirSync(codexDir)
96
+ .filter((f) => f.startsWith("state_") && f.endsWith(".sqlite"))
97
+ .sort()
98
+ .reverse();
99
+ return files.length > 0 ? join(codexDir, files[0]) : undefined;
100
+ }
101
+ catch {
102
+ return undefined;
103
+ }
104
+ }
105
+ /** Build index of Codex sessions (SQLite primary, JSONL fallback) */
90
106
  export async function indexCodexSessions(config) {
91
107
  if (codexIndexCache && Date.now() - codexIndexCache.builtAt < CODEX_INDEX_TTL_MS) {
92
108
  return codexIndexCache.sessions;
93
109
  }
110
+ const hasExplicitSessionRoots = Boolean(config?.paths.codexSessions?.length);
111
+ // Primary: SQLite threads table
112
+ const dbPath = hasExplicitSessionRoots ? undefined : findCodexStateDb();
113
+ if (dbPath) {
114
+ const sqliteSessions = await indexCodexSessionsFromSqlite(dbPath);
115
+ if (sqliteSessions.length > 0) {
116
+ // Register sessions for phase detection and cwd lookup
117
+ for (const s of sqliteSessions) {
118
+ codexSessionFileCache.set(s.filePath, { ...s, mtimeMs: undefined, size: undefined });
119
+ upsertSessionRegistryEntry(codexSessionRegistry, {
120
+ filePath: s.filePath,
121
+ sessionId: s.id,
122
+ cwd: s.cwd,
123
+ firstSeenOffset: 0,
124
+ startedAt: s.timestamp,
125
+ model: s.model,
126
+ source: "codex",
127
+ });
128
+ }
129
+ setCodexIndexCache({ builtAt: Date.now(), sessions: sqliteSessions });
130
+ return sqliteSessions;
131
+ }
132
+ }
133
+ // Fallback: JSONL directory scan (last 7 days)
94
134
  const sessionRoots = getCodexSessionRoots(config);
95
135
  if (!sessionRoots.some((sessionsDir) => existsSync(sessionsDir)))
96
136
  return [];
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Simple concurrency limiter for Promise.all replacement.
3
+ * Limits how many tasks run in parallel to reduce CPU/IO spikes.
4
+ */
5
+ export declare function promiseAllLimited<T>(tasks: Array<() => Promise<T>>, limit: number): Promise<(T | null)[]>;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Simple concurrency limiter for Promise.all replacement.
3
+ * Limits how many tasks run in parallel to reduce CPU/IO spikes.
4
+ */
5
+ export async function promiseAllLimited(tasks, limit) {
6
+ const results = new Array(tasks.length).fill(null);
7
+ let index = 0;
8
+ async function worker() {
9
+ while (index < tasks.length) {
10
+ const i = index++;
11
+ try {
12
+ results[i] = await tasks[i]();
13
+ }
14
+ catch {
15
+ results[i] = null;
16
+ }
17
+ }
18
+ }
19
+ const workers = Array.from({ length: Math.min(limit, tasks.length) }, () => worker());
20
+ await Promise.all(workers);
21
+ return results;
22
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Daemon entry point — loaded by bin/daemon.js.
3
+ * Starts the background scan loop with default paths.
4
+ */
5
+ export {};
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Daemon entry point — loaded by bin/daemon.js.
3
+ * Starts the background scan loop with default paths.
4
+ */
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { loadConfig } from "../config/index.js";
8
+ import { getConfigDir } from "../config/index.js";
9
+ import { runDaemonLoop } from "./daemon-loop.js";
10
+ const DAEMON_DIR = join(tmpdir(), "marmonitor");
11
+ const CONFIG_DIR = getConfigDir();
12
+ async function main() {
13
+ process.title = "marmonitor";
14
+ const config = await loadConfig();
15
+ const intervalSec = Math.max(1, Math.min(30, Math.floor(config.performance.daemonIntervalSec)));
16
+ await runDaemonLoop(config, {
17
+ intervalMs: intervalSec * 1000,
18
+ detailIntervalMs: 30_000,
19
+ snapshotPath: join(DAEMON_DIR, "daemon-snapshot.json"),
20
+ pidPath: join(DAEMON_DIR, "daemon.pid"),
21
+ registryPath: join(CONFIG_DIR, "session-registry.json"),
22
+ });
23
+ }
24
+ main().catch((err) => {
25
+ process.stderr.write(`[marmonitor daemon] Fatal: ${err}\n`);
26
+ process.exit(1);
27
+ });
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Daemon scan loop — runs in background, writes snapshots and registry to files.
3
+ * Reuses watch/dock pattern: light scan every intervalMs, full every detailIntervalMs.
4
+ */
5
+ import type { MarmonitorConfig } from "../config/index.js";
6
+ export interface DaemonOptions {
7
+ intervalMs: number;
8
+ detailIntervalMs: number;
9
+ snapshotPath: string;
10
+ pidPath: string;
11
+ registryPath: string;
12
+ }
13
+ export declare function runDaemonLoop(config: MarmonitorConfig, options: DaemonOptions): Promise<void>;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Daemon scan loop — runs in background, writes snapshots and registry to files.
3
+ * Reuses watch/dock pattern: light scan every intervalMs, full every detailIntervalMs.
4
+ */
5
+ import { unlink } from "node:fs/promises";
6
+ import { writeDaemonPid, writeDaemonSnapshot } from "./daemon-utils.js";
7
+ import { scanAgents } from "./index.js";
8
+ import { perfEnd, perfStart } from "./perf.js";
9
+ import { loadRegistryFromFile, pruneRegistry, saveRegistryToFile, updateRegistry, } from "./session-registry.js";
10
+ function sleep(ms) {
11
+ return new Promise((resolve) => setTimeout(resolve, ms));
12
+ }
13
+ export async function runDaemonLoop(config, options) {
14
+ const { intervalMs, detailIntervalMs, snapshotPath, pidPath, registryPath } = options;
15
+ await writeDaemonPid(pidPath, process.pid);
16
+ const registry = new Map();
17
+ // Restore registry if saved recently (within 10 minutes)
18
+ try {
19
+ const { stat: fsStat } = await import("node:fs/promises");
20
+ const fileStat = await fsStat(registryPath);
21
+ const ageMs = Date.now() - fileStat.mtimeMs;
22
+ if (ageMs < 10 * 60 * 1000) {
23
+ await loadRegistryFromFile(registryPath, registry);
24
+ }
25
+ }
26
+ catch {
27
+ // file missing or inaccessible — start fresh
28
+ }
29
+ let lastHeavyAt = 0;
30
+ let running = true;
31
+ const shutdown = async () => {
32
+ if (!running)
33
+ return;
34
+ running = false;
35
+ // Save registry before exit
36
+ await saveRegistryToFile(registryPath, registry);
37
+ await unlink(pidPath).catch(() => { });
38
+ process.exit(0);
39
+ };
40
+ process.on("SIGTERM", shutdown);
41
+ process.on("SIGINT", shutdown);
42
+ // Memory monitor: warn if RSS exceeds 200MB
43
+ const RSS_WARN_MB = 200;
44
+ let lastMemWarnAt = 0;
45
+ while (running) {
46
+ const now = Date.now();
47
+ const needsHeavy = lastHeavyAt === 0 || now - lastHeavyAt >= detailIntervalMs;
48
+ const enrichmentMode = needsHeavy ? "full" : "light";
49
+ perfStart("daemon-scan");
50
+ try {
51
+ const agents = await scanAgents(config, { enrichmentMode });
52
+ if (needsHeavy)
53
+ lastHeavyAt = now;
54
+ // Update session registry
55
+ updateRegistry(registry, agents);
56
+ // Write snapshot for statusline consumers
57
+ await writeDaemonSnapshot(snapshotPath, agents);
58
+ // Save registry periodically (on heavy scan) + prune old entries
59
+ if (needsHeavy) {
60
+ pruneRegistry(registry, 30);
61
+ await saveRegistryToFile(registryPath, registry);
62
+ }
63
+ }
64
+ catch (err) {
65
+ // scan failures must never crash the daemon
66
+ process.stderr.write(`[marmonitor daemon] scan error: ${err}\n`);
67
+ }
68
+ perfEnd("daemon-scan");
69
+ // Memory check
70
+ const rssMb = process.memoryUsage.rss() / (1024 * 1024);
71
+ if (rssMb > RSS_WARN_MB && now - lastMemWarnAt > 60_000) {
72
+ process.stderr.write(`[marmonitor daemon] Warning: RSS ${Math.round(rssMb)}MB exceeds ${RSS_WARN_MB}MB\n`);
73
+ lastMemWarnAt = now;
74
+ }
75
+ await sleep(intervalMs);
76
+ }
77
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Daemon utility functions for PID management and snapshot I/O.
3
+ * Used by both the daemon loop and CLI commands.
4
+ */
5
+ export declare function writeDaemonPid(pidPath: string, pid: number): Promise<void>;
6
+ export declare function readDaemonPid(pidPath: string): Promise<number | undefined>;
7
+ export declare function isDaemonRunning(pidPath: string): Promise<boolean>;
8
+ export declare function writeDaemonSnapshot(snapshotPath: string, data: unknown[]): Promise<void>;
9
+ export declare function readDaemonSnapshot(snapshotPath: string, ttlMs: number): Promise<unknown[]>;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Daemon utility functions for PID management and snapshot I/O.
3
+ * Used by both the daemon loop and CLI commands.
4
+ */
5
+ import { mkdir, readFile, stat, unlink, writeFile } from "node:fs/promises";
6
+ import { dirname } from "node:path";
7
+ export async function writeDaemonPid(pidPath, pid) {
8
+ await mkdir(dirname(pidPath), { recursive: true });
9
+ await writeFile(pidPath, String(pid), "utf-8");
10
+ }
11
+ export async function readDaemonPid(pidPath) {
12
+ try {
13
+ const content = await readFile(pidPath, "utf-8");
14
+ const pid = Number.parseInt(content.trim(), 10);
15
+ return Number.isNaN(pid) ? undefined : pid;
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ export async function isDaemonRunning(pidPath) {
22
+ const pid = await readDaemonPid(pidPath);
23
+ if (pid === undefined)
24
+ return false;
25
+ try {
26
+ process.kill(pid, 0); // signal 0 = check if process exists
27
+ return true;
28
+ }
29
+ catch {
30
+ // process doesn't exist — stale PID file
31
+ await unlink(pidPath).catch(() => { });
32
+ return false;
33
+ }
34
+ }
35
+ export async function writeDaemonSnapshot(snapshotPath, data) {
36
+ try {
37
+ await mkdir(dirname(snapshotPath), { recursive: true });
38
+ await writeFile(snapshotPath, JSON.stringify(data), "utf-8");
39
+ }
40
+ catch {
41
+ // snapshot write failures must never crash the daemon
42
+ }
43
+ }
44
+ export async function readDaemonSnapshot(snapshotPath, ttlMs) {
45
+ try {
46
+ const fileStat = await stat(snapshotPath);
47
+ if (Date.now() - fileStat.mtimeMs > ttlMs)
48
+ return [];
49
+ const raw = await readFile(snapshotPath, "utf-8");
50
+ const parsed = JSON.parse(raw);
51
+ return Array.isArray(parsed) ? parsed : [];
52
+ }
53
+ catch {
54
+ return [];
55
+ }
56
+ }
@@ -14,7 +14,9 @@ export function toEpochSec(value) {
14
14
  export function parseGeminiSessionContent(raw) {
15
15
  try {
16
16
  const data = JSON.parse(raw);
17
- const messages = Array.isArray(data.messages) ? data.messages : [];
17
+ const messages = Array.isArray(data.messages)
18
+ ? data.messages.filter((msg) => msg != null)
19
+ : [];
18
20
  const latestMessage = messages.at(-1);
19
21
  const latestGeminiMessage = [...messages].reverse().find((msg) => msg.type === "gemini");
20
22
  const lastActivityAt = toEpochSec(data.lastUpdated) ??