marmonitor 0.2.4 → 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.
Files changed (43) hide show
  1. package/README.ko.md +52 -1
  2. package/README.md +76 -1
  3. package/dist/alerts/desktop.d.ts +3 -0
  4. package/dist/alerts/desktop.js +23 -0
  5. package/dist/alerts/index.d.ts +7 -0
  6. package/dist/alerts/index.js +5 -0
  7. package/dist/alerts/log.d.ts +3 -0
  8. package/dist/alerts/log.js +14 -0
  9. package/dist/alerts/snapshot.d.ts +4 -0
  10. package/dist/alerts/snapshot.js +25 -0
  11. package/dist/alerts/store.d.ts +23 -0
  12. package/dist/alerts/store.js +61 -0
  13. package/dist/alerts/token.d.ts +18 -0
  14. package/dist/alerts/token.js +73 -0
  15. package/dist/alerts/types.d.ts +23 -0
  16. package/dist/alerts/types.js +2 -0
  17. package/dist/cli.js +341 -23
  18. package/dist/clipboard.d.ts +12 -0
  19. package/dist/clipboard.js +56 -0
  20. package/dist/config/index.d.ts +14 -0
  21. package/dist/config/index.js +8 -0
  22. package/dist/guard/index.js +51 -5
  23. package/dist/output/badge-themes.d.ts +3 -0
  24. package/dist/output/badge-themes.js +12 -0
  25. package/dist/output/index.d.ts +1 -1
  26. package/dist/output/index.js +2 -2
  27. package/dist/output/utils.d.ts +2 -1
  28. package/dist/output/utils.js +9 -4
  29. package/dist/scanner/claude.js +212 -90
  30. package/dist/scanner/codex.d.ts +2 -0
  31. package/dist/scanner/codex.js +40 -9
  32. package/dist/scanner/daemon-entry.js +2 -0
  33. package/dist/scanner/daemon-loop.d.ts +4 -0
  34. package/dist/scanner/daemon-loop.js +25 -1
  35. package/dist/scanner/gemini.d.ts +10 -0
  36. package/dist/scanner/gemini.js +82 -0
  37. package/dist/scanner/process.js +11 -1
  38. package/dist/tmux/index.d.ts +26 -0
  39. package/dist/tmux/index.js +102 -0
  40. package/dist/turns.d.ts +68 -0
  41. package/dist/turns.js +430 -0
  42. package/dist/types.d.ts +2 -0
  43. package/package.json +3 -1
package/dist/cli.js CHANGED
@@ -3,19 +3,20 @@ 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
- import { evaluateGuard, formatGuardOutput, parseHookEvent, readStdin } from "./guard/index.js";
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
- import { isDaemonRunning, readDaemonPid, readDaemonSnapshot } from "./scanner/daemon-utils.js";
14
- import { parseGeminiSession } from "./scanner/gemini.js";
14
+ import { readDaemonSnapshot } from "./scanner/daemon-utils.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";
18
- import { captureTmuxPaneOutput, jumpToAgent, resolveTmuxJumpTarget } from "./tmux/index.js";
19
+ import { captureTmuxPaneOutput, findActiveAgentPid, jumpToAgent, resolveTmuxJumpTarget, } from "./tmux/index.js";
19
20
  import { getClientTty, jumpBack } from "./tmux/jump-anchor.js";
20
21
  import { findClickedAgent, parseStatusClickToken } from "./tmux/status-click.js";
21
22
  import { VERSION } from "./version.js";
@@ -415,23 +416,36 @@ function statuslineCacheFile(format, attentionLimit, width) {
415
416
  const widthKey = width && width > 0 ? String(width) : "auto";
416
417
  return join(tmpdir(), "marmonitor", `statusline-${format}-${attentionLimit}-${widthKey}.txt`);
417
418
  }
419
+ /** Read cached statusline. When activePanePid is provided, the cache is
420
+ * only valid if the stored panePid (first line) matches — otherwise the
421
+ * active-window highlight would be stale. Returns {content, panePid}. */
418
422
  async function readCachedStatusline(format, attentionLimit, width, ttlMs) {
419
423
  const path = statuslineCacheFile(format, attentionLimit, width);
420
424
  try {
421
425
  const fileStat = await stat(path);
422
426
  if (Date.now() - fileStat.mtimeMs > ttlMs)
423
427
  return undefined;
424
- return (await readFile(path, "utf-8")).trimEnd();
428
+ const raw = (await readFile(path, "utf-8")).trimEnd();
429
+ const newline = raw.indexOf("\n");
430
+ if (newline === -1)
431
+ return { content: raw, panePid: undefined };
432
+ const firstLine = raw.slice(0, newline);
433
+ const pid = Number.parseInt(firstLine, 10);
434
+ if (Number.isFinite(pid)) {
435
+ return { content: raw.slice(newline + 1), panePid: pid };
436
+ }
437
+ return { content: raw, panePid: undefined };
425
438
  }
426
439
  catch {
427
440
  return undefined;
428
441
  }
429
442
  }
430
- async function writeCachedStatusline(format, attentionLimit, width, value) {
443
+ async function writeCachedStatusline(format, attentionLimit, width, value, activePanePid) {
431
444
  const path = statuslineCacheFile(format, attentionLimit, width);
445
+ const data = activePanePid ? `${activePanePid}\n${value}` : value;
432
446
  try {
433
447
  await mkdir(join(tmpdir(), "marmonitor"), { recursive: true });
434
- await writeFile(path, value, "utf-8");
448
+ await writeFile(path, data, "utf-8");
435
449
  }
436
450
  catch {
437
451
  // cache failures must never break statusline rendering
@@ -477,29 +491,52 @@ program
477
491
  }
478
492
  const attentionLimit = config.display.statuslineAttentionLimit;
479
493
  const width = resolveStatuslineWidth(opts.width);
494
+ const isTmuxBadges = opts.statuslineFormat === "tmux-badges";
495
+ // Try cache first. For tmux-badges the cached panePid is checked
496
+ // against the live pane only on cache hit — the tmux call is
497
+ // deferred so cache-miss paths pay for it just once.
480
498
  const cached = await readCachedStatusline(opts.statuslineFormat, attentionLimit, width, config.performance.statuslineTtlMs);
481
499
  if (cached) {
482
- console.log(cached);
483
- return;
500
+ if (isTmuxBadges && cached.panePid !== undefined) {
501
+ const { getActiveTmuxPanePid } = await import("./tmux/index.js");
502
+ const currentPanePid = await getActiveTmuxPanePid();
503
+ if (currentPanePid !== cached.panePid) {
504
+ // Active pane changed — fall through to re-render
505
+ }
506
+ else {
507
+ console.log(cached.content);
508
+ return;
509
+ }
510
+ }
511
+ else {
512
+ console.log(cached.content);
513
+ return;
514
+ }
484
515
  }
485
516
  const agents = await getAgentsSnapshot();
486
517
  if (agents.length === 0) {
487
518
  console.log(renderUnavailableStatusline(opts.statuslineFormat));
488
519
  return;
489
520
  }
490
- // Check jump-back anchor for indicator
521
+ // Check jump-back anchor and resolve active agent for tmux-badges
491
522
  let hasJumpAnchor = false;
492
- if (opts.statuslineFormat === "tmux-badges") {
523
+ let activeAgentPid;
524
+ let activePanePid;
525
+ if (isTmuxBadges) {
493
526
  const { tmpdir: td } = await import("node:os");
494
527
  const { join: pj } = await import("node:path");
495
528
  const { loadJumpAnchor } = await import("./tmux/jump-anchor.js");
496
- const tty = await getClientTty();
529
+ const { getActiveTmuxPanePid } = await import("./tmux/index.js");
530
+ const agentPids = agents.map((a) => a.pid);
531
+ const [tty, panePid] = await Promise.all([getClientTty(), getActiveTmuxPanePid()]);
532
+ activePanePid = panePid;
533
+ activeAgentPid = await findActiveAgentPid(agentPids, activePanePid);
497
534
  if (tty) {
498
535
  hasJumpAnchor = Boolean(await loadJumpAnchor(pj(td(), "marmonitor", "jump-anchors.json"), tty));
499
536
  }
500
537
  }
501
- const rendered = await renderStatusline(agents, opts.statuslineFormat, attentionLimit, width, config.integration.tmux.badgeStyle, hasJumpAnchor);
502
- await writeCachedStatusline(opts.statuslineFormat, attentionLimit, width, rendered);
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);
503
540
  console.log(rendered);
504
541
  return;
505
542
  }
@@ -690,12 +727,119 @@ program
690
727
  return;
691
728
  }
692
729
  const result = evaluateGuard(config, event);
730
+ // Security alert: alerts.enabled 확인 후 dangerous_command / secret_access 감지·기록
731
+ const securityTriggers = config.alerts.enabled
732
+ ? detectGuardTriggers(event).filter((t) => t === "dangerous_command" || t === "secret_access")
733
+ : [];
734
+ if (securityTriggers.length > 0) {
735
+ const { appendAlertLog } = await import("./alerts/index.js");
736
+ const { getConfigDir } = await import("./config/index.js");
737
+ const { join } = await import("node:path");
738
+ const alertsLogPath = join(getConfigDir(), "alerts.log");
739
+ const { sendDesktopNotification } = await import("./alerts/index.js");
740
+ const agentPid = typeof process.ppid === "number" ? process.ppid : 0;
741
+ for (const trigger of securityTriggers) {
742
+ const message = trigger === "secret_access"
743
+ ? `Credential file access: ${event.filePath ?? "(unknown)"}`
744
+ : `Dangerous command detected: ${event.command ?? "(unknown)"}`;
745
+ const alert = {
746
+ id: `security:${agentPid}:${Math.floor(Date.now() / 300_000)}`,
747
+ type: "security",
748
+ severity: "critical",
749
+ agentPid,
750
+ cwd: event.cwd,
751
+ message,
752
+ detail: `tool=${event.toolName ?? "?"} trigger=${trigger}`,
753
+ createdAt: Date.now(),
754
+ };
755
+ if (config.alerts.log)
756
+ await appendAlertLog(alertsLogPath, alert);
757
+ if (config.alerts.desktop)
758
+ void sendDesktopNotification(alert); // fire-and-forget
759
+ }
760
+ }
693
761
  console.log(formatGuardOutput(result));
694
762
  }
695
763
  catch {
696
764
  console.log(JSON.stringify({ decision: "allow" }));
697
765
  }
698
766
  });
767
+ // ── alerts command ──────────────────────────────────────────────────────────
768
+ async function patchAlertsConfig(configPath, patch) {
769
+ await mkdir(dirname(configPath), { recursive: true });
770
+ let current = {};
771
+ try {
772
+ current = JSON.parse(await readFile(configPath, "utf-8"));
773
+ }
774
+ catch {
775
+ // file missing — start fresh
776
+ }
777
+ const alerts = (current.alerts && typeof current.alerts === "object"
778
+ ? { ...current.alerts }
779
+ : {});
780
+ Object.assign(alerts, patch);
781
+ current.alerts = alerts;
782
+ await writeFile(configPath, `${JSON.stringify(current, null, 2)}\n`, "utf-8");
783
+ }
784
+ const alertsCmd = program
785
+ .command("alerts")
786
+ .description("Show or toggle alert settings")
787
+ .option("--config <path>", "Path to settings.json")
788
+ .action(async (opts) => {
789
+ const config = await loadConfig(resolveConfigPath(opts));
790
+ const a = config.alerts;
791
+ console.log(`alerts.enabled : ${a.enabled}`);
792
+ console.log(`alerts.desktop : ${a.desktop}`);
793
+ console.log(`alerts.log : ${a.log}`);
794
+ console.log(`alerts.tokens : ${a.tokens} (token/context threshold alerts)`);
795
+ console.log(`alerts.contextCritThreshold: ${a.contextCritThreshold} (${Math.round(a.contextCritThreshold * 100)}%)`);
796
+ console.log(`alerts.contextWarnThreshold: ${a.contextWarnThreshold === 1.0 ? "disabled" : `${a.contextWarnThreshold} (${Math.round(a.contextWarnThreshold * 100)}%)`}`);
797
+ });
798
+ alertsCmd
799
+ .command("on")
800
+ .description("Enable alert system")
801
+ .option("--config <path>", "Path to settings.json")
802
+ .action(async (opts) => {
803
+ const p = resolveConfigPath(opts) ?? getDefaultConfigPath();
804
+ await patchAlertsConfig(p, { enabled: true });
805
+ console.log("Alerts enabled. Restart daemon to apply: marmonitor restart");
806
+ });
807
+ alertsCmd
808
+ .command("off")
809
+ .description("Disable alert system")
810
+ .option("--config <path>", "Path to settings.json")
811
+ .action(async (opts) => {
812
+ const p = resolveConfigPath(opts) ?? getDefaultConfigPath();
813
+ await patchAlertsConfig(p, { enabled: false });
814
+ console.log("Alerts disabled. Restart daemon to apply: marmonitor restart");
815
+ });
816
+ alertsCmd
817
+ .command("notify <on|off>")
818
+ .description("Toggle desktop notifications")
819
+ .option("--config <path>", "Path to settings.json")
820
+ .action(async (toggle, opts) => {
821
+ if (toggle !== "on" && toggle !== "off") {
822
+ console.error("Usage: marmonitor alerts notify on|off");
823
+ process.exit(1);
824
+ }
825
+ const p = resolveConfigPath(opts) ?? getDefaultConfigPath();
826
+ await patchAlertsConfig(p, { desktop: toggle === "on" });
827
+ console.log(`Desktop notifications ${toggle === "on" ? "enabled" : "disabled"}. Restart daemon to apply: marmonitor restart`);
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
+ });
842
+ // ── end alerts command ───────────────────────────────────────────────────────
699
843
  program
700
844
  .command("debug-phase")
701
845
  .description("Inspect phase signals, stdout heuristic, and tmux capture for one AI session")
@@ -1215,10 +1359,21 @@ program
1215
1359
  console.log(" $ rm -rf ~/.config/marmonitor # settings & session history");
1216
1360
  console.log(" $ rm -rf ~/.tmux/plugins/marmonitor-tmux # tpm plugin");
1217
1361
  });
1362
+ /** Find all running marmonitor daemon PIDs (excludes current CLI process) */
1363
+ async function findRunningDaemonPids() {
1364
+ try {
1365
+ const { default: psList } = await import("ps-list");
1366
+ const procs = await psList();
1367
+ return procs.filter((p) => p.name === "marmonitor" && p.pid !== process.pid).map((p) => p.pid);
1368
+ }
1369
+ catch {
1370
+ return [];
1371
+ }
1372
+ }
1218
1373
  async function startDaemon() {
1219
- if (await isDaemonRunning(DAEMON_PID_PATH)) {
1220
- const pid = await readDaemonPid(DAEMON_PID_PATH);
1221
- console.log(`Daemon already running (PID: ${pid})`);
1374
+ const running = await findRunningDaemonPids();
1375
+ if (running.length > 0) {
1376
+ console.log(`Daemon already running (PID: ${running[0]})`);
1222
1377
  return undefined;
1223
1378
  }
1224
1379
  const { fork } = await import("node:child_process");
@@ -1230,13 +1385,42 @@ async function startDaemon() {
1230
1385
  return child.pid ?? undefined;
1231
1386
  }
1232
1387
  async function stopDaemon() {
1233
- const pid = await readDaemonPid(DAEMON_PID_PATH);
1234
- if (!pid || !(await isDaemonRunning(DAEMON_PID_PATH))) {
1388
+ const pids = await findRunningDaemonPids();
1389
+ if (pids.length === 0) {
1235
1390
  console.log("Daemon is not running.");
1236
1391
  return false;
1237
1392
  }
1238
- process.kill(pid, "SIGTERM");
1239
- console.log(`✓ Daemon stopped (PID: ${pid})`);
1393
+ // Send SIGTERM to all running daemon processes (handles orphans)
1394
+ for (const pid of pids) {
1395
+ try {
1396
+ process.kill(pid, "SIGTERM");
1397
+ }
1398
+ catch { }
1399
+ }
1400
+ // Poll until all processes die (up to 2s)
1401
+ let remaining = [...pids];
1402
+ for (let i = 0; i < 20; i++) {
1403
+ await new Promise((r) => setTimeout(r, 100));
1404
+ remaining = remaining.filter((pid) => {
1405
+ try {
1406
+ process.kill(pid, 0);
1407
+ return true; // still alive
1408
+ }
1409
+ catch {
1410
+ return false; // dead
1411
+ }
1412
+ });
1413
+ if (remaining.length === 0)
1414
+ break;
1415
+ }
1416
+ // Fallback: SIGKILL any survivors
1417
+ for (const pid of remaining) {
1418
+ try {
1419
+ process.kill(pid, "SIGKILL");
1420
+ }
1421
+ catch { }
1422
+ }
1423
+ console.log(`✓ Daemon stopped (PID: ${pids.join(", ")})`);
1240
1424
  return true;
1241
1425
  }
1242
1426
  program
@@ -1258,9 +1442,143 @@ program
1258
1442
  .description("Restart background scan daemon")
1259
1443
  .action(async () => {
1260
1444
  await stopDaemon();
1261
- await new Promise((r) => setTimeout(r, 500));
1262
1445
  await startDaemon();
1263
1446
  process.exit(0);
1264
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
+ });
1265
1583
  installProcessSafetyHandlers();
1266
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
+ }
@@ -86,6 +86,20 @@ export interface MarmonitorConfig {
86
86
  daemonIntervalSec: number;
87
87
  activityRetentionDays: number;
88
88
  };
89
+ alerts: {
90
+ /** 알림 시스템 마스터 토글 */
91
+ enabled: boolean;
92
+ /** macOS/Linux 데스크탑 알림 */
93
+ desktop: boolean;
94
+ /** alerts.log 파일 기록 */
95
+ log: boolean;
96
+ /** 토큰/컨텍스트 임계 알림 카테고리 토글. 보안 알림과 분리 가능. 기본 true */
97
+ tokens: boolean;
98
+ /** 컨텍스트 경고 임계값 (0~1). 0 = 비활성화. 기본 1.0 (비활성) */
99
+ contextWarnThreshold: number;
100
+ /** 컨텍스트 위험 임계값 (0~1). 기본 0.85 */
101
+ contextCritThreshold: number;
102
+ };
89
103
  }
90
104
  /** Get config search paths in priority order */
91
105
  export declare function getConfigSearchPaths(): string[];
@@ -92,6 +92,14 @@ const DEFAULTS = {
92
92
  daemonIntervalSec: 2,
93
93
  activityRetentionDays: 7,
94
94
  },
95
+ alerts: {
96
+ enabled: false,
97
+ desktop: false,
98
+ log: false,
99
+ tokens: true, // 활성 시 토큰/컨텍스트 임계 알림 발사. 보안 알림은 별도 게이트 없음
100
+ contextWarnThreshold: 1.0, // 기본 비활성 (0.70으로 설정 시 활성화)
101
+ contextCritThreshold: 0.85,
102
+ },
95
103
  };
96
104
  function cloneDefaults() {
97
105
  return JSON.parse(JSON.stringify(DEFAULTS));
@@ -1,7 +1,45 @@
1
1
  import { readFile } from "node:fs/promises";
2
- const DANGEROUS_COMMAND_PATTERNS = [/\brm\s+-rf\s+\//, /\bmkfs\b/, /\bdd\s+if=.*\sof=\/dev\//];
3
- const SECRET_PATH_PATTERNS = [/\.env\b/, /\/secrets?\b/, /\/\.ssh\b/, /id_rsa\b/];
4
- const PROD_PATH_PATTERNS = [/\/prod\b/, /\/production\b/, /prod/i];
2
+ // 시스템 경로 판단 기준: /, /*, /etc, /usr, /var, /home, /root, /bin, /sbin, /sys, /proc, /dev, /boot, /lib, ~
3
+ const SYSTEM_PATH = String.raw `(?:\/(?:$|\*|etc(?:\/|$)|usr(?:\/|$)|var(?:\/|$)|home(?:\/|$)|root(?:\/|$)|bin(?:\/|$)|sbin(?:\/|$)|sys(?:\/|$)|proc(?:\/|$)|dev(?:\/|$)|boot(?:\/|$)|lib(?:\/|$))|~(?:\/|$))`;
4
+ const DANGEROUS_COMMAND_PATTERNS = [
5
+ // ── destructive delete: 시스템 경로 대상 + 재귀/강제 옵션 조합 ──
6
+ // 단축 옵션: rm -rf /, rm -fr /etc, rm -Rrf ~ (-[옵션]에 r과 f 둘 다 포함)
7
+ new RegExp(String.raw `\brm\b(?=.*\s-[^\s-]*[rf][^\s-]*[rf])(?=.*\s${SYSTEM_PATH})`, "i"),
8
+ // 롱 옵션: rm --recursive --force /var (순서 무관)
9
+ new RegExp(String.raw `\brm\b(?=.*--recursive\b)(?=.*--force\b)(?=.*\s${SYSTEM_PATH})`, "i"),
10
+ // ── filesystem format ──
11
+ /\bmkfs(?:\.[a-z0-9]+)?\b/i,
12
+ // ── raw disk write (sudo 유무 무관) ──
13
+ /\bdd\b.*\bof=\/dev\/(?:sd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|vd[a-z]\d*|zero|null)\b/i,
14
+ /\bsudo\s+dd\b/i,
15
+ // ── 시스템 경로 대상 권한/소유권 대규모 변경 ──
16
+ new RegExp(String.raw `\bchmod\b.*\s-[^\s]*R[^\s]*(?=.*\s${SYSTEM_PATH})`, "i"),
17
+ new RegExp(String.raw `\bchown\b.*\s-[^\s]*R[^\s]*(?=.*\s${SYSTEM_PATH})`, "i"),
18
+ // ── git force push ──
19
+ /\bgit\s+push\b.*(?:--force\b|-f\b)/i,
20
+ // ── 원격 스크립트 직접 실행 ──
21
+ /\bcurl\b.+\|\s*(?:bash|sh)\b/i,
22
+ /\bwget\b.+\|\s*(?:bash|sh)\b/i,
23
+ /\b(?:bash|sh)\b\s*<\(\s*curl\b/i, // bash <(curl ...)
24
+ /\bsudo\s+(?:bash|sh)\b.*-c\b.*(?:curl|wget)\b.*\|\s*(?:bash|sh)\b/i, // sudo sh -c '... | bash'
25
+ // ── critical process kill ──
26
+ /\bkill\s+-9\s+1\b/i,
27
+ /\bpkill\s+-9\s+(?:init|systemd)\b/i,
28
+ ];
29
+ // secret_access: 정확한 자격증명 파일 경로에만 반응 (content 키워드 false positive 방지)
30
+ // Write/Edit 툴일 때만 체크 → Read는 별도 함수에서 처리
31
+ const SECRET_WRITE_TOOLS = new Set(["Write", "Edit", "str_replace_editor"]);
32
+ const SECRET_EXACT_SUFFIXES = [
33
+ /(?:^|\/)\.env$/, // .env (not .env.example, .env.local)
34
+ /(?:^|\/)id_rsa$/, // SSH private key
35
+ /(?:^|\/)id_ed25519$/, // ED25519 private key
36
+ /(?:^|\/)id_ecdsa$/, // ECDSA private key
37
+ /(?:^|\/)\.netrc$/, // netrc credential file
38
+ /(?:^|\/)credentials$/, // AWS credentials etc
39
+ ];
40
+ // Read 툴에서 실제 private key 파일 경로를 읽는 경우
41
+ const SECRET_READ_TOOLS = new Set(["Read", "cat"]);
42
+ const PROD_PATH_PATTERNS = [/\/prod\b/, /\/production\b/];
5
43
  function normalizeAction(action) {
6
44
  if (action === "block")
7
45
  return "block";
@@ -37,19 +75,27 @@ export function parseHookEvent(input) {
37
75
  return undefined;
38
76
  }
39
77
  }
78
+ function isSecretFilePath(filePath) {
79
+ return SECRET_EXACT_SUFFIXES.some((pattern) => pattern.test(filePath));
80
+ }
40
81
  export function detectGuardTriggers(event) {
41
82
  const triggers = new Set();
42
83
  const command = event.command ?? "";
43
84
  const filePath = event.filePath ?? "";
44
85
  const cwd = event.cwd ?? "";
86
+ const toolName = event.toolName ?? "";
45
87
  if (DANGEROUS_COMMAND_PATTERNS.some((pattern) => pattern.test(command))) {
46
88
  triggers.add("dangerous_command");
47
89
  }
48
90
  if (PROD_PATH_PATTERNS.some((pattern) => pattern.test(command) || pattern.test(filePath))) {
49
91
  triggers.add("prod_path_access");
50
92
  }
51
- if (SECRET_PATH_PATTERNS.some((pattern) => pattern.test(command) || pattern.test(filePath))) {
52
- triggers.add("secret_access");
93
+ // secret_access: Write/Edit 툴 + 정확한 자격증명 파일 경로
94
+ // Read 툴 + 정확한 private key 파일 경로
95
+ if (filePath && isSecretFilePath(filePath)) {
96
+ if (SECRET_WRITE_TOOLS.has(toolName) || SECRET_READ_TOOLS.has(toolName)) {
97
+ triggers.add("secret_access");
98
+ }
53
99
  }
54
100
  if (filePath && cwd && !filePath.startsWith(cwd)) {
55
101
  triggers.add("out_of_cwd_write");
@@ -8,6 +8,8 @@
8
8
  export interface BadgeTheme {
9
9
  badge: string;
10
10
  attention: string;
11
+ /** Attention segment for the currently active tmux window */
12
+ attentionActive: string;
11
13
  focus: string;
12
14
  empty: string;
13
15
  jumpBack: string;
@@ -15,5 +17,6 @@ export interface BadgeTheme {
15
17
  export declare const BADGE_THEMES: Record<string, BadgeTheme>;
16
18
  export declare function renderBadge(theme: BadgeTheme, label: string, fg: string, bg: string): string;
17
19
  export declare function renderAttention(theme: BadgeTheme, index: number, label: string, bg: string): string;
20
+ export declare function renderAttentionActive(theme: BadgeTheme, index: number, label: string, bg: string): string;
18
21
  export declare function renderFocus(theme: BadgeTheme, text: string): string;
19
22
  export declare function resolveTheme(style: string): BadgeTheme;