marmonitor 0.2.2 → 0.2.4

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.
@@ -19,7 +19,59 @@ export async function getSystemInfo() {
19
19
  let monoMode = false;
20
20
  /** Apply badge style to terminal chalk output: mono uses bold/dim only */
21
21
  export function applyTerminalStyle(badgeStyle) {
22
- monoMode = badgeStyle === "basic-mono" || badgeStyle === "text-mono";
22
+ monoMode =
23
+ badgeStyle === "basic-mono" || badgeStyle === "block-mono" || badgeStyle === "text-mono";
24
+ }
25
+ export function abbreviateModel(model) {
26
+ if (!model)
27
+ return "—";
28
+ if (model.includes("opus"))
29
+ return "opus";
30
+ if (model.includes("sonnet"))
31
+ return "sonnet";
32
+ if (model.includes("haiku"))
33
+ return "haiku";
34
+ if (model.length <= 12)
35
+ return model;
36
+ return model.slice(0, 11);
37
+ }
38
+ function cwdToProjectName(cwd) {
39
+ const home = process.env.HOME ?? "";
40
+ const short = cwd.startsWith(home) ? cwd.slice(home.length + 1) : cwd;
41
+ const parts = short.split("/");
42
+ return parts[parts.length - 1] || short;
43
+ }
44
+ /** Strip ANSI escape codes to get visible character count */
45
+ function visibleLength(str) {
46
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape stripping
47
+ return str.replace(/\x1b\[\d*(;\d+)*m/g, "").length;
48
+ }
49
+ /** Pad string to fixed visible width (ANSI-aware) */
50
+ function padVisible(str, width) {
51
+ const visible = visibleLength(str);
52
+ return visible >= width ? str : str + " ".repeat(width - visible);
53
+ }
54
+ /** Right-align a string to fixed width (for numbers like CPU, MEM) */
55
+ function padVisibleRight(str, width) {
56
+ const visible = visibleLength(str);
57
+ return visible >= width ? str : " ".repeat(width - visible) + str;
58
+ }
59
+ function formatTokensCompact(n) {
60
+ if (n >= 1_000_000)
61
+ return `${(n / 1_000_000).toFixed(1)}M`;
62
+ if (n >= 1_000)
63
+ return `${(n / 1_000).toFixed(1)}K`;
64
+ return String(n);
65
+ }
66
+ function formatElapsedCompactTable(epochSec) {
67
+ const sec = Math.floor(Date.now() / 1000 - epochSec);
68
+ if (sec < 60)
69
+ return `${sec}s`;
70
+ if (sec < 3600)
71
+ return `${Math.floor(sec / 60)}m`;
72
+ if (sec < 86400)
73
+ return `${Math.floor(sec / 3600)}h`;
74
+ return `${Math.floor(sec / 86400)}d`;
23
75
  }
24
76
  /** Agent name with distinct color */
25
77
  function agentLabel(name) {
@@ -141,29 +193,95 @@ export async function printStatus(agents) {
141
193
  return;
142
194
  }
143
195
  if (alive.length > 0) {
144
- console.log(`AI Sessions (${alive.length} active):`);
196
+ console.log(`AI Sessions (${alive.length} active):\n`);
197
+ // Column widths — fixed-width columns first, variable-width last
198
+ const W = {
199
+ status: 10,
200
+ agent: 7,
201
+ model: 12,
202
+ pid: 6,
203
+ cpu: 6,
204
+ mem: 7,
205
+ last: 6,
206
+ tokens: 10,
207
+ project: 22,
208
+ branch: 16,
209
+ };
210
+ // Table header
211
+ const cols = [
212
+ "Status".padEnd(W.status),
213
+ "Agent".padEnd(W.agent),
214
+ "Model".padEnd(W.model),
215
+ "PID".padEnd(W.pid),
216
+ "CPU".padEnd(W.cpu),
217
+ "MEM".padEnd(W.mem),
218
+ "Last".padEnd(W.last),
219
+ "Tokens".padEnd(W.tokens),
220
+ "Project".padEnd(W.project),
221
+ "Branch",
222
+ ];
223
+ console.log(` ${chalk.dim(cols.join(" "))}`);
224
+ console.log(chalk.dim(` ${"─".repeat(cols.join(" ").length)}`));
145
225
  for (const a of alive) {
146
- const icon = displayStatusLabel(a.status, a.phase);
147
- const path = shortenPath(a.cwd);
148
- const started = formatElapsed(a.startedAt);
149
- const tokens = formatTokenUsage(a.tokenUsage, a.model);
150
- const agent = agentLabel(a.agentName).padEnd(18);
151
- const phase = phaseIcon(a.phase);
152
- const runtime = runtimeLabel(a.runtimeSource);
153
- const lastTime = a.lastResponseAt
154
- ? chalk.dim(` last response ${formatElapsed(a.lastResponseAt)}`)
226
+ // Fixed-width status: colorize label only, pad with plain spaces after
227
+ const statusWord = a.phase === "permission"
228
+ ? "Allow"
229
+ : a.phase === "thinking"
230
+ ? "Think"
231
+ : a.phase === "tool"
232
+ ? "Tool"
233
+ : a.status;
234
+ const statusLabel2 = `[${statusWord}]`;
235
+ const coloredLabel = statusWord === "Active"
236
+ ? chalk.green(statusLabel2)
237
+ : statusWord === "Idle"
238
+ ? chalk.yellow(statusLabel2)
239
+ : statusWord === "Stalled"
240
+ ? chalk.red(statusLabel2)
241
+ : statusWord === "Allow"
242
+ ? chalk.red(statusLabel2)
243
+ : statusWord === "Think"
244
+ ? chalk.magenta(statusLabel2)
245
+ : statusWord === "Tool"
246
+ ? chalk.green(statusLabel2)
247
+ : chalk.white(statusLabel2);
248
+ const rawStatus = coloredLabel + " ".repeat(Math.max(0, W.status - statusLabel2.length));
249
+ const agentStr = a.agentName === "Claude Code" ? "Claude" : a.agentName;
250
+ const modelStr = abbreviateModel(a.model);
251
+ const cpu = `${a.cpuPercent}%`;
252
+ const mem = `${a.memoryMb.toFixed(0)}MB`;
253
+ const last = a.lastResponseAt
254
+ ? formatElapsedCompactTable(a.lastResponseAt)
155
255
  : a.lastActivityAt
156
- ? chalk.dim(` last activity ${formatElapsed(a.lastActivityAt)}`)
157
- : "";
158
- console.log(` ${icon} ${agent} PID:${String(a.pid).padEnd(6)} ${path}${runtime}${phase}`);
159
- console.log(` CPU:${a.cpuPercent}% MEM:${a.memoryMb.toFixed(0)}MB started ${started}${lastTime}${tokens}`);
256
+ ? formatElapsedCompactTable(a.lastActivityAt)
257
+ : "—";
258
+ const tokens = a.tokenUsage ? `out:${formatTokensCompact(a.tokenUsage.outputTokens)}` : "";
259
+ const project = cwdToProjectName(a.cwd).slice(0, W.project - 1);
260
+ const branchStr = (a.branch ?? "—").slice(0, W.branch - 1);
261
+ const line = [
262
+ rawStatus,
263
+ padVisible(agentStr, W.agent),
264
+ chalk.dim(modelStr.padEnd(W.model)),
265
+ String(a.pid).padEnd(W.pid),
266
+ padVisibleRight(cpu, W.cpu),
267
+ padVisibleRight(mem, W.mem),
268
+ chalk.dim(last.padStart(W.last)),
269
+ chalk.dim(tokens.padEnd(W.tokens)),
270
+ project.padEnd(W.project),
271
+ chalk.dim(branchStr),
272
+ ].join(" ");
273
+ console.log(` ${line}`);
160
274
  if (a.workers && a.workers.length > 0) {
161
- for (let i = 0; i < a.workers.length; i++) {
162
- const w = a.workers[i];
163
- const isLast = i === a.workers.length - 1;
164
- const branch = isLast ? "└──" : "├──";
165
- const wStatus = statusLabel(w.status).trim();
166
- console.log(chalk.dim(` ${branch} PID:${String(w.pid).padEnd(6)} CPU:${w.cpuPercent}% MEM:${w.memoryMb.toFixed(0)}MB ${wStatus}`));
275
+ for (const w of a.workers) {
276
+ const wLine = [
277
+ " ".repeat(W.status),
278
+ "└─".padEnd(W.agent),
279
+ " ".repeat(W.model),
280
+ String(w.pid).padEnd(W.pid),
281
+ padVisibleRight(`${w.cpuPercent}%`, W.cpu),
282
+ padVisibleRight(`${w.memoryMb.toFixed(0)}MB`, W.mem),
283
+ ].join(" ");
284
+ console.log(chalk.dim(` ${wLine}`));
167
285
  }
168
286
  }
169
287
  }
@@ -237,6 +355,8 @@ function attentionKindLabel(kind) {
237
355
  function attentionLine(item) {
238
356
  const name = item.agentName === "Claude Code" ? "Claude" : item.agentName;
239
357
  const path = compactDirLabel(item.cwd);
358
+ const branch = item.branch;
359
+ const branchTag = branch ? chalk.dim(` (${branch})`) : "";
240
360
  const runtime = runtimeLabel(item.runtimeSource);
241
361
  const time = item.lastResponseAt
242
362
  ? ` ${chalk.dim(formatElapsed(item.lastResponseAt))}`
@@ -244,21 +364,21 @@ function attentionLine(item) {
244
364
  ? ` ${chalk.dim(formatElapsed(item.lastActivityAt))}`
245
365
  : "";
246
366
  if (item.kind === "unmatched") {
247
- return `${name} ${chalk.dim(path)}${runtime} PID:${item.pid}${time}`;
367
+ return `${name} ${chalk.dim(path)}${branchTag}${runtime} PID:${item.pid}${time}`;
248
368
  }
249
369
  if (item.kind === "permission") {
250
- return `${name} ${chalk.dim(path)}${runtime} allow pending PID:${item.pid}${time}`;
370
+ return `${name} ${chalk.dim(path)}${branchTag}${runtime} allow pending PID:${item.pid}${time}`;
251
371
  }
252
372
  if (item.kind === "stalled") {
253
- return `${name} ${chalk.dim(path)}${runtime} stalled PID:${item.pid}${time}`;
373
+ return `${name} ${chalk.dim(path)}${branchTag}${runtime} stalled PID:${item.pid}${time}`;
254
374
  }
255
375
  if (item.kind === "thinking") {
256
- return `${name} ${chalk.dim(path)}${runtime} thinking PID:${item.pid}${time}`;
376
+ return `${name} ${chalk.dim(path)}${branchTag}${runtime} thinking PID:${item.pid}${time}`;
257
377
  }
258
378
  if (item.kind === "active") {
259
- return `${name} ${chalk.dim(path)}${runtime} recent PID:${item.pid}${time}`;
379
+ return `${name} ${chalk.dim(path)}${branchTag}${runtime} active PID:${item.pid}${time}`;
260
380
  }
261
- return `${name} ${chalk.dim(path)}${runtime} tool PID:${item.pid}${time}`;
381
+ return `${name} ${chalk.dim(path)}${branchTag}${runtime} tool PID:${item.pid}${time}`;
262
382
  }
263
383
  function jumpAttentionStatusLabel(item) {
264
384
  if (item.kind === "permission")
@@ -267,7 +387,7 @@ function jumpAttentionStatusLabel(item) {
267
387
  return chalk.green("[Thinking]");
268
388
  if (item.kind === "tool")
269
389
  return chalk.cyan("[Tool] ");
270
- return chalk.blue("[Recent] ");
390
+ return chalk.blue("[Active] ");
271
391
  }
272
392
  function jumpAttentionPhaseIcon(item) {
273
393
  if (item.kind === "permission")
@@ -281,6 +401,8 @@ function jumpAttentionPhaseIcon(item) {
281
401
  function jumpAttentionLine(item) {
282
402
  const name = item.agentName === "Claude Code" ? "Claude" : item.agentName;
283
403
  const path = compactDirLabel(item.cwd);
404
+ const branch = item.branch;
405
+ const branchTag = branch ? chalk.dim(` (${branch})`) : "";
284
406
  const runtime = runtimeLabel(item.runtimeSource);
285
407
  const started = item.startedAt ? chalk.dim(` started ${formatElapsed(item.startedAt)}`) : "";
286
408
  const activity = item.lastResponseAt
@@ -293,15 +415,15 @@ function jumpAttentionLine(item) {
293
415
  const icon = jumpAttentionPhaseIcon(item);
294
416
  const agent = agentLabel(item.agentName).padEnd(8);
295
417
  if (item.kind === "permission") {
296
- return ` ${status} ${agent} ${chalk.dim(path)}${runtime}${icon}\n PID:${item.pid} ${stats}${started}${activity}`;
418
+ return ` ${status} ${agent} ${chalk.dim(path)}${branchTag}${runtime}${icon}\n PID:${item.pid} ${stats}${started}${activity}`;
297
419
  }
298
420
  if (item.kind === "thinking") {
299
- return ` ${status} ${agent} ${chalk.dim(path)}${runtime}${icon}\n PID:${item.pid} ${stats}${started}${activity}`;
421
+ return ` ${status} ${agent} ${chalk.dim(path)}${branchTag}${runtime}${icon}\n PID:${item.pid} ${stats}${started}${activity}`;
300
422
  }
301
423
  if (item.kind === "tool") {
302
- return ` ${status} ${agent} ${chalk.dim(path)}${runtime}${icon}\n PID:${item.pid} ${stats}${started}${activity}`;
424
+ return ` ${status} ${agent} ${chalk.dim(path)}${branchTag}${runtime}${icon}\n PID:${item.pid} ${stats}${started}${activity}`;
303
425
  }
304
- return ` ${status} ${agent} ${chalk.dim(path)}${runtime}${icon}\n PID:${item.pid} ${stats}${started}${activity}`;
426
+ return ` ${status} ${agent} ${chalk.dim(path)}${branchTag}${runtime}${icon}\n PID:${item.pid} ${stats}${started}${activity}`;
305
427
  }
306
428
  function paginateJumpAttentionItems(items, page, pageSize = 10) {
307
429
  const normalizedPage = Number.isInteger(page) && page > 0 ? page : 1;
@@ -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;
@@ -73,6 +73,7 @@ export interface AttentionItem {
73
73
  phase?: AgentSession["phase"];
74
74
  lastResponseAt?: number;
75
75
  lastActivityAt?: number;
76
+ branch?: string;
76
77
  }
77
78
  export interface StatusPill {
78
79
  label: string;
@@ -146,7 +147,7 @@ export declare function buildStatusPills(snapshot: StatuslineSnapshot): {
146
147
  };
147
148
  /** Build one-line persistent-bar summary string. */
148
149
  export declare function buildStatuslineSummary(snapshot: StatuslineSnapshot, format?: StatuslineFormat): string;
149
- export type BadgeStyle = "basic" | "basic-mono" | "text" | "text-mono";
150
+ export type BadgeStyle = "basic" | "basic-mono" | "block" | "block-mono" | "text" | "text-mono";
150
151
  export declare function buildTmuxBadgeBar(snapshot: StatuslineSnapshot, focusText?: string, badgeStyle?: BadgeStyle, hasJumpAnchor?: boolean): string;
151
152
  export declare function buildTmuxAttentionPills(items: AttentionItem[], maxCount?: number, width?: number, badgeStyle?: BadgeStyle): string | undefined;
152
153
  export declare function serializeWeztermPills(snapshot: StatuslineSnapshot, focusText?: string): string;
@@ -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,
@@ -331,6 +342,7 @@ export function buildAttentionItems(agents, nowSec = Date.now() / 1000) {
331
342
  phase: agent.phase,
332
343
  lastResponseAt: agent.lastResponseAt,
333
344
  lastActivityAt: agent.lastActivityAt,
345
+ branch: agent.branch,
334
346
  });
335
347
  const tier1 = alive
336
348
  .filter((agent) => attentionPriority(agent, nowSec) !== undefined)
@@ -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;
@@ -13,6 +13,7 @@ export const CLAUDE_SESSION_AMBIGUITY_GAP_SEC = 300;
13
13
  export const CLAUDE_PHASE_RECENT_LINES = 50;
14
14
  export const CODEX_PHASE_RECENT_LINES = 30;
15
15
  export const RECENT_ACTIVITY_ACTIVE_SEC = 180;
16
+ export const STATUS_HYSTERESIS_SEC = 30;
16
17
  // ─── Cache Instances ───────────────────────────────────────────────
17
18
  export const claudeProjectDirCache = new BoundedMap(64);
18
19
  export const claudeTokenCache = new BoundedMap(64);
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Codex binding registry — persists PID/process bindings to Codex thread/jsonl.
3
+ * 1차는 schema + load/save + prune만 제공한다.
4
+ */
5
+ import type { CodexSessionMeta } from "./cache.js";
6
+ export interface CodexBindingRecord {
7
+ pid: number;
8
+ processStartedAt?: number;
9
+ cwd: string;
10
+ threadId: string;
11
+ rolloutPath: string;
12
+ lastVerifiedAt: number;
13
+ confidence: "high" | "medium" | "low";
14
+ unstableCount: number;
15
+ deadAt?: number;
16
+ }
17
+ export type CodexBindingRegistry = Map<string, CodexBindingRecord>;
18
+ export declare function buildCodexBindingKey(pid: number, processStartedAt?: number): string;
19
+ export declare function selectCodexBindingSession(registry: CodexBindingRegistry, pid: number, processStartedAt: number | undefined, cwd: string, sessions: CodexSessionMeta[]): CodexSessionMeta | undefined;
20
+ export declare function upsertCodexBindingRecord(registry: CodexBindingRegistry, params: {
21
+ pid: number;
22
+ processStartedAt?: number;
23
+ cwd: string;
24
+ matched: CodexSessionMeta;
25
+ confidence?: CodexBindingRecord["confidence"];
26
+ }): void;
27
+ export declare function markMissingCodexBindingsDead(registry: CodexBindingRegistry, aliveKeys: Set<string>): number;
28
+ export declare function pruneCodexBindingRegistry(registry: CodexBindingRegistry, maxAgeDays: number): number;
29
+ export declare function saveCodexBindingRegistryToFile(filePath: string, registry: CodexBindingRegistry): Promise<void>;
30
+ export declare function loadCodexBindingRegistryFromFile(filePath: string, registry: CodexBindingRegistry): Promise<void>;