@henryqw/pi-subagent 30.0.0 → 31.0.0

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 (38) hide show
  1. package/CONTEXT.md +2 -2
  2. package/README.md +20 -22
  3. package/dist/ephemeral.d.ts +7 -3
  4. package/dist/ephemeral.js +59 -11
  5. package/dist/herdr-runtime.js +4 -0
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +2 -2
  8. package/dist/native-host.d.ts +96 -0
  9. package/dist/native-host.js +243 -0
  10. package/dist/runner.d.ts +8 -1
  11. package/dist/runner.js +22 -15
  12. package/dist/schema.d.ts +71 -2
  13. package/dist/schema.js +14 -1
  14. package/dist/workspace-schema.d.ts +11 -0
  15. package/dist/workspace.d.ts +5 -2
  16. package/dist/workspace.js +58 -29
  17. package/docs/measurement.md +12 -1
  18. package/docs/orchestration-architecture.html +4 -4
  19. package/docs/orchestration-architecture.svg +2 -2
  20. package/docs/orchestration.md +69 -258
  21. package/docs/workspace.md +4 -80
  22. package/extensions/direct-check-exec.py +91 -0
  23. package/extensions/direct-check-supervisor.mjs +42 -0
  24. package/extensions/direct-check-witness.mjs +34 -0
  25. package/extensions/direct-native.ts +5 -3
  26. package/extensions/direct-outbox.ts +189 -0
  27. package/extensions/direct-owner.ts +49 -0
  28. package/extensions/direct-verification.ts +73 -0
  29. package/extensions/isolated.ts +25 -301
  30. package/extensions/prerequisite-evidence.ts +81 -0
  31. package/extensions/result-transport.ts +6 -4
  32. package/extensions/subagent-command.ts +12 -7
  33. package/extensions/subagent.ts +302 -495
  34. package/extensions/workflow-recovery.ts +359 -0
  35. package/extensions/workflow.ts +156 -40
  36. package/extensions/workspace.ts +16 -74
  37. package/package.json +8 -8
  38. package/skills/pi-subagent/SKILL.md +15 -37
@@ -0,0 +1,243 @@
1
+ import { constants } from "node:fs";
2
+ import { lstat, mkdir, open, readFile, realpath } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { setTimeout as sleep } from "node:timers/promises";
5
+ import { extensionConfigDir } from "@henryqw/pi-config-store";
6
+ import { exactDirectAnswer, assertSettledDirectSession } from "./direct-herdr.js";
7
+ import { PI_SUBAGENT_PROCESS_LEASE, isProcessLeaseIdentity, processLeaseIdentity, scanProcessLease } from "./process-lease.js";
8
+ import { runProcess } from "./process.js";
9
+ import { buildChangesetTaskPrompt } from "./runner.js";
10
+ import { isCleanCommitted } from "./schema.js";
11
+ const legacy = (attempt) => attempt.allocations.some((item) => item.kind === "workspace" || item.kind === "worker_tab" || item.kind === "agent");
12
+ const native = (attempt) => attempt.allocations.find((item) => item.kind === "native" && item.status === "owned");
13
+ const worktree = (attempt) => {
14
+ const record = attempt.allocations.find((item) => item.kind === "worktree" && item.status === "owned");
15
+ if (record?.kind !== "worktree" || !record.worktree)
16
+ throw new Error("Native worker requires its exact owned worktree.");
17
+ return record.worktree;
18
+ };
19
+ const turns = new Map();
20
+ /** New checked tasks own a session and process lease. Saved Herdr allocations retain their original recovery authority. */
21
+ export class NativeHostRuntime {
22
+ directory;
23
+ previous;
24
+ coordinator;
25
+ executor;
26
+ git;
27
+ constructor(previous, coordinator, executor, git, agentDir) {
28
+ this.directory = join(extensionConfigDir("pi-subagent", agentDir), "native-workers");
29
+ this.previous = previous;
30
+ this.coordinator = coordinator;
31
+ this.executor = executor;
32
+ this.git = git;
33
+ }
34
+ allocationKinds(attempt) { return legacy(attempt) ? ["workspace", "worker_tab", "agent"] : ["native"]; }
35
+ address(attempt) {
36
+ if (!/^[A-Za-z0-9_-]{16,128}$/.test(attempt.correlationToken))
37
+ throw new Error("Invalid native worker token.");
38
+ return join(this.directory, attempt.correlationToken, `generation-${attempt.allocationGeneration}`, "process.lease");
39
+ }
40
+ check(intent, attempt, workerId = intent.agentName) {
41
+ if (intent.leasePath !== this.address(attempt) || intent.agentName !== `native-${attempt.correlationToken}` || intent.agentName !== workerId
42
+ || intent.token !== attempt.correlationToken || intent.generation !== attempt.allocationGeneration || intent.worktreeCwd !== worktree(attempt).cwd || legacy(attempt))
43
+ throw new Error("Native worker identity changed.");
44
+ }
45
+ async planHostAllocation(input, ctx) {
46
+ if (input.kind !== "native")
47
+ return this.previous.planHostAllocation(input, ctx);
48
+ ctx.signal.throwIfAborted();
49
+ return { kind: "native", agentName: `native-${input.attempt.correlationToken}`, leasePath: this.address(input.attempt), worktreeCwd: worktree(input.attempt).cwd };
50
+ }
51
+ async allocateHost(input, ctx) {
52
+ const { intent, attempt } = input;
53
+ if (intent.kind !== "native")
54
+ return this.previous.allocateHost(input, ctx);
55
+ this.check(intent, attempt);
56
+ ctx.signal.throwIfAborted();
57
+ const dir = dirname(intent.leasePath);
58
+ await mkdir(dirname(dir), { mode: 0o700, recursive: true });
59
+ if (await realpath(dirname(dir)) !== dirname(dir))
60
+ throw new Error("Native worker directory is not canonical.");
61
+ await mkdir(dir, { mode: 0o700 });
62
+ await (await open(intent.leasePath, "wx", 0o600)).close();
63
+ await (await open(join(dir, "session.jsonl"), "wx", 0o600)).close();
64
+ return { kind: "native", outcome: "owned", leaseIdentity: JSON.stringify(await processLeaseIdentity(intent.leasePath)) };
65
+ }
66
+ async reconcileHostAllocation(input, ctx) {
67
+ if (input.intent.kind !== "native")
68
+ return this.previous.reconcileHostAllocation(input, ctx);
69
+ this.check(input.intent, input.attempt);
70
+ try {
71
+ await lstat(dirname(input.intent.leasePath));
72
+ }
73
+ catch (error) {
74
+ if (error.code === "ENOENT")
75
+ return { kind: "native", outcome: "absent" };
76
+ throw error;
77
+ }
78
+ return { kind: "native", outcome: "possible", failure: "Native session directory exists. Inspect retained evidence before recovery." };
79
+ }
80
+ async identity(intent) {
81
+ const expected = JSON.parse(intent.leaseIdentity ?? "null");
82
+ if (!isProcessLeaseIdentity(expected) || await realpath(intent.leasePath) !== intent.leasePath)
83
+ throw new Error("Original native process lease is unavailable.");
84
+ return processLeaseIdentity(intent.leasePath, expected);
85
+ }
86
+ async holders(intent, ctx, pid) {
87
+ await this.identity(intent);
88
+ const holders = await scanProcessLease(intent.leasePath, (args) => runProcess("lsof", args, { cwd: intent.worktreeCwd, timeoutMs: 3000, signal: ctx.signal }), pid);
89
+ await this.identity(intent);
90
+ return holders;
91
+ }
92
+ async runWorker(input, ctx) {
93
+ if (legacy(input.attempt))
94
+ return this.previous.runWorker(input, ctx);
95
+ const intent = native(input.attempt);
96
+ if (!intent || input.task.kind !== "changeset")
97
+ throw new Error("Missing owned native changeset worker.");
98
+ this.check(intent, input.attempt, input.workerId);
99
+ const dir = dirname(intent.leasePath), sessionFile = join(dir, "session.jsonl");
100
+ if (turns.has(intent.leasePath))
101
+ throw new Error("Native worker already has an active turn.");
102
+ const controller = new AbortController();
103
+ turns.set(intent.leasePath, controller);
104
+ const signal = AbortSignal.any([ctx.signal, controller.signal]);
105
+ let launch;
106
+ let descriptor;
107
+ const ordinal = input.attempt.prompts.length;
108
+ const task = `${buildChangesetTaskPrompt({ ...input, task: input.task, worktreeCwd: intent.worktreeCwd })}\n\nTurn identity: ${intent.token}:${ordinal}`;
109
+ try {
110
+ const policy = input.policy;
111
+ if (!policy)
112
+ throw new Error("Native worker requires the saved execution policy.");
113
+ let maxTurns = policy.maxTurns;
114
+ let maxTokens = policy.maxTokens;
115
+ if (ordinal > 1) {
116
+ await this.identity(intent);
117
+ const info = await lstat(sessionFile);
118
+ if (!info.isFile() || info.size > 16 * 1024 * 1024)
119
+ throw new Error("Invalid retained native session.");
120
+ await assertSettledDirectSession(sessionFile, `${intent.token}:${ordinal - 1}`);
121
+ for (const line of (await readFile(sessionFile, "utf8")).trimEnd().split("\n")) {
122
+ const entry = JSON.parse(line);
123
+ if (entry.type !== "message" || entry.message?.role !== "assistant")
124
+ continue;
125
+ maxTurns--;
126
+ if (maxTokens !== undefined) {
127
+ const tokens = entry.message.usage?.totalTokens;
128
+ if (!Number.isSafeInteger(tokens) || tokens < 0)
129
+ throw new Error("Cannot verify saved native worker usage.");
130
+ maxTokens -= tokens;
131
+ }
132
+ }
133
+ if (maxTurns <= 0 || (maxTokens !== undefined && maxTokens <= 0))
134
+ return { outcome: "blocked", diagnostic: "Native worker session budget is exhausted." };
135
+ }
136
+ const executor = this.executor.withLimits({ maxConcurrency: policy.maxSubagents, maxTurns, maxTokens,
137
+ timeout: { idleMs: policy.childIdleMs, maxMs: policy.childMaxMs } });
138
+ const result = await executor.run({ signal, prepare: async () => {
139
+ if ((await this.holders(intent, { ...ctx, signal })).length)
140
+ throw new Error("Native worker lease is still in use.");
141
+ const stat = await lstat(sessionFile);
142
+ if (!stat.isFile() || (stat.mode & 0o777) !== 0o600 || stat.uid !== process.getuid?.() || stat.size > 16 * 1024 * 1024)
143
+ throw new Error("Native session is not a bounded private file.");
144
+ if (ordinal === 1 && stat.size)
145
+ throw new Error("New native session already contains a turn.");
146
+ launch = await this.coordinator.acquireLaunch(input.task.role, input.task.modelClass, { ...ctx, signal });
147
+ const prepared = launch.launch;
148
+ const args = prepared.args.filter((arg) => arg !== "--no-session");
149
+ if (prepared.role !== input.task.role || prepared.modelClass !== input.task.modelClass || args.length + 1 !== prepared.args.length)
150
+ throw new Error("Native Role launch differs from saved request.");
151
+ descriptor = await open(intent.leasePath, constants.O_RDONLY | constants.O_NOFOLLOW);
152
+ const original = await this.identity(intent), actual = await descriptor.stat({ bigint: true });
153
+ if (String(actual.dev) !== original.device || String(actual.ino) !== original.inode)
154
+ throw new Error("Opened lease differs from the saved allocation.");
155
+ return { launch: { args: [...args, "--session", sessionFile], env: { ...prepared.env, [PI_SUBAGENT_PROCESS_LEASE]: intent.leasePath } }, cwd: intent.worktreeCwd, task, leaseFd: descriptor.fd };
156
+ } });
157
+ launch?.launch.onFallbackUse?.();
158
+ if (result.outcome !== "success")
159
+ return { outcome: "unknown", diagnostic: result.errorMessage || "Native worker did not complete its turn." };
160
+ if ((await lstat(sessionFile)).size > 16 * 1024 * 1024)
161
+ throw new Error("Native session exceeds 16 MiB.");
162
+ exactDirectAnswer(await readFile(sessionFile, "utf8"), `Task: ${task}`);
163
+ const inspection = await this.git.inspectInFlightTaskCandidate({ ...input, root: worktree(input.attempt).repoRoot }, ctx);
164
+ if (!inspection.valid)
165
+ return { outcome: "unknown", diagnostic: "Native worker checkout no longer matches its owner." };
166
+ if (!inspection.clean)
167
+ return { outcome: "uncommitted", diagnostic: "Native worker finished with uncommitted changes." };
168
+ if (!isCleanCommitted(inspection.candidate) || (!input.workspacePaths && inspection.candidate.head === input.preCandidate.head))
169
+ return { outcome: "blocked", diagnostic: "Native worker finished without a new committed candidate." };
170
+ return { outcome: "candidate", candidate: inspection.candidate };
171
+ }
172
+ finally {
173
+ try {
174
+ await descriptor?.close();
175
+ await launch?.cleanup();
176
+ }
177
+ finally {
178
+ turns.delete(intent.leasePath);
179
+ }
180
+ }
181
+ }
182
+ async reconcileWorkerTermination(input, ctx) {
183
+ if (legacy(input.attempt))
184
+ return this.previous.reconcileWorkerTermination(input, ctx);
185
+ const intent = native(input.attempt);
186
+ if (!intent)
187
+ throw new Error("Missing native worker identity.");
188
+ this.check(intent, input.attempt, input.workerId);
189
+ for (let scan = 0; scan < 2; scan++) {
190
+ if (scan)
191
+ await sleep(50, undefined, { signal: ctx.signal });
192
+ if (turns.has(intent.leasePath) || (await this.holders(intent, ctx)).length)
193
+ return { outcome: "active" };
194
+ }
195
+ return { outcome: "terminated" };
196
+ }
197
+ async terminateWorker(input, ctx) {
198
+ if (legacy(input.attempt))
199
+ return this.previous.terminateWorker(input, ctx);
200
+ const intent = native(input.attempt);
201
+ if (!intent)
202
+ throw new Error("Missing native worker identity.");
203
+ this.check(intent, input.attempt, input.workerId);
204
+ const turn = turns.get(intent.leasePath);
205
+ turn?.abort();
206
+ // The executor owns the local process group and the parent copy of its descriptor.
207
+ const deadline = Date.now() + Math.min(ctx.timeoutMs ?? 5000, 5000);
208
+ while (turn && turns.get(intent.leasePath) === turn && Date.now() < deadline) {
209
+ await sleep(50, undefined, { signal: ctx.signal });
210
+ }
211
+ if (turns.has(intent.leasePath))
212
+ return { outcome: "unknown", failure: "Local native worker is still settling." };
213
+ for (const [signal, delay] of [["SIGTERM", 250], ["SIGKILL", 100]]) {
214
+ const holders = await this.holders(intent, ctx);
215
+ if (!holders.length)
216
+ break;
217
+ for (const pid of holders) {
218
+ if (pid === process.pid || turns.has(intent.leasePath))
219
+ return { outcome: "unknown", failure: "The coordinator owns the native worker lease." };
220
+ if (!(await this.holders(intent, ctx, pid)).includes(pid))
221
+ continue;
222
+ ctx.signal.throwIfAborted();
223
+ try {
224
+ process.kill(pid, signal);
225
+ }
226
+ catch (error) {
227
+ if (error.code !== "ESRCH")
228
+ throw error;
229
+ }
230
+ }
231
+ await sleep(delay, undefined, { signal: ctx.signal });
232
+ }
233
+ const result = await this.reconcileWorkerTermination(input, ctx);
234
+ if (result.outcome === "unknown")
235
+ return result;
236
+ return result.outcome === "active" ? { outcome: "unknown", failure: "A process still holds the native worker lease." } : { outcome: "terminated" };
237
+ }
238
+ async cleanupHost(input, ctx) {
239
+ if (legacy(input.attempt))
240
+ return this.previous.cleanupHost(input, ctx);
241
+ return { outcome: "absent" };
242
+ }
243
+ }
package/dist/runner.d.ts CHANGED
@@ -51,7 +51,12 @@ export type AgentAllocationResult = {
51
51
  kind: "agent";
52
52
  outcome: "owned";
53
53
  } | AllocationFailureResult<"agent">;
54
- export type HostAllocationResult = WorkspaceAllocationResult | WorkerTabAllocationResult | AgentAllocationResult;
54
+ export type NativeAllocationResult = {
55
+ kind: "native";
56
+ outcome: "owned";
57
+ leaseIdentity: string;
58
+ } | AllocationFailureResult<"native">;
59
+ export type HostAllocationResult = NativeAllocationResult | WorkspaceAllocationResult | WorkerTabAllocationResult | AgentAllocationResult;
55
60
  export type AllocationResult = WorktreeAllocationResult | HostAllocationResult;
56
61
  export type AllocationReconciliation<Kind extends AllocationKind = AllocationKind> = {
57
62
  kind: Kind;
@@ -135,6 +140,7 @@ export interface CoordinatorRuntime {
135
140
  export type HostAllocationKind = Exclude<AllocationKind, "worktree">;
136
141
  export type HostCleanupKind = Extract<CleanupKind, "worker_tab" | "workspace">;
137
142
  export interface HostRuntime {
143
+ allocationKinds?(attempt: TaskAttempt): readonly HostAllocationKind[];
138
144
  planHostAllocation(input: {
139
145
  readonly requestId: ExecuteRequest["id"];
140
146
  readonly goal: ExecuteRequest["goal"];
@@ -157,6 +163,7 @@ export interface HostRuntime {
157
163
  attempt: TaskAttempt;
158
164
  }, context: OperationContext): Promise<AllocationReconciliation<HostAllocationKind>>;
159
165
  runWorker(input: {
166
+ policy?: ExecutionPolicySnapshot;
160
167
  readonly goal: ExecuteRequest["goal"];
161
168
  readonly contexts: readonly TextTaskContext[];
162
169
  task: TaskRequest;
package/dist/runner.js CHANGED
@@ -230,7 +230,7 @@ function runtimeToken(value) {
230
230
  function runtimeHostAllocationPlan(plan, kind) {
231
231
  if (!plan || typeof plan !== "object" || plan.kind !== kind)
232
232
  throw new Error(`${kind} allocation planning returned the wrong kind.`);
233
- const fields = kind === "workspace"
233
+ const fields = kind === "native" ? ["agentName", "worktreeCwd", "leasePath"] : kind === "workspace"
234
234
  ? ["label", "worktreeCwd", "mainRoot", "repoKey", "herdrRepoRoot"]
235
235
  : kind === "worker_tab"
236
236
  ? ["label", "workspaceId", "workspaceRootTabId", "workspaceRootPaneId", "worktreeCwd", "leasePath"]
@@ -333,7 +333,7 @@ function hasPassingPreliminaryEvidence(request, attempt) {
333
333
  && checkBatchPasses(attempt.preliminaryChecks, request.checks, attempt.candidate)
334
334
  && (!request.judgment || reviewEvidencePasses(attempt.preliminaryReview, "preliminary", request.judgment.criterion, attempt.candidateBase, attempt.candidate))
335
335
  && !attempt.prompts.some((prompt) => prompt.status === "ambiguous")
336
- && allocationByKind(attempt, "agent")?.agentName && !attempt.termination);
336
+ && ownedWorker(attempt)?.agentName && !attempt.termination);
337
337
  }
338
338
  function changesetTaskState(state, id) {
339
339
  const task = taskState(state, id);
@@ -354,6 +354,9 @@ function nextAttemptEventAt(attempt, now) {
354
354
  function allocationByKind(attempt, kind) {
355
355
  return [...attempt.allocations].reverse().find((intent) => intent.kind === kind && intent.status === "owned");
356
356
  }
357
+ function ownedWorker(attempt) {
358
+ return allocationByKind(attempt, "native") ?? allocationByKind(attempt, "agent");
359
+ }
357
360
  function applyOwnedAllocationResult(intent, result) {
358
361
  if (result.kind !== intent.kind)
359
362
  throw new Error(`${intent.kind} allocation returned the wrong result kind.`);
@@ -378,7 +381,10 @@ function applyOwnedAllocationResult(intent, result) {
378
381
  intent.tabId = result.tabId;
379
382
  intent.paneId = result.paneId;
380
383
  }
381
- else if (intent.kind !== "agent" || result.kind !== "agent") {
384
+ else if (intent.kind === "native" && result.kind === "native") {
385
+ intent.leaseIdentity = result.leaseIdentity;
386
+ }
387
+ else if (intent.kind !== "agent") {
382
388
  throw new Error(`${intent.kind} allocation result could not be matched to its persisted plan.`);
383
389
  }
384
390
  intent.status = "owned";
@@ -1123,7 +1129,7 @@ export class IsolatedRunner {
1123
1129
  task.status = "needs_attention";
1124
1130
  task.failure = action.action === "revise" ? action.instruction : "Main rejected this candidate; owned resources remain recorded.";
1125
1131
  await this.saveProductive(handle); // Freeze before touching the exact worker.
1126
- if (action.action === "reject" && allocationByKind(attempt, "agent")) {
1132
+ if (action.action === "reject" && ownedWorker(attempt)) {
1127
1133
  if (await this.terminateWithSafety(handle, task, attempt, action.candidate, scope.signal))
1128
1134
  task.status = "rejected";
1129
1135
  else
@@ -1905,7 +1911,7 @@ export class IsolatedRunner {
1905
1911
  });
1906
1912
  }
1907
1913
  async terminateAbortedAttempt(handle, task, attempt, signal, deadline = this.coordinatorRuntime.now() + TERMINATION_SAFETY_BUDGET_MS, current) {
1908
- if (!allocationByKind(attempt, "agent")?.agentName || attempt.termination?.status === "terminated")
1914
+ if (!ownedWorker(attempt)?.agentName || attempt.termination?.status === "terminated")
1909
1915
  return;
1910
1916
  await this.proveTermination(handle, task, attempt, this.terminationCandidate(attempt), async () => await handle.save(), signal, deadline, current);
1911
1917
  }
@@ -1922,7 +1928,7 @@ export class IsolatedRunner {
1922
1928
  return;
1923
1929
  await verify();
1924
1930
  await this.terminateAbortedAttempt(handle, task, attempt, undefined, undefined, current);
1925
- if (allocationByKind(attempt, "agent") && attempt.termination?.status !== "terminated")
1931
+ if (ownedWorker(attempt) && attempt.termination?.status !== "terminated")
1926
1932
  throw new Error("Worker termination remains unproved.");
1927
1933
  const scope = new DeadlineScope(this.coordinatorRuntime.now() + CLEANUP_SAFETY_BUDGET_MS, () => this.coordinatorRuntime.now());
1928
1934
  try {
@@ -2036,7 +2042,7 @@ export class IsolatedRunner {
2036
2042
  if (attempt.allocations.some((item) => item.status === "allocating" || item.status === "unknown")) {
2037
2043
  throw new Error("Allocation ownership is uncertain; preserve the recorded resources for inspection.");
2038
2044
  }
2039
- if (allocationByKind(attempt, "agent") && attempt.termination?.status !== "terminated") {
2045
+ if (ownedWorker(attempt) && attempt.termination?.status !== "terminated") {
2040
2046
  throw new Error("Exact worker termination remains unproved.");
2041
2047
  }
2042
2048
  if (expected && attempt.termination && attempt.termination.candidate.head !== expected.head
@@ -2300,7 +2306,7 @@ export class IsolatedRunner {
2300
2306
  const request = changesetTaskRequest(state, task.taskId);
2301
2307
  const attempt = latestAttempt(task);
2302
2308
  try {
2303
- for (const kind of ALLOCATION_KINDS) {
2309
+ for (const kind of this.hostRuntime.allocationKinds ? ["worktree", ...this.hostRuntime.allocationKinds(attempt)] : ALLOCATION_KINDS) {
2304
2310
  if (allocationByKind(attempt, kind))
2305
2311
  continue;
2306
2312
  let intent;
@@ -2569,7 +2575,7 @@ export class IsolatedRunner {
2569
2575
  const state = handle.state;
2570
2576
  const request = changesetTaskRequest(state, task.taskId);
2571
2577
  const attempt = latestAttempt(task);
2572
- const workerId = allocationByKind(attempt, "agent")?.agentName;
2578
+ const workerId = ownedWorker(attempt)?.agentName;
2573
2579
  if (!workerId)
2574
2580
  throw new Error("Worker launch has no durably recorded agent ID.");
2575
2581
  let kind = initialKind;
@@ -2643,6 +2649,7 @@ export class IsolatedRunner {
2643
2649
  let worker;
2644
2650
  try {
2645
2651
  worker = await this.callProductive(handle, scope, async (context) => await this.hostRuntime.runWorker({
2652
+ policy: state.policy,
2646
2653
  goal: state.request.goal,
2647
2654
  contexts: resolveTextTaskContexts(state, request),
2648
2655
  task: request,
@@ -2726,7 +2733,7 @@ export class IsolatedRunner {
2726
2733
  task.status = "working";
2727
2734
  continue;
2728
2735
  }
2729
- const workerId = allocationByKind(attempt, "agent")?.agentName;
2736
+ const workerId = ownedWorker(attempt)?.agentName;
2730
2737
  if (!workerId || attempt.termination || !attempt.candidate || !attempt.candidateBase
2731
2738
  || !checkBatchPasses(attempt.preliminaryChecks, request.checks, attempt.candidate)) {
2732
2739
  throw new Error("Readiness requires an exact live owned worker and passing candidate lineage.");
@@ -2780,7 +2787,7 @@ export class IsolatedRunner {
2780
2787
  async proveTermination(handle, task, attempt, candidate, save, signal, deadline = this.coordinatorRuntime.now() + TERMINATION_SAFETY_BUDGET_MS, current) {
2781
2788
  if (attempt.termination?.status === "terminated")
2782
2789
  return;
2783
- const workerId = attempt.termination?.workerId ?? allocationByKind(attempt, "agent")?.agentName;
2790
+ const workerId = attempt.termination?.workerId ?? ownedWorker(attempt)?.agentName;
2784
2791
  if (!workerId)
2785
2792
  throw new Error("Worker termination requires an exact durably owned agent ID.");
2786
2793
  const input = { task: changesetTaskRequest(handle.state, task.taskId), attempt, workerId,
@@ -2822,7 +2829,7 @@ export class IsolatedRunner {
2822
2829
  return await this.withLifecycleLock(handle, async () => await this.terminateWithSafety(handle, task, attempt, candidate, outerSignal, safetyDeadline, true));
2823
2830
  }
2824
2831
  const save = async () => lifecycleLocked ? await handle.save() : await this.saveProductive(handle);
2825
- const workerId = allocationByKind(attempt, "agent")?.agentName;
2832
+ const workerId = ownedWorker(attempt)?.agentName;
2826
2833
  if (!workerId)
2827
2834
  throw new Error("Safety termination requires an exact durably owned agent ID.");
2828
2835
  attempt.termination = { status: "terminating", workerId, candidate };
@@ -3014,7 +3021,7 @@ export class IsolatedRunner {
3014
3021
  contexts: resolveTextTaskContexts(handle.state, request),
3015
3022
  task: request,
3016
3023
  kind: "correction",
3017
- worktreeCwd: allocationByKind(attempt, "agent")?.worktreeCwd ?? "",
3024
+ worktreeCwd: ownedWorker(attempt)?.worktreeCwd ?? "",
3018
3025
  failure: task.failure,
3019
3026
  ...(instruction === undefined ? {} : { instruction }),
3020
3027
  });
@@ -3025,7 +3032,7 @@ export class IsolatedRunner {
3025
3032
  await this.driveWorkerSafely(handle, task, scope, "correction", instruction);
3026
3033
  }
3027
3034
  else {
3028
- if (attempt.termination || allocationByKind(attempt, "agent")) {
3035
+ if (attempt.termination || ownedWorker(attempt)) {
3029
3036
  throw new Error("A promptless attempt with a terminated or potentially active saved agent cannot be retried productively.");
3030
3037
  }
3031
3038
  for (const intent of attempt.allocations.filter((item) => item.status !== "owned")) {
@@ -3278,7 +3285,7 @@ export class IsolatedRunner {
3278
3285
  }
3279
3286
  const control = new FollowupControl((instruction) => {
3280
3287
  const attempt = latestAttempt(task);
3281
- const agent = allocationByKind(attempt, "agent");
3288
+ const agent = ownedWorker(attempt);
3282
3289
  if (!agent)
3283
3290
  throw new Error("Worker launch has no durably recorded agent allocation.");
3284
3291
  buildChangesetTaskPrompt({
package/dist/schema.d.ts CHANGED
@@ -222,7 +222,32 @@ declare const AgentAllocationIntentSchema: Type.TObject<{
222
222
  worktreeCwd: Type.TString;
223
223
  leasePath: Type.TString;
224
224
  }>;
225
+ declare const NativeAllocationIntentSchema: Type.TObject<{
226
+ generation: Type.TInteger;
227
+ token: Type.TString;
228
+ status: Type.TUnion<[Type.TLiteral<"allocating">, Type.TLiteral<"owned">, Type.TLiteral<"absent">, Type.TLiteral<"unknown">]>;
229
+ possibleResources: Type.TOptional<Type.TArray<Type.TString>>;
230
+ failure: Type.TOptional<Type.TString>;
231
+ kind: Type.TLiteral<"native">;
232
+ leaseIdentity: Type.TOptional<Type.TString>;
233
+ agentName: Type.TString;
234
+ worktreeCwd: Type.TString;
235
+ leasePath: Type.TString;
236
+ }>;
237
+ export type NativeAllocationIntent = Static<typeof NativeAllocationIntentSchema>;
238
+ export type NativeAllocationPlan = Pick<NativeAllocationIntent, "kind" | "agentName" | "worktreeCwd" | "leasePath">;
225
239
  export declare const AllocationIntentSchema: Type.TUnion<[Type.TObject<{
240
+ generation: Type.TInteger;
241
+ token: Type.TString;
242
+ status: Type.TUnion<[Type.TLiteral<"allocating">, Type.TLiteral<"owned">, Type.TLiteral<"absent">, Type.TLiteral<"unknown">]>;
243
+ possibleResources: Type.TOptional<Type.TArray<Type.TString>>;
244
+ failure: Type.TOptional<Type.TString>;
245
+ kind: Type.TLiteral<"native">;
246
+ leaseIdentity: Type.TOptional<Type.TString>;
247
+ agentName: Type.TString;
248
+ worktreeCwd: Type.TString;
249
+ leasePath: Type.TString;
250
+ }>, Type.TObject<{
226
251
  generation: Type.TInteger;
227
252
  token: Type.TString;
228
253
  status: Type.TUnion<[Type.TLiteral<"allocating">, Type.TLiteral<"owned">, Type.TLiteral<"absent">, Type.TLiteral<"unknown">]>;
@@ -291,8 +316,8 @@ export type WorktreeAllocationPlan = WorktreeRecord;
291
316
  export type WorkspaceAllocationPlan = Pick<WorkspaceAllocationIntent, "kind" | "label" | "worktreeCwd" | "mainRoot" | "repoKey" | "herdrRepoRoot">;
292
317
  export type WorkerTabAllocationPlan = Pick<WorkerTabAllocationIntent, "kind" | "label" | "workspaceId" | "workspaceRootTabId" | "workspaceRootPaneId" | "worktreeCwd" | "leasePath">;
293
318
  export type AgentAllocationPlan = Pick<AgentAllocationIntent, "kind" | "agentName" | "workspaceId" | "tabId" | "paneId" | "worktreeCwd" | "leasePath">;
294
- export type HostAllocationIntent = WorkspaceAllocationIntent | WorkerTabAllocationIntent | AgentAllocationIntent;
295
- export type HostAllocationPlan = WorkspaceAllocationPlan | WorkerTabAllocationPlan | AgentAllocationPlan;
319
+ export type HostAllocationIntent = NativeAllocationIntent | WorkspaceAllocationIntent | WorkerTabAllocationIntent | AgentAllocationIntent;
320
+ export type HostAllocationPlan = NativeAllocationPlan | WorkspaceAllocationPlan | WorkerTabAllocationPlan | AgentAllocationPlan;
296
321
  export type PromptRecord = Static<typeof PromptRecordSchema>;
297
322
  export type CommandEvidence = Static<typeof CommandEvidenceSchema>;
298
323
  export type CheckBatchEvidence = Static<typeof CheckBatchEvidenceSchema>;
@@ -523,6 +548,17 @@ export declare const TaskAttemptSchema: Type.TObject<{
523
548
  correlationToken: Type.TString;
524
549
  allocationGeneration: Type.TInteger;
525
550
  allocations: Type.TArray<Type.TUnion<[Type.TObject<{
551
+ generation: Type.TInteger;
552
+ token: Type.TString;
553
+ status: Type.TUnion<[Type.TLiteral<"allocating">, Type.TLiteral<"owned">, Type.TLiteral<"absent">, Type.TLiteral<"unknown">]>;
554
+ possibleResources: Type.TOptional<Type.TArray<Type.TString>>;
555
+ failure: Type.TOptional<Type.TString>;
556
+ kind: Type.TLiteral<"native">;
557
+ leaseIdentity: Type.TOptional<Type.TString>;
558
+ agentName: Type.TString;
559
+ worktreeCwd: Type.TString;
560
+ leasePath: Type.TString;
561
+ }>, Type.TObject<{
526
562
  generation: Type.TInteger;
527
563
  token: Type.TString;
528
564
  status: Type.TUnion<[Type.TLiteral<"allocating">, Type.TLiteral<"owned">, Type.TLiteral<"absent">, Type.TLiteral<"unknown">]>;
@@ -721,6 +757,17 @@ declare const ChangesetTaskStateSchema: Type.TObject<{
721
757
  correlationToken: Type.TString;
722
758
  allocationGeneration: Type.TInteger;
723
759
  allocations: Type.TArray<Type.TUnion<[Type.TObject<{
760
+ generation: Type.TInteger;
761
+ token: Type.TString;
762
+ status: Type.TUnion<[Type.TLiteral<"allocating">, Type.TLiteral<"owned">, Type.TLiteral<"absent">, Type.TLiteral<"unknown">]>;
763
+ possibleResources: Type.TOptional<Type.TArray<Type.TString>>;
764
+ failure: Type.TOptional<Type.TString>;
765
+ kind: Type.TLiteral<"native">;
766
+ leaseIdentity: Type.TOptional<Type.TString>;
767
+ agentName: Type.TString;
768
+ worktreeCwd: Type.TString;
769
+ leasePath: Type.TString;
770
+ }>, Type.TObject<{
724
771
  generation: Type.TInteger;
725
772
  token: Type.TString;
726
773
  status: Type.TUnion<[Type.TLiteral<"allocating">, Type.TLiteral<"owned">, Type.TLiteral<"absent">, Type.TLiteral<"unknown">]>;
@@ -1010,6 +1057,17 @@ declare const TaskStateSchema: Type.TUnion<[Type.TObject<{
1010
1057
  correlationToken: Type.TString;
1011
1058
  allocationGeneration: Type.TInteger;
1012
1059
  allocations: Type.TArray<Type.TUnion<[Type.TObject<{
1060
+ generation: Type.TInteger;
1061
+ token: Type.TString;
1062
+ status: Type.TUnion<[Type.TLiteral<"allocating">, Type.TLiteral<"owned">, Type.TLiteral<"absent">, Type.TLiteral<"unknown">]>;
1063
+ possibleResources: Type.TOptional<Type.TArray<Type.TString>>;
1064
+ failure: Type.TOptional<Type.TString>;
1065
+ kind: Type.TLiteral<"native">;
1066
+ leaseIdentity: Type.TOptional<Type.TString>;
1067
+ agentName: Type.TString;
1068
+ worktreeCwd: Type.TString;
1069
+ leasePath: Type.TString;
1070
+ }>, Type.TObject<{
1013
1071
  generation: Type.TInteger;
1014
1072
  token: Type.TString;
1015
1073
  status: Type.TUnion<[Type.TLiteral<"allocating">, Type.TLiteral<"owned">, Type.TLiteral<"absent">, Type.TLiteral<"unknown">]>;
@@ -1869,6 +1927,17 @@ declare const RunStateSchema: Type.TObject<{
1869
1927
  correlationToken: Type.TString;
1870
1928
  allocationGeneration: Type.TInteger;
1871
1929
  allocations: Type.TArray<Type.TUnion<[Type.TObject<{
1930
+ generation: Type.TInteger;
1931
+ token: Type.TString;
1932
+ status: Type.TUnion<[Type.TLiteral<"allocating">, Type.TLiteral<"owned">, Type.TLiteral<"absent">, Type.TLiteral<"unknown">]>;
1933
+ possibleResources: Type.TOptional<Type.TArray<Type.TString>>;
1934
+ failure: Type.TOptional<Type.TString>;
1935
+ kind: Type.TLiteral<"native">;
1936
+ leaseIdentity: Type.TOptional<Type.TString>;
1937
+ agentName: Type.TString;
1938
+ worktreeCwd: Type.TString;
1939
+ leasePath: Type.TString;
1940
+ }>, Type.TObject<{
1872
1941
  generation: Type.TInteger;
1873
1942
  token: Type.TString;
1874
1943
  status: Type.TUnion<[Type.TLiteral<"allocating">, Type.TLiteral<"owned">, Type.TLiteral<"absent">, Type.TLiteral<"unknown">]>;
package/dist/schema.js CHANGED
@@ -132,7 +132,13 @@ const AgentAllocationIntentSchema = Type.Object({
132
132
  worktreeCwd: RuntimeTextSchema,
133
133
  leasePath: RuntimeTextSchema,
134
134
  }, { additionalProperties: false });
135
+ const NativeAllocationIntentSchema = Type.Object({
136
+ kind: Type.Literal("native"), ...AllocationLifecycleFields,
137
+ leaseIdentity: Type.Optional(Type.String({ maxLength: 512 })),
138
+ agentName: RuntimeTextSchema, worktreeCwd: RuntimeTextSchema, leasePath: RuntimeTextSchema,
139
+ }, { additionalProperties: false });
135
140
  export const AllocationIntentSchema = Type.Union([
141
+ NativeAllocationIntentSchema,
136
142
  WorktreeAllocationIntentSchema,
137
143
  WorkspaceAllocationIntentSchema,
138
144
  WorkerTabAllocationIntentSchema,
@@ -1098,7 +1104,7 @@ export function parseRunState(value) {
1098
1104
  }
1099
1105
  if (attempt.termination) {
1100
1106
  const termination = attempt.termination;
1101
- const ownedAgent = [...attempt.allocations].reverse().find((allocation) => allocation.kind === "agent");
1107
+ const ownedAgent = [...attempt.allocations].reverse().find((allocation) => allocation.kind === "agent" || allocation.kind === "native");
1102
1108
  if (!ownedAgent || ownedAgent.status !== "owned" || termination.workerId !== ownedAgent.agentName) {
1103
1109
  throw new Error(`Worker termination for ${definition.id} does not match the exact owned agent.`);
1104
1110
  }
@@ -1176,6 +1182,13 @@ export function parseRunState(value) {
1176
1182
  const worktree = attempt.allocations.find((candidate) => candidate.kind === "worktree" && candidate.status === "owned" && hasWorktreePlan(candidate));
1177
1183
  if (!worktree)
1178
1184
  throw new Error(`${allocation.kind} allocation for ${definition.id} lacks its exact owned worktree parent.`);
1185
+ if (allocation.kind === "native") {
1186
+ if (allocation.worktreeCwd !== worktree.worktree.cwd || allocation.agentName !== `native-${attempt.correlationToken}`
1187
+ || attempt.allocations.some((item) => item.kind !== "worktree" && item !== allocation))
1188
+ throw new Error("Native worker allocation does not match the owned attempt.");
1189
+ requireAbsoluteAllocationPath(allocation.leasePath, "Native process lease");
1190
+ continue;
1191
+ }
1179
1192
  if (allocation.kind === "workspace") {
1180
1193
  for (const [field, value] of Object.entries({
1181
1194
  label: allocation.label, worktreeCwd: allocation.worktreeCwd, mainRoot: allocation.mainRoot,
@@ -157,6 +157,17 @@ export declare const WorkspaceStateSchema: Type.TObject<{
157
157
  correlationToken: Type.TString;
158
158
  allocationGeneration: Type.TInteger;
159
159
  allocations: Type.TArray<Type.TUnion<[Type.TObject<{
160
+ generation: Type.TInteger;
161
+ token: Type.TString;
162
+ status: Type.TUnion<[Type.TLiteral<"allocating">, Type.TLiteral<"owned">, Type.TLiteral<"absent">, Type.TLiteral<"unknown">]>;
163
+ possibleResources: Type.TOptional<Type.TArray<Type.TString>>;
164
+ failure: Type.TOptional<Type.TString>;
165
+ kind: Type.TLiteral<"native">;
166
+ leaseIdentity: Type.TOptional<Type.TString>;
167
+ agentName: Type.TString;
168
+ worktreeCwd: Type.TString;
169
+ leasePath: Type.TString;
170
+ }>, Type.TObject<{
160
171
  generation: Type.TInteger;
161
172
  token: Type.TString;
162
173
  status: Type.TUnion<[Type.TLiteral<"allocating">, Type.TLiteral<"owned">, Type.TLiteral<"absent">, Type.TLiteral<"unknown">]>;
@@ -6,9 +6,10 @@ import { type CoordinatorRuntime, type HostRuntime, type OperationContext } from
6
6
  import { type WorkspaceState } from "./workspace-schema.ts";
7
7
  import { type WorkspaceScope } from "./workspace-scope.ts";
8
8
  export interface WorkspaceRuntimeOptions {
9
+ onStateSaved?(state: WorkspaceState): void;
9
10
  coordinator: CoordinatorRuntime;
10
11
  host(policy: WorkspaceState["policy"]): HostRuntime;
11
- preflightHost(root: string, operation: OperationContext): Promise<void>;
12
+ preflightHost?(root: string, operation: OperationContext): Promise<void>;
12
13
  policy(): ExecutionPolicySnapshot;
13
14
  agentDir?: string;
14
15
  git?: CheckedGitRuntime;
@@ -20,6 +21,9 @@ export declare function workspacePruneOwners(checkouts: readonly string[], agent
20
21
  label: string;
21
22
  text?: string;
22
23
  }>>;
24
+ export declare function readWorkspaceStatus(cwd: string, id: string, agentDir?: string): Promise<WorkspaceState>;
25
+ /** Construct a runner for saved cleanup without enabling launches or allocation. */
26
+ export declare function createWorkspaceCleanupRunner(agentDir?: string): Pick<WorkspaceRunner, "action">;
23
27
  /** A whole repository set is the validation unit. Git mutations remain serial, never atomic. */
24
28
  export declare class WorkspaceRunner {
25
29
  private readonly git;
@@ -28,7 +32,6 @@ export declare class WorkspaceRunner {
28
32
  private readonly active;
29
33
  private readonly options;
30
34
  constructor(options: WorkspaceRuntimeOptions);
31
- private directory;
32
35
  private save;
33
36
  status(cwd: string, id: string): Promise<WorkspaceState>;
34
37
  private locked;