@oyasmi/pipiclaw 0.9.2-beta.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.
@@ -1,3 +1,6 @@
1
+ import { Agent, type ThinkingLevel } from "@earendil-works/pi-agent-core";
2
+ import type { Api, Model } from "@earendil-works/pi-ai";
3
+ import { AgentSession, SettingsManager as SDKSettingsManager, SessionManager } from "@earendil-works/pi-coding-agent";
1
4
  import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
2
5
  import type { ChannelContext } from "../runtime/channel-context.js";
3
6
  import type { ChannelStore } from "../runtime/store.js";
@@ -6,6 +9,11 @@ import { type SubAgentDiscoveryResult } from "../subagents/discovery.js";
6
9
  import { type RunnerBuiltInCommand } from "./commands.js";
7
10
  import type { RunnerFactoryPaths } from "./runner-factory.js";
8
11
  import { type AgentRunner, type RunnerStatusSnapshot, type TurnStatus } from "./types.js";
12
+ /** Apply the pi 0.83 source-model thinking compatibility branch to one real AgentSession. */
13
+ export declare function setModelWithThinkingPreservation(session: AgentSession, manager: SDKSettingsManager, model: Model<Api>): Promise<void>;
14
+ export declare function setThinkingLevelWithConditionalPersist(session: AgentSession, level: ThinkingLevel): void;
15
+ export declare function cycleThinkingLevelWithConditionalPersist(session: AgentSession): ThinkingLevel | undefined;
16
+ export declare function initializeThinkingLevelCompat(agent: Agent, model: Model<Api>, sessionManager: SessionManager, configuredDefault: ThinkingLevel | undefined): ThinkingLevel;
9
17
  export declare class ChannelRunner implements AgentRunner {
10
18
  private readonly executor;
11
19
  private readonly fileStore;
@@ -25,6 +33,8 @@ export declare class ChannelRunner implements AgentRunner {
25
33
  */
26
34
  private readonly projectScope;
27
35
  private session;
36
+ /** Settings manager owned by the currently bound AgentSession. */
37
+ private sessionSettingsManager;
28
38
  private agent;
29
39
  private sessionManager;
30
40
  private readonly settingsManager;
@@ -168,6 +178,9 @@ export declare class ChannelRunner implements AgentRunner {
168
178
  * switch back to the preferred model. Silent — no user notice on recovery.
169
179
  */
170
180
  private maybeRestorePrimaryModel;
181
+ private setModelWithThinkingPreservation;
182
+ private setThinkingLevelCompat;
183
+ private cycleThinkingLevelCompat;
171
184
  /**
172
185
  * Resolve the configured backup model reference against available models.
173
186
  * Returns null when unset, unresolvable/ambiguous, or missing an API key —
@@ -64,12 +64,58 @@ function asSdkSettingsManager(manager) {
64
64
  return SDKSettingsManager.inMemory({
65
65
  defaultProvider: manager.getDefaultProvider(),
66
66
  defaultModel: manager.getDefaultModel(),
67
- defaultThinkingLevel: manager.getDefaultThinkingLevel(),
67
+ defaultThinkingLevel: manager.getDefaultThinkingLevel() ?? DEFAULT_MAIN_THINKING_LEVEL,
68
68
  compaction: manager.getCompactionSettings(),
69
69
  retry: manager.getRetrySettings(),
70
70
  });
71
71
  }
72
72
  const DEFAULT_MAIN_THINKING_LEVEL = "medium";
73
+ /** Apply the pi 0.83 source-model thinking compatibility branch to one real AgentSession. */
74
+ export async function setModelWithThinkingPreservation(session, manager, model) {
75
+ const source = session.model;
76
+ if (!source?.reasoning) {
77
+ await session.setModel(model);
78
+ return;
79
+ }
80
+ const previousDefault = manager.getDefaultThinkingLevel();
81
+ manager.setDefaultThinkingLevel(session.thinkingLevel);
82
+ try {
83
+ await session.setModel(model);
84
+ }
85
+ finally {
86
+ manager.setDefaultThinkingLevel(previousDefault ?? DEFAULT_MAIN_THINKING_LEVEL);
87
+ }
88
+ }
89
+ export function setThinkingLevelWithConditionalPersist(session, level) {
90
+ const before = session.thinkingLevel;
91
+ session.setThinkingLevel(level);
92
+ const effective = session.thinkingLevel;
93
+ if (effective === before)
94
+ return;
95
+ if (!session.model?.reasoning && effective === "off")
96
+ return;
97
+ session.setThinkingLevel(effective, { persist: true });
98
+ }
99
+ export function cycleThinkingLevelWithConditionalPersist(session) {
100
+ const before = session.thinkingLevel;
101
+ const next = session.cycleThinkingLevel();
102
+ const effective = session.thinkingLevel;
103
+ if (next && effective !== before && (session.model?.reasoning || effective !== "off")) {
104
+ session.setThinkingLevel(effective, { persist: true });
105
+ }
106
+ return next;
107
+ }
108
+ export function initializeThinkingLevelCompat(agent, model, sessionManager, configuredDefault) {
109
+ const branch = sessionManager.getBranch();
110
+ const hasThinkingEntry = branch.some((entry) => entry.type === "thinking_level_change");
111
+ const historical = sessionManager.buildSessionContext().thinkingLevel;
112
+ const requested = hasThinkingEntry ? historical : (configuredDefault ?? DEFAULT_MAIN_THINKING_LEVEL);
113
+ const effective = clampThinkingLevel(model, requested);
114
+ agent.state.thinkingLevel = effective;
115
+ if (!hasThinkingEntry)
116
+ sessionManager.appendThinkingLevelChange(effective);
117
+ return effective;
118
+ }
73
119
  /**
74
120
  * Ceilings for the two awaited steps of a session-resource reload. Both reach
75
121
  * the network (model/auth re-resolution; the SDK session's own reload) and
@@ -389,7 +435,7 @@ export class ChannelRunner {
389
435
  getCurrentModelRef: () => formatModelReference(this.session.model ?? this.activeModel),
390
436
  resolveFallbackModel: () => this.resolveFallbackModel(),
391
437
  setModel: async (model) => {
392
- await this.session.setModel(model);
438
+ await this.setModelWithThinkingPreservation(model);
393
439
  },
394
440
  notifySwitch: (from, to, errorSummary) => {
395
441
  fallbackTargetRef = to;
@@ -930,7 +976,7 @@ export class ChannelRunner {
930
976
  return;
931
977
  }
932
978
  try {
933
- await this.session.setModel(this.activeModel);
979
+ await this.setModelWithThinkingPreservation(this.activeModel);
934
980
  this.primaryFailedAt = null;
935
981
  log.logInfo(`[${this.channelId}] Restored primary model ${formatModelReference(this.activeModel)}`);
936
982
  }
@@ -938,6 +984,15 @@ export class ChannelRunner {
938
984
  log.logWarning(`[${this.channelId}] Failed to restore primary model`, errorMessage(err));
939
985
  }
940
986
  }
987
+ async setModelWithThinkingPreservation(model) {
988
+ await setModelWithThinkingPreservation(this.session, this.sessionSettingsManager, model);
989
+ }
990
+ setThinkingLevelCompat(level) {
991
+ setThinkingLevelWithConditionalPersist(this.session, level);
992
+ }
993
+ cycleThinkingLevelCompat() {
994
+ return cycleThinkingLevelWithConditionalPersist(this.session);
995
+ }
941
996
  /**
942
997
  * Resolve the configured backup model reference against available models.
943
998
  * Returns null when unset, unresolvable/ambiguous, or missing an API key —
@@ -979,10 +1034,11 @@ export class ChannelRunner {
979
1034
  this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
980
1035
  const initialResourceLoader = this.createResourceLoader();
981
1036
  const baseToolsOverride = Object.fromEntries(this.currentTools.map((tool) => [tool.name, tool]));
1037
+ this.sessionSettingsManager = asSdkSettingsManager(this.settingsManager);
982
1038
  this.session = new AgentSession({
983
1039
  agent: this.agent,
984
1040
  sessionManager: this.sessionManager,
985
- settingsManager: asSdkSettingsManager(this.settingsManager),
1041
+ settingsManager: this.sessionSettingsManager,
986
1042
  cwd: this.projectScope.projectRoot,
987
1043
  modelRuntime: this.modelRuntime,
988
1044
  resourceLoader: initialResourceLoader,
@@ -1174,11 +1230,11 @@ export class ChannelRunner {
1174
1230
  getSessionStats: () => this.session.getSessionStats(),
1175
1231
  getThinkingLevel: () => this.session.thinkingLevel,
1176
1232
  getAvailableThinkingLevels: () => this.session.getAvailableThinkingLevels(),
1177
- setThinkingLevel: (level) => this.session.setThinkingLevel(level),
1178
- cycleThinkingLevel: () => this.session.cycleThinkingLevel(),
1233
+ setThinkingLevel: (level) => this.setThinkingLevelCompat(level),
1234
+ cycleThinkingLevel: () => this.cycleThinkingLevelCompat(),
1179
1235
  getLastResponseModel: () => getLastAssistantUsage(this.session.messages)?.responseModel,
1180
1236
  switchModel: async (model) => {
1181
- await this.session.setModel(model);
1237
+ await this.setModelWithThinkingPreservation(model);
1182
1238
  this.activeModel = model;
1183
1239
  // Manual /model switch redefines the preferred model and clears fallback state.
1184
1240
  this.primaryFailedAt = null;
@@ -1230,17 +1286,7 @@ export class ChannelRunner {
1230
1286
  * clamped to the selected model before the session starts.
1231
1287
  */
1232
1288
  initializeThinkingLevel(agent, model, sessionManager) {
1233
- const branch = sessionManager.getBranch();
1234
- const hasThinkingEntry = branch.some((entry) => entry.type === "thinking_level_change");
1235
- const sessionThinkingLevel = sessionManager.buildSessionContext().thinkingLevel;
1236
- const requestedLevel = hasThinkingEntry
1237
- ? sessionThinkingLevel
1238
- : (this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_MAIN_THINKING_LEVEL);
1239
- const effectiveLevel = clampThinkingLevel(model, requestedLevel);
1240
- agent.state.thinkingLevel = effectiveLevel;
1241
- if (!hasThinkingEntry) {
1242
- sessionManager.appendThinkingLevelChange(effectiveLevel);
1243
- }
1289
+ initializeThinkingLevelCompat(agent, model, sessionManager, this.settingsManager.getDefaultThinkingLevel());
1244
1290
  }
1245
1291
  createSessionRuntime(sessionManager, sessionStartEvent) {
1246
1292
  const tools = this.buildRuntimeTools();
@@ -1257,16 +1303,18 @@ export class ChannelRunner {
1257
1303
  });
1258
1304
  this.initializeThinkingLevel(agent, this.activeModel, sessionManager);
1259
1305
  const resourceLoader = this.createResourceLoader();
1306
+ const sessionSettingsManager = asSdkSettingsManager(this.settingsManager);
1260
1307
  const session = new AgentSession({
1261
1308
  agent,
1262
1309
  sessionManager,
1263
- settingsManager: asSdkSettingsManager(this.settingsManager),
1310
+ settingsManager: sessionSettingsManager,
1264
1311
  cwd: this.projectScope.projectRoot,
1265
1312
  modelRuntime: this.modelRuntime,
1266
1313
  resourceLoader,
1267
1314
  baseToolsOverride: Object.fromEntries(tools.map((tool) => [tool.name, tool])),
1268
1315
  sessionStartEvent,
1269
1316
  });
1317
+ this.sessionSettingsManager = sessionSettingsManager;
1270
1318
  return { agent, session, resourceLoader };
1271
1319
  }
1272
1320
  buildRuntimeTools() {
@@ -72,7 +72,7 @@ order: 60
72
72
 
73
73
  取回后核对**真实文件、diff 和测试结果**。执行者的完成声明和自验只是第一层证据,代替不了你的独立检查——外部 Agent 尤其如此,它判定"完成"和"通过"的标准不受本 runtime 约束。
74
74
 
75
- `purpose=verify` 的验收者必须是 `mutates: read` 的角色;声明 `mutates: write` 的角色和 `exec` harness 会被 runtime 直接拒绝,不用自己判断。但**过了这道门不等于结论有结构性保证**:attestation 只有在内置角色、且它的 `tools` 里没有 `bash` 时才标 `enforced`(`write`/`edit` 被结构性移除);带 `bash` 的内置角色和所有外部角色都标 `advisory`——`bash` 一样能写文件。看到 `advisory` 就按风险抽查,不要看见 `Verdict: PASS` 就放行。
75
+ `purpose=verify` 的验收者可以声明 `mutates: write`,这样它会在验证期间持有目标工作区的独占 lease,并允许运行可能生成临时产物的测试/构建;但这类 attestation 是 `advisory`,不是完全只读证明。`exec` harness 仍因没有协议终态而被 runtime 直接拒绝。**过了准入门也不等于结论有结构性保证**:内置角色只有在声明 `mutates: read` 且 `tools` 里没有 `bash` 时才标 `enforced`(`write`/`edit` 被结构性移除);带 `bash` 的内置角色、写 verifier 和所有外部角色都标 `advisory`——`bash` 一样能写文件。看到 `advisory` 就按风险抽查,不要看见 `Verdict: PASS` 就放行。协议禁止 verifier 修改被验收实现或为了通过测试而修代码。
76
76
 
77
77
  让验收者只判断、不顺手改产物;改了就得重新验收(细则见 `task-driving.md`)。
78
78
 
@@ -47,10 +47,10 @@ task scope 就是 authority:不要扩大目标、渠道、环境或对象范
47
47
 
48
48
  1. 只有证据成立后才勾选 DoD / Verification checklist。
49
49
  2. 像任何其他委派一样,派发一个 `purpose: verify`、带 `taskId` 的 sub-agent,然后用带 `note` 的 `task_update` 把任务停泊为 `waiting`(不设 wake,`waitingFor: external-signal`)——没有单独的 `request-verification` 动作,也没有 `waiting + waitingFor: verification` 这种状态。
50
- 3. checker 只读检查,结尾返回 `VERDICT: PASS` 或 `VERDICT: FAIL`;完成后 runtime 通过完成唤醒恢复所属 task,依据是 run 记录里的 `taskId`。
51
- 4. 主回合用 `task_verify` 导入 runId;attestation 必须属于当前 task、未改变 workspace,且 contract body hash 与 artifact subject 新鲜。
50
+ 3. checker 只判断、不修复被验收实现,结尾返回 `VERDICT: PASS` 或 `VERDICT: FAIL`;需要运行测试/构建时可以使用声明 `mutates: write` 的 verifier,但它会占用目标工作区独占 lease,并以 `advisory` 强度运行。完成后 runtime 通过完成唤醒恢复所属 task,依据是 run 记录里的 `taskId`。
51
+ 4. 主回合用 `task_verify` 导入 runId;attestation 必须属于当前 task、未改变受保护 workspace 内容,且 contract body hash 与 artifact subject 新鲜。新 subject 以验证开始时的 `baseCommit` 为基准:正常提交已验收内容不算变化;明确临时产物范围外的新源文件,以及验证开始前已存在的 untracked 产品文件变化,仍会使验收失败。
52
52
  5. PASS/FAIL 都恢复 active;PASS 后 complete 仍会重新校验 attestation、contract hash 和 artifact subject。
53
- 6. attestation 标 `advisory` 时(带 `bash` 的内置验收者,以及所有外部验收者),结论只是参考而非结构性保证,仍要按风险抽查;判定强度的来源见 `agent-delegation.md`。
53
+ 6. attestation 标 `advisory` 时(带 `bash` 的内置验收者、声明 `mutates: write` 的 verifier,以及所有外部验收者),结论只是参考而非结构性保证,仍要按风险抽查;判定强度的来源见 `agent-delegation.md`。
54
54
 
55
55
  PASS 绑定 Goal/DoD/Manual/Verification 这段 contract,不绑定 Plan、Current Cycle 或 History。改动 contract 或被验收产物后必须重新验收;不要让 verifier 顺手修实现。
56
56
 
@@ -6,7 +6,7 @@ import { channelJobTaskIds } from "../agent/job-manager.js";
6
6
  import { capReply } from "../agent/reply-limits.js";
7
7
  import { formatLocalTime, parseLocalTime, parseWakeInput } from "../shared/local-time.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
- import { channelDelegationTaskIds } from "../subagents/runs.js";
9
+ import { channelDelegationTaskIds, getSubAgentRunManager } from "../subagents/runs.js";
10
10
  import { applyTaskControlPatch, createDefaultTaskControl, taskBudgetViolation } from "../tasks/control.js";
11
11
  import { countTaskDodItems, extractTaskTitle, missingStandardTaskSections, normalizeTaskId, readActiveTasks, recurringTaskMissedOccurrence, } from "../tasks/ledger.js";
12
12
  import { withTaskMutation } from "../tasks/mutation-lock.js";
@@ -425,8 +425,13 @@ async function doctor(options) {
425
425
  issues.push(issue(`tasks/${entry.id}.md 超出了它的 control 限额:${violation}`, `检查这个任务,明确提高 budget/deadline 或取消它;否则 driver 会升级处理`));
426
426
  }
427
427
  if (status !== "sleeping" && control.verification.status === "passed") {
428
+ const verificationRun = control.verification.runId && options.channelId
429
+ ? getSubAgentRunManager(options.channelId).get(control.verification.runId)
430
+ : undefined;
428
431
  const attestationOk = control.verification.runId
429
- ? await readVerificationAttestation(options.channelDir, control.verification.runId)
432
+ ? await readVerificationAttestation(options.channelDir, control.verification.runId, {
433
+ trustedWorkingDirectory: verificationRun?.workingDirectory,
434
+ })
430
435
  .then((attestation) => attestation.taskId === entry.id &&
431
436
  attestation.verdict === "pass" &&
432
437
  (!storedTask || attestation.bodyHash === taskBodyHash(storedTask.body)))
@@ -21,8 +21,8 @@ export declare function isVerifiedJobWake(jobs: JobSnapshot[], jobId: string, ta
21
21
  /**
22
22
  * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
23
23
  * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
24
- * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
25
- * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
24
+ * because it is published with the terminal record before usage/archive/wake side effects — the
25
+ * same idempotency guard the manager itself relies on. A pending settlement intent leaves it unset.
26
26
  */
27
27
  export declare function isVerifiedDelegationWake(record: RunRecord | undefined, taskId: string): boolean;
28
28
  /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
@@ -23,8 +23,8 @@ export function isVerifiedJobWake(jobs, jobId, taskId) {
23
23
  /**
24
24
  * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
25
25
  * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
26
- * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
27
- * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
26
+ * because it is published with the terminal record before usage/archive/wake side effects — the
27
+ * same idempotency guard the manager itself relies on. A pending settlement intent leaves it unset.
28
28
  */
29
29
  export function isVerifiedDelegationWake(record, taskId) {
30
30
  return record !== undefined && record.settledAt !== undefined && record.taskId === taskId;
@@ -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,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",