@oyasmi/pipiclaw 0.9.2-beta.1 → 0.9.2-beta.3

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 (51) hide show
  1. package/dist/agent/channel-runner.d.ts +13 -0
  2. package/dist/agent/channel-runner.js +67 -19
  3. package/dist/agent/job-manager.js +3 -0
  4. package/dist/playbooks/agent-delegation.md +1 -1
  5. package/dist/playbooks/task-driving.md +3 -3
  6. package/dist/runtime/bootstrap.js +29 -7
  7. package/dist/runtime/channel-event.d.ts +8 -0
  8. package/dist/runtime/subagent-commands.d.ts +8 -0
  9. package/dist/runtime/subagent-commands.js +28 -4
  10. package/dist/runtime/task-commands.js +7 -2
  11. package/dist/runtime/task-wake.d.ts +7 -2
  12. package/dist/runtime/task-wake.js +22 -3
  13. package/dist/settings.d.ts +12 -0
  14. package/dist/settings.js +9 -0
  15. package/dist/subagents/external/claude-code.js +20 -0
  16. package/dist/subagents/external/codex-cli.js +33 -0
  17. package/dist/subagents/external/harness.d.ts +8 -0
  18. package/dist/subagents/external/progress-tail.d.ts +14 -0
  19. package/dist/subagents/external/progress-tail.js +84 -0
  20. package/dist/subagents/external/run.d.ts +6 -0
  21. package/dist/subagents/external/run.js +123 -58
  22. package/dist/subagents/external/settlement.d.ts +7 -1
  23. package/dist/subagents/external/settlement.js +28 -7
  24. package/dist/subagents/runs.d.ts +80 -8
  25. package/dist/subagents/runs.js +260 -58
  26. package/dist/subagents/tool.d.ts +4 -5
  27. package/dist/subagents/tool.js +73 -40
  28. package/dist/subagents/verification-outcome.js +1 -1
  29. package/dist/tasks/artifact-subject.d.ts +38 -4
  30. package/dist/tasks/artifact-subject.js +282 -25
  31. package/dist/tasks/verification.d.ts +24 -2
  32. package/dist/tasks/verification.js +113 -21
  33. package/dist/tools/grep.js +4 -1
  34. package/dist/tools/subagent-manage.js +14 -14
  35. package/dist/tools/task-manage/lifecycle.js +7 -4
  36. package/dist/tools/task-manage/verification.d.ts +1 -1
  37. package/dist/tools/task-manage/verification.js +12 -7
  38. package/dist/tui/pitui-frontend.js +3 -3
  39. package/examples/sub-agents/README.md +14 -13
  40. package/examples/sub-agents/builder-hard.md +17 -16
  41. package/examples/sub-agents/builder.md +16 -12
  42. package/examples/sub-agents/documenter.md +17 -17
  43. package/examples/sub-agents/explorer.md +12 -13
  44. package/examples/sub-agents/git-committer.md +15 -26
  45. package/examples/sub-agents/log-sifter.md +13 -12
  46. package/examples/sub-agents/planner.md +11 -11
  47. package/examples/sub-agents/reviewer.md +21 -12
  48. package/examples/sub-agents/scout.md +16 -12
  49. package/examples/sub-agents/verifier.md +18 -13
  50. package/examples/sub-agents/worker.md +17 -10
  51. package/package.json +5 -5
@@ -1,3 +1,4 @@
1
+ import { isRecord } from "../../shared/type-guards.js";
1
2
  import { detectExistingFlags, expandPlaceholders, formatDroppedPlaceholderWarnings, } from "./harness.js";
2
3
  /**
3
4
  * `codex-cli` harness (spec 040, D3/D4). One prompt, one short-lived process, NDJSON on stdout
@@ -130,4 +131,36 @@ export const codexCliHarness = {
130
131
  errorMessage,
131
132
  };
132
133
  },
134
+ // P1a: the two item types worth surfacing mid-run — the shell command a step is currently
135
+ // running, and todo-list progress. `agent_message`/everything else has nothing to show before
136
+ // the run is over.
137
+ toProgressLabel(line) {
138
+ let event;
139
+ try {
140
+ event = JSON.parse(line.trim());
141
+ }
142
+ catch {
143
+ return undefined;
144
+ }
145
+ if (typeof event !== "object" || event === null)
146
+ return undefined;
147
+ const record = event;
148
+ if (record.type !== "item.started" && record.type !== "item.updated")
149
+ return undefined;
150
+ const item = record.item;
151
+ if (!item)
152
+ return undefined;
153
+ if (item.type === "command_execution" && typeof item.command === "string") {
154
+ const firstLine = item.command.split("\n")[0]?.trim();
155
+ return firstLine ? firstLine.slice(0, 80) : undefined;
156
+ }
157
+ if (item.type === "todo_list" && Array.isArray(item.items)) {
158
+ const total = item.items.length;
159
+ if (total === 0)
160
+ return undefined;
161
+ const done = item.items.filter((entry) => isRecord(entry) && entry.completed === true).length;
162
+ return `待办 ${done}/${total}`;
163
+ }
164
+ return undefined;
165
+ },
133
166
  };
@@ -76,6 +76,14 @@ export interface ExternalHarness {
76
76
  /** Parse stdout into a unified outcome. Must never throw — a parse failure degrades to
77
77
  * `protocolStatus: "unparsable"`, not an exception (D4). */
78
78
  parseOutcome(input: ParseOutcomeInput): ExternalOutcome;
79
+ /**
80
+ * P1a: map one raw output line, still mid-run, to a short human-readable step label — e.g. the
81
+ * command a coding CLI just started, or a todo-list progress count. Same contract as
82
+ * `parseOutcome`: must never throw, and returns `undefined` for a line that carries no
83
+ * progress-worthy information (most lines). Optional — `exec` has no structured protocol to
84
+ * read mid-run, so it omits this entirely rather than implement a no-op.
85
+ */
86
+ toProgressLabel?(line: string): string | undefined;
79
87
  }
80
88
  /**
81
89
  * The D4 status table, shared by the live post-exit path and restart reconciliation (D10.3) so
@@ -0,0 +1,14 @@
1
+ import type { RunHarness } from "../runs.js";
2
+ export interface ExternalProgressTailInput {
3
+ artifactDir: string;
4
+ harnessId: RunHarness;
5
+ /** Process start time, so the "don't bother for a short run" window is measured from when the
6
+ * run actually started producing output, not from registration. */
7
+ startedAt: number;
8
+ onProgress: (label: string) => void;
9
+ }
10
+ export interface ExternalProgressTail {
11
+ stop(): void;
12
+ }
13
+ /** Starts polling; returns a handle whose `stop()` is idempotent and always safe to call. */
14
+ export declare function startExternalProgressTail(input: ExternalProgressTailInput): ExternalProgressTail;
@@ -0,0 +1,84 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { getExternalHarness } from "./registry.js";
4
+ /**
5
+ * P1a: turns an external run's `events.jsonl` — already being written incrementally by the child
6
+ * process — into a trickle of human-readable "what is it doing right now" notices, instead of the
7
+ * silence that today lasts the whole run. Polls rather than watches: correctness never depends on
8
+ * catching every write, so a missed tick just costs one extra poll interval of staleness, and one
9
+ * timer per run stays far simpler than a filesystem watcher per run.
10
+ *
11
+ * Deliberately re-reads the whole file each tick instead of tracking a byte offset: an offset read
12
+ * has to handle a half-written trailing line, this doesn't, and a run's artifact file is small
13
+ * enough (single-digit MB even for a long run) that re-reading it every `POLL_MS` costs nothing a
14
+ * background process needs to care about.
15
+ */
16
+ const POLL_MS = 15_000;
17
+ /** A run that finishes inside this window never gets a progress notice — the settled notice
18
+ * (P0-1) already covers it, and a 45s-or-shorter run does not need a running commentary. */
19
+ const FIRST_NOTICE_DELAY_MS = 45_000;
20
+ /** Floor between two progress notices for the same run, so a chatty harness cannot turn this into
21
+ * a stream of messages. */
22
+ const MIN_NOTICE_GAP_MS = 180_000;
23
+ /** Ceiling on notices for a single run — even a multi-hour run stops narrating after this many. */
24
+ const MAX_NOTICES = 6;
25
+ const NOOP_TAIL = { stop() { } };
26
+ /** Starts polling; returns a handle whose `stop()` is idempotent and always safe to call. */
27
+ export function startExternalProgressTail(input) {
28
+ const harness = getExternalHarness(input.harnessId);
29
+ const toProgressLabel = harness?.toProgressLabel;
30
+ if (!toProgressLabel)
31
+ return NOOP_TAIL; // exec, or a harness that hasn't implemented this.
32
+ const eventsPath = join(input.artifactDir, "events.jsonl");
33
+ let lastLabel;
34
+ let lastNoticeAt = 0;
35
+ let noticeCount = 0;
36
+ let stopped = false;
37
+ const tick = async () => {
38
+ if (stopped || noticeCount >= MAX_NOTICES)
39
+ return;
40
+ const now = Date.now();
41
+ if (now - input.startedAt < FIRST_NOTICE_DELAY_MS)
42
+ return;
43
+ if (lastNoticeAt && now - lastNoticeAt < MIN_NOTICE_GAP_MS)
44
+ return;
45
+ let text;
46
+ try {
47
+ text = await readFile(eventsPath, "utf-8");
48
+ }
49
+ catch {
50
+ return; // Not written yet, or already cleaned up — try again next tick.
51
+ }
52
+ // Walk from the end: the most recent line that actually maps to a label wins, so a trailing
53
+ // run of unlabeled lines (a text message, a torn final line) does not hide real progress.
54
+ const lines = text.split("\n");
55
+ let label;
56
+ for (let i = lines.length - 1; i >= 0; i--) {
57
+ const line = lines[i]?.trim();
58
+ if (!line)
59
+ continue;
60
+ try {
61
+ label = toProgressLabel(line);
62
+ }
63
+ catch {
64
+ label = undefined;
65
+ }
66
+ if (label)
67
+ break;
68
+ }
69
+ if (!label || label === lastLabel || stopped)
70
+ return;
71
+ lastLabel = label;
72
+ lastNoticeAt = now;
73
+ noticeCount++;
74
+ input.onProgress(label);
75
+ };
76
+ const timer = setInterval(() => void tick(), POLL_MS);
77
+ timer.unref?.();
78
+ return {
79
+ stop() {
80
+ stopped = true;
81
+ clearInterval(timer);
82
+ },
83
+ };
84
+ }
@@ -1,5 +1,6 @@
1
1
  import { spawn as nodeSpawn } from "node:child_process";
2
2
  import type { SecurityConfig } from "../../security/types.js";
3
+ import { probeCliVersion, readProcessStartTime } from "../../shared/host-process.js";
3
4
  import type { SubAgentThinkingLevel } from "../discovery.js";
4
5
  import { type RunMutates } from "../runs.js";
5
6
  /**
@@ -51,6 +52,11 @@ export interface LaunchExternalRunInput {
51
52
  securityConfig: SecurityConfig;
52
53
  /** Test seam: inject a fake `child_process.spawn`. */
53
54
  spawnFn?: typeof nodeSpawn;
55
+ /** Test seam: delay or replace the post-spawn process identity probe. The pid is persisted before
56
+ * this probe starts, so a daemon restart cannot mistake a live child for an intent-only run. */
57
+ readProcessStartTimeFn?: typeof readProcessStartTime;
58
+ /** Test seam: delay or replace the best-effort CLI version probe. */
59
+ probeCliVersionFn?: typeof probeCliVersion;
54
60
  }
55
61
  /**
56
62
  * Spec 042 D2: a pre-run failure (file open, spawn, or a cancel that lands before the process
@@ -8,7 +8,7 @@ import { killProcessGroup, probeCliVersion, readProcessStartTime, reapProcessGro
8
8
  import { splitShellWords } from "../../shared/shell-words.js";
9
9
  import { errorMessage } from "../../shared/text-utils.js";
10
10
  import { createEmptyUsageTotals } from "../../shared/types.js";
11
- import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
11
+ import { workspaceSubjectSnapshot } from "../../tasks/artifact-subject.js";
12
12
  import { getSubAgentRunManager } from "../runs.js";
13
13
  import { getExternalHarness } from "./registry.js";
14
14
  import { finalizeExternalRun } from "./settlement.js";
@@ -81,6 +81,18 @@ function mergeInvocationWarnings(warnings, droppedEnvVars) {
81
81
  const envWarning = `Dropped from this process's environment (add back via the role's env: if needed): ${droppedEnvVars.join(", ")}`;
82
82
  return warnings ? [...warnings, envWarning] : [envWarning];
83
83
  }
84
+ /** Close one of the parent-side descriptors without masking the launch error that triggered cleanup. */
85
+ function closeFd(fd) {
86
+ if (fd === undefined)
87
+ return;
88
+ try {
89
+ closeSync(fd);
90
+ }
91
+ catch {
92
+ // The child owns duplicated descriptors now; a parent-side close failure must not skip run
93
+ // settlement or lease release.
94
+ }
95
+ }
84
96
  function classifySpawnError(error) {
85
97
  const code = error.code;
86
98
  return code === "ENOENT" || code === "EACCES" ? "missing-binary" : "launch-failed";
@@ -115,8 +127,12 @@ export async function launchExternalRun(input) {
115
127
  await writeFile(systemPromptFile, `${input.systemPrompt.trim()}\n`, "utf-8");
116
128
  // D9: an external verifier's advisory attestation needs a before/after subject snapshot the
117
129
  // same way the internal path does — taken here, before the process starts, since this is the
118
- // earliest point at which the run is committed to running against this workingDirectory.
119
- const verifySubjectBefore = input.purpose === "verify" ? await workspaceSubjectHash(input.workingDirectory) : undefined;
130
+ // earliest point at which the run is committed to running against this workingDirectory. The
131
+ // fixed base and initial untracked manifest survive a later normal Git commit.
132
+ const verifySubjectSnapshot = input.purpose === "verify" ? await workspaceSubjectSnapshot(input.workingDirectory) : undefined;
133
+ const verifySubjectBefore = verifySubjectSnapshot?.hash;
134
+ const verifyBaseCommit = verifySubjectSnapshot?.baseCommit;
135
+ const verifyBaselineUntrackedPaths = verifySubjectSnapshot?.baselineUntrackedPaths;
120
136
  const argv = input.shell ? [] : splitShellWords(input.command);
121
137
  const invocation = input.shell
122
138
  ? { executable: "/bin/sh", args: ["-lc", input.command], resumable: false }
@@ -151,6 +167,7 @@ export async function launchExternalRun(input) {
151
167
  workingDirectory: input.workingDirectory,
152
168
  artifactDir: input.artifactDir,
153
169
  leaseKey: input.leaseKey,
170
+ mutates: input.mutates,
154
171
  });
155
172
  // The final executable/argv/cwd/capability record must be durable before a process can exist.
156
173
  // `external-agent` uses the strict appender path and rejects on queue or I/O failure; a failure
@@ -194,6 +211,8 @@ export async function launchExternalRun(input) {
194
211
  stderrFd = openSync(stderrPath, "a");
195
212
  }
196
213
  catch (error) {
214
+ closeFd(eventsFd);
215
+ closeFd(stderrFd);
197
216
  const reason = `Failed to open output files: ${errorMessage(error)}`;
198
217
  // Spec 042 D2: `announce: false` — this failure happened inside the same tool call that is
199
218
  // still on the stack; the caller reports it directly instead of waking the channel for a
@@ -215,8 +234,8 @@ export async function launchExternalRun(input) {
215
234
  });
216
235
  }
217
236
  catch (error) {
218
- closeSync(eventsFd);
219
- closeSync(stderrFd);
237
+ closeFd(eventsFd);
238
+ closeFd(stderrFd);
220
239
  const reason = `Failed to launch: ${errorMessage(error)}`;
221
240
  await runManager.settle(input.runId, failedSettleInput(reason), { announce: false });
222
241
  return {
@@ -227,8 +246,8 @@ export async function launchExternalRun(input) {
227
246
  }
228
247
  // The child has its own duped copy of both fds now; ours would otherwise leak across the
229
248
  // lifetime of a long-running daemon dispatching many external runs.
230
- closeSync(eventsFd);
231
- closeSync(stderrFd);
249
+ closeFd(eventsFd);
250
+ closeFd(stderrFd);
232
251
  const spawnFailure = await new Promise((resolve) => {
233
252
  child.once("error", (error) => resolve(error));
234
253
  child.once("spawn", () => resolve(undefined));
@@ -248,67 +267,103 @@ export async function launchExternalRun(input) {
248
267
  // `printf`) can exit and fire "close" before a listener registered after an async gap ever
249
268
  // gets attached — `EventEmitter` does not replay missed events, so that gap would hang this
250
269
  // run in `running` forever.
270
+ let childClosed = false;
251
271
  const closePromise = new Promise((resolve) => {
252
- child.once("close", (code) => resolve(code ?? undefined));
272
+ child.once("close", (code) => {
273
+ childClosed = true;
274
+ resolve(code ?? undefined);
275
+ });
253
276
  });
254
- if (cancelledBeforeSpawn) {
255
- void killProcessGroup(pid);
256
- const reason = "Cancelled while the external process was spawning.";
257
- await runManager.settle(input.runId, { ...failedSettleInput(reason), status: "cancelled" }, { announce: false });
258
- return { ok: false, kind: "cancelled", reason };
259
- }
260
- // The OS-verifiable identity check (D10.3): a restart tells this pid apart from an unrelated
261
- // process that later reuses the same number. `undefined` when `ps` itself is unavailable —
262
- // restore()/sweep() then fall back to trusting `isProcessAlive` alone. Run alongside the D12
263
- // CLI-version probe — neither depends on the other, and both are best-effort/bounded.
264
- const [pidStartedAt, cliVersion] = await Promise.all([
265
- readProcessStartTime(pid),
266
- probeCliVersion(invocation.executable),
267
- ]);
268
277
  const deadlineAt = processStartedAt + input.maxWallTimeSec * 1000;
269
- await runManager.setLaunched(input.runId, {
270
- pid,
271
- pidStartedAt,
272
- argv: spawnedArgv,
273
- deadlineAt,
274
- sessionId: invocation.presetSessionId,
275
- // Spec 042 D1: persisted so a restart reconciliation has the same inputs the live watcher
276
- // below would — without these, a run that finishes after the daemon disappears would settle
277
- // with an inaccurate timeout message, no verify attestation, and an unestimatable duration.
278
- verifySubjectBefore,
279
- maxWallTimeSec: input.maxWallTimeSec,
280
- processStartedAt,
281
- channelDir: input.channelDir,
282
- invocationWarnings: mergeInvocationWarnings(invocation.warnings, envFilterResult.dropped),
283
- // Spec 042 D12: distinguishes "the target CLI's schema drifted" from "the agent failed".
284
- parserVersion: harness.parserVersion,
285
- cliVersion,
286
- roleFingerprint: input.roleFingerprint,
287
- });
288
- if (child.stdin) {
289
- child.stdin.on("error", () => { }); // EPIPE if the process already exited; harmless.
290
- child.stdin.end(stdinContent);
278
+ // Persist the pid and every recovery input immediately after the spawn handshake. In particular,
279
+ // do not wait for `ps` or `<cli> --version`: either probe can be slow while the child is already
280
+ // writing the checkout. The probe results are useful diagnostics, not the launch safety gate.
281
+ try {
282
+ await runManager.setLaunched(input.runId, {
283
+ pid,
284
+ argv: spawnedArgv,
285
+ deadlineAt,
286
+ sessionId: invocation.presetSessionId,
287
+ // Spec 042 D1: persisted so a restart reconciliation has the same inputs the live watcher
288
+ // below would — without these, a run that finishes after the daemon disappears would settle
289
+ // with an inaccurate timeout message, no verify attestation, and an unestimatable duration.
290
+ verifySubjectBefore,
291
+ verifyBaseCommit,
292
+ verifyBaselineUntrackedPaths,
293
+ maxWallTimeSec: input.maxWallTimeSec,
294
+ processStartedAt,
295
+ channelDir: input.channelDir,
296
+ invocationWarnings: mergeInvocationWarnings(invocation.warnings, envFilterResult.dropped),
297
+ // Spec 042 D12: distinguishes "the target CLI's schema drifted" from "the agent failed".
298
+ parserVersion: harness.parserVersion,
299
+ roleFingerprint: input.roleFingerprint,
300
+ });
291
301
  }
302
+ catch (error) {
303
+ // The child already exists, but its pid could not be made durable. Stop it before
304
+ // releasing the lease; otherwise a write verifier could continue mutating the checkout
305
+ // after the caller has observed a launch failure and another writer has entered.
306
+ await killProcessGroup(pid).catch(() => undefined);
307
+ await closePromise;
308
+ const reason = `Failed to persist external launch state: ${errorMessage(error)}`;
309
+ await runManager.settle(input.runId, failedSettleInput(reason), { announce: false }).catch((settleError) => {
310
+ log.logWarning(`Failed to settle external run ${input.runId} after launch persistence failed`, errorMessage(settleError));
311
+ });
312
+ throw error;
313
+ }
314
+ // From this point on cancellation has a real process-group handle. Install it before the
315
+ // best-effort probes and before the pre-spawn cancellation branch, so a cancel cannot release
316
+ // the verifier's lease while this child is still able to write.
292
317
  runManager.registerCancelHandle(input.runId, () => {
293
318
  void killProcessGroup(pid);
294
319
  });
295
- // The narrow window between the pre-spawn placeholder handle (claimExternalLaunch) and the
296
- // real one just above: a cancel arriving there durably marked `terminationReason` (P1-1) but
297
- // had no live process to kill yet. Act on it now.
298
- if (runManager.get(input.runId)?.terminationReason === "cancelled") {
299
- void killProcessGroup(pid);
320
+ if (child.stdin) {
321
+ child.stdin.on("error", () => { }); // EPIPE if the process already exited; harmless.
322
+ child.stdin.end(stdinContent);
300
323
  }
301
- // Prompt, same-process enforcement. Restart recovery persists this same deadline and installs
302
- // one replacement check only when it actually adopts a still-running process.
303
324
  const wallClockTimer = setTimeout(() => {
325
+ if (childClosed)
326
+ return;
304
327
  void runManager.markTerminationReason(input.runId, "timeout").then(() => killProcessGroup(pid));
305
328
  }, input.maxWallTimeSec * 1000);
306
329
  wallClockTimer.unref?.();
307
- // Deliberately not awaited by the caller (D2: external's sync grace window is 0) — this
308
- // continues in the background and settles the run itself once the process exits.
330
+ if (cancelledBeforeSpawn) {
331
+ clearTimeout(wallClockTimer);
332
+ // Do not release the write lease until the spawned child group has received its terminal
333
+ // signal and emitted close. The placeholder cancellation handle can race the spawn
334
+ // confirmation; settling first would admit another writer while this verifier was still able
335
+ // to write.
336
+ await killProcessGroup(pid);
337
+ await closePromise;
338
+ const reason = "Cancelled while the external process was spawning.";
339
+ await runManager.settle(input.runId, { ...failedSettleInput(reason), status: "cancelled" }, { announce: false });
340
+ return { ok: false, kind: "cancelled", reason };
341
+ }
342
+ // The OS-verifiable identity check (D10.3): a restart tells this pid apart from an unrelated
343
+ // process that later reuses the same number. `undefined` when `ps` is unavailable — restore()
344
+ // treats a conflict as unsafe to signal, while ordinary adoption remains conservative. Run
345
+ // alongside the D12 CLI-version probe — neither depends on the other, and both are best-effort.
346
+ const launchMetadataPromise = Promise.all([
347
+ Promise.resolve().then(() => (input.readProcessStartTimeFn ?? readProcessStartTime)(pid)),
348
+ Promise.resolve().then(() => (input.probeCliVersionFn ?? probeCliVersion)(invocation.executable)),
349
+ ])
350
+ .then(async ([pidStartedAt, cliVersion]) => {
351
+ await runManager
352
+ .updateLaunchMetadata(input.runId, { pidStartedAt, cliVersion })
353
+ .catch((error) => log.logWarning(`Failed to persist launch probes for run ${input.runId}`, errorMessage(error)));
354
+ })
355
+ .catch((error) => {
356
+ // The production probes are already best-effort; keep the same property for test seams or
357
+ // a future host implementation and never leave a spawned child unobserved because metadata
358
+ // collection failed.
359
+ log.logWarning(`Failed to collect launch probes for run ${input.runId}`, errorMessage(error));
360
+ });
361
+ // Deliberately attach the close watcher before waiting for probe metadata. A fast child can exit
362
+ // during that wait; the promise is already listening, and finalization waits for the launch
363
+ // metadata promise so terminal publication still follows the same safe order.
309
364
  void closePromise.then(async (exitCode) => {
365
+ await launchMetadataPromise;
310
366
  clearTimeout(wallClockTimer);
311
- runManager.clearCancelHandle(input.runId);
312
367
  // Spec 042 D8: this fires on every exit (normal, cancelled, or timed out) as a backup reap —
313
368
  // a cancel/timeout already killed the group via its own call site above. The common case
314
369
  // (nothing left) returns immediately with no signal and no wait; only a genuinely lingering
@@ -317,10 +372,10 @@ export async function launchExternalRun(input) {
317
372
  const durationMs = Date.now() - processStartedAt;
318
373
  const terminationReason = runManager.get(input.runId)?.terminationReason;
319
374
  // Spec 042 D1: parse whatever the process actually wrote *before* applying a cancel/timeout
320
- // override, instead of returning early on those two reasons. A run killed for wall-time
321
- // budget or cancelled by request may still have produced useful output, usage, and a
322
- // resumable session id — `finalizeExternalRun` keeps all of that; only `status` and
323
- // `failureReason` get overridden by `terminationReason` (P1-1).
375
+ // override, instead of returning early on those two reasons. A run killed for wall-time budget
376
+ // or cancelled by request may still have produced useful output, usage, and a resumable session
377
+ // id — `finalizeExternalRun` keeps all of that; only `status` and `failureReason` get overridden
378
+ // by `terminationReason` (P1-1).
324
379
  await finalizeExternalRun({
325
380
  runId: input.runId,
326
381
  channelId: input.channelId,
@@ -335,10 +390,20 @@ export async function launchExternalRun(input) {
335
390
  terminationReason,
336
391
  maxWallTimeSec: input.maxWallTimeSec,
337
392
  verifySubjectBefore,
393
+ verifyBaseCommit,
394
+ verifyBaselineUntrackedPaths,
395
+ mutates: input.mutates,
338
396
  }, (settleInput, options) => runManager.settle(input.runId, settleInput, options), { announce: terminationReason !== "cancelled" }).catch((error) => {
339
397
  log.logWarning(`Failed to settle external run ${input.runId}`, errorMessage(error));
340
398
  });
341
399
  });
400
+ await launchMetadataPromise;
401
+ // The narrow window between the pre-spawn placeholder handle (claimExternalLaunch) and the
402
+ // real one just above: a cancel arriving there durably marked `terminationReason` (P1-1) but
403
+ // had no live process to kill yet. Act on it now.
404
+ if (runManager.get(input.runId)?.terminationReason === "cancelled") {
405
+ void killProcessGroup(pid);
406
+ }
342
407
  return { ok: true };
343
408
  function failedSettleInput(reason) {
344
409
  return {
@@ -1,4 +1,4 @@
1
- import type { RunHarness, SettleInput } from "../runs.js";
1
+ import type { RunHarness, RunMutates, SettleInput } from "../runs.js";
2
2
  import { type ExternalOutcome } from "./harness.js";
3
3
  export interface BuildExternalSettleInputInput {
4
4
  harnessId: RunHarness;
@@ -36,6 +36,12 @@ export interface FinalizeExternalRunInput {
36
36
  /** The workspace subject hash taken just before this run started (D9's before/after pair for
37
37
  * external verify) — persisted at launch so restart reconciliation has it too. */
38
38
  verifySubjectBefore?: string;
39
+ /** Fixed verification base and initial untracked manifest, persisted for restart reconciliation. */
40
+ verifyBaseCommit?: string;
41
+ verifyBaselineUntrackedPaths?: string[];
42
+ /** P2-2: only a `write` run's completion pays for a `git status` summary — a `read` run cannot
43
+ * have changed anything, and this must never become a hidden cost on the common read-only path. */
44
+ mutates?: RunMutates;
39
45
  }
40
46
  /**
41
47
  * Read this run's artifact files, parse them through its harness, decide its verdict (including a
@@ -3,7 +3,7 @@ import { join } from "node:path";
3
3
  import * as log from "../../log.js";
4
4
  import { formatLocalTime } from "../../shared/local-time.js";
5
5
  import { errorMessage } from "../../shared/text-utils.js";
6
- import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
6
+ import { changedPathsSummary, workspaceSubjectHash } from "../../tasks/artifact-subject.js";
7
7
  import { writeVerificationAttestation } from "../../tasks/verification.js";
8
8
  import { resolveVerificationOutcome } from "../verification-outcome.js";
9
9
  import { classifyExternalOutcome } from "./harness.js";
@@ -78,7 +78,7 @@ export async function finalizeExternalRun(input, settle, options) {
78
78
  stderrTail,
79
79
  errorMessage: `Unknown harness "${input.harnessId}"; cannot judge this run.`,
80
80
  };
81
- const settleInput = buildExternalSettleInput({
81
+ let settleInput = buildExternalSettleInput({
82
82
  harnessId: input.harnessId,
83
83
  outcome,
84
84
  durationMs: input.durationMs,
@@ -86,6 +86,13 @@ export async function finalizeExternalRun(input, settle, options) {
86
86
  terminationReason: input.terminationReason,
87
87
  maxWallTimeSec: input.maxWallTimeSec,
88
88
  });
89
+ // P2-2: only for a run that actually could have changed the working directory, and only once it
90
+ // is known to have finished cleanly — best-effort, never blocks or fails settlement.
91
+ if (input.mutates === "write" && settleInput.status === "completed") {
92
+ const workspaceSummary = await changedPathsSummary(input.workingDirectory).catch(() => undefined);
93
+ if (workspaceSummary)
94
+ settleInput = { ...settleInput, workspaceSummary };
95
+ }
89
96
  const shouldVerify = input.purpose === "verify" &&
90
97
  input.taskId !== undefined &&
91
98
  input.channelDir !== undefined &&
@@ -95,15 +102,26 @@ export async function finalizeExternalRun(input, settle, options) {
95
102
  return;
96
103
  }
97
104
  // 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);
105
+ // hash is the only after-the-fact check available. The base and untracked baseline came from the
106
+ // launch-time snapshot (persisted so restart reconciliation has it too).
107
+ const baseSubjectAvailable = input.verifyBaseCommit !== undefined && input.verifyBaselineUntrackedPaths !== undefined;
108
+ const partialBaseSubject = input.verifyBaseCommit !== undefined && input.verifyBaselineUntrackedPaths === undefined;
109
+ const subjectAfter = partialBaseSubject
110
+ ? undefined
111
+ : await workspaceSubjectHash(input.workingDirectory, baseSubjectAvailable
112
+ ? {
113
+ baseCommit: input.verifyBaseCommit,
114
+ baselineUntrackedPaths: input.verifyBaselineUntrackedPaths,
115
+ }
116
+ : {});
101
117
  const verification = resolveVerificationOutcome({
102
118
  subjectBefore: input.verifySubjectBefore,
103
119
  subjectAfter,
104
120
  finalText: outcome.finalText,
105
121
  runFailed: false, // shouldVerify already gates on settleInput.status === "completed".
106
122
  });
123
+ const legacySubjectAvailable = input.verifyBaseCommit === undefined && input.verifySubjectBefore !== undefined;
124
+ const subjectAvailable = !verification.workspaceChanged && subjectAfter !== undefined && (baseSubjectAvailable || legacySubjectAvailable);
107
125
  await writeVerificationAttestation(input.channelDir, {
108
126
  runId: input.runId,
109
127
  taskId: input.taskId,
@@ -111,8 +129,11 @@ export async function finalizeExternalRun(input, settle, options) {
111
129
  checkedAt: formatLocalTime(),
112
130
  evidence: verification.evidence,
113
131
  workspaceChanged: verification.workspaceChanged,
114
- subjectHash: verification.workspaceChanged ? undefined : subjectAfter,
115
- subjectDir: input.workingDirectory,
132
+ subjectHash: subjectAvailable ? subjectAfter : undefined,
133
+ subjectDir: subjectAvailable ? input.workingDirectory : undefined,
134
+ subjectMode: subjectAvailable ? (baseSubjectAvailable ? "base-relative" : "legacy-head") : undefined,
135
+ subjectBaseCommit: subjectAvailable && baseSubjectAvailable ? input.verifyBaseCommit : undefined,
136
+ subjectBaselineUntrackedPaths: subjectAvailable && baseSubjectAvailable ? input.verifyBaselineUntrackedPaths : undefined,
116
137
  // External verifiers cannot have their tools structurally removed the way an internal
117
138
  // verifier's are — advisory, not enforced (D9).
118
139
  verificationStrength: "advisory",