marmonitor 0.2.6 → 0.2.7

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.
@@ -14,5 +14,42 @@ export declare function detectCodexPhase(sessionFilePath: string | undefined, co
14
14
  export declare function indexCodexSessions(config?: MarmonitorConfig, options?: {
15
15
  activeCwds?: string[];
16
16
  }): Promise<CodexSessionMeta[]>;
17
+ /**
18
+ * Session id a Codex process names in its own command line.
19
+ *
20
+ * This is an identity, not a guess, and it outranks every heuristic. Matching
21
+ * by cwd and nearest start time gets this wrong in the ordinary case of a
22
+ * resumed thread: the process starts today while its session file is dated
23
+ * whenever the thread began, so a newer unrelated session in the same cwd wins
24
+ * the proximity sort and two processes end up on one session (#114).
25
+ */
26
+ export declare function parseCodexSessionIdFromCmd(cmd: string | undefined): string | undefined;
27
+ export interface CodexSessionPick {
28
+ declaredSessionId: string | undefined;
29
+ sessions: CodexSessionMeta[];
30
+ claimedSessionIds: ReadonlySet<string>;
31
+ argvReservedSessionIds: ReadonlySet<string>;
32
+ cwd: string;
33
+ processStartedAt: number | undefined;
34
+ resolveBinding?: (available: CodexSessionMeta[]) => CodexSessionMeta | undefined;
35
+ }
36
+ /**
37
+ * Which session a Codex process owns, in order of how much the answer is
38
+ * actually known (#114).
39
+ *
40
+ * Binding to the wrong session is worse than not binding at all: a misbound
41
+ * process reports another session's tokens and jumps to its pane. So each step
42
+ * refuses instead of falling through to a weaker guess once the strong answer
43
+ * is unavailable.
44
+ *
45
+ * declared the id in the process's own command line — an identity
46
+ * binding what this exact PID resolved to before, from the registry
47
+ * heuristic cwd + nearest start time, the only option left
48
+ *
49
+ * Sessions already claimed this cycle, and sessions another process declared,
50
+ * are removed from the pool before the two weaker steps run — otherwise a guess
51
+ * can steal a session that someone else names outright.
52
+ */
53
+ export declare function selectCodexSessionForProcess(pick: CodexSessionPick): CodexSessionMeta | undefined;
17
54
  /** Match a Codex process to a session by cwd + closest timestamp */
18
55
  export declare function matchCodexSession(processCwd: string, processStartTime: number | undefined, sessions: CodexSessionMeta[]): CodexSessionMeta | undefined;
@@ -6,6 +6,7 @@ import { open, readFile, readdir, stat } from "node:fs/promises";
6
6
  import { homedir } from "node:os";
7
7
  import { join } from "node:path";
8
8
  import { indexCodexSessionsFromSqlite } from "./codex-sqlite.js";
9
+ import { CODEX_VALUE_OPTIONS, getCodexProcessArguments } from "./process.js";
9
10
  import { resolveRuntimeDataPaths } from "../config/index.js";
10
11
  import { advanceJsonlCursor, resolvePhaseFromHistory, resolvePhaseWithDecay, selectCodexSession, updatePhaseHistory, upsertSessionRegistryEntry, } from "../output/utils.js";
11
12
  import { CODEX_INDEX_TTL_MS, CODEX_PHASE_RECENT_LINES, HOME, codexIndexCache, codexPhaseCache, codexSessionFileCache, codexSessionRegistry, setCodexIndexCache, } from "./cache.js";
@@ -270,6 +271,138 @@ export async function indexCodexSessions(config, options) {
270
271
  });
271
272
  return sessions;
272
273
  }
274
+ const CODEX_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
275
+ const CODEX_SESSION_ID_RE = /^(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
276
+ const CODEX_BOOLEAN_OPTIONS = new Set([
277
+ "--all",
278
+ "--include-non-interactive",
279
+ "--strict-config",
280
+ "--oss",
281
+ "--approve-for-me",
282
+ "--dangerously-bypass-approvals-and-sandbox",
283
+ "--dangerously-bypass-hook-trust",
284
+ "--worktree",
285
+ "--search",
286
+ "--no-alt-screen",
287
+ "--no-daemon",
288
+ "--full-auto",
289
+ "--yolo",
290
+ ]);
291
+ /**
292
+ * Session id a Codex process names in its own command line.
293
+ *
294
+ * This is an identity, not a guess, and it outranks every heuristic. Matching
295
+ * by cwd and nearest start time gets this wrong in the ordinary case of a
296
+ * resumed thread: the process starts today while its session file is dated
297
+ * whenever the thread began, so a newer unrelated session in the same cwd wins
298
+ * the proximity sort and two processes end up on one session (#114).
299
+ */
300
+ export function parseCodexSessionIdFromCmd(cmd) {
301
+ if (!cmd)
302
+ return undefined;
303
+ const args = getCodexProcessArguments(cmd);
304
+ if (!args)
305
+ return undefined;
306
+ let resume = false;
307
+ let declared;
308
+ for (let i = 0; i < args.length; i++) {
309
+ const arg = args[i];
310
+ const option = arg.split("=", 1)[0];
311
+ if (arg === "--")
312
+ return declared;
313
+ if (["--last", "--help", "-h", "--version", "-V"].includes(arg))
314
+ return undefined;
315
+ // Image options are variadic; a display string cannot prove where their values end.
316
+ if (option === "--image" || option === "-i")
317
+ return undefined;
318
+ if (option === "--session-id" || option === "--session_id") {
319
+ const value = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : args[++i];
320
+ if (!value || !CODEX_SESSION_ID_RE.test(value))
321
+ return undefined;
322
+ if (declared && declared !== value.toLowerCase())
323
+ return undefined;
324
+ declared = value.toLowerCase();
325
+ }
326
+ else if (CODEX_VALUE_OPTIONS.has(option)) {
327
+ if (!arg.includes("=")) {
328
+ if (args[i + 1] === undefined)
329
+ return undefined;
330
+ i++;
331
+ }
332
+ }
333
+ else if (CODEX_BOOLEAN_OPTIONS.has(arg)) {
334
+ // Options may appear before or after the resume subcommand.
335
+ }
336
+ else if (arg.startsWith("-")) {
337
+ // Unknown options may consume a value. Do not guess a positional boundary.
338
+ return undefined;
339
+ }
340
+ else if (!resume) {
341
+ if (arg.toLowerCase() !== "resume")
342
+ return declared;
343
+ resume = true;
344
+ }
345
+ else {
346
+ const resumed = arg.toLowerCase();
347
+ return CODEX_UUID_RE.test(arg) && (!declared || declared === resumed) ? resumed : undefined;
348
+ }
349
+ }
350
+ return declared;
351
+ }
352
+ /**
353
+ * Which session a Codex process owns, in order of how much the answer is
354
+ * actually known (#114).
355
+ *
356
+ * Binding to the wrong session is worse than not binding at all: a misbound
357
+ * process reports another session's tokens and jumps to its pane. So each step
358
+ * refuses instead of falling through to a weaker guess once the strong answer
359
+ * is unavailable.
360
+ *
361
+ * declared the id in the process's own command line — an identity
362
+ * binding what this exact PID resolved to before, from the registry
363
+ * heuristic cwd + nearest start time, the only option left
364
+ *
365
+ * Sessions already claimed this cycle, and sessions another process declared,
366
+ * are removed from the pool before the two weaker steps run — otherwise a guess
367
+ * can steal a session that someone else names outright.
368
+ */
369
+ export function selectCodexSessionForProcess(pick) {
370
+ const { declaredSessionId, sessions, claimedSessionIds } = pick;
371
+ if (declaredSessionId) {
372
+ if (claimedSessionIds.has(declaredSessionId))
373
+ return undefined;
374
+ return sessions.find((session) => session.id === declaredSessionId);
375
+ }
376
+ const available = sessions.filter((session) => !claimedSessionIds.has(session.id) && !pick.argvReservedSessionIds.has(session.id));
377
+ const bound = pick.resolveBinding?.(available);
378
+ if (bound) {
379
+ const bornWith = sessionBornWithProcess(available, pick.cwd, pick.processStartedAt);
380
+ // A persisted binding can be an old heuristic guess. If this process never
381
+ // wrote the bound file but did create a rollout at startup, the rollout wins
382
+ // and the caller's upsert repairs the registry record.
383
+ if (bornWith &&
384
+ bornWith.id !== bound.id &&
385
+ pick.processStartedAt !== undefined &&
386
+ (bound.lastActivityAt ?? bound.timestamp) < pick.processStartedAt - CODEX_START_SLACK_SEC) {
387
+ return bornWith;
388
+ }
389
+ return bound;
390
+ }
391
+ return matchCodexSession(pick.cwd, pick.processStartedAt, available);
392
+ }
393
+ const CODEX_START_SLACK_SEC = 5;
394
+ /** Codex creates its rollout within seconds of process start. */
395
+ const CODEX_ROLLOUT_BIRTH_WINDOW_SEC = 60;
396
+ /** The one rollout in this cwd created right after the process started, if
397
+ * exactly one exists. Two processes starting together make it ambiguous. */
398
+ function sessionBornWithProcess(sessions, cwd, processStartedAt) {
399
+ if (processStartedAt === undefined)
400
+ return undefined;
401
+ const born = sessions.filter((session) => session.cwd === cwd &&
402
+ session.timestamp >= processStartedAt - CODEX_START_SLACK_SEC &&
403
+ session.timestamp <= processStartedAt + CODEX_ROLLOUT_BIRTH_WINDOW_SEC);
404
+ return born.length === 1 ? born[0] : undefined;
405
+ }
273
406
  /** Match a Codex process to a session by cwd + closest timestamp */
274
407
  export function matchCodexSession(processCwd, processStartTime, sessions) {
275
408
  return selectCodexSession(processCwd, processStartTime, sessions);
@@ -127,6 +127,9 @@ export async function runDaemonLoop(config, options) {
127
127
  startedAt: agent.startedAt,
128
128
  tokenUsage: agent.tokenUsage,
129
129
  lastActivityAt: agent.lastActivityAt,
130
+ // #113: without this, updateRegistry() falls back to the merged
131
+ // lastActivityAt and writes the busy inference to disk.
132
+ observedActivityAt: agent.observedActivityAt,
130
133
  model: agent.model,
131
134
  jsonlPath: sessionFile,
132
135
  });
@@ -6,4 +6,15 @@ export declare function writeDaemonPid(pidPath: string, pid: number): Promise<vo
6
6
  export declare function readDaemonPid(pidPath: string): Promise<number | undefined>;
7
7
  export declare function isDaemonRunning(pidPath: string): Promise<boolean>;
8
8
  export declare function writeDaemonSnapshot(snapshotPath: string, data: unknown[]): Promise<void>;
9
+ export type SnapshotReadResult = {
10
+ health: "fresh" | "stale";
11
+ agents: unknown[];
12
+ ageMs: number;
13
+ } | {
14
+ health: "missing" | "unreadable" | "invalid";
15
+ };
16
+ /** Read data and age from the same file generation, including during atomic replacement.
17
+ * Stale data is diagnostic evidence; callers must explicitly require fresh data for actions. */
18
+ export declare function readDaemonSnapshotResult(snapshotPath: string, ttlMs: number): Promise<SnapshotReadResult>;
19
+ /** Compatibility helper for consumers that accept only fresh data. */
9
20
  export declare function readDaemonSnapshot(snapshotPath: string, ttlMs: number): Promise<unknown[]>;
@@ -2,7 +2,8 @@
2
2
  * Daemon utility functions for PID management and snapshot I/O.
3
3
  * Used by both the daemon loop and CLI commands.
4
4
  */
5
- import { mkdir, readFile, stat, unlink, writeFile } from "node:fs/promises";
5
+ import { randomUUID } from "node:crypto";
6
+ import { mkdir, open, readFile, rename, unlink, writeFile } from "node:fs/promises";
6
7
  import { dirname } from "node:path";
7
8
  export async function writeDaemonPid(pidPath, pid) {
8
9
  await mkdir(dirname(pidPath), { recursive: true });
@@ -33,24 +34,54 @@ export async function isDaemonRunning(pidPath) {
33
34
  }
34
35
  }
35
36
  export async function writeDaemonSnapshot(snapshotPath, data) {
37
+ const temporaryPath = `${snapshotPath}.${process.pid}.${randomUUID()}.tmp`;
36
38
  try {
37
39
  await mkdir(dirname(snapshotPath), { recursive: true });
38
- await writeFile(snapshotPath, JSON.stringify(data), "utf-8");
40
+ await writeFile(temporaryPath, JSON.stringify(data), {
41
+ encoding: "utf-8",
42
+ mode: 0o600,
43
+ flag: "wx",
44
+ });
45
+ await rename(temporaryPath, snapshotPath);
39
46
  }
40
47
  catch {
41
48
  // snapshot write failures must never crash the daemon
42
49
  }
50
+ finally {
51
+ await unlink(temporaryPath).catch(() => { });
52
+ }
43
53
  }
44
- export async function readDaemonSnapshot(snapshotPath, ttlMs) {
54
+ /** Read data and age from the same file generation, including during atomic replacement.
55
+ * Stale data is diagnostic evidence; callers must explicitly require fresh data for actions. */
56
+ export async function readDaemonSnapshotResult(snapshotPath, ttlMs) {
45
57
  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 : [];
58
+ const file = await open(snapshotPath, "r");
59
+ try {
60
+ const [fileStat, raw] = await Promise.all([file.stat(), file.readFile("utf-8")]);
61
+ let parsed;
62
+ try {
63
+ parsed = JSON.parse(raw);
64
+ }
65
+ catch {
66
+ return { health: "invalid" };
67
+ }
68
+ if (!Array.isArray(parsed))
69
+ return { health: "invalid" };
70
+ const ageMs = Math.max(0, Date.now() - fileStat.mtimeMs);
71
+ return { health: ageMs > ttlMs ? "stale" : "fresh", agents: parsed, ageMs };
72
+ }
73
+ finally {
74
+ await file.close();
75
+ }
52
76
  }
53
- catch {
54
- return [];
77
+ catch (error) {
78
+ return {
79
+ health: error.code === "ENOENT" ? "missing" : "unreadable",
80
+ };
55
81
  }
56
82
  }
83
+ /** Compatibility helper for consumers that accept only fresh data. */
84
+ export async function readDaemonSnapshot(snapshotPath, ttlMs) {
85
+ const result = await readDaemonSnapshotResult(snapshotPath, ttlMs);
86
+ return result.health === "fresh" ? result.agents : [];
87
+ }
@@ -2,6 +2,6 @@
2
2
  * Process tree grouping and worker state propagation.
3
3
  */
4
4
  import type { AgentSession } from "../types.js";
5
- export declare function propagateWorkerStateToParent(parent: AgentSession, child: Pick<AgentSession, "status" | "phase" | "lastActivityAt" | "lastResponseAt" | "startedAt" | "cpuPercent" | "memoryMb">): AgentSession;
5
+ export declare function propagateWorkerStateToParent(parent: AgentSession, child: Pick<AgentSession, "status" | "phase" | "lastActivityAt" | "observedActivityAt" | "lastResponseAt" | "startedAt" | "cpuPercent" | "memoryMb" | "resourceUsageAvailable">): AgentSession;
6
6
  /** Group child agent processes under their parent */
7
7
  export declare function groupByParent(sessions: AgentSession[]): AgentSession[];
@@ -15,10 +15,17 @@ export function propagateWorkerStateToParent(parent, child) {
15
15
  phase: inheritedPhase,
16
16
  cpuPercent: parent.cpuPercent + (("cpuPercent" in child && child.cpuPercent) || 0),
17
17
  memoryMb: parent.memoryMb + (("memoryMb" in child && child.memoryMb) || 0),
18
+ resourceUsageAvailable: parent.resourceUsageAvailable !== false && child.resourceUsageAvailable !== false,
18
19
  startedAt: parent.startedAt && child.startedAt
19
20
  ? Math.min(parent.startedAt, child.startedAt)
20
21
  : (parent.startedAt ?? child.startedAt),
21
22
  lastActivityAt: Math.max(parent.lastActivityAt ?? 0, child.lastActivityAt ?? 0, child.lastResponseAt ?? 0, child.startedAt ?? 0),
23
+ // #113: raise the observed component alongside the merged one. Only
24
+ // observed times are persisted now, so leaving this behind would drop a
25
+ // worker's genuinely observed activity from the parent's registry record
26
+ // and break the `lastActivityAt = max(observed, fresh inference)`
27
+ // invariant. The child's own observed field is used, never its merged one.
28
+ observedActivityAt: Math.max(parent.observedActivityAt ?? 0, child.observedActivityAt ?? 0, child.lastResponseAt ?? 0, child.startedAt ?? 0) || undefined,
22
29
  lastResponseAt: Math.max(parent.lastResponseAt ?? 0, child.lastResponseAt ?? 0) || undefined,
23
30
  };
24
31
  }
@@ -36,11 +43,13 @@ export function groupByParent(sessions) {
36
43
  pid: session.pid,
37
44
  cpuPercent: session.cpuPercent,
38
45
  memoryMb: session.memoryMb,
46
+ resourceUsageAvailable: session.resourceUsageAvailable,
39
47
  status: session.status,
40
48
  });
41
49
  const propagated = propagateWorkerStateToParent(parent, session);
42
50
  parent.cpuPercent = propagated.cpuPercent;
43
51
  parent.memoryMb = propagated.memoryMb;
52
+ parent.resourceUsageAvailable = propagated.resourceUsageAvailable;
44
53
  parent.status = propagated.status;
45
54
  parent.phase = propagated.phase;
46
55
  parent.startedAt = propagated.startedAt;
@@ -12,5 +12,23 @@ export { detectAgentFromProcessSignature } from "./process.js";
12
12
  export { propagateWorkerStateToParent } from "./group.js";
13
13
  export { parseGeminiSessionContent } from "./gemini.js";
14
14
  import type { ScanOptions } from "./types.js";
15
+ /**
16
+ * Whether a Claude PID belongs in the batch mtime resolution pass (#108).
17
+ *
18
+ * The batch scores candidates against `processStartedAt` inside a known cwd,
19
+ * so a PID missing either is unscorable there. Such a PID must fall through to
20
+ * the per-PID matcher, which still has an mtime-dominance fallback — keeping it
21
+ * in the batch would mark it "resolved to nothing" instead. `ps -o lstart=`
22
+ * failures are cached for PROCESS_START_TTL_MS, so one transient failure would
23
+ * otherwise leave the session unbound for that entire window.
24
+ *
25
+ * NaN must be rejected as firmly as undefined: getProcessStartTime derives the
26
+ * value with `new Date(...).getTime()`, so an unparseable `ps` line yields NaN,
27
+ * and a NaN deltaSec silently passes every `>` threshold comparison.
28
+ */
29
+ export declare function isBatchableClaudeMtimeRequest<T extends {
30
+ cwd?: string;
31
+ processStartedAt?: number;
32
+ }>(request: T | null | undefined): request is T;
15
33
  /** Scan for all running AI agent sessions */
16
34
  export declare function scanAgents(config: MarmonitorConfig, options?: ScanOptions): Promise<AgentSession[]>;