@oyasmi/pipiclaw 0.9.0-beta.7 → 0.9.0-beta.8

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 (35) hide show
  1. package/dist/memory/review-log.js +0 -0
  2. package/dist/memory/scheduler.d.ts +1 -0
  3. package/dist/memory/scheduler.js +64 -6
  4. package/dist/playbooks/agent-delegation.md +2 -2
  5. package/dist/runtime/bootstrap.js +9 -5
  6. package/dist/runtime/durable-dispatch.d.ts +1 -0
  7. package/dist/runtime/durable-dispatch.js +36 -25
  8. package/dist/runtime/subagent-commands.js +48 -10
  9. package/dist/shared/host-process.d.ts +25 -9
  10. package/dist/shared/host-process.js +59 -10
  11. package/dist/subagents/discovery.d.ts +24 -0
  12. package/dist/subagents/discovery.js +103 -17
  13. package/dist/subagents/external/claude-code.js +10 -3
  14. package/dist/subagents/external/codex-cli.js +9 -3
  15. package/dist/subagents/external/exec.js +1 -0
  16. package/dist/subagents/external/harness.d.ts +22 -0
  17. package/dist/subagents/external/harness.js +22 -4
  18. package/dist/subagents/external/run.d.ts +23 -3
  19. package/dist/subagents/external/run.js +110 -123
  20. package/dist/subagents/external/settlement.d.ts +50 -0
  21. package/dist/subagents/external/settlement.js +123 -0
  22. package/dist/subagents/format.d.ts +4 -0
  23. package/dist/subagents/format.js +7 -0
  24. package/dist/subagents/runs.d.ts +70 -13
  25. package/dist/subagents/runs.js +195 -108
  26. package/dist/subagents/tool.d.ts +27 -2
  27. package/dist/subagents/tool.js +92 -48
  28. package/dist/subagents/verification-outcome.d.ts +26 -0
  29. package/dist/subagents/verification-outcome.js +16 -0
  30. package/dist/subagents/workspace-lease.d.ts +10 -1
  31. package/dist/subagents/workspace-lease.js +15 -2
  32. package/dist/tools/index.js +6 -0
  33. package/dist/tools/subagent-manage.d.ts +20 -6
  34. package/dist/tools/subagent-manage.js +86 -16
  35. package/package.json +1 -1
@@ -1,19 +1,20 @@
1
1
  import { spawn as nodeSpawn } from "node:child_process";
2
2
  import { closeSync, openSync } from "node:fs";
3
- import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { mkdir, writeFile } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import * as log from "../../log.js";
6
6
  import { logSecurityEvent } from "../../security/logger.js";
7
- import { killProcessGroup, readProcessStartTime } from "../../shared/host-process.js";
8
- import { formatLocalTime } from "../../shared/local-time.js";
7
+ import { killProcessGroup, probeCliVersion, readProcessStartTime, reapProcessGroup, } from "../../shared/host-process.js";
9
8
  import { splitShellWords } from "../../shared/shell-words.js";
10
9
  import { errorMessage } from "../../shared/text-utils.js";
11
10
  import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
12
- import { parseVerificationVerdict, writeVerificationAttestation } from "../../tasks/verification.js";
13
11
  import { getSubAgentRunManager } from "../runs.js";
14
- import { classifyExternalOutcome } from "./harness.js";
15
12
  import { getExternalHarness } from "./registry.js";
16
- const WAKE_OUTPUT_TAIL_CHARS = 2_000;
13
+ import { finalizeExternalRun } from "./settlement.js";
14
+ function classifySpawnError(error) {
15
+ const code = error.code;
16
+ return code === "ENOENT" || code === "EACCES" ? "missing-binary" : "launch-failed";
17
+ }
17
18
  function buildStdinContent(harnessId, systemPrompt, task) {
18
19
  // claude-code has a real system-prompt flag (--append-system-prompt-file, D4); every other
19
20
  // harness has no such channel, so the role's system prompt has nowhere to go but the prompt
@@ -22,8 +23,9 @@ function buildStdinContent(harnessId, systemPrompt, task) {
22
23
  return task;
23
24
  return `${systemPrompt.trim()}\n\n---\n\n${task.trim()}\n`;
24
25
  }
25
- /** Launches an external run. Returns once the process is confirmed spawned (or fails fast if it
26
- * never starts); the wait-for-exit-and-settle work continues in the background afterward. */
26
+ /** Launches an external run. Resolves once the process is confirmed spawned (or fails fast if it
27
+ * never starts, spec 042 D2); the wait-for-exit-and-settle work continues in the background
28
+ * afterward. */
27
29
  export async function launchExternalRun(input) {
28
30
  const harness = getExternalHarness(input.harness);
29
31
  if (!harness) {
@@ -58,21 +60,11 @@ export async function launchExternalRun(input) {
58
60
  resumeSessionId: input.resumeSessionId,
59
61
  });
60
62
  const spawnedArgv = [invocation.executable, ...invocation.args];
61
- // Security gate: the final executable/argv/cwd/capability record must be durable before a
62
- // process can exist. `external-agent` uses the strict appender path and rejects on queue or I/O
63
- // failure; callers then release any admission lease without an unaudited child ever starting.
64
- await logSecurityEvent(input.workspaceDir, input.securityConfig, {
65
- type: "external-agent",
66
- tool: "subagent",
67
- channelId: input.channelId,
68
- runId: input.runId,
69
- agent: input.agent,
70
- harness: harness.id,
71
- argv: spawnedArgv,
72
- workingDirectory: input.workingDirectory,
73
- mutates: input.mutates ?? "read",
74
- model: input.externalModelRef,
75
- });
63
+ // Spec 042 D11: admission (inside register(), including the concurrency-limit checks) happens
64
+ // *before* the audit write, not after — previously a run rejected for being over the per-channel
65
+ // or host-wide cap still left behind an `external-agent` audit record claiming a process that
66
+ // never existed. `external-agent` records what was *executed* (D8.1), so the record must not
67
+ // precede the point where this run is actually admitted to run.
76
68
  const runManager = getSubAgentRunManager(input.channelId);
77
69
  await runManager.register({
78
70
  runId: input.runId,
@@ -90,13 +82,38 @@ export async function launchExternalRun(input) {
90
82
  artifactDir: input.artifactDir,
91
83
  leaseKey: input.leaseKey,
92
84
  });
85
+ // The final executable/argv/cwd/capability record must be durable before a process can exist.
86
+ // `external-agent` uses the strict appender path and rejects on queue or I/O failure; a failure
87
+ // here settles the run instead of leaving it an orphaned "running" record (spec 042 D2) — the
88
+ // same reasoning as every other pre-spawn failure below: this is a real fault requiring human
89
+ // attention (disk full, permissions), not something a retry would fix on its own.
90
+ try {
91
+ await logSecurityEvent(input.workspaceDir, input.securityConfig, {
92
+ type: "external-agent",
93
+ tool: "subagent",
94
+ channelId: input.channelId,
95
+ runId: input.runId,
96
+ agent: input.agent,
97
+ harness: harness.id,
98
+ argv: spawnedArgv,
99
+ workingDirectory: input.workingDirectory,
100
+ mutates: input.mutates ?? "read",
101
+ model: input.externalModelRef,
102
+ });
103
+ }
104
+ catch (error) {
105
+ const reason = `Failed to write the mandatory dispatch audit record: ${errorMessage(error)}`;
106
+ await runManager.settle(input.runId, failedSettleInput(reason), { announce: false });
107
+ return { ok: false, kind: "launch-failed", reason };
108
+ }
93
109
  let cancelledBeforeSpawn = false;
94
110
  const launchClaimed = await runManager.claimExternalLaunch(input.runId, () => {
95
111
  cancelledBeforeSpawn = true;
96
112
  });
97
113
  if (!launchClaimed) {
98
- await runManager.settle(input.runId, { ...failedSettleInput("Cancelled before the external process was spawned."), status: "cancelled" }, { announce: false });
99
- return;
114
+ const reason = "Cancelled before the external process was spawned.";
115
+ await runManager.settle(input.runId, { ...failedSettleInput(reason), status: "cancelled" }, { announce: false });
116
+ return { ok: false, kind: "cancelled", reason };
100
117
  }
101
118
  const eventsPath = join(input.artifactDir, "events.jsonl");
102
119
  const stderrPath = join(input.artifactDir, "stderr.log");
@@ -107,10 +124,12 @@ export async function launchExternalRun(input) {
107
124
  stderrFd = openSync(stderrPath, "a");
108
125
  }
109
126
  catch (error) {
110
- await runManager.settle(input.runId, failedSettleInput(`Failed to open output files: ${errorMessage(error)}`), {
111
- announce: true,
112
- });
113
- return;
127
+ const reason = `Failed to open output files: ${errorMessage(error)}`;
128
+ // Spec 042 D2: `announce: false` — this failure happened inside the same tool call that is
129
+ // still on the stack; the caller reports it directly instead of waking the channel for a
130
+ // result it can hand back right now.
131
+ await runManager.settle(input.runId, failedSettleInput(reason), { announce: false });
132
+ return { ok: false, kind: "launch-failed", reason };
114
133
  }
115
134
  const spawnFn = input.spawnFn ?? nodeSpawn;
116
135
  let child;
@@ -127,10 +146,13 @@ export async function launchExternalRun(input) {
127
146
  catch (error) {
128
147
  closeSync(eventsFd);
129
148
  closeSync(stderrFd);
130
- await runManager.settle(input.runId, failedSettleInput(`Failed to launch: ${errorMessage(error)}`), {
131
- announce: true,
132
- });
133
- return;
149
+ const reason = `Failed to launch: ${errorMessage(error)}`;
150
+ await runManager.settle(input.runId, failedSettleInput(reason), { announce: false });
151
+ return {
152
+ ok: false,
153
+ kind: classifySpawnError(error instanceof Error ? error : new Error(String(error))),
154
+ reason,
155
+ };
134
156
  }
135
157
  // The child has its own duped copy of both fds now; ours would otherwise leak across the
136
158
  // lifetime of a long-running daemon dispatching many external runs.
@@ -141,8 +163,13 @@ export async function launchExternalRun(input) {
141
163
  child.once("spawn", () => resolve(undefined));
142
164
  });
143
165
  if (spawnFailure || !child.pid) {
144
- await runManager.settle(input.runId, failedSettleInput(`Failed to launch: ${spawnFailure ? errorMessage(spawnFailure) : "no pid"}`), { announce: true });
145
- return;
166
+ const reason = `Failed to launch: ${spawnFailure ? errorMessage(spawnFailure) : "no pid"}`;
167
+ await runManager.settle(input.runId, failedSettleInput(reason), { announce: false });
168
+ return {
169
+ ok: false,
170
+ kind: spawnFailure ? classifySpawnError(spawnFailure) : "launch-failed",
171
+ reason,
172
+ };
146
173
  }
147
174
  const pid = child.pid;
148
175
  const processStartedAt = Date.now();
@@ -155,13 +182,18 @@ export async function launchExternalRun(input) {
155
182
  });
156
183
  if (cancelledBeforeSpawn) {
157
184
  void killProcessGroup(pid);
158
- await runManager.settle(input.runId, { ...failedSettleInput("Cancelled while the external process was spawning."), status: "cancelled" }, { announce: false });
159
- return;
185
+ const reason = "Cancelled while the external process was spawning.";
186
+ await runManager.settle(input.runId, { ...failedSettleInput(reason), status: "cancelled" }, { announce: false });
187
+ return { ok: false, kind: "cancelled", reason };
160
188
  }
161
189
  // The OS-verifiable identity check (D10.3): a restart tells this pid apart from an unrelated
162
190
  // process that later reuses the same number. `undefined` when `ps` itself is unavailable —
163
- // restore()/sweep() then fall back to trusting `isProcessAlive` alone.
164
- const pidStartedAt = await readProcessStartTime(pid);
191
+ // restore()/sweep() then fall back to trusting `isProcessAlive` alone. Run alongside the D12
192
+ // CLI-version probe — neither depends on the other, and both are best-effort/bounded.
193
+ const [pidStartedAt, cliVersion] = await Promise.all([
194
+ readProcessStartTime(pid),
195
+ probeCliVersion(invocation.executable),
196
+ ]);
165
197
  const deadlineAt = processStartedAt + input.maxWallTimeSec * 1000;
166
198
  await runManager.setLaunched(input.runId, {
167
199
  pid,
@@ -169,6 +201,18 @@ export async function launchExternalRun(input) {
169
201
  argv: spawnedArgv,
170
202
  deadlineAt,
171
203
  sessionId: invocation.presetSessionId,
204
+ // Spec 042 D1: persisted so a restart reconciliation has the same inputs the live watcher
205
+ // below would — without these, a run that finishes after the daemon disappears would settle
206
+ // with an inaccurate timeout message, no verify attestation, and an unestimatable duration.
207
+ verifySubjectBefore,
208
+ maxWallTimeSec: input.maxWallTimeSec,
209
+ processStartedAt,
210
+ channelDir: input.channelDir,
211
+ invocationWarnings: invocation.warnings,
212
+ // Spec 042 D12: distinguishes "the target CLI's schema drifted" from "the agent failed".
213
+ parserVersion: harness.parserVersion,
214
+ cliVersion,
215
+ roleFingerprint: input.roleFingerprint,
172
216
  });
173
217
  if (child.stdin) {
174
218
  child.stdin.on("error", () => { }); // EPIPE if the process already exited; harmless.
@@ -183,8 +227,8 @@ export async function launchExternalRun(input) {
183
227
  if (runManager.get(input.runId)?.terminationReason === "cancelled") {
184
228
  void killProcessGroup(pid);
185
229
  }
186
- // Prompt, same-process enforcement (the sweeper is the cross-restart backstop for this
187
- // deadline, at coarser granularity — see SWEEP_INTERVAL_MS in runs.ts).
230
+ // Prompt, same-process enforcement. Restart recovery persists this same deadline and installs
231
+ // one replacement check only when it actually adopts a still-running process.
188
232
  const wallClockTimer = setTimeout(() => {
189
233
  void runManager.markTerminationReason(input.runId, "timeout").then(() => killProcessGroup(pid));
190
234
  }, input.maxWallTimeSec * 1000);
@@ -194,94 +238,37 @@ export async function launchExternalRun(input) {
194
238
  void closePromise.then(async (exitCode) => {
195
239
  clearTimeout(wallClockTimer);
196
240
  runManager.clearCancelHandle(input.runId);
197
- // The leader can exit before a detached descendant it spawned (e.g. a shell that forked and
198
- // returned); `-pid` still reaches the whole group as long as the group itself is still
199
- // around, so reap it unconditionally rather than only on an explicit cancel/timeout.
200
- await killProcessGroup(pid);
241
+ // Spec 042 D8: this fires on every exit (normal, cancelled, or timed out) as a backup reap —
242
+ // a cancel/timeout already killed the group via its own call site above. The common case
243
+ // (nothing left) returns immediately with no signal and no wait; only a genuinely lingering
244
+ // descendant (the leader exited before it did) pays the TERM-then-KILL sequence.
245
+ await reapProcessGroup(pid);
201
246
  const durationMs = Date.now() - processStartedAt;
202
247
  const terminationReason = runManager.get(input.runId)?.terminationReason;
203
- if (terminationReason === "cancelled") {
204
- await runManager
205
- .settle(input.runId, { ...failedSettleInput("Cancelled by request."), status: "cancelled", durationMs }, { announce: false })
206
- .catch((error) => {
207
- log.logWarning(`Failed to settle external run ${input.runId}`, errorMessage(error));
208
- });
209
- return;
210
- }
211
- if (terminationReason === "timeout") {
212
- // A distinct failure reason from "no protocol terminal event" (P1-1): the process was
213
- // killed on purpose, not just silent — even if a CLI happened to emit a success terminal
214
- // right before SIGTERM landed, the budget is what ended this run.
215
- await runManager
216
- .settle(input.runId, {
217
- ...failedSettleInput(`Wall time budget exceeded (${input.maxWallTimeSec}s)`),
218
- durationMs,
219
- }, { announce: true })
220
- .catch((error) => {
221
- log.logWarning(`Failed to settle external run ${input.runId}`, errorMessage(error));
222
- });
223
- return;
224
- }
225
- const eventsText = await readFile(eventsPath, "utf-8").catch(() => "");
226
- const stderrTail = (await readFile(stderrPath, "utf-8").catch(() => "")).slice(-WAKE_OUTPUT_TAIL_CHARS);
227
- const outcome = harness.parseOutcome({ eventsText, exitCode, stderrTail });
228
- const classification = classifyExternalOutcome(harness.id, outcome);
229
- // D9: the verdict is a fact the run reported, independent of whether the run itself
230
- // "succeeded" — a verifier that cleanly concludes VERDICT: FAIL is still a completed run.
231
- let verificationVerdict;
232
- if (input.purpose === "verify" && input.taskId && input.channelDir && classification.status === "completed") {
233
- const subjectAfter = await workspaceSubjectHash(input.workingDirectory);
234
- const workspaceChanged = verifySubjectBefore !== undefined && subjectAfter !== undefined && verifySubjectBefore !== subjectAfter;
235
- const declaredVerdict = parseVerificationVerdict(outcome.finalText);
236
- verificationVerdict = declaredVerdict === "pass" && !workspaceChanged ? "pass" : "fail";
237
- const evidence = workspaceChanged
238
- ? "Verifier's workspace subject changed; the attestation is invalid."
239
- : !declaredVerdict
240
- ? "Verifier did not emit the required final VERDICT marker."
241
- : outcome.finalText.trim().slice(0, 8_000);
242
- await writeVerificationAttestation(input.channelDir, {
243
- runId: input.runId,
244
- taskId: input.taskId,
245
- verdict: verificationVerdict,
246
- checkedAt: formatLocalTime(),
247
- evidence,
248
- workspaceChanged,
249
- subjectHash: workspaceChanged ? undefined : subjectAfter,
250
- subjectDir: input.workingDirectory,
251
- // External verifiers cannot have their tools structurally removed the way an
252
- // internal verifier's are — the sandbox flag lives in the role's own `command`,
253
- // unverifiable by pipiclaw. Advisory, not enforced (D9).
254
- verificationStrength: "advisory",
255
- }).catch((error) => {
256
- log.logWarning(`Failed to write verification attestation for run ${input.runId}`, errorMessage(error));
257
- });
258
- }
259
- await runManager
260
- .settle(input.runId, {
261
- status: classification.status,
262
- failureReason: classification.failureReason,
263
- usage: {
264
- input: outcome.usage?.input ?? 0,
265
- output: outcome.usage?.output ?? 0,
266
- cacheRead: outcome.usage?.cacheRead ?? 0,
267
- cacheWrite: outcome.usage?.cacheWrite ?? 0,
268
- total: outcome.usage?.total ?? 0,
269
- cost: outcome.usage?.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
270
- },
271
- usageKnown: outcome.usageKnown,
272
- costKnown: outcome.costKnown,
273
- turns: 0,
274
- toolCalls: 0,
248
+ // Spec 042 D1: parse whatever the process actually wrote *before* applying a cancel/timeout
249
+ // override, instead of returning early on those two reasons. A run killed for wall-time
250
+ // budget or cancelled by request may still have produced useful output, usage, and a
251
+ // resumable session id — `finalizeExternalRun` keeps all of that; only `status` and
252
+ // `failureReason` get overridden by `terminationReason` (P1-1).
253
+ await finalizeExternalRun({
254
+ runId: input.runId,
255
+ channelId: input.channelId,
256
+ channelDir: input.channelDir,
257
+ harnessId: harness.id,
258
+ purpose: input.purpose,
259
+ taskId: input.taskId,
260
+ workingDirectory: input.workingDirectory,
261
+ artifactDir: input.artifactDir,
262
+ exitCode,
275
263
  durationMs,
276
- outputText: outcome.finalText,
277
- sessionId: outcome.sessionId,
278
- verificationVerdict,
279
- verificationStrength: verificationVerdict ? "advisory" : undefined,
280
- }, { announce: true })
281
- .catch((error) => {
264
+ terminationReason,
265
+ maxWallTimeSec: input.maxWallTimeSec,
266
+ verifySubjectBefore,
267
+ }, (settleInput, options) => runManager.settle(input.runId, settleInput, options), { announce: terminationReason !== "cancelled" }).catch((error) => {
282
268
  log.logWarning(`Failed to settle external run ${input.runId}`, errorMessage(error));
283
269
  });
284
270
  });
271
+ return { ok: true };
285
272
  function failedSettleInput(reason) {
286
273
  return {
287
274
  status: "failed",
@@ -0,0 +1,50 @@
1
+ import type { RunHarness, SettleInput } from "../runs.js";
2
+ import { type ExternalOutcome } from "./harness.js";
3
+ export interface BuildExternalSettleInputInput {
4
+ harnessId: RunHarness;
5
+ outcome: ExternalOutcome;
6
+ durationMs: number;
7
+ durationEstimated?: boolean;
8
+ terminationReason?: "timeout" | "cancelled";
9
+ maxWallTimeSec?: number;
10
+ }
11
+ /**
12
+ * Translate a parsed outcome into the only `SettleInput` this run will get. `terminationReason`
13
+ * overrides `status`/`failureReason` (P1-1: even a CLI that prints a success terminal right before
14
+ * SIGTERM lands does not get credit for finishing) but never touches usage, output text, or
15
+ * session id — those come from whatever the process actually produced, parsed or not.
16
+ */
17
+ export declare function buildExternalSettleInput(input: BuildExternalSettleInputInput): SettleInput;
18
+ export interface FinalizeExternalRunInput {
19
+ runId: string;
20
+ channelId: string;
21
+ /** Needed only for `purpose=verify`: where the attestation gets written. Absent on an older
22
+ * record (predating spec 042) — verify processing degrades to "skip" rather than guessing. */
23
+ channelDir?: string;
24
+ harnessId: RunHarness;
25
+ purpose: "work" | "verify";
26
+ taskId?: string;
27
+ workingDirectory: string;
28
+ artifactDir: string;
29
+ /** `undefined` when the process was killed by a signal, or when this is a restart
30
+ * reconciliation that never observed the exit at all. */
31
+ exitCode?: number;
32
+ durationMs: number;
33
+ durationEstimated?: boolean;
34
+ terminationReason?: "timeout" | "cancelled";
35
+ maxWallTimeSec?: number;
36
+ /** The workspace subject hash taken just before this run started (D9's before/after pair for
37
+ * external verify) — persisted at launch so restart reconciliation has it too. */
38
+ verifySubjectBefore?: string;
39
+ }
40
+ /**
41
+ * Read this run's artifact files, parse them through its harness, decide its verdict (including a
42
+ * verify attestation when applicable), and hand the result to `settle`. Both the live post-exit
43
+ * path and restart reconciliation call this and only this — there is no second implementation to
44
+ * drift out of sync with the first (spec 042 F1).
45
+ */
46
+ export declare function finalizeExternalRun(input: FinalizeExternalRunInput, settle: (settleInput: SettleInput, options: {
47
+ announce: boolean;
48
+ }) => Promise<void>, options: {
49
+ announce: boolean;
50
+ }): Promise<void>;
@@ -0,0 +1,123 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import * as log from "../../log.js";
4
+ import { formatLocalTime } from "../../shared/local-time.js";
5
+ import { errorMessage } from "../../shared/text-utils.js";
6
+ import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
7
+ import { writeVerificationAttestation } from "../../tasks/verification.js";
8
+ import { resolveVerificationOutcome } from "../verification-outcome.js";
9
+ import { classifyExternalOutcome } from "./harness.js";
10
+ import { getExternalHarness } from "./registry.js";
11
+ /**
12
+ * Spec 042 D1: the one place an external run's parsed outcome becomes a `SettleInput`, and the
13
+ * one place its verify verdict gets decided and attested. Before this module existed, that logic
14
+ * was written three times — the live post-exit path (`external/run.ts`), and restart
15
+ * reconciliation (`runs.ts`) — and the third copy was the thinnest: it never read `events.jsonl`
16
+ * at all on a cancelled/timed-out run, and never attempted a verify attestation, because the
17
+ * inputs it would have needed (`verifySubjectBefore`, `channelDir`) were never persisted. Both
18
+ * defects are closed by making this the only path either caller can take.
19
+ */
20
+ const STDERR_TAIL_CHARS = 2_000;
21
+ /**
22
+ * Translate a parsed outcome into the only `SettleInput` this run will get. `terminationReason`
23
+ * overrides `status`/`failureReason` (P1-1: even a CLI that prints a success terminal right before
24
+ * SIGTERM lands does not get credit for finishing) but never touches usage, output text, or
25
+ * session id — those come from whatever the process actually produced, parsed or not.
26
+ */
27
+ export function buildExternalSettleInput(input) {
28
+ const classification = classifyExternalOutcome(input.harnessId, input.outcome);
29
+ const cancelled = input.terminationReason === "cancelled";
30
+ const timedOut = input.terminationReason === "timeout";
31
+ const status = cancelled ? "cancelled" : timedOut ? "failed" : classification.status;
32
+ const failureReason = cancelled
33
+ ? "Cancelled by request."
34
+ : timedOut
35
+ ? `Wall time budget exceeded (${input.maxWallTimeSec}s)`
36
+ : classification.failureReason;
37
+ return {
38
+ status,
39
+ failureReason,
40
+ usage: {
41
+ input: input.outcome.usage?.input ?? 0,
42
+ output: input.outcome.usage?.output ?? 0,
43
+ cacheRead: input.outcome.usage?.cacheRead ?? 0,
44
+ cacheWrite: input.outcome.usage?.cacheWrite ?? 0,
45
+ total: input.outcome.usage?.total ?? 0,
46
+ cost: input.outcome.usage?.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
47
+ },
48
+ usageKnown: input.outcome.usageKnown,
49
+ costKnown: input.outcome.costKnown,
50
+ turns: 0,
51
+ toolCalls: 0,
52
+ durationMs: input.durationMs,
53
+ durationEstimated: input.durationEstimated,
54
+ outputText: input.outcome.finalText,
55
+ sessionId: input.outcome.sessionId,
56
+ };
57
+ }
58
+ /**
59
+ * Read this run's artifact files, parse them through its harness, decide its verdict (including a
60
+ * verify attestation when applicable), and hand the result to `settle`. Both the live post-exit
61
+ * path and restart reconciliation call this and only this — there is no second implementation to
62
+ * drift out of sync with the first (spec 042 F1).
63
+ */
64
+ export async function finalizeExternalRun(input, settle, options) {
65
+ const harness = getExternalHarness(input.harnessId);
66
+ const eventsPath = join(input.artifactDir, "events.jsonl");
67
+ const stderrPath = join(input.artifactDir, "stderr.log");
68
+ const eventsText = await readFile(eventsPath, "utf-8").catch(() => "");
69
+ const stderrTail = (await readFile(stderrPath, "utf-8").catch(() => "")).slice(-STDERR_TAIL_CHARS);
70
+ const outcome = harness
71
+ ? harness.parseOutcome({ eventsText, exitCode: input.exitCode, stderrTail })
72
+ : {
73
+ finalText: "",
74
+ terminalSeen: false,
75
+ protocolStatus: "unparsable",
76
+ usageKnown: false,
77
+ costKnown: false,
78
+ stderrTail,
79
+ errorMessage: `Unknown harness "${input.harnessId}"; cannot judge this run.`,
80
+ };
81
+ const settleInput = buildExternalSettleInput({
82
+ harnessId: input.harnessId,
83
+ outcome,
84
+ durationMs: input.durationMs,
85
+ durationEstimated: input.durationEstimated,
86
+ terminationReason: input.terminationReason,
87
+ maxWallTimeSec: input.maxWallTimeSec,
88
+ });
89
+ const shouldVerify = input.purpose === "verify" &&
90
+ input.taskId !== undefined &&
91
+ input.channelDir !== undefined &&
92
+ settleInput.status === "completed";
93
+ if (!shouldVerify) {
94
+ await settle(settleInput, options);
95
+ return;
96
+ }
97
+ // D9: an external verifier's tools cannot be structurally removed, so a before/after subject
98
+ // hash is the only after-the-fact check available. `subjectBefore` came from the launch-time
99
+ // snapshot (persisted so restart reconciliation has it too, spec 042 D1).
100
+ const subjectAfter = await workspaceSubjectHash(input.workingDirectory);
101
+ const verification = resolveVerificationOutcome({
102
+ subjectBefore: input.verifySubjectBefore,
103
+ subjectAfter,
104
+ finalText: outcome.finalText,
105
+ runFailed: false, // shouldVerify already gates on settleInput.status === "completed".
106
+ });
107
+ await writeVerificationAttestation(input.channelDir, {
108
+ runId: input.runId,
109
+ taskId: input.taskId,
110
+ verdict: verification.verdict,
111
+ checkedAt: formatLocalTime(),
112
+ evidence: verification.evidence,
113
+ workspaceChanged: verification.workspaceChanged,
114
+ subjectHash: verification.workspaceChanged ? undefined : subjectAfter,
115
+ subjectDir: input.workingDirectory,
116
+ // External verifiers cannot have their tools structurally removed the way an internal
117
+ // verifier's are — advisory, not enforced (D9).
118
+ verificationStrength: "advisory",
119
+ }).catch((error) => {
120
+ log.logWarning(`Failed to write verification attestation for run ${input.runId}`, errorMessage(error));
121
+ });
122
+ await settle({ ...settleInput, verificationVerdict: verification.verdict, verificationStrength: "advisory" }, options);
123
+ }
@@ -7,6 +7,10 @@ import type { RunRecord } from "./runs.js";
7
7
  */
8
8
  export declare function formatDuration(ms: number): string;
9
9
  export declare function elapsedMs(record: RunRecord, now?: number): number;
10
+ /** Spec 042 D1: a restart-reconciled run's duration is an estimate (from the artifact file's mtime
11
+ * or a wall-clock fallback), not a measured process lifetime — prefix it so a reader does not
12
+ * mistake it for a precise figure. */
13
+ export declare function formatRunDuration(record: RunRecord, now?: number): string;
10
14
  export declare function harnessLabel(record: RunRecord): string;
11
15
  /** `undefined` when cost genuinely is not known (e.g. `codex-cli`, `exec`) — never displayed as $0. */
12
16
  export declare function formatCost(record: RunRecord): string | undefined;
@@ -13,6 +13,13 @@ export function formatDuration(ms) {
13
13
  export function elapsedMs(record, now = Date.now()) {
14
14
  return (record.finishedAt ?? now) - record.startedAt;
15
15
  }
16
+ /** Spec 042 D1: a restart-reconciled run's duration is an estimate (from the artifact file's mtime
17
+ * or a wall-clock fallback), not a measured process lifetime — prefix it so a reader does not
18
+ * mistake it for a precise figure. */
19
+ export function formatRunDuration(record, now = Date.now()) {
20
+ const text = formatDuration(elapsedMs(record, now));
21
+ return record.durationEstimated ? `≈${text}` : text;
22
+ }
16
23
  export function harnessLabel(record) {
17
24
  return record.harness ? `${record.runtime}/${record.harness}` : record.runtime;
18
25
  }