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.
package/README.ko.md CHANGED
@@ -41,6 +41,7 @@ tmux에서 여러 AI 코딩 에이전트를 동시에 실행하는 건 이제
41
41
 
42
42
  **tmux 상태바** — 터미널 하단에 항상 표시:
43
43
  - 에이전트 수 (`Cl 12`, `Cx 2`, `Gm 1`) — 실행 중인 세션 수
44
+ - 실행 수는 세션 파일 연결 여부와 별개입니다. 아직 메타데이터를 연결하지 못한 CLI도 포함하며, GUI 본체·서버·보조 프로세스는 제외합니다.
44
45
  - 단계 알림 (`⏳ 1`, `🤔 2`, `🔧 1`) — 주의가 필요한 세션
45
46
  - 번호 필 (`1 ⏳Cl my-project allow`, `2 •Cx api-server 6m`) — `Option+1~5`로 세션 바로 이동
46
47
 
@@ -104,6 +105,11 @@ PID
104
105
  | **Codex** | `cwd + processStartedAt`를 SQLite thread index와 매칭 | `pid + processStartedAt` 키의 binding registry를 통해 rollout JSONL 또는 SQLite row | binding registry TTL 기반 freshness 보정 |
105
106
  | **Gemini** | `cwd` → `~/.gemini/tmp/` 하위 project dir 탐색 | mtime 기준 최신 `chats/session-*.json` | 경량 — 프로젝트 디렉터리당 단일 활성 세션 |
106
107
 
108
+ 명령행의 대화 ID는 Codex 실행 파일의 실제 resume 인자 또는 명시적 session-ID
109
+ 옵션에서 읽습니다. 프롬프트·설정 값·자식 도구 명령에 들어 있는 UUID는 제외합니다.
110
+ 알 수 없는 옵션이나 경계가 모호한 여러 이미지 인자는 명령행 대화 ID의 근거로
111
+ 사용하지 않습니다.
112
+
107
113
  ### 왜 중요한가
108
114
 
109
115
  바인딩 레이어가 상태바에 표시되는 숫자의 신뢰성을 결정합니다. `direct` 바인딩은 세션 메타데이터로 파일 경로가 확인된 상태 — 근거 없이는 교체되지 않습니다. `provisional` 바인딩은 direct 파일이 확인될 때까지 유지되다 자동으로 승격됩니다. Reconciliation은 특정 조건(mtime 격차, 메타데이터 확인, 활성 파일 가드)이 충족될 때만 override를 실행하며, 매 스캔마다 재판단하지 않습니다.
@@ -221,6 +227,18 @@ marmonitor jump-back # 마지막 점프 이전 패널로 복귀
221
227
  marmonitor help # 모든 명령어 및 옵션
222
228
  ```
223
229
 
230
+ `marmonitor status --json`은 snapshot이 최신이면 `agents`가 빈 배열이어도
231
+ 종료코드 0을 반환합니다. 성공 응답에는 `system`, `agents`와 함께
232
+ `snapshot: { "health": "fresh", "ageMs": ... }`가 포함됩니다.
233
+ 최신 snapshot의 세션이 0개이면 상태바에는 `AI:0`으로 표시합니다.
234
+
235
+ snapshot을 사용할 수 없으면 종료코드 1과 함께 다음과 같은 JSON을 반환합니다.
236
+ `{ "error": "snapshot-unavailable", "snapshot": { "health": "stale", "ageMs": 20000 } }`
237
+ 다른 health 값은 `missing`, `invalid`, `unreadable`입니다. 오류 응답에는
238
+ `agents`가 없으므로 연동 프로그램은 종료코드를 확인한 뒤 목록을 읽어야 합니다.
239
+ snapshot health는 파일의 가용성과 최신성을 나타냅니다. 데몬 프로세스의 생존은
240
+ 별도로 확인해야 합니다.
241
+
224
242
  ### 활동 로그
225
243
 
226
244
  AI 세션이 실제로 수행한 작업을 추적합니다 — 파일 편집, bash 명령어, 사용 토큰:
@@ -252,7 +270,16 @@ marmonitor activity --json # JSON 출력
252
270
  | `[Idle]` | 프로세스는 살아 있지만 최근 활동 없음 |
253
271
  | `[Stalled]` | 장기간 활동 없음 |
254
272
  | `[Dead]` | 세션 파일은 있지만 프로세스가 종료됨 |
255
- | `[Unmatched]` | AI 프로세스는 발견되었지만 일치하는 세션 없음 |
273
+ | `[Unmatched]` | 실행 중인 CLI의 세션 메타데이터를 아직 연결하지 못함 (실행 수에는 포함) |
274
+
275
+ 자원 측정에 실패해도 확인된 CLI는 목록에 유지하고 `resourceUsageAvailable: false`로
276
+ 표시합니다. 자원 값은 화면에 `?`로 표시하며, JSON 소비자는 이 값이 false이면
277
+ 숫자 CPU·메모리 필드를 측정값으로 사용하지 않아야 합니다. CPU 측정 실패만으로
278
+ 세션이 멈췄다고 판정하지 않습니다.
279
+
280
+ 배치 자원 조회가 거부되면 PID별로 재측정합니다. 유효한 측정값이 없는 PID는
281
+ 대화 연결 전에 signal 0으로 확인해 `ESRCH`이면 제외하고, `EPERM`이면 생존한
282
+ 실행으로 유지합니다.
256
283
 
257
284
  ## tmux 플러그인
258
285
 
@@ -266,6 +293,12 @@ marmonitor activity --json # JSON 출력
266
293
 
267
294
  ### 뱃지 스타일
268
295
 
296
+ 하단바 이름은 `display.statuslineLabel`로 설정합니다. 기본 `auto`는 같은 경로나 축약 이름이 겹칠 때만 `@local:2.3` 같은 tmux 위치를 붙입니다. `path`는 기존 경로 표시, `tmux`는 확인된 tmux 위치를 사용합니다. 위치를 확인하지 못한 중복 세션은 PID로 구분합니다. 좁은 폭에서 위치가 너무 길어도 PID를 표시하며 클릭 대상은 계속 해당 CLI의 PID입니다.
297
+
298
+ 세션 이동과 터미널 화면 기반 상태 조회에는 PID 계보 또는 TTY 소유 근거가
299
+ 필요합니다. 소유를 확인할 수 없으면 같은 작업 경로의 pane이 하나뿐이어도
300
+ 위치를 미확정으로 처리합니다.
301
+
269
302
  `integration.tmux.badgeStyle`로 tmux 뱃지와 터미널 텍스트 출력의 스타일을 통일할 수 있습니다.
270
303
 
271
304
  - `basic` — 기본 컬러 필
@@ -296,7 +329,8 @@ marmonitor settings-init --stdout
296
329
  {
297
330
  "display": {
298
331
  "attentionLimit": 10,
299
- "statuslineAttentionLimit": 5
332
+ "statuslineAttentionLimit": 5,
333
+ "statuslineLabel": "auto"
300
334
  },
301
335
  "status": {
302
336
  "stalledAfterMin": 20,
package/README.md CHANGED
@@ -104,6 +104,11 @@ Each agent traverses this chain differently:
104
104
  | **Codex** | `cwd + processStartedAt` matched against SQLite thread index | Rollout JSONL or SQLite row, via binding registry keyed on `pid + processStartedAt` | Freshness correction via binding registry TTL |
105
105
  | **Gemini** | `cwd` → resolved project dir under `~/.gemini/tmp/` | Latest `chats/session-*.json` by mtime | Lightweight — single active session per project dir |
106
106
 
107
+ Command-line session identity is read from the Codex executable's actual resume
108
+ argument or explicit session-ID option. UUIDs inside prompts, configuration values,
109
+ and child-tool commands are excluded. Unknown options or ambiguous variadic image
110
+ arguments do not establish command-line session identity.
111
+
107
112
  ### Why this matters
108
113
 
109
114
  The binding layer is what makes the numbers in your status bar trustworthy. A `direct` binding means the file path was confirmed from session metadata — marmonitor won't swap it without evidence. A `provisional` binding is held until a direct file appears, then promoted automatically. Reconciliation only overrides when specific conditions are met (mtime lead, metadata confirmation, active file guard) — not on every scan.
@@ -223,6 +228,18 @@ marmonitor jump-back # Return to pane before last jump
223
228
  marmonitor help # All commands and options
224
229
  ```
225
230
 
231
+ `marmonitor status --json` exits with code 0 when its snapshot is fresh, including
232
+ when `agents` is an empty array. Successful responses include
233
+ `snapshot: { "health": "fresh", "ageMs": ... }` alongside `system` and `agents`.
234
+ The statusline displays a fresh empty inventory as `AI:0`.
235
+
236
+ An unavailable snapshot produces exit code 1 and JSON such as
237
+ `{ "error": "snapshot-unavailable", "snapshot": { "health": "stale", "ageMs": 20000 } }`.
238
+ Other health values are `missing`, `invalid`, and `unreadable`. These error responses
239
+ omit `agents`; integrations should check the exit code before reading the inventory.
240
+ Snapshot health describes file availability and freshness. Daemon process health
241
+ requires a separate check.
242
+
226
243
  ### Activity log
227
244
 
228
245
  Track what your AI sessions actually did — file edits, bash commands, tokens used:
@@ -254,7 +271,16 @@ Activity is collected automatically by the daemon and stored in `~/.config/marmo
254
271
  | `[Idle]` | Process alive, no recent activity |
255
272
  | `[Stalled]` | No activity for extended period |
256
273
  | `[Dead]` | Session file exists but process is gone |
257
- | `[Unmatched]` | AI process found but no matching session |
274
+ | `[Unmatched]` | Running CLI whose session metadata is not yet bound (included in session counts) |
275
+
276
+ When resource measurement fails, detected CLIs remain in the inventory with
277
+ `resourceUsageAvailable: false`. Resource displays use `?`. JSON consumers should
278
+ ignore the numeric CPU/memory placeholders when this flag is false. A failed CPU
279
+ measurement alone cannot establish that a session is stalled.
280
+
281
+ Rejected resource batches are retried per PID. PIDs without valid measurements
282
+ are checked with signal zero before session matching: `ESRCH` excludes an exited
283
+ process, while `EPERM` preserves it as an existing process.
258
284
 
259
285
  ## tmux Plugin
260
286
 
@@ -268,6 +294,12 @@ All settings are customizable via `@marmonitor-*` options. See the [plugin READM
268
294
 
269
295
  ### Badge styles
270
296
 
297
+ Set `display.statuslineLabel` to `auto` (default), `path`, or `tmux`. Auto keeps unique path labels short and appends verified coordinates such as `@local:2.3` when paths or shortened names collide. If a duplicate session has no verified pane, or its location is too long for a narrow layout, a PID suffix keeps it distinct. Click targets remain PID-based.
298
+
299
+ Session jumps and terminal-screen status checks require verified process-tree or
300
+ terminal ownership. When ownership cannot be established, marmonitor leaves the
301
+ location unresolved even if exactly one pane has the same working directory.
302
+
271
303
  tmux badges and terminal text output can share one style via `integration.tmux.badgeStyle`.
272
304
 
273
305
  - `basic` — default colored pills
@@ -324,7 +356,8 @@ marmonitor settings-init --stdout
324
356
  {
325
357
  "display": {
326
358
  "attentionLimit": 10,
327
- "statuslineAttentionLimit": 5
359
+ "statuslineAttentionLimit": 5,
360
+ "statuslineLabel": "auto"
328
361
  },
329
362
  "status": {
330
363
  "stalledAfterMin": 20,
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ import { buildJumpAttentionItems, parseSelectionInput, selectJumpAttentionItem,
11
11
  import { TERMINAL_RESTORE_SEQUENCE, formatProcessFailure } from "./process-safety.js";
12
12
  import { detectClaudePhase, resolveClaudeSessionFile } from "./scanner/claude.js";
13
13
  import { detectCodexPhase, indexCodexSessions, matchCodexSession } from "./scanner/codex.js";
14
- import { readDaemonSnapshot } from "./scanner/daemon-utils.js";
14
+ import { readDaemonSnapshot, readDaemonSnapshotResult, } from "./scanner/daemon-utils.js";
15
15
  import { parseGeminiSession, resolveGeminiChatFile } from "./scanner/gemini.js";
16
16
  import { scanAgents } from "./scanner/index.js";
17
17
  import { loadRegistryFromFile } from "./scanner/session-registry.js";
@@ -81,7 +81,7 @@ function buildHelpAppendix() {
81
81
  " watch Live full-screen monitor",
82
82
  " dock Persistent tmux-friendly monitor",
83
83
  " --statusline Status bar output for tmux",
84
- " clean Review or kill unmatched leftovers",
84
+ " clean Review or kill unmatched CLIs by PID",
85
85
  " debug-phase Inspect raw phase signals for one PID",
86
86
  " guard Claude hook evaluator; fail-open on malformed input/errors",
87
87
  " settings-* Locate, inspect, or initialize settings.json",
@@ -114,7 +114,7 @@ function buildHelpAppendix() {
114
114
  " [Idle] Process alive, no recent activity",
115
115
  " [Stalled] No activity for extended period",
116
116
  " [Dead] Session file exists but process gone",
117
- " [Unmatched] AI process without matching session",
117
+ " [Unmatched] Running CLI whose session metadata is not yet bound",
118
118
  "",
119
119
  "Common settings:",
120
120
  " display.attentionLimit / display.statuslineAttentionLimit",
@@ -264,6 +264,7 @@ function buildMinimalConfigSample() {
264
264
  display: {
265
265
  attentionLimit: 10,
266
266
  statuslineAttentionLimit: 5,
267
+ statuslineLabel: "auto",
267
268
  },
268
269
  integration: {
269
270
  tmux: {
@@ -296,6 +297,7 @@ function buildAdvancedConfigSample() {
296
297
  display: {
297
298
  attentionLimit: 10,
298
299
  statuslineAttentionLimit: 5,
300
+ statuslineLabel: "auto",
299
301
  },
300
302
  integration: {
301
303
  tmux: {
@@ -412,15 +414,15 @@ function resolveAttentionLimit(opts, configuredLimit, interactive = false) {
412
414
  return Math.max(Math.floor(fallback), 1);
413
415
  return Math.min(Math.max(Math.floor(fallback), 1), 10);
414
416
  }
415
- function statuslineCacheFile(format, attentionLimit, width) {
417
+ function statuslineCacheFile(format, attentionLimit, width, labelMode = "auto") {
416
418
  const widthKey = width && width > 0 ? String(width) : "auto";
417
- return join(tmpdir(), "marmonitor", `statusline-${format}-${attentionLimit}-${widthKey}.txt`);
419
+ return join(tmpdir(), "marmonitor", `statusline-${format}-${attentionLimit}-${widthKey}-${labelMode}.txt`);
418
420
  }
419
421
  /** Read cached statusline. When activePanePid is provided, the cache is
420
422
  * only valid if the stored panePid (first line) matches — otherwise the
421
423
  * active-window highlight would be stale. Returns {content, panePid}. */
422
- async function readCachedStatusline(format, attentionLimit, width, ttlMs) {
423
- const path = statuslineCacheFile(format, attentionLimit, width);
424
+ async function readCachedStatusline(format, attentionLimit, width, ttlMs, labelMode = "auto") {
425
+ const path = statuslineCacheFile(format, attentionLimit, width, labelMode);
424
426
  try {
425
427
  const fileStat = await stat(path);
426
428
  if (Date.now() - fileStat.mtimeMs > ttlMs)
@@ -440,8 +442,8 @@ async function readCachedStatusline(format, attentionLimit, width, ttlMs) {
440
442
  return undefined;
441
443
  }
442
444
  }
443
- async function writeCachedStatusline(format, attentionLimit, width, value, activePanePid) {
444
- const path = statuslineCacheFile(format, attentionLimit, width);
445
+ async function writeCachedStatusline(format, attentionLimit, width, value, activePanePid, labelMode = "auto") {
446
+ const path = statuslineCacheFile(format, attentionLimit, width, labelMode);
445
447
  const data = activePanePid ? `${activePanePid}\n${value}` : value;
446
448
  try {
447
449
  await mkdir(join(tmpdir(), "marmonitor"), { recursive: true });
@@ -454,17 +456,29 @@ async function writeCachedStatusline(format, attentionLimit, width, value, activ
454
456
  const DAEMON_DIR = join(tmpdir(), "marmonitor");
455
457
  const DAEMON_PID_PATH = join(DAEMON_DIR, "daemon.pid");
456
458
  const DAEMON_SNAPSHOT_PATH = join(DAEMON_DIR, "daemon-snapshot.json");
457
- const DAEMON_NOT_RUNNING = "Daemon not running. Run: marmonitor start";
458
459
  async function getAgentsSnapshot() {
459
460
  return (await readDaemonSnapshot(DAEMON_SNAPSHOT_PATH, 5_000));
460
461
  }
461
- async function requireDaemonSnapshot() {
462
- const agents = await getAgentsSnapshot();
463
- if (agents.length === 0) {
464
- console.error(DAEMON_NOT_RUNNING);
462
+ async function requireFreshSnapshot(jsonErrors = false) {
463
+ const snapshot = await readDaemonSnapshotResult(DAEMON_SNAPSHOT_PATH, 5_000);
464
+ if (snapshot.health !== "fresh") {
465
+ const detail = snapshot.health === "stale" ? ` (${Math.round(snapshot.ageMs)}ms old)` : "";
466
+ if (jsonErrors) {
467
+ console.log(JSON.stringify({
468
+ error: "snapshot-unavailable",
469
+ snapshot: {
470
+ health: snapshot.health,
471
+ ...(snapshot.health === "stale" ? { ageMs: snapshot.ageMs } : {}),
472
+ },
473
+ }));
474
+ }
475
+ console.error(`Daemon snapshot ${snapshot.health}${detail}; current sessions are unavailable.`);
465
476
  process.exit(1);
466
477
  }
467
- return agents;
478
+ return snapshot;
479
+ }
480
+ async function requireDaemonSnapshot() {
481
+ return (await requireFreshSnapshot()).agents;
468
482
  }
469
483
  async function loadSessionRegistry() {
470
484
  const registry = new Map();
@@ -495,7 +509,7 @@ program
495
509
  // Try cache first. For tmux-badges the cached panePid is checked
496
510
  // against the live pane only on cache hit — the tmux call is
497
511
  // deferred so cache-miss paths pay for it just once.
498
- const cached = await readCachedStatusline(opts.statuslineFormat, attentionLimit, width, config.performance.statuslineTtlMs);
512
+ const cached = await readCachedStatusline(opts.statuslineFormat, attentionLimit, width, config.performance.statuslineTtlMs, config.display.statuslineLabel);
499
513
  if (cached) {
500
514
  if (isTmuxBadges && cached.panePid !== undefined) {
501
515
  const { getActiveTmuxPanePid } = await import("./tmux/index.js");
@@ -513,11 +527,12 @@ program
513
527
  return;
514
528
  }
515
529
  }
516
- const agents = await getAgentsSnapshot();
517
- if (agents.length === 0) {
530
+ const snapshot = await readDaemonSnapshotResult(DAEMON_SNAPSHOT_PATH, 5_000);
531
+ if (snapshot.health !== "fresh") {
518
532
  console.log(renderUnavailableStatusline(opts.statuslineFormat));
519
533
  return;
520
534
  }
535
+ const agents = snapshot.agents;
521
536
  // Check jump-back anchor and resolve active agent for tmux-badges
522
537
  let hasJumpAnchor = false;
523
538
  let activeAgentPid;
@@ -535,8 +550,8 @@ program
535
550
  hasJumpAnchor = Boolean(await loadJumpAnchor(pj(td(), "marmonitor", "jump-anchors.json"), tty));
536
551
  }
537
552
  }
538
- const rendered = await renderStatusline(agents, opts.statuslineFormat, attentionLimit, width, config.integration.tmux.badgeStyle, hasJumpAnchor, activeAgentPid);
539
- await writeCachedStatusline(opts.statuslineFormat, attentionLimit, width, rendered, activePanePid);
553
+ const rendered = await renderStatusline(agents, opts.statuslineFormat, attentionLimit, width, config.integration.tmux.badgeStyle, hasJumpAnchor, activeAgentPid, config.display.statuslineLabel);
554
+ await writeCachedStatusline(opts.statuslineFormat, attentionLimit, width, rendered, activePanePid, config.display.statuslineLabel);
540
555
  console.log(rendered);
541
556
  return;
542
557
  }
@@ -553,11 +568,12 @@ program
553
568
  .option("--json", "Output as JSON")
554
569
  .option("--config <path>", "Path to settings.json")
555
570
  .action(async (opts) => {
556
- const agents = await requireDaemonSnapshot();
571
+ const snapshot = await requireFreshSnapshot(opts.json);
572
+ const agents = snapshot.agents;
557
573
  const config = await loadConfig(resolveConfigPath(opts));
558
574
  applyTerminalStyle(config.integration.tmux.badgeStyle);
559
575
  if (opts.json) {
560
- await printStatusJson(agents);
576
+ await printStatusJson(agents, { health: snapshot.health, ageMs: snapshot.ageMs });
561
577
  }
562
578
  else {
563
579
  await printStatus(agents);
@@ -1223,19 +1239,26 @@ function truncateForDisplay(value, maxLength) {
1223
1239
  }
1224
1240
  program
1225
1241
  .command("clean")
1226
- .description("Show or terminate unmatched processes")
1242
+ .description("Show unmatched CLIs or terminate selected PIDs")
1227
1243
  .option("--config <path>", "Path to settings.json")
1228
1244
  .option("--json", "Output as JSON")
1229
- .option("--kill", "Send SIGTERM to selected unmatched processes")
1245
+ .option("--kill", "Send SIGTERM to the unmatched PID(s) given with --pid")
1230
1246
  .option("--pid <pid...>", "Only include specific unmatched PID(s)")
1231
1247
  .action(async (opts) => {
1232
- const config = await loadConfig(resolveConfigPath(opts));
1233
- const agents = await scanAgents(config, { sessionRegistry: await loadSessionRegistry() });
1234
1248
  const selectedPids = Array.isArray(opts.pid)
1235
1249
  ? opts.pid
1236
1250
  .map((value) => Number.parseInt(value, 10))
1237
1251
  .filter((value) => !Number.isNaN(value))
1238
1252
  : undefined;
1253
+ // Unmatched CLIs are live sessions awaiting metadata, so never kill them
1254
+ // in bulk. Require the caller to name each PID explicitly.
1255
+ if (opts.kill && (!selectedPids || selectedPids.length === 0)) {
1256
+ console.error("--kill requires --pid <pid...>; review candidates with `marmonitor clean`.");
1257
+ process.exitCode = 1;
1258
+ return;
1259
+ }
1260
+ const config = await loadConfig(resolveConfigPath(opts));
1261
+ const agents = await scanAgents(config, { sessionRegistry: await loadSessionRegistry() });
1239
1262
  const targets = selectUnmatchedTargets(agents, selectedPids);
1240
1263
  if (opts.kill) {
1241
1264
  for (const target of targets) {
@@ -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[];
@@ -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"] },
@@ -147,7 +148,11 @@ export async function loadConfig(customPath) {
147
148
  const userConfig = JSON.parse(raw);
148
149
  if (!isJsonObject(userConfig))
149
150
  return cloneDefaults();
150
- 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;
151
156
  }
152
157
  catch {
153
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;