marmonitor 0.2.6 → 0.2.7
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 +36 -2
- package/README.md +35 -2
- package/dist/cli.js +49 -26
- package/dist/config/index.d.ts +1 -0
- package/dist/config/index.js +6 -1
- package/dist/output/index.d.ts +6 -3
- package/dist/output/index.js +43 -32
- package/dist/output/utils.d.ts +9 -2
- package/dist/output/utils.js +58 -2
- package/dist/scanner/cache.d.ts +10 -0
- package/dist/scanner/cache.js +14 -0
- package/dist/scanner/claude.d.ts +70 -3
- package/dist/scanner/claude.js +302 -16
- package/dist/scanner/codex.d.ts +37 -0
- package/dist/scanner/codex.js +133 -0
- package/dist/scanner/daemon-loop.js +3 -0
- package/dist/scanner/daemon-utils.d.ts +11 -0
- package/dist/scanner/daemon-utils.js +42 -11
- package/dist/scanner/group.d.ts +1 -1
- package/dist/scanner/group.js +9 -0
- package/dist/scanner/index.d.ts +18 -0
- package/dist/scanner/index.js +247 -28
- package/dist/scanner/process.d.ts +12 -0
- package/dist/scanner/process.js +241 -25
- package/dist/scanner/session-registry.d.ts +21 -0
- package/dist/scanner/session-registry.js +85 -4
- package/dist/scanner/status.d.ts +36 -1
- package/dist/scanner/status.js +49 -5
- package/dist/sessions.d.ts +9 -0
- package/dist/sessions.js +11 -0
- package/dist/tmux/index.d.ts +7 -3
- package/dist/tmux/index.js +54 -13
- package/dist/types.d.ts +8 -0
- package/package.json +3 -1
package/dist/scanner/index.js
CHANGED
|
@@ -15,17 +15,45 @@ export { propagateWorkerStateToParent } from "./group.js";
|
|
|
15
15
|
export { parseGeminiSessionContent } from "./gemini.js";
|
|
16
16
|
// ─── Internal imports ─────────────────────────────────────────────
|
|
17
17
|
import { claudeSessionRegistry, sessionEnrichmentCache } from "./cache.js";
|
|
18
|
-
import { detectClaudePhase, getClaudeSessionRoots, parseClaudeSession, parseClaudeTokens, } from "./claude.js";
|
|
18
|
+
import { detectClaudePhase, getClaudeSessionRoots, matchClaudeSessionsByMtime, parseClaudeSession, parseClaudeTokens, } from "./claude.js";
|
|
19
19
|
import { buildCodexBindingKey, markMissingCodexBindingsDead, selectCodexBindingSession, upsertCodexBindingRecord, } from "./codex-binding-registry.js";
|
|
20
|
-
import { detectCodexPhase, indexCodexSessions,
|
|
20
|
+
import { detectCodexPhase, indexCodexSessions, parseCodexSessionIdFromCmd, selectCodexSessionForProcess, } from "./codex.js";
|
|
21
21
|
import { promiseAllLimited } from "./concurrency.js";
|
|
22
22
|
import { parseGeminiSession } from "./gemini.js";
|
|
23
23
|
import { groupByParent } from "./group.js";
|
|
24
24
|
import { perfEnd, perfStart } from "./perf.js";
|
|
25
25
|
import { detectAgentFromProcessSignature as _detectAgent, detectRuntimeSource, getProcessCwd, getProcessStartTime, } from "./process.js";
|
|
26
26
|
import { classifySessionTier } from "./session-tier.js";
|
|
27
|
-
import { applyStatusHysteresis, detectCliStdoutPhase, determineStatus,
|
|
27
|
+
import { applyStatusHysteresis, detectCliStdoutPhase, determineStatus, isInferredBusyFresh, mergeObservedActivityAt, resolveCodexInferredBusyAt, resolveEffectiveActivityAt, } from "./status.js";
|
|
28
28
|
// ─── Main Scanner ──────────────────────────────────────────────────
|
|
29
|
+
/**
|
|
30
|
+
* Whether a Claude PID belongs in the batch mtime resolution pass (#108).
|
|
31
|
+
*
|
|
32
|
+
* The batch scores candidates against `processStartedAt` inside a known cwd,
|
|
33
|
+
* so a PID missing either is unscorable there. Such a PID must fall through to
|
|
34
|
+
* the per-PID matcher, which still has an mtime-dominance fallback — keeping it
|
|
35
|
+
* in the batch would mark it "resolved to nothing" instead. `ps -o lstart=`
|
|
36
|
+
* failures are cached for PROCESS_START_TTL_MS, so one transient failure would
|
|
37
|
+
* otherwise leave the session unbound for that entire window.
|
|
38
|
+
*
|
|
39
|
+
* NaN must be rejected as firmly as undefined: getProcessStartTime derives the
|
|
40
|
+
* value with `new Date(...).getTime()`, so an unparseable `ps` line yields NaN,
|
|
41
|
+
* and a NaN deltaSec silently passes every `>` threshold comparison.
|
|
42
|
+
*/
|
|
43
|
+
export function isBatchableClaudeMtimeRequest(request) {
|
|
44
|
+
if (!request)
|
|
45
|
+
return false;
|
|
46
|
+
if (!request.cwd || request.cwd === "unknown")
|
|
47
|
+
return false;
|
|
48
|
+
return Number.isFinite(request.processStartedAt);
|
|
49
|
+
}
|
|
50
|
+
function hasResourceSample(sample) {
|
|
51
|
+
return Boolean(sample &&
|
|
52
|
+
Number.isFinite(sample.cpu) &&
|
|
53
|
+
sample.cpu >= 0 &&
|
|
54
|
+
Number.isFinite(sample.memory) &&
|
|
55
|
+
sample.memory >= 0);
|
|
56
|
+
}
|
|
29
57
|
/** Scan for all running AI agent sessions */
|
|
30
58
|
export async function scanAgents(config, options = {}) {
|
|
31
59
|
const enrichmentMode = options.enrichmentMode ?? "full";
|
|
@@ -33,13 +61,29 @@ export async function scanAgents(config, options = {}) {
|
|
|
33
61
|
const codexBindingRegistry = options.codexBindingRegistry;
|
|
34
62
|
const sessionRegistry = options.sessionRegistry;
|
|
35
63
|
const seenPids = new Set();
|
|
64
|
+
// #108: cycle-local guard against same-cwd Claude PID collisions. A
|
|
65
|
+
// sessionId bound to one PID is excluded from later parseClaudeSession
|
|
66
|
+
// candidate pools in the same scan cycle, so two PIDs whose lstart
|
|
67
|
+
// collides in the same second cannot collapse onto the same sessionId.
|
|
68
|
+
// The mutex serializes the matching step itself — without it, parallel
|
|
69
|
+
// promises would each race the claim Set before either could update it.
|
|
70
|
+
const cycleClaimedClaudeSessionIds = new Set();
|
|
71
|
+
let claudeMatchTail = Promise.resolve();
|
|
72
|
+
const withClaudeMatchLock = (fn) => {
|
|
73
|
+
const prev = claudeMatchTail;
|
|
74
|
+
let releaseLock = () => { };
|
|
75
|
+
claudeMatchTail = new Promise((resolve) => {
|
|
76
|
+
releaseLock = resolve;
|
|
77
|
+
});
|
|
78
|
+
return prev.then(fn).finally(releaseLock);
|
|
79
|
+
};
|
|
36
80
|
perfStart("scanAgents");
|
|
37
81
|
// 1. Find running processes
|
|
38
82
|
perfStart("ps-list");
|
|
39
83
|
const processes = await psList();
|
|
40
84
|
perfEnd("ps-list");
|
|
41
85
|
// Filter to agent processes
|
|
42
|
-
|
|
86
|
+
let agentProcesses = [];
|
|
43
87
|
for (const proc of processes) {
|
|
44
88
|
const agentName = _detectAgent(proc, config);
|
|
45
89
|
if (!agentName)
|
|
@@ -53,13 +97,35 @@ export async function scanAgents(config, options = {}) {
|
|
|
53
97
|
perfStart("pidusage");
|
|
54
98
|
const pids = agentProcesses.map((a) => a.proc.pid);
|
|
55
99
|
let usageMap = {};
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
100
|
+
if (pids.length > 0) {
|
|
101
|
+
try {
|
|
102
|
+
usageMap = await pidusage(pids);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// One rejected batch must not erase measurements for every other PID.
|
|
106
|
+
const retried = await Promise.allSettled(pids.map(async (pid) => pidusage(pid)));
|
|
107
|
+
for (let i = 0; i < retried.length; i++) {
|
|
108
|
+
const result = retried[i];
|
|
109
|
+
if (result.status === "fulfilled")
|
|
110
|
+
usageMap[pids[i]] = result.value;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
61
113
|
}
|
|
62
114
|
perfEnd("pidusage");
|
|
115
|
+
// A successful batch can omit PIDs that exited after the process census.
|
|
116
|
+
// Resolve missing/invalid samples before they can reserve session ownership.
|
|
117
|
+
agentProcesses = agentProcesses.filter(({ proc }) => {
|
|
118
|
+
if (hasResourceSample(usageMap[proc.pid]))
|
|
119
|
+
return true;
|
|
120
|
+
try {
|
|
121
|
+
process.kill(proc.pid, 0);
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
// ESRCH proves exit. EPERM proves existence; other failures remain unknown.
|
|
126
|
+
return error.code !== "ESRCH";
|
|
127
|
+
}
|
|
128
|
+
});
|
|
63
129
|
// 3. Pre-index Codex sessions (once, shared across all Codex processes)
|
|
64
130
|
const codexCwdEntries = isFullEnrichment
|
|
65
131
|
? await promiseAllLimited(agentProcesses
|
|
@@ -79,13 +145,106 @@ export async function scanAgents(config, options = {}) {
|
|
|
79
145
|
? await indexCodexSessions(config, { activeCwds: activeCodexCwds })
|
|
80
146
|
: [];
|
|
81
147
|
perfEnd("codex-index");
|
|
148
|
+
// #114: resolve every Codex process's self-declared session before the
|
|
149
|
+
// enrichment loop, so an explicit binding always outranks another process's
|
|
150
|
+
// heuristic guess regardless of the order the loop happens to run in. This
|
|
151
|
+
// mirrors what matchClaudeSessionsByMtime does for Claude.
|
|
152
|
+
const codexArgvSessionIdByPid = new Map();
|
|
153
|
+
for (const { proc, agentName } of agentProcesses) {
|
|
154
|
+
if (agentName !== "Codex")
|
|
155
|
+
continue;
|
|
156
|
+
const declaredId = parseCodexSessionIdFromCmd(proc.cmd);
|
|
157
|
+
if (declaredId)
|
|
158
|
+
codexArgvSessionIdByPid.set(proc.pid, declaredId);
|
|
159
|
+
}
|
|
160
|
+
const codexArgvReservedSessionIds = new Set(codexArgvSessionIdByPid.values());
|
|
161
|
+
const cycleClaimedCodexSessionIds = new Set();
|
|
162
|
+
let codexMatchChain = Promise.resolve();
|
|
163
|
+
const withCodexMatchLock = (fn) => {
|
|
164
|
+
const next = codexMatchChain.then(fn, fn);
|
|
165
|
+
codexMatchChain = next.catch(() => undefined);
|
|
166
|
+
return next;
|
|
167
|
+
};
|
|
168
|
+
const claudeSessionRoots = getClaudeSessionRoots(config);
|
|
169
|
+
const claudeLegacySessionIds = new Set();
|
|
170
|
+
if (isFullEnrichment) {
|
|
171
|
+
const legacySessionIds = await promiseAllLimited(agentProcesses
|
|
172
|
+
.filter((item) => item.agentName === "Claude Code")
|
|
173
|
+
.map(({ proc }) => async () => {
|
|
174
|
+
const sessionFile = claudeSessionRoots
|
|
175
|
+
.map((root) => join(root, `${proc.pid}.json`))
|
|
176
|
+
.find((candidate) => existsSync(candidate));
|
|
177
|
+
if (!sessionFile)
|
|
178
|
+
return undefined;
|
|
179
|
+
try {
|
|
180
|
+
const data = JSON.parse(await readFile(sessionFile, "utf-8"));
|
|
181
|
+
return typeof data.sessionId === "string" ? data.sessionId : undefined;
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
}), 4);
|
|
187
|
+
for (const sessionId of legacySessionIds) {
|
|
188
|
+
if (sessionId)
|
|
189
|
+
claudeLegacySessionIds.add(sessionId);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
// Resolve mtime-only Claude sessions as one batch before enrichment. A
|
|
193
|
+
// per-PID resolver is order-dependent: a process whose first message is
|
|
194
|
+
// delayed can claim its sibling's fresher JSONL if it happens to lock first.
|
|
195
|
+
// Legacy PID session files keep their direct path and are not part of this
|
|
196
|
+
// heuristic batch.
|
|
197
|
+
const claudeProcessMeta = isFullEnrichment
|
|
198
|
+
? (await promiseAllLimited(agentProcesses
|
|
199
|
+
.filter((item) => item.agentName === "Claude Code")
|
|
200
|
+
.map(({ proc }) => async () => ({
|
|
201
|
+
pid: proc.pid,
|
|
202
|
+
cwd: await getProcessCwd(proc.pid),
|
|
203
|
+
processStartedAt: await getProcessStartTime(proc.pid),
|
|
204
|
+
hasLegacySessionFile: claudeSessionRoots.some((root) => existsSync(join(root, `${proc.pid}.json`))),
|
|
205
|
+
})), 4)).flatMap((meta) => (meta ? [meta] : []))
|
|
206
|
+
: [];
|
|
207
|
+
// Ownership context covers every live Claude PID in the cwd, not just the
|
|
208
|
+
// ones this batch can score. A sibling with an unreadable lstart, or one
|
|
209
|
+
// already resolved through pid.json, still owns one of the jsonls there.
|
|
210
|
+
const liveClaudePidCountByCwd = new Map();
|
|
211
|
+
for (const meta of claudeProcessMeta) {
|
|
212
|
+
if (!meta.cwd || meta.cwd === "unknown")
|
|
213
|
+
continue;
|
|
214
|
+
liveClaudePidCountByCwd.set(meta.cwd, (liveClaudePidCountByCwd.get(meta.cwd) ?? 0) + 1);
|
|
215
|
+
}
|
|
216
|
+
const claudeMtimeRequests = claudeProcessMeta
|
|
217
|
+
.filter((meta) => !meta.hasLegacySessionFile)
|
|
218
|
+
.flatMap((meta) => (isBatchableClaudeMtimeRequest(meta) ? [meta] : []));
|
|
219
|
+
const claudeMtimeMatches = await matchClaudeSessionsByMtime(claudeMtimeRequests, config, {
|
|
220
|
+
liveClaudePidCountByCwd,
|
|
221
|
+
reservedSessionIds: claudeLegacySessionIds,
|
|
222
|
+
});
|
|
223
|
+
const claudeMtimePidSet = new Set(claudeMtimeRequests.map((request) => request.pid));
|
|
224
|
+
// The per-PID matcher's no-start-time fallback picks the most recent jsonl,
|
|
225
|
+
// which is only defensible when nothing else in the cwd could own it. With a
|
|
226
|
+
// sibling present it would hand one pane's session to the other, so those
|
|
227
|
+
// PIDs are refused outright instead.
|
|
228
|
+
const claudeSiblingBlockedPids = new Set(claudeProcessMeta
|
|
229
|
+
.filter((meta) => !meta.hasLegacySessionFile &&
|
|
230
|
+
!claudeMtimePidSet.has(meta.pid) &&
|
|
231
|
+
meta.cwd !== undefined &&
|
|
232
|
+
(liveClaudePidCountByCwd.get(meta.cwd) ?? 0) > 1)
|
|
233
|
+
.map((meta) => meta.pid));
|
|
234
|
+
const reservedClaudeSessionIds = new Set([
|
|
235
|
+
...claudeLegacySessionIds,
|
|
236
|
+
...[...claudeMtimeMatches.values()].map((match) => match.sessionId),
|
|
237
|
+
]);
|
|
82
238
|
// 4. Build sessions with enrichment (concurrency limited)
|
|
83
239
|
const sessionPromises = agentProcesses.map(({ proc, agentName }) => async () => {
|
|
84
240
|
const usage = usageMap[proc.pid];
|
|
85
|
-
const
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
-
|
|
241
|
+
const resourceUsageAvailable = hasResourceSample(usage);
|
|
242
|
+
const cpuPercent = resourceUsageAvailable ? Math.round(usage.cpu * 10) / 10 : 0;
|
|
243
|
+
const memoryMb = resourceUsageAvailable
|
|
244
|
+
? Math.round((usage.memory / (1024 * 1024)) * 10) / 10
|
|
245
|
+
: 0;
|
|
246
|
+
// A failed measurement is not evidence that an observed process is tiny or absent.
|
|
247
|
+
if (resourceUsageAvailable && memoryMb < config.status.minMemoryMb)
|
|
89
248
|
return null;
|
|
90
249
|
let cwd = "unknown";
|
|
91
250
|
let sessionId;
|
|
@@ -97,11 +256,14 @@ export async function scanAgents(config, options = {}) {
|
|
|
97
256
|
let phase;
|
|
98
257
|
let lastResponseAt;
|
|
99
258
|
let lastActivityAt;
|
|
259
|
+
let inferredBusyAt;
|
|
100
260
|
let codexSessionFile;
|
|
101
261
|
const runtimeSource = detectRuntimeSource(agentName, proc.cmd);
|
|
102
262
|
const cacheKey = `${agentName}:${proc.pid}`;
|
|
103
263
|
const cachedEnrichment = sessionEnrichmentCache.get(cacheKey);
|
|
104
264
|
// Determine session tier for differential enrichment
|
|
265
|
+
// #113: tiering intentionally uses the merged time — a process that looks
|
|
266
|
+
// busy should stay hot even while its session file lags behind.
|
|
105
267
|
const tier = cachedEnrichment
|
|
106
268
|
? classifySessionTier(cachedEnrichment.lastActivityAt, Date.now() / 1000, cpuPercent, cachedEnrichment.phase)
|
|
107
269
|
: "hot"; // no cache = first time seeing this session, treat as hot
|
|
@@ -112,7 +274,11 @@ export async function scanAgents(config, options = {}) {
|
|
|
112
274
|
if (regEntry?.filePath) {
|
|
113
275
|
try {
|
|
114
276
|
const fileStat = await stat(regEntry.filePath);
|
|
115
|
-
|
|
277
|
+
// #113: compared against a file mtime, so it must use the observed
|
|
278
|
+
// time — a merged one would hide a real write behind an inference.
|
|
279
|
+
// With no observation, 0 promotes the session, which is the safe way
|
|
280
|
+
// to be wrong for a check that only decides whether to look harder.
|
|
281
|
+
const cachedActivity = (cachedEnrichment.observedActivityAt ?? 0) * 1000;
|
|
116
282
|
if (fileStat.mtimeMs > cachedActivity + 1000) {
|
|
117
283
|
coldPromoted = true; // JSONL changed → force enrichment
|
|
118
284
|
}
|
|
@@ -134,17 +300,39 @@ export async function scanAgents(config, options = {}) {
|
|
|
134
300
|
sessionMatched = cachedEnrichment.sessionMatched ?? false;
|
|
135
301
|
phase = cachedEnrichment.phase;
|
|
136
302
|
lastResponseAt = cachedEnrichment.lastResponseAt;
|
|
137
|
-
|
|
303
|
+
// #113: restore the observed component, not the merged one — otherwise
|
|
304
|
+
// observedActivityAt below inherits the inference and the every-scan
|
|
305
|
+
// updateRegistry() call writes it to disk. The inference is carried
|
|
306
|
+
// separately so its TTL keeps measuring age since the process last
|
|
307
|
+
// looked busy.
|
|
308
|
+
lastActivityAt = cachedEnrichment.observedActivityAt;
|
|
309
|
+
inferredBusyAt = cachedEnrichment.inferredBusyAt;
|
|
138
310
|
}
|
|
139
311
|
else if (!isFullEnrichment && !cachedEnrichment) {
|
|
140
|
-
//
|
|
141
|
-
|
|
312
|
+
// Existence was established by process detection, not by a file binding.
|
|
313
|
+
// Keep new CLIs unbound until a heavy scan can actually resolve metadata.
|
|
314
|
+
sessionMatched = false;
|
|
142
315
|
}
|
|
143
316
|
else if (agentName === "Claude Code") {
|
|
144
317
|
// Get cwd and start time early so mtime-based matching can use them
|
|
145
318
|
const processCwd = (await getProcessCwd(proc.pid)) ?? undefined;
|
|
146
319
|
const processStartTime = await getProcessStartTime(proc.pid);
|
|
147
|
-
const
|
|
320
|
+
const preselectedMtimeMatch = claudeMtimePidSet.has(proc.pid)
|
|
321
|
+
? (claudeMtimeMatches.get(proc.pid) ?? null)
|
|
322
|
+
: claudeSiblingBlockedPids.has(proc.pid)
|
|
323
|
+
? null
|
|
324
|
+
: undefined;
|
|
325
|
+
// #108: serialize Claude matches and pass the cycle-claim Set in so
|
|
326
|
+
// each PID's match step sees previously bound sessionIds and skips
|
|
327
|
+
// them. parseClaudeSession adds to the Set itself is not enough —
|
|
328
|
+
// a race window between read & add would still let two PIDs win the
|
|
329
|
+
// same sessionId; the mutex closes that window.
|
|
330
|
+
const claudeData = await withClaudeMatchLock(async () => {
|
|
331
|
+
const result = await parseClaudeSession(proc.pid, processCwd, processStartTime, config, cycleClaimedClaudeSessionIds, preselectedMtimeMatch, reservedClaudeSessionIds);
|
|
332
|
+
if (result.sessionId)
|
|
333
|
+
cycleClaimedClaudeSessionIds.add(result.sessionId);
|
|
334
|
+
return result;
|
|
335
|
+
});
|
|
148
336
|
if (claudeData.cwd)
|
|
149
337
|
cwd = claudeData.cwd;
|
|
150
338
|
if (cwd === "unknown")
|
|
@@ -169,15 +357,31 @@ export async function scanAgents(config, options = {}) {
|
|
|
169
357
|
(await getProcessCwd(proc.pid)) ??
|
|
170
358
|
"unknown";
|
|
171
359
|
processStartedAt = await getProcessStartTime(proc.pid);
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
360
|
+
// #114: serialize so each PID sees what earlier ones claimed. Binding to
|
|
361
|
+
// the wrong session is worse than not binding — a misbound process shows
|
|
362
|
+
// another session's tokens and jumps to its pane — so every step refuses
|
|
363
|
+
// rather than falling through to a guess once a claim exists.
|
|
364
|
+
const matched = await withCodexMatchLock(async () => {
|
|
365
|
+
const picked = selectCodexSessionForProcess({
|
|
366
|
+
declaredSessionId: codexArgvSessionIdByPid.get(proc.pid),
|
|
367
|
+
sessions: codexSessions,
|
|
368
|
+
claimedSessionIds: cycleClaimedCodexSessionIds,
|
|
369
|
+
argvReservedSessionIds: codexArgvReservedSessionIds,
|
|
370
|
+
cwd,
|
|
371
|
+
processStartedAt,
|
|
372
|
+
resolveBinding: codexBindingRegistry
|
|
373
|
+
? (available) => selectCodexBindingSession(codexBindingRegistry, proc.pid, processStartedAt, cwd, available)
|
|
374
|
+
: undefined,
|
|
375
|
+
});
|
|
376
|
+
if (picked)
|
|
377
|
+
cycleClaimedCodexSessionIds.add(picked.id);
|
|
378
|
+
return picked;
|
|
379
|
+
});
|
|
175
380
|
if (matched) {
|
|
176
381
|
sessionMatched = true;
|
|
177
382
|
sessionId = matched.id;
|
|
178
383
|
startedAt = matched.timestamp;
|
|
179
|
-
lastActivityAt =
|
|
180
|
-
Math.max(cachedEnrichment?.lastActivityAt ?? 0, matched.lastActivityAt ?? 0) || undefined;
|
|
384
|
+
lastActivityAt = mergeObservedActivityAt(cachedEnrichment?.observedActivityAt, matched.lastActivityAt);
|
|
181
385
|
model = matched.model;
|
|
182
386
|
codexSessionFile = matched.filePath;
|
|
183
387
|
if (matched.totalTokenUsage) {
|
|
@@ -203,9 +407,11 @@ export async function scanAgents(config, options = {}) {
|
|
|
203
407
|
matched,
|
|
204
408
|
});
|
|
205
409
|
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
410
|
+
// #113: the CPU/phase inference is kept out of lastActivityAt so it can
|
|
411
|
+
// never be persisted or ratcheted into permanence.
|
|
412
|
+
inferredBusyAt =
|
|
413
|
+
resolveCodexInferredBusyAt(cpuPercent, phase, config.status.activeCpuThreshold, agentName) ?? cachedEnrichment?.inferredBusyAt;
|
|
414
|
+
lastActivityAt = mergeObservedActivityAt(cachedEnrichment?.observedActivityAt, lastActivityAt);
|
|
209
415
|
}
|
|
210
416
|
else if (agentName === "Gemini") {
|
|
211
417
|
cwd = cachedEnrichment?.cwd ?? (await getProcessCwd(proc.pid)) ?? "unknown";
|
|
@@ -223,15 +429,23 @@ export async function scanAgents(config, options = {}) {
|
|
|
223
429
|
}
|
|
224
430
|
}
|
|
225
431
|
if (sessionId && sessionRegistry?.has(sessionId)) {
|
|
432
|
+
// The registry only ever stores observed activity (#113), so merging it
|
|
433
|
+
// monotonically is safe — rollout mtimes do not move backwards.
|
|
226
434
|
const persistedLastActivityAt = sessionRegistry.get(sessionId)?.lastActivityAt;
|
|
227
|
-
lastActivityAt =
|
|
435
|
+
lastActivityAt = mergeObservedActivityAt(lastActivityAt, persistedLastActivityAt);
|
|
228
436
|
}
|
|
437
|
+
// Everything above tracks observed activity; the inference is layered on
|
|
438
|
+
// only for reporting, and only while it is still fresh.
|
|
439
|
+
if (!isInferredBusyFresh(inferredBusyAt))
|
|
440
|
+
inferredBusyAt = undefined;
|
|
441
|
+
const observedActivityAt = lastActivityAt;
|
|
442
|
+
lastActivityAt = resolveEffectiveActivityAt(observedActivityAt, inferredBusyAt);
|
|
229
443
|
if (cwd === "unknown" && isFullEnrichment) {
|
|
230
444
|
cwd = cachedEnrichment?.cwd ?? (await getProcessCwd(proc.pid)) ?? "unknown";
|
|
231
445
|
}
|
|
232
446
|
const statusBaseAt = lastActivityAt ?? lastResponseAt ?? startedAt;
|
|
233
447
|
const elapsed = statusBaseAt ? Date.now() / 1000 - statusBaseAt : undefined;
|
|
234
|
-
const rawStatus = determineStatus(cpuPercent, elapsed, sessionMatched, phase, config, agentName);
|
|
448
|
+
const rawStatus = determineStatus(resourceUsageAvailable ? cpuPercent : Number.NaN, elapsed, sessionMatched, phase, config, agentName);
|
|
235
449
|
const status = applyStatusHysteresis(rawStatus, cachedEnrichment?.status, elapsed, phase, agentName);
|
|
236
450
|
// Read git branch from .git/HEAD (full enrichment only, ~0.1ms per session)
|
|
237
451
|
let branch = cachedEnrichment?.branch;
|
|
@@ -252,6 +466,7 @@ export async function scanAgents(config, options = {}) {
|
|
|
252
466
|
cwd,
|
|
253
467
|
cpuPercent,
|
|
254
468
|
memoryMb,
|
|
469
|
+
resourceUsageAvailable,
|
|
255
470
|
status,
|
|
256
471
|
startedAt,
|
|
257
472
|
processStartedAt,
|
|
@@ -262,6 +477,8 @@ export async function scanAgents(config, options = {}) {
|
|
|
262
477
|
phase,
|
|
263
478
|
lastResponseAt,
|
|
264
479
|
lastActivityAt,
|
|
480
|
+
observedActivityAt,
|
|
481
|
+
inferredBusyAt,
|
|
265
482
|
runtimeSource,
|
|
266
483
|
branch,
|
|
267
484
|
};
|
|
@@ -278,6 +495,8 @@ export async function scanAgents(config, options = {}) {
|
|
|
278
495
|
phase: session.phase,
|
|
279
496
|
lastResponseAt: session.lastResponseAt,
|
|
280
497
|
lastActivityAt: session.lastActivityAt,
|
|
498
|
+
observedActivityAt: session.observedActivityAt,
|
|
499
|
+
inferredBusyAt: session.inferredBusyAt,
|
|
281
500
|
runtimeSource: session.runtimeSource,
|
|
282
501
|
branch: session.branch,
|
|
283
502
|
});
|
|
@@ -5,11 +5,23 @@ import { execFile } from "node:child_process";
|
|
|
5
5
|
import type { MarmonitorConfig } from "../config/index.js";
|
|
6
6
|
import type { RuntimeSource } from "../types.js";
|
|
7
7
|
export declare const execFileAsync: typeof execFile.__promisify__;
|
|
8
|
+
/**
|
|
9
|
+
* Parse a `ps -o lstart=` line into epoch seconds.
|
|
10
|
+
*
|
|
11
|
+
* Exported for tests: the locale that produced a given line cannot be recreated
|
|
12
|
+
* on an arbitrary CI runner, so the parser is exercised with captured output
|
|
13
|
+
* instead of a live `ps` call.
|
|
14
|
+
*/
|
|
15
|
+
export declare function parsePsLstart(raw: string): number | undefined;
|
|
8
16
|
/** Get process cwd via lsof (fallback for non-Claude agents) */
|
|
9
17
|
export declare function getProcessCwd(pid: number): Promise<string | undefined>;
|
|
10
18
|
export declare function getProcessStartTime(pid: number): Promise<number | undefined>;
|
|
11
19
|
export declare function detectRuntimeSource(agentName: string, cmd?: string): RuntimeSource | undefined;
|
|
12
20
|
export declare function matchesProcessCommand(command: string, processName: string): boolean;
|
|
21
|
+
export declare const CODEX_VALUE_OPTIONS: Set<string>;
|
|
22
|
+
/** Arguments belonging to a native Codex executable or supported Node entry point.
|
|
23
|
+
* Prompt text and other programs mentioning Codex do not establish executable identity. */
|
|
24
|
+
export declare function getCodexProcessArguments(command: string): string[] | undefined;
|
|
13
25
|
/** Match a process against agent signatures using process name first, then cmd fallback. */
|
|
14
26
|
export declare function detectAgentFromProcessSignature(proc: {
|
|
15
27
|
name: string;
|