pi-better-server 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/package.json +3 -3
  2. package/scripts/measure-shared-reads/daemon.mjs +7 -0
  3. package/scripts/measure-shared-reads/probe.mjs +10 -0
  4. package/scripts/measure-shared-reads.mjs +145 -0
  5. package/scripts/test-on-pi.sh +19 -2
  6. package/src/cli.ts +39 -2
  7. package/src/client.ts +9 -4
  8. package/src/daemon-owner.ts +47 -6
  9. package/src/handshake.ts +8 -7
  10. package/src/lifecycle-config.ts +4 -0
  11. package/src/paths.ts +1 -11
  12. package/src/protocol.ts +5 -0
  13. package/src/registry.ts +2 -1
  14. package/src/runtime/background-history.ts +241 -0
  15. package/src/runtime/background.ts +173 -0
  16. package/src/runtime/cancellation.ts +95 -0
  17. package/src/runtime/client.ts +111 -0
  18. package/src/runtime/domain/assignment-observation.d.mts +1 -0
  19. package/src/runtime/domain/assignment-observation.mjs +103 -0
  20. package/src/runtime/domain/assignment-projection.d.mts +1 -0
  21. package/src/runtime/domain/assignment-projection.mjs +245 -0
  22. package/src/runtime/domain/background/conditions.mjs +93 -0
  23. package/src/runtime/domain/background/process-identity.mjs +110 -0
  24. package/src/runtime/domain/background/process.mjs +511 -0
  25. package/src/runtime/domain/background/registry.mjs +374 -0
  26. package/src/runtime/domain/background/snapshot.mjs +73 -0
  27. package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
  28. package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
  29. package/src/runtime/domain/background/supervisor/store.mjs +604 -0
  30. package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
  31. package/src/runtime/domain/background/supervisor/types.mjs +47 -0
  32. package/src/runtime/domain/background/terminal-publication.mjs +58 -0
  33. package/src/runtime/domain/background/types.mjs +3 -0
  34. package/src/runtime/domain/coordinator/index.mjs +50 -0
  35. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
  36. package/src/runtime/domain/coordinator/src/discovery.mjs +85 -0
  37. package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
  38. package/src/runtime/domain/coordinator/src/operations.mjs +299 -0
  39. package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
  40. package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
  41. package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
  42. package/src/runtime/domain/coordinator/src/schema.mjs +351 -0
  43. package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
  44. package/src/runtime/domain/coordinator/src/store.mjs +235 -0
  45. package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
  46. package/src/runtime/domain/coordinator/src/types.mjs +24 -0
  47. package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
  48. package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
  49. package/src/runtime/domain/health-observation.d.mts +3 -0
  50. package/src/runtime/domain/health-observation.mjs +613 -0
  51. package/src/runtime/domain/health-surface.mjs +279 -0
  52. package/src/runtime/domain/log-cursor.mjs +148 -0
  53. package/src/runtime/domain/log-paths.mjs +13 -0
  54. package/src/runtime/domain/parse.d.mts +2 -0
  55. package/src/runtime/domain/parse.mjs +1173 -0
  56. package/src/runtime/domain/process-status.d.mts +1 -0
  57. package/src/runtime/domain/process-status.mjs +25 -0
  58. package/src/runtime/domain/session-store.d.mts +2 -0
  59. package/src/runtime/domain/session-store.mjs +489 -0
  60. package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
  61. package/src/runtime/domain/shared-harness-settings.mjs +126 -0
  62. package/src/runtime/domain/shared-log-utils.mjs +1223 -0
  63. package/src/runtime/domain/shared-stall-detector.mjs +37 -0
  64. package/src/runtime/domain/widget.d.mts +1 -0
  65. package/src/runtime/domain/widget.mjs +250 -0
  66. package/src/runtime/guardian.ts +189 -0
  67. package/src/runtime/health-config.ts +27 -0
  68. package/src/runtime/local-client.ts +34 -0
  69. package/src/runtime/queries.ts +76 -0
  70. package/src/runtime/query-executor.ts +228 -0
  71. package/src/runtime/query-worker.mjs +118 -0
  72. package/src/runtime/read-model.ts +357 -0
  73. package/src/runtime/root.ts +29 -0
  74. package/src/runtime/socket.ts +10 -0
  75. package/src/runtime/status-cli.ts +11 -0
  76. package/src/runtime/work-client.d.mts +13 -0
  77. package/src/runtime/work-client.mjs +88 -0
  78. package/src/server.ts +136 -12
  79. package/src/session-activity.ts +22 -2
  80. package/src/shared-ssh-core/index.ts +30 -1
  81. package/src/startup/activation.ts +32 -5
  82. package/src/startup/ensure.ts +13 -1
  83. package/src/startup/install.ts +2 -0
  84. package/src/version.ts +4 -0
@@ -0,0 +1,3 @@
1
+ export function resolveHealthThresholds(config?: any): any;
2
+ export function healthThresholdsForConfig(config: any): any;
3
+ export function extractChildEventFactsFromLog(id: string, options?: { logPath?: string }): { facts: any; rawLog: any };
@@ -0,0 +1,613 @@
1
+ // Generated from packages/pi-better-subagents/health-observation.ts. Do not edit directly.
2
+ /**
3
+ * Multi-dimensional subagent health observations (issue #66).
4
+ *
5
+ * Pure seam: accepts durable status, process-liveness facts, parsed child-event
6
+ * facts, optional raw-log diagnostics, thresholds, and `now`, then produces an
7
+ * observation. Never writes metadata and never kills processes.
8
+ *
9
+ * Event vocabulary follows docs/evidence/issue-64/NOTES.md. Stale is residual:
10
+ * open tools, compaction, and active model-error/retry phases explain silence
11
+ * and must not collapse into stale. Raw log mtime/size is diagnostic only.
12
+ */
13
+ import { statSync } from "node:fs";
14
+ import { DEFAULT_MAX_READ_BYTES, readAppendedLines } from "./log-cursor.mjs";
15
+ import { logPathFor } from "./log-paths.mjs";
16
+ import { observeStall } from "./shared-stall-detector.mjs";
17
+ /** Defaults tuned for coordinator workloads; override per call or via config. */
18
+ export const DEFAULT_HEALTH_THRESHOLDS = Object.freeze({
19
+ quietMs: 60_000,
20
+ staleMs: 5 * 60_000,
21
+ longToolMs: 2 * 60_000,
22
+ longCompactionMs: 2 * 60_000,
23
+ });
24
+ function positiveMs(n, fallback) {
25
+ const v = Number(n);
26
+ return Number.isFinite(v) && v > 0 ? Math.floor(v) : fallback;
27
+ }
28
+ function envDuration(name) {
29
+ const raw = process.env[name];
30
+ if (!raw || raw.trim() === "")
31
+ return undefined;
32
+ const value = Number(raw);
33
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : undefined;
34
+ }
35
+ /** Merge partial thresholds / config keys onto defaults. */
36
+ export function resolveHealthThresholds(partial) {
37
+ const p = (partial ?? {});
38
+ return {
39
+ quietMs: positiveMs(p.quietMs ?? p.healthQuietMs, DEFAULT_HEALTH_THRESHOLDS.quietMs),
40
+ staleMs: positiveMs(p.staleMs ?? p.healthStaleMs, DEFAULT_HEALTH_THRESHOLDS.staleMs),
41
+ longToolMs: positiveMs(p.longToolMs ?? p.healthLongToolMs, DEFAULT_HEALTH_THRESHOLDS.longToolMs),
42
+ longCompactionMs: positiveMs(p.longCompactionMs ?? p.healthLongCompactionMs, DEFAULT_HEALTH_THRESHOLDS.longCompactionMs),
43
+ };
44
+ }
45
+ export function healthThresholdsForConfig(config) {
46
+ return resolveHealthThresholds({
47
+ ...config,
48
+ healthQuietMs: config.healthQuietMs ?? envDuration("PI_BETTER_STALL_QUIET_MS"),
49
+ healthStaleMs: config.healthStaleMs ?? envDuration("PI_BETTER_STALL_MS"),
50
+ });
51
+ }
52
+ function emptyFacts() {
53
+ return {
54
+ activeTools: [],
55
+ compacting: false,
56
+ model: { state: "ok", errorHistory: [] },
57
+ sawAgentSettled: false,
58
+ longModelCallSupported: false,
59
+ };
60
+ }
61
+ /**
62
+ * Wall-clock time from parsed event provenance only.
63
+ * Never invents timestamps from raw log mtime, `Date.now()`, or stream ordinals —
64
+ * those would promote diagnostic writes into healthy activity.
65
+ */
66
+ function eventTime(e) {
67
+ if (typeof e.at === "number" && Number.isFinite(e.at))
68
+ return e.at;
69
+ if (typeof e.timestamp === "number" && Number.isFinite(e.timestamp))
70
+ return e.timestamp;
71
+ const msg = e.message;
72
+ if (msg && typeof msg.timestamp === "number" && Number.isFinite(msg.timestamp)) {
73
+ return msg.timestamp;
74
+ }
75
+ return undefined;
76
+ }
77
+ /** Clear latched retry intent after later successful child progress. */
78
+ function markRecovered(state) {
79
+ if (state.lastError || state.errorHistory.length > 0 || state.retrying || state.willRetry === true) {
80
+ state.recoveredAfterError = true;
81
+ }
82
+ state.retrying = false;
83
+ if (state.willRetry === true)
84
+ state.willRetry = false;
85
+ }
86
+ function bumpMeaningful(state, at) {
87
+ if (typeof at !== "number" || !Number.isFinite(at))
88
+ return;
89
+ if (state.last === undefined || at >= state.last)
90
+ state.last = at;
91
+ }
92
+ function isAssistantMessage(msg) {
93
+ return !!msg && typeof msg === "object" && msg.role === "assistant";
94
+ }
95
+ function assistantIsError(msg) {
96
+ return msg.stopReason === "error" || typeof msg.errorMessage === "string";
97
+ }
98
+ function pushError(history, entry, max = 8) {
99
+ if (!entry.message)
100
+ return;
101
+ history.push(entry);
102
+ while (history.length > max)
103
+ history.shift();
104
+ }
105
+ /**
106
+ * Every event type `extractChildEventFacts` below branches on. The fold has no
107
+ * default branch — an event of any other type (`message_update` and friends,
108
+ * which are 98% of a log by volume) cannot move a single fact — so incremental
109
+ * readers may drop unlisted types before parsing them without changing any
110
+ * observation. Keep in step with the fold: `health_observation.test.mjs` fails
111
+ * if the fold branches on a type this set does not name, or names one the fold
112
+ * no longer reads.
113
+ */
114
+ export const CHILD_EVENT_FACT_TYPES = new Set([
115
+ "tool_execution_start",
116
+ "tool_execution_update",
117
+ "tool_execution_end",
118
+ "compaction_start",
119
+ "compaction_end",
120
+ "auto_retry_start",
121
+ "auto_retry_end",
122
+ "message_end",
123
+ "turn_end",
124
+ "agent_end",
125
+ "agent_settled",
126
+ ]);
127
+ /** Leading `{"type":"…"` of an NDJSON event line, read without parsing it. */
128
+ const LEADING_TYPE = /^\s*\{\s*"type"\s*:\s*"([A-Za-z0-9_.-]+)"/;
129
+ /**
130
+ * Whether a raw log line could move any fact. Lines whose type we can read
131
+ * cheaply and that the fold ignores are rejected without a `JSON.parse`; a line
132
+ * whose shape we cannot read cheaply is kept, so the fold stays authoritative.
133
+ */
134
+ export function mayAffectChildEventFacts(line) {
135
+ const match = LEADING_TYPE.exec(line);
136
+ if (!match)
137
+ return true;
138
+ return CHILD_EVENT_FACT_TYPES.has(match[1]);
139
+ }
140
+ /**
141
+ * Extract health-relevant facts from an in-memory event list (tests / callers
142
+ * that already parsed NDJSON). Skips non-objects; ignores raw non-JSON noise.
143
+ */
144
+ export function extractChildEventFacts(events) {
145
+ const openTools = new Map();
146
+ let anonymous = 0;
147
+ const meaningful = {};
148
+ let lastToolAt;
149
+ let compacting = false;
150
+ let compactionStartedAt;
151
+ let lastCompaction;
152
+ let sawAgentSettled = false;
153
+ let retry;
154
+ const recovery = {
155
+ recoveredAfterError: false,
156
+ retrying: false,
157
+ willRetry: undefined,
158
+ lastError: undefined,
159
+ errorHistory: [],
160
+ };
161
+ for (const raw of events) {
162
+ if (!raw || typeof raw !== "object")
163
+ continue;
164
+ const e = raw;
165
+ const type = typeof e.type === "string" ? e.type : undefined;
166
+ if (!type)
167
+ continue;
168
+ // Only parsed-event write provenance counts as wall-clock activity.
169
+ const at = eventTime(e);
170
+ if (type === "tool_execution_start") {
171
+ const toolName = typeof e.toolName === "string" ? e.toolName : "unknown";
172
+ const toolCallId = typeof e.toolCallId === "string" ? e.toolCallId : undefined;
173
+ const key = toolCallId ?? `anonymous:${anonymous++}`;
174
+ openTools.set(key, { toolCallId, toolName, startedAt: at });
175
+ lastToolAt = at ?? lastToolAt;
176
+ bumpMeaningful(meaningful, at);
177
+ continue;
178
+ }
179
+ if (type === "tool_execution_update") {
180
+ lastToolAt = at ?? lastToolAt;
181
+ bumpMeaningful(meaningful, at);
182
+ continue;
183
+ }
184
+ if (type === "tool_execution_end") {
185
+ const toolCallId = typeof e.toolCallId === "string" ? e.toolCallId : undefined;
186
+ if (toolCallId) {
187
+ openTools.delete(toolCallId);
188
+ }
189
+ else if (typeof e.toolName === "string") {
190
+ const match = [...openTools].find(([, t]) => t.toolName === e.toolName);
191
+ if (match)
192
+ openTools.delete(match[0]);
193
+ }
194
+ lastToolAt = at ?? lastToolAt;
195
+ bumpMeaningful(meaningful, at);
196
+ // Successful tool completion supersedes prior retry intent (AC9).
197
+ if (e.isError !== true)
198
+ markRecovered(recovery);
199
+ continue;
200
+ }
201
+ if (type === "compaction_start") {
202
+ compacting = true;
203
+ compactionStartedAt = at;
204
+ bumpMeaningful(meaningful, at);
205
+ continue;
206
+ }
207
+ if (type === "compaction_end") {
208
+ compacting = false;
209
+ lastCompaction = {
210
+ reason: typeof e.reason === "string" ? e.reason : undefined,
211
+ aborted: typeof e.aborted === "boolean" ? e.aborted : undefined,
212
+ willRetry: typeof e.willRetry === "boolean" ? e.willRetry : undefined,
213
+ errorMessage: typeof e.errorMessage === "string" ? e.errorMessage : undefined,
214
+ at,
215
+ };
216
+ compactionStartedAt = undefined;
217
+ bumpMeaningful(meaningful, at);
218
+ continue;
219
+ }
220
+ if (type === "auto_retry_start") {
221
+ recovery.retrying = true;
222
+ recovery.recoveredAfterError = false;
223
+ recovery.willRetry = true;
224
+ retry = {
225
+ attempt: typeof e.attempt === "number" ? e.attempt : undefined,
226
+ maxAttempts: typeof e.maxAttempts === "number" ? e.maxAttempts : undefined,
227
+ startedAt: at,
228
+ };
229
+ const msg = typeof e.errorMessage === "string" ? e.errorMessage : "model retry";
230
+ recovery.lastError = { message: msg, at };
231
+ pushError(recovery.errorHistory, recovery.lastError);
232
+ bumpMeaningful(meaningful, at);
233
+ continue;
234
+ }
235
+ if (type === "auto_retry_end") {
236
+ recovery.retrying = false;
237
+ const success = e.success === true;
238
+ if (success) {
239
+ markRecovered(recovery);
240
+ }
241
+ else {
242
+ const msg = typeof e.finalError === "string"
243
+ ? e.finalError
244
+ : (recovery.lastError?.message ?? "model retry exhausted");
245
+ recovery.lastError = { message: msg, at };
246
+ pushError(recovery.errorHistory, recovery.lastError);
247
+ recovery.recoveredAfterError = false;
248
+ }
249
+ bumpMeaningful(meaningful, at);
250
+ continue;
251
+ }
252
+ if (type === "message_end") {
253
+ const msg = e.message;
254
+ if (isAssistantMessage(msg)) {
255
+ if (assistantIsError(msg)) {
256
+ const message = typeof msg.errorMessage === "string"
257
+ ? msg.errorMessage
258
+ : "assistant stopReason=error";
259
+ recovery.lastError = { message, at };
260
+ pushError(recovery.errorHistory, recovery.lastError);
261
+ recovery.recoveredAfterError = false;
262
+ // Model-error evidence is meaningful for timing, not healthy progress.
263
+ bumpMeaningful(meaningful, at);
264
+ }
265
+ else {
266
+ bumpMeaningful(meaningful, at);
267
+ // Later successful assistant evidence clears retry/warning (AC9).
268
+ markRecovered(recovery);
269
+ }
270
+ }
271
+ // user message_end is not child progress
272
+ continue;
273
+ }
274
+ if (type === "turn_end") {
275
+ const msg = e.message;
276
+ if (isAssistantMessage(msg) && !assistantIsError(msg)) {
277
+ bumpMeaningful(meaningful, at);
278
+ markRecovered(recovery);
279
+ }
280
+ continue;
281
+ }
282
+ if (type === "agent_end") {
283
+ if (typeof e.willRetry === "boolean")
284
+ recovery.willRetry = e.willRetry;
285
+ if (recovery.willRetry === true) {
286
+ recovery.retrying = true;
287
+ recovery.recoveredAfterError = false;
288
+ bumpMeaningful(meaningful, at);
289
+ }
290
+ continue;
291
+ }
292
+ if (type === "agent_settled") {
293
+ sawAgentSettled = true;
294
+ // Settled ends the active retry phase; retain error history for detail.
295
+ recovery.retrying = false;
296
+ if (recovery.willRetry === true)
297
+ recovery.willRetry = false;
298
+ bumpMeaningful(meaningful, at);
299
+ continue;
300
+ }
301
+ // message_update is noisy; intentionally NOT meaningful for stale detection.
302
+ }
303
+ let modelState = "ok";
304
+ if (recovery.retrying || recovery.willRetry === true)
305
+ modelState = "retrying";
306
+ else if (recovery.lastError && !recovery.recoveredAfterError)
307
+ modelState = "error";
308
+ else
309
+ modelState = "ok";
310
+ return {
311
+ lastMeaningfulAt: meaningful.last,
312
+ activeTools: [...openTools.values()],
313
+ lastToolAt,
314
+ compacting,
315
+ compactionStartedAt,
316
+ lastCompaction,
317
+ model: {
318
+ state: modelState,
319
+ lastError: recovery.lastError,
320
+ errorHistory: [...recovery.errorHistory],
321
+ retry,
322
+ },
323
+ sawAgentSettled,
324
+ willRetry: recovery.willRetry,
325
+ longModelCallSupported: false,
326
+ };
327
+ }
328
+ /** Parse the fact-relevant events out of raw NDJSON lines. */
329
+ function parseFactEvents(lines) {
330
+ const events = [];
331
+ const sizes = [];
332
+ for (const line of lines) {
333
+ const s = line.trim();
334
+ if (!s || s[0] !== "{")
335
+ continue;
336
+ if (!mayAffectChildEventFacts(s))
337
+ continue;
338
+ try {
339
+ events.push(JSON.parse(s));
340
+ sizes.push(s.length);
341
+ }
342
+ catch {
343
+ // bad JSON — ignore (noise / partial line)
344
+ }
345
+ }
346
+ return { events, sizes };
347
+ }
348
+ // ---- incremental log reading ----------------------------------------------
349
+ //
350
+ // Logs are append-only and reach gigabytes, so facts are folded from an
351
+ // accumulated event list that grows by the bytes appended since the last read
352
+ // (see log-cursor.ts). Only the types the fold consumes are retained, which is
353
+ // ~2% of a log's lines; `message_update` alone is 98% of the volume and cannot
354
+ // move a fact. The retained list is capped, oldest-first, and a drop is
355
+ // reported as a diagnostic rather than silently changing an observation.
356
+ /** Memory budget for one run's retained fact-relevant events. */
357
+ const MAX_RETAINED_EVENT_BYTES = 8 * 1024 * 1024; // 8 MiB
358
+ function maxHealthReadBytes() {
359
+ const raw = process.env.PI_SUBAGENT_MAX_HEALTH_READ_BYTES;
360
+ if (!raw)
361
+ return DEFAULT_MAX_READ_BYTES;
362
+ const n = Number(raw);
363
+ return Number.isFinite(n) && n > 0 ? n : DEFAULT_MAX_READ_BYTES;
364
+ }
365
+ /**
366
+ * Runs tracked at once. A backstop, not a policy: callers are expected to reset
367
+ * a dismissed run, and this bounds the leak if one forgets.
368
+ */
369
+ const MAX_TRACKED_RUNS = 64;
370
+ const factLogStates = new Map();
371
+ /**
372
+ * Forget the incremental read position for a run (or all runs). Call after a run
373
+ * is dismissed, and in tests that rewrite a log under a reused id.
374
+ */
375
+ export function resetChildEventLogCursor(id) {
376
+ if (id === undefined)
377
+ factLogStates.clear();
378
+ else
379
+ factLogStates.delete(id);
380
+ }
381
+ function rememberState(id, state) {
382
+ // Re-insert so the map orders least-recently-read first.
383
+ factLogStates.delete(id);
384
+ factLogStates.set(id, state);
385
+ while (factLogStates.size > MAX_TRACKED_RUNS) {
386
+ const oldest = factLogStates.keys().next();
387
+ if (oldest.done)
388
+ break;
389
+ factLogStates.delete(oldest.value);
390
+ }
391
+ }
392
+ function trimToBudget(state) {
393
+ while (state.bytes > MAX_RETAINED_EVENT_BYTES && state.events.length > 1) {
394
+ state.events.shift();
395
+ state.bytes -= state.sizes.shift() ?? 0;
396
+ state.dropped = true;
397
+ }
398
+ if (state.bytes < 0)
399
+ state.bytes = 0;
400
+ }
401
+ /**
402
+ * Read a run log for event facts + raw mtime/size diagnostics.
403
+ * Raw log write time never promotes activity health by itself.
404
+ *
405
+ * Reads incrementally: only bytes appended since the previous call for this id
406
+ * are parsed, so a hot-path caller never re-reads a whole multi-gigabyte log.
407
+ * Pass `logText` to fold a caller-supplied log instead, which bypasses the
408
+ * cursor entirely.
409
+ */
410
+ export function extractChildEventFactsFromLog(id, opts = {}) {
411
+ const path = opts.logPath ?? logPathFor(id);
412
+ const rawLog = {};
413
+ try {
414
+ const st = statSync(path);
415
+ rawLog.mtimeMs = Math.trunc(st.mtimeMs);
416
+ rawLog.sizeBytes = st.size;
417
+ }
418
+ catch (err) {
419
+ rawLog.error = err instanceof Error ? err.message : String(err);
420
+ }
421
+ // Do not synthesise wall-clock timestamps from raw mtime / now. Untimestamped
422
+ // events still contribute structural facts (open tools, compacting, model
423
+ // phase); activity age only moves on parsed-event write provenance.
424
+ // `opts.now` is accepted for API symmetry with callers but must not mint times.
425
+ void opts.now;
426
+ if (opts.logText !== undefined) {
427
+ const { events } = parseFactEvents(opts.logText.split("\n"));
428
+ return { facts: extractChildEventFacts(events), rawLog };
429
+ }
430
+ const key = opts.logPath ?? id;
431
+ const previous = factLogStates.get(key);
432
+ const read = readAppendedLines(path, previous?.cursor, maxHealthReadBytes());
433
+ if (read.error !== undefined) {
434
+ rawLog.error = rawLog.error ?? read.error;
435
+ if (!previous)
436
+ return { facts: emptyFacts(), rawLog };
437
+ }
438
+ const state = read.restarted || !previous
439
+ ? { cursor: read.cursor, events: [], sizes: [], bytes: 0, truncated: false, dropped: false }
440
+ : previous;
441
+ state.cursor = read.cursor;
442
+ state.truncated = state.truncated || read.truncated;
443
+ const parsed = parseFactEvents(read.lines);
444
+ if (parsed.events.length > 0) {
445
+ state.events.push(...parsed.events);
446
+ state.sizes.push(...parsed.sizes);
447
+ for (const size of parsed.sizes)
448
+ state.bytes += size;
449
+ trimToBudget(state);
450
+ }
451
+ rememberState(key, state);
452
+ if (state.truncated)
453
+ rawLog.windowTruncated = true;
454
+ if (state.dropped)
455
+ rawLog.eventsDropped = true;
456
+ return { facts: extractChildEventFacts(state.events), rawLog };
457
+ }
458
+ function processLiveness(status, supervised) {
459
+ if (status === "orphaned")
460
+ return "orphaned";
461
+ if (status === "lost")
462
+ return "lost";
463
+ if (status === "completed" || status === "failed" || status === "killed" || status === "exited") {
464
+ return "terminal";
465
+ }
466
+ if (status === "running")
467
+ return supervised === false ? "unknown" : "supervised";
468
+ return "unknown";
469
+ }
470
+ function fmtAge(ms) {
471
+ let value = ms;
472
+ if (!Number.isFinite(value) || value < 0)
473
+ value = 0;
474
+ const s = Math.floor(value / 1000);
475
+ if (s < 60)
476
+ return `${s}s`;
477
+ const m = Math.floor(s / 60);
478
+ if (m < 60)
479
+ return `${m}m`;
480
+ const h = Math.floor(m / 60);
481
+ return `${h}h${m % 60}m`;
482
+ }
483
+ /**
484
+ * Compute a multi-dimensional health observation. Pure.
485
+ */
486
+ export function observeRunHealth(input) {
487
+ const thresholds = resolveHealthThresholds(input.thresholds);
488
+ const now = input.now;
489
+ const facts = input.facts;
490
+ const rawLog = input.rawLog ?? {};
491
+ // ---- tool dimension
492
+ const active = facts.activeTools[facts.activeTools.length - 1];
493
+ let toolState = "idle";
494
+ let toolAge;
495
+ if (active) {
496
+ const start = active.startedAt ?? facts.lastToolAt ?? facts.lastMeaningfulAt;
497
+ toolAge = typeof start === "number" ? Math.max(0, now - start) : undefined;
498
+ toolState = toolAge !== undefined && toolAge >= thresholds.longToolMs
499
+ ? "long_running"
500
+ : "running";
501
+ }
502
+ // ---- compaction dimension
503
+ let compactionState = "idle";
504
+ let compactionAge;
505
+ if (facts.compacting) {
506
+ const start = facts.compactionStartedAt ?? facts.lastMeaningfulAt;
507
+ compactionAge = typeof start === "number" ? Math.max(0, now - start) : undefined;
508
+ compactionState = compactionAge !== undefined && compactionAge >= thresholds.longCompactionMs
509
+ ? "long_compacting"
510
+ : "compacting";
511
+ }
512
+ // ---- model dimension
513
+ const modelState = facts.model.state;
514
+ let listWarning;
515
+ if (modelState === "retrying")
516
+ listWarning = "model retrying";
517
+ else if (modelState === "error")
518
+ listWarning = "model error";
519
+ // recovered → listWarning stays undefined (cleared from compact/list)
520
+ // ---- activity (residual stale)
521
+ const anchor = facts.lastMeaningfulAt ?? input.startedAt;
522
+ const meaningfulAgeMs = typeof anchor === "number" ? Math.max(0, now - anchor) : undefined;
523
+ const explainedByPhase = toolState !== "idle"
524
+ || compactionState !== "idle"
525
+ || modelState === "retrying"
526
+ || modelState === "error";
527
+ const terminal = input.status === "failed"
528
+ || input.status === "completed"
529
+ || input.status === "killed"
530
+ || input.status === "lost"
531
+ || input.status === "exited";
532
+ const stall = observeStall({
533
+ now,
534
+ lastProgressAt: facts.lastMeaningfulAt,
535
+ startedAt: input.startedAt,
536
+ // Terminal work and explicit model/tool/compaction phases can be quiet,
537
+ // but neither is an unexplained stalled worker.
538
+ exempt: terminal || explainedByPhase,
539
+ thresholds: { quietMs: thresholds.quietMs, stallMs: thresholds.staleMs },
540
+ });
541
+ const activity = stall.state === "stalled"
542
+ ? "stale"
543
+ : stall.state === "quiet"
544
+ ? "quiet"
545
+ // Legacy metadata without any timestamp remains conservative.
546
+ : stall.state === "unknown" && !terminal && !explainedByPhase
547
+ ? "stale"
548
+ : "healthy";
549
+ const process = {
550
+ liveness: processLiveness(input.status, input.process?.supervised),
551
+ supervised: input.process?.supervised,
552
+ };
553
+ const compaction = {
554
+ state: compactionState,
555
+ startedAt: facts.compactionStartedAt,
556
+ ageMs: compactionAge,
557
+ last: facts.lastCompaction,
558
+ };
559
+ const tool = {
560
+ state: toolState,
561
+ active,
562
+ ageMs: toolAge,
563
+ };
564
+ const model = {
565
+ state: modelState,
566
+ listWarning,
567
+ lastError: facts.model.lastError,
568
+ errorHistory: [...facts.model.errorHistory],
569
+ retry: facts.model.retry,
570
+ // longModelCall omitted — unsupported without explicit lifecycle events (#64)
571
+ };
572
+ const compactFacts = buildCompactFacts({
573
+ activity,
574
+ compaction,
575
+ tool,
576
+ model,
577
+ });
578
+ return {
579
+ status: input.status,
580
+ process,
581
+ activity,
582
+ lastMeaningfulAt: facts.lastMeaningfulAt,
583
+ meaningfulAgeMs,
584
+ compaction,
585
+ tool,
586
+ model,
587
+ rawLog,
588
+ compactFacts,
589
+ thresholds,
590
+ };
591
+ }
592
+ function buildCompactFacts(p) {
593
+ const facts = [];
594
+ if (p.compaction.state === "long_compacting") {
595
+ const age = p.compaction.ageMs !== undefined ? ` ${fmtAge(p.compaction.ageMs)}` : "";
596
+ facts.push(`long compacting${age}`.trim());
597
+ }
598
+ else if (p.compaction.state === "compacting") {
599
+ const age = p.compaction.ageMs !== undefined ? ` ${fmtAge(p.compaction.ageMs)}` : "";
600
+ facts.push(`compacting${age}`.trim());
601
+ }
602
+ if (p.tool.state !== "idle" && p.tool.active) {
603
+ const age = p.tool.ageMs !== undefined ? ` ${fmtAge(p.tool.ageMs)}` : "";
604
+ const name = p.tool.active.toolName;
605
+ facts.push(p.tool.state === "long_running" ? `long ${name}${age}`.trim() : `${name}${age}`.trim());
606
+ }
607
+ if (p.model.listWarning)
608
+ facts.push(p.model.listWarning);
609
+ // Residual stale only when nothing more specific is already listed.
610
+ if (p.activity === "stale" && facts.length === 0)
611
+ facts.push("stale");
612
+ return facts.slice(0, 2);
613
+ }