@oyasmi/pipiclaw 0.9.1 → 0.9.2-beta.2

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 (167) hide show
  1. package/dist/agent/channel-runner.d.ts +15 -1
  2. package/dist/agent/channel-runner.js +76 -24
  3. package/dist/agent/effect-ledger.js +9 -2
  4. package/dist/agent/job-manager.d.ts +4 -0
  5. package/dist/agent/job-manager.js +17 -2
  6. package/dist/agent/prompt/manifest.d.ts +1 -1
  7. package/dist/agent/prompt/manifest.js +1 -1
  8. package/dist/agent/prompt/sections.js +8 -5
  9. package/dist/agent/session-events.d.ts +2 -0
  10. package/dist/agent/session-events.js +29 -14
  11. package/dist/agent/turn-recovery.js +2 -2
  12. package/dist/agent/type-guards.js +5 -1
  13. package/dist/agent/workspace-resources.d.ts +2 -2
  14. package/dist/agent/workspace-resources.js +41 -3
  15. package/dist/executor.d.ts +14 -0
  16. package/dist/executor.js +96 -24
  17. package/dist/file-store.d.ts +96 -0
  18. package/dist/file-store.js +189 -0
  19. package/dist/memory/consolidation.js +2 -26
  20. package/dist/memory/files.js +7 -7
  21. package/dist/memory/maintenance-jobs.js +2 -34
  22. package/dist/memory/maintenance-state.js +2 -1
  23. package/dist/memory/recall.d.ts +10 -0
  24. package/dist/memory/recall.js +15 -7
  25. package/dist/memory/session-search.js +6 -22
  26. package/dist/memory/transcript.d.ts +10 -0
  27. package/dist/memory/transcript.js +39 -0
  28. package/dist/playbooks/agent-delegation.md +7 -5
  29. package/dist/playbooks/background-jobs.md +1 -1
  30. package/dist/playbooks/catalog.d.ts +1 -1
  31. package/dist/playbooks/catalog.js +1 -1
  32. package/dist/playbooks/event-scheduling.md +2 -0
  33. package/dist/playbooks/memory-and-learning.md +11 -11
  34. package/dist/playbooks/runtime-orientation.md +3 -3
  35. package/dist/playbooks/task-driving.md +7 -7
  36. package/dist/playbooks/task-planning.md +5 -5
  37. package/dist/runtime/app-home.js +1 -1
  38. package/dist/runtime/bootstrap.js +10 -0
  39. package/dist/runtime/dingtalk.js +3 -2
  40. package/dist/runtime/durable-dispatch.d.ts +26 -1
  41. package/dist/runtime/durable-dispatch.js +51 -5
  42. package/dist/runtime/event-commands.js +7 -16
  43. package/dist/runtime/events.d.ts +4 -2
  44. package/dist/runtime/events.js +15 -20
  45. package/dist/runtime/subagent-commands.js +1 -1
  46. package/dist/runtime/task-commands.d.ts +1 -1
  47. package/dist/runtime/task-commands.js +17 -12
  48. package/dist/runtime/task-driver.js +2 -2
  49. package/dist/runtime/task-wake.d.ts +2 -2
  50. package/dist/runtime/task-wake.js +2 -2
  51. package/dist/security/block-message.d.ts +11 -0
  52. package/dist/security/block-message.js +12 -0
  53. package/dist/security/path-guard-check.d.ts +13 -0
  54. package/dist/security/path-guard-check.js +39 -0
  55. package/dist/security/path-guard.js +32 -14
  56. package/dist/settings.js +3 -2
  57. package/dist/shared/atomic-file.d.ts +17 -1
  58. package/dist/shared/atomic-file.js +50 -3
  59. package/dist/shared/duration.d.ts +2 -0
  60. package/dist/shared/duration.js +7 -0
  61. package/dist/shared/safe-id.d.ts +19 -0
  62. package/dist/shared/safe-id.js +24 -0
  63. package/dist/shared/text-utils.d.ts +1 -1
  64. package/dist/shared/text-utils.js +3 -8
  65. package/dist/shared/type-guards.d.ts +2 -0
  66. package/dist/shared/type-guards.js +4 -0
  67. package/dist/subagents/discovery.d.ts +44 -17
  68. package/dist/subagents/discovery.js +82 -111
  69. package/dist/subagents/external/claude-code.js +1 -3
  70. package/dist/subagents/external/harness.d.ts +1 -1
  71. package/dist/subagents/external/run.d.ts +6 -0
  72. package/dist/subagents/external/run.js +122 -58
  73. package/dist/subagents/external/settlement.d.ts +3 -0
  74. package/dist/subagents/external/settlement.js +19 -5
  75. package/dist/subagents/format.d.ts +3 -2
  76. package/dist/subagents/format.js +3 -7
  77. package/dist/subagents/runs.d.ts +45 -9
  78. package/dist/subagents/runs.js +184 -64
  79. package/dist/subagents/tool.d.ts +35 -24
  80. package/dist/subagents/tool.js +631 -577
  81. package/dist/subagents/verification-outcome.js +1 -1
  82. package/dist/subagents/workspace-lease.js +1 -1
  83. package/dist/tasks/artifact-subject.d.ts +30 -4
  84. package/dist/tasks/artifact-subject.js +257 -25
  85. package/dist/tasks/control.js +7 -9
  86. package/dist/tasks/ledger.d.ts +2 -2
  87. package/dist/tasks/ledger.js +3 -7
  88. package/dist/tasks/transitions.d.ts +5 -1
  89. package/dist/tasks/transitions.js +2 -2
  90. package/dist/tasks/verification.d.ts +24 -2
  91. package/dist/tasks/verification.js +113 -21
  92. package/dist/tools/bash.d.ts +0 -1
  93. package/dist/tools/bash.js +45 -40
  94. package/dist/tools/config.d.ts +6 -1
  95. package/dist/tools/config.js +9 -0
  96. package/dist/tools/edit.d.ts +2 -3
  97. package/dist/tools/edit.js +274 -86
  98. package/dist/tools/event-manage.d.ts +13 -7
  99. package/dist/tools/event-manage.js +52 -14
  100. package/dist/tools/glob-match.d.ts +11 -0
  101. package/dist/tools/glob-match.js +75 -0
  102. package/dist/tools/glob.d.ts +15 -0
  103. package/dist/tools/glob.js +113 -0
  104. package/dist/tools/grep.d.ts +0 -1
  105. package/dist/tools/grep.js +57 -42
  106. package/dist/tools/ignore-dirs.d.ts +6 -0
  107. package/dist/tools/ignore-dirs.js +15 -0
  108. package/dist/tools/index.d.ts +3 -0
  109. package/dist/tools/index.js +50 -40
  110. package/dist/tools/job.d.ts +0 -1
  111. package/dist/tools/job.js +1 -8
  112. package/dist/tools/line-index.d.ts +16 -0
  113. package/dist/tools/line-index.js +76 -0
  114. package/dist/tools/memory-manage.d.ts +20 -8
  115. package/dist/tools/memory-manage.js +65 -92
  116. package/dist/tools/presentation.d.ts +2 -0
  117. package/dist/tools/presentation.js +109 -0
  118. package/dist/tools/read.d.ts +2 -2
  119. package/dist/tools/read.js +97 -133
  120. package/dist/tools/registry.d.ts +4 -1
  121. package/dist/tools/registry.js +89 -22
  122. package/dist/tools/send-media.d.ts +6 -6
  123. package/dist/tools/send-media.js +16 -49
  124. package/dist/tools/session-search.d.ts +0 -1
  125. package/dist/tools/session-search.js +0 -1
  126. package/dist/tools/skill-security.d.ts +0 -2
  127. package/dist/tools/skill-security.js +0 -24
  128. package/dist/tools/skill.d.ts +31 -0
  129. package/dist/tools/skill.js +153 -0
  130. package/dist/tools/subagent-manage.d.ts +6 -5
  131. package/dist/tools/subagent-manage.js +60 -60
  132. package/dist/tools/task-manage/create.d.ts +2 -2
  133. package/dist/tools/task-manage/create.js +1 -3
  134. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  135. package/dist/tools/task-manage/lifecycle.js +56 -60
  136. package/dist/tools/task-manage/schema.d.ts +27 -15
  137. package/dist/tools/task-manage/schema.js +58 -74
  138. package/dist/tools/task-manage/shared.d.ts +11 -6
  139. package/dist/tools/task-manage/shared.js +30 -21
  140. package/dist/tools/task-manage/types.d.ts +14 -15
  141. package/dist/tools/task-manage/verification.d.ts +5 -5
  142. package/dist/tools/task-manage/verification.js +18 -15
  143. package/dist/tools/task-manage.d.ts +8 -11
  144. package/dist/tools/task-manage.js +63 -50
  145. package/dist/tools/tool-details.d.ts +17 -1
  146. package/dist/tools/tool-details.js +24 -0
  147. package/dist/tools/truncate.d.ts +5 -5
  148. package/dist/tools/truncate.js +5 -5
  149. package/dist/tools/web-fetch.d.ts +0 -1
  150. package/dist/tools/web-fetch.js +0 -1
  151. package/dist/tools/web-search.d.ts +0 -1
  152. package/dist/tools/web-search.js +0 -1
  153. package/dist/tools/write-content.d.ts +3 -3
  154. package/dist/tools/write-content.js +12 -51
  155. package/dist/tools/write.d.ts +2 -3
  156. package/dist/tools/write.js +3 -4
  157. package/dist/tui/pitui-frontend.js +3 -3
  158. package/dist/usage/ledger.js +7 -4
  159. package/examples/sub-agents/README.md +13 -13
  160. package/examples/sub-agents/documenter.md +2 -1
  161. package/examples/sub-agents/reviewer.md +2 -0
  162. package/examples/sub-agents/scout.md +2 -1
  163. package/examples/sub-agents/verifier.md +6 -4
  164. package/examples/sub-agents/worker.md +2 -1
  165. package/package.json +5 -5
  166. package/dist/tools/skill-manage.d.ts +0 -41
  167. package/dist/tools/skill-manage.js +0 -232
@@ -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,19 @@ export async function launchExternalRun(input) {
335
390
  terminationReason,
336
391
  maxWallTimeSec: input.maxWallTimeSec,
337
392
  verifySubjectBefore,
393
+ verifyBaseCommit,
394
+ verifyBaselineUntrackedPaths,
338
395
  }, (settleInput, options) => runManager.settle(input.runId, settleInput, options), { announce: terminationReason !== "cancelled" }).catch((error) => {
339
396
  log.logWarning(`Failed to settle external run ${input.runId}`, errorMessage(error));
340
397
  });
341
398
  });
399
+ await launchMetadataPromise;
400
+ // The narrow window between the pre-spawn placeholder handle (claimExternalLaunch) and the
401
+ // real one just above: a cancel arriving there durably marked `terminationReason` (P1-1) but
402
+ // had no live process to kill yet. Act on it now.
403
+ if (runManager.get(input.runId)?.terminationReason === "cancelled") {
404
+ void killProcessGroup(pid);
405
+ }
342
406
  return { ok: true };
343
407
  function failedSettleInput(reason) {
344
408
  return {
@@ -36,6 +36,9 @@ 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[];
39
42
  }
40
43
  /**
41
44
  * Read this run's artifact files, parse them through its harness, decide its verdict (including a
@@ -95,15 +95,26 @@ export async function finalizeExternalRun(input, settle, options) {
95
95
  return;
96
96
  }
97
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);
98
+ // hash is the only after-the-fact check available. The base and untracked baseline came from the
99
+ // launch-time snapshot (persisted so restart reconciliation has it too).
100
+ const baseSubjectAvailable = input.verifyBaseCommit !== undefined && input.verifyBaselineUntrackedPaths !== undefined;
101
+ const partialBaseSubject = input.verifyBaseCommit !== undefined && input.verifyBaselineUntrackedPaths === undefined;
102
+ const subjectAfter = partialBaseSubject
103
+ ? undefined
104
+ : await workspaceSubjectHash(input.workingDirectory, baseSubjectAvailable
105
+ ? {
106
+ baseCommit: input.verifyBaseCommit,
107
+ baselineUntrackedPaths: input.verifyBaselineUntrackedPaths,
108
+ }
109
+ : {});
101
110
  const verification = resolveVerificationOutcome({
102
111
  subjectBefore: input.verifySubjectBefore,
103
112
  subjectAfter,
104
113
  finalText: outcome.finalText,
105
114
  runFailed: false, // shouldVerify already gates on settleInput.status === "completed".
106
115
  });
116
+ const legacySubjectAvailable = input.verifyBaseCommit === undefined && input.verifySubjectBefore !== undefined;
117
+ const subjectAvailable = !verification.workspaceChanged && subjectAfter !== undefined && (baseSubjectAvailable || legacySubjectAvailable);
107
118
  await writeVerificationAttestation(input.channelDir, {
108
119
  runId: input.runId,
109
120
  taskId: input.taskId,
@@ -111,8 +122,11 @@ export async function finalizeExternalRun(input, settle, options) {
111
122
  checkedAt: formatLocalTime(),
112
123
  evidence: verification.evidence,
113
124
  workspaceChanged: verification.workspaceChanged,
114
- subjectHash: verification.workspaceChanged ? undefined : subjectAfter,
115
- subjectDir: input.workingDirectory,
125
+ subjectHash: subjectAvailable ? subjectAfter : undefined,
126
+ subjectDir: subjectAvailable ? input.workingDirectory : undefined,
127
+ subjectMode: subjectAvailable ? (baseSubjectAvailable ? "base-relative" : "legacy-head") : undefined,
128
+ subjectBaseCommit: subjectAvailable && baseSubjectAvailable ? input.verifyBaseCommit : undefined,
129
+ subjectBaselineUntrackedPaths: subjectAvailable && baseSubjectAvailable ? input.verifyBaselineUntrackedPaths : undefined,
116
130
  // External verifiers cannot have their tools structurally removed the way an internal
117
131
  // verifier's are — advisory, not enforced (D9).
118
132
  verificationStrength: "advisory",
@@ -1,11 +1,12 @@
1
+ import { formatDuration } from "../shared/duration.js";
1
2
  import type { RunRecord } from "./runs.js";
2
3
  /**
3
4
  * Shared display primitives for delegation runs (spec 041), used by both the model-facing
4
- * `subagent_manage` tool and the human-facing `/subagents` runtime command. Only the pieces that
5
+ * `subagent_list`/`subagent_run` tools and the human-facing `/subagents` runtime command. Only the pieces that
5
6
  * are genuinely language/audience-neutral live here — duration math, the harness label, and the
6
7
  * cost guard — not full line templates, since the two surfaces render in different languages.
7
8
  */
8
- export declare function formatDuration(ms: number): string;
9
+ export { formatDuration };
9
10
  export declare function elapsedMs(record: RunRecord, now?: number): number;
10
11
  /** Spec 042 D1: a restart-reconciled run's duration is an estimate (from the artifact file's mtime
11
12
  * or a wall-clock fallback), not a measured process lifetime — prefix it so a reader does not
@@ -1,15 +1,11 @@
1
+ import { formatDuration } from "../shared/duration.js";
1
2
  /**
2
3
  * Shared display primitives for delegation runs (spec 041), used by both the model-facing
3
- * `subagent_manage` tool and the human-facing `/subagents` runtime command. Only the pieces that
4
+ * `subagent_list`/`subagent_run` tools and the human-facing `/subagents` runtime command. Only the pieces that
4
5
  * are genuinely language/audience-neutral live here — duration math, the harness label, and the
5
6
  * cost guard — not full line templates, since the two surfaces render in different languages.
6
7
  */
7
- export function formatDuration(ms) {
8
- const seconds = Math.round(ms / 1000);
9
- if (seconds < 60)
10
- return `${seconds}s`;
11
- return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
12
- }
8
+ export { formatDuration };
13
9
  export function elapsedMs(record, now = Date.now()) {
14
10
  return (record.finishedAt ?? now) - record.startedAt;
15
11
  }
@@ -75,10 +75,16 @@ export interface RunRecord extends RunUsage {
75
75
  turns?: number;
76
76
  toolCalls?: number;
77
77
  verificationVerdict?: "pass" | "fail";
78
- /** `enforced` for a built-in verifier (tools structurally removed); `advisory` for external (D9). */
78
+ /** `enforced` only for a structurally read-only verifier; write-capable/external runs are advisory. */
79
79
  verificationStrength?: "enforced" | "advisory";
80
80
  /** Set once settlement (write output, free resources) has happened; guards against replay. */
81
81
  settledAt?: number;
82
+ /**
83
+ * Durable settlement intent. While this exists the public status remains `running` and the
84
+ * lease is still held; it lets a restart finish a settlement that crashed after the intent was
85
+ * recorded but before the terminal record was published.
86
+ */
87
+ settlementPending?: PendingSettlement;
82
88
  /** Set once this run's usage has been written to the ledger; guards against double billing. */
83
89
  usageRecorded?: boolean;
84
90
  /** Set once the completion wake has been hallmarked for delivery; guards against a duplicate wake. */
@@ -101,10 +107,11 @@ export interface RunRecord extends RunUsage {
101
107
  sessionId?: string;
102
108
  leaseKey?: string;
103
109
  mutates?: RunMutates;
104
- /** Spec 042 D1: persisted at launch so restart reconciliation has the same inputs a live
105
- * watcher would — the workspace subject hash taken just before an external verify run
106
- * started, so a restart can still write its attestation instead of silently skipping it. */
110
+ /** Persisted at launch so restart reconciliation has the same inputs as a live verifier. */
107
111
  verifySubjectBefore?: string;
112
+ /** Fixed commit and initial untracked manifest for the base-relative verification subject. */
113
+ verifyBaseCommit?: string;
114
+ verifyBaselineUntrackedPaths?: string[];
108
115
  /** Spec 042 D1: the role's wall-time budget, persisted so restart reconciliation can report an
109
116
  * accurate "budget exceeded (Ns)" reason instead of reverse-engineering it from `deadlineAt`. */
110
117
  maxWallTimeSec?: number;
@@ -148,6 +155,23 @@ export interface RegisterRunInput {
148
155
  artifactDir: string;
149
156
  /** Set only when the caller already holds a workspace write lease for this run (D10.1). */
150
157
  leaseKey?: string;
158
+ mutates?: RunMutates;
159
+ }
160
+ interface PendingSettlement {
161
+ status: SettleInput["status"];
162
+ failureReason?: string;
163
+ usage: UsageTotals;
164
+ usageKnown: boolean;
165
+ costKnown: boolean;
166
+ turns: number;
167
+ toolCalls: number;
168
+ durationMs: number;
169
+ durationEstimated?: boolean;
170
+ verificationVerdict?: "pass" | "fail";
171
+ verificationStrength?: "enforced" | "advisory";
172
+ sessionId?: string;
173
+ finishedAt: number;
174
+ announce: boolean;
151
175
  }
152
176
  export interface SettleInput {
153
177
  status: "completed" | "failed" | "cancelled" | "lost";
@@ -185,9 +209,9 @@ export declare class SubAgentRunManager {
185
209
  private readonly channelId;
186
210
  private readonly options;
187
211
  private readonly runs;
188
- /** In-memory cancel handles for runs alive in *this* process (internal runs; external process
189
- * kill goes through pid, not this map, once phase 2/3 lands). Never persisted: a restart loses
190
- * the only thing that could reach an in-process worker anyway (D10.3). */
212
+ /** In-memory cancel handles for runs alive in *this* process (internal worker abort or live
213
+ * external process-group kill). Never persisted: a restart cannot reach an in-process worker,
214
+ * while adopted external runs are cancelled through their persisted pid (D10.3). */
191
215
  private readonly cancelHandles;
192
216
  /** External launch intents exist before a safe live child handle does. A cancel in that window
193
217
  * is remembered here and consumed before spawn, rather than spawning a process nothing can cancel. */
@@ -242,6 +266,8 @@ export declare class SubAgentRunManager {
242
266
  * before the process exits — restore/deadline recovery must have the same inputs a live watcher
243
267
  * would, not a thinner subset. */
244
268
  verifySubjectBefore?: string;
269
+ verifyBaseCommit?: string;
270
+ verifyBaselineUntrackedPaths?: string[];
245
271
  maxWallTimeSec?: number;
246
272
  processStartedAt?: number;
247
273
  channelDir?: string;
@@ -256,6 +282,12 @@ export declare class SubAgentRunManager {
256
282
  parserVersion?: number;
257
283
  cliVersion?: string;
258
284
  }): Promise<void>;
285
+ /** Persist best-effort probe results after the pid/launch recovery record is already durable.
286
+ * A slow or unavailable `ps`/`--version` probe must never reopen the post-spawn recovery window. */
287
+ updateLaunchMetadata(runId: string, info: {
288
+ pidStartedAt?: string;
289
+ cliVersion?: string;
290
+ }): Promise<void>;
259
291
  /** Reserve a task wake exactly once. A replay of the same durable dispatch may resume an
260
292
  * interrupted activation, while copied text or a different dispatch id can never claim it. */
261
293
  beginWakeConsumption(runId: string, taskId: string, dispatchId: string): Promise<boolean>;
@@ -283,13 +315,15 @@ export declare class SubAgentRunManager {
283
315
  * harmless — this is the same fix as job-manager's `announce()` reordering (D7).
284
316
  */
285
317
  private announce;
286
- /** Explicit cancel (`subagent_manage op=cancel`, spec 040 D6). Does not wake — it is the model's own decision. */
318
+ /** Explicit cancel (`subagent_run op=cancel`, spec 040 D6). Does not wake — it is the model's own decision. */
287
319
  cancel(runId: string): Promise<RunStatus | "not_found">;
288
320
  /**
289
321
  * Rebuild in-memory state after a restart. Internal runs cannot survive a restart by
290
322
  * construction (D10.3): the worker lived in the process that just disappeared, so any record
291
323
  * still `running` is settled as `lost` and the channel is woken to say so. External runs are
292
- * left alone here — the harness-specific probe (spec 040 phase 2/3) reconciles those.
324
+ * left for the harness-specific probe (spec 040 phase 2/3), except an adopted write run whose
325
+ * lease cannot be rebuilt: it is killed and settled as `lost` rather than allowed to continue
326
+ * without mutual exclusion.
293
327
  */
294
328
  restore(): Promise<number>;
295
329
  /** Whether `record.pid` is still the same process that was launched, when that can be checked
@@ -297,6 +331,7 @@ export declare class SubAgentRunManager {
297
331
  * launch) means there is nothing to compare against — trust `isProcessAlive` alone rather
298
332
  * than manufacture a false negative. */
299
333
  private isSameProcess;
334
+ private processIdentity;
300
335
  /**
301
336
  * Restart reconciliation for an external run still marked `running` (D10.3), and the terminal
302
337
  * judgement `sweep()` uses once an adopted run's process is confirmed gone. Unlike internal
@@ -340,3 +375,4 @@ export declare function channelDelegationTaskIds(channelId: string): Set<string>
340
375
  * like `restoreChannelJobs`.
341
376
  */
342
377
  export declare function restoreAllSubAgentRuns(): Promise<number>;
378
+ export {};