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.
@@ -339,6 +339,7 @@ export function buildAttentionItems(agents, nowSec = Date.now() / 1000) {
339
339
  cwd: agent.cwd,
340
340
  cpuPercent: agent.cpuPercent,
341
341
  memoryMb: agent.memoryMb,
342
+ resourceUsageAvailable: agent.resourceUsageAvailable,
342
343
  startedAt: agent.startedAt,
343
344
  runtimeSource: agent.runtimeSource,
344
345
  status: agent.status,
@@ -586,7 +587,61 @@ export function buildTmuxBadgeBar(snapshot, focusText, badgeStyle = "basic", has
586
587
  const focus = focusText ? renderFocus(theme, focusText) : "";
587
588
  return [agentPills.join(" "), alertPills.join(" "), jumpBack, focus].filter(Boolean).join(" ");
588
589
  }
589
- export function buildTmuxAttentionPills(items, maxCount = 5, width, badgeStyle = "basic", activeAgentPid) {
590
+ /** Build identities before truncating attention items so hidden siblings do
591
+ * not make a visible label alternate between ambiguous and unambiguous. */
592
+ function statuslineLabels(items, maxLength, options) {
593
+ const candidates = [
594
+ ...new Map([...(options.collisionItems ?? []), ...items].map((item) => [item.pid, item])).values(),
595
+ ];
596
+ const mode = options.mode ?? "auto";
597
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: sanitize untrusted display names
598
+ const clean = (value) => value.replace(/[\x00-\x1f\x7f]/g, "?");
599
+ const paths = new Map(candidates.map((item) => [item.pid, clean(compactStatuslineDirLabel(item.cwd, maxLength))]));
600
+ const counts = new Map();
601
+ for (const path of paths.values())
602
+ counts.set(path, (counts.get(path) ?? 0) + 1);
603
+ const fit = (item, identity) => {
604
+ const suffix = identity.length <= maxLength ? identity : `pid:${item.pid}`;
605
+ const budget = maxLength - suffix.length - 1;
606
+ return budget > 0
607
+ ? `${truncateMiddle(clean(compactStatuslineDirLabel(item.cwd, budget)), budget)} ${suffix}`
608
+ : suffix;
609
+ };
610
+ const labels = new Map();
611
+ for (const item of candidates) {
612
+ const path = paths.get(item.pid) ?? "";
613
+ const collision = (counts.get(path) ?? 0) > 1;
614
+ const target = options.tmuxTargets?.get(item.pid);
615
+ const location = target && target.match !== "cwd"
616
+ ? clean(`@${target.pane.sessionName}:${target.pane.windowIndex}.${target.pane.paneIndex}`)
617
+ : undefined;
618
+ if (mode === "path" || (mode === "auto" && !collision)) {
619
+ labels.set(item.pid, path);
620
+ }
621
+ else if (mode === "tmux" && location) {
622
+ labels.set(item.pid, location.length <= maxLength ? location : `pid:${item.pid}`);
623
+ }
624
+ else if (collision) {
625
+ labels.set(item.pid, fit(item, location ?? `pid:${item.pid}`));
626
+ }
627
+ else {
628
+ labels.set(item.pid, path);
629
+ }
630
+ }
631
+ // Two real CLIs can share a pane, and sanitized names can also collide.
632
+ const labelCounts = new Map();
633
+ for (const label of labels.values())
634
+ labelCounts.set(label, (labelCounts.get(label) ?? 0) + 1);
635
+ for (const item of candidates) {
636
+ let label = labels.get(item.pid) ?? "";
637
+ if (mode !== "path" && (labelCounts.get(label) ?? 0) > 1)
638
+ label = fit(item, `pid:${item.pid}`);
639
+ // tmux interprets # syntax and terminal controls in subprocess output.
640
+ labels.set(item.pid, label.replace(/#/g, "##"));
641
+ }
642
+ return labels;
643
+ }
644
+ export function buildTmuxAttentionPills(items, maxCount = 5, width, badgeStyle = "basic", activeAgentPid, labelOptions = {}) {
590
645
  if (maxCount <= 0)
591
646
  return undefined;
592
647
  const layout = resolveStatuslineDetailLayout(width, maxCount);
@@ -594,12 +649,13 @@ export function buildTmuxAttentionPills(items, maxCount = 5, width, badgeStyle =
594
649
  .filter((item) => item.kind !== "unmatched" && item.kind !== "stalled")
595
650
  .slice(0, layout.itemCount);
596
651
  const theme = resolveTheme(badgeStyle);
652
+ const labels = statuslineLabels(items, layout.pathMaxLength, labelOptions);
597
653
  if (jumpItems.length === 0) {
598
654
  return theme.empty;
599
655
  }
600
656
  const segments = jumpItems.map((item, index) => {
601
657
  const agent = agentShortName(item.agentName);
602
- const path = compactStatuslineDirLabel(item.cwd, layout.pathMaxLength);
658
+ const path = labels.get(item.pid) ?? compactStatuslineDirLabel(item.cwd, layout.pathMaxLength);
603
659
  const time = formatElapsedCompact(item.lastActivityAt ?? item.lastResponseAt);
604
660
  const label = item.kind === "permission"
605
661
  ? `⏳${agent} ${path} allow`
@@ -10,9 +10,19 @@ export declare const PROCESS_START_TTL_MS = 300000;
10
10
  export declare const CODEX_INDEX_TTL_MS = 30000;
11
11
  export declare const CLAUDE_SESSION_MTIME_MATCH_SEC = 120;
12
12
  export declare const CLAUDE_SESSION_AMBIGUITY_GAP_SEC = 300;
13
+ export declare const CLAUDE_MATCH_TOP_DELTA_SEC = 10;
14
+ export declare const CLAUDE_MATCH_GAP_SEC = 5;
13
15
  export declare const CLAUDE_PHASE_RECENT_LINES = 50;
14
16
  export declare const CODEX_PHASE_RECENT_LINES = 30;
15
17
  export declare const RECENT_ACTIVITY_ACTIVE_SEC = 180;
18
+ /**
19
+ * How long a Codex "looks busy" inference (CPU burst / stdout phase) may stand
20
+ * in for observed activity. #090 added the inference so `last activity` would
21
+ * not snap back to the old rollout mtime the moment a tool finished; #113 is
22
+ * the same value never expiring, leaving a session that went quiet ten days
23
+ * ago looking recent forever. Real work keeps re-stamping within this window.
24
+ */
25
+ export declare const CODEX_INFERRED_BUSY_TTL_SEC = 180;
16
26
  export declare const STATUS_HYSTERESIS_SEC = 30;
17
27
  export interface FileTokenCacheEntry {
18
28
  mtimeMs: number;
@@ -10,9 +10,23 @@ export const PROCESS_START_TTL_MS = 300_000;
10
10
  export const CODEX_INDEX_TTL_MS = 30_000;
11
11
  export const CLAUDE_SESSION_MTIME_MATCH_SEC = 120;
12
12
  export const CLAUDE_SESSION_AMBIGUITY_GAP_SEC = 300;
13
+ // Dual-threshold for matchClaudeSessionByMtime: a jsonl must be (a) authored
14
+ // close enough to processStartedAt AND (b) clearly closer than the runner-up.
15
+ // See local issue #108 — without (b), two near-simultaneous Claude starts in
16
+ // the same cwd collapse onto the same sessionId in the daemon snapshot.
17
+ export const CLAUDE_MATCH_TOP_DELTA_SEC = 10;
18
+ export const CLAUDE_MATCH_GAP_SEC = 5;
13
19
  export const CLAUDE_PHASE_RECENT_LINES = 50;
14
20
  export const CODEX_PHASE_RECENT_LINES = 30;
15
21
  export const RECENT_ACTIVITY_ACTIVE_SEC = 180;
22
+ /**
23
+ * How long a Codex "looks busy" inference (CPU burst / stdout phase) may stand
24
+ * in for observed activity. #090 added the inference so `last activity` would
25
+ * not snap back to the old rollout mtime the moment a tool finished; #113 is
26
+ * the same value never expiring, leaving a session that went quiet ten days
27
+ * ago looking recent forever. Real work keeps re-stamping within this window.
28
+ */
29
+ export const CODEX_INFERRED_BUSY_TTL_SEC = RECENT_ACTIVITY_ACTIVE_SEC;
16
30
  export const STATUS_HYSTERESIS_SEC = 30;
17
31
  // ─── Cache Instances ───────────────────────────────────────────────
18
32
  export const claudeProjectDirCache = new BoundedMap(64);
@@ -21,12 +21,79 @@ export declare function parseClaudeTokens(sessionId: string, cwd: string, starte
21
21
  * Detect current Claude session phase by reading the last few lines of JSONL.
22
22
  */
23
23
  export declare function detectClaudePhase(sessionId: string, cwd: string, startedAt?: number, config?: MarmonitorConfig): Promise<PhaseResult>;
24
+ /**
25
+ * Claude Code writes `procStart` into ~/.claude/sessions/<pid>.json as a UTC
26
+ * calendar string ("Mon Aug 17 05:43:19 2026"). Measured against `ps -o
27
+ * lstart=` on every live session, it names the same instant to the second —
28
+ * so it identifies which *incarnation* of a PID authored the file.
29
+ *
30
+ * `new Date()` would read the string as local time, which is off by the UTC
31
+ * offset, hence the explicit suffix.
32
+ */
33
+ export declare function parseClaudePidJsonProcStart(procStart: unknown): number | undefined;
34
+ /**
35
+ * Whether a pid.json was written by the process currently holding that PID.
36
+ *
37
+ * PIDs are recycled, and the legacy lookup trusts `sessions/<pid>.json` on
38
+ * filename alone — a new process inheriting a dead one's PID would adopt its
39
+ * sessionId. Comparing `procStart` against the live start time settles that
40
+ * deterministically instead of inferring it from mtime staleness.
41
+ *
42
+ * Returns "unknown" when either side is missing (older Claude Code builds have
43
+ * no `procStart`, and `ps` can fail), so callers keep their previous behaviour
44
+ * rather than discarding a record they cannot judge.
45
+ */
46
+ export declare function classifyClaudePidJsonOwnership(procStart: unknown, processStartedAt: number | undefined): "owned" | "recycled" | "unknown";
47
+ export interface ClaudeMtimeMatchRequest {
48
+ pid: number;
49
+ cwd?: string;
50
+ processStartedAt?: number;
51
+ }
52
+ export interface ClaudeMtimeMatch {
53
+ filePath: string;
54
+ sessionId: string;
55
+ cwd: string;
56
+ startedAt?: number;
57
+ lastActivityAt: number;
58
+ }
59
+ export interface ClaudeMtimeBatchOptions {
60
+ /**
61
+ * Live Claude PID count per cwd, counting every process that could own a
62
+ * jsonl there — including PIDs this batch cannot score (unreadable lstart)
63
+ * and PIDs already resolved through legacy pid.json. Sole ownership judged
64
+ * from the batch's own group would miss those and wrongly relax.
65
+ */
66
+ liveClaudePidCountByCwd?: ReadonlyMap<string, number>;
67
+ /** sessionIds already owned via legacy pid.json — never propose them. */
68
+ reservedSessionIds?: ReadonlySet<string>;
69
+ }
70
+ /**
71
+ * Select mtime matches for all same-cwd Claude PIDs in one scan cycle.
72
+ *
73
+ * A one-PID-at-a-time resolver is order-dependent: when process A's first
74
+ * message is delayed, it can claim process B's fresher JSONL before B is
75
+ * scanned. Resolve competing proposals as a batch instead. If two PIDs are
76
+ * within the same dominance window for one JSONL, leave it unbound rather
77
+ * than guessing an owner.
78
+ */
79
+ export declare function matchClaudeSessionsByMtime(requests: ClaudeMtimeMatchRequest[], config?: MarmonitorConfig, options?: ClaudeMtimeBatchOptions): Promise<Map<number, ClaudeMtimeMatch>>;
24
80
  /**
25
81
  * Match a Claude session by scanning JSONL files in the project directory.
26
82
  * When processStartedAt is available, matches by JSONL creation timestamp
27
83
  * (first-line timestamp) proximity to process start time.
28
84
  * Falls back to the most recently modified JSONL when no start time is available.
85
+ *
86
+ * Fail-closed dual threshold (local issue #108): a candidate is accepted only
87
+ * when (a) its proximity to processStartedAt is within CLAUDE_MATCH_TOP_DELTA_SEC
88
+ * AND (b) it dominates the runner-up by at least CLAUDE_MATCH_GAP_SEC. When
89
+ * cycleClaimedSessionIds is supplied, any session already bound to another PID
90
+ * in this scan cycle is excluded from the candidate pool — without this, two
91
+ * same-cwd Claude PIDs whose lstart falls in the same second tiebreak onto the
92
+ * same jsonl and the daemon snapshot collapses both PIDs onto one sessionId.
29
93
  */
30
- export declare function matchClaudeSessionByMtime(cwd: string, processStartedAt: number | undefined, config?: MarmonitorConfig): Promise<Partial<AgentSession> | undefined>;
31
- /** Parse Claude Code session file for enriched data */
32
- export declare function parseClaudeSession(pid: number, cwd?: string, processStartedAt?: number, config?: MarmonitorConfig): Promise<Partial<AgentSession>>;
94
+ export declare function matchClaudeSessionByMtime(cwd: string, processStartedAt: number | undefined, config?: MarmonitorConfig, cycleClaimedSessionIds?: Set<string>): Promise<Partial<AgentSession> | undefined>;
95
+ /** Parse Claude Code session file for enriched data.
96
+ * cycleClaimedSessionIds (#108): per-scan-cycle Set of sessionIds already
97
+ * bound to another PID. Threaded to matchClaudeSessionByMtime so same-cwd
98
+ * multi-PID environments cannot collapse onto a single sessionId. */
99
+ export declare function parseClaudeSession(pid: number, cwd?: string, processStartedAt?: number, config?: MarmonitorConfig, cycleClaimedSessionIds?: Set<string>, preselectedMtimeMatch?: ClaudeMtimeMatch | null, reservedSessionIds?: ReadonlySet<string>): Promise<Partial<AgentSession>>;
@@ -6,7 +6,7 @@ import { realpath as fsRealpath, open, readFile, readdir, stat } from "node:fs/p
6
6
  import { basename, join } from "node:path";
7
7
  import { resolveRuntimeDataPaths } from "../config/index.js";
8
8
  import { advanceJsonlCursor, resolvePhaseFromHistory, resolvePhaseWithDecay, resolveSessionRegistryPath, selectRecentSessionFile, updatePhaseHistory, upsertSessionRegistryEntry, } from "../output/utils.js";
9
- import { CLAUDE_PHASE_RECENT_LINES, CLAUDE_SESSION_MTIME_MATCH_SEC, HOME, claudePhaseCache, claudeProjectDirCache, claudeSessionRegistry, claudeTokenCache, } from "./cache.js";
9
+ import { CLAUDE_MATCH_GAP_SEC, CLAUDE_MATCH_TOP_DELTA_SEC, CLAUDE_PHASE_RECENT_LINES, CLAUDE_SESSION_MTIME_MATCH_SEC, HOME, claudePhaseCache, claudeProjectDirCache, claudeSessionRegistry, claudeTokenCache, } from "./cache.js";
10
10
  async function listClaudeSessionCandidates(projectDirName, projectRoots) {
11
11
  const candidates = [];
12
12
  for (const projectsDir of projectRoots) {
@@ -418,6 +418,45 @@ async function readJsonlSessionMeta(filePath) {
418
418
  await fd?.close().catch(() => { });
419
419
  }
420
420
  }
421
+ /**
422
+ * Claude Code writes `procStart` into ~/.claude/sessions/<pid>.json as a UTC
423
+ * calendar string ("Mon Aug 17 05:43:19 2026"). Measured against `ps -o
424
+ * lstart=` on every live session, it names the same instant to the second —
425
+ * so it identifies which *incarnation* of a PID authored the file.
426
+ *
427
+ * `new Date()` would read the string as local time, which is off by the UTC
428
+ * offset, hence the explicit suffix.
429
+ */
430
+ export function parseClaudePidJsonProcStart(procStart) {
431
+ if (typeof procStart !== "string" || !procStart.trim())
432
+ return undefined;
433
+ const parsed = new Date(`${procStart.trim()} UTC`).getTime();
434
+ return Number.isFinite(parsed) ? parsed / 1000 : undefined;
435
+ }
436
+ /** Slack for the one-second rendering precision on both sides of the compare. */
437
+ const CLAUDE_PROC_START_TOLERANCE_SEC = 2;
438
+ /**
439
+ * Whether a pid.json was written by the process currently holding that PID.
440
+ *
441
+ * PIDs are recycled, and the legacy lookup trusts `sessions/<pid>.json` on
442
+ * filename alone — a new process inheriting a dead one's PID would adopt its
443
+ * sessionId. Comparing `procStart` against the live start time settles that
444
+ * deterministically instead of inferring it from mtime staleness.
445
+ *
446
+ * Returns "unknown" when either side is missing (older Claude Code builds have
447
+ * no `procStart`, and `ps` can fail), so callers keep their previous behaviour
448
+ * rather than discarding a record they cannot judge.
449
+ */
450
+ export function classifyClaudePidJsonOwnership(procStart, processStartedAt) {
451
+ const recorded = parseClaudePidJsonProcStart(procStart);
452
+ if (recorded === undefined)
453
+ return "unknown";
454
+ if (processStartedAt === undefined || !Number.isFinite(processStartedAt))
455
+ return "unknown";
456
+ return Math.abs(recorded - processStartedAt) <= CLAUDE_PROC_START_TOLERANCE_SEC
457
+ ? "owned"
458
+ : "recycled";
459
+ }
421
460
  /**
422
461
  * Stale-session override resolver.
423
462
  *
@@ -437,7 +476,7 @@ async function readJsonlSessionMeta(filePath) {
437
476
  * - F3: anything ambiguous falls through to `undefined` (unresolved) —
438
477
  * a missed match is safer than a misrouted one.
439
478
  */
440
- async function chooseStaleSessionOverride(processCwd, currentSessionId, processStartedAt, config) {
479
+ async function chooseStaleSessionOverride(processCwd, currentSessionId, processStartedAt, config, cycleClaimedSessionIds, reservedSessionIds) {
441
480
  const projectDirName = await findClaudeProjectDir(processCwd, currentSessionId, config);
442
481
  if (!projectDirName)
443
482
  return undefined;
@@ -488,6 +527,16 @@ async function chooseStaleSessionOverride(processCwd, currentSessionId, processS
488
527
  return undefined;
489
528
  if (recentMeta.sessionId === currentSessionId)
490
529
  return undefined;
530
+ // #108: a session chosen by the stale override is just as capable of
531
+ // collapsing two PIDs as a direct mtime match. The per-cycle ownership
532
+ // check must therefore cover this legacy path as well.
533
+ if (cycleClaimedSessionIds?.has(recentMeta.sessionId))
534
+ return undefined;
535
+ // Active PID metadata and batch-selected mtime matches are reserved before
536
+ // individual parsing begins. A stale legacy record must not steal one of
537
+ // those sibling sessions merely because it acquired the mutex first.
538
+ if (reservedSessionIds?.has(recentMeta.sessionId))
539
+ return undefined;
491
540
  // F2: the candidate sessionId is already direct-bound in the registry.
492
541
  // Overriding would let two sessionIds share one jsonl — the exact bug
493
542
  // in #103. Keeps the one-jsonl-per-sessionId invariant.
@@ -501,13 +550,186 @@ async function chooseStaleSessionOverride(processCwd, currentSessionId, processS
501
550
  filePath: recentPath,
502
551
  };
503
552
  }
553
+ /** How far one jsonl must lead the runner-up by mtime to win without timestamps. */
554
+ const CLAUDE_MTIME_FALLBACK_LEAD_MS = 5 * 60 * 1000;
555
+ async function listClaudeMtimeCandidates(cwd, config) {
556
+ const projectDirName = await findClaudeProjectDir(cwd, undefined, config);
557
+ if (!projectDirName)
558
+ return [];
559
+ const candidates = await listClaudeSessionCandidates(projectDirName, getClaudeProjectRoots(config)).catch(() => []);
560
+ const result = [];
561
+ for (const candidate of candidates) {
562
+ const meta = await readJsonlSessionMeta(candidate.path);
563
+ if (!meta?.sessionId)
564
+ continue;
565
+ // A jsonl whose meta window carries no timestamp is still a real session —
566
+ // dropping it here would hide the only candidate in a cwd and leave a live
567
+ // PID permanently unbound. Keep it and let the mtime fallback score it.
568
+ const timestampMs = meta.timestamp ? new Date(meta.timestamp).getTime() : Number.NaN;
569
+ result.push({
570
+ ...candidate,
571
+ sessionId: meta.sessionId,
572
+ cwd: meta.cwd,
573
+ timestamp: Number.isFinite(timestampMs) ? meta.timestamp : undefined,
574
+ });
575
+ }
576
+ return result;
577
+ }
578
+ function scoreClaudeMtimeCandidates(candidates, processStartedAt) {
579
+ const startMs = processStartedAt * 1000;
580
+ const active = candidates.filter((candidate) => candidate.mtimeMs >= startMs - CLAUDE_SESSION_MTIME_MATCH_SEC * 1000);
581
+ const pool = active.length > 0 ? active : candidates;
582
+ const activeCount = active.length;
583
+ const scored = pool
584
+ .filter((candidate) => candidate.timestamp !== undefined)
585
+ .map((candidate) => ({
586
+ ...candidate,
587
+ deltaSec: Math.abs(new Date(candidate.timestamp).getTime() / 1000 - processStartedAt),
588
+ }))
589
+ .sort((a, b) => a.deltaSec - b.deltaSec);
590
+ if (scored.length > 0)
591
+ return { scored, activeCount };
592
+ // No candidate carries a first-line timestamp, so proximity scoring is
593
+ // impossible. Mirror matchClaudeSessionByMtime's fallback: commit only when
594
+ // one jsonl clearly leads the rest by mtime. deltaSec 0 marks it as the sole
595
+ // proposal — two PIDs reaching this path for the same jsonl still tie and
596
+ // therefore still cancel each other out in the contention pass.
597
+ const byMtime = [...pool].sort((a, b) => b.mtimeMs - a.mtimeMs);
598
+ const latest = byMtime[0];
599
+ const runnerUp = byMtime[1];
600
+ if (!latest)
601
+ return { scored: [], activeCount };
602
+ if (runnerUp && latest.mtimeMs - runnerUp.mtimeMs < CLAUDE_MTIME_FALLBACK_LEAD_MS)
603
+ return { scored: [], activeCount };
604
+ return { scored: [{ ...latest, deltaSec: 0 }], activeCount };
605
+ }
606
+ /**
607
+ * Whether a scored candidate list is safe to bind.
608
+ *
609
+ * `soleOwner` means this cwd holds exactly one live Claude PID and exactly one
610
+ * actively-written jsonl. Collapse needs two of something, so neither failure
611
+ * mode this guard exists for is reachable there — and the absolute proximity
612
+ * cap would otherwise reject a resumed session whose jsonl predates its lstart
613
+ * by hours or days, which is the common shape of a long-running session.
614
+ * Dominance still applies in every other case; it is what actually prevents
615
+ * two PIDs from landing on one sessionId.
616
+ */
617
+ function isConfidentClaudeMtimeMatch(score, soleOwner = false) {
618
+ const top = score.scored[0];
619
+ if (!top)
620
+ return false;
621
+ const second = score.scored[1];
622
+ if (soleOwner)
623
+ return !second;
624
+ if (top.deltaSec > CLAUDE_MATCH_TOP_DELTA_SEC)
625
+ return false;
626
+ return !second || second.deltaSec - top.deltaSec >= CLAUDE_MATCH_GAP_SEC;
627
+ }
628
+ function toClaudeMtimeMatch(candidate, fallbackCwd) {
629
+ return {
630
+ filePath: candidate.path,
631
+ sessionId: candidate.sessionId,
632
+ cwd: candidate.cwd ?? fallbackCwd,
633
+ startedAt: candidate.timestamp ? new Date(candidate.timestamp).getTime() / 1000 : undefined,
634
+ lastActivityAt: candidate.mtimeMs / 1000,
635
+ };
636
+ }
637
+ async function hydrateClaudeMtimeMatch(match, config) {
638
+ upsertSessionRegistryEntry(claudeSessionRegistry, {
639
+ filePath: match.filePath,
640
+ sessionId: match.sessionId,
641
+ cwd: match.cwd,
642
+ firstSeenOffset: 0,
643
+ startedAt: match.startedAt,
644
+ source: "claude",
645
+ binding: basename(match.filePath).includes(match.sessionId) ? "direct" : "provisional",
646
+ });
647
+ const tokenData = await parseClaudeTokens(match.sessionId, match.cwd, match.startedAt, config);
648
+ return {
649
+ cwd: match.cwd,
650
+ sessionId: match.sessionId,
651
+ startedAt: match.startedAt,
652
+ lastActivityAt: match.lastActivityAt,
653
+ sessionMatched: true,
654
+ tokenUsage: tokenData.tokenUsage,
655
+ model: tokenData.model,
656
+ };
657
+ }
658
+ /**
659
+ * Select mtime matches for all same-cwd Claude PIDs in one scan cycle.
660
+ *
661
+ * A one-PID-at-a-time resolver is order-dependent: when process A's first
662
+ * message is delayed, it can claim process B's fresher JSONL before B is
663
+ * scanned. Resolve competing proposals as a batch instead. If two PIDs are
664
+ * within the same dominance window for one JSONL, leave it unbound rather
665
+ * than guessing an owner.
666
+ */
667
+ export async function matchClaudeSessionsByMtime(requests, config, options) {
668
+ const matches = new Map();
669
+ const byCwd = new Map();
670
+ for (const request of requests) {
671
+ if (!request.cwd || request.cwd === "unknown")
672
+ continue;
673
+ if (!Number.isFinite(request.processStartedAt))
674
+ continue;
675
+ const group = byCwd.get(request.cwd) ?? [];
676
+ group.push(request);
677
+ byCwd.set(request.cwd, group);
678
+ }
679
+ for (const [cwd, group] of byCwd) {
680
+ // A jsonl already owned through pid.json is not up for grabs; proposing it
681
+ // here would let a heuristic match outrank an authoritative one.
682
+ const candidates = (await listClaudeMtimeCandidates(cwd, config)).filter((candidate) => !options?.reservedSessionIds?.has(candidate.sessionId));
683
+ const liveClaudePidCount = options?.liveClaudePidCountByCwd?.get(cwd) ?? group.length;
684
+ const proposals = [];
685
+ for (const request of group) {
686
+ const processStartedAt = request.processStartedAt;
687
+ if (processStartedAt === undefined)
688
+ continue;
689
+ const score = scoreClaudeMtimeCandidates(candidates, processStartedAt);
690
+ // Knowing how many live PIDs share this cwd is what the batch pass buys
691
+ // us; a per-PID resolver could never tell "sole owner" from "one of two".
692
+ const soleOwner = liveClaudePidCount === 1 && score.activeCount === 1;
693
+ if (isConfidentClaudeMtimeMatch(score, soleOwner)) {
694
+ const top = score.scored[0];
695
+ proposals.push({ pid: request.pid, candidate: top, deltaSec: top.deltaSec });
696
+ }
697
+ }
698
+ const proposalsBySession = new Map();
699
+ for (const proposal of proposals) {
700
+ const contenders = proposalsBySession.get(proposal.candidate.sessionId) ?? [];
701
+ contenders.push(proposal);
702
+ proposalsBySession.set(proposal.candidate.sessionId, contenders);
703
+ }
704
+ for (const contenders of proposalsBySession.values()) {
705
+ contenders.sort((a, b) => a.deltaSec - b.deltaSec);
706
+ const winner = contenders[0];
707
+ const runnerUp = contenders[1];
708
+ // The owner must be clearly closer too. A one-second lstart difference
709
+ // is normal process-start precision noise, not enough evidence to give
710
+ // either PID a shared JSONL.
711
+ if (runnerUp && runnerUp.deltaSec - winner.deltaSec < CLAUDE_MATCH_GAP_SEC)
712
+ continue;
713
+ matches.set(winner.pid, toClaudeMtimeMatch(winner.candidate, cwd));
714
+ }
715
+ }
716
+ return matches;
717
+ }
504
718
  /**
505
719
  * Match a Claude session by scanning JSONL files in the project directory.
506
720
  * When processStartedAt is available, matches by JSONL creation timestamp
507
721
  * (first-line timestamp) proximity to process start time.
508
722
  * Falls back to the most recently modified JSONL when no start time is available.
723
+ *
724
+ * Fail-closed dual threshold (local issue #108): a candidate is accepted only
725
+ * when (a) its proximity to processStartedAt is within CLAUDE_MATCH_TOP_DELTA_SEC
726
+ * AND (b) it dominates the runner-up by at least CLAUDE_MATCH_GAP_SEC. When
727
+ * cycleClaimedSessionIds is supplied, any session already bound to another PID
728
+ * in this scan cycle is excluded from the candidate pool — without this, two
729
+ * same-cwd Claude PIDs whose lstart falls in the same second tiebreak onto the
730
+ * same jsonl and the daemon snapshot collapses both PIDs onto one sessionId.
509
731
  */
510
- export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
732
+ export async function matchClaudeSessionByMtime(cwd, processStartedAt, config, cycleClaimedSessionIds) {
511
733
  const projectDirName = await findClaudeProjectDir(cwd, undefined, config);
512
734
  if (!projectDirName)
513
735
  return undefined;
@@ -522,10 +744,15 @@ export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
522
744
  for (const file of files) {
523
745
  if (!file.endsWith(".jsonl"))
524
746
  continue;
747
+ // Basename without ".jsonl" is the sessionId on disk; we use it to
748
+ // skip files already claimed by another PID in this scan cycle.
749
+ const sessionId = basename(file, ".jsonl");
750
+ if (cycleClaimedSessionIds?.has(sessionId))
751
+ continue;
525
752
  try {
526
753
  const filePath = join(projectDir, file);
527
754
  const fileStat = await stat(filePath);
528
- candidates.push({ path: filePath, mtimeMs: fileStat.mtimeMs });
755
+ candidates.push({ path: filePath, mtimeMs: fileStat.mtimeMs, sessionId });
529
756
  }
530
757
  catch {
531
758
  // skip
@@ -558,16 +785,26 @@ export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
558
785
  });
559
786
  }
560
787
  if (scored.length > 0) {
561
- // Pick the JSONL whose creation time is closest to process start
562
788
  scored.sort((a, b) => a.deltaSec - b.deltaSec);
563
- // Only accept if within reasonable tolerance (5 minutes)
564
- if (scored[0].deltaSec <= 300) {
565
- bestPath = scored[0].path;
789
+ const top = scored[0];
790
+ const second = scored[1];
791
+ // Require (a) top close enough AND (b) dominant over the runner-up.
792
+ // Without (b), two near-simultaneous Claude starts in the same cwd
793
+ // both land on whichever jsonl wins the tiebreak — same-sessionId
794
+ // collapse in the daemon snapshot. With (a)+(b), ambiguous matches
795
+ // are deferred to a later scan cycle (snapshot sessionId stays
796
+ // unset; CLI surfaces "session not ready") instead of misrouting.
797
+ const dominates = !second || second.deltaSec - top.deltaSec >= CLAUDE_MATCH_GAP_SEC;
798
+ if (top.deltaSec <= CLAUDE_MATCH_TOP_DELTA_SEC && dominates) {
799
+ bestPath = top.path;
566
800
  }
801
+ // Intentional fail-closed: if scored produced a result that does not
802
+ // pass the dual threshold, do NOT fall back to mtime — fallback is
803
+ // reserved for the case where no jsonl carries a timestamp at all.
567
804
  }
568
- // Fallback: no timestamp-scored match — only commit if one file clearly leads
569
- // to avoid mismatching when multiple sessions share the same cwd.
570
- if (!bestPath) {
805
+ else {
806
+ // Fallback: no timestamp-scored match — only commit if one file clearly
807
+ // leads by mtime to avoid mismatching when multiple sessions share cwd.
571
808
  pool.sort((a, b) => b.mtimeMs - a.mtimeMs);
572
809
  const latest = pool[0];
573
810
  const second = pool[1];
@@ -621,8 +858,11 @@ export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
621
858
  return undefined;
622
859
  }
623
860
  }
624
- /** Parse Claude Code session file for enriched data */
625
- export async function parseClaudeSession(pid, cwd, processStartedAt, config) {
861
+ /** Parse Claude Code session file for enriched data.
862
+ * cycleClaimedSessionIds (#108): per-scan-cycle Set of sessionIds already
863
+ * bound to another PID. Threaded to matchClaudeSessionByMtime so same-cwd
864
+ * multi-PID environments cannot collapse onto a single sessionId. */
865
+ export async function parseClaudeSession(pid, cwd, processStartedAt, config, cycleClaimedSessionIds, preselectedMtimeMatch, reservedSessionIds) {
626
866
  // 1st: try legacy sessions/{pid}.json
627
867
  const sessionFile = getClaudeSessionRoots(config)
628
868
  .map((root) => join(root, `${pid}.json`))
@@ -632,13 +872,25 @@ export async function parseClaudeSession(pid, cwd, processStartedAt, config) {
632
872
  const fileStat = await stat(sessionFile);
633
873
  const raw = await readFile(sessionFile, "utf-8");
634
874
  const data = JSON.parse(raw);
875
+ const ownership = classifyClaudePidJsonOwnership(data.procStart, processStartedAt);
876
+ // #107 A: a recycled PID inherits the dead process's file. Nothing in it
877
+ // describes the process we are looking at, so drop it wholesale rather
878
+ // than trying to repair it, and let the mtime heuristic decide.
879
+ if (ownership === "recycled") {
880
+ return resolveClaudeSessionByMtime(cwd, processStartedAt, config, cycleClaimedSessionIds, preselectedMtimeMatch);
881
+ }
635
882
  const processCwd = cwd ?? data.cwd;
636
883
  const sessionStartedAt = data.startedAt ? data.startedAt / 1000 : undefined;
637
884
  let resolvedSessionId = data.sessionId;
638
885
  let resolvedCwd = data.cwd;
639
886
  let resolvedStartedAt = sessionStartedAt;
640
- if (processCwd && processCwd !== "unknown") {
641
- const override = await chooseStaleSessionOverride(processCwd, data.sessionId, processStartedAt, config);
887
+ // #107 B: Claude Code keeps this file current — verified live by running
888
+ // /clear, which rewrote sessionId while leaving procStart untouched. A
889
+ // maintained record beats the override's "most recent jsonl in the cwd"
890
+ // guess, which in that same experiment picked the session /clear had just
891
+ // abandoned (its first entry sits 1s from lstart, the live one 34m away).
892
+ if (ownership !== "owned" && processCwd && processCwd !== "unknown") {
893
+ const override = await chooseStaleSessionOverride(processCwd, data.sessionId, processStartedAt, config, cycleClaimedSessionIds, reservedSessionIds);
642
894
  if (override) {
643
895
  resolvedSessionId = override.sessionId;
644
896
  resolvedCwd = override.cwd ?? processCwd;
@@ -656,6 +908,21 @@ export async function parseClaudeSession(pid, cwd, processStartedAt, config) {
656
908
  });
657
909
  }
658
910
  }
911
+ // #107 C: pid.json's `startedAt` is when the CLI process came up, not
912
+ // when the current conversation began. /clear starts a new sessionId in
913
+ // the same process, so after one the two differ by however long the
914
+ // process had been running (34 minutes in the live experiment). Take the
915
+ // session's own first entry when the record is authoritative.
916
+ if (ownership === "owned" && resolvedSessionId && resolvedCwd) {
917
+ const directPath = await resolveClaudeSessionFile(resolvedSessionId, resolvedCwd, resolvedStartedAt, config);
918
+ const directMeta = directPath ? await readJsonlSessionMeta(directPath) : undefined;
919
+ const sessionBeganAt = directMeta?.timestamp
920
+ ? new Date(directMeta.timestamp).getTime() / 1000
921
+ : undefined;
922
+ if (sessionBeganAt !== undefined && Number.isFinite(sessionBeganAt)) {
923
+ resolvedStartedAt = sessionBeganAt;
924
+ }
925
+ }
659
926
  const result = {
660
927
  cwd: resolvedCwd,
661
928
  sessionId: resolvedSessionId,
@@ -663,6 +930,12 @@ export async function parseClaudeSession(pid, cwd, processStartedAt, config) {
663
930
  lastActivityAt: fileStat.mtimeMs / 1000,
664
931
  sessionMatched: true,
665
932
  };
933
+ // Legacy PID records can be stale or duplicated. Returning a sessionId
934
+ // that is already owned in this scan cycle would recreate the collapse
935
+ // the mtime path prevents.
936
+ if (resolvedSessionId && cycleClaimedSessionIds?.has(resolvedSessionId)) {
937
+ return { cwd: resolvedCwd ?? processCwd, startedAt: resolvedStartedAt };
938
+ }
666
939
  if (resolvedSessionId && resolvedCwd) {
667
940
  const tokenData = await parseClaudeTokens(resolvedSessionId, resolvedCwd, resolvedStartedAt, config);
668
941
  result.tokenUsage = tokenData.tokenUsage;
@@ -675,8 +948,21 @@ export async function parseClaudeSession(pid, cwd, processStartedAt, config) {
675
948
  }
676
949
  }
677
950
  // 2nd: match by JSONL mtime in project directory
951
+ return resolveClaudeSessionByMtime(cwd, processStartedAt, config, cycleClaimedSessionIds, preselectedMtimeMatch);
952
+ }
953
+ /**
954
+ * The mtime-heuristic half of parseClaudeSession, reachable both as the normal
955
+ * fallback and when a pid.json turns out to belong to a recycled PID (#107).
956
+ */
957
+ async function resolveClaudeSessionByMtime(cwd, processStartedAt, config, cycleClaimedSessionIds, preselectedMtimeMatch) {
958
+ if (preselectedMtimeMatch !== undefined) {
959
+ if (!preselectedMtimeMatch || cycleClaimedSessionIds?.has(preselectedMtimeMatch.sessionId)) {
960
+ return {};
961
+ }
962
+ return hydrateClaudeMtimeMatch(preselectedMtimeMatch, config);
963
+ }
678
964
  if (cwd && cwd !== "unknown") {
679
- const matched = await matchClaudeSessionByMtime(cwd, processStartedAt, config);
965
+ const matched = await matchClaudeSessionByMtime(cwd, processStartedAt, config, cycleClaimedSessionIds);
680
966
  if (matched)
681
967
  return matched;
682
968
  }