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.
Files changed (42) hide show
  1. package/README.ko.md +39 -3
  2. package/README.md +41 -4
  3. package/dist/alerts/token.js +10 -2
  4. package/dist/cli.js +201 -28
  5. package/dist/clipboard.d.ts +12 -0
  6. package/dist/clipboard.js +56 -0
  7. package/dist/config/index.d.ts +3 -0
  8. package/dist/config/index.js +10 -4
  9. package/dist/output/index.d.ts +6 -3
  10. package/dist/output/index.js +43 -32
  11. package/dist/output/utils.d.ts +9 -2
  12. package/dist/output/utils.js +58 -2
  13. package/dist/scanner/cache.d.ts +10 -0
  14. package/dist/scanner/cache.js +14 -0
  15. package/dist/scanner/claude.d.ts +70 -3
  16. package/dist/scanner/claude.js +350 -26
  17. package/dist/scanner/codex.d.ts +39 -0
  18. package/dist/scanner/codex.js +171 -9
  19. package/dist/scanner/daemon-loop.d.ts +2 -0
  20. package/dist/scanner/daemon-loop.js +9 -2
  21. package/dist/scanner/daemon-utils.d.ts +11 -0
  22. package/dist/scanner/daemon-utils.js +42 -11
  23. package/dist/scanner/gemini.d.ts +10 -0
  24. package/dist/scanner/gemini.js +82 -0
  25. package/dist/scanner/group.d.ts +1 -1
  26. package/dist/scanner/group.js +9 -0
  27. package/dist/scanner/index.d.ts +18 -0
  28. package/dist/scanner/index.js +247 -28
  29. package/dist/scanner/process.d.ts +12 -0
  30. package/dist/scanner/process.js +242 -16
  31. package/dist/scanner/session-registry.d.ts +21 -0
  32. package/dist/scanner/session-registry.js +85 -4
  33. package/dist/scanner/status.d.ts +36 -1
  34. package/dist/scanner/status.js +49 -5
  35. package/dist/sessions.d.ts +9 -0
  36. package/dist/sessions.js +11 -0
  37. package/dist/tmux/index.d.ts +29 -5
  38. package/dist/tmux/index.js +131 -16
  39. package/dist/turns.d.ts +68 -0
  40. package/dist/turns.js +430 -0
  41. package/dist/types.d.ts +8 -0
  42. package/package.json +3 -1
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Cross-platform clipboard writer with fallback chain.
3
+ *
4
+ * macOS : pbcopy
5
+ * Linux : wl-copy → xclip → xsel (in that order)
6
+ *
7
+ * Throws ClipboardError with a human-readable reason when all commands fail.
8
+ */
9
+ import { spawn } from "node:child_process";
10
+ export class ClipboardError extends Error {
11
+ constructor(message) {
12
+ super(message);
13
+ this.name = "ClipboardError";
14
+ }
15
+ }
16
+ function commandsForPlatform() {
17
+ if (process.platform === "darwin") {
18
+ return [{ command: "pbcopy", args: [] }];
19
+ }
20
+ return [
21
+ { command: "wl-copy", args: [] },
22
+ { command: "xclip", args: ["-selection", "clipboard"] },
23
+ { command: "xsel", args: ["--clipboard", "--input"] },
24
+ ];
25
+ }
26
+ async function tryRun(command, args, text) {
27
+ return new Promise((resolve) => {
28
+ let settled = false;
29
+ const done = (ok) => {
30
+ if (settled)
31
+ return;
32
+ settled = true;
33
+ resolve(ok);
34
+ };
35
+ try {
36
+ const child = spawn(command, args, { stdio: ["pipe", "ignore", "ignore"] });
37
+ child.on("error", () => done(false));
38
+ child.on("close", (code) => done(code === 0));
39
+ child.stdin.on("error", () => done(false));
40
+ child.stdin.end(text);
41
+ }
42
+ catch {
43
+ done(false);
44
+ }
45
+ });
46
+ }
47
+ export async function writeClipboard(text) {
48
+ const candidates = commandsForPlatform();
49
+ const tried = [];
50
+ for (const { command, args } of candidates) {
51
+ tried.push(command);
52
+ if (await tryRun(command, args, text))
53
+ return;
54
+ }
55
+ throw new ClipboardError(`Clipboard copy failed (tried: ${tried.join(", ")}). Try --stdout to print instead.`);
56
+ }
@@ -29,6 +29,7 @@ export interface MarmonitorConfig {
29
29
  sortBy: "cwd" | "agent" | "status" | "pid";
30
30
  attentionLimit: number;
31
31
  statuslineAttentionLimit: number;
32
+ statuslineLabel: "path" | "tmux" | "auto";
32
33
  };
33
34
  agents: Record<string, {
34
35
  processNames: string[];
@@ -93,6 +94,8 @@ export interface MarmonitorConfig {
93
94
  desktop: boolean;
94
95
  /** alerts.log 파일 기록 */
95
96
  log: boolean;
97
+ /** 토큰/컨텍스트 임계 알림 카테고리 토글. 보안 알림과 분리 가능. 기본 true */
98
+ tokens: boolean;
96
99
  /** 컨텍스트 경고 임계값 (0~1). 0 = 비활성화. 기본 1.0 (비활성) */
97
100
  contextWarnThreshold: number;
98
101
  /** 컨텍스트 위험 임계값 (0~1). 기본 0.85 */
@@ -47,6 +47,7 @@ const DEFAULTS = {
47
47
  sortBy: "cwd",
48
48
  attentionLimit: 10,
49
49
  statuslineAttentionLimit: 5,
50
+ statuslineLabel: "auto",
50
51
  },
51
52
  agents: {
52
53
  "Claude Code": { processNames: ["claude"] },
@@ -93,9 +94,10 @@ const DEFAULTS = {
93
94
  activityRetentionDays: 7,
94
95
  },
95
96
  alerts: {
96
- enabled: true,
97
- desktop: true,
98
- log: true,
97
+ enabled: false,
98
+ desktop: false,
99
+ log: false,
100
+ tokens: true, // 활성 시 토큰/컨텍스트 임계 알림 발사. 보안 알림은 별도 게이트 없음
99
101
  contextWarnThreshold: 1.0, // 기본 비활성 (0.70으로 설정 시 활성화)
100
102
  contextCritThreshold: 0.85,
101
103
  },
@@ -146,7 +148,11 @@ export async function loadConfig(customPath) {
146
148
  const userConfig = JSON.parse(raw);
147
149
  if (!isJsonObject(userConfig))
148
150
  return cloneDefaults();
149
- return deepMerge(cloneDefaults(), userConfig);
151
+ const merged = deepMerge(cloneDefaults(), userConfig);
152
+ if (merged.display && !["path", "tmux", "auto"].includes(merged.display.statuslineLabel)) {
153
+ merged.display.statuslineLabel = "auto";
154
+ }
155
+ return merged;
150
156
  }
151
157
  catch {
152
158
  // Malformed or unreadable config — use defaults silently
@@ -1,5 +1,5 @@
1
1
  import type { TmuxJumpResult } from "../tmux/index.js";
2
- import type { AgentSession, SystemInfo } from "../types.js";
2
+ import type { AgentSession, StatuslineLabelMode, SystemInfo } from "../types.js";
3
3
  import { type BadgeStyle, type StatuslineFormat } from "./utils.js";
4
4
  /** Collect system resource info */
5
5
  export declare function getSystemInfo(): Promise<SystemInfo>;
@@ -9,7 +9,10 @@ export declare function abbreviateModel(model: string | undefined): string;
9
9
  /** Print agent status as formatted text */
10
10
  export declare function printStatus(agents: AgentSession[]): Promise<void>;
11
11
  /** Print agent status as JSON */
12
- export declare function printStatusJson(agents: AgentSession[]): Promise<void>;
12
+ export declare function printStatusJson(agents: AgentSession[], snapshot?: {
13
+ health: string;
14
+ ageMs: number;
15
+ }): Promise<void>;
13
16
  export declare function printCleanPlan(agents: AgentSession[], kill: boolean): void;
14
17
  export declare function printCleanJson(agents: AgentSession[], executed: boolean, signal?: string): void;
15
18
  export declare function renderJumpAttentionChooser(agents: AgentSession[], page?: number, pageSize?: number): string;
@@ -27,6 +30,6 @@ export declare function printDock(agents: AgentSession[], maxLines?: number): Pr
27
30
  /** Print one-line summary for tmux/terminal status bar */
28
31
  export declare function renderUnavailableStatusline(format?: StatuslineFormat): string;
29
32
  /** Print one-line summary for tmux/terminal status bar */
30
- export declare function renderStatusline(agents: AgentSession[], format?: StatuslineFormat, attentionLimit?: number, width?: number, badgeStyle?: BadgeStyle, hasJumpAnchor?: boolean, activeAgentPid?: number): Promise<string>;
33
+ export declare function renderStatusline(agents: AgentSession[], format?: StatuslineFormat, attentionLimit?: number, width?: number, badgeStyle?: BadgeStyle, hasJumpAnchor?: boolean, activeAgentPid?: number, statuslineLabel?: StatuslineLabelMode): Promise<string>;
31
34
  /** Print one-line summary for tmux/terminal status bar */
32
35
  export declare function printStatusline(agents: AgentSession[], format?: StatuslineFormat, attentionLimit?: number, width?: number): Promise<void>;
@@ -1,6 +1,8 @@
1
1
  import chalk from "chalk";
2
2
  import * as si from "systeminformation";
3
- import { buildAttentionFocusText, buildAttentionItems, buildJumpAttentionItems, buildStatuslineSummary, buildTmuxAttentionPills, buildTmuxBadgeBar, compactDirLabel, formatElapsed, formatTokens, serializeWeztermPills, shortenPath, } from "./utils.js";
3
+ import { partitionSessions } from "../sessions.js";
4
+ import { resolveAgentTmuxTargets } from "../tmux/index.js";
5
+ import { buildAttentionFocusText, buildAttentionItems, buildJumpAttentionItems, buildStatuslineSummary, buildTmuxAttentionPills, buildTmuxBadgeBar, compactDirLabel, compactStatuslineDirLabel, formatElapsed, formatTokens, resolveStatuslineDetailLayout, serializeWeztermPills, shortenPath, } from "./utils.js";
4
6
  /** Collect system resource info */
5
7
  export async function getSystemInfo() {
6
8
  const [cpu, mem, battery] = await Promise.all([si.currentLoad(), si.mem(), si.battery()]);
@@ -185,15 +187,15 @@ export async function printStatus(agents) {
185
187
  const sys = await getSystemInfo();
186
188
  printSystemLine(sys);
187
189
  console.log();
188
- const alive = agents.filter((a) => a.status !== "Dead" && a.status !== "Unmatched");
189
- const unmatched = agents.filter((a) => a.status === "Unmatched");
190
- const dead = agents.filter((a) => a.status === "Dead");
190
+ const { running, matched: alive, unmatched, dead } = partitionSessions(agents);
191
191
  if (alive.length === 0 && unmatched.length === 0 && dead.length === 0) {
192
192
  console.log("No AI agent sessions detected.");
193
193
  return;
194
194
  }
195
+ if (running.length > 0) {
196
+ console.log(`AI Sessions (${running.length} running, ${unmatched.length} unmatched):\n`);
197
+ }
195
198
  if (alive.length > 0) {
196
- console.log(`AI Sessions (${alive.length} active):\n`);
197
199
  // Column widths — fixed-width columns first, variable-width last
198
200
  const W = {
199
201
  status: 10,
@@ -248,8 +250,8 @@ export async function printStatus(agents) {
248
250
  const rawStatus = coloredLabel + " ".repeat(Math.max(0, W.status - statusLabel2.length));
249
251
  const agentStr = a.agentName === "Claude Code" ? "Claude" : a.agentName;
250
252
  const modelStr = abbreviateModel(a.model);
251
- const cpu = `${a.cpuPercent}%`;
252
- const mem = `${a.memoryMb.toFixed(0)}MB`;
253
+ const cpu = a.resourceUsageAvailable === false ? "?" : `${a.cpuPercent}%`;
254
+ const mem = a.resourceUsageAvailable === false ? "?" : `${a.memoryMb.toFixed(0)}MB`;
253
255
  const last = a.lastResponseAt
254
256
  ? formatElapsedCompactTable(a.lastResponseAt)
255
257
  : a.lastActivityAt
@@ -278,8 +280,8 @@ export async function printStatus(agents) {
278
280
  "└─".padEnd(W.agent),
279
281
  " ".repeat(W.model),
280
282
  String(w.pid).padEnd(W.pid),
281
- padVisibleRight(`${w.cpuPercent}%`, W.cpu),
282
- padVisibleRight(`${w.memoryMb.toFixed(0)}MB`, W.mem),
283
+ padVisibleRight(w.resourceUsageAvailable === false ? "?" : `${w.cpuPercent}%`, W.cpu),
284
+ padVisibleRight(w.resourceUsageAvailable === false ? "?" : `${w.memoryMb.toFixed(0)}MB`, W.mem),
283
285
  ].join(" ");
284
286
  console.log(chalk.dim(` ${wLine}`));
285
287
  }
@@ -287,10 +289,10 @@ export async function printStatus(agents) {
287
289
  }
288
290
  }
289
291
  if (unmatched.length > 0) {
290
- console.log(chalk.magenta(`\nUnmatched Processes (${unmatched.length}) — no matching session, consider killing:`));
292
+ console.log(chalk.magenta(`\nUnmatched CLI Sessions (${unmatched.length}) — session metadata not yet bound:`));
291
293
  for (const a of unmatched) {
292
294
  const agent = agentLabel(a.agentName);
293
- console.log(` ${chalk.magenta("[Unmatched]")} ${agent} PID:${a.pid} MEM:${a.memoryMb.toFixed(0)}MB${runtimeLabel(a.runtimeSource)} ${chalk.dim(`kill ${a.pid}`)}`);
295
+ console.log(` ${chalk.magenta("[Unmatched]")} ${agent} PID:${a.pid} MEM:${a.resourceUsageAvailable === false ? "?" : `${a.memoryMb.toFixed(0)}MB`}${runtimeLabel(a.runtimeSource)} ${chalk.dim(shortenPath(a.cwd))}`);
294
296
  }
295
297
  }
296
298
  if (dead.length > 0) {
@@ -305,21 +307,21 @@ export async function printStatus(agents) {
305
307
  }
306
308
  }
307
309
  /** Print agent status as JSON */
308
- export async function printStatusJson(agents) {
310
+ export async function printStatusJson(agents, snapshot) {
309
311
  const sys = await getSystemInfo();
310
- console.log(JSON.stringify({ system: sys, agents }, null, 2));
312
+ console.log(JSON.stringify({ system: sys, agents, ...(snapshot ? { snapshot } : {}) }, null, 2));
311
313
  }
312
314
  export function printCleanPlan(agents, kill) {
313
315
  if (agents.length === 0) {
314
- console.log("No unmatched processes to clean.");
316
+ console.log("No unmatched CLIs.");
315
317
  return;
316
318
  }
317
319
  console.log(kill
318
- ? `Cleaning ${agents.length} unmatched process(es) with SIGTERM:`
319
- : `Cleanup candidates (${agents.length}) — rerun with --kill to terminate:`);
320
+ ? `Sending SIGTERM to ${agents.length} unmatched CLI(s):`
321
+ : `Unmatched CLIs (${agents.length}) — these may be live sessions; terminate one with --kill --pid <pid>:`);
320
322
  for (const agent of agents) {
321
323
  const label = agentLabel(agent.agentName);
322
- console.log(` ${label} PID:${agent.pid} MEM:${agent.memoryMb.toFixed(0)}MB${runtimeLabel(agent.runtimeSource)} ${shortenPath(agent.cwd)}`);
324
+ console.log(` ${label} PID:${agent.pid} MEM:${agent.resourceUsageAvailable === false ? "?" : `${agent.memoryMb.toFixed(0)}MB`}${runtimeLabel(agent.runtimeSource)} ${shortenPath(agent.cwd)}`);
323
325
  }
324
326
  }
325
327
  export function printCleanJson(agents, executed, signal = "SIGTERM") {
@@ -333,6 +335,7 @@ export function printCleanJson(agents, executed, signal = "SIGTERM") {
333
335
  cwd: agent.cwd,
334
336
  runtimeSource: agent.runtimeSource,
335
337
  memoryMb: agent.memoryMb,
338
+ resourceUsageAvailable: agent.resourceUsageAvailable,
336
339
  })),
337
340
  }, null, 2));
338
341
  }
@@ -410,7 +413,9 @@ function jumpAttentionLine(item) {
410
413
  : item.lastActivityAt
411
414
  ? chalk.dim(` last activity ${formatElapsed(item.lastActivityAt)}`)
412
415
  : "";
413
- const stats = `CPU:${item.cpuPercent ?? 0}% MEM:${item.memoryMb?.toFixed(0) ?? "0"}MB`;
416
+ const stats = item.resourceUsageAvailable === false
417
+ ? "CPU:? MEM:?"
418
+ : `CPU:${item.cpuPercent ?? 0}% MEM:${item.memoryMb?.toFixed(0) ?? "0"}MB`;
414
419
  const status = jumpAttentionStatusLabel(item);
415
420
  const icon = jumpAttentionPhaseIcon(item);
416
421
  const agent = agentLabel(item.agentName).padEnd(8);
@@ -522,8 +527,7 @@ export function printJumpJson(result) {
522
527
  */
523
528
  export async function printDock(agents, maxLines = 12) {
524
529
  const sys = await getSystemInfo();
525
- const alive = agents.filter((a) => a.status !== "Dead" && a.status !== "Unmatched");
526
- const unmatched = agents.filter((a) => a.status === "Unmatched");
530
+ const { running, matched: alive, unmatched } = partitionSessions(agents);
527
531
  const waitingCount = alive.filter((a) => a.phase === "permission").length;
528
532
  const stalledCount = alive.filter((a) => a.status === "Stalled").length;
529
533
  const alerts = [];
@@ -532,9 +536,9 @@ export async function printDock(agents, maxLines = 12) {
532
536
  if (stalledCount > 0)
533
537
  alerts.push(chalk.yellow(`${stalledCount} stalled`));
534
538
  if (unmatched.length > 0)
535
- alerts.push(chalk.magenta(`${unmatched.length} orphan`));
539
+ alerts.push(chalk.magenta(`${unmatched.length} unmatched`));
536
540
  const alertStr = alerts.length > 0 ? ` ${alerts.join(" ")}` : "";
537
- console.log(`${chalk.bold("AI")} ${alive.length}/${agents.length} CPU:${sys.cpuPercent.toFixed(0)}% MEM:${sys.memoryUsedGb}G${alertStr}`);
541
+ console.log(`${chalk.bold("AI")} ${running.length} running CPU:${sys.cpuPercent.toFixed(0)}% MEM:${sys.memoryUsedGb}G${alertStr}`);
538
542
  console.log(chalk.dim("─".repeat(36)));
539
543
  const prioritized = [...alive].sort((a, b) => {
540
544
  const pri = (agent) => {
@@ -567,7 +571,7 @@ export async function printDock(agents, maxLines = 12) {
567
571
  console.log(chalk.dim(` +${prioritized.length - shown.length} more`));
568
572
  }
569
573
  if (unmatched.length > 0) {
570
- console.log(chalk.magenta(`! ${unmatched.length} unmatched (marmonitor clean)`));
574
+ console.log(chalk.magenta(`! ${unmatched.length} CLI sessions awaiting metadata`));
571
575
  }
572
576
  }
573
577
  /** Print one-line summary for tmux/terminal status bar */
@@ -578,10 +582,9 @@ export function renderUnavailableStatusline(format = "compact") {
578
582
  return "marmonitor unavailable";
579
583
  }
580
584
  /** Print one-line summary for tmux/terminal status bar */
581
- export async function renderStatusline(agents, format = "compact", attentionLimit = 5, width, badgeStyle = "basic", hasJumpAnchor = false, activeAgentPid) {
582
- const alive = agents.filter((a) => a.status !== "Dead" && a.status !== "Unmatched");
583
- const unmatched = agents.filter((a) => a.status === "Unmatched");
584
- if (alive.length === 0) {
585
+ export async function renderStatusline(agents, format = "compact", attentionLimit = 5, width, badgeStyle = "basic", hasJumpAnchor = false, activeAgentPid, statuslineLabel = "auto") {
586
+ const { running, matched: alive, unmatched } = partitionSessions(agents);
587
+ if (running.length === 0) {
585
588
  return format === "wezterm-pills" ? renderUnavailableStatusline(format) : "AI:0";
586
589
  }
587
590
  const sys = await getSystemInfo();
@@ -591,11 +594,11 @@ export async function renderStatusline(agents, format = "compact", attentionLimi
591
594
  const highCpuCount = alive.filter((a) => a.cpuPercent >= 10).length;
592
595
  const thinkingCount = alive.filter((a) => a.phase === "thinking").length;
593
596
  const toolCount = alive.filter((a) => a.phase === "tool").length;
594
- const claudeCount = alive.filter((a) => a.agentName === "Claude Code").length;
595
- const codexCount = alive.filter((a) => a.agentName === "Codex").length;
596
- const geminiCount = alive.filter((a) => a.agentName === "Gemini").length;
597
+ const claudeCount = running.filter((a) => a.agentName === "Claude Code").length;
598
+ const codexCount = running.filter((a) => a.agentName === "Codex").length;
599
+ const geminiCount = running.filter((a) => a.agentName === "Gemini").length;
597
600
  const snapshot = {
598
- aliveCount: alive.length,
601
+ aliveCount: running.length,
599
602
  waitingCount,
600
603
  riskCount: 0,
601
604
  stalledCount,
@@ -611,7 +614,15 @@ export async function renderStatusline(agents, format = "compact", attentionLimi
611
614
  memoryUsedGb: sys.memoryUsedGb,
612
615
  };
613
616
  if (format === "tmux-badges") {
614
- const focusText = buildTmuxAttentionPills(buildJumpAttentionItems(agents), attentionLimit, width, badgeStyle, activeAgentPid);
617
+ const pathMaxLength = resolveStatuslineDetailLayout(width, attentionLimit).pathMaxLength;
618
+ const paths = running.map((agent) => compactStatuslineDirLabel(agent.cwd, pathMaxLength));
619
+ const needsLocations = statuslineLabel === "tmux" ||
620
+ (statuslineLabel === "auto" && new Set(paths).size < paths.length);
621
+ const focusText = buildTmuxAttentionPills(buildJumpAttentionItems(agents), attentionLimit, width, badgeStyle, activeAgentPid, {
622
+ mode: statuslineLabel,
623
+ collisionItems: running,
624
+ tmuxTargets: needsLocations ? await resolveAgentTmuxTargets(running) : undefined,
625
+ });
615
626
  return buildTmuxBadgeBar(snapshot, focusText, badgeStyle, hasJumpAnchor);
616
627
  }
617
628
  if (format === "wezterm-pills") {
@@ -1,4 +1,5 @@
1
- import type { AgentSession, SessionPhase } from "../types.js";
1
+ import type { TmuxJumpTarget } from "../tmux/index.js";
2
+ import type { AgentSession, SessionPhase, StatuslineLabelMode } from "../types.js";
2
3
  /**
3
4
  * Pure utility functions for marmonitor.
4
5
  * Extracted for testability — no side effects, no I/O.
@@ -67,6 +68,7 @@ export interface AttentionItem {
67
68
  cwd: string;
68
69
  cpuPercent?: number;
69
70
  memoryMb?: number;
71
+ resourceUsageAvailable?: boolean;
70
72
  startedAt?: number;
71
73
  runtimeSource?: AgentSession["runtimeSource"];
72
74
  status: AgentSession["status"];
@@ -150,5 +152,10 @@ export declare function buildStatusPills(snapshot: StatuslineSnapshot): {
150
152
  export declare function buildStatuslineSummary(snapshot: StatuslineSnapshot, format?: StatuslineFormat): string;
151
153
  export type BadgeStyle = "basic" | "basic-mono" | "block" | "block-mono" | "text" | "text-mono";
152
154
  export declare function buildTmuxBadgeBar(snapshot: StatuslineSnapshot, focusText?: string, badgeStyle?: BadgeStyle, hasJumpAnchor?: boolean): string;
153
- export declare function buildTmuxAttentionPills(items: AttentionItem[], maxCount?: number, width?: number, badgeStyle?: BadgeStyle, activeAgentPid?: number): string | undefined;
155
+ export interface StatuslineLabelOptions {
156
+ mode?: StatuslineLabelMode;
157
+ tmuxTargets?: ReadonlyMap<number, TmuxJumpTarget>;
158
+ collisionItems?: ReadonlyArray<Pick<AgentSession, "pid" | "cwd">>;
159
+ }
160
+ export declare function buildTmuxAttentionPills(items: AttentionItem[], maxCount?: number, width?: number, badgeStyle?: BadgeStyle, activeAgentPid?: number, labelOptions?: StatuslineLabelOptions): string | undefined;
154
161
  export declare function serializeWeztermPills(snapshot: StatuslineSnapshot, focusText?: string): string;
@@ -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>>;