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

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 (77) hide show
  1. package/dist/agent/channel-runner.d.ts +1 -0
  2. package/dist/agent/channel-runner.js +21 -2
  3. package/dist/agent/index.d.ts +1 -1
  4. package/dist/agent/index.js +1 -1
  5. package/dist/agent/job-manager.d.ts +3 -3
  6. package/dist/agent/job-manager.js +0 -1
  7. package/dist/agent/runner-factory.d.ts +16 -4
  8. package/dist/agent/runner-factory.js +9 -23
  9. package/dist/agent/types.d.ts +9 -1
  10. package/dist/agent/types.js +3 -16
  11. package/dist/memory/review-log.js +0 -0
  12. package/dist/memory/scheduler.d.ts +1 -0
  13. package/dist/memory/scheduler.js +64 -6
  14. package/dist/playbooks/agent-delegation.md +2 -2
  15. package/dist/runtime/bootstrap.d.ts +10 -2
  16. package/dist/runtime/bootstrap.js +83 -55
  17. package/dist/runtime/channel-event.d.ts +41 -0
  18. package/dist/runtime/channel-event.js +1 -0
  19. package/dist/runtime/delivery.d.ts +3 -2
  20. package/dist/runtime/dingtalk.d.ts +9 -31
  21. package/dist/runtime/durable-dispatch.d.ts +4 -2
  22. package/dist/runtime/durable-dispatch.js +36 -25
  23. package/dist/runtime/events.d.ts +3 -2
  24. package/dist/runtime/events.js +2 -3
  25. package/dist/runtime/subagent-commands.js +48 -10
  26. package/dist/runtime/task-commands.js +2 -2
  27. package/dist/runtime/task-driver.d.ts +7 -7
  28. package/dist/runtime/task-driver.js +1 -4
  29. package/dist/runtime/task-migration.js +1 -1
  30. package/dist/runtime/task-wake.d.ts +4 -4
  31. package/dist/settings.d.ts +0 -106
  32. package/dist/settings.js +0 -224
  33. package/dist/shared/host-process.d.ts +25 -9
  34. package/dist/shared/host-process.js +59 -10
  35. package/dist/shared/types.d.ts +1 -0
  36. package/dist/shared/types.js +10 -1
  37. package/dist/subagents/discovery.d.ts +24 -0
  38. package/dist/subagents/discovery.js +103 -17
  39. package/dist/subagents/external/claude-code.js +10 -3
  40. package/dist/subagents/external/codex-cli.js +9 -3
  41. package/dist/subagents/external/exec.js +1 -0
  42. package/dist/subagents/external/harness.d.ts +22 -0
  43. package/dist/subagents/external/harness.js +22 -4
  44. package/dist/subagents/external/run.d.ts +23 -3
  45. package/dist/subagents/external/run.js +112 -131
  46. package/dist/subagents/external/settlement.d.ts +50 -0
  47. package/dist/subagents/external/settlement.js +123 -0
  48. package/dist/subagents/format.d.ts +4 -0
  49. package/dist/subagents/format.js +7 -0
  50. package/dist/subagents/runs.d.ts +73 -16
  51. package/dist/subagents/runs.js +197 -120
  52. package/dist/subagents/tool.d.ts +38 -6
  53. package/dist/subagents/tool.js +93 -61
  54. package/dist/subagents/verification-outcome.d.ts +26 -0
  55. package/dist/subagents/verification-outcome.js +16 -0
  56. package/dist/subagents/workspace-lease.d.ts +10 -1
  57. package/dist/subagents/workspace-lease.js +15 -2
  58. package/dist/tasks/ledger.js +1 -1
  59. package/dist/{shared → tasks}/task-schedule.js +1 -1
  60. package/dist/tools/bash.js +1 -1
  61. package/dist/tools/event-manage.js +1 -4
  62. package/dist/tools/grep.js +2 -3
  63. package/dist/tools/index.js +6 -0
  64. package/dist/tools/job.js +5 -5
  65. package/dist/tools/memory-manage.js +3 -6
  66. package/dist/tools/session-search.js +0 -1
  67. package/dist/tools/skill-manage.js +3 -3
  68. package/dist/tools/subagent-manage.d.ts +20 -6
  69. package/dist/tools/subagent-manage.js +88 -18
  70. package/dist/tools/task-manage/shared.js +2 -2
  71. package/dist/tools/task-manage.js +1 -4
  72. package/dist/tools/web-fetch.js +0 -1
  73. package/dist/tui/app.js +4 -4
  74. package/package.json +1 -1
  75. /package/dist/{shared → tasks}/task-events.d.ts +0 -0
  76. /package/dist/{shared → tasks}/task-events.js +0 -0
  77. /package/dist/{shared → tasks}/task-schedule.d.ts +0 -0
@@ -1,4 +1,4 @@
1
- import { detectExistingFlags, expandPlaceholders, } from "./harness.js";
1
+ import { detectExistingFlags, expandPlaceholders, formatDroppedPlaceholderWarnings, } from "./harness.js";
2
2
  /**
3
3
  * `codex-cli` harness (spec 040, D3/D4). One prompt, one short-lived process, NDJSON on stdout
4
4
  * (`--json -`). Chosen as the first structured harness because its process model already matches
@@ -28,6 +28,7 @@ function toCodexEffort(level) {
28
28
  }
29
29
  export const codexCliHarness = {
30
30
  id: "codex-cli",
31
+ parserVersion: 1,
31
32
  buildInvocation(input) {
32
33
  if (input.argv.length === 0) {
33
34
  throw new Error("codex-cli: command produced no argv tokens");
@@ -35,7 +36,7 @@ export const codexCliHarness = {
35
36
  const [executable, ...rest] = input.argv;
36
37
  const existing = detectExistingFlags(rest);
37
38
  const effort = toCodexEffort(input.thinkingLevel);
38
- const { argv: expandedRest, used } = expandPlaceholders(rest, {
39
+ const { argv: expandedRest, used, dropped, } = expandPlaceholders(rest, {
39
40
  $MODEL: input.model,
40
41
  $EFFORT: effort,
41
42
  $PROMPT_FILE: input.promptFile,
@@ -53,7 +54,12 @@ export const codexCliHarness = {
53
54
  const args = input.resumeSessionId
54
55
  ? [...baseArgs, "resume", input.resumeSessionId, "--json", "-"]
55
56
  : [...baseArgs, "--json", "-"];
56
- return { executable, args, resumable: true };
57
+ return {
58
+ executable,
59
+ args,
60
+ resumable: true,
61
+ warnings: dropped.length > 0 ? formatDroppedPlaceholderWarnings(dropped) : undefined,
62
+ };
57
63
  },
58
64
  parseOutcome(input) {
59
65
  let finalText = "";
@@ -12,6 +12,7 @@
12
12
  const MAX_OUTPUT_CHARS = 16_000;
13
13
  export const execHarness = {
14
14
  id: "exec",
15
+ parserVersion: 1,
15
16
  buildInvocation(input) {
16
17
  if (input.argv.length === 0) {
17
18
  throw new Error("exec: command produced no argv tokens");
@@ -33,6 +33,10 @@ export interface BuildInvocationResult {
33
33
  * not just at settlement.
34
34
  */
35
35
  presetSessionId?: string;
36
+ /** Spec 042 D10: non-fatal invocation-time warnings (e.g. an argv token dropped because its
37
+ * placeholder had no value) — persisted onto the run record so `/subagents show` can surface
38
+ * them, since a silently-dropped flag can otherwise look identical to a role that never wanted it. */
39
+ warnings?: string[];
36
40
  }
37
41
  export type ExternalProtocolStatus = "completed" | "failed" | "absent" | "unparsable";
38
42
  export interface ExternalOutcome {
@@ -60,6 +64,13 @@ export interface ParseOutcomeInput {
60
64
  }
61
65
  export interface ExternalHarness {
62
66
  readonly id: "claude-code" | "codex-cli" | "exec";
67
+ /**
68
+ * Spec 042 D12: bumped by hand whenever this adapter's `parseOutcome` schema assumptions
69
+ * change. Persisted on the run and shown by `/subagents show`, so a failure caused by upstream
70
+ * CLI schema drift is distinguishable from a failure the target CLI itself reported — "the
71
+ * adapter is stale" and "the agent failed" look identical from a run's status alone otherwise.
72
+ */
73
+ readonly parserVersion: number;
63
74
  /** Assemble argv. The command line is never joined into a single shell string (D4). */
64
75
  buildInvocation(input: ExternalInvocationInput): BuildInvocationResult;
65
76
  /** Parse stdout into a unified outcome. Must never throw — a parse failure degrades to
@@ -91,9 +102,20 @@ export type Placeholder = (typeof PLACEHOLDERS)[number];
91
102
  * (D4). Returns which placeholders were actually found, so a harness knows whether it still needs
92
103
  * to *append* the corresponding flag (a placeholder present ⇒ never append; absent ⇒ append per
93
104
  * the harness's own rule).
105
+ *
106
+ * Spec 042 D10: a token that still references a placeholder after substitution (its value was
107
+ * `undefined`, e.g. `--model $MODEL` on a role with no `model:` configured) is dropped from argv
108
+ * entirely rather than reaching the process as a literal `"$MODEL"` string — that literal-string
109
+ * failure is exactly what D4's "argv, not a shell string" design exists to prevent, just arriving
110
+ * through a different door (a missing value instead of a shell-quoting bug). `dropped` carries the
111
+ * original tokens so the caller can turn them into a run-visible warning.
94
112
  */
95
113
  export declare function expandPlaceholders(argv: string[], values: Partial<Record<Placeholder, string>>): {
96
114
  argv: string[];
97
115
  used: Set<Placeholder>;
116
+ dropped: string[];
98
117
  };
118
+ /** Turn `expandPlaceholders`'s `dropped` tokens into run-visible warning strings (spec 042 D10),
119
+ * shared so every structured harness reports the same wording. */
120
+ export declare function formatDroppedPlaceholderWarnings(dropped: string[]): string[];
99
121
  export {};
@@ -73,10 +73,19 @@ const PLACEHOLDERS = ["$MODEL", "$EFFORT", "$PROMPT_FILE", "$SYSTEM_PROMPT_FILE"
73
73
  * (D4). Returns which placeholders were actually found, so a harness knows whether it still needs
74
74
  * to *append* the corresponding flag (a placeholder present ⇒ never append; absent ⇒ append per
75
75
  * the harness's own rule).
76
+ *
77
+ * Spec 042 D10: a token that still references a placeholder after substitution (its value was
78
+ * `undefined`, e.g. `--model $MODEL` on a role with no `model:` configured) is dropped from argv
79
+ * entirely rather than reaching the process as a literal `"$MODEL"` string — that literal-string
80
+ * failure is exactly what D4's "argv, not a shell string" design exists to prevent, just arriving
81
+ * through a different door (a missing value instead of a shell-quoting bug). `dropped` carries the
82
+ * original tokens so the caller can turn them into a run-visible warning.
76
83
  */
77
84
  export function expandPlaceholders(argv, values) {
78
85
  const used = new Set();
79
- const expanded = argv.map((token) => {
86
+ const dropped = [];
87
+ const expanded = [];
88
+ for (const token of argv) {
80
89
  let result = token;
81
90
  for (const placeholder of PLACEHOLDERS) {
82
91
  const value = values[placeholder];
@@ -85,7 +94,16 @@ export function expandPlaceholders(argv, values) {
85
94
  result = result.split(placeholder).join(value);
86
95
  }
87
96
  }
88
- return result;
89
- });
90
- return { argv: expanded, used };
97
+ if (PLACEHOLDERS.some((placeholder) => result.includes(placeholder))) {
98
+ dropped.push(token);
99
+ continue;
100
+ }
101
+ expanded.push(result);
102
+ }
103
+ return { argv: expanded, used, dropped };
104
+ }
105
+ /** Turn `expandPlaceholders`'s `dropped` tokens into run-visible warning strings (spec 042 D10),
106
+ * shared so every structured harness reports the same wording. */
107
+ export function formatDroppedPlaceholderWarnings(dropped) {
108
+ return dropped.map((token) => `Dropped argv token "${token}": it references a placeholder with no value configured for this run (e.g. no "model:" set for $MODEL).`);
91
109
  }
@@ -40,6 +40,9 @@ export interface LaunchExternalRunInput {
40
40
  resumeSessionId?: string;
41
41
  /** The role's own `mutates` declaration, carried through to the dispatch audit event (D8.1). */
42
42
  mutates?: RunMutates;
43
+ /** Spec 042 D7: fingerprint of the role's `command`/`externalModelRef`/`shell`, persisted so a
44
+ * later `follow_up` can detect a hot-edited role before resuming under it. */
45
+ roleFingerprint?: string;
43
46
  /** Where the audit trail lives (`<workspaceDir>/.pipiclaw/security.log` by default) and whether
44
47
  * it is enabled — every external dispatch writes an `external-agent` audit event (D8.1), since
45
48
  * external processes never pass through command-guard and this is the only record of what
@@ -49,6 +52,23 @@ export interface LaunchExternalRunInput {
49
52
  /** Test seam: inject a fake `child_process.spawn`. */
50
53
  spawnFn?: typeof nodeSpawn;
51
54
  }
52
- /** Launches an external run. Returns once the process is confirmed spawned (or fails fast if it
53
- * never starts); the wait-for-exit-and-settle work continues in the background afterward. */
54
- export declare function launchExternalRun(input: LaunchExternalRunInput): Promise<void>;
55
+ /**
56
+ * Spec 042 D2: a pre-run failure (file open, spawn, or a cancel that lands before the process
57
+ * exists) used to settle the run and return `void`, leaving the caller no way to tell the model
58
+ * anything went wrong in this same turn — it would see "[Dispatched] ... running" and then, for
59
+ * two of the three cases, never be woken at all. `missing-binary` (spawn `ENOENT`/`EACCES`) needs
60
+ * a human to install the CLI or fix `command`, so callers should surface it as a plain `Error`
61
+ * (AGENTS.md's "can the model resolve this alone?" test says no); the other two are model-fixable
62
+ * (retry the dispatch, or accept that a race cancelled it) and should be a `RecoverableToolError`.
63
+ */
64
+ export type ExternalLaunchResult = {
65
+ ok: true;
66
+ } | {
67
+ ok: false;
68
+ kind: "missing-binary" | "launch-failed" | "cancelled";
69
+ reason: string;
70
+ };
71
+ /** Launches an external run. Resolves once the process is confirmed spawned (or fails fast if it
72
+ * never starts, spec 042 D2); the wait-for-exit-and-settle work continues in the background
73
+ * afterward. */
74
+ export declare function launchExternalRun(input: LaunchExternalRunInput): Promise<ExternalLaunchResult>;
@@ -1,19 +1,21 @@
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";
10
+ import { createEmptyUsageTotals } from "../../shared/types.js";
11
11
  import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
12
- import { parseVerificationVerdict, writeVerificationAttestation } from "../../tasks/verification.js";
13
12
  import { getSubAgentRunManager } from "../runs.js";
14
- import { classifyExternalOutcome } from "./harness.js";
15
13
  import { getExternalHarness } from "./registry.js";
16
- const WAKE_OUTPUT_TAIL_CHARS = 2_000;
14
+ import { finalizeExternalRun } from "./settlement.js";
15
+ function classifySpawnError(error) {
16
+ const code = error.code;
17
+ return code === "ENOENT" || code === "EACCES" ? "missing-binary" : "launch-failed";
18
+ }
17
19
  function buildStdinContent(harnessId, systemPrompt, task) {
18
20
  // claude-code has a real system-prompt flag (--append-system-prompt-file, D4); every other
19
21
  // harness has no such channel, so the role's system prompt has nowhere to go but the prompt
@@ -22,8 +24,9 @@ function buildStdinContent(harnessId, systemPrompt, task) {
22
24
  return task;
23
25
  return `${systemPrompt.trim()}\n\n---\n\n${task.trim()}\n`;
24
26
  }
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. */
27
+ /** Launches an external run. Resolves once the process is confirmed spawned (or fails fast if it
28
+ * never starts, spec 042 D2); the wait-for-exit-and-settle work continues in the background
29
+ * afterward. */
27
30
  export async function launchExternalRun(input) {
28
31
  const harness = getExternalHarness(input.harness);
29
32
  if (!harness) {
@@ -58,21 +61,11 @@ export async function launchExternalRun(input) {
58
61
  resumeSessionId: input.resumeSessionId,
59
62
  });
60
63
  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
- });
64
+ // Spec 042 D11: admission (inside register(), including the concurrency-limit checks) happens
65
+ // *before* the audit write, not after — previously a run rejected for being over the per-channel
66
+ // or host-wide cap still left behind an `external-agent` audit record claiming a process that
67
+ // never existed. `external-agent` records what was *executed* (D8.1), so the record must not
68
+ // precede the point where this run is actually admitted to run.
76
69
  const runManager = getSubAgentRunManager(input.channelId);
77
70
  await runManager.register({
78
71
  runId: input.runId,
@@ -90,13 +83,38 @@ export async function launchExternalRun(input) {
90
83
  artifactDir: input.artifactDir,
91
84
  leaseKey: input.leaseKey,
92
85
  });
86
+ // The final executable/argv/cwd/capability record must be durable before a process can exist.
87
+ // `external-agent` uses the strict appender path and rejects on queue or I/O failure; a failure
88
+ // here settles the run instead of leaving it an orphaned "running" record (spec 042 D2) — the
89
+ // same reasoning as every other pre-spawn failure below: this is a real fault requiring human
90
+ // attention (disk full, permissions), not something a retry would fix on its own.
91
+ try {
92
+ await logSecurityEvent(input.workspaceDir, input.securityConfig, {
93
+ type: "external-agent",
94
+ tool: "subagent",
95
+ channelId: input.channelId,
96
+ runId: input.runId,
97
+ agent: input.agent,
98
+ harness: harness.id,
99
+ argv: spawnedArgv,
100
+ workingDirectory: input.workingDirectory,
101
+ mutates: input.mutates ?? "read",
102
+ model: input.externalModelRef,
103
+ });
104
+ }
105
+ catch (error) {
106
+ const reason = `Failed to write the mandatory dispatch audit record: ${errorMessage(error)}`;
107
+ await runManager.settle(input.runId, failedSettleInput(reason), { announce: false });
108
+ return { ok: false, kind: "launch-failed", reason };
109
+ }
93
110
  let cancelledBeforeSpawn = false;
94
111
  const launchClaimed = await runManager.claimExternalLaunch(input.runId, () => {
95
112
  cancelledBeforeSpawn = true;
96
113
  });
97
114
  if (!launchClaimed) {
98
- await runManager.settle(input.runId, { ...failedSettleInput("Cancelled before the external process was spawned."), status: "cancelled" }, { announce: false });
99
- return;
115
+ const reason = "Cancelled before the external process was spawned.";
116
+ await runManager.settle(input.runId, { ...failedSettleInput(reason), status: "cancelled" }, { announce: false });
117
+ return { ok: false, kind: "cancelled", reason };
100
118
  }
101
119
  const eventsPath = join(input.artifactDir, "events.jsonl");
102
120
  const stderrPath = join(input.artifactDir, "stderr.log");
@@ -107,10 +125,12 @@ export async function launchExternalRun(input) {
107
125
  stderrFd = openSync(stderrPath, "a");
108
126
  }
109
127
  catch (error) {
110
- await runManager.settle(input.runId, failedSettleInput(`Failed to open output files: ${errorMessage(error)}`), {
111
- announce: true,
112
- });
113
- return;
128
+ const reason = `Failed to open output files: ${errorMessage(error)}`;
129
+ // Spec 042 D2: `announce: false` — this failure happened inside the same tool call that is
130
+ // still on the stack; the caller reports it directly instead of waking the channel for a
131
+ // result it can hand back right now.
132
+ await runManager.settle(input.runId, failedSettleInput(reason), { announce: false });
133
+ return { ok: false, kind: "launch-failed", reason };
114
134
  }
115
135
  const spawnFn = input.spawnFn ?? nodeSpawn;
116
136
  let child;
@@ -127,10 +147,13 @@ export async function launchExternalRun(input) {
127
147
  catch (error) {
128
148
  closeSync(eventsFd);
129
149
  closeSync(stderrFd);
130
- await runManager.settle(input.runId, failedSettleInput(`Failed to launch: ${errorMessage(error)}`), {
131
- announce: true,
132
- });
133
- return;
150
+ const reason = `Failed to launch: ${errorMessage(error)}`;
151
+ await runManager.settle(input.runId, failedSettleInput(reason), { announce: false });
152
+ return {
153
+ ok: false,
154
+ kind: classifySpawnError(error instanceof Error ? error : new Error(String(error))),
155
+ reason,
156
+ };
134
157
  }
135
158
  // The child has its own duped copy of both fds now; ours would otherwise leak across the
136
159
  // lifetime of a long-running daemon dispatching many external runs.
@@ -141,8 +164,13 @@ export async function launchExternalRun(input) {
141
164
  child.once("spawn", () => resolve(undefined));
142
165
  });
143
166
  if (spawnFailure || !child.pid) {
144
- await runManager.settle(input.runId, failedSettleInput(`Failed to launch: ${spawnFailure ? errorMessage(spawnFailure) : "no pid"}`), { announce: true });
145
- return;
167
+ const reason = `Failed to launch: ${spawnFailure ? errorMessage(spawnFailure) : "no pid"}`;
168
+ await runManager.settle(input.runId, failedSettleInput(reason), { announce: false });
169
+ return {
170
+ ok: false,
171
+ kind: spawnFailure ? classifySpawnError(spawnFailure) : "launch-failed",
172
+ reason,
173
+ };
146
174
  }
147
175
  const pid = child.pid;
148
176
  const processStartedAt = Date.now();
@@ -155,13 +183,18 @@ export async function launchExternalRun(input) {
155
183
  });
156
184
  if (cancelledBeforeSpawn) {
157
185
  void killProcessGroup(pid);
158
- await runManager.settle(input.runId, { ...failedSettleInput("Cancelled while the external process was spawning."), status: "cancelled" }, { announce: false });
159
- return;
186
+ const reason = "Cancelled while the external process was spawning.";
187
+ await runManager.settle(input.runId, { ...failedSettleInput(reason), status: "cancelled" }, { announce: false });
188
+ return { ok: false, kind: "cancelled", reason };
160
189
  }
161
190
  // The OS-verifiable identity check (D10.3): a restart tells this pid apart from an unrelated
162
191
  // 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);
192
+ // restore()/sweep() then fall back to trusting `isProcessAlive` alone. Run alongside the D12
193
+ // CLI-version probe — neither depends on the other, and both are best-effort/bounded.
194
+ const [pidStartedAt, cliVersion] = await Promise.all([
195
+ readProcessStartTime(pid),
196
+ probeCliVersion(invocation.executable),
197
+ ]);
165
198
  const deadlineAt = processStartedAt + input.maxWallTimeSec * 1000;
166
199
  await runManager.setLaunched(input.runId, {
167
200
  pid,
@@ -169,6 +202,18 @@ export async function launchExternalRun(input) {
169
202
  argv: spawnedArgv,
170
203
  deadlineAt,
171
204
  sessionId: invocation.presetSessionId,
205
+ // Spec 042 D1: persisted so a restart reconciliation has the same inputs the live watcher
206
+ // below would — without these, a run that finishes after the daemon disappears would settle
207
+ // with an inaccurate timeout message, no verify attestation, and an unestimatable duration.
208
+ verifySubjectBefore,
209
+ maxWallTimeSec: input.maxWallTimeSec,
210
+ processStartedAt,
211
+ channelDir: input.channelDir,
212
+ invocationWarnings: invocation.warnings,
213
+ // Spec 042 D12: distinguishes "the target CLI's schema drifted" from "the agent failed".
214
+ parserVersion: harness.parserVersion,
215
+ cliVersion,
216
+ roleFingerprint: input.roleFingerprint,
172
217
  });
173
218
  if (child.stdin) {
174
219
  child.stdin.on("error", () => { }); // EPIPE if the process already exited; harmless.
@@ -183,8 +228,8 @@ export async function launchExternalRun(input) {
183
228
  if (runManager.get(input.runId)?.terminationReason === "cancelled") {
184
229
  void killProcessGroup(pid);
185
230
  }
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).
231
+ // Prompt, same-process enforcement. Restart recovery persists this same deadline and installs
232
+ // one replacement check only when it actually adopts a still-running process.
188
233
  const wallClockTimer = setTimeout(() => {
189
234
  void runManager.markTerminationReason(input.runId, "timeout").then(() => killProcessGroup(pid));
190
235
  }, input.maxWallTimeSec * 1000);
@@ -194,106 +239,42 @@ export async function launchExternalRun(input) {
194
239
  void closePromise.then(async (exitCode) => {
195
240
  clearTimeout(wallClockTimer);
196
241
  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);
242
+ // Spec 042 D8: this fires on every exit (normal, cancelled, or timed out) as a backup reap —
243
+ // a cancel/timeout already killed the group via its own call site above. The common case
244
+ // (nothing left) returns immediately with no signal and no wait; only a genuinely lingering
245
+ // descendant (the leader exited before it did) pays the TERM-then-KILL sequence.
246
+ await reapProcessGroup(pid);
201
247
  const durationMs = Date.now() - processStartedAt;
202
248
  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,
249
+ // Spec 042 D1: parse whatever the process actually wrote *before* applying a cancel/timeout
250
+ // override, instead of returning early on those two reasons. A run killed for wall-time
251
+ // budget or cancelled by request may still have produced useful output, usage, and a
252
+ // resumable session id — `finalizeExternalRun` keeps all of that; only `status` and
253
+ // `failureReason` get overridden by `terminationReason` (P1-1).
254
+ await finalizeExternalRun({
255
+ runId: input.runId,
256
+ channelId: input.channelId,
257
+ channelDir: input.channelDir,
258
+ harnessId: harness.id,
259
+ purpose: input.purpose,
260
+ taskId: input.taskId,
261
+ workingDirectory: input.workingDirectory,
262
+ artifactDir: input.artifactDir,
263
+ exitCode,
275
264
  durationMs,
276
- outputText: outcome.finalText,
277
- sessionId: outcome.sessionId,
278
- verificationVerdict,
279
- verificationStrength: verificationVerdict ? "advisory" : undefined,
280
- }, { announce: true })
281
- .catch((error) => {
265
+ terminationReason,
266
+ maxWallTimeSec: input.maxWallTimeSec,
267
+ verifySubjectBefore,
268
+ }, (settleInput, options) => runManager.settle(input.runId, settleInput, options), { announce: terminationReason !== "cancelled" }).catch((error) => {
282
269
  log.logWarning(`Failed to settle external run ${input.runId}`, errorMessage(error));
283
270
  });
284
271
  });
272
+ return { ok: true };
285
273
  function failedSettleInput(reason) {
286
274
  return {
287
275
  status: "failed",
288
276
  failureReason: reason,
289
- usage: {
290
- input: 0,
291
- output: 0,
292
- cacheRead: 0,
293
- cacheWrite: 0,
294
- total: 0,
295
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
296
- },
277
+ usage: createEmptyUsageTotals(),
297
278
  usageKnown: false,
298
279
  costKnown: false,
299
280
  turns: 0,
@@ -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>;