@henryqw/pi-subagent 27.15.1 → 27.16.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.
- package/CONTEXT.md +9 -0
- package/README.md +8 -0
- package/dist/herdr-runtime.d.ts +10 -1
- package/dist/herdr-runtime.js +51 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -0
- package/dist/process.d.ts +1 -0
- package/dist/process.js +1 -1
- package/dist/runner.d.ts +21 -0
- package/dist/runner.js +7 -3
- package/dist/schema.d.ts +4 -4
- package/dist/schema.js +4 -4
- package/dist/store.d.ts +1 -1
- package/dist/workspace-schema.d.ts +462 -0
- package/dist/workspace-schema.js +111 -0
- package/dist/workspace-scope.d.ts +16 -0
- package/dist/workspace-scope.js +60 -0
- package/dist/workspace.d.ts +98 -0
- package/dist/workspace.js +623 -0
- package/docs/orchestration.md +4 -0
- package/docs/workspace.md +85 -0
- package/extensions/result-transport.ts +1 -0
- package/extensions/subagent.ts +29 -8
- package/extensions/workflow.ts +14 -4
- package/extensions/workspace.ts +83 -0
- package/package.json +2 -2
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { chmod, lstat, mkdir, open, readFile, readdir, realpath } from "node:fs/promises";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { extensionConfigDir, readTextFileBounded, writePrivateTextFileAtomically } from "@henryqw/pi-config-store";
|
|
6
|
+
import { lock } from "proper-lockfile";
|
|
7
|
+
import { Check } from "typebox/value";
|
|
8
|
+
import { CheckedGitRuntime } from "./git-runtime.js";
|
|
9
|
+
import { IntegrationGit } from "./integration-git.js";
|
|
10
|
+
import { FileRunStore } from "./store.js";
|
|
11
|
+
import { runProcess } from "./process.js";
|
|
12
|
+
import { runGit } from "./git-process.js";
|
|
13
|
+
import { utf8Prefix } from "./ephemeral.js";
|
|
14
|
+
import { CLEANUP_KINDS, sameIdentity } from "./schema.js";
|
|
15
|
+
import { DeadlineScope } from "./runner.js";
|
|
16
|
+
import { parseWorkspaceRequest, parseWorkspaceState, sameSet, workerTask, WorkspaceActionSchema } from "./workspace-schema.js";
|
|
17
|
+
import { resolveWorkspaceScope, workspaceInputPath } from "./workspace-scope.js";
|
|
18
|
+
const hash = (value) => createHash("sha256").update(value).digest("hex");
|
|
19
|
+
const diagnostic = (error) => utf8Prefix(error instanceof Error ? error.message : String(error), 8192);
|
|
20
|
+
const context = (signal) => ({ signal, timeoutMs: 30_000 });
|
|
21
|
+
const safeContext = () => context(AbortSignal.timeout(30_000));
|
|
22
|
+
const owned = (attempt) => {
|
|
23
|
+
const intent = attempt.allocations.find((item) => item.kind === "worktree");
|
|
24
|
+
if (!intent?.worktree || intent.status !== "owned")
|
|
25
|
+
throw new Error("Workspace member has no exact owned worktree.");
|
|
26
|
+
return intent.worktree;
|
|
27
|
+
};
|
|
28
|
+
const branchBase = (repo) => ({ ...repo.base, branch: `refs/heads/${owned(repo.attempt).branch}` });
|
|
29
|
+
function suite(manifest) {
|
|
30
|
+
const value = JSON.parse(manifest);
|
|
31
|
+
if (value?.scripts?.test === undefined)
|
|
32
|
+
return undefined;
|
|
33
|
+
if (typeof value.scripts.test !== "string" || !value.scripts.test.trim())
|
|
34
|
+
throw new Error("Root package.json test script must be a non-empty string.");
|
|
35
|
+
return value.scripts.test;
|
|
36
|
+
}
|
|
37
|
+
const passes = (evidence, checks, expected) => Boolean(evidence
|
|
38
|
+
&& sameSet(evidence.before, expected) && sameSet(evidence.after, expected) && evidence.results.length === checks.length
|
|
39
|
+
&& evidence.results.every((result, index) => result.code === 0 && !result.killed && result.repository === checks[index].repository
|
|
40
|
+
&& result.command === checks[index].command && JSON.stringify(result.args) === JSON.stringify(checks[index].args)));
|
|
41
|
+
/** Include workspace ownership in the existing prune gate, including unchanged secondary worktrees. */
|
|
42
|
+
export async function workspacePruneOwners(checkouts, agentDir) {
|
|
43
|
+
const owners = [];
|
|
44
|
+
for (const root of new Set(checkouts.map((path) => dirname(path)))) {
|
|
45
|
+
const directory = join(extensionConfigDir("pi-subagent", agentDir), "workspace-state", hash(root));
|
|
46
|
+
let names;
|
|
47
|
+
try {
|
|
48
|
+
names = await readdir(directory);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (error.code !== "ENOENT")
|
|
52
|
+
owners.push({ label: "Unreadable workspace state may own this resource" });
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (names.length > 256) {
|
|
56
|
+
owners.push({ label: "Workspace state inventory limit reached" });
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
for (const name of names) {
|
|
60
|
+
try {
|
|
61
|
+
const text = await readTextFileBounded(join(directory, name, "state.json"), 2 * 1024 * 1024);
|
|
62
|
+
const state = parseWorkspaceState(JSON.parse(text));
|
|
63
|
+
if (state.status !== "cleaned")
|
|
64
|
+
owners.push({ label: `Owned by workspace request ${state.request.id}; use subagent_workspace`, text });
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
owners.push({ label: `Unreadable workspace request ${name} may own this resource` });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return owners;
|
|
72
|
+
}
|
|
73
|
+
/** A whole repository set is the validation unit. Git mutations remain serial, never atomic. */
|
|
74
|
+
export class WorkspaceRunner {
|
|
75
|
+
git;
|
|
76
|
+
integration;
|
|
77
|
+
store;
|
|
78
|
+
active = new Map();
|
|
79
|
+
options;
|
|
80
|
+
constructor(options) {
|
|
81
|
+
this.options = options;
|
|
82
|
+
this.git = options.git ?? new CheckedGitRuntime();
|
|
83
|
+
this.integration = options.integration ?? new IntegrationGit();
|
|
84
|
+
this.store = new FileRunStore(options.agentDir);
|
|
85
|
+
}
|
|
86
|
+
directory(root, id) {
|
|
87
|
+
if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(id) || id.length > 80)
|
|
88
|
+
throw new Error("Invalid workspace request ID.");
|
|
89
|
+
const directory = resolve(extensionConfigDir("pi-subagent", this.options.agentDir), "workspace-state", hash(root), id);
|
|
90
|
+
if (directory === root || directory.startsWith(`${root}/`))
|
|
91
|
+
throw new Error("Workspace state must be outside the workspace.");
|
|
92
|
+
return directory;
|
|
93
|
+
}
|
|
94
|
+
async save(state) {
|
|
95
|
+
parseWorkspaceState(state);
|
|
96
|
+
const text = JSON.stringify(state);
|
|
97
|
+
if (Buffer.byteLength(text) > 2 * 1024 * 1024)
|
|
98
|
+
throw new Error("Workspace state exceeds 2 MiB; resources are retained.");
|
|
99
|
+
await writePrivateTextFileAtomically(join(this.directory(state.root, state.request.id), "state.json"), text);
|
|
100
|
+
}
|
|
101
|
+
async status(cwd, id) {
|
|
102
|
+
const root = await realpath(cwd), path = join(this.directory(root, id), "state.json");
|
|
103
|
+
const stat = await lstat(path);
|
|
104
|
+
if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077) !== 0 || await realpath(path) !== path)
|
|
105
|
+
throw new Error("Workspace state is not an exact private regular file.");
|
|
106
|
+
const state = parseWorkspaceState(JSON.parse(await readTextFileBounded(path, 2 * 1024 * 1024)));
|
|
107
|
+
if (state.root !== root || state.request.id !== id)
|
|
108
|
+
throw new Error("Workspace state address changed.");
|
|
109
|
+
return state;
|
|
110
|
+
}
|
|
111
|
+
async locked(scope, id, operation) {
|
|
112
|
+
const directory = this.directory(scope.root, id);
|
|
113
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
114
|
+
if (await realpath(directory) !== directory)
|
|
115
|
+
throw new Error("Workspace state directory is not canonical.");
|
|
116
|
+
await chmod(directory, 0o700);
|
|
117
|
+
const release = await lock(join(directory, "lifecycle"), { realpath: false, stale: 30_000, update: 5_000, retries: 0 });
|
|
118
|
+
const roots = Object.values(scope.repositories).map(({ root }) => root).sort();
|
|
119
|
+
const lease = async (index) => index === roots.length ? await operation()
|
|
120
|
+
: await this.store.withProductiveRunLease(roots[index], async () => await lease(index + 1));
|
|
121
|
+
try {
|
|
122
|
+
return await lease(0);
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
await release();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
async plan(value, cwd, signal = new AbortController().signal) {
|
|
129
|
+
const request = parseWorkspaceRequest(value);
|
|
130
|
+
const scope = await resolveWorkspaceScope(cwd, request.repositories, signal);
|
|
131
|
+
const bases = {}, scripts = {};
|
|
132
|
+
for (const [name, repo] of Object.entries(scope.repositories)) {
|
|
133
|
+
bases[name] = await this.git.inspectMainBase({ root: repo.root }, context(signal));
|
|
134
|
+
const entry = await runGit(["ls-tree", bases[name].head, "--", "package.json"], repo.root, signal);
|
|
135
|
+
if (entry.code !== 0)
|
|
136
|
+
throw new Error(`Cannot inspect committed manifest for repository ${name}: ${entry.stderr}`);
|
|
137
|
+
if (!entry.stdout)
|
|
138
|
+
continue;
|
|
139
|
+
const manifest = await runGit(["show", `${bases[name].head}:package.json`], repo.root, signal);
|
|
140
|
+
if (manifest.code !== 0)
|
|
141
|
+
throw new Error(`Cannot read committed test script for repository ${name}: ${manifest.stderr}`);
|
|
142
|
+
const script = suite(manifest.stdout);
|
|
143
|
+
if (script !== undefined)
|
|
144
|
+
scripts[name] = script;
|
|
145
|
+
}
|
|
146
|
+
for (const path of Object.values(request.tasks[0].inputs ?? {})) {
|
|
147
|
+
await workspaceInputPath(scope, path);
|
|
148
|
+
if ((await lstat(path)).size > 64 * 1024)
|
|
149
|
+
throw new Error("Each workspace input must be at most 64 KiB.");
|
|
150
|
+
}
|
|
151
|
+
// Resolve the same effective Role, tools, Skills, and model as a single-repository launch.
|
|
152
|
+
const rolePlan = await this.options.coordinator.preflight({ request: { mode: "isolated", id: request.id, goal: request.goal,
|
|
153
|
+
tasks: [workerTask(request)], finalChecks: request.finalChecks.map(({ repository: _repository, ...check }) => check) },
|
|
154
|
+
cwd: Object.values(scope.repositories)[0].root, dryRun: true }, context(signal));
|
|
155
|
+
return { request, scope, bases, scripts, routes: rolePlan.routes };
|
|
156
|
+
}
|
|
157
|
+
async execute(value, cwd, signal = new AbortController().signal, accepted) {
|
|
158
|
+
const plan = await this.plan(value, cwd, signal);
|
|
159
|
+
await this.options.preflightHost(plan.scope.root, context(signal));
|
|
160
|
+
return await this.locked(plan.scope, plan.request.id, async () => {
|
|
161
|
+
const { request, scope, bases, scripts } = plan;
|
|
162
|
+
const policy = this.options.policy();
|
|
163
|
+
const state = { version: 1, root: scope.root, request, status: "allocating", inputs: {}, repositories: {},
|
|
164
|
+
policy: { ...policy } };
|
|
165
|
+
for (const [name, repo] of Object.entries(scope.repositories))
|
|
166
|
+
state.repositories[name] = { ...repo, base: bases[name], ...(scripts[name] === undefined ? {} : { testScript: scripts[name] }),
|
|
167
|
+
attempt: { number: 1, waveNumber: 1, waveBase: bases[name], correlationToken: randomBytes(12).toString("hex"), allocationGeneration: 1, allocations: [], prompts: [], cleanup: CLEANUP_KINDS.map((kind) => ({ kind, status: "pending" })) } };
|
|
168
|
+
// Exclusive creation prevents replay, including a prior crash before the first allocation.
|
|
169
|
+
const file = await open(join(this.directory(scope.root, request.id), "state.json"), constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
|
|
170
|
+
try {
|
|
171
|
+
await file.writeFile(JSON.stringify(parseWorkspaceState(state)));
|
|
172
|
+
await file.sync();
|
|
173
|
+
}
|
|
174
|
+
finally {
|
|
175
|
+
await file.close();
|
|
176
|
+
}
|
|
177
|
+
const directory = await open(this.directory(scope.root, request.id), "r");
|
|
178
|
+
try {
|
|
179
|
+
await directory.sync();
|
|
180
|
+
}
|
|
181
|
+
finally {
|
|
182
|
+
await directory.close();
|
|
183
|
+
}
|
|
184
|
+
accepted?.(structuredClone(state));
|
|
185
|
+
const controller = new AbortController(), key = `${scope.root}\0${request.id}`;
|
|
186
|
+
this.active.set(key, controller);
|
|
187
|
+
const activeSignal = AbortSignal.any([signal, controller.signal]);
|
|
188
|
+
try {
|
|
189
|
+
for (const [name, source] of Object.entries(request.tasks[0].inputs ?? {})) {
|
|
190
|
+
const bytes = await readFile(await workspaceInputPath(scope, source));
|
|
191
|
+
if (bytes.length > 64 * 1024)
|
|
192
|
+
throw new Error("Workspace input grew beyond 64 KiB.");
|
|
193
|
+
const path = join(this.directory(scope.root, request.id), `input-${name}`);
|
|
194
|
+
state.inputs[name] = { source, path, digest: hash(bytes) };
|
|
195
|
+
await this.save(state);
|
|
196
|
+
const input = await open(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o400);
|
|
197
|
+
try {
|
|
198
|
+
await input.writeFile(bytes);
|
|
199
|
+
await input.sync();
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
await input.close();
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
await this.allocate(state, activeSignal);
|
|
206
|
+
await this.work(state, activeSignal);
|
|
207
|
+
state.candidates = await this.inspectWorkers(state, activeSignal);
|
|
208
|
+
if (Object.keys(state.repositories).every((name) => state.candidates[name].head === state.repositories[name].base.head))
|
|
209
|
+
throw new Error("The worker made no committed change in the selected repository set.");
|
|
210
|
+
await this.stop(state);
|
|
211
|
+
state.status = "checking";
|
|
212
|
+
await this.save(state);
|
|
213
|
+
state.preliminary = await this.checks(state, state.candidates, request.tasks[0].checks, false, activeSignal);
|
|
214
|
+
if (!passes(state.preliminary, request.tasks[0].checks, state.candidates))
|
|
215
|
+
throw new Error("Workspace task checks failed or the complete input set changed.");
|
|
216
|
+
state.status = "ready";
|
|
217
|
+
delete state.failure;
|
|
218
|
+
await this.save(state);
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
state.failure = diagnostic(error);
|
|
222
|
+
state.status = activeSignal.aborted ? "aborted" : "attention";
|
|
223
|
+
try {
|
|
224
|
+
await this.stop(state);
|
|
225
|
+
}
|
|
226
|
+
catch (stopError) {
|
|
227
|
+
state.failure = diagnostic(`${state.failure}\nTermination: ${diagnostic(stopError)}`);
|
|
228
|
+
}
|
|
229
|
+
await this.save(state);
|
|
230
|
+
}
|
|
231
|
+
finally {
|
|
232
|
+
this.active.delete(key);
|
|
233
|
+
}
|
|
234
|
+
return state;
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
async verifyScope(state, signal) {
|
|
238
|
+
const scope = await resolveWorkspaceScope(state.root, state.request.repositories, signal);
|
|
239
|
+
for (const [name, repo] of Object.entries(scope.repositories))
|
|
240
|
+
if (repo.common !== state.repositories[name].common)
|
|
241
|
+
throw new Error(`Repository identity changed: ${name}.`);
|
|
242
|
+
for (const [name, input] of Object.entries(state.inputs)) {
|
|
243
|
+
if (input.path !== join(this.directory(state.root, state.request.id), `input-${name}`) || input.source !== state.request.tasks[0].inputs?.[name])
|
|
244
|
+
throw new Error("Workspace input identity changed.");
|
|
245
|
+
await workspaceInputPath(scope, input.source);
|
|
246
|
+
for (const path of [input.source, input.path]) {
|
|
247
|
+
const stat = await lstat(path);
|
|
248
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 64 * 1024 || await realpath(path) !== path || hash(await readFile(path)) !== input.digest)
|
|
249
|
+
throw new Error(`Read-only workspace input changed: ${name}.`);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (Object.keys(state.inputs).length !== Object.keys(state.request.tasks[0].inputs ?? {}).length)
|
|
253
|
+
throw new Error("Workspace input set is incomplete.");
|
|
254
|
+
}
|
|
255
|
+
async allocate(state, signal) {
|
|
256
|
+
const task = workerTask(state.request);
|
|
257
|
+
for (const repo of Object.values(state.repositories)) {
|
|
258
|
+
await this.verifyScope(state, signal);
|
|
259
|
+
for (const member of Object.values(state.repositories))
|
|
260
|
+
if (!sameIdentity(await this.git.inspectMainBase({ root: member.root }, context(signal)), member.base))
|
|
261
|
+
throw new Error("Main changed before complete-set allocation.");
|
|
262
|
+
const intent = { kind: "worktree", generation: 1, token: repo.attempt.correlationToken, status: "allocating" };
|
|
263
|
+
repo.attempt.allocations.push(intent);
|
|
264
|
+
await this.save(state);
|
|
265
|
+
const result = await this.git.allocateWorktree({ requestId: state.request.id, root: repo.root, task, attempt: repo.attempt, intent,
|
|
266
|
+
onPrepared: async (worktree) => { intent.worktree = worktree; await this.save(state); } }, context(signal));
|
|
267
|
+
intent.status = result.outcome === "owned" ? "owned" : result.outcome;
|
|
268
|
+
if (result.outcome !== "owned") {
|
|
269
|
+
intent.failure = result.failure;
|
|
270
|
+
await this.save(state);
|
|
271
|
+
throw new Error(result.failure);
|
|
272
|
+
}
|
|
273
|
+
await this.save(state);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
paths(state, integration) {
|
|
277
|
+
return Object.fromEntries(Object.entries(state.repositories).map(([name, repo]) => {
|
|
278
|
+
const path = integration ? repo.integration?.path : owned(repo.attempt).path;
|
|
279
|
+
if (!path)
|
|
280
|
+
throw new Error(`Missing integration checkout: ${name}.`);
|
|
281
|
+
return [name, path];
|
|
282
|
+
}));
|
|
283
|
+
}
|
|
284
|
+
async work(state, signal) {
|
|
285
|
+
const task = workerTask(state.request), attempt = Object.values(state.repositories)[0].attempt, host = this.options.host(state.policy);
|
|
286
|
+
const paths = this.paths(state, false);
|
|
287
|
+
const goal = `${state.request.goal}\n\nRead-only input copies (never promote these files):\n${JSON.stringify(Object.fromEntries(Object.entries(state.inputs).map(([name, input]) => [name, input.path])))}\n\nCheck repository labels refer to this absolute worktree map:\n${JSON.stringify(paths)}`;
|
|
288
|
+
for (const kind of ["workspace", "worker_tab", "agent"]) {
|
|
289
|
+
const plan = await host.planHostAllocation({ requestId: state.request.id, goal, kind, task, attempt }, context(signal));
|
|
290
|
+
const intent = { ...plan, generation: 1, token: attempt.correlationToken, status: "allocating" };
|
|
291
|
+
attempt.allocations.push(intent);
|
|
292
|
+
await this.save(state);
|
|
293
|
+
if (intent.kind === "worktree")
|
|
294
|
+
throw new Error("Invalid host plan.");
|
|
295
|
+
const result = await host.allocateHost({ requestId: state.request.id, intent, task, attempt,
|
|
296
|
+
acquireLaunch: () => this.options.coordinator.acquireLaunch(task.role, task.modelClass, context(signal)) }, context(signal));
|
|
297
|
+
intent.status = result.outcome === "owned" ? "owned" : result.outcome;
|
|
298
|
+
if (result.outcome === "owned") {
|
|
299
|
+
if (intent.kind === "workspace" && result.kind === "workspace")
|
|
300
|
+
Object.assign(intent, { workspaceId: result.workspaceId, rootTabId: result.rootTabId, rootPaneId: result.rootPaneId });
|
|
301
|
+
if (intent.kind === "worker_tab" && result.kind === "worker_tab")
|
|
302
|
+
Object.assign(intent, { tabId: result.tabId, paneId: result.paneId });
|
|
303
|
+
}
|
|
304
|
+
else
|
|
305
|
+
intent.failure = result.failure;
|
|
306
|
+
await this.save(state);
|
|
307
|
+
if (result.outcome !== "owned")
|
|
308
|
+
throw new Error(result.failure);
|
|
309
|
+
}
|
|
310
|
+
const agent = attempt.allocations.find((item) => item.kind === "agent");
|
|
311
|
+
if (!agent || agent.kind !== "agent")
|
|
312
|
+
throw new Error("Worker identity is missing.");
|
|
313
|
+
const preCandidate = branchBase(Object.values(state.repositories)[0]);
|
|
314
|
+
attempt.prompts.push({ kind: "initial", status: "submitting", preCandidate, at: Date.now() });
|
|
315
|
+
state.status = "working";
|
|
316
|
+
await this.save(state);
|
|
317
|
+
const observation = new DeadlineScope(this.options.coordinator.now() + state.policy.childMaxMs, () => this.options.coordinator.now(), signal);
|
|
318
|
+
const prompt = attempt.prompts[0];
|
|
319
|
+
try {
|
|
320
|
+
const result = await observation.call((operation) => host.runWorker({ goal, contexts: [], task, attempt, workerId: agent.agentName,
|
|
321
|
+
kind: "initial", preCandidate, workspacePaths: paths, idleMs: state.policy.childIdleMs }, operation));
|
|
322
|
+
if (result.outcome !== "candidate") {
|
|
323
|
+
prompt.status = result.outcome === "not_prompted" ? "not_sent" : result.outcome === "unknown" || result.outcome === "interrupted" ? "ambiguous" : "settled";
|
|
324
|
+
throw new Error(result.diagnostic ?? "Workspace worker did not finish with an exact candidate.");
|
|
325
|
+
}
|
|
326
|
+
prompt.status = "settled";
|
|
327
|
+
prompt.candidate = result.candidate;
|
|
328
|
+
await this.save(state);
|
|
329
|
+
}
|
|
330
|
+
catch (error) {
|
|
331
|
+
if (prompt.status === "submitting")
|
|
332
|
+
prompt.status = "ambiguous";
|
|
333
|
+
prompt.failure = diagnostic(error);
|
|
334
|
+
await this.save(state);
|
|
335
|
+
throw error;
|
|
336
|
+
}
|
|
337
|
+
finally {
|
|
338
|
+
observation.close();
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
async inspectWorkers(state, signal) {
|
|
342
|
+
await this.verifyScope(state, signal);
|
|
343
|
+
const result = {};
|
|
344
|
+
for (const [name, repo] of Object.entries(state.repositories)) {
|
|
345
|
+
const inspection = await this.git.inspectInFlightTaskCandidate({ root: repo.root, task: workerTask(state.request), attempt: repo.attempt }, context(signal));
|
|
346
|
+
if (!inspection.valid || !inspection.clean)
|
|
347
|
+
throw new Error(`Repository ${name} has no exact clean owned candidate.`);
|
|
348
|
+
const candidate = inspection.candidate;
|
|
349
|
+
await this.integration.inspectWorker(repo.root, owned(repo.attempt), candidate, signal);
|
|
350
|
+
if (state.candidates && !sameIdentity(candidate, state.candidates[name]))
|
|
351
|
+
throw new Error(`Sealed worker candidate changed: ${name}.`);
|
|
352
|
+
result[name] = candidate;
|
|
353
|
+
repo.attempt.candidate = candidate;
|
|
354
|
+
}
|
|
355
|
+
return result;
|
|
356
|
+
}
|
|
357
|
+
async stop(state) {
|
|
358
|
+
const primary = Object.values(state.repositories)[0];
|
|
359
|
+
const attempt = primary.attempt;
|
|
360
|
+
if (attempt.termination?.status === "terminated")
|
|
361
|
+
return;
|
|
362
|
+
const agent = attempt.allocations.find((item) => item.kind === "agent");
|
|
363
|
+
if (!agent)
|
|
364
|
+
return;
|
|
365
|
+
if (agent.kind !== "agent" || agent.status !== "owned")
|
|
366
|
+
throw new Error("Agent allocation is uncertain; manual host reconciliation is required. All worktrees are retained.");
|
|
367
|
+
const host = this.options.host(state.policy), input = { task: workerTask(state.request), attempt, workerId: agent.agentName, candidate: attempt.candidate ?? branchBase(Object.values(state.repositories)[0]) };
|
|
368
|
+
attempt.termination = { status: "terminating", workerId: agent.agentName, candidate: input.candidate };
|
|
369
|
+
await this.save(state);
|
|
370
|
+
let result = await host.reconcileWorkerTermination(input, safeContext());
|
|
371
|
+
if (result.outcome === "active")
|
|
372
|
+
result = await host.terminateWorker(input, safeContext());
|
|
373
|
+
attempt.termination.status = result.outcome === "terminated" ? "terminated" : "unknown";
|
|
374
|
+
await this.save(state);
|
|
375
|
+
if (result.outcome !== "terminated")
|
|
376
|
+
throw new Error(result.outcome === "unknown" ? result.failure : "Worker termination is not proved.");
|
|
377
|
+
}
|
|
378
|
+
async inspectTips(state, signal) {
|
|
379
|
+
await this.verifyScope(state, signal);
|
|
380
|
+
const result = {};
|
|
381
|
+
for (const [name, repo] of Object.entries(state.repositories)) {
|
|
382
|
+
if (!repo.integration || repo.allocation !== "owned" || !repo.stage || repo.stage === "staging")
|
|
383
|
+
throw new Error(`Repository ${name} is not fully staged.`);
|
|
384
|
+
result[name] = await this.integration.inspectCombined(repo.root, repo.integration, repo.base, repo.receipt ? [repo.receipt] : [], signal);
|
|
385
|
+
}
|
|
386
|
+
if (state.tips && !sameSet(result, state.tips))
|
|
387
|
+
throw new Error("Integration input set changed.");
|
|
388
|
+
return result;
|
|
389
|
+
}
|
|
390
|
+
async checks(state, expected, commands, integration, signal) {
|
|
391
|
+
const inspect = () => integration ? this.inspectTips(state, signal) : this.inspectWorkers(state, signal);
|
|
392
|
+
const before = await inspect();
|
|
393
|
+
if (!sameSet(before, expected))
|
|
394
|
+
throw new Error("Complete check input set changed before validation.");
|
|
395
|
+
const results = [], paths = this.paths(state, integration);
|
|
396
|
+
for (const check of commands) {
|
|
397
|
+
for (const [name, path] of Object.entries(paths)) {
|
|
398
|
+
const baseline = state.repositories[name].testScript;
|
|
399
|
+
if (baseline !== undefined && suite(await readFile(join(path, "package.json"), "utf8")) !== baseline)
|
|
400
|
+
throw new Error(`Canonical test script changed: ${name}.`);
|
|
401
|
+
}
|
|
402
|
+
const result = await (this.options.execute ?? runProcess)(check.command, check.args, { cwd: paths[check.repository], signal, timeoutMs: state.policy.childMaxMs,
|
|
403
|
+
env: { PI_SUBAGENT_REPOSITORIES: JSON.stringify(paths), PI_SUBAGENT_INPUTS: JSON.stringify(Object.fromEntries(Object.entries(state.inputs).map(([name, input]) => [name, input.path]))) } });
|
|
404
|
+
results.push({ ...check, code: result.code, killed: result.killed, stdout: utf8Prefix(result.stdout, 8192), stderr: utf8Prefix(result.stderr, 8192) });
|
|
405
|
+
if (result.code !== 0 || result.killed || !sameSet(await inspect(), before))
|
|
406
|
+
break;
|
|
407
|
+
}
|
|
408
|
+
return { before, after: await inspect(), results };
|
|
409
|
+
}
|
|
410
|
+
async action(value, cwd, signal = new AbortController().signal) {
|
|
411
|
+
if (!Check(WorkspaceActionSchema, value))
|
|
412
|
+
throw new Error("Invalid workspace action.");
|
|
413
|
+
const action = value, root = await realpath(cwd);
|
|
414
|
+
if (["status", "abort", "reconcile", "cleanup"].includes(action.action) ? action.expected !== undefined : action.expected === undefined)
|
|
415
|
+
throw new Error("stage, validate, and promote require the complete expected identity set; other actions do not accept it.");
|
|
416
|
+
if (action.action === "status")
|
|
417
|
+
return await this.status(root, action.id);
|
|
418
|
+
if (action.action === "abort")
|
|
419
|
+
this.active.get(`${root}\0${action.id}`)?.abort();
|
|
420
|
+
const before = await this.status(root, action.id);
|
|
421
|
+
const scope = await resolveWorkspaceScope(root, before.request.repositories, signal);
|
|
422
|
+
return await this.locked(scope, action.id, async () => {
|
|
423
|
+
const state = await this.status(root, action.id);
|
|
424
|
+
try {
|
|
425
|
+
if (action.action === "abort") {
|
|
426
|
+
await this.stop(state);
|
|
427
|
+
state.status = "aborted";
|
|
428
|
+
}
|
|
429
|
+
else if (action.action === "cleanup")
|
|
430
|
+
await this.cleanup(state, signal);
|
|
431
|
+
else {
|
|
432
|
+
await this.verifyScope(state, signal);
|
|
433
|
+
if (action.action === "stage")
|
|
434
|
+
await this.stage(state, action.expected, signal);
|
|
435
|
+
else if (action.action === "validate") {
|
|
436
|
+
if (state.status !== "staged" || !state.tips || !sameSet(state.tips, action.expected))
|
|
437
|
+
throw new Error("Validation requires the exact fully staged set.");
|
|
438
|
+
state.status = "validating";
|
|
439
|
+
await this.save(state);
|
|
440
|
+
state.final = await this.checks(state, state.tips, state.request.finalChecks, true, signal);
|
|
441
|
+
if (!passes(state.final, state.request.finalChecks, state.tips))
|
|
442
|
+
throw new Error("Combined workspace checks failed.");
|
|
443
|
+
state.status = "validated";
|
|
444
|
+
}
|
|
445
|
+
else if (action.action === "promote")
|
|
446
|
+
await this.promote(state, action.expected, signal);
|
|
447
|
+
else if (action.action === "reconcile")
|
|
448
|
+
await this.reconcile(state, signal);
|
|
449
|
+
}
|
|
450
|
+
delete state.failure;
|
|
451
|
+
}
|
|
452
|
+
catch (error) {
|
|
453
|
+
state.failure = diagnostic(error);
|
|
454
|
+
if (action.action !== "cleanup") {
|
|
455
|
+
if (Object.values(state.repositories).some((repo) => repo.promotion))
|
|
456
|
+
state.status = "partial";
|
|
457
|
+
else if (!["ready", "validated", "staged", "aborted", "cleaned"].includes(state.status))
|
|
458
|
+
state.status = "attention";
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
await this.save(state);
|
|
462
|
+
return state;
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
async stage(state, expected, signal) {
|
|
466
|
+
if (state.status !== "ready" || !state.candidates || !sameSet(expected, state.candidates)
|
|
467
|
+
|| !passes(state.preliminary, state.request.tasks[0].checks, state.candidates))
|
|
468
|
+
throw new Error("Stage requires the exact complete checked candidate set.");
|
|
469
|
+
await this.stop(state);
|
|
470
|
+
await this.inspectWorkers(state, signal);
|
|
471
|
+
// Every Main target is inspected before the first allocation or merge.
|
|
472
|
+
await this.preflightMain(state, false, signal);
|
|
473
|
+
state.status = "staging";
|
|
474
|
+
await this.save(state);
|
|
475
|
+
for (const [name, repo] of Object.entries(state.repositories)) {
|
|
476
|
+
repo.allocation = "allocating";
|
|
477
|
+
await this.save(state);
|
|
478
|
+
const allocation = await this.integration.allocate(repo.root, `workspace-${state.request.id}-${randomBytes(12).toString("hex")}`, repo.base, async (worktree) => { repo.integration = worktree; await this.save(state); }, signal, [state.request.id, name, "integration"]);
|
|
479
|
+
if (allocation.outcome !== "ready")
|
|
480
|
+
throw new Error(allocation.failure);
|
|
481
|
+
repo.allocation = "owned";
|
|
482
|
+
await this.save(state);
|
|
483
|
+
if (state.candidates[name].head === repo.base.head) {
|
|
484
|
+
repo.stage = "unchanged";
|
|
485
|
+
await this.save(state);
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
repo.stage = "staging";
|
|
489
|
+
await this.save(state);
|
|
490
|
+
const result = await this.integration.stage(repo.root, repo.integration, repo.base, [], owned(repo.attempt), state.candidates[name], signal);
|
|
491
|
+
if (result.outcome !== "ready")
|
|
492
|
+
throw new Error(result.failure);
|
|
493
|
+
repo.receipt = result.value;
|
|
494
|
+
repo.stage = "staged";
|
|
495
|
+
await this.save(state);
|
|
496
|
+
}
|
|
497
|
+
state.tips = await this.inspectTips(state, signal);
|
|
498
|
+
state.status = "staged";
|
|
499
|
+
}
|
|
500
|
+
async preflightMain(state, promotion, signal) {
|
|
501
|
+
await this.verifyScope(state, signal);
|
|
502
|
+
for (const [name, repo] of Object.entries(state.repositories)) {
|
|
503
|
+
const expected = promotion && repo.promotion?.status === "promoted" ? repo.promotion.mainAfter : repo.base;
|
|
504
|
+
if (!sameIdentity(await this.git.inspectMain({ root: repo.root }, context(signal)), expected))
|
|
505
|
+
throw new Error(`Main target ${name} is dirty or changed; no later target will be promoted.`);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
async promote(state, expected, signal) {
|
|
509
|
+
if (!["validated", "partial"].includes(state.status) || !state.tips || !sameSet(state.tips, expected) || !passes(state.final, state.request.finalChecks, state.tips))
|
|
510
|
+
throw new Error("Promotion requires the exact complete passing final input set.");
|
|
511
|
+
if (Object.values(state.repositories).some((repo) => repo.promotion?.status === "promoting"))
|
|
512
|
+
throw new Error("Reconcile the interrupted per-repository promotion intent before continuing.");
|
|
513
|
+
await this.stop(state);
|
|
514
|
+
await this.inspectWorkers(state, signal);
|
|
515
|
+
await this.inspectTips(state, signal);
|
|
516
|
+
await this.preflightMain(state, true, signal);
|
|
517
|
+
for (const [name, repo] of Object.entries(state.repositories))
|
|
518
|
+
repo.promotion ??= { status: "pending", expected: repo.base, tip: state.tips[name] };
|
|
519
|
+
state.status = "promoting";
|
|
520
|
+
await this.save(state);
|
|
521
|
+
for (const [name, repo] of Object.entries(state.repositories)) {
|
|
522
|
+
if (repo.promotion.status === "promoted")
|
|
523
|
+
continue;
|
|
524
|
+
// Recheck all targets between serial mutations as well as before the first one.
|
|
525
|
+
await this.preflightMain(state, true, signal);
|
|
526
|
+
await this.inspectTips(state, signal);
|
|
527
|
+
repo.promotion.status = "promoting";
|
|
528
|
+
await this.save(state);
|
|
529
|
+
let main;
|
|
530
|
+
if (repo.stage === "unchanged")
|
|
531
|
+
main = await this.git.inspectMain({ root: repo.root }, context(signal));
|
|
532
|
+
else {
|
|
533
|
+
const tip = state.tips[name];
|
|
534
|
+
const result = await this.integration.promote({ root: repo.root, integration: repo.integration, base: repo.base, stages: [repo.receipt],
|
|
535
|
+
checks: { phase: "final", candidate: tip, identityAfter: tip, results: state.final.results.map(({ repository: _repository, ...result }) => result), passed: true, at: Date.now() },
|
|
536
|
+
commands: state.request.finalChecks.map(({ repository: _repository, ...check }) => check) }, signal);
|
|
537
|
+
if (result.outcome !== "ready")
|
|
538
|
+
throw new Error(`${name}: ${result.failure}. Earlier promotion receipts remain valid; no rollback was attempted.`);
|
|
539
|
+
main = result.value;
|
|
540
|
+
}
|
|
541
|
+
repo.promotion = { ...repo.promotion, status: "promoted", mainAfter: main };
|
|
542
|
+
await this.save(state);
|
|
543
|
+
}
|
|
544
|
+
await this.preflightMain(state, true, signal);
|
|
545
|
+
state.status = "promoted";
|
|
546
|
+
}
|
|
547
|
+
async reconcile(state, signal) {
|
|
548
|
+
await this.stop(state);
|
|
549
|
+
if (Object.values(state.repositories).some((repo) => repo.promotion)) {
|
|
550
|
+
for (const repo of Object.values(state.repositories)) {
|
|
551
|
+
if (repo.promotion?.status !== "promoting")
|
|
552
|
+
continue;
|
|
553
|
+
const actual = await this.git.inspectMain({ root: repo.root }, context(signal));
|
|
554
|
+
if (sameIdentity(actual, { ...repo.promotion.tip, branch: repo.base.branch }))
|
|
555
|
+
repo.promotion = { ...repo.promotion, status: "promoted", mainAfter: actual };
|
|
556
|
+
else if (sameIdentity(actual, repo.base))
|
|
557
|
+
repo.promotion.status = "pending";
|
|
558
|
+
else
|
|
559
|
+
throw new Error("Main differs from both saved promotion endpoints; manual reconciliation is required. Nothing was rolled back.");
|
|
560
|
+
await this.save(state);
|
|
561
|
+
}
|
|
562
|
+
await this.inspectTips(state, signal);
|
|
563
|
+
await this.preflightMain(state, true, signal);
|
|
564
|
+
state.status = Object.values(state.repositories).every((repo) => repo.promotion?.status === "promoted") ? "promoted" : "partial";
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
if (!state.candidates)
|
|
568
|
+
throw new Error("Interrupted allocation or worker execution requires manual inspection. Prompts and allocations are never replayed.");
|
|
569
|
+
await this.inspectWorkers(state, signal);
|
|
570
|
+
for (const [name, repo] of Object.entries(state.repositories)) {
|
|
571
|
+
if (repo.allocation === "allocating" || !repo.integration)
|
|
572
|
+
throw new Error("Incomplete integration allocation is retained for manual reconciliation; it is not adopted or replayed.");
|
|
573
|
+
if (repo.stage === "staging") {
|
|
574
|
+
const result = await this.integration.reconcileStage(repo.root, repo.integration, repo.base, [], owned(repo.attempt), state.candidates[name], signal);
|
|
575
|
+
if (result.outcome !== "ready" || result.value === "not_started")
|
|
576
|
+
throw new Error(result.outcome === "ready" ? "Interrupted merge did not start; its intent is retained without replay." : result.failure);
|
|
577
|
+
repo.receipt = result.value;
|
|
578
|
+
repo.stage = "staged";
|
|
579
|
+
await this.save(state);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
state.tips = await this.inspectTips(state, signal);
|
|
583
|
+
state.status = passes(state.final, state.request.finalChecks, state.tips) ? "validated" : "staged";
|
|
584
|
+
}
|
|
585
|
+
async cleanup(state, signal) {
|
|
586
|
+
if (state.status !== "promoted" && state.status !== "cleaned")
|
|
587
|
+
throw new Error("Workspace cleanup requires all repositories to be promoted. Failed and aborted work stays retained for manual inspection.");
|
|
588
|
+
await this.stop(state);
|
|
589
|
+
await this.preflightMain(state, true, signal);
|
|
590
|
+
const first = Object.values(state.repositories)[0], host = this.options.host(state.policy);
|
|
591
|
+
first.cleanup ??= [];
|
|
592
|
+
for (const kind of ["worker_tab", "workspace"]) {
|
|
593
|
+
const step = first.attempt.cleanup.find((item) => item.kind === kind);
|
|
594
|
+
if (step.status === "completed")
|
|
595
|
+
continue;
|
|
596
|
+
step.status = "running";
|
|
597
|
+
await this.save(state);
|
|
598
|
+
const result = await host.cleanupHost({ requestId: state.request.id, kind, task: workerTask(state.request), attempt: first.attempt }, context(signal));
|
|
599
|
+
if (result.outcome === "blocked")
|
|
600
|
+
throw new Error(result.failure);
|
|
601
|
+
step.status = "completed";
|
|
602
|
+
if (!first.cleanup.includes(kind))
|
|
603
|
+
first.cleanup.push(kind);
|
|
604
|
+
await this.save(state);
|
|
605
|
+
}
|
|
606
|
+
for (const [name, repo] of Object.entries(state.repositories)) {
|
|
607
|
+
repo.cleanup ??= [];
|
|
608
|
+
for (const [label, info, expected, kind] of [
|
|
609
|
+
["worker", owned(repo.attempt), state.candidates[name], "worktree"], ["worker_branch", owned(repo.attempt), state.candidates[name], "branch"],
|
|
610
|
+
["integration", repo.integration, state.tips[name], "worktree"], ["integration_branch", repo.integration, state.tips[name], "branch"],
|
|
611
|
+
]) {
|
|
612
|
+
if (repo.cleanup.includes(label))
|
|
613
|
+
continue;
|
|
614
|
+
const result = await this.integration.release(repo.root, info, expected, kind, signal);
|
|
615
|
+
if (result.outcome !== "ready")
|
|
616
|
+
throw new Error(result.failure);
|
|
617
|
+
repo.cleanup.push(label);
|
|
618
|
+
await this.save(state);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
state.status = "cleaned";
|
|
622
|
+
}
|
|
623
|
+
}
|
package/docs/orchestration.md
CHANGED
|
@@ -196,6 +196,10 @@ Recorded time comes only from the `durationMs` of the latest matched tool result
|
|
|
196
196
|
|
|
197
197
|
Activity uses the existing session sample and file-size cache. The extension ignores a partial trailing JSONL entry until it is complete. For display, the extension removes terminal control characters from tool names. Narrow rows remove activity before other metrics, so worker identity and failure state stay visible. Activity and time are display information, not proof of task completion, worker ownership, or a timeout.
|
|
198
198
|
|
|
199
|
+
## Explicit workspace selection
|
|
200
|
+
|
|
201
|
+
The optional top-level `repositories` map selects independent repositories in a non-Git workspace. See [Checked workspace tasks](./workspace.md) for complete-set identity, one-worker allocation, input copies, direct reporting, and serial promotion recovery. This path uses `subagent_workspace`; the scalar tools below keep their existing one-repository contract.
|
|
202
|
+
|
|
199
203
|
## Isolated contract
|
|
200
204
|
|
|
201
205
|
An isolated request has one durable ID, one goal, and 1 to 8 typed tasks.
|