pi-better-server 0.6.0 → 0.7.1

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 (142) hide show
  1. package/package.json +4 -3
  2. package/scripts/measure-full-runtime/frontend.ts +10 -2
  3. package/scripts/measure-full-runtime.mjs +2 -0
  4. package/src/codex/return.ts +3 -2
  5. package/src/detach/extension.ts +20 -3
  6. package/src/event-log.ts +40 -12
  7. package/src/hosted-session.ts +11 -5
  8. package/src/remote-client/packages.ts +1 -4
  9. package/src/runtime/background-tools.ts +54 -8
  10. package/src/runtime/background.ts +16 -4
  11. package/src/runtime/domain/background/process.mjs +49 -11
  12. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  13. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  14. package/src/runtime/domain/background-service/index.domain.mjs +19 -0
  15. package/src/runtime/domain/background-service/index.ts +19 -0
  16. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
  17. package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
  18. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
  19. package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
  20. package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
  21. package/src/runtime/domain/background-service/observed-waits.ts +168 -24
  22. package/src/runtime/domain/background-service/process.domain.mjs +49 -11
  23. package/src/runtime/domain/background-service/process.ts +45 -11
  24. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  25. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  26. package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
  27. package/src/runtime/domain/background-service/runtime.ts +8 -73
  28. package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +2 -3
  29. package/src/runtime/domain/background-service/shared-harness-settings.ts +2 -5
  30. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
  31. package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
  32. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  33. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  34. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
  35. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
  36. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +1 -1
  37. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +1 -1
  38. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  39. package/src/runtime/domain/background-service/stall.ts +7 -4
  40. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  41. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  42. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  43. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  44. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
  45. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  46. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  47. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  48. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  49. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  50. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  51. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  52. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  53. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  54. package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
  55. package/src/runtime/domain/background-service/tools.ts +26 -16
  56. package/src/runtime/domain/background-service/types.ts +4 -2
  57. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  58. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  59. package/src/runtime/domain/catalog/catalog-preferences.mjs +1 -3
  60. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  61. package/src/runtime/domain/coordinator/src/store.mjs +5 -1
  62. package/src/runtime/domain/log-paths.mjs +8 -1
  63. package/src/runtime/domain/parse.mjs +9 -5
  64. package/src/runtime/domain/sandbox-policy/README.md +3 -3
  65. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  66. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +2 -3
  67. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +2 -5
  68. package/src/runtime/domain/session-store.mjs +7 -0
  69. package/src/runtime/domain/shared-harness-settings.mjs +2 -3
  70. package/src/runtime/domain/subagents/README.md +12 -10
  71. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
  72. package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
  73. package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
  74. package/src/runtime/domain/subagents/assignment-report.ts +20 -0
  75. package/src/runtime/domain/subagents/batch.mjs +13 -5
  76. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +1 -3
  77. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -5
  78. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  79. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  80. package/src/runtime/domain/subagents/config.domain.mjs +5 -0
  81. package/src/runtime/domain/subagents/config.ts +8 -2
  82. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  83. package/src/runtime/domain/subagents/continuation.ts +4 -2
  84. package/src/runtime/domain/subagents/extensions.mjs +1 -0
  85. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  86. package/src/runtime/domain/subagents/failures.ts +10 -2
  87. package/src/runtime/domain/subagents/finalization.domain.mjs +39 -32
  88. package/src/runtime/domain/subagents/finalization.ts +37 -30
  89. package/src/runtime/domain/subagents/git-workspace.domain.mjs +51 -6
  90. package/src/runtime/domain/subagents/git-workspace.ts +48 -6
  91. package/src/runtime/domain/subagents/index.domain.mjs +208 -75
  92. package/src/runtime/domain/subagents/index.ts +213 -75
  93. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +508 -0
  94. package/src/runtime/domain/subagents/isolated-workspace.ts +551 -0
  95. package/src/runtime/domain/subagents/list.mjs +2 -2
  96. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
  97. package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
  98. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  99. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  100. package/src/runtime/domain/subagents/package.json +4 -2
  101. package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
  102. package/src/runtime/domain/subagents/parse.ts +10 -5
  103. package/src/runtime/domain/subagents/registry.domain.mjs +31 -25
  104. package/src/runtime/domain/subagents/registry.ts +31 -13
  105. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  106. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  107. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  108. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  109. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  110. package/src/runtime/domain/subagents/session-store.ts +9 -0
  111. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  112. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  113. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
  114. package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
  115. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +2 -3
  116. package/src/runtime/domain/subagents/shared-harness-settings.ts +2 -5
  117. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
  118. package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
  119. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  120. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  121. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
  122. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
  123. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  124. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  125. package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
  126. package/src/runtime/domain/subagents/task-policy.ts +5 -1
  127. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  128. package/src/runtime/domain/subagents/tools.ts +4 -7
  129. package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
  130. package/src/runtime/domain/subagents/work-observation.ts +20 -1
  131. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  132. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  133. package/src/runtime/domain/subagents/workspace-prepare-worker.mjs +12 -0
  134. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  135. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  136. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  137. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  138. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  139. package/src/runtime/read-model.ts +4 -2
  140. package/src/runtime/root.ts +5 -2
  141. package/src/shared-ssh-core/index.ts +1 -1
  142. package/src/version.ts +1 -1
@@ -1,14 +1,11 @@
1
1
  // Generated from packages/harness-settings/index.ts. Do not edit directly.
2
2
  import { existsSync, lstatSync, realpathSync, readFileSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { randomUUID } from "node:crypto";
4
- import { createRequire } from "node:module";
5
4
  import { join } from "node:path";
6
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ // A static import lets the compiled Pi loader resolve dependencies of the settings lock.
7
+ import lockfile from "proper-lockfile";
7
8
 
8
- // Match Pi's settings lock without depending on a private SDK import.
9
- const lockfile = createRequire(import.meta.url)("proper-lockfile") as {
10
- lockSync(path: string, options: { realpath: boolean }): () => void;
11
- };
12
9
  const NAMESPACE = "piBetterHarness";
13
10
  export interface HarnessSettingsSeams { agentDir?: () => string }
14
11
 
@@ -72,6 +72,13 @@ export function durableSubagentRoot(env = process.env, home = homedir()) {
72
72
  const agentDir = env.PI_CODING_AGENT_DIR?.trim();
73
73
  return join(agentDir || join(home, ".pi", "agent"), "subagents");
74
74
  }
75
+ export function resultDir(id) {
76
+ return /^sa_[a-z0-9]+_[a-z0-9]+$/i.test(id) ? join(durableSubagentRoot(), "results", id) : undefined;
77
+ }
78
+ export function retainedLogPath(id) {
79
+ const dir = resultDir(id);
80
+ return dir && join(dir, "output.log");
81
+ }
75
82
  /** Durable `--session-dir` for new child launches. */
76
83
  export function durableSessionsDir() {
77
84
  return join(durableSubagentRoot(), "sessions");
@@ -2,11 +2,10 @@
2
2
  // Generated from packages/harness-settings/index.ts. Do not edit directly.
3
3
  import { existsSync, lstatSync, realpathSync, readFileSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { randomUUID } from "node:crypto";
5
- import { createRequire } from "node:module";
6
5
  import { join } from "node:path";
7
6
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
8
- // Match Pi's settings lock without depending on a private SDK import.
9
- const lockfile = createRequire(import.meta.url)("proper-lockfile");
7
+ // A static import lets the compiled Pi loader resolve dependencies of the settings lock.
8
+ import lockfile from "proper-lockfile";
10
9
  const NAMESPACE = "piBetterHarness";
11
10
  export function harnessSettingsPath(seams = {}) {
12
11
  return join((seams.agentDir ?? getAgentDir)(), "settings.json");
@@ -31,7 +31,8 @@ The API is `runtime-client/src/runtime/client.mjs`, exporting `ensureRuntime`.
31
31
  - Explicit tool allowlists for child sessions, and `skills` for prompt exposure: omit it to keep user-catalog discovery, pass `[]` for no skills, or pass absolute `SKILL.md` paths for exactly those. See [skill exposure](docs/usage.md#skill-exposure).
32
32
  - Durable logs, result retrieval, and [failure observations](docs/failure-observations.md) independent of lifecycle status. A live child handles its own tool errors; the parent is woken only for actionable incidents, and children can classify handled failures with `failure_disposition`.
33
33
  - Live background-work navigator for active runs.
34
- - Harness-owned run timing: every run gets independent factual alerts for a tool call left open (5 min) and for no progress (10 min), plus a 60-minute hard timeout. Change the timeout in `/subagents settings`; `0` disables it. Soft deadlines remain opt-in. Configure per spawn with `deadline_minutes`, `grace_minutes`, `max_minutes`, `tool_wait_minutes`, `stuck_minutes`, globally in `config.json` / `PI_SUBAGENT_*_MINUTES`, or in `/subagents settings`. See [usage notes](docs/usage.md#run-timing-deadline-ceiling-tool-wait-stuck).
34
+ - Git writers start in separate Clones by default. **Git workspace** in `/subagents settings` also offers Worktree. Results carry the working directory or a recoverable copy, including incomplete work. [Workspace recovery](docs/usage.md#git-workspaces)
35
+ - Harness-owned run timing: every run gets independent factual alerts for a tool call left open (5 min) and for no progress (10 min), plus a 60-minute hard timeout. Choose a duration or **No limit** under **Run timeout** in `/subagents settings`. Soft deadlines remain opt-in. Configure per spawn with `deadline_minutes`, `grace_minutes`, `max_minutes`, `tool_wait_minutes`, `stuck_minutes`, globally in `config.json` / `PI_SUBAGENT_*_MINUTES`, or in `/subagents settings`. See [usage notes](docs/usage.md#run-timing-deadline-ceiling-tool-wait-stuck).
35
36
 
36
37
  Every single or batch launch automatically joins one shared supervision watcher in the
37
38
  foreground Pi process. The last active run's exit or stop tears it down; a later
@@ -41,6 +42,8 @@ alerts retain supervision until their handoff is handled, so lost work is not si
41
42
 
42
43
  ## Worker Ownership
43
44
 
45
+ Every subagent follows the same contract for preserving work and delivering results to its parent. It applies to read-only investigations as well as tasks that create or change files. [Subagent lifecycle, preservation and delivery](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-subagents/docs/adr/0007-subagent-lifecycle.md)
46
+
44
47
  Every child launch, including clean, batch and unsandboxed launches, loads a Pi
45
48
  hook that keeps external CI/PR monitoring with its coordinator. Workers finish
46
49
  their assigned implementation or diagnosis, run focused checks, push only when
@@ -93,19 +96,18 @@ Linux confinement requires a usable `bubblewrap` backend and Pi SDK 0.82.1 or ne
93
96
 
94
97
  The user config sets `delegationMode` to `manual`, `adaptive` (default), or
95
98
  `coordinator`. `/subagents settings` (or `/subagents`) opens a settings page
96
- for delegation mode, the concurrent-subagent cap (default 6), the tool-wait
97
- alert (default 5 minutes), the no-progress alert (default 10 minutes), and the
98
- default skill exposure. The two time values are edited independently; `0` turns
99
- one alert off. Skill exposure cycles between Discover automatically and No skill
99
+ for delegation mode, the concurrent-subagent cap (default 6), and Git workspace
100
+ (Clone or Worktree). Run timeout supports a duration or **No limit**. The
101
+ tool-wait alert (default 5 minutes) and no-progress alert (default 10 minutes)
102
+ have separate intervals. Enter `0` to turn an alert off. Skill exposure cycles between Discover automatically and No skill
100
103
  catalog. The Selected skills row opens the same searchable checkbox picker used
101
104
  by `/agents`: it lists loaded skills by name and description, Space toggles one,
102
105
  Enter applies, and typing filters without dropping checked items. Saved paths
103
106
  missing from discovery stay visible as unavailable and survive apply. Zero
104
107
  checked applies No skill catalog, not discovery. Manual Add skill path remains
105
- available. The page names whether the current value comes from the saved config
106
- or this session. The session choice controls the next launch before Ctrl+S, and
107
- edits persist across reloads. Ctrl+S saves mode, cap, timing alerts, and skill
108
- exposure as defaults, and Reset to defaults clears session overrides, including
108
+ available. The Skill exposure row shows where the current skill setting comes from. The session choice controls the next launch before Ctrl+S, and
109
+ edits persist across reloads. Ctrl+S saves delegation, workspace, timing, and skill
110
+ settings as defaults, and Reset to defaults clears session overrides, including
109
111
  the skill list. Agents opens the same catalog as `/agents`; a definition that inherits
110
112
  skill exposure shows whether the live value comes from this session, saved
111
113
  config, or discovery, and an invalid draft is marked invalid rather than shown
@@ -194,7 +196,7 @@ The projection exposes an opaque semantic `revision`, readable `reason`, attempt
194
196
  identity, process status, termination evidence and retained evidence references.
195
197
  Compare revisions for equality; unchanged observations keep the same revision.
196
198
  Unavailable or unsupported coordinator reads report Waiting with an unverified
197
- reason. See the [projection contract](../../docs/adr/0022-assignment-progress-projection.md).
199
+ reason. See the [projection contract](https://github.com/1aboveio/pi-better-harness/blob/main/docs/adr/0022-assignment-progress-projection.md).
198
200
 
199
201
  - Repository: https://github.com/1aboveio/pi-better-harness
200
202
  - Detailed notes: https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-subagents/docs/usage.md
@@ -7,7 +7,7 @@ import { openSync, closeSync, fstatSync, readSync, realpathSync, constants } fro
7
7
  import { openStore, ownerDiff } from "./shared-operation-coordinator/index.domain.mjs";
8
8
  import { processStartToken, readMeta } from "./registry.domain.mjs";
9
9
  import { credentialFilePaths } from "./shared-sandbox-core.domain.mjs";
10
- import { readAssignmentReport } from "./assignment-report.domain.mjs";
10
+ import { assignmentReportOutcomeReason, readAssignmentReport } from "./assignment-report.domain.mjs";
11
11
  export const ASSIGNMENT_OUTCOMES_VERSION = 1;
12
12
  const closedHosts = globalThis.__assignmentOutcomeClosedHosts ??= new Set();
13
13
  export function createOutcomeHost() {
@@ -126,13 +126,10 @@ export function commitAssignmentTerminal(meta, recoveryFailure = false) {
126
126
  }
127
127
  const complete = meta.status === "completed" && (report ? report.status === "complete"
128
128
  : !invalidReport && waits.some((w) => w.acknowledgement?.disposition === "assignment-complete"));
129
- const reportReason = report?.status === "incomplete" ? `Assignment incomplete: ${report.reason}`
130
- + (report.blocker ? ` Blocked (${report.blocker.kind}): ${report.blocker.reason}.` : "")
131
- + (report.remainingWork ? ` Remaining work: ${report.remainingWork.join("; ")}.` : "") : report?.reason;
132
129
  try {
133
130
  return store.recordAssignmentOutcome({ ...binding, revision: 1,
134
131
  outcome: complete ? "succeeded" : meta.status === "killed" ? "cancelled" : "failed",
135
- reason: (meta.failureReason || invalidReport || (meta.status === "completed" && report ? reportReason : complete ? "Assigned work and required interpretation are complete."
132
+ reason: (meta.failureReason || invalidReport || (meta.status === "completed" && report ? assignmentReportOutcomeReason(report) : complete ? "Assigned work and required interpretation are complete."
136
133
  : meta.status === "completed" && meta.assignmentReportRejection ? `Assignment report rejected: ${meta.assignmentReportRejection.reason}`
137
134
  : 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."
138
135
  : `Assignment ended ${meta.status}; retained attempt evidence is available.`)).slice(0, 8192),
@@ -8,7 +8,7 @@ import type { RunMeta } from "./registry.ts";
8
8
  import { processStartToken, readMeta } from "./registry.ts";
9
9
  import type { PermissionSnapshot } from "./permission-policy.ts";
10
10
  import { credentialFilePaths } from "./shared-sandbox-core.ts";
11
- import { readAssignmentReport } from "./assignment-report.ts";
11
+ import { assignmentReportOutcomeReason, readAssignmentReport } from "./assignment-report.ts";
12
12
 
13
13
  export const ASSIGNMENT_OUTCOMES_VERSION = 1;
14
14
  const closedHosts = (globalThis as typeof globalThis & { __assignmentOutcomeClosedHosts?: Set<string> }).__assignmentOutcomeClosedHosts ??= new Set<string>();
@@ -91,12 +91,9 @@ export function commitAssignmentTerminal(meta: RunMeta, recoveryFailure = false)
91
91
  catch { if (meta.status === "completed") invalidReport = "Assignment completion is unverified: retained report evidence is unavailable or changed."; }
92
92
  const complete = meta.status === "completed" && (report ? report.status === "complete"
93
93
  : !invalidReport && waits.some((w) => w.acknowledgement?.disposition === "assignment-complete"));
94
- const reportReason = report?.status === "incomplete" ? `Assignment incomplete: ${report.reason}`
95
- + (report.blocker ? ` Blocked (${report.blocker.kind}): ${report.blocker.reason}.` : "")
96
- + (report.remainingWork ? ` Remaining work: ${report.remainingWork.join("; ")}.` : "") : report?.reason;
97
94
  try { return store.recordAssignmentOutcome({ ...binding, revision: 1,
98
95
  outcome: complete ? "succeeded" : meta.status === "killed" ? "cancelled" : "failed",
99
- reason: (meta.failureReason || invalidReport || (meta.status === "completed" && report ? reportReason : complete ? "Assigned work and required interpretation are complete."
96
+ reason: (meta.failureReason || invalidReport || (meta.status === "completed" && report ? assignmentReportOutcomeReason(report) : complete ? "Assigned work and required interpretation are complete."
100
97
  : meta.status === "completed" && meta.assignmentReportRejection ? `Assignment report rejected: ${meta.assignmentReportRejection.reason}`
101
98
  : 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."
102
99
  : `Assignment ended ${meta.status}; retained attempt evidence is available.`)).slice(0, 8192),
@@ -6,6 +6,7 @@ import { homedir } from "node:os";
6
6
  import { runDir, writeMeta } from "./registry.domain.mjs";
7
7
  import { credentialFilePaths } from "./shared-sandbox-core.domain.mjs";
8
8
  import { OperationBridgeError, redactSecret } from "./operation-bridge-types.domain.mjs";
9
+ import { requireText } from "./shared-operation-coordinator/src/validate.domain.mjs";
9
10
  const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
10
11
  const inside = (root, path) => { const rel = relative(root, path); return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); };
11
12
  function retainedBytes(path, limit) {
@@ -23,6 +24,23 @@ function retainedBytes(path, limit) {
23
24
  closeSync(fd);
24
25
  }
25
26
  }
27
+ export function assignmentReportOutcomeReason(report) {
28
+ if (report.status === "complete")
29
+ return report.reason;
30
+ return (`Assignment incomplete: ${report.reason}`
31
+ + (report.blocker ? ` Blocked (${report.blocker.kind}): ${report.blocker.reason}.` : "")
32
+ + (report.remainingWork ? ` Remaining work: ${report.remainingWork.join("; ")}.` : "")).slice(0, 8192);
33
+ }
34
+ function validateReportText(report) {
35
+ requireText("report.reason", report.reason, 2048);
36
+ for (const item of report.remainingWork ?? [])
37
+ requireText("report.remaining_work", item, 1024);
38
+ if (report.blocker)
39
+ requireText("report.blocker.reason", report.blocker.reason, 1024);
40
+ for (const evidence of report.evidence)
41
+ requireText("report.evidence.explanation", evidence.explanation, 1024);
42
+ requireText("report.outcome_reason", assignmentReportOutcomeReason(report), 8192);
43
+ }
26
44
  /** Runs synchronously under the authenticated handler: no yield between authority and persistence. */
27
45
  export function recordAssignmentReport(id, input, assertAuthority, current) {
28
46
  const meta = assertAuthority();
@@ -86,6 +104,7 @@ function retainAssignmentReport(id, input, meta, assertAuthority, current) {
86
104
  status: report.status, reason: report.reason,
87
105
  ...(report.remaining_work ? { remainingWork: report.remaining_work } : {}), ...(report.blocker ? { blocker: report.blocker } : {}),
88
106
  evidence: snapshots.map(({ digest, source, explanation, range }) => ({ path: join(directory, digest), digest, source, explanation, ...(range ? { range } : {}) })) };
107
+ validateReportText(retained);
89
108
  const text = JSON.stringify(retained);
90
109
  if (Buffer.byteLength(text) > 65536)
91
110
  throw new Error("Assignment report exceeds its retained metadata bound.");
@@ -170,5 +189,8 @@ export function readAssignmentReport(meta) {
170
189
  || e.range.offset + e.range.bytes > e.range.sourceBytes)))
171
190
  throw new Error("Retained assignment evidence changed.");
172
191
  }
192
+ // Older accepted reports may contain prose the terminal store cannot retain.
193
+ // Treat those as unverified evidence rather than throwing during finalization.
194
+ validateReportText(report);
173
195
  return report;
174
196
  }
@@ -6,6 +6,7 @@ import { runDir, writeMeta, type RunMeta } from "./registry.ts";
6
6
  import { credentialFilePaths } from "./shared-sandbox-core.ts";
7
7
  import type { PermissionSnapshot, PermissionProfile } from "./permission-policy.ts";
8
8
  import { OperationBridgeError, redactSecret } from "./operation-bridge-types.ts";
9
+ import { requireText } from "./shared-operation-coordinator/src/validate.ts";
9
10
 
10
11
  const hash = (bytes: string | Buffer) => createHash("sha256").update(bytes).digest("hex");
11
12
  const inside = (root: string, path: string) => { const rel = relative(root, path); return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); };
@@ -33,6 +34,21 @@ interface ReportInput {
33
34
  evidence: Array<{ path: string; explanation: string; offset?: number; max_bytes?: number }>;
34
35
  }
35
36
 
37
+ export function assignmentReportOutcomeReason(report: AssignmentReport): string {
38
+ if (report.status === "complete") return report.reason;
39
+ return (`Assignment incomplete: ${report.reason}`
40
+ + (report.blocker ? ` Blocked (${report.blocker.kind}): ${report.blocker.reason}.` : "")
41
+ + (report.remainingWork ? ` Remaining work: ${report.remainingWork.join("; ")}.` : "")).slice(0, 8192);
42
+ }
43
+
44
+ function validateReportText(report: AssignmentReport): void {
45
+ requireText("report.reason", report.reason, 2048);
46
+ for (const item of report.remainingWork ?? []) requireText("report.remaining_work", item, 1024);
47
+ if (report.blocker) requireText("report.blocker.reason", report.blocker.reason, 1024);
48
+ for (const evidence of report.evidence) requireText("report.evidence.explanation", evidence.explanation, 1024);
49
+ requireText("report.outcome_reason", assignmentReportOutcomeReason(report), 8192);
50
+ }
51
+
36
52
  /** Runs synchronously under the authenticated handler: no yield between authority and persistence. */
37
53
  export function recordAssignmentReport(id: string, input: unknown, assertAuthority: () => RunMeta, current?: PermissionSnapshot) {
38
54
  const meta = assertAuthority();
@@ -86,6 +102,7 @@ function retainAssignmentReport(id: string, input: unknown, meta: RunMeta, asser
86
102
  status: report.status as AssignmentReport["status"], reason: report.reason,
87
103
  ...(report.remaining_work ? { remainingWork: report.remaining_work } : {}), ...(report.blocker ? { blocker: report.blocker } : {}),
88
104
  evidence: snapshots.map(({ digest, source, explanation, range }) => ({ path: join(directory, digest), digest, source, explanation, ...(range ? { range } : {}) })) };
105
+ validateReportText(retained);
89
106
  const text = JSON.stringify(retained);
90
107
  if (Buffer.byteLength(text) > 65536) throw new Error("Assignment report exceeds its retained metadata bound.");
91
108
  const digest = hash(text);
@@ -152,5 +169,8 @@ export function readAssignmentReport(meta: RunMeta): AssignmentReport | null {
152
169
  || !Number.isSafeInteger(e.range.sourceBytes) || e.range.sourceBytes < 0 || e.range.bytes !== bytes.length
153
170
  || e.range.offset + e.range.bytes > e.range.sourceBytes))) throw new Error("Retained assignment evidence changed.");
154
171
  }
172
+ // Older accepted reports may contain prose the terminal store cannot retain.
173
+ // Treat those as unverified evidence rather than throwing during finalization.
174
+ validateReportText(report);
155
175
  return report;
156
176
  }
@@ -90,13 +90,15 @@ export function mergeJobOptions(shared, job) {
90
90
  cwd: job.cwd ?? shared?.cwd,
91
91
  // Same semantics as subagent_spawn: shared and per-job values must reach
92
92
  // spawnSubagentRun so batch jobs can request disposable clone workspaces.
93
+ isolation: job.isolation ?? shared?.isolation,
94
+ recover_in_clone: job.recover_in_clone,
93
95
  git_clone_workspace: job.git_clone_workspace ?? shared?.git_clone_workspace,
94
96
  approve: job.approve ?? shared?.approve,
95
97
  allow_nested: job.allow_nested ?? shared?.allow_nested,
96
98
  // Native session id selected for this JOB only. A shared value would make
97
99
  // every job contend for the same conversation writer, so it is not inherited.
98
- session_id: typeof job.session_id === "string" ? job.session_id : undefined,
99
- session_name: typeof job.session_name === "string" ? job.session_name : undefined,
100
+ session_id: typeof job.session_id === "string" ? normalizeSessionSelector(job.session_id) : undefined,
101
+ session_name: typeof job.session_name === "string" ? normalizeSessionSelector(job.session_name) : undefined,
100
102
  // Harness timing; an explicit null means "not set", so it falls through to shared.
101
103
  deadline_minutes: job.deadline_minutes ?? shared?.deadline_minutes,
102
104
  grace_minutes: job.grace_minutes ?? shared?.grace_minutes,
@@ -108,6 +110,10 @@ export function mergeJobOptions(shared, job) {
108
110
  ...catalogSelector(shared, job),
109
111
  };
110
112
  }
113
+ /** Keep nonblank selectors exact. Only a blank string is equivalent to omission. */
114
+ export function normalizeSessionSelector(value) {
115
+ return typeof value === "string" && value.trim() === "" ? undefined : value;
116
+ }
111
117
  function catalogText(value) {
112
118
  return typeof value === "string" && value.trim() !== "" ? value : undefined;
113
119
  }
@@ -148,11 +154,13 @@ export function validateBatchPlan({ shared, jobs, onCapacity, config }) {
148
154
  if (typeof job.prompt !== "string" || job.prompt.trim() === "") {
149
155
  throw new Error(`job ${i + 1} is missing a non-empty prompt.`);
150
156
  }
151
- if (job.session_id !== undefined && job.session_name !== undefined)
157
+ const sessionId = normalizeSessionSelector(job.session_id);
158
+ const sessionName = normalizeSessionSelector(job.session_name);
159
+ if (sessionId !== undefined && sessionName !== undefined)
152
160
  throw new Error(`job ${i + 1}: pass either session_id or session_name, not both.`);
153
- if (job.session_name !== undefined && (typeof job.session_name !== "string" || job.session_name.trim() === ""))
161
+ if (sessionName !== undefined && typeof sessionName !== "string")
154
162
  throw new Error(`job ${i + 1} session_name must be a non-empty name.`);
155
- if (job.session_id !== undefined && (typeof job.session_id !== "string" || job.session_id.trim() === "")) {
163
+ if (sessionId !== undefined && typeof sessionId !== "string") {
156
164
  throw new Error(`job ${i + 1} session_id must be a non-empty native session id.`);
157
165
  }
158
166
  if (seenPrompts.has(job.prompt)) {
@@ -1,7 +1,7 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/catalog-preferences.ts. Do not edit directly.
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
- import { createRequire } from "node:module";
4
+ import lockfile from "proper-lockfile";
5
5
  import { join, resolve } from "node:path";
6
6
  import { THINKING_LEVELS } from "./thinking.domain.mjs";
7
7
  const ID = /^(role|agent)\.[a-z0-9]+(?:[.-][a-z0-9]+)*$/;
@@ -92,8 +92,6 @@ export function readCatalogPreferences(root) {
92
92
  }
93
93
  }
94
94
  function acquire(path) {
95
- // Read-only catalog consumers (including the portable CLI) need no lock adapter.
96
- const lockfile = createRequire(import.meta.url)("proper-lockfile");
97
95
  for (let attempt = 0; attempt < 100; attempt++) {
98
96
  try {
99
97
  return lockfile.lockSync(path, { realpath: false });
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
- import { createRequire } from "node:module";
3
+ import lockfile from "proper-lockfile";
4
4
  import { join, resolve } from "node:path";
5
5
  import { THINKING_LEVELS, type ThinkingLevel } from "./thinking.ts";
6
6
 
@@ -84,10 +84,6 @@ export function readCatalogPreferences(root: string): { settings: CatalogPrefere
84
84
  }
85
85
 
86
86
  function acquire(path: string): () => void {
87
- // Read-only catalog consumers (including the portable CLI) need no lock adapter.
88
- const lockfile = createRequire(import.meta.url)("proper-lockfile") as {
89
- lockSync(path: string, options: { realpath: boolean }): () => void;
90
- };
91
87
  for (let attempt = 0; attempt < 100; attempt++) {
92
88
  try { return lockfile.lockSync(path, { realpath: false }); }
93
89
  catch (error) {
@@ -453,7 +453,7 @@ function removeAgedRunArtifacts(meta, cutoff, retained, scope, errors) {
453
453
  const fresh = readMeta(meta.id) ?? meta;
454
454
  if (!ageSweepEligible(fresh, cutoff, retained, scope))
455
455
  return false;
456
- if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId) }))
456
+ if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId), errors }))
457
457
  return true;
458
458
  errors.push(`${runDir(meta.id)}: could not remove run artifacts`);
459
459
  return false;
@@ -686,6 +686,7 @@ export function collectSizeCapEntries() {
686
686
  return [];
687
687
  }
688
688
  const entries = [];
689
+ const workspaces = new Map();
689
690
  for (const id of ids) {
690
691
  const dir = runDir(id);
691
692
  const meta = readMeta(id);
@@ -696,7 +697,15 @@ export function collectSizeCapEntries() {
696
697
  dirMtimeMs: safeStatMtime(dir) ?? 0,
697
698
  bytes: dirBytes(dir),
698
699
  });
700
+ const workspace = meta?.recipe?.workspace;
701
+ if (workspace && meta && meta.startedAt >= (workspaces.get(workspace.owner)?.started ?? 0)) {
702
+ workspaces.set(workspace.owner, { root: workspace.root, started: meta.startedAt, entry: entries[entries.length - 1] });
703
+ }
699
704
  }
705
+ // A restored conversation may have outlived its first attempt. Charge its
706
+ // one shared checkout to the most recent writer still in the registry.
707
+ for (const { root, entry } of workspaces.values())
708
+ entry.bytes += dirBytes(root);
700
709
  return entries;
701
710
  }
702
711
  /**
@@ -798,7 +807,7 @@ function removeSizeCappedRun(id, scope, errors) {
798
807
  return "retained";
799
808
  if (scope.occupancy.runIds.has(fresh.id))
800
809
  return "retained";
801
- if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId) }))
810
+ if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId), errors }))
802
811
  return "removed";
803
812
  errors.push(`${runDir(id)}: could not remove run artifacts`);
804
813
  return "failed";
@@ -615,7 +615,7 @@ function removeAgedRunArtifacts(
615
615
  if (!conversationQuiescentUnderLock(meta.sessionId, runIds)) return false;
616
616
  const fresh = readMeta(meta.id) ?? meta;
617
617
  if (!ageSweepEligible(fresh, cutoff, retained, scope)) return false;
618
- if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId) })) return true;
618
+ if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId), errors })) return true;
619
619
  errors.push(`${runDir(meta.id)}: could not remove run artifacts`);
620
620
  return false;
621
621
  }, () => false);
@@ -867,6 +867,7 @@ export function collectSizeCapEntries(): SizeCapEntry[] {
867
867
  return [];
868
868
  }
869
869
  const entries: SizeCapEntry[] = [];
870
+ const workspaces = new Map<string, { root: string; started: number; entry: SizeCapEntry }>();
870
871
  for (const id of ids) {
871
872
  const dir = runDir(id);
872
873
  const meta = readMeta(id);
@@ -877,7 +878,14 @@ export function collectSizeCapEntries(): SizeCapEntry[] {
877
878
  dirMtimeMs: safeStatMtime(dir) ?? 0,
878
879
  bytes: dirBytes(dir),
879
880
  });
881
+ const workspace = meta?.recipe?.workspace;
882
+ if (workspace && meta && meta.startedAt >= (workspaces.get(workspace.owner)?.started ?? 0)) {
883
+ workspaces.set(workspace.owner, { root: workspace.root, started: meta.startedAt, entry: entries[entries.length - 1]! });
884
+ }
880
885
  }
886
+ // A restored conversation may have outlived its first attempt. Charge its
887
+ // one shared checkout to the most recent writer still in the registry.
888
+ for (const { root, entry } of workspaces.values()) entry.bytes += dirBytes(root);
881
889
  return entries;
882
890
  }
883
891
 
@@ -999,7 +1007,7 @@ function removeSizeCappedRun(
999
1007
  if (!TERMINAL_CLEANUP_STATUSES.has(fresh.status)) return "retained";
1000
1008
  if (outcomeProtected(fresh)) return "retained";
1001
1009
  if (scope.occupancy.runIds.has(fresh.id)) return "retained";
1002
- if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId) })) return "removed";
1010
+ if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId), errors })) return "removed";
1003
1011
  errors.push(`${runDir(id)}: could not remove run artifacts`);
1004
1012
  return "failed";
1005
1013
  }, () => "retained");
@@ -132,6 +132,11 @@ export function writeSubagentSettings(settings, path = configPath()) {
132
132
  delegationMode: settings.delegationMode,
133
133
  maxConcurrent: settings.maxConcurrent,
134
134
  };
135
+ if (settings.gitWorkspace !== undefined) {
136
+ if (settings.gitWorkspace !== "clone" && settings.gitWorkspace !== "worktree")
137
+ throw new Error("Unknown Git workspace mode.");
138
+ next.gitWorkspace = settings.gitWorkspace;
139
+ }
135
140
  if (settings.maxMinutes !== undefined) {
136
141
  next.maxMinutes = validatedTimingMinutes(settings.maxMinutes, "maxMinutes");
137
142
  }
@@ -25,6 +25,7 @@ import { harnessSettingsPath, readHarnessSetting, updateHarnessSetting } from ".
25
25
  export interface SubagentConfig extends TimingSettings {
26
26
  /** Foreground delegation policy; /subagents mode overrides this for the current session. */
27
27
  delegationMode?: DelegationMode | null;
28
+ gitWorkspace?: "clone" | "worktree";
28
29
  defaultModel?: string | null;
29
30
  defaultTools?: string | null;
30
31
  /**
@@ -44,7 +45,7 @@ export interface SubagentConfig extends TimingSettings {
44
45
  /**
45
46
  * Provider → extension package(s) that authenticate it. Model auth is not
46
47
  * tool-shaped: `xai/grok-4.5` needs pi-xai-oauth loaded whatever the tools.
47
- * A built-in entry covers `ollama-cloud`; an entry here replaces it.
48
+ * Entries here override built-in mappings, including Ollama Cloud and LiteLLM.
48
49
  */
49
50
  providerExtensions?: Record<string, string | string[]> | null;
50
51
  /**
@@ -197,6 +198,7 @@ export function writeSubagentSettings(
197
198
  settings: {
198
199
  delegationMode: DelegationMode;
199
200
  maxConcurrent: number;
201
+ gitWorkspace?: "clone" | "worktree";
200
202
  maxMinutes?: number;
201
203
  /** Omit to preserve the saved value; `null` explicitly records discovery. */
202
204
  defaultSkills?: string[] | null;
@@ -211,11 +213,15 @@ export function writeSubagentSettings(
211
213
  if (!isConcurrencyCap(settings.maxConcurrent)) throw new Error("Concurrent subagents must be a positive whole number.");
212
214
  const next: {
213
215
  delegationMode: DelegationMode; maxConcurrent: number; maxMinutes?: number; defaultSkills?: string[] | null;
214
- toolWaitMinutes?: number; stuckMinutes?: number;
216
+ toolWaitMinutes?: number; stuckMinutes?: number; gitWorkspace?: "clone" | "worktree";
215
217
  } = {
216
218
  delegationMode: settings.delegationMode,
217
219
  maxConcurrent: settings.maxConcurrent,
218
220
  };
221
+ if (settings.gitWorkspace !== undefined) {
222
+ if (settings.gitWorkspace !== "clone" && settings.gitWorkspace !== "worktree") throw new Error("Unknown Git workspace mode.");
223
+ next.gitWorkspace = settings.gitWorkspace;
224
+ }
219
225
  if (settings.maxMinutes !== undefined) {
220
226
  next.maxMinutes = validatedTimingMinutes(settings.maxMinutes, "maxMinutes");
221
227
  }
@@ -1,4 +1,5 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/continuation.ts. Do not edit directly.
2
+ import { hasWorkspaceCheckpoint } from "./isolated-workspace.domain.mjs";
2
3
  /**
3
4
  * Subagent continuation.
4
5
  *
@@ -452,7 +453,8 @@ export function planContinuation(options) {
452
453
  catch {
453
454
  workspaceIsDir = false;
454
455
  }
455
- if (!workspaceIsDir)
456
+ const recoverable = !workspaceIsDir && recipe.workspace && hasWorkspaceCheckpoint(recipe.workspace);
457
+ if (!workspaceIsDir && !recoverable)
456
458
  throw refusal(id, `its workspace ${recipe.cwd} is missing.`);
457
459
  if (recipe.sandboxDir !== undefined) {
458
460
  let sandboxIsDir = false;
@@ -462,7 +464,7 @@ export function planContinuation(options) {
462
464
  catch {
463
465
  sandboxIsDir = false;
464
466
  }
465
- if (!sandboxIsDir)
467
+ if (!sandboxIsDir && !recoverable)
466
468
  throw refusal(id, `its sandbox workspace ${recipe.sandboxDir} is missing.`);
467
469
  }
468
470
  const lookup = findSavedConversation({
@@ -1,3 +1,4 @@
1
+ import { hasWorkspaceCheckpoint } from "./isolated-workspace.ts";
1
2
  /**
2
3
  * Subagent continuation.
3
4
  *
@@ -536,11 +537,12 @@ export function planContinuation(options: {
536
537
 
537
538
  let workspaceIsDir = false;
538
539
  try { workspaceIsDir = statSync(recipe.cwd).isDirectory(); } catch { workspaceIsDir = false; }
539
- if (!workspaceIsDir) throw refusal(id, `its workspace ${recipe.cwd} is missing.`);
540
+ const recoverable = !workspaceIsDir && recipe.workspace && hasWorkspaceCheckpoint(recipe.workspace);
541
+ if (!workspaceIsDir && !recoverable) throw refusal(id, `its workspace ${recipe.cwd} is missing.`);
540
542
  if (recipe.sandboxDir !== undefined) {
541
543
  let sandboxIsDir = false;
542
544
  try { sandboxIsDir = statSync(recipe.sandboxDir).isDirectory(); } catch { sandboxIsDir = false; }
543
- if (!sandboxIsDir) throw refusal(id, `its sandbox workspace ${recipe.sandboxDir} is missing.`);
545
+ if (!sandboxIsDir && !recoverable) throw refusal(id, `its sandbox workspace ${recipe.sandboxDir} is missing.`);
544
546
  }
545
547
 
546
548
  const lookup: ConversationLookup = findSavedConversation({
@@ -47,6 +47,7 @@ export const SELF_SPEC = "self";
47
47
  export const BUILTIN_PROVIDER_EXTENSIONS = {
48
48
  "router": "npm:pi-better-model-router",
49
49
  "ollama-cloud": "npm:pi-ollama-cloud",
50
+ "litellm": "npm:pi-provider-litellm",
50
51
  };
51
52
  /** Split "xai/grok-4.5" -> "xai". Returns undefined when there is no provider. */
52
53
  export function providerOf(model) {
@@ -1,5 +1,6 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/failures.ts. Do not edit directly.
2
- import { closeSync, fstatSync, openSync, readSync } from "node:fs";
2
+ import { resultDir } from "./session-store.domain.mjs";
3
+ import { existsSync, closeSync, fstatSync, openSync, readSync } from "node:fs";
3
4
  import { join } from "node:path";
4
5
  import { logPathFor, runDir, taskRuntimeTrust } from "./registry.domain.mjs";
5
6
  import { activeFailures, actionableFailures, disposeIncidents, failureIdentity, findIncident, formatFailureSummary, formatTerminalFailureFacts, markFailureAttentionDelivered, observeFailures, pendingFailureAttention, readFailureState } from "./shared-failure-observations.domain.mjs";
@@ -16,7 +17,10 @@ const workerDiagnostics = new SandboxDiagnostics({ context: "worker",
16
17
  });
17
18
  export { formatFailureSummary, pendingFailureAttention, markFailureAttentionDelivered, toolOperation };
18
19
  export const failurePath = (id) => join(runDir(id), "failures.jsonl");
19
- export const readRunFailures = (id) => readFailureState(failurePath(id));
20
+ export function readRunFailures(id) {
21
+ const retained = !existsSync(runDir(id)) && resultDir(id);
22
+ return readFailureState(retained ? join(retained, "failures.jsonl") : failurePath(id));
23
+ }
20
24
  const scans = new Map();
21
25
  /** When each run's trust first could not be read, for the bounded wait (#325). */
22
26
  const trustUnknownSince = new Map();
@@ -176,6 +180,11 @@ function exactRuleLeftovers(path, prior) {
176
180
  /** Scan complete source records, independent of the finite progress/transcript tail. */
177
181
  export function collectRunFailures(id, cwd, terminal = false, assertCurrent = () => { }) {
178
182
  assertCurrent();
183
+ if (!existsSync(runDir(id))) {
184
+ const retained = resultDir(id);
185
+ if (retained && existsSync(join(retained, "result.json")))
186
+ return readRunFailures(id);
187
+ }
179
188
  const path = failurePath(id);
180
189
  let fd;
181
190
  try {
@@ -1,4 +1,5 @@
1
- import { closeSync, fstatSync, openSync, readSync } from "node:fs";
1
+ import { resultDir } from "./session-store.ts";
2
+ import { existsSync, closeSync, fstatSync, openSync, readSync } from "node:fs";
2
3
  import { join } from "node:path";
3
4
  import { logPathFor, runDir, taskRuntimeTrust } from "./registry.ts";
4
5
  import { activeFailures, actionableFailures, disposeIncidents, failureIdentity, findIncident, formatFailureSummary, formatTerminalFailureFacts, markFailureAttentionDelivered,
@@ -18,7 +19,10 @@ const workerDiagnostics = new SandboxDiagnostics({ context: "worker",
18
19
 
19
20
  export { formatFailureSummary, pendingFailureAttention, markFailureAttentionDelivered, toolOperation };
20
21
  export const failurePath = (id: string) => join(runDir(id), "failures.jsonl");
21
- export const readRunFailures = (id: string): FailureState => readFailureState(failurePath(id));
22
+ export function readRunFailures(id: string): FailureState {
23
+ const retained = !existsSync(runDir(id)) && resultDir(id);
24
+ return readFailureState(retained ? join(retained, "failures.jsonl") : failurePath(id));
25
+ }
22
26
  interface Scan {
23
27
  offset: number; head: string; identity: string; model: IncidentModel; retry?: number;
24
28
  /**
@@ -162,6 +166,10 @@ function exactRuleLeftovers(path: string, prior: FailureState): Set<string> {
162
166
  /** Scan complete source records, independent of the finite progress/transcript tail. */
163
167
  export function collectRunFailures(id: string, cwd: string, terminal = false, assertCurrent: () => void = () => {}): FailureState {
164
168
  assertCurrent();
169
+ if (!existsSync(runDir(id))) {
170
+ const retained = resultDir(id);
171
+ if (retained && existsSync(join(retained, "result.json"))) return readRunFailures(id);
172
+ }
165
173
  const path = failurePath(id);
166
174
  let fd: number;
167
175
  try { fd = openSync(logPathFor(id), "r"); }