pi-better-subagents 0.32.6 → 0.33.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 (50) hide show
  1. package/README.md +13 -0
  2. package/assignment-outcomes.ts +14 -3
  3. package/assignment-projection.mjs +13 -17
  4. package/assignment-report.ts +92 -0
  5. package/child-operations.ts +2 -0
  6. package/child-ownership.ts +1 -1
  7. package/health-observation.ts +9 -4
  8. package/index.ts +142 -77
  9. package/list.mjs +3 -2
  10. package/navigator.mjs +2 -1
  11. package/operation-bridge-types.ts +18 -1
  12. package/output-payload.ts +4 -1
  13. package/package.json +4 -2
  14. package/parse.ts +7 -6
  15. package/registry.ts +4 -2
  16. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  17. package/runtime-client/artifacts/darwin-arm64.json +1 -0
  18. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  19. package/runtime-client/artifacts/darwin-x64.json +1 -0
  20. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  21. package/runtime-client/artifacts/linux-arm64.json +1 -0
  22. package/runtime-client/artifacts/linux-x64.gz +0 -0
  23. package/runtime-client/artifacts/linux-x64.json +1 -0
  24. package/runtime-client/scripts/private-runtime/format.mjs +90 -0
  25. package/runtime-client/src/daemon-owner.mjs +217 -0
  26. package/runtime-client/src/runtime/client.mjs +130 -0
  27. package/runtime-client/src/runtime/root.mjs +41 -0
  28. package/runtime-client/src/runtime/socket.mjs +9 -0
  29. package/runtime-client/src/runtime/status-cli.mjs +14 -0
  30. package/runtime-client/src/runtime/work-client.mjs +88 -0
  31. package/runtime-client/src/startup/artifact.mjs +76 -0
  32. package/runtime-client/src/startup/install.mjs +184 -0
  33. package/runtime-client/src/startup/managed-types.mjs +1 -0
  34. package/runtime-client/src/startup/runtime.mjs +120 -0
  35. package/session-store.ts +85 -30
  36. package/shared-harness-settings.ts +4 -2
  37. package/shared-log-utils.ts +18 -7
  38. package/shared-navigator.ts +26 -8
  39. package/shared-operation-coordinator/assignment-observation.mjs +63 -3
  40. package/shared-operation-coordinator/index.ts +2 -0
  41. package/shared-operation-coordinator/src/errors.ts +2 -0
  42. package/shared-operation-coordinator/src/schema.ts +20 -0
  43. package/shared-operation-coordinator/src/store.ts +35 -0
  44. package/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  45. package/shared-work-client.d.mts +9 -0
  46. package/shared-work-client.mjs +88 -0
  47. package/tools.ts +53 -3
  48. package/work-observation.ts +177 -0
  49. package/worker-operations-host.ts +3 -0
  50. package/worker-waits.ts +50 -13
package/README.md CHANGED
@@ -6,6 +6,19 @@
6
6
 
7
7
  Use `pi-better-subagents` when you want Pi to launch independent agent work without blocking the current conversation. Each subagent runs in its own `pi -p` child process, reports back when finished, and keeps durable logs for later inspection.
8
8
 
9
+ ## Runtime Status
10
+
11
+ Run `pi-subagents-runtime-status` to ensure the manifest-pinned local server and
12
+ print its canonical agent root, build, Node version, instance and capabilities as JSON.
13
+ This command does not create a hosted Pi session or require Harness.
14
+ The first use installs a verified private Node 24 and locked server dependencies.
15
+ Set `PI_OFFLINE=1` to require the cached runtime without downloads.
16
+ `PI_CODING_AGENT_DIR` selects the agent root; `PI_SERVER_DIR` selects the initial
17
+ transport directory. Later calls for the same canonical root reuse the registered
18
+ transport, including calls from Background Tasks or another package installation.
19
+ An incompatible or unhealthy live owner is an error, not a reason to replace it.
20
+ The API is `runtime-client/src/runtime/client.mjs`, exporting `ensureRuntime`.
21
+
9
22
  ## Screenshots
10
23
 
11
24
  <p><img src="https://raw.githubusercontent.com/1aboveio/pi-better-harness/main/docs/images/package-gallery/pi-better-subagents.png" alt="pi-better-subagents rendered in Pi" width="49%" /><img src="https://raw.githubusercontent.com/1aboveio/pi-better-harness/main/docs/images/package-gallery/overview/pi-better-subagents.png" alt="pi-better-subagents package overview" width="49%" /></p>
@@ -7,6 +7,7 @@ import type { RunMeta } from "./registry.ts";
7
7
  import { processStartToken } from "./registry.ts";
8
8
  import type { PermissionSnapshot } from "./permission-policy.ts";
9
9
  import { credentialFilePaths } from "./shared-sandbox-core.ts";
10
+ import { readAssignmentReport } from "./assignment-report.ts";
10
11
 
11
12
  export const ASSIGNMENT_OUTCOMES_VERSION = 1;
12
13
  const closedHosts = (globalThis as typeof globalThis & { __assignmentOutcomeClosedHosts?: Set<string> }).__assignmentOutcomeClosedHosts ??= new Set<string>();
@@ -62,13 +63,23 @@ export function commitAssignmentTerminal(meta: RunMeta, recoveryFailure = false)
62
63
  if (!recoveryFailure && meta.status !== "killed" && meta.operations?.resumeLaunchToken && waits.some((w) => !w.acknowledgement && ["resuming", "ready"].includes(w.phase))) return null;
63
64
  // A coherent attempt exit does not establish interpretation or completion.
64
65
  if (meta.status === "completed" && waits.some((w) => !w.acknowledgement)) return null;
66
+ let report = null;
67
+ let invalidReport = "";
68
+ try { report = readAssignmentReport(meta); }
69
+ catch { if (meta.status === "completed") invalidReport = "Assignment completion is unverified: retained report evidence is unavailable or changed."; }
70
+ const complete = meta.status === "completed" && (report ? report.status === "complete"
71
+ : !invalidReport && waits.some((w) => w.acknowledgement?.disposition === "assignment-complete"));
65
72
  return store.recordAssignmentOutcome({ ...binding, revision: 1,
66
- outcome: meta.status === "completed" ? "succeeded" : meta.status === "killed" ? "cancelled" : "failed",
67
- reason: meta.failureReason || (meta.status === "completed" ? "Assigned work and required interpretation are complete." : `Assignment ended ${meta.status}; retained attempt evidence is available.`),
73
+ outcome: complete ? "succeeded" : meta.status === "killed" ? "cancelled" : "failed",
74
+ reason: meta.failureReason || invalidReport || (meta.status === "completed" && report ? report.reason : complete ? "Assigned work and required interpretation are complete."
75
+ : meta.status === "completed" ? "Assignment completion is unverified: the attempt exited without an evidence-backed completion decision. Inspect retained output and continue unfinished work or report a concrete blocker."
76
+ : `Assignment ended ${meta.status}; retained attempt evidence is available.`),
68
77
  processUncertain: meta.status === "lost" || typeof meta.exitCode !== "number"
69
78
  || waits.some((w) => w.dependencies.some((d) => d.terminalRevision === 0)
70
79
  || store.listResumeClaims({ waitId: w.waitId, generation: w.generation, state: "published" }).length > 0),
71
- evidence: [{ kind: "log", ref: meta.logPath, summary: `Attempt ${meta.id}: ${meta.status}` }],
80
+ evidence: [{ kind: "log", ref: meta.logPath, summary: `Attempt ${meta.id}: ${meta.status}` },
81
+ ...(report ? [{ kind: "artifact" as const, ref: meta.assignmentReport!.path, summary: report.reason },
82
+ ...report.evidence.map((e) => ({ kind: "artifact" as const, ref: e.path, summary: e.explanation }))] : [])],
72
83
  waits: waits.map((w) => ({ waitId: w.waitId, generation: w.generation, cancelEpoch: w.cancelEpoch })),
73
84
  });
74
85
  });
@@ -1,10 +1,17 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
2
3
  import { readFileSync, readdirSync, statSync } from "node:fs";
3
4
  import { homedir, tmpdir } from "node:os";
4
5
  import { join } from "node:path";
5
6
  import { readAssignmentWaits } from "./shared-operation-coordinator/assignment-observation.mjs";
6
7
 
7
8
  export const ASSIGNMENT_STATES = ["running", "waiting", "completed", "failed", "cancelled"];
9
+ const observations = new AsyncLocalStorage();
10
+
11
+ /** Bind an immutable observation to one read call, never to a supervision loop. */
12
+ export function withAssignmentObservations(rows, read) {
13
+ return observations.run(new Map(rows.map(row => [row.meta.id, row.assignment])), read);
14
+ }
8
15
 
9
16
  /** A projection revision is a content-addressed semantic token, not a clock. */
10
17
  export function projectAssignment(meta, processStatus, observation = { verified: true, waits: [] }) {
@@ -57,19 +64,7 @@ export function projectAssignment(meta, processStatus, observation = { verified:
57
64
 
58
65
  /** All consumers use the same lineage and authoritative wait read. Park caches are hints only. */
59
66
  export function assignmentFor(meta, processStatus = meta.status, options = {}) {
60
- return assignmentFromSnapshot(meta, processStatus, options, () => readAttempts(options));
61
- }
62
-
63
- function readAttempts(options) {
64
- const base = options.baseDir ?? join(tmpdir(), "pi-better-subagents");
65
- const attempts = [];
66
- try {
67
- for (const id of readdirSync(join(base, "runs"))) {
68
- const candidate = readAttempt(base, id);
69
- if (candidate) attempts.push(candidate);
70
- }
71
- } catch { /* Registry gaps cannot establish a newer attempt. */ }
72
- return attempts;
67
+ return createAssignmentProjector(options)(meta, processStatus);
73
68
  }
74
69
 
75
70
  function readAttempt(base, id) {
@@ -188,6 +183,7 @@ export function createAssignmentProjector(options = {}) {
188
183
  let prepared;
189
184
  const snapshots = new Map();
190
185
  const readSnapshot = (meta) => {
186
+ if (options.attempts) return options.attempts;
191
187
  const key = conversationKey(meta.sessionId, meta.cwd);
192
188
  if (!snapshots.has(key)) {
193
189
  prepared ??= prepareAttemptIndex(options);
@@ -195,7 +191,7 @@ export function createAssignmentProjector(options = {}) {
195
191
  }
196
192
  return snapshots.get(key);
197
193
  };
198
- return (meta, processStatus = meta.status) => assignmentFromSnapshot(meta, processStatus, options,
194
+ return (meta, processStatus = meta.status) => observations.getStore()?.get(meta.id) ?? assignmentFromSnapshot(meta, processStatus, options,
199
195
  () => readSnapshot(meta));
200
196
  }
201
197
 
@@ -232,7 +228,7 @@ function assignmentFromSnapshot(meta, processStatus, options, readSnapshot) {
232
228
  const status = current.id === meta.id ? processStatus : current.status;
233
229
  const sessionId = current.operations?.conversationId ?? current.sessionId;
234
230
  const observation = options.observation ?? (sessionId && (current.assignment || current.operations || current.park)
235
- ? readAssignmentWaits(options.coordinatorPath ?? join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite"),
231
+ ? (options.observe ?? ((owner) => readAssignmentWaits(options.coordinatorPath ?? join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite"), owner)))(
236
232
  { sessionId, workspace: current.operations?.workspace ?? current.cwd,
237
233
  ...(current.assignment ? { assignmentId: current.assignment.assignmentId } : {}),
238
234
  attemptIds: [...lineage.keys()], waitRefs: [...lineage.values()].flatMap((attempt) =>
@@ -243,6 +239,6 @@ function assignmentFromSnapshot(meta, processStatus, options, readSnapshot) {
243
239
  return projectAssignment(current, status, observation);
244
240
  }
245
241
 
246
- export function assignmentDiagnostic(assignment) {
247
- return `Assignment ${assignment.state} r${assignment.revision}: ${assignment.reason} Process ${assignment.processStatus}; termination ${assignment.termination}. Evidence: ${assignment.evidence.join(", ")}`;
242
+ export function assignmentDiagnostic(assignment, options = {}) {
243
+ return `Assignment ${assignment.state} r${assignment.revision}: ${assignment.reason} Process ${assignment.processStatus}; termination ${assignment.termination}.${options.includeEvidence === false ? "" : ` Evidence: ${assignment.evidence.join(", ")}`}`;
248
244
  }
@@ -0,0 +1,92 @@
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, mkdirSync, openSync, readSync, realpathSync, writeFileSync } from "node:fs";
3
+ import { isAbsolute, join, relative, resolve } from "node:path";
4
+ import { homedir } from "node:os";
5
+ import { runDir, writeMeta, type RunMeta } from "./registry.ts";
6
+ import { credentialFilePaths } from "./shared-sandbox-core.ts";
7
+ import type { PermissionSnapshot, PermissionProfile } from "./permission-policy.ts";
8
+
9
+ const hash = (bytes: string | Buffer) => createHash("sha256").update(bytes).digest("hex");
10
+ const inside = (root: string, path: string) => { const rel = relative(root, path); return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); };
11
+ function retainedBytes(path: string, limit: number): Buffer {
12
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
13
+ try {
14
+ const stat = fstatSync(fd);
15
+ if (!stat.isFile() || stat.size > limit) throw new Error("Retained assignment evidence exceeds its bound.");
16
+ const bytes = Buffer.alloc(stat.size);
17
+ if (readSync(fd, bytes, 0, bytes.length, 0) !== bytes.length) throw new Error("Retained assignment evidence changed.");
18
+ return bytes;
19
+ } finally { closeSync(fd); }
20
+ }
21
+ export interface AssignmentReport {
22
+ version: 1; assignmentId: string; attemptId: string; requestDigest: string; status: "complete" | "incomplete"; reason: string;
23
+ evidence: Array<{ path: string; digest: string; source: string; explanation: string }>;
24
+ }
25
+
26
+ /** Runs synchronously under the authenticated handler: no yield between authority and persistence. */
27
+ export function recordAssignmentReport(id: string, input: unknown, assertAuthority: () => RunMeta, current?: PermissionSnapshot) {
28
+ const meta = assertAuthority();
29
+ const report = input as { status: string; reason: string; evidence: Array<{ path: string; explanation: string }> };
30
+ if (!["complete", "incomplete"].includes(report.status) || !report.reason?.trim() || report.reason.length > 2048
31
+ || !Array.isArray(report.evidence) || report.evidence.length < 1 || report.evidence.length > 4) throw new Error("Invalid assignment report.");
32
+ const root = realpathSync(meta.cwd);
33
+ const directory = join(runDir(id), "assignment-report-v1");
34
+ const captured = (meta.operations?.policy.sandbox as { permissions?: Partial<PermissionProfile> } | null)?.permissions;
35
+ if (captured && captured.projectFiles !== "read" && captured.projectFiles !== "read-write") throw new Error("Captured assignment evidence read permission refused.");
36
+ for (const policy of [current?.permissions, current?.subagentPermissions]) {
37
+ if (policy?.enabled && policy.projectFiles !== "read" && policy.projectFiles !== "read-write") throw new Error("Current assignment evidence read permission refused.");
38
+ }
39
+ if (meta.operations?.policy.sandbox && !current?.permissions) throw new Error("Current assignment evidence read authority unavailable.");
40
+ const requestDigest = hash(JSON.stringify([report.status, report.reason, report.evidence.map((e) => [e.path, e.explanation])]));
41
+ if (meta.assignmentReport) {
42
+ const accepted = readAssignmentReport(meta)!;
43
+ if (accepted.requestDigest !== requestDigest) throw new Error("Conflicting assignment report refused.");
44
+ return { reportId: meta.assignmentReport.digest, status: accepted.status, note: "Report retained. Assignment terminalization after exit and exact parent disposition remain separate." };
45
+ }
46
+ const snapshots = report.evidence.map((e) => {
47
+ if (!e.path || !e.explanation?.trim() || e.explanation.length > 1024) throw new Error("Evidence needs a bounded explanation.");
48
+ const source = realpathSync(resolve(root, e.path));
49
+ if (!inside(root, source) || credentialFilePaths(homedir()).some((p) => inside(p, source))) throw new Error("Foreign or credential assignment evidence refused.");
50
+ const fd = openSync(source, constants.O_RDONLY | constants.O_NOFOLLOW);
51
+ try {
52
+ const stat = fstatSync(fd);
53
+ if (!stat.isFile() || stat.size > 65536) throw new Error("Assignment evidence must be a file of at most 65536 bytes.");
54
+ const bytes = Buffer.alloc(stat.size);
55
+ if (readSync(fd, bytes, 0, bytes.length, 0) !== bytes.length) throw new Error("Assignment evidence changed during capture.");
56
+ return { bytes, digest: hash(bytes), source, explanation: e.explanation };
57
+ } finally { closeSync(fd); }
58
+ });
59
+ const retained: AssignmentReport = { version: 1, assignmentId: meta.assignment!.assignmentId, attemptId: id, requestDigest,
60
+ status: report.status as AssignmentReport["status"], reason: report.reason,
61
+ evidence: snapshots.map(({ digest, source, explanation }) => ({ path: join(directory, digest), digest, source, explanation })) };
62
+ const text = JSON.stringify(retained);
63
+ if (Buffer.byteLength(text) > 65536) throw new Error("Assignment report exceeds its retained metadata bound.");
64
+ const digest = hash(text);
65
+ const latest = assertAuthority();
66
+ if (latest.assignmentReport) {
67
+ if (latest.assignmentReport.digest !== digest) throw new Error("Conflicting assignment report refused.");
68
+ readAssignmentReport(latest);
69
+ } else {
70
+ mkdirSync(directory, { recursive: true });
71
+ for (const snapshot of snapshots) writeFileSync(join(directory, snapshot.digest), snapshot.bytes, { mode: 0o600 });
72
+ const path = join(directory, `${digest}.json`);
73
+ writeFileSync(path, text, { mode: 0o600 });
74
+ writeMeta({ ...latest, assignmentReport: { version: 1, assignmentId: retained.assignmentId, attemptId: id, digest, path } });
75
+ }
76
+ return { reportId: digest, status: report.status, note: "Report retained. Assignment terminalization after exit and exact parent disposition remain separate." };
77
+ }
78
+
79
+ export function readAssignmentReport(meta: RunMeta): AssignmentReport | null {
80
+ const ref = meta.assignmentReport;
81
+ if (!ref) return null;
82
+ if (ref.version !== 1 || !/^[a-f0-9]{64}$/.test(ref.digest) || ref.assignmentId !== meta.assignment?.assignmentId || ref.attemptId !== meta.id
83
+ || ref.path !== join(runDir(meta.id), "assignment-report-v1", `${ref.digest}.json`)) throw new Error("Foreign assignment report reference.");
84
+ const text = retainedBytes(ref.path, 65536).toString("utf8");
85
+ if (hash(text) !== ref.digest) throw new Error("Retained assignment report changed.");
86
+ const report = JSON.parse(text) as AssignmentReport;
87
+ if (report.version !== 1 || report.assignmentId !== ref.assignmentId || report.attemptId !== meta.id) throw new Error("Foreign assignment report.");
88
+ for (const e of report.evidence) {
89
+ if (!/^[a-f0-9]{64}$/.test(e.digest) || e.path !== join(runDir(meta.id), "assignment-report-v1", e.digest) || hash(retainedBytes(e.path, 65536)) !== e.digest) throw new Error("Retained assignment evidence changed.");
90
+ }
91
+ return report;
92
+ }
@@ -509,6 +509,7 @@ export function verifyDescriptor(value: unknown, config: Pick<ChildOperationBrid
509
509
  function validateCapabilities(value: unknown): OperationBridgeCapabilities {
510
510
  if (!value || typeof value !== "object") throw new OperationBridgeError("invalid-request", "parent handshake has no capabilities");
511
511
  const record = value as Record<string, unknown>;
512
+ if (record.reportAssignment !== undefined && typeof record.reportAssignment !== "boolean") throw new OperationBridgeError("invalid-request", "parent reporting capability is invalid");
512
513
  const background = record.background;
513
514
  if (!background || typeof background !== "object") throw new OperationBridgeError("invalid-request", "parent handshake has no background capabilities");
514
515
  const bg = background as Record<string, unknown>;
@@ -519,6 +520,7 @@ function validateCapabilities(value: unknown): OperationBridgeCapabilities {
519
520
  if (typeof record[key] !== "boolean") throw new OperationBridgeError("invalid-request", `parent capability ${key} is invalid`);
520
521
  }
521
522
  return Object.freeze({
523
+ ...(typeof record.reportAssignment === "boolean" ? { reportAssignment: record.reportAssignment } : {}),
522
524
  background: Object.freeze({
523
525
  spawn: bg.spawn as boolean,
524
526
  watch: bg.watch as boolean,
@@ -4,7 +4,7 @@ import { STEER_FILE_ENV } from "./child-steer.ts";
4
4
  import { supportsPromptSections } from "./shared-execution-policy.ts";
5
5
  import { restrictContextFilesToWorktree } from "./shared-worktree-context.ts";
6
6
 
7
- export const WORKER_HANDOFF = "Worker ownership: complete your assigned implementation or diagnosis, run focused checks, push only when authorized, write the requested result, then return. Pending CI is a handoff, not a failed implementation or a CI pass. The coordinator owns CI/PR monitoring, review scheduling, readiness, enqueueing and merge. Do not start external delivery watchers or background monitoring. Short status reads and failed-log retrieval for diagnosis are allowed. Legitimate local tests and builds may run to completion within their command limits. Use Bash for short diagnostic commands and focused checks needed to implement the change. When supervised background tools are available, retain ownership of assigned validation: launch a known long command with bg_task_spawn or repeated observation with bg_task_watch, continue independent work, then call wait_for_operations to park when no independent work remains. On continuation, inspect the operation's terminal evidence and acknowledge its interpretation before continuing the assignment. Parking is a saved-conversation dependency, not a request for the parent model to relay commands or results. An explicit restricted tool loadout may omit background support; return the exact command, cwd, required environment variable names (never secret values), current evidence and remaining validation to the coordinator. Do not emulate background execution with polling, sleep loops, nohup or shell detachment. Established command-only operations and external delivery monitoring belong to the coordinator's background tools.";
7
+ export const WORKER_HANDOFF = "Worker ownership: complete your assigned implementation or diagnosis, run focused checks, push only when authorized, write the requested result, then return. Pending CI is a handoff, not a failed implementation or a CI pass. The coordinator owns CI/PR monitoring, review scheduling, readiness, enqueueing and merge. Do not start external delivery watchers or background monitoring. Short status reads and failed-log retrieval for diagnosis are allowed. Legitimate local tests and builds may run to completion within their command limits. Use Bash for short diagnostic commands and focused checks needed to implement the change. When supervised background tools are available, retain ownership of assigned validation: launch a known long command with bg_task_spawn or repeated observation with bg_task_watch, continue independent work, then call wait_for_operations to park when no independent work remains. On continuation, inspect the operation's terminal evidence and acknowledge its interpretation before continuing the assignment. Parking is a saved-conversation dependency, not a request for the parent model to relay commands or results. An explicit restricted tool loadout may omit background support; return the exact command, cwd, required environment variable names (never secret values), current evidence and remaining validation to the coordinator. Do not emulate background execution with polling, sleep loops, nohup or shell detachment. Established command-only operations and external delivery monitoring belong to the coordinator's background tools. When report_assignment_result is available, call it before your final answer with your explicit complete or incomplete judgment and retained workspace artifact evidence. Reporting does not interpret waits or record parent acceptance; do not report complete while required work remains.";
8
8
  export const WORKER_HANDOFF_SECTION = "worker_handoff";
9
9
  const REFUSAL = "Worker ownership: CI/PR monitoring belongs to the coordinator. Return the PR/run ID, pushed HEAD and current evidence with CI pending; do not retry the watcher through another tool or script. Local tests/builds and short diagnostic status/log reads remain allowed.";
10
10
  const WATCH_SCRIPTS = new Set(["watch-pr-delivery.mjs", "watch-delivery.mjs", "watch-candidate-delivery.mjs"]);
@@ -71,6 +71,10 @@ export function resolveHealthThresholds(
71
71
 
72
72
  /** Load thresholds from extension config.json (best-effort). */
73
73
  export function loadHealthThresholdsFromConfig(config: SubagentConfig = loadConfig()): HealthThresholds {
74
+ return healthThresholdsForConfig(config);
75
+ }
76
+
77
+ export function healthThresholdsForConfig(config: SubagentConfig): HealthThresholds {
74
78
  return resolveHealthThresholds({
75
79
  ...config,
76
80
  healthQuietMs: config.healthQuietMs ?? envDuration("PI_BETTER_STALL_QUIET_MS"),
@@ -525,9 +529,9 @@ function trimToBudget(state: FactLogState): void {
525
529
  */
526
530
  export function extractChildEventFactsFromLog(
527
531
  id: string,
528
- opts: { now?: number; logText?: string } = {},
532
+ opts: { now?: number; logText?: string; logPath?: string } = {},
529
533
  ): { facts: ChildEventFacts; rawLog: RawLogDiagnostic } {
530
- const path = logPathFor(id);
534
+ const path = opts.logPath ?? logPathFor(id);
531
535
  const rawLog: RawLogDiagnostic = {};
532
536
  try {
533
537
  const st = statSync(path);
@@ -548,7 +552,8 @@ export function extractChildEventFactsFromLog(
548
552
  return { facts: extractChildEventFacts(events), rawLog };
549
553
  }
550
554
 
551
- const previous = factLogStates.get(id);
555
+ const key = opts.logPath ?? id;
556
+ const previous = factLogStates.get(key);
552
557
  const read = readAppendedLines(path, previous?.cursor, maxHealthReadBytes());
553
558
  if (read.error !== undefined) {
554
559
  rawLog.error = rawLog.error ?? read.error;
@@ -568,7 +573,7 @@ export function extractChildEventFactsFromLog(
568
573
  for (const size of parsed.sizes) state.bytes += size;
569
574
  trimToBudget(state);
570
575
  }
571
- rememberState(id, state);
576
+ rememberState(key, state);
572
577
 
573
578
  if (state.truncated) rawLog.windowTruncated = true;
574
579
  if (state.dropped) rawLog.eventsDropped = true;