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,380 @@
|
|
|
1
|
+
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
|
|
2
|
+
import { ROLE_NAMES } from "../config/schema.ts";
|
|
3
|
+
import { normalizeScope } from "../engine/verify.ts";
|
|
4
|
+
|
|
5
|
+
export const PLAN_ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
|
|
6
|
+
|
|
7
|
+
export interface PlanStep {
|
|
8
|
+
id: string; // "1.2"
|
|
9
|
+
title: string;
|
|
10
|
+
depends: string[];
|
|
11
|
+
scope: string[];
|
|
12
|
+
acceptance: string;
|
|
13
|
+
role?: string;
|
|
14
|
+
profile?: string;
|
|
15
|
+
validation: string[];
|
|
16
|
+
body: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface PlanBlock {
|
|
20
|
+
id: string; // "1"
|
|
21
|
+
title: string;
|
|
22
|
+
acceptance: string;
|
|
23
|
+
validation: string[];
|
|
24
|
+
body: string;
|
|
25
|
+
steps: PlanStep[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface PlanDocument {
|
|
29
|
+
id: string;
|
|
30
|
+
goal: string;
|
|
31
|
+
context: string;
|
|
32
|
+
blocks: PlanBlock[];
|
|
33
|
+
risks: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface PlanParseResult {
|
|
37
|
+
plan?: PlanDocument;
|
|
38
|
+
errors: string[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const BLOCK_HEADING = /^##\s+Block\s+(\S+?)\s*:\s*(.+?)\s*$/i;
|
|
42
|
+
const STEP_HEADING = /^###\s+Step\s+(\S+?)\s*:\s*(.+?)\s*$/i;
|
|
43
|
+
const SECTION_HEADING = /^##\s+(.+?)\s*$/;
|
|
44
|
+
const ATTRIBUTE = /^[-*]\s+([A-Za-z][\w-]*)\s*:\s*(.*)$/;
|
|
45
|
+
|
|
46
|
+
const BLOCK_KEYS = new Set(["acceptance", "validation"]);
|
|
47
|
+
const STEP_KEYS = new Set(["depends", "scope", "acceptance", "role", "profile", "validation"]);
|
|
48
|
+
|
|
49
|
+
/** Pulls the plan document out of a planner's final answer (fenced or bare, with trailing JSON blocks removed). */
|
|
50
|
+
export function extractPlanDocument(answer: string): string {
|
|
51
|
+
const fences = fencedCandidates(answer).filter((content) => /^##\s+Block\s/im.test(content));
|
|
52
|
+
if (fences.length > 0) {
|
|
53
|
+
const valid = fences.find((content) => parsePlan(content).errors.length === 0);
|
|
54
|
+
return (valid ?? fences.sort((a, b) => b.length - a.length)[0]).trim();
|
|
55
|
+
}
|
|
56
|
+
let text = answer;
|
|
57
|
+
const start = text.search(/^---\s*$/m);
|
|
58
|
+
if (start > 0 && /^---\s*\n[\s\S]*?\bid\s*:/m.test(text.slice(start))) text = text.slice(start);
|
|
59
|
+
// Drop trailing JSON blocks (dispositions) after the document.
|
|
60
|
+
text = text.replace(/(?:\n```json[\s\S]*?```\s*)+$/i, "\n");
|
|
61
|
+
return text.trim();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Contents of the fenced blocks tagged markdown/md (or untagged) at the top level of an answer. A plan holds fences of
|
|
66
|
+
* its own, so a fence closes the outer block only when it is at least as long and nesting is balanced: an inner fence
|
|
67
|
+
* with an info string opens a level, a bare fence closes one. The greedy variant (to the last closing fence) is added
|
|
68
|
+
* as a second candidate for untagged inner fences.
|
|
69
|
+
*/
|
|
70
|
+
function fencedCandidates(answer: string): string[] {
|
|
71
|
+
const lines = answer.split("\n");
|
|
72
|
+
const result: string[] = [];
|
|
73
|
+
for (let index = 0; index < lines.length; index++) {
|
|
74
|
+
const open = lines[index].match(/^(`{3,}|~{3,})[ \t]*([^\s`]*)[ \t]*$/);
|
|
75
|
+
if (!open) continue;
|
|
76
|
+
const fence = open[1];
|
|
77
|
+
if (open[2] && !/^(markdown|md)$/i.test(open[2])) {
|
|
78
|
+
// A code block of another language at the top level: skip to its end.
|
|
79
|
+
const close = lines.findIndex((line, at) => at > index && line.startsWith(fence) && line.trim() === line.trim().replace(/[^`~]/g, ""));
|
|
80
|
+
if (close > 0) index = close;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
let depth = 0;
|
|
84
|
+
let end = -1;
|
|
85
|
+
let lastClose = -1;
|
|
86
|
+
for (let inner = index + 1; inner < lines.length; inner++) {
|
|
87
|
+
const line = lines[inner];
|
|
88
|
+
const marker = line.match(/^(`{3,}|~{3,})(.*)$/);
|
|
89
|
+
if (!marker || marker[1][0] !== fence[0]) continue;
|
|
90
|
+
const bare = marker[2].trim() === "";
|
|
91
|
+
if (bare && marker[1].length >= fence.length) lastClose = inner;
|
|
92
|
+
if (!bare) depth++;
|
|
93
|
+
else if (depth > 0 && marker[1].length < fence.length + 1) depth--;
|
|
94
|
+
else if (marker[1].length >= fence.length && end < 0) end = inner;
|
|
95
|
+
}
|
|
96
|
+
if (end > 0) result.push(lines.slice(index + 1, end).join("\n"));
|
|
97
|
+
if (lastClose > 0 && lastClose !== end) result.push(lines.slice(index + 1, lastClose).join("\n"));
|
|
98
|
+
if (end > 0) index = end;
|
|
99
|
+
}
|
|
100
|
+
return result;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Parses and validates a plan document. */
|
|
104
|
+
export function parsePlan(text: string): PlanParseResult {
|
|
105
|
+
const errors: string[] = [];
|
|
106
|
+
const normalized = text.replace(/\r\n/g, "\n").trim();
|
|
107
|
+
const frontMatter = normalized.match(/^---\n([\s\S]*?)\n---\s*(?:\n|$)/);
|
|
108
|
+
let id = "";
|
|
109
|
+
let goal = "";
|
|
110
|
+
let body = normalized;
|
|
111
|
+
if (!frontMatter) {
|
|
112
|
+
errors.push("missing front matter (--- id: ... goal: ... ---) at the top of the document");
|
|
113
|
+
} else {
|
|
114
|
+
body = normalized.slice(frontMatter[0].length);
|
|
115
|
+
let meta: unknown;
|
|
116
|
+
try {
|
|
117
|
+
meta = parseYaml(frontMatter[1]);
|
|
118
|
+
} catch (error) {
|
|
119
|
+
errors.push(`front matter is not valid YAML: ${(error as Error).message.split("\n")[0]}`);
|
|
120
|
+
}
|
|
121
|
+
const record = (typeof meta === "object" && meta !== null ? meta : {}) as Record<string, unknown>;
|
|
122
|
+
id = typeof record.id === "string" ? record.id.trim() : "";
|
|
123
|
+
goal = typeof record.goal === "string" ? record.goal.trim() : "";
|
|
124
|
+
if (!id) errors.push("front matter: id is required");
|
|
125
|
+
else if (!PLAN_ID_PATTERN.test(id)) errors.push(`front matter: id "${id}" must match [a-z0-9][a-z0-9-]*`);
|
|
126
|
+
if (!goal) errors.push("front matter: goal is required");
|
|
127
|
+
for (const key of Object.keys(record)) {
|
|
128
|
+
if (key !== "id" && key !== "goal") errors.push(`front matter: unknown key "${key}"`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const blocks: PlanBlock[] = [];
|
|
133
|
+
let context = "";
|
|
134
|
+
let risks = "";
|
|
135
|
+
type Target = { kind: "context" } | { kind: "risks" } | { kind: "block"; block: PlanBlock; attributes: boolean } | { kind: "step"; step: PlanStep; attributes: boolean };
|
|
136
|
+
let target: Target | undefined;
|
|
137
|
+
const bodies = new Map<object, string[]>();
|
|
138
|
+
const appendBody = (owner: object, line: string) => {
|
|
139
|
+
const list = bodies.get(owner) ?? [];
|
|
140
|
+
list.push(line);
|
|
141
|
+
bodies.set(owner, list);
|
|
142
|
+
};
|
|
143
|
+
const contextOwner = {};
|
|
144
|
+
const risksOwner = {};
|
|
145
|
+
let inFence = false;
|
|
146
|
+
|
|
147
|
+
for (const [index, line] of body.split("\n").entries()) {
|
|
148
|
+
const lineNo = index + 1;
|
|
149
|
+
if (/^\s*(```|~~~)/.test(line)) inFence = !inFence;
|
|
150
|
+
if (!inFence) {
|
|
151
|
+
const step = line.match(STEP_HEADING);
|
|
152
|
+
if (step) {
|
|
153
|
+
const block = blocks.at(-1);
|
|
154
|
+
const newStep: PlanStep = { id: step[1], title: step[2], depends: [], scope: [], acceptance: "", validation: [], body: "" };
|
|
155
|
+
if (!block) errors.push(`line ${lineNo}: step ${step[1]} appears before any block`);
|
|
156
|
+
else block.steps.push(newStep);
|
|
157
|
+
target = { kind: "step", step: newStep, attributes: true };
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
const blockMatch = line.match(BLOCK_HEADING);
|
|
161
|
+
if (blockMatch) {
|
|
162
|
+
const block: PlanBlock = { id: blockMatch[1], title: blockMatch[2], acceptance: "", validation: [], body: "", steps: [] };
|
|
163
|
+
blocks.push(block);
|
|
164
|
+
target = { kind: "block", block, attributes: true };
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
const section = line.match(SECTION_HEADING);
|
|
168
|
+
if (section && !line.startsWith("###")) {
|
|
169
|
+
const name = section[1].toLowerCase();
|
|
170
|
+
if (name === "context") target = { kind: "context" };
|
|
171
|
+
else if (name === "risks") target = { kind: "risks" };
|
|
172
|
+
else errors.push(`line ${lineNo}: unknown section "## ${section[1]}" (expected Context, Block N: title, Risks)`);
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
if (!target) {
|
|
177
|
+
if (line.trim()) errors.push(`line ${lineNo}: text outside any section`);
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (target.kind === "context") appendBody(contextOwner, line);
|
|
181
|
+
else if (target.kind === "risks") appendBody(risksOwner, line);
|
|
182
|
+
else {
|
|
183
|
+
const attribute = !inFence && target.attributes ? line.match(ATTRIBUTE) : null;
|
|
184
|
+
if (attribute) {
|
|
185
|
+
const key = attribute[1].toLowerCase();
|
|
186
|
+
const value = attribute[2].trim();
|
|
187
|
+
if (target.kind === "block") applyBlockAttribute(target.block, key, value, errors, lineNo);
|
|
188
|
+
else applyStepAttribute(target.step, key, value, errors, lineNo);
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
if (line.trim()) target.attributes = false;
|
|
192
|
+
appendBody(target.kind === "block" ? target.block : target.step, line);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
context = (bodies.get(contextOwner) ?? []).join("\n").trim();
|
|
197
|
+
risks = (bodies.get(risksOwner) ?? []).join("\n").trim();
|
|
198
|
+
for (const block of blocks) {
|
|
199
|
+
block.body = (bodies.get(block) ?? []).join("\n").trim();
|
|
200
|
+
for (const step of block.steps) step.body = (bodies.get(step) ?? []).join("\n").trim();
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const plan: PlanDocument = { id, goal, context, blocks, risks };
|
|
204
|
+
errors.push(...validatePlan(plan));
|
|
205
|
+
return errors.length > 0 ? { errors } : { plan, errors };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function splitList(value: string): string[] {
|
|
209
|
+
return value
|
|
210
|
+
.split(",")
|
|
211
|
+
.map((entry) => entry.trim().replace(/^`|`$/g, ""))
|
|
212
|
+
.filter(Boolean);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function applyBlockAttribute(block: PlanBlock, key: string, value: string, errors: string[], lineNo: number): void {
|
|
216
|
+
if (!BLOCK_KEYS.has(key)) {
|
|
217
|
+
errors.push(`line ${lineNo}: block ${block.id}: unknown attribute "${key}" (allowed: acceptance, validation)`);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (key === "acceptance") block.acceptance = block.acceptance ? `${block.acceptance}; ${value}` : value;
|
|
221
|
+
else if (value) block.validation.push(value.replace(/^`|`$/g, ""));
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function applyStepAttribute(step: PlanStep, key: string, value: string, errors: string[], lineNo: number): void {
|
|
225
|
+
if (!STEP_KEYS.has(key)) {
|
|
226
|
+
errors.push(`line ${lineNo}: step ${step.id}: unknown attribute "${key}" (allowed: ${[...STEP_KEYS].join(", ")})`);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
switch (key) {
|
|
230
|
+
case "depends":
|
|
231
|
+
step.depends = /^(none|-|)$/i.test(value) ? [] : splitList(value);
|
|
232
|
+
break;
|
|
233
|
+
case "scope":
|
|
234
|
+
step.scope.push(...splitList(value));
|
|
235
|
+
break;
|
|
236
|
+
case "acceptance":
|
|
237
|
+
step.acceptance = step.acceptance ? `${step.acceptance}; ${value}` : value;
|
|
238
|
+
break;
|
|
239
|
+
case "role":
|
|
240
|
+
step.role = value;
|
|
241
|
+
break;
|
|
242
|
+
case "profile":
|
|
243
|
+
step.profile = value;
|
|
244
|
+
break;
|
|
245
|
+
case "validation":
|
|
246
|
+
if (value) step.validation.push(value.replace(/^`|`$/g, ""));
|
|
247
|
+
break;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Structural validation; returns error messages. Normalizes step scopes in place. */
|
|
252
|
+
export function validatePlan(plan: PlanDocument): string[] {
|
|
253
|
+
const errors: string[] = [];
|
|
254
|
+
if (plan.blocks.length === 0) errors.push("the plan has no blocks (## Block 1: title)");
|
|
255
|
+
const blockIndex = new Map<string, number>();
|
|
256
|
+
const stepBlock = new Map<string, number>();
|
|
257
|
+
for (const [index, block] of plan.blocks.entries()) {
|
|
258
|
+
if (blockIndex.has(block.id)) errors.push(`block ${block.id}: duplicate block id`);
|
|
259
|
+
blockIndex.set(block.id, index);
|
|
260
|
+
if (!block.acceptance) errors.push(`block ${block.id}: acceptance is required`);
|
|
261
|
+
if (block.steps.length === 0) errors.push(`block ${block.id}: needs at least one step`);
|
|
262
|
+
for (const step of block.steps) {
|
|
263
|
+
if (stepBlock.has(step.id)) errors.push(`step ${step.id}: duplicate step id`);
|
|
264
|
+
stepBlock.set(step.id, index);
|
|
265
|
+
if (!step.id.startsWith(`${block.id}.`)) errors.push(`step ${step.id}: id must start with its block id (${block.id}.)`);
|
|
266
|
+
if (!step.acceptance) errors.push(`step ${step.id}: acceptance is required`);
|
|
267
|
+
if (step.scope.length === 0) errors.push(`step ${step.id}: scope is required`);
|
|
268
|
+
const { scope, errors: scopeErrors } = normalizeScope(step.scope);
|
|
269
|
+
step.scope = scope;
|
|
270
|
+
for (const error of scopeErrors) errors.push(`step ${step.id}: ${error}`);
|
|
271
|
+
if (step.role !== undefined && !(ROLE_NAMES as readonly string[]).includes(step.role)) {
|
|
272
|
+
errors.push(`step ${step.id}: unknown role "${step.role}"`);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
for (const [index, block] of plan.blocks.entries()) {
|
|
277
|
+
for (const step of block.steps) {
|
|
278
|
+
for (const dependency of step.depends) {
|
|
279
|
+
const dependencyBlock = stepBlock.get(dependency);
|
|
280
|
+
if (dependencyBlock === undefined) errors.push(`step ${step.id}: depends on unknown step ${dependency}`);
|
|
281
|
+
else if (dependencyBlock > index) errors.push(`step ${step.id}: depends on step ${dependency} of a later block`);
|
|
282
|
+
if (dependency === step.id) errors.push(`step ${step.id}: depends on itself`);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
const cycle = findCycle(plan);
|
|
287
|
+
if (cycle) errors.push(`dependency cycle: ${cycle.join(" -> ")}`);
|
|
288
|
+
return errors;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function findCycle(plan: PlanDocument): string[] | undefined {
|
|
292
|
+
const graph = new Map<string, string[]>();
|
|
293
|
+
for (const step of allSteps(plan)) graph.set(step.id, step.depends.filter((id) => id !== step.id));
|
|
294
|
+
const state = new Map<string, "visiting" | "done">();
|
|
295
|
+
const stack: string[] = [];
|
|
296
|
+
const visit = (id: string): string[] | undefined => {
|
|
297
|
+
if (state.get(id) === "done") return undefined;
|
|
298
|
+
if (state.get(id) === "visiting") return [...stack.slice(stack.indexOf(id)), id];
|
|
299
|
+
state.set(id, "visiting");
|
|
300
|
+
stack.push(id);
|
|
301
|
+
for (const next of graph.get(id) ?? []) {
|
|
302
|
+
if (!graph.has(next)) continue;
|
|
303
|
+
const cycle = visit(next);
|
|
304
|
+
if (cycle) return cycle;
|
|
305
|
+
}
|
|
306
|
+
stack.pop();
|
|
307
|
+
state.set(id, "done");
|
|
308
|
+
return undefined;
|
|
309
|
+
};
|
|
310
|
+
for (const id of graph.keys()) {
|
|
311
|
+
const cycle = visit(id);
|
|
312
|
+
if (cycle) return cycle;
|
|
313
|
+
}
|
|
314
|
+
return undefined;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export function allSteps(plan: PlanDocument): PlanStep[] {
|
|
318
|
+
return plan.blocks.flatMap((block) => block.steps);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Steps of a block in dependency order, stable by document order. */
|
|
322
|
+
export function stepOrder(block: PlanBlock): PlanStep[] {
|
|
323
|
+
const ids = new Set(block.steps.map((step) => step.id));
|
|
324
|
+
const done = new Set<string>();
|
|
325
|
+
const ordered: PlanStep[] = [];
|
|
326
|
+
while (ordered.length < block.steps.length) {
|
|
327
|
+
const next = block.steps.find(
|
|
328
|
+
(step) => !done.has(step.id) && step.depends.every((dependency) => !ids.has(dependency) || done.has(dependency)),
|
|
329
|
+
);
|
|
330
|
+
if (!next) break; // A cycle; validation reports it.
|
|
331
|
+
ordered.push(next);
|
|
332
|
+
done.add(next.id);
|
|
333
|
+
}
|
|
334
|
+
return ordered;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** The block's combined scope (union of its steps' scopes). */
|
|
338
|
+
export function blockScope(block: PlanBlock): string[] {
|
|
339
|
+
return [...new Set(block.steps.flatMap((step) => step.scope))];
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export function serializePlan(plan: PlanDocument): string {
|
|
343
|
+
const lines: string[] = ["---", stringifyYaml({ id: plan.id, goal: plan.goal }).trim(), "---", "", "## Context"];
|
|
344
|
+
if (plan.context) lines.push(plan.context);
|
|
345
|
+
for (const block of plan.blocks) {
|
|
346
|
+
lines.push("", `## Block ${block.id}: ${block.title}`, `- acceptance: ${block.acceptance}`);
|
|
347
|
+
for (const validation of block.validation) lines.push(`- validation: ${validation}`);
|
|
348
|
+
if (block.body) lines.push("", block.body);
|
|
349
|
+
for (const step of block.steps) {
|
|
350
|
+
lines.push("", `### Step ${step.id}: ${step.title}`);
|
|
351
|
+
lines.push(`- depends: ${step.depends.length > 0 ? step.depends.join(", ") : "none"}`);
|
|
352
|
+
lines.push(`- scope: ${step.scope.join(", ")}`);
|
|
353
|
+
lines.push(`- acceptance: ${step.acceptance}`);
|
|
354
|
+
if (step.role) lines.push(`- role: ${step.role}`);
|
|
355
|
+
if (step.profile) lines.push(`- profile: ${step.profile}`);
|
|
356
|
+
for (const validation of step.validation) lines.push(`- validation: ${validation}`);
|
|
357
|
+
if (step.body) lines.push("", step.body);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
lines.push("", "## Risks");
|
|
361
|
+
if (plan.risks) lines.push(plan.risks);
|
|
362
|
+
return `${lines.join("\n")}\n`;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Makes a plan id from a goal: `<date>-<slug>`. */
|
|
366
|
+
export function planIdFor(goal: string, date = new Date()): string {
|
|
367
|
+
const day = date.toISOString().slice(0, 10);
|
|
368
|
+
const slug = goal
|
|
369
|
+
.toLowerCase()
|
|
370
|
+
.normalize("NFKD")
|
|
371
|
+
.replace(/[̀-ͯ]/g, "")
|
|
372
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
373
|
+
.replace(/^-+|-+$/g, "")
|
|
374
|
+
.split("-")
|
|
375
|
+
.slice(0, 6)
|
|
376
|
+
.join("-")
|
|
377
|
+
.slice(0, 48)
|
|
378
|
+
.replace(/-+$/g, "");
|
|
379
|
+
return `${day}-${slug || "plan"}`;
|
|
380
|
+
}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { Baseline } from "../engine/baseline.ts";
|
|
4
|
+
import { allSteps, parsePlan, type PlanDocument } from "./planfile.ts";
|
|
5
|
+
|
|
6
|
+
export type StepStatus = "pending" | "running" | "done" | "failed" | "interrupted" | "skipped";
|
|
7
|
+
export type BlockStatus = "pending" | "running" | "in_review" | "accepted" | "paused" | "skipped";
|
|
8
|
+
export type PlanStatus = "draft" | "approved" | "executing" | "paused" | "completed" | "completed_with_skips" | "aborted";
|
|
9
|
+
|
|
10
|
+
export interface Finding {
|
|
11
|
+
id: string; // "F1" for critique, "R1" for review
|
|
12
|
+
severity: "blocking" | "advisory";
|
|
13
|
+
summary: string;
|
|
14
|
+
evidence?: string;
|
|
15
|
+
file?: string;
|
|
16
|
+
line?: number;
|
|
17
|
+
block?: string;
|
|
18
|
+
source: string; // profile, or "verdict"
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface StepAttempt {
|
|
22
|
+
kind: "run" | "retry" | "fix";
|
|
23
|
+
runId?: string;
|
|
24
|
+
profile: string;
|
|
25
|
+
status: string;
|
|
26
|
+
reason?: string;
|
|
27
|
+
/** Clipped worker report; the full one is in the run's result.md while retention keeps it. */
|
|
28
|
+
summary: string;
|
|
29
|
+
changedFiles: string[];
|
|
30
|
+
outOfScope: string[];
|
|
31
|
+
at: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface StepState {
|
|
35
|
+
id: string;
|
|
36
|
+
status: StepStatus;
|
|
37
|
+
/** Profile that ran the step, and its session when it can be continued. */
|
|
38
|
+
profile?: string;
|
|
39
|
+
sessionId?: string;
|
|
40
|
+
baseline?: Baseline;
|
|
41
|
+
attempts: StepAttempt[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ReviewRecord {
|
|
45
|
+
attempt: number;
|
|
46
|
+
runId?: string;
|
|
47
|
+
profile?: string;
|
|
48
|
+
status: string;
|
|
49
|
+
reason?: string;
|
|
50
|
+
findings: Finding[];
|
|
51
|
+
/** Files of the frozen change set with their hashes. */
|
|
52
|
+
frozen: Record<string, string>;
|
|
53
|
+
reviewerChanges: string[];
|
|
54
|
+
summary: string;
|
|
55
|
+
at: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface VerdictRecord {
|
|
59
|
+
verdict: "accepted" | "needs_fix" | "blocked" | "none";
|
|
60
|
+
feedback: string;
|
|
61
|
+
at: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface BlockState {
|
|
65
|
+
id: string;
|
|
66
|
+
status: BlockStatus;
|
|
67
|
+
baseline?: Baseline;
|
|
68
|
+
fixAttempts: number;
|
|
69
|
+
outOfScope: string[];
|
|
70
|
+
reviews: ReviewRecord[];
|
|
71
|
+
verdicts: VerdictRecord[];
|
|
72
|
+
/** At acceptance: the files of the block and their hashes, and the commit when one was made. */
|
|
73
|
+
accepted?: { files: Record<string, string>; head?: string | null; commit?: string };
|
|
74
|
+
pauseReason?: string;
|
|
75
|
+
/** Where a paused block continues: another fix cycle, or review and verdict again. */
|
|
76
|
+
resumeAt?: "review" | "fix";
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface PlanState {
|
|
80
|
+
version: 1;
|
|
81
|
+
planId: string;
|
|
82
|
+
goal: string;
|
|
83
|
+
status: PlanStatus;
|
|
84
|
+
createdAt: string;
|
|
85
|
+
updatedAt: string;
|
|
86
|
+
pauseReason?: string;
|
|
87
|
+
/** Whether the tree was clean when execution started (required for per-block commits). */
|
|
88
|
+
startedClean?: boolean;
|
|
89
|
+
planning: { revisions: number; unresolved: Finding[]; dispositions: Array<{ finding: string; disposition: string; reason?: string }> };
|
|
90
|
+
blocks: Array<BlockState & { steps: StepState[] }>;
|
|
91
|
+
log: Array<{ at: string; event: string }>;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function plansDir(workspace: string, configDirName: string): string {
|
|
95
|
+
return join(workspace, configDirName, "master-orchestrator", "plans");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Workspace-relative prefix of the plans directory, excluded from change sets and commits. */
|
|
99
|
+
export function plansPrefix(configDirName: string): string {
|
|
100
|
+
return `${configDirName}/master-orchestrator/plans/`;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function planPaths(workspace: string, configDirName: string, planId: string) {
|
|
104
|
+
const dir = plansDir(workspace, configDirName);
|
|
105
|
+
return { dir, plan: join(dir, `${planId}.md`), state: join(dir, `${planId}.state.json`) };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function newState(plan: PlanDocument): PlanState {
|
|
109
|
+
const now = new Date().toISOString();
|
|
110
|
+
return {
|
|
111
|
+
version: 1,
|
|
112
|
+
planId: plan.id,
|
|
113
|
+
goal: plan.goal,
|
|
114
|
+
status: "draft",
|
|
115
|
+
createdAt: now,
|
|
116
|
+
updatedAt: now,
|
|
117
|
+
planning: { revisions: 0, unresolved: [], dispositions: [] },
|
|
118
|
+
blocks: plan.blocks.map((block) => ({
|
|
119
|
+
id: block.id,
|
|
120
|
+
status: "pending",
|
|
121
|
+
fixAttempts: 0,
|
|
122
|
+
outOfScope: [],
|
|
123
|
+
reviews: [],
|
|
124
|
+
verdicts: [],
|
|
125
|
+
steps: block.steps.map((step) => ({ id: step.id, status: "pending", attempts: [] })),
|
|
126
|
+
})),
|
|
127
|
+
log: [{ at: now, event: "created" }],
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Aligns the state with an edited plan: known ids keep their state, new ones start pending, removed ones go. */
|
|
132
|
+
export function syncState(state: PlanState, plan: PlanDocument): PlanState {
|
|
133
|
+
const blocks = plan.blocks.map((block) => {
|
|
134
|
+
const known = state.blocks.find((entry) => entry.id === block.id);
|
|
135
|
+
const steps = block.steps.map(
|
|
136
|
+
(step) => known?.steps.find((entry) => entry.id === step.id) ?? { id: step.id, status: "pending" as StepStatus, attempts: [] },
|
|
137
|
+
);
|
|
138
|
+
return known
|
|
139
|
+
? { ...known, steps }
|
|
140
|
+
: { id: block.id, status: "pending" as BlockStatus, fixAttempts: 0, outOfScope: [], reviews: [], verdicts: [], steps };
|
|
141
|
+
});
|
|
142
|
+
return { ...state, goal: plan.goal, blocks };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function stepState(state: PlanState, stepId: string): StepState | undefined {
|
|
146
|
+
for (const block of state.blocks) {
|
|
147
|
+
const step = block.steps.find((entry) => entry.id === stepId);
|
|
148
|
+
if (step) return step;
|
|
149
|
+
}
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function blockState(state: PlanState, blockId: string) {
|
|
154
|
+
return state.blocks.find((entry) => entry.id === blockId);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export async function saveState(path: string, state: PlanState, event?: string): Promise<void> {
|
|
158
|
+
state.updatedAt = new Date().toISOString();
|
|
159
|
+
if (event) {
|
|
160
|
+
state.log.push({ at: state.updatedAt, event });
|
|
161
|
+
if (state.log.length > 200) state.log.splice(0, state.log.length - 200);
|
|
162
|
+
}
|
|
163
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
164
|
+
await writeFile(temp, `${JSON.stringify(state, null, 2)}\n`);
|
|
165
|
+
await rename(temp, path);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export async function loadState(path: string): Promise<PlanState | undefined> {
|
|
169
|
+
try {
|
|
170
|
+
const state = JSON.parse(await readFile(path, "utf8")) as PlanState;
|
|
171
|
+
return state?.version === 1 ? state : undefined;
|
|
172
|
+
} catch {
|
|
173
|
+
return undefined;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export async function savePlanFile(path: string, text: string): Promise<void> {
|
|
178
|
+
await mkdir(join(path, ".."), { recursive: true });
|
|
179
|
+
await writeFile(path, text.endsWith("\n") ? text : `${text}\n`);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export interface StoredPlan {
|
|
183
|
+
id: string;
|
|
184
|
+
text: string;
|
|
185
|
+
plan?: PlanDocument;
|
|
186
|
+
errors: string[];
|
|
187
|
+
state?: PlanState;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export async function loadPlan(workspace: string, configDirName: string, planId: string): Promise<StoredPlan | undefined> {
|
|
191
|
+
const paths = planPaths(workspace, configDirName, planId);
|
|
192
|
+
let text: string;
|
|
193
|
+
try {
|
|
194
|
+
text = await readFile(paths.plan, "utf8");
|
|
195
|
+
} catch {
|
|
196
|
+
return undefined;
|
|
197
|
+
}
|
|
198
|
+
const parsed = parsePlan(text);
|
|
199
|
+
return { id: planId, text, plan: parsed.plan, errors: parsed.errors, state: await loadState(paths.state) };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Plans of the workspace, most recently updated first. */
|
|
203
|
+
export async function listPlans(workspace: string, configDirName: string): Promise<Array<{ id: string; state?: PlanState }>> {
|
|
204
|
+
let names: string[];
|
|
205
|
+
try {
|
|
206
|
+
names = await readdir(plansDir(workspace, configDirName));
|
|
207
|
+
} catch {
|
|
208
|
+
return [];
|
|
209
|
+
}
|
|
210
|
+
const ids = names.filter((name) => name.endsWith(".md")).map((name) => name.slice(0, -3));
|
|
211
|
+
const result = await Promise.all(
|
|
212
|
+
ids.map(async (id) => ({ id, state: await loadState(planPaths(workspace, configDirName, id).state) })),
|
|
213
|
+
);
|
|
214
|
+
return result.sort((a, b) => (b.state?.updatedAt ?? "").localeCompare(a.state?.updatedAt ?? ""));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export function planSummary(plan: PlanDocument, state: PlanState): string {
|
|
218
|
+
const lines = [`Plan ${state.planId}: ${state.status}${state.pauseReason ? ` (${state.pauseReason})` : ""}`, `Goal: ${plan.goal}`];
|
|
219
|
+
for (const block of plan.blocks) {
|
|
220
|
+
const bs = blockState(state, block.id);
|
|
221
|
+
lines.push(`Block ${block.id} [${bs?.status ?? "pending"}] ${block.title}`);
|
|
222
|
+
for (const step of block.steps) lines.push(` Step ${step.id} [${stepState(state, step.id)?.status ?? "pending"}] ${step.title}`);
|
|
223
|
+
}
|
|
224
|
+
return lines.join("\n");
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export function countSteps(plan: PlanDocument): number {
|
|
228
|
+
return allSteps(plan).length;
|
|
229
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
export type Verdict = "accepted" | "needs_fix" | "blocked";
|
|
2
|
+
|
|
3
|
+
export interface VerdictSubmission {
|
|
4
|
+
blockId: string;
|
|
5
|
+
verdict: Verdict;
|
|
6
|
+
feedback: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
interface Pending {
|
|
10
|
+
planId: string;
|
|
11
|
+
blockId: string;
|
|
12
|
+
reminded: boolean;
|
|
13
|
+
resolve: (value: VerdictSubmission | undefined) => void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Connects an executing plan with the plan_verdict tool. The plan waits in `expect`; the tool calls `submit`;
|
|
18
|
+
* `settled` runs when the pi agent goes idle and decides between one reminder and a pause.
|
|
19
|
+
*/
|
|
20
|
+
export class VerdictBroker {
|
|
21
|
+
private pending: Pending | undefined;
|
|
22
|
+
|
|
23
|
+
get waiting(): { planId: string; blockId: string } | undefined {
|
|
24
|
+
return this.pending ? { planId: this.pending.planId, blockId: this.pending.blockId } : undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
expect(planId: string, blockId: string, signal: AbortSignal): Promise<VerdictSubmission | undefined> {
|
|
28
|
+
this.pending?.resolve(undefined);
|
|
29
|
+
return new Promise((resolve) => {
|
|
30
|
+
const onAbort = () => {
|
|
31
|
+
if (this.pending?.resolve === finish) this.pending = undefined;
|
|
32
|
+
resolve(undefined);
|
|
33
|
+
};
|
|
34
|
+
const finish = (value: VerdictSubmission | undefined) => {
|
|
35
|
+
signal.removeEventListener("abort", onAbort);
|
|
36
|
+
if (this.pending?.resolve === finish) this.pending = undefined;
|
|
37
|
+
resolve(value);
|
|
38
|
+
};
|
|
39
|
+
this.pending = { planId, blockId, reminded: false, resolve: finish };
|
|
40
|
+
if (signal.aborted) onAbort();
|
|
41
|
+
else signal.addEventListener("abort", onAbort, { once: true });
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Called by the tool. Returns the text for the tool result. */
|
|
46
|
+
submit(submission: VerdictSubmission): { ok: boolean; message: string } {
|
|
47
|
+
const pending = this.pending;
|
|
48
|
+
if (!pending) return { ok: false, message: "No block is waiting for a verdict. Do not call plan_verdict again." };
|
|
49
|
+
if (pending.blockId !== submission.blockId) {
|
|
50
|
+
return { ok: false, message: `Block ${pending.blockId} of plan ${pending.planId} is waiting for the verdict, not block ${submission.blockId}.` };
|
|
51
|
+
}
|
|
52
|
+
if (submission.verdict !== "accepted" && !submission.feedback.trim()) {
|
|
53
|
+
return { ok: false, message: `A ${submission.verdict} verdict needs feedback that says what must change or what blocks the block.` };
|
|
54
|
+
}
|
|
55
|
+
pending.resolve(submission);
|
|
56
|
+
return { ok: true, message: `Verdict "${submission.verdict}" recorded for block ${submission.blockId} of plan ${pending.planId}. The plan continues in the background; end your turn.` };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The agent went idle without a verdict: "remind" once, then "pause" (the plan is released with no verdict). */
|
|
60
|
+
settled(): "remind" | "pause" | undefined {
|
|
61
|
+
const pending = this.pending;
|
|
62
|
+
if (!pending) return undefined;
|
|
63
|
+
if (!pending.reminded) {
|
|
64
|
+
pending.reminded = true;
|
|
65
|
+
return "remind";
|
|
66
|
+
}
|
|
67
|
+
pending.resolve(undefined);
|
|
68
|
+
return "pause";
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
cancel(): void {
|
|
72
|
+
this.pending?.resolve(undefined);
|
|
73
|
+
}
|
|
74
|
+
}
|