faberun 0.8.0 → 0.9.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.
@@ -9,10 +9,11 @@
9
9
  * Nothing here invokes a model or the engine; it only writes and hashes
10
10
  * bytes, so freezing a plan can never be mistaken for starting a run.
11
11
  */
12
- import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
12
+ import { mkdirSync, readFileSync, rmSync } from "node:fs";
13
13
  import { join } from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import { CONTRACT_VERSION, PROTOCOL_SCHEMA_VERSION, contractDigest, validateContract } from "../contract/index.mjs";
16
+ import { writeJsonAtomic } from "../run/store.mjs";
16
17
 
17
18
  /** @typedef {import("../contract/index.mjs").JsonObject} JsonObject */
18
19
 
@@ -55,7 +56,7 @@ export function freezePlan(plan, { outDir, provenance }) {
55
56
  contractVersion: CONTRACT_VERSION,
56
57
  ...plan,
57
58
  });
58
- writeFileSync(contractPath, `${JSON.stringify(raw, null, 2)}\n`);
59
+ writeJsonAtomic(contractPath, raw);
59
60
  try {
60
61
  validateContract(raw, contractPath);
61
62
  } catch (error) {
@@ -76,7 +77,10 @@ export function freezePlan(plan, { outDir, provenance }) {
76
77
  findings: provenance.findings,
77
78
  },
78
79
  });
79
- writeFileSync(join(outDir, "plan.json"), `${JSON.stringify(frozen, null, 2)}\n`);
80
+ // Atomic: the pipeline rewrites this file with its status straight after, and a
81
+ // reader polling for the frozen plan must never see a torn or half-written one
82
+ // (measured 2026-09-17: eval case D25 read a statusless plan.json on a slow runner).
83
+ writeJsonAtomic(join(outDir, "plan.json"), frozen);
80
84
  return frozen;
81
85
  }
82
86
 
@@ -0,0 +1,371 @@
1
+ /**
2
+ * The planning pipeline: `faberun plan` as successive ordinary runs (draft,
3
+ * review, revise up to a round budget) followed by the deterministic stages
4
+ * (sizing, routing, freeze), never as one long-lived process. Separate from
5
+ * `template.mjs` (which only builds the one-node contracts) and from
6
+ * `freeze.mjs` (which only turns a plan into a validated contract on disk):
7
+ * this module is the one place that sequences those runs, decides when a
8
+ * plan is contested instead of frozen, and records the operator-approval
9
+ * open-question. `launch` and `wait` are the only two seams that touch a
10
+ * process or the wall clock, so a test drives the whole pipeline through
11
+ * `runContract` in-process, deterministically.
12
+ */
13
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
14
+ import { dirname, join, relative, resolve } from "node:path";
15
+ import { validateContract } from "../contract/index.mjs";
16
+ import { discoveryOutput } from "../contract/worker-result.mjs";
17
+ import { readWorkerResultFile } from "../engine/result-file.mjs";
18
+ import { classifyRunProgress } from "../campaign/chain.mjs";
19
+ import { campaignDir } from "../campaign/layout.mjs";
20
+ import { appendSeatAllowanceEvent, readJournal } from "../campaign/journal.mjs";
21
+ import { readCampaign } from "../campaign/record.mjs";
22
+ import { campaignCli } from "../cli/campaign.mjs";
23
+ import { appendJsonl, writeJsonAtomic } from "../run/store.mjs";
24
+ import { allowanceDelta, allowanceEventFields, sampleAllowance } from "../seat/allowance.mjs";
25
+ import { validateSpec } from "./spec.mjs";
26
+ import { collectRepoFacts } from "./repo-facts.mjs";
27
+ import { RISK_TIERS, buildPlanningContract, validateFindings, validatePlanOutput } from "./template.mjs";
28
+ import { applySizingRules } from "./sizing.mjs";
29
+ import { resolveRuntimes } from "./routing.mjs";
30
+ import { freezePlan } from "./freeze.mjs";
31
+
32
+ /** @typedef {import("../contract/index.mjs").JsonObject} JsonObject */
33
+ /** @typedef {import("../contract/index.mjs").ValidatedContract} ValidatedContract */
34
+ /** @typedef {import("./template.mjs").PlanOutput} PlanOutput */
35
+ /** @typedef {import("./template.mjs").PlanFindingOutput} PlanFindingOutput */
36
+ /** @typedef {import("./sizing.mjs").PlanNode & {objective: string}} SizedPlanNode */
37
+ /** @typedef {"standard"|"high"|"none"} ApproveBelow */
38
+ /** @typedef {(contractPath: string, contract: ValidatedContract) => Promise<void>|void} LaunchFn */
39
+ /** @typedef {(runDir: string) => Promise<import("../engine/supervise.mjs").RunProgress>|import("../engine/supervise.mjs").RunProgress} WaitFn */
40
+ /** @typedef {{status: "frozen", plansDir: string, planPath: string, contractPath: string, approved: boolean, findings: PlanFindingOutput[]}} FrozenPipelineResult */
41
+ /** @typedef {{status: "contested", plansDir: string, planPath: string, findings: PlanFindingOutput[], round: number}} ContestedPipelineResult */
42
+
43
+ /**
44
+ * The session id every automated journal entry this pipeline writes carries.
45
+ * There is no human session behind a `plan` invocation, so a fixed id names
46
+ * the writer the same way `src/web/api.mjs`'s `WEB_SESSION_ID` names the web
47
+ * surface's own automated writes.
48
+ */
49
+ export const PLANNER_SESSION_ID = "planner";
50
+
51
+ /**
52
+ * No taskKind/riskTier row is opinionated by default: absent an operator
53
+ * `--runtime-defaults` instruction, every sized node routes through plain
54
+ * availability discovery (`resolveRuntimes`'s cheapest worker, strongest
55
+ * cross-vendor judge). A default table cannot safely name a `prefer` runtime
56
+ * id without knowing the operator's own catalogue, so "small default" here
57
+ * means empty rather than guessed.
58
+ */
59
+ export const DEFAULT_ROUTING_TABLE = /** @type {import("./routing.mjs").RoutingRule[]} */ ([]);
60
+
61
+ /** The sizing budget a frozen node's verification is measured against, absent a project-specific one. */
62
+ export const DEFAULT_NODE_BUDGET_MS = 600_000;
63
+
64
+ const APPROVE_BELOW_VALUES = new Set(["standard", "high", "none"]);
65
+
66
+ /**
67
+ * @param {{specPath: string, campaignId: string, phase: string, cwd?: string, reviewRounds?: number, approveBelow?: ApproveBelow, runtimeDefaults?: {worker?: string, judge?: string}, runtimes: Record<string, JsonObject>, launch: LaunchFn, wait: WaitFn}} options
68
+ * @returns {Promise<FrozenPipelineResult|ContestedPipelineResult>}
69
+ */
70
+ export async function runPlanningPipeline(options) {
71
+ const {
72
+ specPath, campaignId, phase, runtimes, launch, wait,
73
+ reviewRounds = 2, runtimeDefaults = {},
74
+ } = options;
75
+ const approveBelow = /** @type {ApproveBelow} */ (options.approveBelow ?? "standard");
76
+ if (!APPROVE_BELOW_VALUES.has(approveBelow)) throw new TypeError(`approveBelow must be one of ${[...APPROVE_BELOW_VALUES].join(", ")}`);
77
+ if (typeof launch !== "function") throw new TypeError("runPlanningPipeline requires a launch seam");
78
+ if (typeof wait !== "function") throw new TypeError("runPlanningPipeline requires a wait seam");
79
+ const cwd = resolve(options.cwd ?? ".");
80
+
81
+ const campaignPath = campaignDir(join(cwd, ".runs"), campaignId);
82
+ const campaign = readCampaign(campaignPath);
83
+ if (campaign.status !== "active") throw new Error(`campaign is closed: ${campaignId}`);
84
+
85
+ const relativeSpecPath = repoRelativePath(cwd, specPath, "specPath");
86
+ const specText = readFileSync(resolve(cwd, relativeSpecPath), "utf8");
87
+ const specValidation = validateSpec(specText, { cwd, strict: true });
88
+ if (specValidation.class === "structured" && !specValidation.ok) {
89
+ const detail = specValidation.findings.map((finding) => `${finding.rule}: ${finding.message}`).join("; ");
90
+ throw new Error(`spec ${specPath} fails strict traceability: ${detail}`);
91
+ }
92
+
93
+ const plansDir = join(cwd, ".runs", "campaigns", campaignId, "plans", phase);
94
+ mkdirSync(plansDir, { recursive: true });
95
+ const pipelineLog = join(plansDir, "pipeline.jsonl");
96
+ /** @param {string} stage @param {Record<string, unknown>} [extra] */
97
+ const logStage = (stage, extra = {}) => appendJsonl(pipelineLog, {
98
+ type: "plan.stage", at: new Date().toISOString(), campaignId, phase, stage, ...extra,
99
+ });
100
+
101
+ const repoFacts = collectRepoFacts(cwd);
102
+ const repoFactsPath = join(plansDir, "repo-facts.json");
103
+ writeFileSync(repoFactsPath, `${JSON.stringify(repoFacts, null, 2)}\n`);
104
+ const relativeRepoFactsPath = relative(cwd, repoFactsPath);
105
+ logStage("repo-facts", { gitHead: repoFacts.gitHead });
106
+
107
+ let n = 0;
108
+ const nextN = () => { n += 1; return n; };
109
+
110
+ /**
111
+ * Build, validate, persist, launch and wait for one planning contract, and
112
+ * return the discovery `output` its worker recorded. Every stage the
113
+ * pipeline runs is an ordinary run: it lands in `usage.jsonl` exactly like
114
+ * any other node, and this is the only place that reads its result back.
115
+ *
116
+ * @param {import("./template.mjs").PlanningKind} kind
117
+ * @param {Record<string, unknown>} inputs
118
+ * @returns {Promise<{contract: ValidatedContract, output: Record<string, unknown>}>}
119
+ */
120
+ const runStage = async (kind, inputs) => {
121
+ const stageN = nextN();
122
+ const contractPath = join(plansDir, "nodes", `${kind}-${stageN}.contract.json`);
123
+ mkdirSync(dirname(contractPath), { recursive: true });
124
+ const relativeCwd = relative(dirname(contractPath), cwd) || ".";
125
+ const raw = buildPlanningContract(kind, {
126
+ campaignId, phase, n: stageN, runtimes, runtimeDefaults, cwd: relativeCwd, ...inputs,
127
+ });
128
+ const validated = validateContract(raw, contractPath);
129
+ writeFileSync(contractPath, `${JSON.stringify(raw, null, 2)}\n`);
130
+ await launch(contractPath, validated);
131
+ const runDir = join(validated.cwd, ".runs", validated.id);
132
+ const progress = await wait(runDir);
133
+ const classification = classifyRunProgress(progress);
134
+ if (classification !== "succeeded") {
135
+ throw new Error(`planning stage ${kind} did not succeed: run ${validated.id} ${classification}`);
136
+ }
137
+ const result = readWorkerResultFile(runDir, kind);
138
+ const output = result ? discoveryOutput(result) : null;
139
+ if (!output) throw new Error(`planning stage ${kind}: run ${validated.id} recorded no discovery output`);
140
+ return { contract: validated, output };
141
+ };
142
+
143
+ const draft = await runStage("draft", { specPath: relativeSpecPath, repoFactsPath: relativeRepoFactsPath });
144
+ let plan = validatePlanOutput(draft.output.plan);
145
+ logStage("draft", { runId: draft.contract.id, nodeCount: plan.nodes.length });
146
+
147
+ const workingPlanPath = join(plansDir, "plan.working.json");
148
+ writeJsonAtomic(workingPlanPath, plan);
149
+ const relativeWorkingPlanPath = relative(cwd, workingPlanPath);
150
+
151
+ /** @type {PlanFindingOutput[]} */
152
+ let findings = [];
153
+ for (let round = 1; round <= reviewRounds; round += 1) {
154
+ const review = await runStage("review", { specPath: relativeSpecPath, repoFactsPath: relativeRepoFactsPath, planPath: relativeWorkingPlanPath });
155
+ findings = validateFindings(review.output.findings);
156
+ const criticalFindings = findings.filter((finding) => finding.severity === "critical");
157
+ logStage("review", { round, runId: review.contract.id, findingsCount: findings.length, criticalCount: criticalFindings.length });
158
+ if (criticalFindings.length === 0) break;
159
+ if (round === reviewRounds) {
160
+ const planPath = join(plansDir, "plan.json");
161
+ writeJsonAtomic(planPath, { formatVersion: 1, status: "contested", rounds: round, findings });
162
+ logStage("contested", { round, criticalCount: criticalFindings.length });
163
+ await campaignCli([
164
+ "note", campaignId, "--cwd", cwd, "--session-id", PLANNER_SESSION_ID,
165
+ "--kind", "open-question", "--question-id", `plan-${phase}-contested`,
166
+ "--text", `Plan for phase ${phase} is contested after ${round} review round(s): ${criticalFindings.map((finding) => finding.text).join("; ")}`,
167
+ ]);
168
+ return { status: "contested", plansDir, planPath, findings, round };
169
+ }
170
+ const findingsPath = join(plansDir, `findings-round-${round}.json`);
171
+ writeJsonAtomic(findingsPath, findings);
172
+ const revise = await runStage("revise", {
173
+ specPath: relativeSpecPath, repoFactsPath: relativeRepoFactsPath, findingsPath: relative(cwd, findingsPath),
174
+ });
175
+ plan = validatePlanOutput(revise.output.plan);
176
+ writeJsonAtomic(workingPlanPath, plan);
177
+ logStage("revise", { round, runId: revise.contract.id });
178
+ }
179
+
180
+ const sizing = applySizingRules(
181
+ { nodes: plan.nodes.map(toSizingNode), justification: plan.justification },
182
+ { nodeBudgetMs: DEFAULT_NODE_BUDGET_MS, facts: repoFacts },
183
+ );
184
+ logStage("sizing", { transformations: sizing.transformations.length, nodeCount: sizing.plan.nodes.length });
185
+
186
+ const routingRuntimes = /** @type {Record<string, import("./routing.mjs").RoutingRuntime>} */ (runtimes);
187
+ const routing = resolveRuntimes(sizing.plan.nodes, {
188
+ table: [...DEFAULT_ROUTING_TABLE],
189
+ runtimes: routingRuntimes,
190
+ availability: availabilityOf(runtimes),
191
+ runtimeDefaults,
192
+ });
193
+ logStage("routing", { assignments: Object.keys(routing.assignments).length });
194
+
195
+ const highestRiskTier = highestOf(sizing.plan.nodes.map((node) => node.riskTier ?? RISK_TIERS[0]));
196
+ const nodes = sizing.plan.nodes.map((node) => toContractNode(/** @type {SizedPlanNode} */ (node), phase, routing.assignments[node.id]));
197
+ const frozen = freezePlan({
198
+ id: `${campaignId}-${phase}`,
199
+ campaignId,
200
+ goal: campaign.goal,
201
+ // `freezePlan` writes contract.json inside `outDir` (`plansDir`), so `cwd`
202
+ // has to point back at the repo root from there, exactly like `runStage`
203
+ // computes it for the nodes it writes under `plansDir/nodes/`.
204
+ cwd: relative(plansDir, cwd) || ".",
205
+ runtimes,
206
+ runtimeDefaults,
207
+ nodes,
208
+ }, {
209
+ outDir: plansDir,
210
+ provenance: {
211
+ targetGitHead: repoFacts.gitHead,
212
+ planner: { runtimeId: runtimeDefaults.worker ?? "", model: modelOf(runtimes, runtimeDefaults.worker) },
213
+ reviewer: { runtimeId: runtimeDefaults.judge ?? "", model: modelOf(runtimes, runtimeDefaults.judge) },
214
+ sizing: sizing.transformations,
215
+ findings,
216
+ },
217
+ });
218
+ logStage("freeze", { contractId: `${campaignId}-${phase}`, highestRiskTier });
219
+
220
+ // A delta only means something between two samples of the same seat: freeze
221
+ // re-samples the exact harness `campaign init` recorded at `sample: "start"`
222
+ // (the operator's own seat), not the plan's worker runtime, which is very
223
+ // often a different harness entirely (codex, dsh, agy, zcode workers under
224
+ // a claude operator) and would make the delta null in the common case
225
+ // instead of the rare one. With no start entry at all (a pipeline run with
226
+ // no preceding `campaign init`, as in every replay-driven pipeline test)
227
+ // there is no seat to re-sample, so freeze samples nothing and spends no
228
+ // call.
229
+ const journalEntries = /** @type {any[]} */ (readJournal(campaignPath));
230
+ const startEntry = journalEntries.findLast((entry) => entry.type === "seat.allowance" && entry.sample === "start");
231
+ const freezeHarness = startEntry?.harness ?? null;
232
+ const freezeAllowance = await sampleAllowance({ harness: freezeHarness });
233
+ const startAllowance = startEntry
234
+ ? { remaining: startEntry.remaining ?? null, limit: startEntry.limit ?? null, resetsAt: startEntry.resetsAt ?? null, window: startEntry.window ?? null }
235
+ : null;
236
+ appendSeatAllowanceEvent(campaignPath, {
237
+ sample: "freeze",
238
+ harness: freezeHarness,
239
+ delta: allowanceDelta(startAllowance, freezeAllowance),
240
+ ...allowanceEventFields(freezeAllowance),
241
+ });
242
+
243
+ const approved = approveBelow === "high" ? true : approveBelow === "none" ? false : highestRiskTier !== "high";
244
+ const planPath = join(plansDir, "plan.json");
245
+ writeJsonAtomic(planPath, { ...frozen, status: "frozen", approved });
246
+ if (!approved) {
247
+ await campaignCli([
248
+ "note", campaignId, "--cwd", cwd, "--session-id", PLANNER_SESSION_ID,
249
+ "--kind", "open-question", "--question-id", `plan-${phase}-approval`,
250
+ "--text", `Plan for phase ${phase} carries a ${highestRiskTier}-risk node; approval is required under --approve-below ${approveBelow}.`,
251
+ ]);
252
+ }
253
+ logStage("approval", { approved, approveBelow, highestRiskTier });
254
+
255
+ return { status: "frozen", plansDir, planPath, contractPath: join(plansDir, "contract.json"), approved, findings };
256
+ }
257
+
258
+ /**
259
+ * `path` made relative to `cwd`, refused when it escapes it: every planning
260
+ * contract's readFiles must resolve inside the same cwd a run validates
261
+ * against, so a spec outside the target repository can never be named there.
262
+ *
263
+ * @param {string} cwd
264
+ * @param {string} path
265
+ * @param {string} label
266
+ * @returns {string}
267
+ */
268
+ function repoRelativePath(cwd, path, label) {
269
+ const relativePath = relative(cwd, resolve(cwd, path));
270
+ if (relativePath.startsWith("..")) throw new Error(`${label} must be inside ${cwd}: ${path}`);
271
+ return relativePath;
272
+ }
273
+
274
+ /**
275
+ * Every declared runtime treated as available. Live discovery (probing a
276
+ * harness for real exhaustion) is a separate concern this pipeline does not
277
+ * take on; a campaign that needs it can inject a table row and prune its
278
+ * `runtimes` catalogue instead.
279
+ *
280
+ * @param {Record<string, JsonObject>} runtimes
281
+ * @returns {Record<string, {available: true, exhaustedUntil: null}>}
282
+ */
283
+ function availabilityOf(runtimes) {
284
+ return Object.fromEntries(Object.keys(runtimes).map((id) => [id, { available: true, exhaustedUntil: null }]));
285
+ }
286
+
287
+ /**
288
+ * @param {Record<string, JsonObject>} runtimes
289
+ * @param {string|undefined} id
290
+ * @returns {string}
291
+ */
292
+ function modelOf(runtimes, id) {
293
+ const model = id ? runtimes[id]?.model : undefined;
294
+ return typeof model === "string" ? model : "";
295
+ }
296
+
297
+ /**
298
+ * @param {string[]} riskTiers
299
+ * @returns {string}
300
+ */
301
+ function highestOf(riskTiers) {
302
+ return riskTiers.reduce((highest, tier) => (RISK_TIERS.indexOf(tier) > RISK_TIERS.indexOf(highest) ? tier : highest), RISK_TIERS[0]);
303
+ }
304
+
305
+ /**
306
+ * A draft or revise output node (flat `readFiles`/`writeFiles`/`verification`)
307
+ * turned into the shape `applySizingRules` merges and splits: those fields move
308
+ * under `taskPacket`, alongside `sizing.mjs`'s own `writeFiles`/`verification`
309
+ * expectations, while `objective` rides along as a passthrough field a merge
310
+ * never touches.
311
+ *
312
+ * @param {import("./template.mjs").PlanOutputNode} node
313
+ * @returns {SizedPlanNode}
314
+ */
315
+ function toSizingNode(node) {
316
+ return /** @type {SizedPlanNode} */ ({
317
+ id: node.id,
318
+ dependsOn: node.dependsOn,
319
+ taskKind: node.taskKind,
320
+ riskTier: node.riskTier,
321
+ objective: node.objective,
322
+ definitionOfDone: node.definitionOfDone,
323
+ taskPacket: {
324
+ readFiles: node.readFiles,
325
+ writeFiles: node.writeFiles,
326
+ verification: node.verification,
327
+ },
328
+ });
329
+ }
330
+
331
+ /**
332
+ * A sized plan node's classification and shape, turned into the contract node
333
+ * `freezePlan` validates. `riskTier: "low"` gets no gate; `standard` an
334
+ * advisory one; `high` a blocking one, which `validateGate` requires `major`
335
+ * in `failOn` for.
336
+ *
337
+ * @param {SizedPlanNode} node
338
+ * @param {string} phase
339
+ * @param {{worker: string|null, judge: string|null}|undefined} assignment
340
+ * @returns {JsonObject}
341
+ */
342
+ function toContractNode(node, phase, assignment) {
343
+ const riskTier = /** @type {string} */ (node.riskTier);
344
+ const gate = riskTier === "low"
345
+ ? false
346
+ : {
347
+ review: riskTier === "high" ? "blocking" : "advisory",
348
+ failOn: riskTier === "high" ? ["major", "critical"] : ["critical"],
349
+ ...(assignment?.judge ? { runtime: assignment.judge } : {}),
350
+ };
351
+ return {
352
+ id: node.id,
353
+ type: node.taskKind,
354
+ phase,
355
+ dependsOn: node.dependsOn ?? [],
356
+ ...(assignment?.worker ? { runtime: assignment.worker } : {}),
357
+ taskPacket: {
358
+ mode: "execution",
359
+ objective: node.objective,
360
+ instructions: [node.objective],
361
+ readFiles: node.taskPacket.readFiles ?? [],
362
+ writeFiles: node.taskPacket.writeFiles ?? [],
363
+ symbols: [],
364
+ decisions: [],
365
+ nonGoals: [],
366
+ verification: node.taskPacket.verification,
367
+ },
368
+ definitionOfDone: node.definitionOfDone ?? [],
369
+ gate,
370
+ };
371
+ }