marmonitor 0.2.3 → 0.2.5

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/dist/cli.js CHANGED
@@ -4,18 +4,18 @@ import { dirname, join } from "node:path";
4
4
  import { Command } from "commander";
5
5
  import { renderInstallBanner, renderRuntimeBanner } from "./banner/index.js";
6
6
  import { getConfigDir, getConfigSearchPaths, getDefaultConfigPath, loadConfig, resolveConfigPath as resolveLoadedConfigPath, } from "./config/index.js";
7
- import { evaluateGuard, formatGuardOutput, parseHookEvent, readStdin } from "./guard/index.js";
7
+ import { detectGuardTriggers, evaluateGuard, formatGuardOutput, parseHookEvent, readStdin, } from "./guard/index.js";
8
8
  import { applyTerminalStyle, printAttention, printAttentionJson, printCleanJson, printCleanPlan, printDock, printJumpJson, printJumpResult, printStatus, printStatusJson, renderJumpAttentionChooser, renderStatusline, renderUnavailableStatusline, } from "./output/index.js";
9
9
  import { buildJumpAttentionItems, parseSelectionInput, selectJumpAttentionItem, selectJumpAttentionItemOnPage, selectUnmatchedTargets, } from "./output/utils.js";
10
10
  import { TERMINAL_RESTORE_SEQUENCE, formatProcessFailure } from "./process-safety.js";
11
11
  import { detectClaudePhase } from "./scanner/claude.js";
12
12
  import { detectCodexPhase, indexCodexSessions, matchCodexSession } from "./scanner/codex.js";
13
- import { isDaemonRunning, readDaemonPid, readDaemonSnapshot } from "./scanner/daemon-utils.js";
13
+ import { readDaemonSnapshot } from "./scanner/daemon-utils.js";
14
14
  import { parseGeminiSession } from "./scanner/gemini.js";
15
15
  import { scanAgents } from "./scanner/index.js";
16
16
  import { loadRegistryFromFile } from "./scanner/session-registry.js";
17
17
  import { detectCliStdoutPhase } from "./scanner/status.js";
18
- import { captureTmuxPaneOutput, jumpToAgent, resolveTmuxJumpTarget } from "./tmux/index.js";
18
+ import { captureTmuxPaneOutput, findActiveAgentPid, jumpToAgent, resolveTmuxJumpTarget, } from "./tmux/index.js";
19
19
  import { getClientTty, jumpBack } from "./tmux/jump-anchor.js";
20
20
  import { findClickedAgent, parseStatusClickToken } from "./tmux/status-click.js";
21
21
  import { VERSION } from "./version.js";
@@ -415,23 +415,36 @@ function statuslineCacheFile(format, attentionLimit, width) {
415
415
  const widthKey = width && width > 0 ? String(width) : "auto";
416
416
  return join(tmpdir(), "marmonitor", `statusline-${format}-${attentionLimit}-${widthKey}.txt`);
417
417
  }
418
+ /** Read cached statusline. When activePanePid is provided, the cache is
419
+ * only valid if the stored panePid (first line) matches — otherwise the
420
+ * active-window highlight would be stale. Returns {content, panePid}. */
418
421
  async function readCachedStatusline(format, attentionLimit, width, ttlMs) {
419
422
  const path = statuslineCacheFile(format, attentionLimit, width);
420
423
  try {
421
424
  const fileStat = await stat(path);
422
425
  if (Date.now() - fileStat.mtimeMs > ttlMs)
423
426
  return undefined;
424
- return (await readFile(path, "utf-8")).trimEnd();
427
+ const raw = (await readFile(path, "utf-8")).trimEnd();
428
+ const newline = raw.indexOf("\n");
429
+ if (newline === -1)
430
+ return { content: raw, panePid: undefined };
431
+ const firstLine = raw.slice(0, newline);
432
+ const pid = Number.parseInt(firstLine, 10);
433
+ if (Number.isFinite(pid)) {
434
+ return { content: raw.slice(newline + 1), panePid: pid };
435
+ }
436
+ return { content: raw, panePid: undefined };
425
437
  }
426
438
  catch {
427
439
  return undefined;
428
440
  }
429
441
  }
430
- async function writeCachedStatusline(format, attentionLimit, width, value) {
442
+ async function writeCachedStatusline(format, attentionLimit, width, value, activePanePid) {
431
443
  const path = statuslineCacheFile(format, attentionLimit, width);
444
+ const data = activePanePid ? `${activePanePid}\n${value}` : value;
432
445
  try {
433
446
  await mkdir(join(tmpdir(), "marmonitor"), { recursive: true });
434
- await writeFile(path, value, "utf-8");
447
+ await writeFile(path, data, "utf-8");
435
448
  }
436
449
  catch {
437
450
  // cache failures must never break statusline rendering
@@ -477,29 +490,52 @@ program
477
490
  }
478
491
  const attentionLimit = config.display.statuslineAttentionLimit;
479
492
  const width = resolveStatuslineWidth(opts.width);
493
+ const isTmuxBadges = opts.statuslineFormat === "tmux-badges";
494
+ // Try cache first. For tmux-badges the cached panePid is checked
495
+ // against the live pane only on cache hit — the tmux call is
496
+ // deferred so cache-miss paths pay for it just once.
480
497
  const cached = await readCachedStatusline(opts.statuslineFormat, attentionLimit, width, config.performance.statuslineTtlMs);
481
498
  if (cached) {
482
- console.log(cached);
483
- return;
499
+ if (isTmuxBadges && cached.panePid !== undefined) {
500
+ const { getActiveTmuxPanePid } = await import("./tmux/index.js");
501
+ const currentPanePid = await getActiveTmuxPanePid();
502
+ if (currentPanePid !== cached.panePid) {
503
+ // Active pane changed — fall through to re-render
504
+ }
505
+ else {
506
+ console.log(cached.content);
507
+ return;
508
+ }
509
+ }
510
+ else {
511
+ console.log(cached.content);
512
+ return;
513
+ }
484
514
  }
485
515
  const agents = await getAgentsSnapshot();
486
516
  if (agents.length === 0) {
487
517
  console.log(renderUnavailableStatusline(opts.statuslineFormat));
488
518
  return;
489
519
  }
490
- // Check jump-back anchor for indicator
520
+ // Check jump-back anchor and resolve active agent for tmux-badges
491
521
  let hasJumpAnchor = false;
492
- if (opts.statuslineFormat === "tmux-badges") {
522
+ let activeAgentPid;
523
+ let activePanePid;
524
+ if (isTmuxBadges) {
493
525
  const { tmpdir: td } = await import("node:os");
494
526
  const { join: pj } = await import("node:path");
495
527
  const { loadJumpAnchor } = await import("./tmux/jump-anchor.js");
496
- const tty = await getClientTty();
528
+ const { getActiveTmuxPanePid } = await import("./tmux/index.js");
529
+ const agentPids = agents.map((a) => a.pid);
530
+ const [tty, panePid] = await Promise.all([getClientTty(), getActiveTmuxPanePid()]);
531
+ activePanePid = panePid;
532
+ activeAgentPid = await findActiveAgentPid(agentPids, activePanePid);
497
533
  if (tty) {
498
534
  hasJumpAnchor = Boolean(await loadJumpAnchor(pj(td(), "marmonitor", "jump-anchors.json"), tty));
499
535
  }
500
536
  }
501
- const rendered = await renderStatusline(agents, opts.statuslineFormat, attentionLimit, width, config.integration.tmux.badgeStyle, hasJumpAnchor);
502
- await writeCachedStatusline(opts.statuslineFormat, attentionLimit, width, rendered);
537
+ const rendered = await renderStatusline(agents, opts.statuslineFormat, attentionLimit, width, config.integration.tmux.badgeStyle, hasJumpAnchor, activeAgentPid);
538
+ await writeCachedStatusline(opts.statuslineFormat, attentionLimit, width, rendered, activePanePid);
503
539
  console.log(rendered);
504
540
  return;
505
541
  }
@@ -542,9 +578,11 @@ program
542
578
  });
543
579
  program
544
580
  .command("attention")
545
- .description("Show prioritized sessions that need attention")
581
+ .description("Show prioritized sessions that need attention, optionally jump to one")
546
582
  .option("--json", "Output as JSON")
547
583
  .option("--interactive", "Choose an attention item and jump to its tmux pane")
584
+ .option("--pid <pid>", "Jump to AI session by PID")
585
+ .option("--attention-index <n>", "Jump to Nth attention item directly")
548
586
  .option("--limit <n>", "Max items to show", "12")
549
587
  .option("--config <path>", "Path to settings.json")
550
588
  .action(async (opts) => {
@@ -553,11 +591,78 @@ program
553
591
  applyTerminalStyle(config.integration.tmux.badgeStyle);
554
592
  const limit = resolveAttentionLimit(opts, config.display.attentionLimit);
555
593
  const interactiveLimit = resolveAttentionLimit(opts, config.display.attentionLimit, true);
556
- if (opts.interactive && opts.json) {
557
- console.error("--interactive cannot be combined with --json.");
558
- process.exit(1);
594
+ const useDirectPid = typeof opts.pid === "string";
595
+ const useDirectIndex = typeof opts.attentionIndex === "string";
596
+ const useInteractive = Boolean(opts.interactive);
597
+ // Direct jump by PID
598
+ if (useDirectPid) {
599
+ const pid = Number.parseInt(opts.pid, 10);
600
+ if (Number.isNaN(pid)) {
601
+ console.error(`Invalid pid: ${opts.pid}`);
602
+ process.exit(1);
603
+ }
604
+ const agent = agents.find((a) => a.pid === pid);
605
+ if (!agent) {
606
+ const result = {
607
+ found: false,
608
+ executed: false,
609
+ insideTmux: Boolean(process.env.TMUX),
610
+ pid,
611
+ message: `AI session not found for pid ${pid}.`,
612
+ };
613
+ if (opts.json) {
614
+ printJumpJson(result);
615
+ }
616
+ else {
617
+ printJumpResult(result);
618
+ }
619
+ process.exit(1);
620
+ }
621
+ const result = await jumpToAgent(agent);
622
+ if (opts.json) {
623
+ printJumpJson(result);
624
+ }
625
+ else {
626
+ printJumpResult(result);
627
+ }
628
+ if (!result.found)
629
+ process.exit(1);
630
+ return;
559
631
  }
560
- if (opts.interactive) {
632
+ // Direct jump by attention index
633
+ if (useDirectIndex) {
634
+ const selection = Number.parseInt(opts.attentionIndex, 10);
635
+ if (Number.isNaN(selection) || selection < 1) {
636
+ console.error(`Invalid attention index: ${opts.attentionIndex}`);
637
+ process.exit(1);
638
+ }
639
+ const item = selectJumpAttentionItem(agents, selection);
640
+ if (!item) {
641
+ console.error(`No jumpable attention item at index ${selection}.`);
642
+ process.exit(1);
643
+ }
644
+ const agent = agents.find((a) => a.pid === item.pid);
645
+ if (!agent) {
646
+ console.error(`AI session not found for pid ${item.pid}.`);
647
+ process.exit(1);
648
+ }
649
+ const result = await jumpToAgent(agent);
650
+ if (opts.json) {
651
+ printJumpJson(result);
652
+ }
653
+ else {
654
+ printJumpResult(result);
655
+ }
656
+ if (!result.found)
657
+ process.exit(1);
658
+ return;
659
+ }
660
+ // Interactive chooser
661
+ if (useInteractive) {
662
+ if (opts.json) {
663
+ console.error("--interactive cannot be combined with --json.");
664
+ process.exit(1);
665
+ }
561
666
  if (!process.stdin.isTTY) {
562
667
  console.error("--interactive requires an interactive terminal.");
563
668
  process.exit(1);
@@ -599,6 +704,7 @@ program
599
704
  process.exit(1);
600
705
  return;
601
706
  }
707
+ // Default: list mode
602
708
  if (opts.json) {
603
709
  printAttentionJson(agents, limit);
604
710
  }
@@ -620,12 +726,105 @@ program
620
726
  return;
621
727
  }
622
728
  const result = evaluateGuard(config, event);
729
+ // Security alert: alerts.enabled 확인 후 dangerous_command / secret_access 감지·기록
730
+ const securityTriggers = config.alerts.enabled
731
+ ? detectGuardTriggers(event).filter((t) => t === "dangerous_command" || t === "secret_access")
732
+ : [];
733
+ if (securityTriggers.length > 0) {
734
+ const { appendAlertLog } = await import("./alerts/index.js");
735
+ const { getConfigDir } = await import("./config/index.js");
736
+ const { join } = await import("node:path");
737
+ const alertsLogPath = join(getConfigDir(), "alerts.log");
738
+ const { sendDesktopNotification } = await import("./alerts/index.js");
739
+ const agentPid = typeof process.ppid === "number" ? process.ppid : 0;
740
+ for (const trigger of securityTriggers) {
741
+ const message = trigger === "secret_access"
742
+ ? `Credential file access: ${event.filePath ?? "(unknown)"}`
743
+ : `Dangerous command detected: ${event.command ?? "(unknown)"}`;
744
+ const alert = {
745
+ id: `security:${agentPid}:${Math.floor(Date.now() / 300_000)}`,
746
+ type: "security",
747
+ severity: "critical",
748
+ agentPid,
749
+ cwd: event.cwd,
750
+ message,
751
+ detail: `tool=${event.toolName ?? "?"} trigger=${trigger}`,
752
+ createdAt: Date.now(),
753
+ };
754
+ if (config.alerts.log)
755
+ await appendAlertLog(alertsLogPath, alert);
756
+ if (config.alerts.desktop)
757
+ void sendDesktopNotification(alert); // fire-and-forget
758
+ }
759
+ }
623
760
  console.log(formatGuardOutput(result));
624
761
  }
625
762
  catch {
626
763
  console.log(JSON.stringify({ decision: "allow" }));
627
764
  }
628
765
  });
766
+ // ── alerts command ──────────────────────────────────────────────────────────
767
+ async function patchAlertsConfig(configPath, patch) {
768
+ await mkdir(dirname(configPath), { recursive: true });
769
+ let current = {};
770
+ try {
771
+ current = JSON.parse(await readFile(configPath, "utf-8"));
772
+ }
773
+ catch {
774
+ // file missing — start fresh
775
+ }
776
+ const alerts = (current.alerts && typeof current.alerts === "object"
777
+ ? { ...current.alerts }
778
+ : {});
779
+ Object.assign(alerts, patch);
780
+ current.alerts = alerts;
781
+ await writeFile(configPath, `${JSON.stringify(current, null, 2)}\n`, "utf-8");
782
+ }
783
+ const alertsCmd = program
784
+ .command("alerts")
785
+ .description("Show or toggle alert settings")
786
+ .option("--config <path>", "Path to settings.json")
787
+ .action(async (opts) => {
788
+ const config = await loadConfig(resolveConfigPath(opts));
789
+ const a = config.alerts;
790
+ console.log(`alerts.enabled : ${a.enabled}`);
791
+ console.log(`alerts.desktop : ${a.desktop}`);
792
+ console.log(`alerts.log : ${a.log}`);
793
+ console.log(`alerts.contextCritThreshold: ${a.contextCritThreshold} (${Math.round(a.contextCritThreshold * 100)}%)`);
794
+ console.log(`alerts.contextWarnThreshold: ${a.contextWarnThreshold === 1.0 ? "disabled" : `${a.contextWarnThreshold} (${Math.round(a.contextWarnThreshold * 100)}%)`}`);
795
+ });
796
+ alertsCmd
797
+ .command("on")
798
+ .description("Enable alert system")
799
+ .option("--config <path>", "Path to settings.json")
800
+ .action(async (opts) => {
801
+ const p = resolveConfigPath(opts) ?? getDefaultConfigPath();
802
+ await patchAlertsConfig(p, { enabled: true });
803
+ console.log("Alerts enabled. Restart daemon to apply: marmonitor restart");
804
+ });
805
+ alertsCmd
806
+ .command("off")
807
+ .description("Disable alert system")
808
+ .option("--config <path>", "Path to settings.json")
809
+ .action(async (opts) => {
810
+ const p = resolveConfigPath(opts) ?? getDefaultConfigPath();
811
+ await patchAlertsConfig(p, { enabled: false });
812
+ console.log("Alerts disabled. Restart daemon to apply: marmonitor restart");
813
+ });
814
+ alertsCmd
815
+ .command("notify <on|off>")
816
+ .description("Toggle desktop notifications")
817
+ .option("--config <path>", "Path to settings.json")
818
+ .action(async (toggle, opts) => {
819
+ if (toggle !== "on" && toggle !== "off") {
820
+ console.error("Usage: marmonitor alerts notify on|off");
821
+ process.exit(1);
822
+ }
823
+ const p = resolveConfigPath(opts) ?? getDefaultConfigPath();
824
+ await patchAlertsConfig(p, { desktop: toggle === "on" });
825
+ console.log(`Desktop notifications ${toggle === "on" ? "enabled" : "disabled"}. Restart daemon to apply: marmonitor restart`);
826
+ });
827
+ // ── end alerts command ───────────────────────────────────────────────────────
629
828
  program
630
829
  .command("debug-phase")
631
830
  .description("Inspect phase signals, stdout heuristic, and tmux capture for one AI session")
@@ -770,106 +969,30 @@ program
770
969
  console.log("Pane capture:");
771
970
  console.log(payload.paneOutput ?? "(none)");
772
971
  });
972
+ // "jump" is kept as an alias for backward compatibility (Option+N bindings, scripts).
973
+ // --attention maps to attention --interactive, --attention-index and --pid pass through.
773
974
  program
774
975
  .command("jump")
775
- .description("Jump to the tmux pane running a specific AI session")
776
- .option("--pid <pid>", "AI process PID")
976
+ .description("Alias for 'attention' — jump to an AI session's tmux pane")
977
+ .option("--pid <pid>", "Jump to AI session by PID")
777
978
  .option("--attention", "Choose from attention items interactively")
778
- .option("--attention-index <n>", "Jump to Nth jumpable attention item")
979
+ .option("--attention-index <n>", "Jump to Nth attention item directly")
779
980
  .option("--json", "Output as JSON")
780
981
  .option("--config <path>", "Path to settings.json")
781
982
  .action(async (opts) => {
782
- const agents = await requireDaemonSnapshot();
783
- const config = await loadConfig(resolveConfigPath(opts));
784
- const useAttention = Boolean(opts.attention);
785
- const useAttentionIndex = typeof opts.attentionIndex === "string";
786
- const usePid = typeof opts.pid === "string";
787
- const selectedModes = [useAttention, useAttentionIndex, usePid].filter(Boolean).length;
788
- if (selectedModes !== 1) {
789
- console.error("Use exactly one of --pid <pid>, --attention, or --attention-index <n>.");
790
- process.exit(1);
791
- }
792
- let pid;
793
- if (useAttention) {
794
- if (!process.stdin.isTTY) {
795
- console.error("--attention requires an interactive terminal.");
796
- process.exit(1);
797
- }
798
- const limit = resolveAttentionLimit({ limit: undefined }, config.display.attentionLimit, true);
799
- const totalItems = buildJumpAttentionItems(agents).length;
800
- const totalPages = Math.max(1, Math.ceil(totalItems / limit));
801
- let currentPage = 1;
802
- let item;
803
- while (true) {
804
- clearScreen();
805
- console.log(renderJumpAttentionChooser(agents, currentPage, limit));
806
- const pageItemCount = Math.min(limit, Math.max(totalItems - (currentPage - 1) * limit, 0));
807
- const action = await promptSelectionAction(pageItemCount, currentPage, totalPages);
808
- if (!action || action.kind === "cancel")
809
- return;
810
- if (action.kind === "next") {
811
- currentPage = Math.min(currentPage + 1, totalPages);
812
- continue;
813
- }
814
- if (action.kind === "prev") {
815
- currentPage = Math.max(currentPage - 1, 1);
816
- continue;
817
- }
818
- item = selectJumpAttentionItemOnPage(agents, currentPage, action.selection, limit);
819
- break;
820
- }
821
- if (!item) {
822
- console.error("Invalid selection.");
823
- process.exit(1);
824
- }
825
- pid = item.pid;
826
- }
827
- else if (useAttentionIndex) {
828
- const selection = Number.parseInt(opts.attentionIndex, 10);
829
- if (Number.isNaN(selection) || selection < 1) {
830
- console.error(`Invalid attention index: ${opts.attentionIndex}`);
831
- process.exit(1);
832
- }
833
- const item = selectJumpAttentionItem(agents, selection);
834
- if (!item) {
835
- console.error(`No jumpable attention item at index ${selection}.`);
836
- process.exit(1);
837
- }
838
- pid = item.pid;
839
- }
840
- else {
841
- pid = Number.parseInt(opts.pid, 10);
842
- if (Number.isNaN(pid)) {
843
- console.error(`Invalid pid: ${opts.pid}`);
844
- process.exit(1);
845
- }
846
- }
847
- const agent = agents.find((item) => item.pid === pid);
848
- if (!agent) {
849
- const result = {
850
- found: false,
851
- executed: false,
852
- insideTmux: Boolean(process.env.TMUX),
853
- pid,
854
- message: `AI session not found for pid ${pid}.`,
855
- };
856
- if (opts.json) {
857
- printJumpJson(result);
858
- }
859
- else {
860
- printJumpResult(result);
861
- }
862
- process.exit(1);
863
- }
864
- const result = await jumpToAgent(agent);
865
- if (opts.json) {
866
- printJumpJson(result);
867
- }
868
- else {
869
- printJumpResult(result);
870
- }
871
- if (!result.found)
872
- process.exit(1);
983
+ // Translate jump flags to attention flags and re-parse
984
+ const args = ["attention"];
985
+ if (opts.attention)
986
+ args.push("--interactive");
987
+ if (opts.attentionIndex)
988
+ args.push("--attention-index", opts.attentionIndex);
989
+ if (opts.pid)
990
+ args.push("--pid", opts.pid);
991
+ if (opts.json)
992
+ args.push("--json");
993
+ if (opts.config)
994
+ args.push("--config", opts.config);
995
+ await program.parseAsync(args, { from: "user" });
873
996
  });
874
997
  program
875
998
  .command("jump-back")
@@ -973,6 +1096,8 @@ program
973
1096
  .option("--pid <pid>", "Filter by AI process PID")
974
1097
  .option("--session <sid>", "Filter by session ID (prefix match)")
975
1098
  .option("--days <n>", "Number of days to show", "1")
1099
+ .option("--lines <n>", "Max activity lines per session (default 30, max 200)", "30")
1100
+ .option("--order <dir>", "Sort order: desc (newest first) or asc (oldest first)", "desc")
976
1101
  .option("--json", "Output as JSON")
977
1102
  .action(async (opts) => {
978
1103
  const { getConfigDir } = await import("./config/index.js");
@@ -980,6 +1105,8 @@ program
980
1105
  const { getRecentDateKeys, readActivityLog } = await import("./scanner/activity-log.js");
981
1106
  const logDir = pj(getConfigDir(), "activity-log");
982
1107
  const days = Math.max(1, Math.min(90, Number(opts.days) || 1));
1108
+ const maxLines = Math.max(1, Math.min(200, Number(opts.lines) || 30));
1109
+ const descOrder = opts.order !== "asc";
983
1110
  const allEntries = [];
984
1111
  for (const dateStr of getRecentDateKeys(days)) {
985
1112
  const entries = await readActivityLog(logDir, dateStr);
@@ -987,14 +1114,24 @@ program
987
1114
  }
988
1115
  // Filter
989
1116
  let filtered = allEntries;
1117
+ let pidFilterAgent;
990
1118
  if (opts.pid) {
991
1119
  const agents = await getAgentsSnapshot();
992
1120
  const agent = agents.find((a) => a.pid === Number(opts.pid));
993
1121
  if (agent?.sessionId) {
1122
+ pidFilterAgent = {
1123
+ agentName: agent.agentName,
1124
+ pid: agent.pid,
1125
+ cwd: agent.cwd,
1126
+ sessionId: agent.sessionId,
1127
+ };
994
1128
  const sidPrefix = agent.sessionId.slice(0, 12);
995
1129
  filtered = filtered.filter((e) => e.sid.startsWith(sidPrefix));
996
1130
  }
997
1131
  else {
1132
+ pidFilterAgent = agent
1133
+ ? { agentName: agent.agentName, pid: agent.pid, cwd: agent.cwd, sessionId: "" }
1134
+ : undefined;
998
1135
  filtered = [];
999
1136
  }
1000
1137
  }
@@ -1003,11 +1140,27 @@ program
1003
1140
  filtered = filtered.filter((e) => e.sid.startsWith(prefix));
1004
1141
  }
1005
1142
  if (opts.json) {
1143
+ if (descOrder)
1144
+ filtered.reverse();
1006
1145
  console.log(JSON.stringify(filtered, null, 2));
1007
1146
  return;
1008
1147
  }
1009
1148
  if (filtered.length === 0) {
1010
- console.log("No activity found.");
1149
+ if (pidFilterAgent) {
1150
+ console.log(`No activity found for PID ${pidFilterAgent.pid}.`);
1151
+ console.log(` Agent: ${pidFilterAgent.agentName}`);
1152
+ console.log(` CWD: ${pidFilterAgent.cwd}`);
1153
+ if (pidFilterAgent.sessionId) {
1154
+ console.log(` SID: ${pidFilterAgent.sessionId.slice(0, 12)}...`);
1155
+ }
1156
+ else {
1157
+ console.log(" SID: (no session matched — activity logging may not have started)");
1158
+ }
1159
+ console.log(`\n Activity log checked: last ${days} day(s) in ${logDir}`);
1160
+ }
1161
+ else {
1162
+ console.log("No activity found.");
1163
+ }
1011
1164
  return;
1012
1165
  }
1013
1166
  // Group by session
@@ -1025,15 +1178,17 @@ program
1025
1178
  console.log(`\n${agent} ${sid}... ${cwd}`);
1026
1179
  console.log(` ${entries.length} actions out:${formatTokensShort(totalOut)} cache:${formatTokensShort(totalCache)}`);
1027
1180
  console.log(" ─────────────────────────────────────");
1028
- for (const e of entries.slice(-20)) {
1181
+ const sorted = descOrder ? [...entries].reverse() : entries;
1182
+ const shown = sorted.slice(0, maxLines);
1183
+ for (const e of shown) {
1029
1184
  const t = new Date(e.ts * 1000).toLocaleTimeString("en-GB", {
1030
1185
  hour: "2-digit",
1031
1186
  minute: "2-digit",
1032
1187
  });
1033
1188
  console.log(` ${t} ${e.tool}: ${truncateForDisplay(e.target, 60)}`);
1034
1189
  }
1035
- if (entries.length > 20) {
1036
- console.log(` ... +${entries.length - 20} more`);
1190
+ if (entries.length > maxLines) {
1191
+ console.log(` ... +${entries.length - maxLines} more (use --lines to show more)`);
1037
1192
  }
1038
1193
  }
1039
1194
  });
@@ -1189,10 +1344,21 @@ program
1189
1344
  console.log(" $ rm -rf ~/.config/marmonitor # settings & session history");
1190
1345
  console.log(" $ rm -rf ~/.tmux/plugins/marmonitor-tmux # tpm plugin");
1191
1346
  });
1347
+ /** Find all running marmonitor daemon PIDs (excludes current CLI process) */
1348
+ async function findRunningDaemonPids() {
1349
+ try {
1350
+ const { default: psList } = await import("ps-list");
1351
+ const procs = await psList();
1352
+ return procs.filter((p) => p.name === "marmonitor" && p.pid !== process.pid).map((p) => p.pid);
1353
+ }
1354
+ catch {
1355
+ return [];
1356
+ }
1357
+ }
1192
1358
  async function startDaemon() {
1193
- if (await isDaemonRunning(DAEMON_PID_PATH)) {
1194
- const pid = await readDaemonPid(DAEMON_PID_PATH);
1195
- console.log(`Daemon already running (PID: ${pid})`);
1359
+ const running = await findRunningDaemonPids();
1360
+ if (running.length > 0) {
1361
+ console.log(`Daemon already running (PID: ${running[0]})`);
1196
1362
  return undefined;
1197
1363
  }
1198
1364
  const { fork } = await import("node:child_process");
@@ -1204,13 +1370,42 @@ async function startDaemon() {
1204
1370
  return child.pid ?? undefined;
1205
1371
  }
1206
1372
  async function stopDaemon() {
1207
- const pid = await readDaemonPid(DAEMON_PID_PATH);
1208
- if (!pid || !(await isDaemonRunning(DAEMON_PID_PATH))) {
1373
+ const pids = await findRunningDaemonPids();
1374
+ if (pids.length === 0) {
1209
1375
  console.log("Daemon is not running.");
1210
1376
  return false;
1211
1377
  }
1212
- process.kill(pid, "SIGTERM");
1213
- console.log(`✓ Daemon stopped (PID: ${pid})`);
1378
+ // Send SIGTERM to all running daemon processes (handles orphans)
1379
+ for (const pid of pids) {
1380
+ try {
1381
+ process.kill(pid, "SIGTERM");
1382
+ }
1383
+ catch { }
1384
+ }
1385
+ // Poll until all processes die (up to 2s)
1386
+ let remaining = [...pids];
1387
+ for (let i = 0; i < 20; i++) {
1388
+ await new Promise((r) => setTimeout(r, 100));
1389
+ remaining = remaining.filter((pid) => {
1390
+ try {
1391
+ process.kill(pid, 0);
1392
+ return true; // still alive
1393
+ }
1394
+ catch {
1395
+ return false; // dead
1396
+ }
1397
+ });
1398
+ if (remaining.length === 0)
1399
+ break;
1400
+ }
1401
+ // Fallback: SIGKILL any survivors
1402
+ for (const pid of remaining) {
1403
+ try {
1404
+ process.kill(pid, "SIGKILL");
1405
+ }
1406
+ catch { }
1407
+ }
1408
+ console.log(`✓ Daemon stopped (PID: ${pids.join(", ")})`);
1214
1409
  return true;
1215
1410
  }
1216
1411
  program
@@ -1232,7 +1427,6 @@ program
1232
1427
  .description("Restart background scan daemon")
1233
1428
  .action(async () => {
1234
1429
  await stopDaemon();
1235
- await new Promise((r) => setTimeout(r, 500));
1236
1430
  await startDaemon();
1237
1431
  process.exit(0);
1238
1432
  });
@@ -62,7 +62,7 @@ export interface MarmonitorConfig {
62
62
  dockToggle: string;
63
63
  directJump: string[];
64
64
  };
65
- badgeStyle: "basic" | "basic-mono" | "text" | "text-mono";
65
+ badgeStyle: "basic" | "basic-mono" | "block" | "block-mono" | "text" | "text-mono";
66
66
  };
67
67
  wezterm: {
68
68
  enabled: boolean;
@@ -86,6 +86,18 @@ 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
+ /** 컨텍스트 경고 임계값 (0~1). 0 = 비활성화. 기본 1.0 (비활성) */
97
+ contextWarnThreshold: number;
98
+ /** 컨텍스트 위험 임계값 (0~1). 기본 0.85 */
99
+ contextCritThreshold: number;
100
+ };
89
101
  }
90
102
  /** Get config search paths in priority order */
91
103
  export declare function getConfigSearchPaths(): string[];
@@ -92,6 +92,13 @@ const DEFAULTS = {
92
92
  daemonIntervalSec: 2,
93
93
  activityRetentionDays: 7,
94
94
  },
95
+ alerts: {
96
+ enabled: true,
97
+ desktop: true,
98
+ log: true,
99
+ contextWarnThreshold: 1.0, // 기본 비활성 (0.70으로 설정 시 활성화)
100
+ contextCritThreshold: 0.85,
101
+ },
95
102
  };
96
103
  function cloneDefaults() {
97
104
  return JSON.parse(JSON.stringify(DEFAULTS));