marmonitor 0.2.5 → 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.
- package/README.ko.md +39 -3
- package/README.md +41 -4
- package/dist/alerts/token.js +10 -2
- package/dist/cli.js +201 -28
- package/dist/clipboard.d.ts +12 -0
- package/dist/clipboard.js +56 -0
- package/dist/config/index.d.ts +3 -0
- package/dist/config/index.js +10 -4
- package/dist/output/index.d.ts +6 -3
- package/dist/output/index.js +43 -32
- package/dist/output/utils.d.ts +9 -2
- package/dist/output/utils.js +58 -2
- package/dist/scanner/cache.d.ts +10 -0
- package/dist/scanner/cache.js +14 -0
- package/dist/scanner/claude.d.ts +70 -3
- package/dist/scanner/claude.js +350 -26
- package/dist/scanner/codex.d.ts +39 -0
- package/dist/scanner/codex.js +171 -9
- package/dist/scanner/daemon-loop.d.ts +2 -0
- package/dist/scanner/daemon-loop.js +9 -2
- package/dist/scanner/daemon-utils.d.ts +11 -0
- package/dist/scanner/daemon-utils.js +42 -11
- package/dist/scanner/gemini.d.ts +10 -0
- package/dist/scanner/gemini.js +82 -0
- package/dist/scanner/group.d.ts +1 -1
- package/dist/scanner/group.js +9 -0
- package/dist/scanner/index.d.ts +18 -0
- package/dist/scanner/index.js +247 -28
- package/dist/scanner/process.d.ts +12 -0
- package/dist/scanner/process.js +242 -16
- package/dist/scanner/session-registry.d.ts +21 -0
- package/dist/scanner/session-registry.js +85 -4
- package/dist/scanner/status.d.ts +36 -1
- package/dist/scanner/status.js +49 -5
- package/dist/sessions.d.ts +9 -0
- package/dist/sessions.js +11 -0
- package/dist/tmux/index.d.ts +29 -5
- package/dist/tmux/index.js +131 -16
- package/dist/turns.d.ts +68 -0
- package/dist/turns.js +430 -0
- package/dist/types.d.ts +8 -0
- package/package.json +3 -1
package/dist/scanner/claude.js
CHANGED
|
@@ -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,7 +418,65 @@ async function readJsonlSessionMeta(filePath) {
|
|
|
418
418
|
await fd?.close().catch(() => { });
|
|
419
419
|
}
|
|
420
420
|
}
|
|
421
|
-
|
|
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
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Stale-session override resolver.
|
|
462
|
+
*
|
|
463
|
+
* Picks a non-current jsonl when the current sessionId's metadata is stale
|
|
464
|
+
* (e.g. just after /clear), but refuses to do so when the current jsonl
|
|
465
|
+
* clearly belongs to this process or when the candidate jsonl is already
|
|
466
|
+
* claimed in the registry. See local issue #103 / GH #56 for the misrouting
|
|
467
|
+
* case this guards.
|
|
468
|
+
*
|
|
469
|
+
* Conservative guards layered on top of the legacy mtime-lead check:
|
|
470
|
+
* - F1: if currentDirectPath exists and its first-line timestamp is on or
|
|
471
|
+
* after processStartedAt, the current jsonl was authored by this
|
|
472
|
+
* process — keep it, do not override.
|
|
473
|
+
* - F2: if the override-candidate sessionId is already direct-bound in
|
|
474
|
+
* claudeSessionRegistry, refuse the override. Keeps the
|
|
475
|
+
* one-jsonl-per-sessionId invariant intact.
|
|
476
|
+
* - F3: anything ambiguous falls through to `undefined` (unresolved) —
|
|
477
|
+
* a missed match is safer than a misrouted one.
|
|
478
|
+
*/
|
|
479
|
+
async function chooseStaleSessionOverride(processCwd, currentSessionId, processStartedAt, config, cycleClaimedSessionIds, reservedSessionIds) {
|
|
422
480
|
const projectDirName = await findClaudeProjectDir(processCwd, currentSessionId, config);
|
|
423
481
|
if (!projectDirName)
|
|
424
482
|
return undefined;
|
|
@@ -435,27 +493,56 @@ async function chooseStaleSessionOverride(processCwd, currentSessionId, config)
|
|
|
435
493
|
.find((candidate) => existsSync(candidate))
|
|
436
494
|
: undefined;
|
|
437
495
|
if (currentDirectPath) {
|
|
496
|
+
let currentStat;
|
|
497
|
+
let recentStat;
|
|
438
498
|
try {
|
|
439
|
-
|
|
440
|
-
stat(recentPath),
|
|
441
|
-
stat(currentDirectPath),
|
|
442
|
-
]);
|
|
443
|
-
const minLeadMs = 5 * 60 * 1000;
|
|
444
|
-
const staleGapMs = 30 * 60 * 1000;
|
|
445
|
-
if (recentStat.mtimeMs - currentStat.mtimeMs < minLeadMs)
|
|
446
|
-
return undefined;
|
|
447
|
-
if (Date.now() - currentStat.mtimeMs < staleGapMs)
|
|
448
|
-
return undefined;
|
|
499
|
+
[recentStat, currentStat] = await Promise.all([stat(recentPath), stat(currentDirectPath)]);
|
|
449
500
|
}
|
|
450
501
|
catch {
|
|
451
502
|
return undefined;
|
|
452
503
|
}
|
|
504
|
+
// F1: a non-empty current jsonl whose first event is on or after the
|
|
505
|
+
// process start belongs to this process. Same-cwd sibling sessions land
|
|
506
|
+
// here and must not be routed onto another session's active jsonl.
|
|
507
|
+
if (currentStat.size > 0 && processStartedAt !== undefined) {
|
|
508
|
+
const currentMeta = await readJsonlSessionMeta(currentDirectPath);
|
|
509
|
+
if (currentMeta?.timestamp) {
|
|
510
|
+
const jsonlCreatedAtSec = new Date(currentMeta.timestamp).getTime() / 1000;
|
|
511
|
+
if (Number.isFinite(jsonlCreatedAtSec)) {
|
|
512
|
+
const CLOCK_SKEW_SEC = 60;
|
|
513
|
+
if (jsonlCreatedAtSec >= processStartedAt - CLOCK_SKEW_SEC)
|
|
514
|
+
return undefined;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
const minLeadMs = 5 * 60 * 1000;
|
|
519
|
+
const staleGapMs = 30 * 60 * 1000;
|
|
520
|
+
if (recentStat.mtimeMs - currentStat.mtimeMs < minLeadMs)
|
|
521
|
+
return undefined;
|
|
522
|
+
if (Date.now() - currentStat.mtimeMs < staleGapMs)
|
|
523
|
+
return undefined;
|
|
453
524
|
}
|
|
454
525
|
const recentMeta = await readJsonlSessionMeta(recentPath);
|
|
455
526
|
if (!recentMeta?.sessionId)
|
|
456
527
|
return undefined;
|
|
457
528
|
if (recentMeta.sessionId === currentSessionId)
|
|
458
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;
|
|
540
|
+
// F2: the candidate sessionId is already direct-bound in the registry.
|
|
541
|
+
// Overriding would let two sessionIds share one jsonl — the exact bug
|
|
542
|
+
// in #103. Keeps the one-jsonl-per-sessionId invariant.
|
|
543
|
+
const recentBinding = claudeSessionRegistry.get(recentMeta.sessionId);
|
|
544
|
+
if (recentBinding?.binding === "direct")
|
|
545
|
+
return undefined;
|
|
459
546
|
return {
|
|
460
547
|
sessionId: recentMeta.sessionId,
|
|
461
548
|
cwd: recentMeta.cwd ?? processCwd,
|
|
@@ -463,13 +550,186 @@ async function chooseStaleSessionOverride(processCwd, currentSessionId, config)
|
|
|
463
550
|
filePath: recentPath,
|
|
464
551
|
};
|
|
465
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
|
+
}
|
|
466
718
|
/**
|
|
467
719
|
* Match a Claude session by scanning JSONL files in the project directory.
|
|
468
720
|
* When processStartedAt is available, matches by JSONL creation timestamp
|
|
469
721
|
* (first-line timestamp) proximity to process start time.
|
|
470
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.
|
|
471
731
|
*/
|
|
472
|
-
export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
|
|
732
|
+
export async function matchClaudeSessionByMtime(cwd, processStartedAt, config, cycleClaimedSessionIds) {
|
|
473
733
|
const projectDirName = await findClaudeProjectDir(cwd, undefined, config);
|
|
474
734
|
if (!projectDirName)
|
|
475
735
|
return undefined;
|
|
@@ -484,10 +744,15 @@ export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
|
|
|
484
744
|
for (const file of files) {
|
|
485
745
|
if (!file.endsWith(".jsonl"))
|
|
486
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;
|
|
487
752
|
try {
|
|
488
753
|
const filePath = join(projectDir, file);
|
|
489
754
|
const fileStat = await stat(filePath);
|
|
490
|
-
candidates.push({ path: filePath, mtimeMs: fileStat.mtimeMs });
|
|
755
|
+
candidates.push({ path: filePath, mtimeMs: fileStat.mtimeMs, sessionId });
|
|
491
756
|
}
|
|
492
757
|
catch {
|
|
493
758
|
// skip
|
|
@@ -520,16 +785,26 @@ export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
|
|
|
520
785
|
});
|
|
521
786
|
}
|
|
522
787
|
if (scored.length > 0) {
|
|
523
|
-
// Pick the JSONL whose creation time is closest to process start
|
|
524
788
|
scored.sort((a, b) => a.deltaSec - b.deltaSec);
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
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;
|
|
528
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.
|
|
529
804
|
}
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
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.
|
|
533
808
|
pool.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
534
809
|
const latest = pool[0];
|
|
535
810
|
const second = pool[1];
|
|
@@ -583,8 +858,11 @@ export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
|
|
|
583
858
|
return undefined;
|
|
584
859
|
}
|
|
585
860
|
}
|
|
586
|
-
/** Parse Claude Code session file for enriched data
|
|
587
|
-
|
|
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) {
|
|
588
866
|
// 1st: try legacy sessions/{pid}.json
|
|
589
867
|
const sessionFile = getClaudeSessionRoots(config)
|
|
590
868
|
.map((root) => join(root, `${pid}.json`))
|
|
@@ -594,13 +872,25 @@ export async function parseClaudeSession(pid, cwd, processStartedAt, config) {
|
|
|
594
872
|
const fileStat = await stat(sessionFile);
|
|
595
873
|
const raw = await readFile(sessionFile, "utf-8");
|
|
596
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
|
+
}
|
|
597
882
|
const processCwd = cwd ?? data.cwd;
|
|
598
883
|
const sessionStartedAt = data.startedAt ? data.startedAt / 1000 : undefined;
|
|
599
884
|
let resolvedSessionId = data.sessionId;
|
|
600
885
|
let resolvedCwd = data.cwd;
|
|
601
886
|
let resolvedStartedAt = sessionStartedAt;
|
|
602
|
-
|
|
603
|
-
|
|
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);
|
|
604
894
|
if (override) {
|
|
605
895
|
resolvedSessionId = override.sessionId;
|
|
606
896
|
resolvedCwd = override.cwd ?? processCwd;
|
|
@@ -618,6 +908,21 @@ export async function parseClaudeSession(pid, cwd, processStartedAt, config) {
|
|
|
618
908
|
});
|
|
619
909
|
}
|
|
620
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
|
+
}
|
|
621
926
|
const result = {
|
|
622
927
|
cwd: resolvedCwd,
|
|
623
928
|
sessionId: resolvedSessionId,
|
|
@@ -625,6 +930,12 @@ export async function parseClaudeSession(pid, cwd, processStartedAt, config) {
|
|
|
625
930
|
lastActivityAt: fileStat.mtimeMs / 1000,
|
|
626
931
|
sessionMatched: true,
|
|
627
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
|
+
}
|
|
628
939
|
if (resolvedSessionId && resolvedCwd) {
|
|
629
940
|
const tokenData = await parseClaudeTokens(resolvedSessionId, resolvedCwd, resolvedStartedAt, config);
|
|
630
941
|
result.tokenUsage = tokenData.tokenUsage;
|
|
@@ -637,8 +948,21 @@ export async function parseClaudeSession(pid, cwd, processStartedAt, config) {
|
|
|
637
948
|
}
|
|
638
949
|
}
|
|
639
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
|
+
}
|
|
640
964
|
if (cwd && cwd !== "unknown") {
|
|
641
|
-
const matched = await matchClaudeSessionByMtime(cwd, processStartedAt, config);
|
|
965
|
+
const matched = await matchClaudeSessionByMtime(cwd, processStartedAt, config, cycleClaimedSessionIds);
|
|
642
966
|
if (matched)
|
|
643
967
|
return matched;
|
|
644
968
|
}
|
package/dist/scanner/codex.d.ts
CHANGED
|
@@ -5,6 +5,8 @@ import type { MarmonitorConfig } from "../config/index.js";
|
|
|
5
5
|
import type { SessionPhase } from "../types.js";
|
|
6
6
|
import type { CodexSessionMeta } from "./cache.js";
|
|
7
7
|
export type { CodexSessionMeta } from "./cache.js";
|
|
8
|
+
declare function mergeCodexIndexedSessions(baseSessions: CodexSessionMeta[], incomingSessions: CodexSessionMeta[]): CodexSessionMeta[];
|
|
9
|
+
export { mergeCodexIndexedSessions };
|
|
8
10
|
export declare function getCodexSessionRoots(config?: MarmonitorConfig): string[];
|
|
9
11
|
/** Detect Codex session phase from session JSONL */
|
|
10
12
|
export declare function detectCodexPhase(sessionFilePath: string | undefined, config?: MarmonitorConfig): Promise<SessionPhase>;
|
|
@@ -12,5 +14,42 @@ export declare function detectCodexPhase(sessionFilePath: string | undefined, co
|
|
|
12
14
|
export declare function indexCodexSessions(config?: MarmonitorConfig, options?: {
|
|
13
15
|
activeCwds?: string[];
|
|
14
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;
|
|
15
54
|
/** Match a Codex process to a session by cwd + closest timestamp */
|
|
16
55
|
export declare function matchCodexSession(processCwd: string, processStartTime: number | undefined, sessions: CodexSessionMeta[]): CodexSessionMeta | undefined;
|