marmonitor 0.2.5 → 0.2.6

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
@@ -204,6 +204,7 @@ marmonitor restart # 데몬 재시작 (예: npm 업데이트 후)
204
204
  |--------|------|
205
205
  | `prefix + a` | 어텐션 팝업 — 검토할 세션 선택 |
206
206
  | `prefix + j` | 점프 팝업 — 이동할 세션 선택 |
207
+ | `prefix + y` | 활성 패널의 최신 AI 답변 턴 복사 |
207
208
  | `prefix + m` | 독 — 컴팩트 모니터 패널 |
208
209
  | `Option+1~5` | 어텐션 세션 #1~5로 바로 이동 |
209
210
  | `Option+`` | 이전 패널로 돌아가기 |
@@ -214,6 +215,7 @@ marmonitor restart # 데몬 재시작 (예: npm 업데이트 후)
214
215
  marmonitor status # 전체 세션 목록
215
216
  marmonitor attention # 입력이 필요한 세션 확인
216
217
  marmonitor activity # 각 세션의 활동 내역 (도구 호출 + 토큰)
218
+ marmonitor copy-latest-turn # 활성 tmux 패널의 최신 AI/user 턴 복사
217
219
  marmonitor watch # 실시간 전체 화면 모니터
218
220
  marmonitor jump-back # 마지막 점프 이전 패널로 복귀
219
221
  marmonitor help # 모든 명령어 및 옵션
@@ -257,7 +259,7 @@ marmonitor activity --json # JSON 출력
257
259
  [marmonitor-tmux](https://github.com/mjjo16/marmonitor-tmux) 플러그인이 tmux 설정을 자동으로 처리합니다:
258
260
 
259
261
  - 에이전트 뱃지와 어텐션 필이 포함된 2번째 상태 라인
260
- - 팝업, 점프, 독 키 바인딩
262
+ - 팝업, 점프, 최신 턴 복사, 독 키 바인딩
261
263
  - Option+1~5 다이렉트 점프
262
264
 
263
265
  `@marmonitor-*` 옵션으로 원하는 대로 바꿀 수 있습니다. 자세한 내용은 [플러그인 README](https://github.com/mjjo16/marmonitor-tmux)를 참조하세요.
package/README.md CHANGED
@@ -206,6 +206,7 @@ The daemon must be running for all other commands to work. `marmonitor setup tmu
206
206
  |----------|--------|
207
207
  | `prefix + a` | Attention popup — choose a session to review |
208
208
  | `prefix + j` | Jump popup — pick a session to jump to |
209
+ | `prefix + y` | Copy the latest AI assistant turn from the active pane |
209
210
  | `prefix + m` | Dock — compact monitor pane |
210
211
  | `Option+1~5` | Direct jump to attention session #1~5 |
211
212
  | `Option+`` | Jump back to previous pane |
@@ -216,6 +217,7 @@ The daemon must be running for all other commands to work. `marmonitor setup tmu
216
217
  marmonitor status # Full session inventory
217
218
  marmonitor attention # What needs your input?
218
219
  marmonitor activity # What did each session do? (tool calls + tokens)
220
+ marmonitor copy-latest-turn # Copy the latest AI/user turn from the active tmux pane
219
221
  marmonitor watch # Live full-screen monitor
220
222
  marmonitor jump-back # Return to pane before last jump
221
223
  marmonitor help # All commands and options
@@ -259,7 +261,7 @@ Activity is collected automatically by the daemon and stored in `~/.config/marmo
259
261
  The [marmonitor-tmux](https://github.com/mjjo16/marmonitor-tmux) plugin handles all tmux setup automatically:
260
262
 
261
263
  - 2nd status line with agent badges and attention pills
262
- - Key bindings for popup, jump, and dock
264
+ - Key bindings for popup, jump, latest-turn copy, and dock
263
265
  - Option+1~5 direct jump
264
266
 
265
267
  All settings are customizable via `@marmonitor-*` options. See the [plugin README](https://github.com/mjjo16/marmonitor-tmux) for details.
@@ -287,11 +289,13 @@ Useful commands:
287
289
  marmonitor alerts
288
290
  marmonitor alerts on
289
291
  marmonitor alerts off
292
+ marmonitor alerts tokens on
293
+ marmonitor alerts tokens off
290
294
  marmonitor alerts notify on
291
295
  marmonitor alerts notify off
292
296
  ```
293
297
 
294
- Desktop notifications can be enabled separately from alert collection. After changing alert settings, restart the daemon to apply them:
298
+ Desktop notifications can be enabled separately from alert collection, and token/context alerts can be silenced without turning off security alerts. After changing alert settings, restart the daemon to apply them:
295
299
 
296
300
  ```bash
297
301
  marmonitor restart
@@ -35,8 +35,16 @@ export function checkTokenAlert(store, agent, thresholds = DEFAULT_TOKEN_THRESHO
35
35
  if (!usage)
36
36
  return undefined;
37
37
  // lastInputTokens = most recent API call's input_tokens = actual current context size.
38
- // Fall back to cumulative inputTokens only if lastInputTokens is unavailable.
39
- const used = usage.lastInputTokens ?? usage.inputTokens;
38
+ // Only fire when this definitive signal is available as a finite number.
39
+ // `Number.isFinite` rejects undefined / null (e.g. from external JSON) / NaN /
40
+ // Infinity in one check. Falling back to the cumulative inputTokens (which
41
+ // grows unboundedly across a session) would massively overstate the context %
42
+ // for agents that do not populate lastInputTokens — most notably Codex.
43
+ // Tracked as GitHub #55 / local #102 (root fix: split TokenUsage into
44
+ // cumulative vs context-window fields).
45
+ if (!Number.isFinite(usage.lastInputTokens))
46
+ return undefined;
47
+ const used = usage.lastInputTokens;
40
48
  const limit = contextLimit(agent.model);
41
49
  const ratio = used / limit;
42
50
  if (ratio >= thresholds.critAt) {
package/dist/cli.js CHANGED
@@ -3,15 +3,16 @@ import { tmpdir } from "node:os";
3
3
  import { dirname, join } from "node:path";
4
4
  import { Command } from "commander";
5
5
  import { renderInstallBanner, renderRuntimeBanner } from "./banner/index.js";
6
+ import { ClipboardError, writeClipboard } from "./clipboard.js";
6
7
  import { getConfigDir, getConfigSearchPaths, getDefaultConfigPath, loadConfig, resolveConfigPath as resolveLoadedConfigPath, } from "./config/index.js";
7
8
  import { detectGuardTriggers, evaluateGuard, formatGuardOutput, parseHookEvent, readStdin, } from "./guard/index.js";
8
9
  import { applyTerminalStyle, printAttention, printAttentionJson, printCleanJson, printCleanPlan, printDock, printJumpJson, printJumpResult, printStatus, printStatusJson, renderJumpAttentionChooser, renderStatusline, renderUnavailableStatusline, } from "./output/index.js";
9
10
  import { buildJumpAttentionItems, parseSelectionInput, selectJumpAttentionItem, selectJumpAttentionItemOnPage, selectUnmatchedTargets, } from "./output/utils.js";
10
11
  import { TERMINAL_RESTORE_SEQUENCE, formatProcessFailure } from "./process-safety.js";
11
- import { detectClaudePhase } from "./scanner/claude.js";
12
+ import { detectClaudePhase, resolveClaudeSessionFile } from "./scanner/claude.js";
12
13
  import { detectCodexPhase, indexCodexSessions, matchCodexSession } from "./scanner/codex.js";
13
14
  import { readDaemonSnapshot } from "./scanner/daemon-utils.js";
14
- import { parseGeminiSession } from "./scanner/gemini.js";
15
+ import { parseGeminiSession, resolveGeminiChatFile } from "./scanner/gemini.js";
15
16
  import { scanAgents } from "./scanner/index.js";
16
17
  import { loadRegistryFromFile } from "./scanner/session-registry.js";
17
18
  import { detectCliStdoutPhase } from "./scanner/status.js";
@@ -790,6 +791,7 @@ const alertsCmd = program
790
791
  console.log(`alerts.enabled : ${a.enabled}`);
791
792
  console.log(`alerts.desktop : ${a.desktop}`);
792
793
  console.log(`alerts.log : ${a.log}`);
794
+ console.log(`alerts.tokens : ${a.tokens} (token/context threshold alerts)`);
793
795
  console.log(`alerts.contextCritThreshold: ${a.contextCritThreshold} (${Math.round(a.contextCritThreshold * 100)}%)`);
794
796
  console.log(`alerts.contextWarnThreshold: ${a.contextWarnThreshold === 1.0 ? "disabled" : `${a.contextWarnThreshold} (${Math.round(a.contextWarnThreshold * 100)}%)`}`);
795
797
  });
@@ -824,6 +826,19 @@ alertsCmd
824
826
  await patchAlertsConfig(p, { desktop: toggle === "on" });
825
827
  console.log(`Desktop notifications ${toggle === "on" ? "enabled" : "disabled"}. Restart daemon to apply: marmonitor restart`);
826
828
  });
829
+ alertsCmd
830
+ .command("tokens <on|off>")
831
+ .description("Toggle token/context threshold alerts (security alerts unaffected)")
832
+ .option("--config <path>", "Path to settings.json")
833
+ .action(async (toggle, opts) => {
834
+ if (toggle !== "on" && toggle !== "off") {
835
+ console.error("Usage: marmonitor alerts tokens on|off");
836
+ process.exit(1);
837
+ }
838
+ const p = resolveConfigPath(opts) ?? getDefaultConfigPath();
839
+ await patchAlertsConfig(p, { tokens: toggle === "on" });
840
+ console.log(`Token/context alerts ${toggle === "on" ? "enabled" : "disabled"}. Restart daemon to apply: marmonitor restart`);
841
+ });
827
842
  // ── end alerts command ───────────────────────────────────────────────────────
828
843
  program
829
844
  .command("debug-phase")
@@ -1430,5 +1445,140 @@ program
1430
1445
  await startDaemon();
1431
1446
  process.exit(0);
1432
1447
  });
1448
+ // ── copy-latest-turn command ─────────────────────────────────────────────────
1449
+ program
1450
+ .command("copy-latest-turn")
1451
+ .description("Copy the most recent AI turn of the active tmux pane to the clipboard (Claude / Codex / Gemini)")
1452
+ .option("--role <role>", "Which turn to copy: assistant (default) or user", "assistant")
1453
+ .option("--mode <mode>", "Extraction mode: text (default) or bundle", "text")
1454
+ .option("--pane-pid <pid>", "Override active pane PID (default: tmux active pane). Useful for tmux key bindings that pass #{pane_pid}.")
1455
+ .option("--stdout", "Print the turn to stdout instead of copying to clipboard")
1456
+ .option("--config <path>", "Path to settings.json")
1457
+ .action(async (opts) => {
1458
+ const { parseClaudeConversationTurns, parseCodexConversationTurns, parseGeminiConversationTurns, selectLatestTurn, turnTextForMode, } = await import("./turns.js");
1459
+ const role = opts.role === "user" ? "user" : "assistant";
1460
+ const mode = opts.mode === "bundle" ? "bundle" : "text";
1461
+ const agents = await requireDaemonSnapshot();
1462
+ let agent;
1463
+ let panePidOverridden = false;
1464
+ if (typeof opts.panePid === "string") {
1465
+ const panePid = Number.parseInt(opts.panePid, 10);
1466
+ if (!Number.isFinite(panePid)) {
1467
+ console.error(`Invalid --pane-pid value: ${opts.panePid}`);
1468
+ process.exit(1);
1469
+ }
1470
+ panePidOverridden = true;
1471
+ const agentPids = agents.map((a) => a.pid);
1472
+ const matchedPid = await findActiveAgentPid(agentPids, panePid);
1473
+ if (matchedPid !== undefined) {
1474
+ agent = agents.find((a) => a.pid === matchedPid);
1475
+ }
1476
+ }
1477
+ else {
1478
+ // Active tmux pane fallback
1479
+ const agentPids = agents.map((a) => a.pid);
1480
+ const matchedPid = await findActiveAgentPid(agentPids);
1481
+ if (matchedPid !== undefined) {
1482
+ agent = agents.find((a) => a.pid === matchedPid);
1483
+ }
1484
+ }
1485
+ if (!agent) {
1486
+ console.error(panePidOverridden
1487
+ ? `No AI session matched the given pane PID (${opts.panePid}).`
1488
+ : "No AI session in this tmux pane. Switch to a Claude pane and try again.");
1489
+ process.exit(1);
1490
+ }
1491
+ const config = await loadConfig(resolveConfigPath(opts));
1492
+ // Resolve the agent-specific source file and parse to SessionTurn[].
1493
+ let sessionFile;
1494
+ let turns = [];
1495
+ if (agent.agentName === "Claude Code") {
1496
+ // Trust the daemon snapshot's per-PID sessionId. Earlier we tried a
1497
+ // cwd-keyed live re-resolve here (F1, see #62 review), but that lost
1498
+ // PID identity when two Claude sessions share the same cwd —
1499
+ // `matchClaudeSessionByMtime` returned whichever jsonl scored best by
1500
+ // cwd alone, so `prefix+y` in pane A could copy pane B's turn. The
1501
+ // narrower `/resume` staleness concern that motivated F1 is tracked
1502
+ // separately under #107 (daemon snapshot freshness).
1503
+ if (!agent.sessionId) {
1504
+ console.error("Active Claude session has no sessionId yet — try again in a moment.");
1505
+ process.exit(1);
1506
+ }
1507
+ sessionFile = await resolveClaudeSessionFile(agent.sessionId, agent.cwd, agent.startedAt, config);
1508
+ if (!sessionFile) {
1509
+ console.error("Claude session file not found for this pane.");
1510
+ process.exit(1);
1511
+ }
1512
+ const raw = await readFile(sessionFile, "utf-8");
1513
+ turns = parseClaudeConversationTurns(raw);
1514
+ }
1515
+ else if (agent.agentName === "Codex") {
1516
+ // Mirror scanner's session resolution priority: persistent binding
1517
+ // registry (PID × processStartedAt → rollout) first, fallback to
1518
+ // cwd + processStartedAt matching. Same-cwd multi-Codex environments
1519
+ // would otherwise route to the wrong rollout file.
1520
+ const codexSessions = await indexCodexSessions(config, { activeCwds: [agent.cwd] });
1521
+ const { loadCodexBindingRegistryFromFile, selectCodexBindingSession } = await import("./scanner/codex-binding-registry.js");
1522
+ const bindingRegistry = new Map();
1523
+ await loadCodexBindingRegistryFromFile(join(getConfigDir(), "codex-binding-registry.json"), bindingRegistry);
1524
+ const matched = selectCodexBindingSession(bindingRegistry, agent.pid, agent.processStartedAt, agent.cwd, codexSessions) ?? matchCodexSession(agent.cwd, agent.processStartedAt, codexSessions);
1525
+ if (!matched?.filePath) {
1526
+ console.error("Codex rollout file not found for this pane.");
1527
+ process.exit(1);
1528
+ }
1529
+ sessionFile = matched.filePath;
1530
+ const raw = await readFile(sessionFile, "utf-8");
1531
+ turns = parseCodexConversationTurns(raw);
1532
+ }
1533
+ else if (agent.agentName === "Gemini") {
1534
+ // Match the snapshot's sessionId against on-disk Gemini chats first so
1535
+ // multi-session same-cwd environments don't fall back to "latest mtime
1536
+ // wins". parseGeminiSession (latest mtime) remains as a graceful fallback.
1537
+ sessionFile = await resolveGeminiChatFile(agent.cwd, agent.sessionId);
1538
+ if (!sessionFile) {
1539
+ const gemini = await parseGeminiSession(agent.cwd);
1540
+ sessionFile = gemini.sessionFile;
1541
+ }
1542
+ if (!sessionFile) {
1543
+ console.error("Gemini chat file not found for this pane.");
1544
+ process.exit(1);
1545
+ }
1546
+ const raw = await readFile(sessionFile, "utf-8");
1547
+ turns = parseGeminiConversationTurns(raw);
1548
+ }
1549
+ else {
1550
+ console.error(`Turn copy is not supported for ${agent.agentName} yet.`);
1551
+ process.exit(1);
1552
+ }
1553
+ const turn = selectLatestTurn(turns, role);
1554
+ if (!turn) {
1555
+ console.error(`No recent ${role} turn found in this ${agent.agentName} session.`);
1556
+ process.exit(1);
1557
+ }
1558
+ const text = turnTextForMode(turn, mode);
1559
+ if (!text) {
1560
+ console.error(`Latest ${role} turn has no ${mode === "bundle" ? "bundle" : "text"} content.`);
1561
+ process.exit(1);
1562
+ }
1563
+ if (opts.stdout) {
1564
+ console.log(text);
1565
+ return;
1566
+ }
1567
+ try {
1568
+ await writeClipboard(text);
1569
+ const chars = text.length;
1570
+ const label = role === "assistant" ? "AI" : "user";
1571
+ console.log(`marmonitor: copied ${label} turn (${chars} chars)`);
1572
+ }
1573
+ catch (err) {
1574
+ if (err instanceof ClipboardError) {
1575
+ console.error(err.message);
1576
+ }
1577
+ else {
1578
+ console.error(`Clipboard copy failed: ${err.message}. Try --stdout instead.`);
1579
+ }
1580
+ process.exit(1);
1581
+ }
1582
+ });
1433
1583
  installProcessSafetyHandlers();
1434
1584
  program.parse();
@@ -0,0 +1,12 @@
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
+ export declare class ClipboardError extends Error {
10
+ constructor(message: string);
11
+ }
12
+ export declare function writeClipboard(text: string): Promise<void>;
@@ -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
+ }
@@ -93,6 +93,8 @@ export interface MarmonitorConfig {
93
93
  desktop: boolean;
94
94
  /** alerts.log 파일 기록 */
95
95
  log: boolean;
96
+ /** 토큰/컨텍스트 임계 알림 카테고리 토글. 보안 알림과 분리 가능. 기본 true */
97
+ tokens: boolean;
96
98
  /** 컨텍스트 경고 임계값 (0~1). 0 = 비활성화. 기본 1.0 (비활성) */
97
99
  contextWarnThreshold: number;
98
100
  /** 컨텍스트 위험 임계값 (0~1). 기본 0.85 */
@@ -93,9 +93,10 @@ const DEFAULTS = {
93
93
  activityRetentionDays: 7,
94
94
  },
95
95
  alerts: {
96
- enabled: true,
97
- desktop: true,
98
- log: true,
96
+ enabled: false,
97
+ desktop: false,
98
+ log: false,
99
+ tokens: true, // 활성 시 토큰/컨텍스트 임계 알림 발사. 보안 알림은 별도 게이트 없음
99
100
  contextWarnThreshold: 1.0, // 기본 비활성 (0.70으로 설정 시 활성화)
100
101
  contextCritThreshold: 0.85,
101
102
  },
@@ -418,7 +418,26 @@ async function readJsonlSessionMeta(filePath) {
418
418
  await fd?.close().catch(() => { });
419
419
  }
420
420
  }
421
- async function chooseStaleSessionOverride(processCwd, currentSessionId, config) {
421
+ /**
422
+ * Stale-session override resolver.
423
+ *
424
+ * Picks a non-current jsonl when the current sessionId's metadata is stale
425
+ * (e.g. just after /clear), but refuses to do so when the current jsonl
426
+ * clearly belongs to this process or when the candidate jsonl is already
427
+ * claimed in the registry. See local issue #103 / GH #56 for the misrouting
428
+ * case this guards.
429
+ *
430
+ * Conservative guards layered on top of the legacy mtime-lead check:
431
+ * - F1: if currentDirectPath exists and its first-line timestamp is on or
432
+ * after processStartedAt, the current jsonl was authored by this
433
+ * process — keep it, do not override.
434
+ * - F2: if the override-candidate sessionId is already direct-bound in
435
+ * claudeSessionRegistry, refuse the override. Keeps the
436
+ * one-jsonl-per-sessionId invariant intact.
437
+ * - F3: anything ambiguous falls through to `undefined` (unresolved) —
438
+ * a missed match is safer than a misrouted one.
439
+ */
440
+ async function chooseStaleSessionOverride(processCwd, currentSessionId, processStartedAt, config) {
422
441
  const projectDirName = await findClaudeProjectDir(processCwd, currentSessionId, config);
423
442
  if (!projectDirName)
424
443
  return undefined;
@@ -435,27 +454,46 @@ async function chooseStaleSessionOverride(processCwd, currentSessionId, config)
435
454
  .find((candidate) => existsSync(candidate))
436
455
  : undefined;
437
456
  if (currentDirectPath) {
457
+ let currentStat;
458
+ let recentStat;
438
459
  try {
439
- const [recentStat, currentStat] = await Promise.all([
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;
460
+ [recentStat, currentStat] = await Promise.all([stat(recentPath), stat(currentDirectPath)]);
449
461
  }
450
462
  catch {
451
463
  return undefined;
452
464
  }
465
+ // F1: a non-empty current jsonl whose first event is on or after the
466
+ // process start belongs to this process. Same-cwd sibling sessions land
467
+ // here and must not be routed onto another session's active jsonl.
468
+ if (currentStat.size > 0 && processStartedAt !== undefined) {
469
+ const currentMeta = await readJsonlSessionMeta(currentDirectPath);
470
+ if (currentMeta?.timestamp) {
471
+ const jsonlCreatedAtSec = new Date(currentMeta.timestamp).getTime() / 1000;
472
+ if (Number.isFinite(jsonlCreatedAtSec)) {
473
+ const CLOCK_SKEW_SEC = 60;
474
+ if (jsonlCreatedAtSec >= processStartedAt - CLOCK_SKEW_SEC)
475
+ return undefined;
476
+ }
477
+ }
478
+ }
479
+ const minLeadMs = 5 * 60 * 1000;
480
+ const staleGapMs = 30 * 60 * 1000;
481
+ if (recentStat.mtimeMs - currentStat.mtimeMs < minLeadMs)
482
+ return undefined;
483
+ if (Date.now() - currentStat.mtimeMs < staleGapMs)
484
+ return undefined;
453
485
  }
454
486
  const recentMeta = await readJsonlSessionMeta(recentPath);
455
487
  if (!recentMeta?.sessionId)
456
488
  return undefined;
457
489
  if (recentMeta.sessionId === currentSessionId)
458
490
  return undefined;
491
+ // F2: the candidate sessionId is already direct-bound in the registry.
492
+ // Overriding would let two sessionIds share one jsonl — the exact bug
493
+ // in #103. Keeps the one-jsonl-per-sessionId invariant.
494
+ const recentBinding = claudeSessionRegistry.get(recentMeta.sessionId);
495
+ if (recentBinding?.binding === "direct")
496
+ return undefined;
459
497
  return {
460
498
  sessionId: recentMeta.sessionId,
461
499
  cwd: recentMeta.cwd ?? processCwd,
@@ -600,7 +638,7 @@ export async function parseClaudeSession(pid, cwd, processStartedAt, config) {
600
638
  let resolvedCwd = data.cwd;
601
639
  let resolvedStartedAt = sessionStartedAt;
602
640
  if (processCwd && processCwd !== "unknown") {
603
- const override = await chooseStaleSessionOverride(processCwd, data.sessionId, config);
641
+ const override = await chooseStaleSessionOverride(processCwd, data.sessionId, processStartedAt, config);
604
642
  if (override) {
605
643
  resolvedSessionId = override.sessionId;
606
644
  resolvedCwd = override.cwd ?? processCwd;
@@ -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>;
@@ -10,6 +10,33 @@ import { resolveRuntimeDataPaths } from "../config/index.js";
10
10
  import { advanceJsonlCursor, resolvePhaseFromHistory, resolvePhaseWithDecay, selectCodexSession, updatePhaseHistory, upsertSessionRegistryEntry, } from "../output/utils.js";
11
11
  import { CODEX_INDEX_TTL_MS, CODEX_PHASE_RECENT_LINES, HOME, codexIndexCache, codexPhaseCache, codexSessionFileCache, codexSessionRegistry, setCodexIndexCache, } from "./cache.js";
12
12
  const CODEX_SQLITE_RECENT_DAYS = 7;
13
+ function mergeCodexIndexedSessions(baseSessions, incomingSessions) {
14
+ const merged = new Map();
15
+ for (const session of baseSessions) {
16
+ merged.set(session.id, session);
17
+ }
18
+ for (const session of incomingSessions) {
19
+ const existing = merged.get(session.id);
20
+ if (!existing) {
21
+ merged.set(session.id, session);
22
+ continue;
23
+ }
24
+ merged.set(session.id, {
25
+ ...existing,
26
+ ...session,
27
+ filePath: session.filePath || existing.filePath,
28
+ cwd: session.cwd || existing.cwd,
29
+ timestamp: Math.min(existing.timestamp || session.timestamp, session.timestamp || existing.timestamp),
30
+ lastActivityAt: Math.max(existing.lastActivityAt ?? 0, session.lastActivityAt ?? 0) || undefined,
31
+ totalTokenUsage: session.totalTokenUsage?.total_tokens !== undefined
32
+ ? session.totalTokenUsage
33
+ : existing.totalTokenUsage,
34
+ model: session.model ?? existing.model,
35
+ });
36
+ }
37
+ return [...merged.values()].sort((a, b) => (b.lastActivityAt ?? b.timestamp) - (a.lastActivityAt ?? a.timestamp));
38
+ }
39
+ export { mergeCodexIndexedSessions };
13
40
  export function getCodexSessionRoots(config) {
14
41
  return config
15
42
  ? resolveRuntimeDataPaths(config).codexSessions
@@ -113,16 +140,17 @@ export async function indexCodexSessions(config, options) {
113
140
  return codexIndexCache.sessions;
114
141
  }
115
142
  const hasExplicitSessionRoots = Boolean(config?.paths.codexSessions?.length);
143
+ const sqliteSessions = [];
116
144
  // Primary: SQLite threads table
117
145
  const dbPath = hasExplicitSessionRoots ? undefined : findCodexStateDb();
118
146
  if (dbPath) {
119
- const sqliteSessions = await indexCodexSessionsFromSqlite(dbPath, {
147
+ const indexed = await indexCodexSessionsFromSqlite(dbPath, {
120
148
  recentUpdatedAfter: Math.floor(Date.now() / 1000) - CODEX_SQLITE_RECENT_DAYS * 86400,
121
149
  includeCwds: activeCwds,
122
150
  });
123
- if (sqliteSessions.length > 0) {
151
+ if (indexed.length > 0) {
124
152
  // Register sessions for phase detection and cwd lookup
125
- for (const s of sqliteSessions) {
153
+ for (const s of indexed) {
126
154
  codexSessionFileCache.set(s.filePath, { ...s, mtimeMs: undefined, size: undefined });
127
155
  upsertSessionRegistryEntry(codexSessionRegistry, {
128
156
  filePath: s.filePath,
@@ -135,10 +163,7 @@ export async function indexCodexSessions(config, options) {
135
163
  binding: "direct",
136
164
  });
137
165
  }
138
- if (!hasTargetedFilter) {
139
- setCodexIndexCache({ builtAt: Date.now(), sessions: sqliteSessions });
140
- }
141
- return sqliteSessions;
166
+ sqliteSessions.push(...indexed);
142
167
  }
143
168
  }
144
169
  // Fallback: JSONL directory scan (last 7 days)
@@ -200,6 +225,9 @@ export async function indexCodexSessions(config, options) {
200
225
  }
201
226
  }
202
227
  if (meta.id && meta.cwd && meta.timestamp) {
228
+ if (hasTargetedFilter && !activeCwds.includes(meta.cwd)) {
229
+ continue;
230
+ }
203
231
  const parsed = {
204
232
  filePath,
205
233
  id: meta.id,
@@ -235,11 +263,12 @@ export async function indexCodexSessions(config, options) {
235
263
  catch {
236
264
  // sessions dir error
237
265
  }
266
+ const sessions = mergeCodexIndexedSessions(sqliteSessions, metas);
238
267
  setCodexIndexCache({
239
268
  builtAt: Date.now(),
240
- sessions: metas,
269
+ sessions,
241
270
  });
242
- return metas;
271
+ return sessions;
243
272
  }
244
273
  /** Match a Codex process to a session by cwd + closest timestamp */
245
274
  export function matchCodexSession(processCwd, processStartTime, sessions) {
@@ -15,4 +15,6 @@ export interface DaemonOptions {
15
15
  activityLogDir: string;
16
16
  activityRetentionDays: number;
17
17
  }
18
+ /** Token/context threshold alerts fire only when both master and category toggles are on. */
19
+ export declare function shouldRunTokenAlerts(config: MarmonitorConfig): boolean;
18
20
  export declare function runDaemonLoop(config: MarmonitorConfig, options: DaemonOptions): Promise<void>;
@@ -13,6 +13,10 @@ import { loadRegistryFromFile, pruneRegistry, saveRegistryToFile, updateRegistry
13
13
  function sleep(ms) {
14
14
  return new Promise((resolve) => setTimeout(resolve, ms));
15
15
  }
16
+ /** Token/context threshold alerts fire only when both master and category toggles are on. */
17
+ export function shouldRunTokenAlerts(config) {
18
+ return Boolean(config.alerts.enabled && config.alerts.tokens);
19
+ }
16
20
  export async function runDaemonLoop(config, options) {
17
21
  const { intervalMs, detailIntervalMs, snapshotPath, alertsSnapshotPath, alertsLogPath, pidPath, registryPath, codexBindingRegistryPath, activityLogDir, activityRetentionDays, } = options;
18
22
  // Activity log: per-session JSONL cursor offsets (in-memory only)
@@ -69,8 +73,8 @@ export async function runDaemonLoop(config, options) {
69
73
  updateRegistry(registry, agents);
70
74
  // Write snapshot for statusline consumers
71
75
  await writeDaemonSnapshot(snapshotPath, agents);
72
- // Check token thresholds and fire alerts (alerts.enabled 확인)
73
- if (config.alerts.enabled) {
76
+ // Check token thresholds and fire alerts (alerts.enabled + alerts.tokens 확인)
77
+ if (shouldRunTokenAlerts(config)) {
74
78
  const thresholds = {
75
79
  warnAt: config.alerts.contextWarnThreshold,
76
80
  critAt: config.alerts.contextCritThreshold,
@@ -16,6 +16,16 @@ export interface GeminiSessionMeta {
16
16
  export declare function toEpochSec(value: string | undefined): number | undefined;
17
17
  export declare function parseGeminiSessionContent(raw: string): Partial<GeminiSessionMeta>;
18
18
  export declare function resolveGeminiProjectDir(cwd: string): Promise<string | undefined>;
19
+ /**
20
+ * Resolve a Gemini chats file by sessionId match first, then by latest mtime.
21
+ *
22
+ * Same-cwd multi-session safety: when `sessionId` is provided we scan each
23
+ * chats/*.json's `sessionId` field and return the matching path. Without a
24
+ * match we fall back to the most recently modified file (the legacy
25
+ * behaviour of parseGeminiSession). Returns undefined if no chats dir or
26
+ * no files exist.
27
+ */
28
+ export declare function resolveGeminiChatFile(cwd: string, sessionId?: string): Promise<string | undefined>;
19
29
  export declare function parseGeminiSession(cwd: string): Promise<Partial<AgentSession> & {
20
30
  sessionFile?: string;
21
31
  }>;