marmonitor 0.2.0 → 0.2.3

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
@@ -87,6 +87,20 @@ marmonitor setup tmux
87
87
 
88
88
  [marmonitor-tmux](https://github.com/mjjo16/marmonitor-tmux) 플러그인을 `~/.tmux.conf`에 추가합니다. tmux 안에서 `prefix + I`을 눌러 활성화하세요.
89
89
 
90
+ `marmonitor`를 업그레이드한 뒤에는 다음 명령으로 tmux 연동 업데이트 경로를 확인하세요:
91
+
92
+ ```bash
93
+ marmonitor update-integration
94
+ ```
95
+
96
+ `prefix + U`로 TPM 플러그인을 업데이트했는데도 클릭 동작이나 팝업 키바인딩이 이전 버전처럼 남아 있다면, 실행 중인 tmux 서버에 플러그인을 다시 적용해야 합니다:
97
+
98
+ ```bash
99
+ tmux run-shell ~/.tmux/plugins/marmonitor-tmux/marmonitor.tmux
100
+ ```
101
+
102
+ 이 증상은 주로 기존 tmux 세션에서 플러그인을 업그레이드할 때 발생합니다. 신규 설치에서 `prefix + I`로 처음 로드하는 경우에는 보통 바로 최신 바인딩이 적용됩니다.
103
+
90
104
  <details>
91
105
  <summary>직접 ~/.tmux.conf에 추가하기</summary>
92
106
 
package/README.md CHANGED
@@ -95,6 +95,14 @@ marmonitor update-integration
95
95
 
96
96
  This checks whether your tmux integration also needs a TPM/plugin update.
97
97
 
98
+ If you updated the TPM plugin with `prefix + U` but click actions or popup keybindings still behave like the old version, re-apply the plugin in the running tmux server:
99
+
100
+ ```bash
101
+ tmux run-shell ~/.tmux/plugins/marmonitor-tmux/marmonitor.tmux
102
+ ```
103
+
104
+ This mainly affects existing tmux sessions after a plugin upgrade. Fresh installs via `prefix + I` usually load the current bindings immediately.
105
+
98
106
  <details>
99
107
  <summary>Or add manually to ~/.tmux.conf</summary>
100
108
 
@@ -131,7 +139,19 @@ npm link
131
139
 
132
140
  ## Quick Start
133
141
 
134
- Once installed, your tmux status bar automatically shows AI session badges. You also get:
142
+ ### Start the daemon
143
+
144
+ marmonitor runs as a background daemon that scans your AI sessions every 2 seconds:
145
+
146
+ ```bash
147
+ marmonitor start # Start the daemon
148
+ marmonitor stop # Stop the daemon
149
+ marmonitor restart # Restart (e.g. after npm update)
150
+ ```
151
+
152
+ The daemon must be running for all other commands to work. `marmonitor setup tmux` starts it automatically.
153
+
154
+ ### tmux shortcuts
135
155
 
136
156
  | Shortcut | Action |
137
157
  |----------|--------|
@@ -139,16 +159,33 @@ Once installed, your tmux status bar automatically shows AI session badges. You
139
159
  | `prefix + j` | Jump popup — pick a session to jump to |
140
160
  | `prefix + m` | Dock — compact monitor pane |
141
161
  | `Option+1~5` | Direct jump to attention session #1~5 |
162
+ | `Option+`` | Jump back to previous pane |
142
163
 
143
- CLI commands:
164
+ ### CLI commands
144
165
 
145
166
  ```bash
146
167
  marmonitor status # Full session inventory
147
168
  marmonitor attention # What needs your input?
169
+ marmonitor activity # What did each session do? (tool calls + tokens)
148
170
  marmonitor watch # Live full-screen monitor
171
+ marmonitor jump-back # Return to pane before last jump
149
172
  marmonitor help # All commands and options
150
173
  ```
151
174
 
175
+ ### Activity log
176
+
177
+ Track what your AI sessions actually did — file edits, bash commands, tokens used:
178
+
179
+ ```bash
180
+ marmonitor activity # Today's activity
181
+ marmonitor activity --pid 1234 # Filter by PID
182
+ marmonitor activity --session abc # Filter by session ID
183
+ marmonitor activity --days 3 # Last 3 days
184
+ marmonitor activity --json # JSON output
185
+ ```
186
+
187
+ Activity is collected automatically by the daemon and stored in `~/.config/marmonitor/activity-log/` (7-day retention).
188
+
152
189
  ## Phase Icons
153
190
 
154
191
  | Icon | Phase | Meaning |
@@ -249,6 +286,10 @@ npm uninstall -g marmonitor # Remove CLI
249
286
  - **Conservative defaults** — all integrations are opt-in
250
287
  - **tmux-first** — terminal-native WezTerm/iTerm2 surfaces are currently paused
251
288
 
289
+ ## Changelog
290
+
291
+ See [CHANGELOG.md](CHANGELOG.md) for release history and breaking changes.
292
+
252
293
  ## Contributing
253
294
 
254
295
  See [CONTRIBUTING.md](CONTRIBUTING.md) for setup, commit conventions, and PR guidelines. For architecture details, see [ARCHITECTURE.md](ARCHITECTURE.md).
@@ -63,6 +63,7 @@ const msg = `
63
63
  Commands:
64
64
  $ marmonitor status Show all AI sessions
65
65
  $ marmonitor attention Sessions needing your input
66
+ $ marmonitor activity What did each session do?
66
67
  $ marmonitor help All commands and shortcuts
67
68
 
68
69
  Uninstall:
package/dist/cli.js CHANGED
@@ -13,6 +13,7 @@ import { detectCodexPhase, indexCodexSessions, matchCodexSession } from "./scann
13
13
  import { isDaemonRunning, readDaemonPid, readDaemonSnapshot } from "./scanner/daemon-utils.js";
14
14
  import { parseGeminiSession } from "./scanner/gemini.js";
15
15
  import { scanAgents } from "./scanner/index.js";
16
+ import { loadRegistryFromFile } from "./scanner/session-registry.js";
16
17
  import { detectCliStdoutPhase } from "./scanner/status.js";
17
18
  import { captureTmuxPaneOutput, jumpToAgent, resolveTmuxJumpTarget } from "./tmux/index.js";
18
19
  import { getClientTty, jumpBack } from "./tmux/jump-anchor.js";
@@ -75,6 +76,7 @@ function buildHelpAppendix() {
75
76
  "Core workflows:",
76
77
  " status Full one-shot inventory of local AI sessions",
77
78
  " attention Priority list for sessions that need review",
79
+ " activity Show recent tool usage and tokens per session",
78
80
  " watch Live full-screen monitor",
79
81
  " dock Persistent tmux-friendly monitor",
80
82
  " --statusline Status bar output for tmux",
@@ -119,11 +121,34 @@ function buildHelpAppendix() {
119
121
  " integration.tmux.keys.*",
120
122
  " paths.* (runtime data path overrides)",
121
123
  "",
124
+ "Daemon:",
125
+ " start Start background scan daemon (required before use)",
126
+ " stop Stop daemon",
127
+ " restart Restart daemon (e.g. after update)",
128
+ " activity Show what each session did (tool calls + tokens)",
129
+ "",
130
+ "Activity log options:",
131
+ " --pid <pid> Filter by process ID",
132
+ " --session <sid> Filter by session ID prefix",
133
+ " --days <n> Number of days to show (default: 1)",
134
+ " --json JSON output",
135
+ "",
136
+ "Navigation:",
137
+ " jump --pid <pid> Jump to a session's tmux pane",
138
+ " jump --attention Interactive jump chooser",
139
+ " jump-back Return to pane before last jump",
140
+ "",
141
+ "Integration:",
142
+ " setup tmux Add tmux plugin to ~/.tmux.conf",
143
+ " update-integration Check tmux plugin sync status",
144
+ " uninstall-integration Remove tmux integration",
145
+ "",
122
146
  "Default tmux shortcuts:",
123
147
  " Prefix+a Attention popup",
124
148
  " Prefix+j Jump popup",
125
149
  " Prefix+m Toggle dock",
126
150
  " Option+1..5 Direct jump to numbered attention sessions",
151
+ " Option+` Jump back to previous pane",
127
152
  "",
128
153
  `Config location: ${getConfigDir()}/settings.json`,
129
154
  "Common settings:",
@@ -427,6 +452,11 @@ async function requireDaemonSnapshot() {
427
452
  }
428
453
  return agents;
429
454
  }
455
+ async function loadSessionRegistry() {
456
+ const registry = new Map();
457
+ await loadRegistryFromFile(join(getConfigDir(), "session-registry.json"), registry);
458
+ return registry;
459
+ }
430
460
  program
431
461
  .option("--statusline", "One-line summary for tmux statusbar")
432
462
  .option("--statusline-format <format>", "Statusline format: compact | standard | extended | tmux-badges", "compact")
@@ -613,7 +643,10 @@ program
613
643
  const config = await loadConfig(resolveConfigPath(opts));
614
644
  let agents;
615
645
  try {
616
- agents = await scanAgents(config, { enrichmentMode: "full" });
646
+ agents = await scanAgents(config, {
647
+ enrichmentMode: "full",
648
+ sessionRegistry: await loadSessionRegistry(),
649
+ });
617
650
  }
618
651
  catch (error) {
619
652
  const payload = {
@@ -655,10 +688,16 @@ program
655
688
  sessionLastResponseAt = gemini.lastResponseAt;
656
689
  }
657
690
  else if (agent.agentName === "Codex") {
658
- const codexSessions = await indexCodexSessions(config);
659
- const matched = matchCodexSession(agent.cwd, agent.startedAt, codexSessions);
691
+ const { loadCodexBindingRegistryFromFile, selectCodexBindingSession, buildCodexBindingKey } = await import("./scanner/codex-binding-registry.js");
692
+ const { getConfigDir } = await import("./config/index.js");
693
+ const { join: pj } = await import("node:path");
694
+ const codexSessions = await indexCodexSessions(config, { activeCwds: [agent.cwd] });
695
+ const bindingRegistry = new Map();
696
+ await loadCodexBindingRegistryFromFile(pj(getConfigDir(), "codex-binding-registry.json"), bindingRegistry);
697
+ const matched = selectCodexBindingSession(bindingRegistry, agent.pid, agent.processStartedAt, agent.cwd, codexSessions) ?? matchCodexSession(agent.cwd, agent.processStartedAt, codexSessions);
660
698
  sessionPhase = await detectCodexPhase(matched?.filePath, config);
661
699
  sessionSourceFile = matched?.filePath;
700
+ sessionLastActivityAt = matched?.lastActivityAt;
662
701
  }
663
702
  else if (agent.agentName === "Claude Code" && agent.sessionId) {
664
703
  const phaseResult = await detectClaudePhase(agent.sessionId, agent.cwd, agent.startedAt, config);
@@ -688,7 +727,27 @@ program
688
727
  }
689
728
  : null,
690
729
  paneOutput: paneOutput?.trimEnd() ?? null,
730
+ codexBinding: null,
691
731
  };
732
+ // Codex binding diagnostics
733
+ if (agent.agentName === "Codex") {
734
+ const { loadCodexBindingRegistryFromFile, buildCodexBindingKey } = await import("./scanner/codex-binding-registry.js");
735
+ const { getConfigDir } = await import("./config/index.js");
736
+ const { join: pj } = await import("node:path");
737
+ const bindingRegistry = new Map();
738
+ await loadCodexBindingRegistryFromFile(pj(getConfigDir(), "codex-binding-registry.json"), bindingRegistry);
739
+ const binding = bindingRegistry.get(buildCodexBindingKey(agent.pid, agent.processStartedAt));
740
+ if (binding) {
741
+ payload.codexBinding = {
742
+ threadId: binding.threadId,
743
+ rolloutPath: binding.rolloutPath,
744
+ confidence: binding.confidence,
745
+ unstableCount: binding.unstableCount,
746
+ lastVerifiedAt: binding.lastVerifiedAt,
747
+ deadAt: binding.deadAt ?? null,
748
+ };
749
+ }
750
+ }
692
751
  if (opts.json) {
693
752
  console.log(JSON.stringify(payload, null, 2));
694
753
  return;
@@ -703,6 +762,11 @@ program
703
762
  console.log(`Stdout phase: ${payload.stdoutPhase ?? "(none)"}`);
704
763
  console.log(`Session file: ${payload.sessionSourceFile ?? "(none)"}`);
705
764
  console.log(`tmux target: ${payload.tmuxTarget ? `${payload.tmuxTarget.pane} (${payload.tmuxTarget.match})` : "(none)"}`);
765
+ if (payload.codexBinding) {
766
+ const b = payload.codexBinding;
767
+ console.log(`Codex binding: thread=${b.threadId} confidence=${b.confidence} unstable=${b.unstableCount}`);
768
+ console.log(` rollout: ${b.rolloutPath}`);
769
+ }
706
770
  console.log("Pane capture:");
707
771
  console.log(payload.paneOutput ?? "(none)");
708
772
  });
@@ -903,6 +967,90 @@ program
903
967
  agents = []; // daemon stopped mid-loop
904
968
  }
905
969
  });
970
+ program
971
+ .command("activity")
972
+ .description("Show recent tool usage and token activity per session")
973
+ .option("--pid <pid>", "Filter by AI process PID")
974
+ .option("--session <sid>", "Filter by session ID (prefix match)")
975
+ .option("--days <n>", "Number of days to show", "1")
976
+ .option("--json", "Output as JSON")
977
+ .action(async (opts) => {
978
+ const { getConfigDir } = await import("./config/index.js");
979
+ const { join: pj } = await import("node:path");
980
+ const { getRecentDateKeys, readActivityLog } = await import("./scanner/activity-log.js");
981
+ const logDir = pj(getConfigDir(), "activity-log");
982
+ const days = Math.max(1, Math.min(90, Number(opts.days) || 1));
983
+ const allEntries = [];
984
+ for (const dateStr of getRecentDateKeys(days)) {
985
+ const entries = await readActivityLog(logDir, dateStr);
986
+ allEntries.push(...entries);
987
+ }
988
+ // Filter
989
+ let filtered = allEntries;
990
+ if (opts.pid) {
991
+ const agents = await getAgentsSnapshot();
992
+ const agent = agents.find((a) => a.pid === Number(opts.pid));
993
+ if (agent?.sessionId) {
994
+ const sidPrefix = agent.sessionId.slice(0, 12);
995
+ filtered = filtered.filter((e) => e.sid.startsWith(sidPrefix));
996
+ }
997
+ else {
998
+ filtered = [];
999
+ }
1000
+ }
1001
+ if (opts.session) {
1002
+ const prefix = opts.session;
1003
+ filtered = filtered.filter((e) => e.sid.startsWith(prefix));
1004
+ }
1005
+ if (opts.json) {
1006
+ console.log(JSON.stringify(filtered, null, 2));
1007
+ return;
1008
+ }
1009
+ if (filtered.length === 0) {
1010
+ console.log("No activity found.");
1011
+ return;
1012
+ }
1013
+ // Group by session
1014
+ const bySession = new Map();
1015
+ for (const e of filtered) {
1016
+ const key = `${e.sid}|${e.agent}|${e.cwd}`;
1017
+ if (!bySession.has(key))
1018
+ bySession.set(key, []);
1019
+ bySession.get(key).push(e);
1020
+ }
1021
+ for (const [key, entries] of bySession) {
1022
+ const [sid, agent, cwd] = key.split("|");
1023
+ const totalOut = entries.reduce((sum, e) => sum + (e.tokens?.out ?? 0), 0);
1024
+ const totalCache = entries.reduce((sum, e) => sum + (e.tokens?.cache ?? 0), 0);
1025
+ console.log(`\n${agent} ${sid}... ${cwd}`);
1026
+ console.log(` ${entries.length} actions out:${formatTokensShort(totalOut)} cache:${formatTokensShort(totalCache)}`);
1027
+ console.log(" ─────────────────────────────────────");
1028
+ for (const e of entries.slice(-20)) {
1029
+ const t = new Date(e.ts * 1000).toLocaleTimeString("en-GB", {
1030
+ hour: "2-digit",
1031
+ minute: "2-digit",
1032
+ });
1033
+ console.log(` ${t} ${e.tool}: ${truncateForDisplay(e.target, 60)}`);
1034
+ }
1035
+ if (entries.length > 20) {
1036
+ console.log(` ... +${entries.length - 20} more`);
1037
+ }
1038
+ }
1039
+ });
1040
+ function formatTokensShort(n) {
1041
+ if (n >= 1_000_000)
1042
+ return `${(n / 1_000_000).toFixed(1)}M`;
1043
+ if (n >= 1_000)
1044
+ return `${(n / 1_000).toFixed(1)}K`;
1045
+ return String(n);
1046
+ }
1047
+ function truncateForDisplay(value, maxLength) {
1048
+ if (value.length <= maxLength)
1049
+ return value;
1050
+ if (maxLength <= 3)
1051
+ return value.slice(0, maxLength);
1052
+ return `${value.slice(0, maxLength - 3)}...`;
1053
+ }
906
1054
  program
907
1055
  .command("clean")
908
1056
  .description("Show or terminate unmatched processes")
@@ -912,7 +1060,7 @@ program
912
1060
  .option("--pid <pid...>", "Only include specific unmatched PID(s)")
913
1061
  .action(async (opts) => {
914
1062
  const config = await loadConfig(resolveConfigPath(opts));
915
- const agents = await scanAgents(config);
1063
+ const agents = await scanAgents(config, { sessionRegistry: await loadSessionRegistry() });
916
1064
  const selectedPids = Array.isArray(opts.pid)
917
1065
  ? opts.pid
918
1066
  .map((value) => Number.parseInt(value, 10))
@@ -1002,7 +1150,8 @@ program
1002
1150
  console.log("Update path:");
1003
1151
  console.log(" 1. Press prefix+U in tmux");
1004
1152
  console.log(` 2. Or run: git -C ${pluginDir} pull --ff-only`);
1005
- console.log(" 3. Reload tmux if keybindings or popup sizing changed");
1153
+ console.log(` 3. Re-apply the plugin in the running tmux server: tmux run-shell ${join(pluginDir, "marmonitor.tmux")}`);
1154
+ console.log(" 4. If the status bar still looks stale, reload tmux.conf or restart tmux");
1006
1155
  }
1007
1156
  });
1008
1157
  program
@@ -84,6 +84,7 @@ export interface MarmonitorConfig {
84
84
  statuslineTtlMs: number;
85
85
  stdoutHeuristicTtlMs: number;
86
86
  daemonIntervalSec: number;
87
+ activityRetentionDays: number;
87
88
  };
88
89
  }
89
90
  /** Get config search paths in priority order */
@@ -90,6 +90,7 @@ const DEFAULTS = {
90
90
  statuslineTtlMs: 2000,
91
91
  stdoutHeuristicTtlMs: 2000,
92
92
  daemonIntervalSec: 2,
93
+ activityRetentionDays: 7,
93
94
  },
94
95
  };
95
96
  function cloneDefaults() {
@@ -31,7 +31,7 @@ export declare function resolveStatuslineDetailLayout(width: number | undefined,
31
31
  * Claude Code replaces both "/" and "." with "-". */
32
32
  export declare function cwdToProjectDirName(cwd: string): string;
33
33
  /** Determine agent status from CPU, elapsed time, and session match state */
34
- export declare function determineStatus(cpuPercent: number, elapsedSec: number | undefined, sessionMatched: boolean, activeCpuThreshold: number, stalledAfterMin: number, phase?: SessionPhase, recentActivityActiveSec?: number): "Active" | "Idle" | "Stalled" | "Unmatched" | "Dead";
34
+ export declare function determineStatus(cpuPercent: number, elapsedSec: number | undefined, sessionMatched: boolean, activeCpuThreshold: number, stalledAfterMin: number, phase?: SessionPhase, recentActivityActiveSec?: number, agentName?: string): "Active" | "Idle" | "Stalled" | "Unmatched" | "Dead";
35
35
  export interface CodexSessionCandidate {
36
36
  cwd: string;
37
37
  timestamp: number;
@@ -113,7 +113,7 @@ export function cwdToProjectDirName(cwd) {
113
113
  return cwd.replace(/[/.]/g, "-");
114
114
  }
115
115
  /** Determine agent status from CPU, elapsed time, and session match state */
116
- export function determineStatus(cpuPercent, elapsedSec, sessionMatched, activeCpuThreshold, stalledAfterMin, phase, recentActivityActiveSec = 180) {
116
+ export function determineStatus(cpuPercent, elapsedSec, sessionMatched, activeCpuThreshold, stalledAfterMin, phase, recentActivityActiveSec = 180, agentName) {
117
117
  if (!sessionMatched)
118
118
  return "Unmatched";
119
119
  if (cpuPercent > activeCpuThreshold)
@@ -122,6 +122,11 @@ export function determineStatus(cpuPercent, elapsedSec, sessionMatched, activeCp
122
122
  (elapsedSec === undefined || elapsedSec <= recentActivityActiveSec)) {
123
123
  return "Active";
124
124
  }
125
+ if (agentName === "Codex" &&
126
+ elapsedSec !== undefined &&
127
+ elapsedSec <= Math.min(60, recentActivityActiveSec)) {
128
+ return "Active";
129
+ }
125
130
  const stalledSec = stalledAfterMin * 60;
126
131
  if (elapsedSec !== undefined && elapsedSec > stalledSec && cpuPercent < 0.1) {
127
132
  return "Stalled";
@@ -316,7 +321,13 @@ function orderedAttentionItems(items) {
316
321
  /** Build prioritized attention list for popup/jump UX.
317
322
  * Order: permission -> fresh thinking/tool -> recent alive sessions -> stale thinking/tool. */
318
323
  export function buildAttentionItems(agents, nowSec = Date.now() / 1000) {
319
- const alive = agents.filter((agent) => agent.status !== "Dead" && agent.status !== "Unmatched" && agent.status !== "Stalled");
324
+ const alive = agents.filter((agent) => {
325
+ const kind = attentionKind(agent);
326
+ if (kind === "permission" || kind === "thinking" || kind === "tool") {
327
+ return true;
328
+ }
329
+ return agent.status !== "Dead" && agent.status !== "Unmatched" && agent.status !== "Stalled";
330
+ });
320
331
  const toAttentionItem = (agent, priority, kind) => ({
321
332
  kind,
322
333
  priority,
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Activity log — extracts tool_use from Claude/Codex JSONL and writes daily logs.
3
+ * Stored in ~/.config/marmonitor/activity-log/YYYY-MM-DD.jsonl
4
+ */
5
+ export interface ActivityEntry {
6
+ ts: number;
7
+ sid: string;
8
+ agent: string;
9
+ cwd: string;
10
+ tool: string;
11
+ target: string;
12
+ tokens?: {
13
+ in: number;
14
+ out: number;
15
+ cache: number;
16
+ };
17
+ }
18
+ export declare function formatDateKey(date: Date): string;
19
+ export declare function getRecentDateKeys(days: number, now?: Date): string[];
20
+ /** Extract tool_use entries from Claude Code JSONL lines */
21
+ export declare function extractClaudeToolUses(lines: string[], sessionId: string, agent: string, cwd: string): ActivityEntry[];
22
+ /** Extract tool events from Codex JSONL lines */
23
+ export declare function extractCodexToolUses(lines: string[], sessionId: string, agent: string, cwd: string): ActivityEntry[];
24
+ /** Append activity entries to daily log file */
25
+ export declare function appendActivityEntries(logDir: string, dateStr: string, entries: ActivityEntry[]): Promise<void>;
26
+ /** Read activity log for a specific date */
27
+ export declare function readActivityLog(logDir: string, dateStr: string): Promise<ActivityEntry[]>;
28
+ /** Delete activity logs older than retentionDays */
29
+ export declare function cleanupOldActivityLogs(logDir: string, retentionDays: number, now?: Date): Promise<number>;
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Activity log — extracts tool_use from Claude/Codex JSONL and writes daily logs.
3
+ * Stored in ~/.config/marmonitor/activity-log/YYYY-MM-DD.jsonl
4
+ */
5
+ import { mkdir, readFile, readdir, unlink, writeFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ export function formatDateKey(date) {
8
+ const year = date.getFullYear();
9
+ const month = String(date.getMonth() + 1).padStart(2, "0");
10
+ const day = String(date.getDate()).padStart(2, "0");
11
+ return `${year}-${month}-${day}`;
12
+ }
13
+ export function getRecentDateKeys(days, now = new Date()) {
14
+ const keys = [];
15
+ for (let d = 0; d < days; d++) {
16
+ const date = new Date(now);
17
+ date.setDate(now.getDate() - d);
18
+ keys.push(formatDateKey(date));
19
+ }
20
+ return keys;
21
+ }
22
+ /** Extract tool_use entries from Claude Code JSONL lines */
23
+ export function extractClaudeToolUses(lines, sessionId, agent, cwd) {
24
+ const entries = [];
25
+ for (const line of lines) {
26
+ try {
27
+ const d = JSON.parse(line);
28
+ if (d.type !== "assistant")
29
+ continue;
30
+ const msg = d.message ?? {};
31
+ const usage = msg.usage;
32
+ const ts = parseTimestamp(d.timestamp);
33
+ if (!ts)
34
+ continue;
35
+ const content = msg.content ?? [];
36
+ for (const c of content) {
37
+ if (c.type !== "tool_use")
38
+ continue;
39
+ const entry = {
40
+ ts,
41
+ sid: sessionId,
42
+ agent,
43
+ cwd,
44
+ tool: c.name ?? "unknown",
45
+ target: extractTarget(c.name, c.input ?? {}),
46
+ };
47
+ if (usage) {
48
+ entry.tokens = {
49
+ in: usage.input_tokens ?? 0,
50
+ out: usage.output_tokens ?? 0,
51
+ cache: usage.cache_read_input_tokens ?? 0,
52
+ };
53
+ }
54
+ entries.push(entry);
55
+ }
56
+ }
57
+ catch {
58
+ // skip malformed lines
59
+ }
60
+ }
61
+ return entries;
62
+ }
63
+ /** Extract tool events from Codex JSONL lines */
64
+ export function extractCodexToolUses(lines, sessionId, agent, cwd) {
65
+ const entries = [];
66
+ let lastTokens;
67
+ for (const line of lines) {
68
+ try {
69
+ const d = JSON.parse(line);
70
+ if (d.type !== "event_msg")
71
+ continue;
72
+ const payload = d.payload ?? {};
73
+ const ts = parseTimestamp(d.timestamp);
74
+ if (payload.type === "token_count") {
75
+ const last = payload.info?.last_token_usage;
76
+ if (last) {
77
+ lastTokens = {
78
+ in: last.input_tokens ?? 0,
79
+ out: last.output_tokens ?? 0,
80
+ cache: last.cached_input_tokens ?? 0,
81
+ };
82
+ }
83
+ continue;
84
+ }
85
+ if (!ts)
86
+ continue;
87
+ if (payload.type === "exec_command_end") {
88
+ const cmd = Array.isArray(payload.command) ? payload.command.slice(-1)[0] : "";
89
+ entries.push({
90
+ ts,
91
+ sid: sessionId,
92
+ agent,
93
+ cwd: payload.cwd ?? cwd,
94
+ tool: "Bash",
95
+ target: cmd.split("\n")[0].slice(0, 100),
96
+ ...(lastTokens ? { tokens: lastTokens } : {}),
97
+ });
98
+ lastTokens = undefined;
99
+ }
100
+ else if (payload.type === "patch_apply_end") {
101
+ const stdout = payload.stdout ?? "";
102
+ const fileMatch = stdout.match(/[MA]\s+(.+)/);
103
+ const target = fileMatch ? fileMatch[1].trim() : "unknown";
104
+ entries.push({
105
+ ts,
106
+ sid: sessionId,
107
+ agent,
108
+ cwd,
109
+ tool: "Edit",
110
+ target: target.slice(0, 100),
111
+ ...(lastTokens ? { tokens: lastTokens } : {}),
112
+ });
113
+ lastTokens = undefined;
114
+ }
115
+ else if (payload.type === "web_search_end") {
116
+ entries.push({
117
+ ts,
118
+ sid: sessionId,
119
+ agent,
120
+ cwd,
121
+ tool: "WebSearch",
122
+ target: (payload.query ?? "").slice(0, 100),
123
+ ...(lastTokens ? { tokens: lastTokens } : {}),
124
+ });
125
+ lastTokens = undefined;
126
+ }
127
+ }
128
+ catch {
129
+ // skip malformed lines
130
+ }
131
+ }
132
+ return entries;
133
+ }
134
+ /** Append activity entries to daily log file */
135
+ export async function appendActivityEntries(logDir, dateStr, entries) {
136
+ if (entries.length === 0)
137
+ return;
138
+ await mkdir(logDir, { recursive: true });
139
+ const filePath = join(logDir, `${dateStr}.jsonl`);
140
+ const data = `${entries.map((e) => JSON.stringify(e)).join("\n")}\n`;
141
+ try {
142
+ const existing = await readFile(filePath, "utf-8");
143
+ await writeFile(filePath, existing + data, "utf-8");
144
+ }
145
+ catch {
146
+ await writeFile(filePath, data, "utf-8");
147
+ }
148
+ }
149
+ /** Read activity log for a specific date */
150
+ export async function readActivityLog(logDir, dateStr) {
151
+ try {
152
+ const raw = await readFile(join(logDir, `${dateStr}.jsonl`), "utf-8");
153
+ return raw
154
+ .trim()
155
+ .split("\n")
156
+ .filter(Boolean)
157
+ .map((line) => JSON.parse(line));
158
+ }
159
+ catch {
160
+ return [];
161
+ }
162
+ }
163
+ /** Delete activity logs older than retentionDays */
164
+ export async function cleanupOldActivityLogs(logDir, retentionDays, now = new Date()) {
165
+ // Use start-of-day to avoid deleting today's cutoff date file early
166
+ const cutoffDate = new Date(now.getTime() - retentionDays * 86400000);
167
+ const cutoff = new Date(cutoffDate.getFullYear(), cutoffDate.getMonth(), cutoffDate.getDate());
168
+ const cutoffKey = formatDateKey(cutoff);
169
+ let deleted = 0;
170
+ try {
171
+ const files = await readdir(logDir);
172
+ for (const file of files) {
173
+ if (!file.endsWith(".jsonl"))
174
+ continue;
175
+ const dateStr = file.replace(".jsonl", "");
176
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr))
177
+ continue;
178
+ if (dateStr < cutoffKey) {
179
+ await unlink(join(logDir, file));
180
+ deleted++;
181
+ }
182
+ }
183
+ }
184
+ catch {
185
+ // directory missing — nothing to clean
186
+ }
187
+ return deleted;
188
+ }
189
+ // ─── Helpers ─────────────────────────────────────────────────
190
+ function parseTimestamp(ts) {
191
+ if (typeof ts === "number")
192
+ return Math.floor(ts);
193
+ if (typeof ts === "string") {
194
+ try {
195
+ return Math.floor(new Date(ts).getTime() / 1000);
196
+ }
197
+ catch {
198
+ return undefined;
199
+ }
200
+ }
201
+ return undefined;
202
+ }
203
+ function extractTarget(toolName, input) {
204
+ if (toolName === "Read" || toolName === "Write" || toolName === "Edit") {
205
+ return String(input.file_path ?? "unknown").slice(0, 100);
206
+ }
207
+ if (toolName === "Bash") {
208
+ return String(input.command ?? "")
209
+ .split("\n")[0]
210
+ .slice(0, 100);
211
+ }
212
+ if (toolName === "Grep") {
213
+ return String(input.pattern ?? "").slice(0, 50);
214
+ }
215
+ if (toolName === "Agent") {
216
+ return String(input.description ?? "").slice(0, 50);
217
+ }
218
+ if (toolName === "Skill") {
219
+ return String(input.skill ?? "");
220
+ }
221
+ if (toolName === "Glob") {
222
+ return String(input.pattern ?? "");
223
+ }
224
+ return toolName;
225
+ }
@@ -13,6 +13,7 @@ export declare const CLAUDE_SESSION_AMBIGUITY_GAP_SEC = 300;
13
13
  export declare const CLAUDE_PHASE_RECENT_LINES = 50;
14
14
  export declare const CODEX_PHASE_RECENT_LINES = 30;
15
15
  export declare const RECENT_ACTIVITY_ACTIVE_SEC = 180;
16
+ export declare const STATUS_HYSTERESIS_SEC = 30;
16
17
  export interface FileTokenCacheEntry {
17
18
  mtimeMs: number;
18
19
  size: number;