master-orchestrator 0.0.0-stage → 0.2.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/CHANGELOG.md +19 -0
- package/LICENSE +21 -0
- package/README.md +176 -2
- package/package.json +56 -4
- package/src/adapters/agy.ts +285 -0
- package/src/adapters/claude.ts +317 -0
- package/src/adapters/codex.ts +162 -0
- package/src/adapters/common.ts +211 -0
- package/src/adapters/dsh.ts +356 -0
- package/src/adapters/fake-agent.mjs +50 -0
- package/src/adapters/fake.ts +88 -0
- package/src/adapters/gemini.ts +239 -0
- package/src/adapters/grok.ts +328 -0
- package/src/adapters/omp.ts +119 -0
- package/src/adapters/opencode.ts +228 -0
- package/src/adapters/pi.ts +284 -0
- package/src/adapters/registry.ts +27 -0
- package/src/adapters/types.ts +201 -0
- package/src/config/load.ts +290 -0
- package/src/config/profiles.ts +64 -0
- package/src/config/schema.ts +158 -0
- package/src/config/write.ts +83 -0
- package/src/engine/artifacts.ts +145 -0
- package/src/engine/baseline.ts +132 -0
- package/src/engine/execute.ts +437 -0
- package/src/engine/git.ts +32 -0
- package/src/engine/hostenv.ts +54 -0
- package/src/engine/registry.ts +280 -0
- package/src/engine/runner.ts +249 -0
- package/src/engine/types.ts +55 -0
- package/src/engine/verify.ts +100 -0
- package/src/index.ts +602 -0
- package/src/prompts/envelope.ts +29 -0
- package/src/prompts/templates.ts +389 -0
- package/src/ui/configure.ts +174 -0
- package/src/ui/dialogs.ts +88 -0
- package/src/ui/doctor.ts +120 -0
- package/src/ui/format.ts +94 -0
- package/src/ui/host.ts +100 -0
- package/src/ui/render.ts +86 -0
- package/src/ui/widget.ts +70 -0
- package/src/workflows/budget.ts +66 -0
- package/src/workflows/common.ts +100 -0
- package/src/workflows/debate.ts +488 -0
- package/src/workflows/host.ts +78 -0
- package/src/workflows/plan-exec.ts +807 -0
- package/src/workflows/plan.ts +407 -0
- package/src/workflows/planfile.ts +380 -0
- package/src/workflows/planstate.ts +229 -0
- package/src/workflows/verdict.ts +74 -0
|
@@ -0,0 +1,807 @@
|
|
|
1
|
+
import { writeFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { clip } from "../adapters/common.ts";
|
|
4
|
+
import type { RoleName } from "../config/schema.ts";
|
|
5
|
+
import { createWorkflowDir, lockPath, runsRoot } from "../engine/artifacts.ts";
|
|
6
|
+
import { diffBaseline, hashWorkspaceFile, takeBaseline, type Baseline } from "../engine/baseline.ts";
|
|
7
|
+
import { git } from "../engine/git.ts";
|
|
8
|
+
import { acquireWriteLock, type LockHandle } from "../engine/registry.ts";
|
|
9
|
+
import type { RunResult } from "../engine/types.ts";
|
|
10
|
+
import { inScope } from "../engine/verify.ts";
|
|
11
|
+
import { fitParts, resultPath } from "./budget.ts";
|
|
12
|
+
import { ensureAlive, errorText, formatList, resolveRole } from "./common.ts";
|
|
13
|
+
import { MESSAGE_TYPES, WorkflowStopped, type WorkflowDeps } from "./host.ts";
|
|
14
|
+
import { approvePlan, formatFindings, parseFindings } from "./plan.ts";
|
|
15
|
+
import { blockScope, parsePlan, serializePlan, stepOrder, type PlanBlock, type PlanDocument, type PlanStep } from "./planfile.ts";
|
|
16
|
+
import {
|
|
17
|
+
blockState,
|
|
18
|
+
listPlans,
|
|
19
|
+
loadPlan,
|
|
20
|
+
planPaths,
|
|
21
|
+
plansPrefix,
|
|
22
|
+
planSummary,
|
|
23
|
+
saveState,
|
|
24
|
+
savePlanFile,
|
|
25
|
+
stepState,
|
|
26
|
+
syncState,
|
|
27
|
+
type BlockState,
|
|
28
|
+
type Finding,
|
|
29
|
+
type PlanState,
|
|
30
|
+
type StepAttempt,
|
|
31
|
+
type StepState,
|
|
32
|
+
} from "./planstate.ts";
|
|
33
|
+
|
|
34
|
+
type BlockWithSteps = BlockState & { steps: StepState[] };
|
|
35
|
+
type Issue = { kind: "step"; stepId: string; reason: string } | { kind: "block"; reason: string };
|
|
36
|
+
type Choice = "retry" | "skip" | "edit" | "abort" | "pause";
|
|
37
|
+
|
|
38
|
+
interface ExecContext {
|
|
39
|
+
deps: WorkflowDeps;
|
|
40
|
+
planId: string;
|
|
41
|
+
plan: PlanDocument;
|
|
42
|
+
state: PlanState;
|
|
43
|
+
paths: ReturnType<typeof planPaths>;
|
|
44
|
+
lock: LockHandle;
|
|
45
|
+
signal: AbortSignal;
|
|
46
|
+
artifactsDir: string;
|
|
47
|
+
roles: Map<string, string[]>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const SUMMARY_CHARS = 4000;
|
|
51
|
+
|
|
52
|
+
/** Runs (or resumes) the execution of an approved plan (sections 11.3 to 11.7). Returns the final state. */
|
|
53
|
+
export async function executePlan(deps: WorkflowDeps, planId: string, options: { resume?: boolean } = {}): Promise<PlanState | undefined> {
|
|
54
|
+
const { host } = deps;
|
|
55
|
+
const stored = await loadPlan(host.workspace, deps.configDirName, planId);
|
|
56
|
+
if (!stored) throw new Error(`Plan ${planId} was not found in ${deps.configDirName}/master-orchestrator/plans/.`);
|
|
57
|
+
if (!stored.plan) throw new Error(`Plan ${planId} does not validate:\n${stored.errors.map((error) => `- ${error}`).join("\n")}`);
|
|
58
|
+
if (!stored.state) throw new Error(`Plan ${planId} has no state file; approve it with /plan resume ${planId}.`);
|
|
59
|
+
const plan = stored.plan;
|
|
60
|
+
let state = syncState(stored.state, plan);
|
|
61
|
+
if (!["approved", "executing", "paused"].includes(state.status)) throw new Error(`Plan ${planId} is ${state.status}; only an approved or paused plan can execute.`);
|
|
62
|
+
const paths = planPaths(host.workspace, deps.configDirName, planId);
|
|
63
|
+
|
|
64
|
+
// Preconditions (11.3).
|
|
65
|
+
const baseline = await takeBaseline(host.workspace);
|
|
66
|
+
if (!baseline.git) throw new Error(`Plan execution needs a Git workspace: ${baseline.reason ?? "no Git baseline"}.`);
|
|
67
|
+
const prefix = plansPrefix(deps.configDirName);
|
|
68
|
+
const pending = Object.keys(baseline.entries).filter((path) => !path.startsWith(prefix));
|
|
69
|
+
if (state.status === "approved") {
|
|
70
|
+
if (pending.length > 0) {
|
|
71
|
+
if (deps.getConfig().planning.execution.requireCleanTree) {
|
|
72
|
+
throw new Error(`The working tree is not clean (planning.execution.requireCleanTree):\n${formatList(pending.slice(0, 30))}`);
|
|
73
|
+
}
|
|
74
|
+
if (!host.hasUI) throw new Error("The working tree has pending changes and there is no UI to confirm them.");
|
|
75
|
+
const ok = await host.confirm(`Start plan ${planId} with pending changes?`, `These files have changes that predate the plan:\n${pending.slice(0, 30).join("\n")}`);
|
|
76
|
+
if (!ok) return undefined;
|
|
77
|
+
}
|
|
78
|
+
state.startedClean = pending.length === 0;
|
|
79
|
+
} else if (options.resume) {
|
|
80
|
+
const mismatch = await acceptedMismatch(host.workspace, state);
|
|
81
|
+
if (mismatch.length > 0) {
|
|
82
|
+
const text = `The workspace differs from the state recorded at the last accepted block:\n${mismatch.slice(0, 30).join("\n")}`;
|
|
83
|
+
if (!host.hasUI) throw new Error(`${text}\nResume in an interactive session to confirm.`);
|
|
84
|
+
if (!(await host.confirm(`Resume plan ${planId} anyway?`, text))) return undefined;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const lock = await acquireWriteLock(lockPath(deps.agentDir, host.workspace), {
|
|
89
|
+
instanceId: deps.instanceId,
|
|
90
|
+
sessionId: deps.sessionId(),
|
|
91
|
+
owner: `plan:${planId}`,
|
|
92
|
+
workspace: host.workspace,
|
|
93
|
+
});
|
|
94
|
+
const controller = new AbortController();
|
|
95
|
+
deps.registry.addWorkflow({ id: planId, kind: "plan", header: "plan · executing", controller });
|
|
96
|
+
const ctx: ExecContext = {
|
|
97
|
+
deps,
|
|
98
|
+
planId,
|
|
99
|
+
plan,
|
|
100
|
+
state,
|
|
101
|
+
paths,
|
|
102
|
+
lock,
|
|
103
|
+
signal: controller.signal,
|
|
104
|
+
artifactsDir: await createWorkflowDir(deps.agentDir, host.workspace, planId),
|
|
105
|
+
roles: new Map(),
|
|
106
|
+
};
|
|
107
|
+
host.setVerdictTool(true);
|
|
108
|
+
try {
|
|
109
|
+
// A step that was running when the session ended is interrupted (11.7).
|
|
110
|
+
for (const block of state.blocks) {
|
|
111
|
+
for (const step of block.steps) if (step.status === "running") step.status = "interrupted";
|
|
112
|
+
if ((block.status === "running" || block.status === "in_review") && block.steps.every((step) => step.status === "done" || step.status === "skipped")) {
|
|
113
|
+
block.resumeAt = "review";
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
state.status = "executing";
|
|
117
|
+
state.pauseReason = undefined;
|
|
118
|
+
await saveState(paths.state, state, options.resume ? "resumed" : "execution started");
|
|
119
|
+
await mainLoop(ctx);
|
|
120
|
+
state = ctx.state;
|
|
121
|
+
} catch (error) {
|
|
122
|
+
state = ctx.state;
|
|
123
|
+
const entry = deps.registry.listWorkflows().find((item) => item.id === planId);
|
|
124
|
+
for (const block of state.blocks) for (const step of block.steps) if (step.status === "running") step.status = "interrupted";
|
|
125
|
+
if (entry?.stopIntent === "abort") {
|
|
126
|
+
state.status = "aborted";
|
|
127
|
+
await saveState(paths.state, state, "aborted by the user");
|
|
128
|
+
if (host.alive()) host.notify(`Plan ${planId} aborted.`, "warning");
|
|
129
|
+
} else if (error instanceof WorkflowStopped || ctx.signal.aborted) {
|
|
130
|
+
state.status = "paused";
|
|
131
|
+
state.pauseReason = "stopped";
|
|
132
|
+
for (const block of state.blocks) if (block.status === "running" || block.status === "in_review") block.status = "paused";
|
|
133
|
+
await saveState(paths.state, state, "stopped");
|
|
134
|
+
if (host.alive()) host.notify(`Plan ${planId} stopped. Resume it with /plan resume ${planId}.`, "warning");
|
|
135
|
+
} else {
|
|
136
|
+
state.status = "paused";
|
|
137
|
+
state.pauseReason = errorText(error);
|
|
138
|
+
await saveState(paths.state, state, `paused on error: ${clip(errorText(error), 200)}`);
|
|
139
|
+
if (host.alive()) {
|
|
140
|
+
host.sendMessage(
|
|
141
|
+
{ customType: MESSAGE_TYPES.plan, content: `Plan ${planId} paused on an error: ${errorText(error)}\nResume it with /plan resume ${planId}.`, details: { planId, status: "paused" }, display: true },
|
|
142
|
+
false,
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
} finally {
|
|
147
|
+
lock.release();
|
|
148
|
+
deps.verdicts.cancel();
|
|
149
|
+
deps.registry.removeWorkflow(planId);
|
|
150
|
+
if (host.alive()) host.setVerdictTool(false);
|
|
151
|
+
}
|
|
152
|
+
return state;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async function mainLoop(ctx: ExecContext): Promise<void> {
|
|
156
|
+
const { deps } = ctx;
|
|
157
|
+
restart: for (;;) {
|
|
158
|
+
const blocks = ctx.plan.blocks;
|
|
159
|
+
for (const [index, block] of blocks.entries()) {
|
|
160
|
+
for (;;) {
|
|
161
|
+
checkStop(ctx);
|
|
162
|
+
const bs = blockState(ctx.state, block.id) as BlockWithSteps;
|
|
163
|
+
if (bs.status === "accepted" || bs.status === "skipped") break;
|
|
164
|
+
deps.registry.setWorkflowHeader(ctx.planId, `plan block ${index + 1}/${blocks.length}`);
|
|
165
|
+
const issue = findIssue(bs);
|
|
166
|
+
if (issue) {
|
|
167
|
+
const choice = await decide(ctx, block, issue);
|
|
168
|
+
if (choice === "abort") {
|
|
169
|
+
ctx.state.status = "aborted";
|
|
170
|
+
await save(ctx, "aborted by the user");
|
|
171
|
+
deps.host.notify(`Plan ${ctx.planId} aborted.`, "warning");
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (choice === "pause") return pause(ctx, issue.reason);
|
|
175
|
+
if (choice === "edit") {
|
|
176
|
+
if (await editPlan(ctx)) continue restart;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (choice === "skip") {
|
|
180
|
+
if (issue.kind === "step") {
|
|
181
|
+
(stepState(ctx.state, issue.stepId) as StepState).status = "skipped";
|
|
182
|
+
await save(ctx, `step ${issue.stepId} skipped`);
|
|
183
|
+
} else {
|
|
184
|
+
bs.status = "skipped";
|
|
185
|
+
await save(ctx, `block ${block.id} skipped`);
|
|
186
|
+
break;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
// retry: fall through to runBlock, which continues from the failed step or the block's resume point.
|
|
190
|
+
bs.status = "running";
|
|
191
|
+
bs.pauseReason = undefined;
|
|
192
|
+
} else if (bs.status === "pending" && deps.getConfig().planning.execution.mode === "block") {
|
|
193
|
+
const ok = deps.host.hasUI ? await deps.host.confirm(`Start block ${block.id} of plan ${ctx.planId}?`, `${block.title}\n\nAcceptance: ${block.acceptance}`) : false;
|
|
194
|
+
ensureAlive(deps);
|
|
195
|
+
if (!ok) {
|
|
196
|
+
bs.status = "paused";
|
|
197
|
+
bs.pauseReason = "waiting for confirmation to start the block";
|
|
198
|
+
return pause(ctx, bs.pauseReason);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
await runBlock(ctx, block, bs);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
await finish(ctx);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function findIssue(bs: BlockWithSteps): Issue | undefined {
|
|
210
|
+
const step = bs.steps.find((entry) => entry.status === "failed" || entry.status === "interrupted");
|
|
211
|
+
if (step) {
|
|
212
|
+
const last = step.attempts.at(-1);
|
|
213
|
+
return { kind: "step", stepId: step.id, reason: `step ${step.id} ${step.status}${last?.reason ? `: ${last.reason}` : ""}` };
|
|
214
|
+
}
|
|
215
|
+
if (bs.status === "paused") return { kind: "block", reason: bs.pauseReason ?? `block ${bs.id} paused` };
|
|
216
|
+
return undefined;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function decide(ctx: ExecContext, block: PlanBlock, issue: Issue): Promise<Choice> {
|
|
220
|
+
const { host } = ctx.deps;
|
|
221
|
+
if (!host.hasUI) return "pause";
|
|
222
|
+
const options =
|
|
223
|
+
issue.kind === "step"
|
|
224
|
+
? ["Retry the step", "Skip the step", "Edit the plan", "Abort the plan", "Pause (resume later)"]
|
|
225
|
+
: ["Retry the block", "Skip the block", "Edit the plan", "Abort the plan", "Pause (resume later)"];
|
|
226
|
+
let detail = "";
|
|
227
|
+
if (issue.kind === "step") {
|
|
228
|
+
const ss = stepState(ctx.state, issue.stepId);
|
|
229
|
+
if (ss?.baseline) {
|
|
230
|
+
const changes = await diffBaseline(host.workspace, ss.baseline);
|
|
231
|
+
const files = filterPlans(ctx, changes.changed);
|
|
232
|
+
detail = files.length > 0 ? ` · partial changes: ${files.slice(0, 8).join(", ")}${files.length > 8 ? ", …" : ""}` : " · no partial changes";
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
const choice = await host.select(`Plan ${ctx.planId}, block ${block.id}: ${issue.reason}${detail}`, options);
|
|
236
|
+
ensureAlive(ctx.deps);
|
|
237
|
+
if (!choice) return "pause";
|
|
238
|
+
if (choice.startsWith("Retry")) return "retry";
|
|
239
|
+
if (choice.startsWith("Skip")) return "skip";
|
|
240
|
+
if (choice.startsWith("Edit")) return "edit";
|
|
241
|
+
if (choice.startsWith("Abort")) return "abort";
|
|
242
|
+
return "pause";
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function pause(ctx: ExecContext, reason: string): Promise<void> {
|
|
246
|
+
ctx.state.status = "paused";
|
|
247
|
+
ctx.state.pauseReason = reason;
|
|
248
|
+
await save(ctx, `paused: ${clip(reason, 200)}`);
|
|
249
|
+
ensureAlive(ctx.deps);
|
|
250
|
+
ctx.deps.host.sendMessage(
|
|
251
|
+
{
|
|
252
|
+
customType: MESSAGE_TYPES.plan,
|
|
253
|
+
content: `Plan ${ctx.planId} paused: ${reason}\n\n${planSummary(ctx.plan, ctx.state)}\n\nResume it with /plan resume ${ctx.planId}.`,
|
|
254
|
+
details: { planId: ctx.planId, status: "paused", reason },
|
|
255
|
+
display: true,
|
|
256
|
+
},
|
|
257
|
+
false,
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async function editPlan(ctx: ExecContext): Promise<boolean> {
|
|
262
|
+
const { host } = ctx.deps;
|
|
263
|
+
let text = serializePlan(ctx.plan);
|
|
264
|
+
for (;;) {
|
|
265
|
+
const edited = await host.editor(`Edit plan ${ctx.planId}`, text);
|
|
266
|
+
ensureAlive(ctx.deps);
|
|
267
|
+
if (edited === undefined) return false;
|
|
268
|
+
const parsed = parsePlan(edited);
|
|
269
|
+
if (parsed.plan && parsed.plan.id !== ctx.planId) parsed.errors.push(`front matter: id must stay "${ctx.planId}"`);
|
|
270
|
+
if (parsed.plan && parsed.errors.length === 0) {
|
|
271
|
+
ctx.plan = parsed.plan;
|
|
272
|
+
ctx.state = syncState(ctx.state, parsed.plan);
|
|
273
|
+
await savePlanFile(ctx.paths.plan, serializePlan(parsed.plan));
|
|
274
|
+
await save(ctx, "plan edited during execution");
|
|
275
|
+
return true;
|
|
276
|
+
}
|
|
277
|
+
host.notify(`The edited plan does not validate:\n${parsed.errors.map((error) => `- ${error}`).join("\n")}`, "error");
|
|
278
|
+
text = edited;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async function runBlock(ctx: ExecContext, block: PlanBlock, bs: BlockWithSteps): Promise<void> {
|
|
283
|
+
const { deps } = ctx;
|
|
284
|
+
const config = deps.getConfig().planning.execution;
|
|
285
|
+
bs.status = "running";
|
|
286
|
+
if (!bs.baseline) bs.baseline = await takeBaseline(deps.host.workspace);
|
|
287
|
+
await save(ctx, `block ${block.id} running`);
|
|
288
|
+
|
|
289
|
+
for (const step of stepOrder(block)) {
|
|
290
|
+
const ss = stepState(ctx.state, step.id) as StepState;
|
|
291
|
+
if (ss.status === "done" || ss.status === "skipped") continue;
|
|
292
|
+
deps.registry.setWorkflowHeader(ctx.planId, `plan block ${blockNumber(ctx, block)} · step ${step.id}`);
|
|
293
|
+
const result = await runStep(ctx, block, step, ss, bs);
|
|
294
|
+
if (result.status !== "completed") {
|
|
295
|
+
ss.status = result.status === "cancelled" ? "interrupted" : "failed";
|
|
296
|
+
checkStop(ctx);
|
|
297
|
+
await save(ctx, `step ${step.id} ${ss.status}`);
|
|
298
|
+
return; // The main loop asks the user (11.4).
|
|
299
|
+
}
|
|
300
|
+
ss.status = "done";
|
|
301
|
+
await save(ctx, `step ${step.id} done`);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
for (;;) {
|
|
305
|
+
checkStop(ctx);
|
|
306
|
+
if (bs.resumeAt === "fix") {
|
|
307
|
+
bs.resumeAt = undefined;
|
|
308
|
+
const fixed = await fixCycle(ctx, block, bs);
|
|
309
|
+
if (!fixed) return;
|
|
310
|
+
}
|
|
311
|
+
bs.resumeAt = undefined;
|
|
312
|
+
const review = config.review === "per-block" ? await reviewBlock(ctx, block, bs) : undefined;
|
|
313
|
+
const verdict = await requestVerdict(ctx, block, bs, review);
|
|
314
|
+
if (!verdict) {
|
|
315
|
+
bs.status = "paused";
|
|
316
|
+
bs.pauseReason = `no verdict for block ${block.id}`;
|
|
317
|
+
bs.resumeAt = "review";
|
|
318
|
+
bs.verdicts.push({ verdict: "none", feedback: "", at: new Date().toISOString() });
|
|
319
|
+
await save(ctx, bs.pauseReason);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
bs.verdicts.push({ verdict: verdict.verdict, feedback: verdict.feedback, at: new Date().toISOString() });
|
|
323
|
+
if (verdict.verdict === "accepted") {
|
|
324
|
+
await acceptBlock(ctx, block, bs);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
if (verdict.verdict === "needs_fix" && bs.fixAttempts < config.maxFixAttempts) {
|
|
328
|
+
bs.fixAttempts++;
|
|
329
|
+
await save(ctx, `block ${block.id} needs a fix (${bs.fixAttempts}/${config.maxFixAttempts})`);
|
|
330
|
+
const fixed = await fixCycle(ctx, block, bs);
|
|
331
|
+
if (!fixed) return;
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
bs.status = "paused";
|
|
335
|
+
bs.resumeAt = verdict.verdict === "needs_fix" ? "fix" : "review";
|
|
336
|
+
bs.pauseReason =
|
|
337
|
+
verdict.verdict === "blocked"
|
|
338
|
+
? `block ${block.id} blocked: ${clip(verdict.feedback, 300)}`
|
|
339
|
+
: `block ${block.id} still needs a fix after ${bs.fixAttempts} attempt(s): ${clip(verdict.feedback, 300)}`;
|
|
340
|
+
await save(ctx, bs.pauseReason);
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function blockNumber(ctx: ExecContext, block: PlanBlock): string {
|
|
346
|
+
return `${ctx.plan.blocks.indexOf(block) + 1}/${ctx.plan.blocks.length}`;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
async function profilesFor(ctx: ExecContext, step: PlanStep): Promise<string[]> {
|
|
350
|
+
if (step.profile) return [step.profile];
|
|
351
|
+
const role = (step.role ?? "implementer") as RoleName;
|
|
352
|
+
let chain = ctx.roles.get(role);
|
|
353
|
+
if (!chain) {
|
|
354
|
+
chain = await resolveRole(ctx.deps, role, false);
|
|
355
|
+
ctx.roles.set(role, chain);
|
|
356
|
+
}
|
|
357
|
+
return chain;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function stepAssignment(ctx: ExecContext, block: PlanBlock, step: PlanStep): string {
|
|
361
|
+
const templates = ctx.deps.getTemplates();
|
|
362
|
+
const done = block.steps
|
|
363
|
+
.filter((other) => other !== step)
|
|
364
|
+
.flatMap((other) => {
|
|
365
|
+
const ss = stepState(ctx.state, other.id);
|
|
366
|
+
if (ss?.status !== "done") return [];
|
|
367
|
+
return [`- Step ${other.id} ${other.title}: ${clip(ss.attempts.at(-1)?.summary ?? "done", 600)}`];
|
|
368
|
+
});
|
|
369
|
+
const earlier = ctx.plan.blocks
|
|
370
|
+
.slice(0, ctx.plan.blocks.indexOf(block))
|
|
371
|
+
.map((other) => `- Block ${other.id} ${other.title}: ${blockState(ctx.state, other.id)?.status ?? "pending"}`);
|
|
372
|
+
const validation = [...step.validation.map((command) => `- step: ${command}`), ...block.validation.map((command) => `- block: ${command}`)];
|
|
373
|
+
return templates.render("planStep", {
|
|
374
|
+
goal: ctx.plan.goal,
|
|
375
|
+
context: ctx.plan.context || "(none)",
|
|
376
|
+
blockId: block.id,
|
|
377
|
+
blockTitle: block.title,
|
|
378
|
+
blockBody: block.body || "(no description)",
|
|
379
|
+
blockAcceptance: block.acceptance,
|
|
380
|
+
stepId: step.id,
|
|
381
|
+
stepTitle: step.title,
|
|
382
|
+
stepBody: step.body || "(no description)",
|
|
383
|
+
stepAcceptance: step.acceptance,
|
|
384
|
+
validation: validation.length > 0 ? `Validation commands:\n${validation.join("\n")}` : "No validation command is given; run the checks that apply.",
|
|
385
|
+
done: [...earlier, ...done].join("\n") || "(nothing yet)",
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
async function runStep(ctx: ExecContext, block: PlanBlock, step: PlanStep, ss: StepState, bs: BlockWithSteps): Promise<RunResult> {
|
|
390
|
+
const { deps } = ctx;
|
|
391
|
+
const templates = deps.getTemplates();
|
|
392
|
+
const chain = await profilesFor(ctx, step);
|
|
393
|
+
const retry = ss.attempts.length > 0;
|
|
394
|
+
ss.status = "running";
|
|
395
|
+
if (!ss.baseline) ss.baseline = await takeBaseline(deps.host.workspace);
|
|
396
|
+
await save(ctx, `step ${step.id} running`);
|
|
397
|
+
|
|
398
|
+
let task = stepAssignment(ctx, block, step);
|
|
399
|
+
if (retry) {
|
|
400
|
+
const changes = await diffBaseline(deps.host.workspace, ss.baseline);
|
|
401
|
+
task = templates.render("planRetry", {
|
|
402
|
+
reason: ss.attempts.at(-1)?.reason ?? ss.attempts.at(-1)?.status ?? "unknown",
|
|
403
|
+
files: formatList(filterPlans(ctx, changes.changed)),
|
|
404
|
+
assignment: task,
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// Follow-up: the same step's session on retry, or the previous step's session when it resolves to the same profile.
|
|
409
|
+
let followUp: { profile: string; sessionId: string } | undefined;
|
|
410
|
+
if (retry && ss.profile && ss.sessionId) followUp = { profile: ss.profile, sessionId: ss.sessionId };
|
|
411
|
+
else if (!retry) {
|
|
412
|
+
const order = stepOrder(block);
|
|
413
|
+
const previous = order.slice(0, order.indexOf(step)).reverse().map((other) => stepState(ctx.state, other.id)).find((other) => other?.status === "done");
|
|
414
|
+
if (previous?.profile && previous.sessionId && chain.includes(previous.profile)) followUp = { profile: previous.profile, sessionId: previous.sessionId };
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
let result = await runImplement(ctx, task, step.scope, followUp ? [followUp.profile] : chain, `step ${step.id}`, followUp?.sessionId);
|
|
418
|
+
if (followUp && result.status !== "completed" && result.status !== "cancelled" && result.status !== "timeout") {
|
|
419
|
+
recordAttempt(ss, retry ? "retry" : "run", result);
|
|
420
|
+
result = await runImplement(ctx, task, step.scope, chain, `step ${step.id}`);
|
|
421
|
+
}
|
|
422
|
+
recordAttempt(ss, retry ? "retry" : "run", result);
|
|
423
|
+
ss.profile = result.profile;
|
|
424
|
+
ss.sessionId = result.resumable ? result.sessionId : undefined;
|
|
425
|
+
bs.outOfScope = [...new Set([...bs.outOfScope, ...filterPlans(ctx, result.outOfScopeChanges)])];
|
|
426
|
+
return result;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function runImplement(ctx: ExecContext, task: string, scope: string[], profiles: string[], label: string, sessionId?: string): Promise<RunResult> {
|
|
430
|
+
return ctx.deps.engine.run({
|
|
431
|
+
task,
|
|
432
|
+
mode: "implement",
|
|
433
|
+
scope,
|
|
434
|
+
workspace: ctx.deps.host.workspace,
|
|
435
|
+
profiles,
|
|
436
|
+
followUp: sessionId ? { sessionId } : undefined,
|
|
437
|
+
label,
|
|
438
|
+
workflowId: ctx.planId,
|
|
439
|
+
signal: ctx.signal,
|
|
440
|
+
lock: ctx.lock,
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function recordAttempt(ss: StepState, kind: StepAttempt["kind"], result: RunResult): void {
|
|
445
|
+
ss.attempts.push({
|
|
446
|
+
kind,
|
|
447
|
+
runId: result.runId,
|
|
448
|
+
profile: result.profile,
|
|
449
|
+
status: result.status,
|
|
450
|
+
reason: result.reason,
|
|
451
|
+
summary: clip(result.finalText ?? "", SUMMARY_CHARS),
|
|
452
|
+
changedFiles: result.changedFiles,
|
|
453
|
+
outOfScope: result.outOfScopeChanges,
|
|
454
|
+
at: new Date().toISOString(),
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function filterPlans(ctx: ExecContext, files: string[]): string[] {
|
|
459
|
+
const prefix = plansPrefix(ctx.deps.configDirName);
|
|
460
|
+
return files.filter((file) => !file.startsWith(prefix));
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
async function blockFiles(ctx: ExecContext, baseline: Baseline): Promise<string[]> {
|
|
464
|
+
const changes = await diffBaseline(ctx.deps.host.workspace, baseline);
|
|
465
|
+
return filterPlans(ctx, changes.changed);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
async function hashes(workspace: string, files: string[]): Promise<Record<string, string>> {
|
|
469
|
+
const entries = await Promise.all(files.map(async (file) => [file, await hashWorkspaceFile(workspace, file)] as const));
|
|
470
|
+
return Object.fromEntries(entries);
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** Diff of `files` between the baseline's HEAD and the working tree, including new untracked files. */
|
|
474
|
+
export async function changeSetDiff(workspace: string, head: string | null | undefined, files: string[]): Promise<string> {
|
|
475
|
+
if (files.length === 0) return "";
|
|
476
|
+
let tracked: Set<string> = new Set();
|
|
477
|
+
let text = "";
|
|
478
|
+
if (head) {
|
|
479
|
+
const listed = await git(workspace, ["ls-tree", "-r", "--name-only", "--full-tree", "-z", head]);
|
|
480
|
+
const prefix = (await git(workspace, ["rev-parse", "--show-prefix"])).stdout.trim();
|
|
481
|
+
tracked = new Set(
|
|
482
|
+
listed.stdout
|
|
483
|
+
.split("\0")
|
|
484
|
+
.filter((path) => path.startsWith(prefix))
|
|
485
|
+
.map((path) => path.slice(prefix.length)),
|
|
486
|
+
);
|
|
487
|
+
const inHead = files.filter((file) => tracked.has(file));
|
|
488
|
+
if (inHead.length > 0) text += (await git(workspace, ["diff", "--no-color", "--relative", head, "--", ...inHead])).stdout;
|
|
489
|
+
}
|
|
490
|
+
for (const file of files.filter((entry) => !tracked.has(entry))) {
|
|
491
|
+
text += (await git(workspace, ["diff", "--no-color", "--no-index", "--", "/dev/null", file])).stdout;
|
|
492
|
+
}
|
|
493
|
+
return text;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
async function reviewBlock(ctx: ExecContext, block: PlanBlock, bs: BlockWithSteps) {
|
|
497
|
+
const { deps } = ctx;
|
|
498
|
+
const templates = deps.getTemplates();
|
|
499
|
+
const workspace = deps.host.workspace;
|
|
500
|
+
const attempt = bs.reviews.length + 1;
|
|
501
|
+
deps.registry.setWorkflowHeader(ctx.planId, `plan block ${blockNumber(ctx, block)} · review`);
|
|
502
|
+
const files = await blockFiles(ctx, bs.baseline as Baseline);
|
|
503
|
+
const frozen = await hashes(workspace, files);
|
|
504
|
+
const diffPath = join(ctx.artifactsDir, `block-${block.id}-review-${attempt}.diff`);
|
|
505
|
+
await writeFile(diffPath, await changeSetDiff(workspace, bs.baseline?.head, files));
|
|
506
|
+
bs.status = "in_review";
|
|
507
|
+
await save(ctx, `block ${block.id} in review (${attempt})`);
|
|
508
|
+
|
|
509
|
+
const skipped = block.steps.filter((step) => stepState(ctx.state, step.id)?.status === "skipped");
|
|
510
|
+
const task = templates.render("planReview", {
|
|
511
|
+
goal: ctx.plan.goal,
|
|
512
|
+
blockId: block.id,
|
|
513
|
+
blockTitle: block.title,
|
|
514
|
+
blockBody: block.body || "(no description)",
|
|
515
|
+
blockAcceptance: block.acceptance,
|
|
516
|
+
steps: block.steps
|
|
517
|
+
.map((step) => `- Step ${step.id} ${step.title} [${stepState(ctx.state, step.id)?.status}] · scope: ${step.scope.join(", ")} · acceptance: ${step.acceptance}`)
|
|
518
|
+
.join("\n"),
|
|
519
|
+
skipped: skipped.length > 0 ? `Skipped steps (not implemented): ${skipped.map((step) => step.id).join(", ")}\n` : "",
|
|
520
|
+
files: formatList(files),
|
|
521
|
+
diffPath,
|
|
522
|
+
});
|
|
523
|
+
const reviewers = ctx.roles.get("reviewer") ?? (await resolveRole(deps, "reviewer", false));
|
|
524
|
+
ctx.roles.set("reviewer", reviewers);
|
|
525
|
+
let result: RunResult | undefined;
|
|
526
|
+
let error: string | undefined;
|
|
527
|
+
try {
|
|
528
|
+
result = await deps.engine.run({ task, mode: "analyze", workspace, profiles: reviewers, label: `review block ${block.id}`, workflowId: ctx.planId, signal: ctx.signal });
|
|
529
|
+
} catch (caught) {
|
|
530
|
+
error = errorText(caught);
|
|
531
|
+
}
|
|
532
|
+
checkStop(ctx);
|
|
533
|
+
const after = await blockFiles(ctx, bs.baseline as Baseline);
|
|
534
|
+
const afterHashes = await hashes(workspace, [...new Set([...after, ...files])]);
|
|
535
|
+
const reviewerChanges = Object.keys(afterHashes).filter((file) => afterHashes[file] !== frozen[file] && (file in frozen || after.includes(file)));
|
|
536
|
+
const findings = result?.status === "completed" ? parseFindings(result.finalText, "R", result.profile) : undefined;
|
|
537
|
+
const record = {
|
|
538
|
+
attempt,
|
|
539
|
+
runId: result?.runId,
|
|
540
|
+
profile: result?.profile,
|
|
541
|
+
status: result?.status ?? "failed",
|
|
542
|
+
reason: result?.reason ?? error,
|
|
543
|
+
findings: findings ?? [],
|
|
544
|
+
frozen,
|
|
545
|
+
reviewerChanges,
|
|
546
|
+
summary: clip(result?.finalText ?? "", SUMMARY_CHARS),
|
|
547
|
+
at: new Date().toISOString(),
|
|
548
|
+
};
|
|
549
|
+
bs.reviews.push(record);
|
|
550
|
+
await save(ctx, `block ${block.id} reviewed (${record.status})`);
|
|
551
|
+
return { record, result, diffPath, files, findingsParsed: Boolean(findings) };
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
async function requestVerdict(ctx: ExecContext, block: PlanBlock, bs: BlockWithSteps, review: Awaited<ReturnType<typeof reviewBlock>> | undefined) {
|
|
555
|
+
const { deps } = ctx;
|
|
556
|
+
const templates = deps.getTemplates();
|
|
557
|
+
bs.status = "in_review";
|
|
558
|
+
const files = review?.files ?? (await blockFiles(ctx, bs.baseline as Baseline));
|
|
559
|
+
const steps = block.steps.map((step) => {
|
|
560
|
+
const ss = stepState(ctx.state, step.id);
|
|
561
|
+
return `- Step ${step.id} ${step.title} [${ss?.status}] · acceptance: ${step.acceptance}`;
|
|
562
|
+
});
|
|
563
|
+
const reports = block.steps.flatMap((step) => {
|
|
564
|
+
const ss = stepState(ctx.state, step.id);
|
|
565
|
+
return (ss?.attempts ?? []).slice(-2).map((attempt) => ({
|
|
566
|
+
title: `Step ${step.id} · ${attempt.kind} · ${attempt.profile} · ${attempt.status}`,
|
|
567
|
+
text: attempt.summary || "(no report)",
|
|
568
|
+
fullPath: attempt.runId ? join(runsRoot(deps.agentDir, deps.host.workspace), attempt.runId, "result.md") : undefined,
|
|
569
|
+
}));
|
|
570
|
+
});
|
|
571
|
+
let findings: string;
|
|
572
|
+
if (!review) findings = "No independent review (planning.execution.review is none). Your own check is the only one.";
|
|
573
|
+
else if (review.record.status !== "completed") findings = `The review run ended ${review.record.status}: ${review.record.reason ?? "no reason"}. Check the block yourself.`;
|
|
574
|
+
else if (!review.findingsParsed) findings = `The reviewer returned no valid findings block; its report is at ${resultPath(review.result?.artifactsDir ?? "")}.\n\n${review.record.summary}`;
|
|
575
|
+
else findings = `${formatFindings(review.record.findings)}\n\nFull review: ${resultPath(review.result?.artifactsDir ?? "")}${review.diffPath ? `\nFrozen diff: ${review.diffPath}` : ""}`;
|
|
576
|
+
const vars = {
|
|
577
|
+
blockId: block.id,
|
|
578
|
+
planId: ctx.planId,
|
|
579
|
+
blockTitle: block.title,
|
|
580
|
+
blockAcceptance: `${block.acceptance}${block.validation.length > 0 ? `\nValidation: ${block.validation.join("; ")}` : ""}`,
|
|
581
|
+
steps: steps.join("\n"),
|
|
582
|
+
files: formatList(files),
|
|
583
|
+
outOfScope: bs.outOfScope.length > 0 ? `## Out-of-scope changes\n\n${formatList(bs.outOfScope)}\n` : "",
|
|
584
|
+
reviewerChanges:
|
|
585
|
+
review && review.record.reviewerChanges.length > 0
|
|
586
|
+
? `## Changes made by the reviewer\n\nThese files changed during the review and are not part of the block's frozen change set. Decide, before your verdict, whether to undo them with your own tools or keep them:\n${formatList(review.record.reviewerChanges)}\n`
|
|
587
|
+
: "",
|
|
588
|
+
findings,
|
|
589
|
+
};
|
|
590
|
+
const fixed = templates.render("planVerdict", { ...vars, reports: "" });
|
|
591
|
+
const content = templates.render("planVerdict", { ...vars, reports: fitParts(reports, fixed) });
|
|
592
|
+
await save(ctx, `block ${block.id} awaiting verdict`);
|
|
593
|
+
ensureAlive(deps);
|
|
594
|
+
deps.registry.setWorkflowHeader(ctx.planId, `plan block ${blockNumber(ctx, block)} · verdict`);
|
|
595
|
+
const pending = deps.verdicts.expect(ctx.planId, block.id, ctx.signal);
|
|
596
|
+
deps.host.sendMessage({ customType: MESSAGE_TYPES.block, content, details: { planId: ctx.planId, blockId: block.id, phase: "verdict" }, display: true }, true);
|
|
597
|
+
const verdict = await pending;
|
|
598
|
+
checkStop(ctx);
|
|
599
|
+
return verdict;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
async function fixCycle(ctx: ExecContext, block: PlanBlock, bs: BlockWithSteps): Promise<boolean> {
|
|
603
|
+
const { deps } = ctx;
|
|
604
|
+
const templates = deps.getTemplates();
|
|
605
|
+
const lastReview = bs.reviews.at(-1);
|
|
606
|
+
const lastVerdict = [...bs.verdicts].reverse().find((entry) => entry.verdict === "needs_fix" || entry.verdict === "blocked");
|
|
607
|
+
const findings: Finding[] = [...(lastReview?.findings.filter((finding) => finding.severity === "blocking") ?? [])];
|
|
608
|
+
if (lastVerdict?.feedback) findings.push({ id: "V1", severity: "blocking", summary: lastVerdict.feedback, source: "verdict" });
|
|
609
|
+
if (findings.length === 0) findings.push({ id: "V1", severity: "blocking", summary: "The verdict asked for a fix without details; recheck the block's acceptance criteria.", source: "verdict" });
|
|
610
|
+
|
|
611
|
+
// Owner: the last step (document order) whose scope contains the finding's file; otherwise the block's last step.
|
|
612
|
+
const groups = new Map<string, Finding[]>();
|
|
613
|
+
const last = block.steps.at(-1) as PlanStep;
|
|
614
|
+
for (const finding of findings) {
|
|
615
|
+
const owner = (finding.file ? [...block.steps].reverse().find((step) => inScope(finding.file as string, step.scope)) : undefined) ?? last;
|
|
616
|
+
groups.set(owner.id, [...(groups.get(owner.id) ?? []), finding]);
|
|
617
|
+
}
|
|
618
|
+
const scope = blockScope(block);
|
|
619
|
+
const files = await blockFiles(ctx, bs.baseline as Baseline);
|
|
620
|
+
const diffPath = join(ctx.artifactsDir, `block-${block.id}-fix-${bs.fixAttempts}.diff`);
|
|
621
|
+
await writeFile(diffPath, await changeSetDiff(deps.host.workspace, bs.baseline?.head, files));
|
|
622
|
+
for (const step of block.steps) {
|
|
623
|
+
const group = groups.get(step.id);
|
|
624
|
+
if (!group) continue;
|
|
625
|
+
checkStop(ctx);
|
|
626
|
+
deps.registry.setWorkflowHeader(ctx.planId, `plan block ${blockNumber(ctx, block)} · fix ${step.id}`);
|
|
627
|
+
const ss = stepState(ctx.state, step.id) as StepState;
|
|
628
|
+
const chain = ss.profile ? [ss.profile] : await profilesFor(ctx, step);
|
|
629
|
+
const fullContext = `${stepAssignment(ctx, block, step)}\n\n## Current change set of the block\n\nChanged files:\n${formatList(files)}\n\nThe diff is saved at ${diffPath}.\n`;
|
|
630
|
+
const followUpTask = templates.render("planFix", { blockId: block.id, blockTitle: block.title, findings: formatFindings(group), context: "" });
|
|
631
|
+
const freshTask = templates.render("planFix", { blockId: block.id, blockTitle: block.title, findings: formatFindings(group), context: fullContext });
|
|
632
|
+
let result: RunResult;
|
|
633
|
+
if (ss.sessionId && ss.profile) {
|
|
634
|
+
result = await runImplement(ctx, followUpTask, scope, [ss.profile], `fix ${step.id}`, ss.sessionId);
|
|
635
|
+
if (result.status !== "completed" && result.status !== "cancelled" && result.status !== "timeout") {
|
|
636
|
+
recordAttempt(ss, "fix", result);
|
|
637
|
+
result = await runImplement(ctx, freshTask, scope, chain, `fix ${step.id}`);
|
|
638
|
+
}
|
|
639
|
+
} else {
|
|
640
|
+
result = await runImplement(ctx, freshTask, scope, chain, `fix ${step.id}`);
|
|
641
|
+
}
|
|
642
|
+
recordAttempt(ss, "fix", result);
|
|
643
|
+
ss.profile = result.profile;
|
|
644
|
+
ss.sessionId = result.resumable ? result.sessionId : ss.sessionId;
|
|
645
|
+
bs.outOfScope = [...new Set([...bs.outOfScope, ...filterPlans(ctx, result.outOfScopeChanges)])];
|
|
646
|
+
checkStop(ctx);
|
|
647
|
+
if (result.status !== "completed") {
|
|
648
|
+
bs.status = "paused";
|
|
649
|
+
bs.resumeAt = "fix";
|
|
650
|
+
bs.pauseReason = `the fix run for step ${step.id} ended ${result.status}${result.reason ? `: ${result.reason}` : ""}`;
|
|
651
|
+
await save(ctx, bs.pauseReason);
|
|
652
|
+
return false;
|
|
653
|
+
}
|
|
654
|
+
await save(ctx, `fix for step ${step.id} done`);
|
|
655
|
+
}
|
|
656
|
+
return true;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
async function acceptBlock(ctx: ExecContext, block: PlanBlock, bs: BlockWithSteps): Promise<void> {
|
|
660
|
+
const { deps } = ctx;
|
|
661
|
+
const workspace = deps.host.workspace;
|
|
662
|
+
const files = await blockFiles(ctx, bs.baseline as Baseline);
|
|
663
|
+
let commit: string | undefined;
|
|
664
|
+
if (deps.getConfig().planning.execution.commit === "per-block" && files.length > 0) {
|
|
665
|
+
if (!ctx.state.startedClean) {
|
|
666
|
+
deps.host.notify(`Block ${block.id} was not committed: the plan did not start from a clean tree.`, "warning");
|
|
667
|
+
} else {
|
|
668
|
+
const add = await git(workspace, ["add", "-A", "--", ...files]);
|
|
669
|
+
const message = `${block.title}\n\nPlan ${ctx.planId}, block ${block.id}.`;
|
|
670
|
+
const done = add.code === 0 ? await git(workspace, ["commit", "-q", "-m", message, "--", ...files]) : add;
|
|
671
|
+
if (done.code === 0) commit = (await git(workspace, ["rev-parse", "HEAD"])).stdout.trim();
|
|
672
|
+
else deps.host.notify(`Block ${block.id} could not be committed: ${clip(done.stderr.trim() || done.stdout.trim(), 300)}`, "warning");
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
const head = (await git(workspace, ["rev-parse", "-q", "--verify", "HEAD"])).stdout.trim() || null;
|
|
676
|
+
bs.accepted = { files: await hashes(workspace, files), head, commit };
|
|
677
|
+
bs.status = "accepted";
|
|
678
|
+
bs.pauseReason = undefined;
|
|
679
|
+
bs.resumeAt = undefined;
|
|
680
|
+
await save(ctx, `block ${block.id} accepted${commit ? ` (commit ${commit.slice(0, 10)})` : ""}`);
|
|
681
|
+
if (deps.host.alive()) deps.host.notify(`Plan ${ctx.planId}: block ${block.id} accepted${commit ? `, commit ${commit.slice(0, 10)}` : ""}.`, "info");
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
async function finish(ctx: ExecContext): Promise<void> {
|
|
685
|
+
const { deps, state, plan } = ctx;
|
|
686
|
+
const skipped = state.blocks.some((block) => block.status === "skipped" || block.steps.some((step) => step.status === "skipped"));
|
|
687
|
+
state.status = skipped ? "completed_with_skips" : "completed";
|
|
688
|
+
await save(ctx, state.status);
|
|
689
|
+
ensureAlive(deps);
|
|
690
|
+
const parts = plan.blocks.map((block) => {
|
|
691
|
+
const bs = blockState(state, block.id) as BlockWithSteps;
|
|
692
|
+
const lastReview = bs.reviews.at(-1);
|
|
693
|
+
const remaining = lastReview?.findings ?? [];
|
|
694
|
+
const lines = [
|
|
695
|
+
`Status: ${bs.status}${bs.accepted?.commit ? ` · commit ${bs.accepted.commit.slice(0, 10)}` : ""} · fix cycles: ${bs.fixAttempts}`,
|
|
696
|
+
`Steps: ${block.steps.map((step) => `${step.id} ${stepState(state, step.id)?.status}`).join(", ")}`,
|
|
697
|
+
`Changed files: ${Object.keys(bs.accepted?.files ?? {}).join(", ") || "(none)"}`,
|
|
698
|
+
bs.outOfScope.length > 0 ? `Out-of-scope changes: ${bs.outOfScope.join(", ")}` : "",
|
|
699
|
+
`Last verdict: ${bs.verdicts.at(-1)?.verdict ?? "none"}${bs.verdicts.at(-1)?.feedback ? ` (${bs.verdicts.at(-1)?.feedback})` : ""}`,
|
|
700
|
+
`Review findings of the last review:\n${formatFindings(remaining)}`,
|
|
701
|
+
].filter(Boolean);
|
|
702
|
+
return { title: `Block ${block.id}: ${block.title}`, text: lines.join("\n") };
|
|
703
|
+
});
|
|
704
|
+
const templates = deps.getTemplates();
|
|
705
|
+
const vars = { planId: ctx.planId, goal: plan.goal, status: state.status };
|
|
706
|
+
const fixed = templates.render("planReport", { ...vars, blocks: "" });
|
|
707
|
+
deps.host.sendMessage(
|
|
708
|
+
{ customType: MESSAGE_TYPES.plan, content: templates.render("planReport", { ...vars, blocks: fitParts(parts, fixed) }), details: { planId: ctx.planId, status: state.status }, display: true },
|
|
709
|
+
true,
|
|
710
|
+
);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
async function save(ctx: ExecContext, event: string): Promise<void> {
|
|
714
|
+
await saveState(ctx.paths.state, ctx.state, event);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
function checkStop(ctx: ExecContext): void {
|
|
718
|
+
if (ctx.signal.aborted) throw new WorkflowStopped("cancelled");
|
|
719
|
+
if (!ctx.deps.host.alive()) throw new WorkflowStopped("extension instance replaced");
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** Files of the last accepted block whose content no longer matches the recorded state. */
|
|
723
|
+
async function acceptedMismatch(workspace: string, state: PlanState): Promise<string[]> {
|
|
724
|
+
const last = [...state.blocks].reverse().find((block) => block.status === "accepted" && block.accepted);
|
|
725
|
+
if (!last?.accepted) return [];
|
|
726
|
+
const mismatch: string[] = [];
|
|
727
|
+
for (const [file, hash] of Object.entries(last.accepted.files)) {
|
|
728
|
+
if ((await hashWorkspaceFile(workspace, file)) !== hash) mismatch.push(file);
|
|
729
|
+
}
|
|
730
|
+
return mismatch;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/** The plan `/plan resume` continues: the given id, or the most recent unfinished one. */
|
|
734
|
+
export async function findResumable(deps: WorkflowDeps, id?: string): Promise<string | undefined> {
|
|
735
|
+
if (id) return id;
|
|
736
|
+
const plans = await listPlans(deps.host.workspace, deps.configDirName);
|
|
737
|
+
return plans.find((entry) => entry.state && ["paused", "executing", "approved", "draft"].includes(entry.state.status))?.id;
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/** `/plan resume [id]`: a draft goes back to approval, an approved or paused plan continues executing. */
|
|
741
|
+
export async function resumePlan(deps: WorkflowDeps, id?: string): Promise<PlanState | undefined> {
|
|
742
|
+
const { host } = deps;
|
|
743
|
+
const planId = await findResumable(deps, id);
|
|
744
|
+
if (!planId) throw new Error("No plan to resume in this workspace.");
|
|
745
|
+
if (deps.registry.listWorkflows().some((entry) => entry.id === planId)) throw new Error(`Plan ${planId} is already running in this session.`);
|
|
746
|
+
const stored = await loadPlan(host.workspace, deps.configDirName, planId);
|
|
747
|
+
if (!stored) throw new Error(`Plan ${planId} was not found.`);
|
|
748
|
+
if (!stored.state) throw new Error(`Plan ${planId} has no state file.`);
|
|
749
|
+
if (["completed", "completed_with_skips", "aborted"].includes(stored.state.status)) {
|
|
750
|
+
throw new Error(`Plan ${planId} is ${stored.state.status}; there is nothing to resume.`);
|
|
751
|
+
}
|
|
752
|
+
if (!stored.plan) {
|
|
753
|
+
if (stored.state.status !== "draft") {
|
|
754
|
+
throw new Error(`Plan ${planId} does not validate; fix the file first:\n${stored.errors.map((error) => `- ${error}`).join("\n")}`);
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
if (stored.plan) {
|
|
758
|
+
host.sendMessage(
|
|
759
|
+
{ customType: MESSAGE_TYPES.plan, content: planSummary(stored.plan, syncState(stored.state, stored.plan)), details: { planId, status: stored.state.status }, display: true },
|
|
760
|
+
false,
|
|
761
|
+
);
|
|
762
|
+
}
|
|
763
|
+
if (stored.state.status === "draft") {
|
|
764
|
+
if (!stored.plan) throw new Error(`Plan ${planId} does not validate:\n${stored.errors.map((error) => `- ${error}`).join("\n")}`);
|
|
765
|
+
const decision = await approvePlan(deps, {
|
|
766
|
+
planId,
|
|
767
|
+
plan: stored.plan,
|
|
768
|
+
state: syncState(stored.state, stored.plan),
|
|
769
|
+
context: `## Goal\n\n${stored.plan.goal}\n\n## Context\n\n${stored.plan.context}`,
|
|
770
|
+
});
|
|
771
|
+
if (decision !== "approved") return undefined;
|
|
772
|
+
return executePlan(deps, planId);
|
|
773
|
+
}
|
|
774
|
+
return executePlan(deps, planId, { resume: true });
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/** `/plan status`: the active plan of this session, or the most recent plan of the workspace. */
|
|
778
|
+
export async function planStatus(deps: WorkflowDeps): Promise<string> {
|
|
779
|
+
const active = deps.registry.listWorkflows().find((entry) => entry.kind === "plan");
|
|
780
|
+
const plans = await listPlans(deps.host.workspace, deps.configDirName);
|
|
781
|
+
const id = active?.id ?? plans[0]?.id;
|
|
782
|
+
if (!id) return "No plan in this workspace.";
|
|
783
|
+
const stored = await loadPlan(deps.host.workspace, deps.configDirName, id);
|
|
784
|
+
if (!stored?.plan || !stored.state) return `Plan ${id}: ${stored?.state?.status ?? "no state"}${stored?.errors.length ? ` (does not validate)` : ""}`;
|
|
785
|
+
const header = active ? `Active: ${active.header}\n` : "";
|
|
786
|
+
const others = plans.filter((entry) => entry.id !== id).slice(0, 5).map((entry) => `- ${entry.id}: ${entry.state?.status ?? "no state"}`);
|
|
787
|
+
return `${header}${planSummary(stored.plan, syncState(stored.state, stored.plan))}${others.length > 0 ? `\n\nOther plans:\n${others.join("\n")}` : ""}`;
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/** `/plan abort`: stops the active plan and marks it aborted; without an active plan, aborts the most recent paused one. */
|
|
791
|
+
export async function abortPlan(deps: WorkflowDeps, id?: string): Promise<string> {
|
|
792
|
+
const active = deps.registry.listWorkflows().find((entry) => entry.kind === "plan" && (!id || entry.id === id));
|
|
793
|
+
if (active) {
|
|
794
|
+
active.stopIntent = "abort";
|
|
795
|
+
active.controller.abort();
|
|
796
|
+
return `Aborting plan ${active.id}.`;
|
|
797
|
+
}
|
|
798
|
+
const planId = await findResumable(deps, id);
|
|
799
|
+
if (!planId) return "No plan to abort.";
|
|
800
|
+
const paths = planPaths(deps.host.workspace, deps.configDirName, planId);
|
|
801
|
+
const stored = await loadPlan(deps.host.workspace, deps.configDirName, planId);
|
|
802
|
+
if (!stored?.state) return `Plan ${planId} has no state file.`;
|
|
803
|
+
if (["completed", "completed_with_skips", "aborted"].includes(stored.state.status)) return `Plan ${planId} is already ${stored.state.status}.`;
|
|
804
|
+
stored.state.status = "aborted";
|
|
805
|
+
await saveState(paths.state, stored.state, "aborted by the user");
|
|
806
|
+
return `Plan ${planId} aborted.`;
|
|
807
|
+
}
|