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,407 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { createWorkflowDir } from "../engine/artifacts.ts";
|
|
3
|
+
import type { RunResult } from "../engine/types.ts";
|
|
4
|
+
import { fitParts, resultPath } from "./budget.ts";
|
|
5
|
+
import { costGate, ensureAlive, errorText, frameBrief, lastJsonBlock, profileLabel, resolveRole, titleOf } from "./common.ts";
|
|
6
|
+
import { ENTRY_TYPE, MESSAGE_TYPES, WorkflowStopped, type WorkflowDeps } from "./host.ts";
|
|
7
|
+
import { extractPlanDocument, parsePlan, planIdFor, serializePlan, type PlanDocument } from "./planfile.ts";
|
|
8
|
+
import { newState, planPaths, saveState, savePlanFile, syncState, type Finding, type PlanState } from "./planstate.ts";
|
|
9
|
+
|
|
10
|
+
/** A planner conversation: follow-ups in its session when the adapter can resume, stateless runs otherwise. */
|
|
11
|
+
export class PlannerSession {
|
|
12
|
+
private readonly deps: WorkflowDeps;
|
|
13
|
+
private readonly chain: string[];
|
|
14
|
+
private readonly workflowId: string;
|
|
15
|
+
private readonly signal: AbortSignal;
|
|
16
|
+
profile?: string;
|
|
17
|
+
sessionId?: string;
|
|
18
|
+
runs = 0;
|
|
19
|
+
|
|
20
|
+
constructor(deps: WorkflowDeps, chain: string[], workflowId: string, signal: AbortSignal) {
|
|
21
|
+
this.deps = deps;
|
|
22
|
+
this.chain = chain;
|
|
23
|
+
this.workflowId = workflowId;
|
|
24
|
+
this.signal = signal;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async ask(task: string, statelessContext: string, label: string): Promise<RunResult> {
|
|
28
|
+
const followUp = this.profile && this.sessionId ? { sessionId: this.sessionId } : undefined;
|
|
29
|
+
let result = await this.run(followUp ? task : join(statelessContext, task), followUp ? [this.profile as string] : this.chain, label, followUp);
|
|
30
|
+
if (followUp && result.status !== "completed" && !this.signal.aborted && result.status !== "timeout") {
|
|
31
|
+
// The session could not be continued: start over with the full context.
|
|
32
|
+
this.sessionId = undefined;
|
|
33
|
+
result = await this.run(join(statelessContext, task), this.chain, label);
|
|
34
|
+
}
|
|
35
|
+
this.profile = result.profile;
|
|
36
|
+
this.sessionId = result.resumable ? result.sessionId : undefined;
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
private run(task: string, profiles: string[], label: string, followUp?: { sessionId: string }): Promise<RunResult> {
|
|
41
|
+
this.runs++;
|
|
42
|
+
return this.deps.engine.run({
|
|
43
|
+
task,
|
|
44
|
+
mode: "analyze",
|
|
45
|
+
workspace: this.deps.host.workspace,
|
|
46
|
+
profiles,
|
|
47
|
+
followUp,
|
|
48
|
+
label,
|
|
49
|
+
workflowId: this.workflowId,
|
|
50
|
+
signal: this.signal,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function join(context: string, task: string): string {
|
|
56
|
+
return context ? `${context}\n\n---\n\n${task}` : task;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Asks the planner for a plan document; one repair follow-up when it does not parse. */
|
|
60
|
+
export async function obtainPlan(
|
|
61
|
+
deps: WorkflowDeps,
|
|
62
|
+
session: PlannerSession,
|
|
63
|
+
task: string,
|
|
64
|
+
statelessContext: string,
|
|
65
|
+
planId: string,
|
|
66
|
+
label: string,
|
|
67
|
+
): Promise<{ plan: PlanDocument; answer: string; result: RunResult }> {
|
|
68
|
+
const templates = deps.getTemplates();
|
|
69
|
+
const planFormat = templates.render("planFormat", { planId });
|
|
70
|
+
const result = await session.ask(task, statelessContext, label);
|
|
71
|
+
if (result.status !== "completed") throw new Error(`The planner run ended ${result.status}: ${result.reason ?? "no reason"} (${result.artifactsDir})`);
|
|
72
|
+
const answer = result.finalText ?? "";
|
|
73
|
+
let parsed = parseAnswer(answer, planId);
|
|
74
|
+
if (parsed.plan) return { plan: parsed.plan, answer, result };
|
|
75
|
+
|
|
76
|
+
const repairTask = templates.render("planRepair", { errors: parsed.errors.map((error) => `- ${error}`).join("\n"), planFormat });
|
|
77
|
+
const repair = await session.ask(repairTask, `${statelessContext}\n\n## Your previous output\n\n${answer}`, `${label} · repair`);
|
|
78
|
+
if (repair.status !== "completed") throw new Error(`The planner's repair run ended ${repair.status}: ${repair.reason ?? "no reason"}`);
|
|
79
|
+
parsed = parseAnswer(repair.finalText ?? "", planId);
|
|
80
|
+
if (!parsed.plan) throw new Error(`The planner's plan still does not parse after one repair:\n${parsed.errors.map((error) => `- ${error}`).join("\n")}`);
|
|
81
|
+
return { plan: parsed.plan, answer: repair.finalText ?? "", result: repair };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function parseAnswer(answer: string, planId: string): { plan?: PlanDocument; errors: string[] } {
|
|
85
|
+
const document = extractPlanDocument(answer);
|
|
86
|
+
// The id is the engine's: it names the files.
|
|
87
|
+
const fixed = document.replace(/^(---\s*\n[\s\S]*?^id\s*:).*$/m, `$1 ${planId}`);
|
|
88
|
+
const parsed = parsePlan(fixed);
|
|
89
|
+
if (parsed.plan) parsed.plan.id = planId;
|
|
90
|
+
return parsed;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Parses critic or reviewer findings from the last fenced JSON block. */
|
|
94
|
+
export function parseFindings(text: string | undefined, prefix: string, source: string, start = 1): Finding[] | undefined {
|
|
95
|
+
const json = lastJsonBlock(text);
|
|
96
|
+
const list = json && typeof json === "object" && Array.isArray((json as { findings?: unknown }).findings) ? (json as { findings: unknown[] }).findings : undefined;
|
|
97
|
+
if (!list) return undefined;
|
|
98
|
+
const findings: Finding[] = [];
|
|
99
|
+
for (const entry of list) {
|
|
100
|
+
if (!entry || typeof entry !== "object") continue;
|
|
101
|
+
const item = entry as Record<string, unknown>;
|
|
102
|
+
const summary = typeof item.summary === "string" ? item.summary.trim() : "";
|
|
103
|
+
if (!summary) continue;
|
|
104
|
+
findings.push({
|
|
105
|
+
id: `${prefix}${start + findings.length}`,
|
|
106
|
+
severity: item.severity === "blocking" ? "blocking" : "advisory",
|
|
107
|
+
summary,
|
|
108
|
+
evidence: typeof item.evidence === "string" ? item.evidence : undefined,
|
|
109
|
+
file: typeof item.file === "string" && item.file.trim() ? item.file.trim().replace(/^\.\//, "") : undefined,
|
|
110
|
+
line: typeof item.line === "number" ? item.line : undefined,
|
|
111
|
+
block: typeof item.block === "string" || typeof item.block === "number" ? String(item.block) : undefined,
|
|
112
|
+
source,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
return findings;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function formatFindings(findings: Finding[]): string {
|
|
119
|
+
if (findings.length === 0) return "(none)";
|
|
120
|
+
return findings
|
|
121
|
+
.map((finding) => {
|
|
122
|
+
const where = [finding.block ? `block ${finding.block}` : "", finding.file ? `${finding.file}${finding.line ? `:${finding.line}` : ""}` : ""]
|
|
123
|
+
.filter(Boolean)
|
|
124
|
+
.join(", ");
|
|
125
|
+
return `- ${finding.id} [${finding.severity}]${where ? ` (${where})` : ""} ${finding.summary}${finding.evidence ? `\n Evidence: ${finding.evidence}` : ""}\n Source: ${finding.source}`;
|
|
126
|
+
})
|
|
127
|
+
.join("\n");
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
interface CritiqueRound {
|
|
131
|
+
findings: Finding[];
|
|
132
|
+
notes: string[];
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function critique(deps: WorkflowDeps, critics: string[], brief: string, planText: string, workflowId: string, round: number, signal: AbortSignal): Promise<CritiqueRound> {
|
|
136
|
+
const templates = deps.getTemplates();
|
|
137
|
+
const task = templates.render("planCritique", { brief, plan: planText });
|
|
138
|
+
const results = await Promise.all(
|
|
139
|
+
critics.map((profile) =>
|
|
140
|
+
deps.engine
|
|
141
|
+
.run({ task, mode: "analyze", workspace: deps.host.workspace, profiles: [profile], label: `critic ${profile} · round ${round}`, workflowId, signal })
|
|
142
|
+
.catch((error: Error) => error),
|
|
143
|
+
),
|
|
144
|
+
);
|
|
145
|
+
const findings: Finding[] = [];
|
|
146
|
+
const notes: string[] = [];
|
|
147
|
+
for (const [index, result] of results.entries()) {
|
|
148
|
+
const profile = critics[index];
|
|
149
|
+
if (result instanceof Error) {
|
|
150
|
+
notes.push(`critic ${profile}: ${result.message}`);
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (result.status !== "completed") {
|
|
154
|
+
notes.push(`critic ${profile}: ${result.status} ${result.reason ?? ""}`.trim());
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
const parsed = parseFindings(result.finalText, "F", profile, findings.length + 1);
|
|
158
|
+
if (!parsed) notes.push(`critic ${profile}: no valid findings block (see ${resultPath(result.artifactsDir)})`);
|
|
159
|
+
else findings.push(...parsed);
|
|
160
|
+
}
|
|
161
|
+
return { findings, notes };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export interface PlanningResult {
|
|
165
|
+
planId?: string;
|
|
166
|
+
status: "approved" | "draft" | "discarded" | "cancelled" | "failed";
|
|
167
|
+
error?: string;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** From the user's goal to an approved plan (section 11.1, phases 1 to 5). */
|
|
171
|
+
export async function runPlanning(deps: WorkflowDeps, goal: string): Promise<PlanningResult> {
|
|
172
|
+
const config = deps.getConfig();
|
|
173
|
+
const templates = deps.getTemplates();
|
|
174
|
+
const { host } = deps;
|
|
175
|
+
const planner = await resolveRole(deps, "planner", false);
|
|
176
|
+
const critics = [...new Set(await resolveRole(deps, "critic", true))];
|
|
177
|
+
|
|
178
|
+
let planId = planIdFor(goal);
|
|
179
|
+
for (let index = 2; existsSync(planPaths(host.workspace, deps.configDirName, planId).plan); index++) planId = `${planIdFor(goal)}-${index}`;
|
|
180
|
+
const controller = new AbortController();
|
|
181
|
+
const signal = controller.signal;
|
|
182
|
+
deps.registry.addWorkflow({ id: planId, kind: "plan", header: "plan · framing", controller });
|
|
183
|
+
let started = false;
|
|
184
|
+
try {
|
|
185
|
+
const brief = await frameBrief(deps, goal, "the coding agents who will plan and implement it", "Plan", signal);
|
|
186
|
+
if (!brief) {
|
|
187
|
+
host.notify("Planning cancelled.", "info");
|
|
188
|
+
return { status: "cancelled" };
|
|
189
|
+
}
|
|
190
|
+
const maxRevisions = config.planning.maxRevisions;
|
|
191
|
+
const bound = 2 + maxRevisions * 2 + critics.length * (1 + maxRevisions);
|
|
192
|
+
const gate = await costGate(deps, "Start planning?", [
|
|
193
|
+
`Planner: ${planner.map((name) => profileLabel(deps, name)).join(" → ")}`,
|
|
194
|
+
`Critics (${critics.length}): ${critics.map((name) => profileLabel(deps, name)).join(", ")}`,
|
|
195
|
+
`Revisions: up to ${maxRevisions}`,
|
|
196
|
+
`Upper bound: ${bound} runs (analyze mode, full access, in ${host.workspace})`,
|
|
197
|
+
"Execution needs your approval of the plan and is not included.",
|
|
198
|
+
]);
|
|
199
|
+
if (!gate) {
|
|
200
|
+
host.notify("Planning cancelled.", "info");
|
|
201
|
+
return { status: "cancelled" };
|
|
202
|
+
}
|
|
203
|
+
started = true;
|
|
204
|
+
await createWorkflowDir(deps.agentDir, host.workspace, planId);
|
|
205
|
+
const paths = planPaths(host.workspace, deps.configDirName, planId);
|
|
206
|
+
const session = new PlannerSession(deps, planner, planId, signal);
|
|
207
|
+
const context = `## Brief\n\n${brief}`;
|
|
208
|
+
|
|
209
|
+
deps.registry.setWorkflowHeader(planId, "plan · draft");
|
|
210
|
+
const draft = await obtainPlan(
|
|
211
|
+
deps,
|
|
212
|
+
session,
|
|
213
|
+
templates.render("planDraft", { brief, planFormat: templates.render("planFormat", { planId }) }),
|
|
214
|
+
"",
|
|
215
|
+
planId,
|
|
216
|
+
"planner · draft",
|
|
217
|
+
);
|
|
218
|
+
let plan = draft.plan;
|
|
219
|
+
let state = newState(plan);
|
|
220
|
+
await savePlanFile(paths.plan, serializePlan(plan));
|
|
221
|
+
await saveState(paths.state, state, "drafted");
|
|
222
|
+
ensureAlive(deps);
|
|
223
|
+
host.appendEntry(ENTRY_TYPE, { kind: "plan", id: planId, title: titleOf(goal), plan: paths.plan });
|
|
224
|
+
|
|
225
|
+
let round = 0;
|
|
226
|
+
deps.registry.setWorkflowHeader(planId, `plan · critique ${round + 1}`);
|
|
227
|
+
let review = await critique(deps, critics, brief, serializePlan(plan), planId, round, signal);
|
|
228
|
+
while (review.findings.some((finding) => finding.severity === "blocking") && state.planning.revisions < maxRevisions) {
|
|
229
|
+
if (signal.aborted) throw new WorkflowStopped("cancelled");
|
|
230
|
+
deps.registry.setWorkflowHeader(planId, `plan · revision ${state.planning.revisions + 1}/${maxRevisions}`);
|
|
231
|
+
const revised = await obtainPlan(
|
|
232
|
+
deps,
|
|
233
|
+
session,
|
|
234
|
+
templates.render("planRevise", { findings: formatFindings(review.findings), planFormat: templates.render("planFormat", { planId }) }),
|
|
235
|
+
`${context}\n\n## Your current plan\n\n${serializePlan(plan)}`,
|
|
236
|
+
planId,
|
|
237
|
+
`planner · revision ${state.planning.revisions + 1}`,
|
|
238
|
+
);
|
|
239
|
+
plan = revised.plan;
|
|
240
|
+
state = syncState(state, plan);
|
|
241
|
+
state.planning.revisions++;
|
|
242
|
+
state.planning.dispositions = parseDispositions(revised.answer);
|
|
243
|
+
await savePlanFile(paths.plan, serializePlan(plan));
|
|
244
|
+
await saveState(paths.state, state, `revised (${state.planning.revisions})`);
|
|
245
|
+
round++;
|
|
246
|
+
deps.registry.setWorkflowHeader(planId, `plan · critique ${round + 1}`);
|
|
247
|
+
review = await critique(deps, critics, brief, serializePlan(plan), planId, round, signal);
|
|
248
|
+
}
|
|
249
|
+
state.planning.unresolved = review.findings.filter((finding) => finding.severity === "blocking");
|
|
250
|
+
await saveState(paths.state, state, "critique done");
|
|
251
|
+
ensureAlive(deps);
|
|
252
|
+
|
|
253
|
+
deps.registry.setWorkflowHeader(planId, "plan · approval");
|
|
254
|
+
const decision = await approvePlan(deps, { planId, plan, state, session, context, notes: review.notes, advisory: review.findings.filter((f) => f.severity === "advisory") });
|
|
255
|
+
return { planId, status: decision };
|
|
256
|
+
} catch (error) {
|
|
257
|
+
if (error instanceof WorkflowStopped || signal.aborted) {
|
|
258
|
+
if (host.alive()) host.notify(`Planning ${planId} stopped${started ? `; the draft stays in ${deps.configDirName}/master-orchestrator/plans/` : ""}.`, "warning");
|
|
259
|
+
return { planId: started ? planId : undefined, status: "cancelled" };
|
|
260
|
+
}
|
|
261
|
+
if (!started) throw error;
|
|
262
|
+
if (host.alive()) {
|
|
263
|
+
host.sendMessage({ customType: MESSAGE_TYPES.plan, content: `Planning ${planId} failed: ${errorText(error)}`, details: { planId, status: "failed" }, display: true }, false);
|
|
264
|
+
}
|
|
265
|
+
return { planId, status: "failed", error: errorText(error) };
|
|
266
|
+
} finally {
|
|
267
|
+
deps.registry.removeWorkflow(planId);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function parseDispositions(answer: string): PlanState["planning"]["dispositions"] {
|
|
272
|
+
const json = lastJsonBlock(answer);
|
|
273
|
+
const list = json && typeof json === "object" ? (json as { dispositions?: unknown }).dispositions : undefined;
|
|
274
|
+
if (!Array.isArray(list)) return [];
|
|
275
|
+
return list
|
|
276
|
+
.filter((entry): entry is Record<string, unknown> => Boolean(entry) && typeof entry === "object")
|
|
277
|
+
.map((entry) => ({
|
|
278
|
+
finding: String(entry.finding ?? "?"),
|
|
279
|
+
disposition: entry.disposition === "rejected" ? "rejected" : "fixed",
|
|
280
|
+
reason: typeof entry.reason === "string" ? entry.reason : undefined,
|
|
281
|
+
}));
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export interface ApprovalInput {
|
|
285
|
+
planId: string;
|
|
286
|
+
plan: PlanDocument;
|
|
287
|
+
state: PlanState;
|
|
288
|
+
session?: PlannerSession;
|
|
289
|
+
context: string;
|
|
290
|
+
notes?: string[];
|
|
291
|
+
advisory?: Finding[];
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const APPROVE = "Approve and execute";
|
|
295
|
+
const EDIT = "Edit the plan";
|
|
296
|
+
const REVISE = "Request a revision";
|
|
297
|
+
const KEEP = "Keep as draft (resume later)";
|
|
298
|
+
const DISCARD = "Discard";
|
|
299
|
+
|
|
300
|
+
/** The approval dialog loop (phase 5). Approval starts execution through the injected executor. */
|
|
301
|
+
export async function approvePlan(deps: WorkflowDeps, input: ApprovalInput): Promise<"approved" | "draft" | "discarded"> {
|
|
302
|
+
const { host } = deps;
|
|
303
|
+
const templates = deps.getTemplates();
|
|
304
|
+
const paths = planPaths(host.workspace, deps.configDirName, input.planId);
|
|
305
|
+
let { plan, state } = input;
|
|
306
|
+
let text = serializePlan(plan);
|
|
307
|
+
let invalid: string[] = [];
|
|
308
|
+
const show = () =>
|
|
309
|
+
host.sendMessage(
|
|
310
|
+
{ customType: MESSAGE_TYPES.plan, content: approvalMessage(input.planId, text, state, input.notes ?? [], input.advisory ?? [], invalid), details: { planId: input.planId, status: state.status, plan: paths.plan }, display: true },
|
|
311
|
+
false,
|
|
312
|
+
);
|
|
313
|
+
if (!host.hasUI) {
|
|
314
|
+
show();
|
|
315
|
+
host.notify(`Plan ${input.planId} is a draft. Approve it with /plan resume ${input.planId} in an interactive session.`, "info");
|
|
316
|
+
return "draft";
|
|
317
|
+
}
|
|
318
|
+
show();
|
|
319
|
+
for (;;) {
|
|
320
|
+
const options = invalid.length > 0 ? [EDIT, REVISE, KEEP, DISCARD] : [APPROVE, EDIT, REVISE, KEEP, DISCARD];
|
|
321
|
+
const unresolved = state.planning.unresolved.length;
|
|
322
|
+
const choice = await host.select(
|
|
323
|
+
`Plan ${input.planId}${invalid.length > 0 ? " (does not validate)" : ""}${unresolved > 0 ? ` · ${unresolved} unresolved blocking finding(s)` : ""}`,
|
|
324
|
+
options,
|
|
325
|
+
);
|
|
326
|
+
ensureAlive(deps);
|
|
327
|
+
if (choice === APPROVE) {
|
|
328
|
+
state.status = "approved";
|
|
329
|
+
await saveState(paths.state, state, "approved");
|
|
330
|
+
return "approved";
|
|
331
|
+
}
|
|
332
|
+
if (choice === EDIT) {
|
|
333
|
+
const edited = await host.editor(`Edit plan ${input.planId}`, text);
|
|
334
|
+
ensureAlive(deps);
|
|
335
|
+
if (edited === undefined) continue;
|
|
336
|
+
text = edited;
|
|
337
|
+
const parsed = parsePlan(edited);
|
|
338
|
+
if (parsed.plan && parsed.plan.id !== input.planId) parsed.errors.push(`front matter: id must stay "${input.planId}"`);
|
|
339
|
+
if (parsed.plan && parsed.errors.length === 0) {
|
|
340
|
+
plan = parsed.plan;
|
|
341
|
+
state = syncState(state, plan);
|
|
342
|
+
text = serializePlan(plan);
|
|
343
|
+
invalid = [];
|
|
344
|
+
await savePlanFile(paths.plan, text);
|
|
345
|
+
await saveState(paths.state, state, "edited by the user");
|
|
346
|
+
} else {
|
|
347
|
+
invalid = parsed.errors;
|
|
348
|
+
await savePlanFile(paths.plan, edited);
|
|
349
|
+
host.notify(`The edited plan does not validate:\n${invalid.map((error) => `- ${error}`).join("\n")}`, "error");
|
|
350
|
+
}
|
|
351
|
+
show();
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
if (choice === REVISE) {
|
|
355
|
+
const comments = await host.editor(`Revision request for plan ${input.planId}`, "");
|
|
356
|
+
ensureAlive(deps);
|
|
357
|
+
if (!comments?.trim()) continue;
|
|
358
|
+
const controller = new AbortController();
|
|
359
|
+
const registered = deps.registry.listWorkflows().some((entry) => entry.id === input.planId);
|
|
360
|
+
if (!registered) deps.registry.addWorkflow({ id: input.planId, kind: "plan", header: "plan · user revision", controller });
|
|
361
|
+
try {
|
|
362
|
+
const session = input.session ?? new PlannerSession(deps, await resolveRole(deps, "planner", false), input.planId, controller.signal);
|
|
363
|
+
input.session = session;
|
|
364
|
+
const revised = await obtainPlan(
|
|
365
|
+
deps,
|
|
366
|
+
session,
|
|
367
|
+
templates.render("planUserRevise", { comments, planFormat: templates.render("planFormat", { planId: input.planId }) }),
|
|
368
|
+
`${input.context}\n\n## Your current plan\n\n${text}`,
|
|
369
|
+
input.planId,
|
|
370
|
+
"planner · user revision",
|
|
371
|
+
);
|
|
372
|
+
plan = revised.plan;
|
|
373
|
+
state = syncState(state, plan);
|
|
374
|
+
text = serializePlan(plan);
|
|
375
|
+
invalid = [];
|
|
376
|
+
await savePlanFile(paths.plan, text);
|
|
377
|
+
await saveState(paths.state, state, "revised on request");
|
|
378
|
+
} catch (error) {
|
|
379
|
+
host.notify(`The revision failed: ${errorText(error)}`, "error");
|
|
380
|
+
} finally {
|
|
381
|
+
if (!registered) deps.registry.removeWorkflow(input.planId);
|
|
382
|
+
}
|
|
383
|
+
ensureAlive(deps);
|
|
384
|
+
show();
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
if (choice === DISCARD) {
|
|
388
|
+
state.status = "aborted";
|
|
389
|
+
await saveState(paths.state, state, "discarded");
|
|
390
|
+
host.notify(`Plan ${input.planId} discarded. Its files stay in ${paths.dir}.`, "info");
|
|
391
|
+
return "discarded";
|
|
392
|
+
}
|
|
393
|
+
host.notify(`Plan ${input.planId} kept as a draft. Continue with /plan resume ${input.planId}.`, "info");
|
|
394
|
+
return "draft";
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function approvalMessage(planId: string, text: string, state: PlanState, notes: string[], advisory: Finding[], invalid: string[]): string {
|
|
399
|
+
const parts = [`Plan ${planId} is ready for approval. Nothing runs before the user approves it.`, "", text.trim()];
|
|
400
|
+
if (invalid.length > 0) parts.push("", "## The edited plan does not validate", "", ...invalid.map((error) => `- ${error}`));
|
|
401
|
+
if (state.planning.unresolved.length > 0) parts.push("", "## Unresolved blocking findings", "", formatFindings(state.planning.unresolved));
|
|
402
|
+
const rejected = state.planning.dispositions.filter((entry) => entry.disposition === "rejected");
|
|
403
|
+
if (rejected.length > 0) parts.push("", "## Findings the planner rejected", "", ...rejected.map((entry) => `- ${entry.finding}: ${entry.reason ?? "(no reason)"}`));
|
|
404
|
+
if (advisory.length > 0) parts.push("", "## Advisory findings", "", formatFindings(advisory));
|
|
405
|
+
if (notes.length > 0) parts.push("", "## Notes", "", ...notes.map((note) => `- ${note}`));
|
|
406
|
+
return fitParts([{ title: `Plan ${planId}`, text: parts.join("\n") }]);
|
|
407
|
+
}
|