@digital-agora/friday 0.11.0 → 0.12.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.
Files changed (38) hide show
  1. package/README.md +6 -3
  2. package/bundles/friday-claude-0.1.0.zip +0 -0
  3. package/bundles/friday-opencode-0.1.0.zip +0 -0
  4. package/dist/adapters/claude/index.js +2 -1
  5. package/dist/adapters/claude/runtime.js +293 -49
  6. package/dist/adapters/claude/workflows.js +91 -36
  7. package/dist/adapters/drivers.js +41 -14
  8. package/dist/adapters/opencode/index.js +2 -1
  9. package/dist/adapters/skill.js +10 -2
  10. package/dist/cli.js +42 -7
  11. package/dist/contracts.js +200 -0
  12. package/dist/flow.js +227 -0
  13. package/dist/graph.js +11 -5
  14. package/dist/handoff.js +76 -3
  15. package/dist/ir.js +1 -0
  16. package/dist/load.js +3 -0
  17. package/dist/prompts.js +81 -5
  18. package/dist/reads.js +1 -1
  19. package/dist/slice.js +90 -0
  20. package/dist/specialize.js +10 -0
  21. package/dist/step-schemas.js +28 -3
  22. package/dist/validate.js +38 -20
  23. package/pack/model-policy.yaml +5 -0
  24. package/pack/orchestrations/architecture-decision.yaml +5 -0
  25. package/pack/orchestrations/bugfix-tdd.yaml +1 -1
  26. package/pack/orchestrations/discovery.yaml +16 -3
  27. package/pack/orchestrations/feature-delivery.yaml +11 -3
  28. package/pack/orchestrations/prompt-delivery.yaml +13 -5
  29. package/pack/orchestrations/prompt-discovery.yaml +3 -0
  30. package/pack/pack.yaml +12 -2
  31. package/pack/personas/backend-engineer.yaml +1 -1
  32. package/pack/personas/devops-engineer.yaml +1 -1
  33. package/pack/personas/frontend-engineer.yaml +1 -1
  34. package/package.json +1 -1
  35. package/schemas/decisions.schema.yaml +28 -0
  36. package/schemas/handoff.schema.yaml +66 -4
  37. package/schemas/orchestration.schema.yaml +10 -4
  38. package/schemas/pack.schema.yaml +25 -0
@@ -1,7 +1,11 @@
1
1
  import { FIELD_GUIDES, LEAN_SCHEMAS } from "../../step-schemas.js";
2
2
  import * as P from "../../prompts.js";
3
3
  import { RUNTIME } from "./runtime.js";
4
- import { SUMMARY_DROPS, loopMap, readsMap } from "../../reads.js";
4
+ import { SUMMARY_DROPS, loopMap, readsMap, stepPlaces } from "../../reads.js";
5
+ // Parking is the orchestration check's call (decision 58): the runtime parks only when it says so.
6
+ import { canPark } from "../../flow.js";
7
+ import { handoffSlice } from "../../slice.js";
8
+ import { contractIssues } from "../../contracts.js";
5
9
  const j = (v) => JSON.stringify(v);
6
10
  function refLit(r) {
7
11
  return j(r);
@@ -57,6 +61,19 @@ function compileStep(step, phase, ctx) {
57
61
  ` const out = await call(${id}, ${stepRef(step)}, ${j(step.prompt)}${step.output === "git" ? " + gitText()" : ""}, SCHEMAS.${schema}, item, ${ph});`,
58
62
  up ? ` collect(${id}, out);` : ` if (out) state.outputs[key(${id}, item)] = out;`,
59
63
  ];
64
+ // DSL first, code after (decision 65): the contracts are checked before the run goes on; the
65
+ // step runs once more with the problems, and any still there are open gaps for the round.
66
+ if (step.output === "interfaces") {
67
+ const prompt = j(step.prompt);
68
+ body = [
69
+ ` let out = await call(${id}, ${stepRef(step)}, ${prompt}, SCHEMAS.${schema}, item, ${ph});`,
70
+ " const dsl = (o) => (o ? contractIssues(((o.result || {}).interfaceContracts) || [], ((o.result || {}).shapes) || {}) : []);",
71
+ " let ci = dsl(out);",
72
+ ` if (ci.length && !halted()) { const again = await call(${id}, ${stepRef(step)}, ${prompt} + ${j("\n\n" + P.CONTRACT_RETRY + "\n")} + ci.map((x) => "- " + x).join("\\n"), SCHEMAS.${schema}, item, ${ph}); if (again) { out = again; ci = dsl(out); } }`,
73
+ up ? ` collect(${id}, out);` : ` if (out) state.outputs[key(${id}, item)] = out;`,
74
+ ` ci.forEach((x, i) => state.gaps.push({ id: ${id} + ".contract-" + (i + 1), area: "interfaces", gap: x, why: ${j(P.CONTRACT_GAP_WHY)}, impact: "high", solutions: [{ option: "Complete the contract in the DSL", tradeoff: "none" }], recommended: 0, blocking: true, changesBehaviour: false, topic: "interface-dsl-" + (i + 1), step: ${id} }));`,
75
+ ];
76
+ }
60
77
  if (up && step.output === "tasks") {
61
78
  body[0] = body[0].replace(j(step.prompt), () => j(step.prompt + "\n\n" + P.GUARD_CHECKS + "\n\n" + P.BREAKDOWN));
62
79
  body.push(` guardGaps(${id}, out);`);
@@ -82,12 +99,16 @@ function compileStep(step, phase, ctx) {
82
99
  " // A prerequisite the handoff itself marks unmet goes back upstream before any agent runs (decision 48).",
83
100
  ' const unmet = ((HANDOFF && HANDOFF.prerequisites) || []).filter((p) => p.status !== "met");',
84
101
  ` if (unmet.length) { needsUpstream(${id}, null, "the handoff has unmet prerequisites", unmet.map((p) => p.id + ": " + p.description + " (check: " + p.check + ")")); return; }`,
85
- ` const out = await call(${id}, ${stepRef(step)}, ${j(P.PREFLIGHT)}, SCHEMAS.PREFLIGHT, item, ${ph});`,
102
+ ` const out = await call(${id}, ${stepRef(step)}, ${j(P.PREFLIGHT)} + worktreesText(), SCHEMAS.PREFLIGHT, item, ${ph}, true);`,
86
103
  " if (!out || halted()) return;",
87
104
  ` state.outputs[${id}] = out;`,
88
105
  ` if (out.status === "failed") { stop({ status: "failed", step: ${id}, reason: out.summary }); return; }`,
89
106
  " const missing = (out.prerequisites || []).concat(out.pins || []).filter((x) => !x.resolved);",
90
107
  ` if (missing.length) { needsUpstream(${id}, null, "prerequisites or version pins cannot be resolved where the agents run", missing.map((x) => (x.id || x.package + "@" + x.version) + ": " + x.evidence)); return; }`,
108
+ " // Every working tree on the branch the run names; uncommitted changes are reported, not refused (decision 56).",
109
+ " const wrong = wrongBranches(out);",
110
+ ` if (wrong.length) { needsUpstream(${id}, null, "a working tree is not on the expected branch", wrong); return; }`,
111
+ " (out.worktrees || []).filter((w) => (w.changes || []).length).forEach((w) => trace(" + id + ", null, null, \"uncommitted\", w.path + \": \" + w.changes.length + \" changed path(s)\"));",
91
112
  ` trace(${id}, null, null, "ready", ((out.bootstrap || {}).commands || []).join("; "));`,
92
113
  " state.bootstrapped = true;",
93
114
  ];
@@ -108,49 +129,65 @@ function compileStep(step, phase, ctx) {
108
129
  ` if (!items.length) { stop({ status: "failed", step: ${id}, reason: ${j(`${step.over} is empty`)} }); return; }`,
109
130
  " // Waves follow dependsOn; items in a wave run concurrently. A barrier between waves is",
110
131
  " // required because a task may only start once the tasks it depends on are done.",
111
- ` for (const wave of waves(items, ${j(step.order ?? "none")})) {`,
132
+ ` for (const all of waves(items, ${j(step.order ?? "none")})) {`,
112
133
  " if (halted()) return;",
134
+ " // Parked tasks and the tasks that depend on them wait for the answers (decision 56).",
135
+ " const wave = all.filter((it) => !isParked(it));",
136
+ ` all.filter((it) => isParked(it)).forEach((it) => trace(${id}, it, null, "parked", "waits for a parked blocker"));`,
137
+ " if (!wave.length) continue;",
113
138
  ` trace(${id}, null, null, "wave", wave.map((it) => it.id).join(", "));`,
114
139
  ` await parallel(wave.map((it) => async () => { ${kids.map((k) => `await ${k}(it);`).join(" ")} }));`,
115
140
  " }",
141
+ ...(step.over === "handoff.tasks" ? [" // The task loop is over: every parked blocker goes upstream in one stop.", " releaseParked();"] : []),
116
142
  ];
117
143
  break;
118
144
  }
119
145
  case "tdd-pair": {
120
146
  const scope = j("\n\n" + P.scopeText(ctx.pyramid, step.testScope, true));
121
147
  body = [
148
+ " // Done in a run before and not amended since (decision 63): kept, not built again.",
149
+ " const before = doneBefore(item);",
150
+ ` if (before) { state.outputs[key(${id}, item)] = { summary: before.summary, green: true, rounds: 0, resumed: true, files: before.files || [], testFiles: before.testFiles || [], violations: [] }; ownTests(item, before.testFiles); markSeen(item); markDone(item); trace(${id}, item, null, "done before", "kept from an earlier run"); return; }`,
122
151
  " markSeen(item);",
123
- ` const red = await call(${j(step.id + ".test")}, ${refLit(step.test)}, ${j(P.TDD_TEST)} + (A.commitAtGreen ? ${j(" " + P.RESUME_FROM_COMMIT)} : "") + ${scope}, SCHEMAS.TEST, item, ${ph});`,
124
- " if (!red || halted()) return;",
125
- ` state.outputs[key(${j(step.id + ".test")}, item)] = red;`,
126
- " // Behaviour the tests would have to decide goes back upstream, never into a note (decision 52).",
127
- ` if ((red.questions || []).length) { needsUpstream(${j(step.id + ".test")}, item, "the tests need behaviour the handoff leaves undecided", red.questions); return; }`,
128
- " ownTests(item, red.testFiles);",
129
- " recordLevels(item, red.levels);",
130
- " // Resume-safe: acceptance already met by passing tests -> one independent verify, no impl round.",
131
- " if (red.alreadyMet) {",
132
- ` const v0 = await call(${j(step.id + ".verify")}, ${refLit(step.verify)}, ${j(P.TDD_VERIFY)} + ${scope} + ownersText(item), SCHEMAS.VERIFY, item, ${ph});`,
133
- " if (!v0 || halted()) return;",
134
- " const bad0 = violations(evidenceCommands(v0));",
135
- ` recordViolations(${j(step.id)}, item, bad0);`,
136
- ` const gaps0 = evidenceGaps(v0, ${j(step.testScope)}, item);`,
137
- ` trace(${id}, item, 0, v0.green && !bad0.length && !gaps0.length && foreignOk(v0, item) ? "already met" : "not met", gaps0.join("; "));`,
138
- ` if (v0.green && !bad0.length && !gaps0.length && foreignOk(v0, item)) { state.outputs[key(${id}, item)] = { summary: red.summary, green: true, rounds: 0, alreadyMet: true, files: red.testFiles || [], violations: [] }; markDone(item); return; }`,
152
+ " // A document task (an ADR, a guide) has no tests (decision 62): no test design; its writer writes",
153
+ " // the document and verify runs only the static level, against the acceptance criteria.",
154
+ ' const doc = !!(item && item.taskKind === "document");',
155
+ ' let feedback = "";',
156
+ " let bad = [];",
157
+ " if (doc) state.testLevels[item.id] = [];",
158
+ " else {",
159
+ ` const red = await call(${j(step.id + ".test")}, ${refLit(step.test)}, ${j(P.TDD_TEST)} + (A.commitAtGreen ? ${j(" " + P.RESUME_FROM_COMMIT)} : "") + ${scope}, SCHEMAS.TEST, item, ${ph});`,
160
+ " if (!red || halted()) return;",
161
+ ` state.outputs[key(${j(step.id + ".test")}, item)] = red;`,
162
+ " // Behaviour the tests would have to decide goes back upstream, never into a note (decision 52).",
163
+ ` if ((red.questions || []).length) { upstreamOrPark(${j(step.id + ".test")}, item, "the tests need behaviour the handoff leaves undecided", red.questions); return; }`,
164
+ " ownTests(item, red.testFiles);",
165
+ " recordLevels(item, red.levels);",
166
+ " // Resume-safe: acceptance already met by passing tests -> one independent verify, no impl round.",
167
+ " if (red.alreadyMet) {",
168
+ ` const v0 = await call(${j(step.id + ".verify")}, ${refLit(step.verify)}, ${j(P.TDD_VERIFY)} + ${scope} + ownersText(item), SCHEMAS.VERIFY, item, ${ph});`,
169
+ " if (!v0 || halted()) return;",
170
+ " const bad0 = violations(evidenceCommands(v0));",
171
+ ` recordViolations(${j(step.id)}, item, bad0);`,
172
+ ` const gaps0 = evidenceGaps(v0, ${j(step.testScope)}, item);`,
173
+ ` trace(${id}, item, 0, v0.green && !bad0.length && !gaps0.length && foreignOk(v0, item) ? "already met" : "not met", gaps0.concat(foreignProblems(v0, item)).join("; "));`,
174
+ ` if (v0.green && !bad0.length && !gaps0.length && foreignOk(v0, item)) { state.outputs[key(${id}, item)] = { summary: red.summary, green: true, rounds: 0, alreadyMet: true, files: red.testFiles || [], violations: [] }; markDone(item); return; }`,
175
+ " }",
176
+ ' feedback = "Failing tests: " + (red.testFiles || []).join(", ") + "\\n" + red.failureOutput;',
177
+ " bad = violations(red.commands);",
178
+ ` recordViolations(${j(step.id + ".test")}, item, bad);`,
179
+ ' if (bad.length) feedback += "\\nPyramid violation while writing the tests: " + bad.join("; ");',
139
180
  " }",
140
- ' let feedback = "Failing tests: " + (red.testFiles || []).join(", ") + "\\n" + red.failureOutput;',
141
- " let bad = violations(red.commands);",
142
- ` recordViolations(${j(step.id + ".test")}, item, bad);`,
143
- ' if (bad.length) feedback += "\\nPyramid violation while writing the tests: " + bad.join("; ");',
144
181
  ` for (let round = 1; round <= ${step.maxRounds}; round++) {`,
145
- ` const impl = await call(${j(step.id + ".impl")}, ${refLit(step.impl)}, ${j(P.TDD_IMPL)} + (A.commitAtGreen ? ${j(" " + P.COMMIT_AT_GREEN)} : "") + ${scope} + "\\n\\n" + feedback, SCHEMAS.RESULT, item, ${ph});`,
182
+ ` const impl = await call(${j(step.id + ".impl")}, ${refLit(step.impl)}, (doc ? ${j(P.TDD_DOCUMENT)} : ${j(P.TDD_IMPL)}) + (A.commitAtGreen ? ${j(" " + P.COMMIT_AT_GREEN)} : "") + ${scope} + "\\n\\n" + feedback, SCHEMAS.RESULT, item, ${ph});`,
146
183
  " if (!impl || halted()) return;",
147
184
  " // A wrong test goes back to test-design inside the loop, not upstream.",
148
185
  " // A test is not changed to let the code pass (decision 47): test-design decides, and keeps",
149
186
  " // the test unless it shows the test is wrong.",
150
- " if (impl.testConflict) {",
187
+ " if (impl.testConflict && !doc) {",
151
188
  ` const fixed = await call(${j(step.id + ".test")}, ${refLit(step.test)}, ${j(P.TDD_TEST_CONFLICT)} + ${scope} + "\\n\\n" + JSON.stringify(impl.testConflict), SCHEMAS.TEST, item, ${ph});`,
152
189
  " if (!fixed || halted()) return;",
153
- ` if ((fixed.questions || []).length) { needsUpstream(${j(step.id + ".test")}, item, "the tests need behaviour the handoff leaves undecided", fixed.questions); return; }`,
190
+ ` if ((fixed.questions || []).length) { upstreamOrPark(${j(step.id + ".test")}, item, "the tests need behaviour the handoff leaves undecided", fixed.questions); return; }`,
154
191
  " const change = fixed.testChange || {};",
155
192
  " const justified = !!(change.justification && String(change.justification).trim() && (change.kept || (change.criterion && String(change.criterion).trim())));",
156
193
  ` state.testChanges.push({ step: ${id}, item: item && item.id, round: round, conflict: impl.testConflict, kept: change.kept === true, criterion: change.criterion || null, justification: change.justification || null, files: fixed.testFiles || [] });`,
@@ -168,10 +205,11 @@ function compileStep(step, phase, ctx) {
168
205
  ' : "Failing tests (changed after a test conflict: " + change.justification + "): " + (fixed.testFiles || []).join(", ") + "\\n" + fixed.failureOutput;',
169
206
  " continue;",
170
207
  " }",
171
- ` const v = await call(${j(step.id + ".verify")}, ${refLit(step.verify)}, ${j(P.TDD_VERIFY)} + ${scope} + ownersText(item), SCHEMAS.VERIFY, item, ${ph});`,
208
+ ` const v = await call(${j(step.id + ".verify")}, ${refLit(step.verify)}, (doc ? ${j(P.TDD_VERIFY_DOCUMENT)} : ${j(P.TDD_VERIFY)}) + ${scope} + ownersText(item), SCHEMAS.VERIFY, item, ${ph});`,
172
209
  " if (!v || halted()) return;",
173
210
  " // Another task's red test in the shared tree is reported as owned by it, not as this task's failure.",
174
- " if (!foreignOk(v, item)) v.green = false;",
211
+ " const foreignWhy = foreignProblems(v, item);",
212
+ " if (foreignWhy.length) v.green = false;",
175
213
  " (v.foreignFailures || []).forEach(function (x) { state.foreign.push({ step: " + j(step.id) + ", item: item && item.id, test: x.test, owner: x.owner }); });",
176
214
  " // A round that ran an emulator or e2e suite is not green, whatever the result.",
177
215
  " bad = violations((impl.checks || []).map((c) => c.command).concat(evidenceCommands(v)));",
@@ -179,11 +217,15 @@ function compileStep(step, phase, ctx) {
179
217
  " // Evidence before green (decision 44): verify's word alone does not make the round green.",
180
218
  ` const gaps = v.green ? evidenceGaps(v, ${j(step.testScope)}, item) : [];`,
181
219
  " const green = v.green && !bad.length && !gaps.length;",
220
+ " // A red round always says why: its failures, evidence gaps and foreign failures that are this",
221
+ " // task's, or that verify named none. An empty list would leave the implementer nothing to fix.",
222
+ " const why = (v.failures || []).concat(gaps, foreignWhy);",
223
+ ' if (!green && !why.length && !bad.length) why.push("verify judged the round red but named no failing test or command: run every command in scope, fix what fails and report each command with its exit code");',
182
224
  ` state.outputs[key(${id}, item)] = { summary: impl.summary, green: green, rounds: round, files: impl.files || [], violations: bad, evidence: v.evidence || [] };`,
183
- ` trace(${id}, item, round, green ? "green" : "red", (v.failures || []).concat(gaps, bad.map((c) => "forbidden: " + c)).join("; "));`,
225
+ ` trace(${id}, item, round, green ? "green" : "red", why.concat(bad.map((c) => "forbidden: " + c)).join("; "));`,
184
226
  " if (green) { markDone(item); return; }",
185
- ` state.red = (state.red || []).concat([{ step: ${id}, item: item && item.id, round: round, failures: (v.failures || []).concat(gaps), violations: bad }]);`,
186
- ' feedback = "Round " + round + " is not green:\\n" + (v.failures || []).concat(gaps).join("\\n");',
227
+ ` state.red = (state.red || []).concat([{ step: ${id}, item: item && item.id, round: round, failures: why, violations: bad }]);`,
228
+ ' feedback = "Round " + round + " is not green:\\n" + why.join("\\n");',
187
229
  ' if (bad.length) feedback += "\\nPyramid violation: you ran " + bad.join("; ") + ". The task loop runs only the scope above; integration runs the rest.";',
188
230
  " }",
189
231
  ` stop({ status: "failed", step: ${id}, item: item && item.id, reason: ${j(`not green within the test scope after ${step.maxRounds} rounds`)} });`,
@@ -283,20 +325,21 @@ export function compileClaudeWorkflow(w, ir) {
283
325
  const retro = w.retro ? [`const RETRO = await retro(${j(w.retro)}, ${j(P.RETRO)});`] : ["const RETRO = null;"];
284
326
  const finish = w.stream === "upstream"
285
327
  ? [
286
- "if (state.halt) return Object.assign({}, state.halt, { trace: state.trace }, RETRO ? { retro: RETRO } : {});",
328
+ "if (state.halt) return Object.assign({}, state.halt, { trace: state.trace, usage: state.usage }, RETRO ? { retro: RETRO } : {});",
287
329
  'if (!state.handoff) return { status: "failed", reason: "handoff step did not run" };',
288
- 'return { status: "awaiting-approval", workId: A.workId, handoff: state.handoff, answers: (A.answers || []).concat(state.autoAnswers), gapResolutions: A.gapResolutions || [], round: ROUND, deferred: state.deferred, trace: state.trace, retro: RETRO };',
330
+ 'return { status: "awaiting-approval", workId: A.workId, handoff: state.handoff, answers: (A.answers || []).concat(state.autoAnswers), gapResolutions: A.gapResolutions || [], round: ROUND, deferred: state.deferred, trace: state.trace, usage: state.usage, retro: RETRO };',
289
331
  ]
290
332
  : [
291
- "if (state.halt) return Object.assign({}, state.halt, { pyramidViolations: state.violations, decisions: state.decisions, testChanges: state.testChanges, trace: state.trace, retro: RETRO });",
292
- 'return { status: "done", workId: (HANDOFF && HANDOFF.workId) || A.workId || null, outputs: state.outputs, pyramidViolations: state.violations, foreignFailures: state.foreign, decisions: state.decisions, testChanges: state.testChanges, trace: state.trace, retro: RETRO };',
333
+ "// A run that halts for another reason still returns the blockers it had parked (decision 56).",
334
+ "if (state.halt) return Object.assign({}, state.halt, state.parked.length ? { parked: state.parked, parkedTasks: state.parkedTasks } : {}, { doneTasks: doneTasksOut(), pyramidViolations: state.violations, decisions: state.decisions, amendments: AMENDMENTS, testChanges: state.testChanges, trace: state.trace, usage: state.usage, retro: RETRO });",
335
+ 'return { status: "done", workId: (HANDOFF && HANDOFF.workId) || A.workId || null, outputs: state.outputs, pyramidViolations: state.violations, foreignFailures: state.foreign, decisions: state.decisions, amendments: AMENDMENTS, testChanges: state.testChanges, trace: state.trace, usage: state.usage, retro: RETRO };',
293
336
  ];
294
337
  return [
295
338
  `export const meta = ${j(meta)}`,
296
339
  "",
297
340
  `// Generated by friday from pack ${ir.pack.id} v${ir.pack.version}, workflow ${w.id}. Do not edit:`,
298
341
  "// change the YAML and rebuild.",
299
- `const WORKFLOW = ${j({ id: w.id, stream: w.stream, orchestrator: w.orchestrator, ...(w.maxRounds ? { maxRounds: w.maxRounds } : {}), ...(w.maxItemsPerRound ? { maxItemsPerRound: w.maxItemsPerRound } : {}), ...(w.deferNonBlocking ? { deferNonBlocking: true } : {}) })};`,
342
+ `const WORKFLOW = ${j({ id: w.id, stream: w.stream, orchestrator: w.orchestrator, ...(w.maxRounds ? { maxRounds: w.maxRounds } : {}), ...(w.maxItemsPerRound ? { maxItemsPerRound: w.maxItemsPerRound } : {}), ...(w.deferNonBlocking ? { deferNonBlocking: true } : {}), ...(canPark(w) ? { taskLoop: true } : {}) })};`,
300
343
  `const MODELS = ${j(models)};`,
301
344
  `const AGENTS = ${j(ir.agentIndex)};`,
302
345
  `const STACKS = ${j(ir.pack.stacks)};`,
@@ -308,18 +351,30 @@ export function compileClaudeWorkflow(w, ir) {
308
351
  `const FORBIDDEN_IN_LOOP = ${j(ir.pack.testPyramid?.forbiddenInLoop ?? [])};`,
309
352
  `const LEVELS = ${j(Object.fromEntries((ir.pack.testPyramid?.levels ?? []).map((l) => [l.id, l.commands])))};`,
310
353
  `const DECIDE_BLOCKER = ${j(P.DECIDE_BLOCKER)};`,
354
+ `const PRECEDENCE = ${j(P.PRECEDENCE)};`,
355
+ // The project's documented decisions (decision 64): upstream steps get them, the join settles by topic.
356
+ `const DECISIONS = ${j(w.stream === "upstream" ? ir.decisions.map((d) => ({ id: d.id, topics: d.topics, source: d.source })) : [])};`,
357
+ `const DECISIONS_TEXT = ${j(w.stream === "upstream" && ir.decisions.length ? P.documentedDecisionsText(ir.decisions) : "")};`,
311
358
  `const BOOTSTRAPPED = ${j(P.BOOTSTRAPPED)};`,
312
359
  `const DECIDER = ${j(w.stream === "downstream" ? { persona: "lead-developer", taskKind: "decide" } : null)};`,
313
360
  `const LOOP_LEVELS = ${j(ir.pack.testPyramid?.loopLevels ?? [])};`,
314
361
  // What each step's agents read from earlier steps (decision 55).
315
362
  `const READS = ${j(readsMap(w))};`,
316
363
  `const LOOPS = ${j(loopMap(w))};`,
364
+ // Step order: an upstream step sees only the answers of its own step and the steps before it (decision 59).
365
+ `const STEP_ORDER = ${j([...stepPlaces(w).keys()])};`,
317
366
  `const SUMMARY_DROPS = ${j(SUMMARY_DROPS)};`,
367
+ // The handoff slice a task's agents get (decisions 60, 61), shared with friday handoff check.
368
+ handoffSlice.toString(),
369
+ // The interface contract DSL's checks (decision 65), shared with friday handoff check.
370
+ contractIssues.toString(),
318
371
  RUNTIME,
319
372
  ...ctx.fns,
320
373
  "",
321
374
  ...guard,
322
375
  ...top.map((t) => `phase(${j(t.step.title ?? t.step.id)});\nawait ${t.name}(null);`),
376
+ // A blocker still parked when the steps are over goes upstream before the retro (decision 56).
377
+ ...(w.stream === "downstream" ? ["releaseParked();"] : []),
323
378
  ...(w.retro ? ['phase("retro");'] : []),
324
379
  ...retro,
325
380
  ...finish,
@@ -1,5 +1,6 @@
1
1
  import { loopExits } from "../graph.js";
2
2
  import { readsText } from "../reads.js";
3
+ import * as P from "../prompts.js";
3
4
  export const CLI = "npx -y @digital-agora/friday";
4
5
  function who(ref, ir) {
5
6
  const kinds = ref.taskKind === "{{task.taskKind}}" ? (ref.allowedTaskKinds ?? []) : [ref.taskKind];
@@ -53,10 +54,10 @@ function planLines(steps, ir, depth) {
53
54
  : `${n} **${s.id}** (gap analysis) - ${ref(s)}. Checkpoint: if anything is open, stop here and ask the user.${when}`);
54
55
  break;
55
56
  case "agent":
56
- out.push(`${n} **${s.id}** - ${ref(s)}: ${s.prompt}${s.output === "tasks" && ir.orchestrations.find((w) => w.steps.includes(s))?.stream === "upstream" ? " Every new guard test is run or dry-run against the current repository now; a failure nothing addresses becomes an open gap. Every task names the acceptance criteria it proves (`covers`); a criterion no task covers is an open gap. Registry work is its own task (`needs: [registry]`); a task that removes or renames a public symbol lists the codebases it `breaks` and the tasks that close the break (`closedBy`)." : ""}${when}`);
57
+ out.push(`${n} **${s.id}** - ${ref(s)}: ${s.prompt}${s.output === "tasks" && ir.orchestrations.find((w) => w.steps.includes(s))?.stream === "upstream" ? " Every new guard test is run or dry-run against the current repository now; a failure nothing addresses becomes an open gap. Every task names the acceptance criteria it proves (`covers`); a criterion no task covers is an open gap. Registry work is its own task (`needs: [registry]`); a task that removes or renames a public symbol lists the codebases it `breaks` and the tasks that close the break (`closedBy`)." : ""}${s.output === "interfaces" ? " DSL first, code after (decision 65): check its contracts at once. Every contract says `change` (new, changed, existing); a new or changed one has its `kind` and body (operations, each with every error, a payload, a shape, or an OpenAPI or AsyncAPI `spec.file`) and its `owner`; every shape it names is declared in `shapes`. Problems -> run the step once more with them; any still there are open gaps of the round." : ""}${when}`);
57
58
  break;
58
59
  case "preflight":
59
- out.push(`${n} **${s.id}** (preflight) - ${ref(s)} installs the workspace once from the lockfile (offline when the store allows), runs every handoff prerequisite's check and resolves every version pin the tasks name, where the agents run. A prerequisite the handoff marks unmet, or anything it cannot resolve -> stop, needs-upstream, before anything is built. Every later step reuses that install and never installs online.${when}`);
60
+ out.push(`${n} **${s.id}** (preflight) - ${ref(s)} installs the workspace once from the lockfile (offline when the store allows), runs every handoff prerequisite's check and resolves every version pin the tasks name, where the agents run, and reports each working tree's branch and uncommitted changes. A prerequisite the handoff marks unmet, anything it cannot resolve, or a working tree on another branch than the run names -> stop, needs-upstream, before anything is built. Every later step reuses that install and never installs online.${when}`);
60
61
  break;
61
62
  case "handoff":
62
63
  out.push(`${n} **${s.id}** (handoff) - ${ref(s)} writes docs/friday/<workId>/handoff.yaml and gap-analysis.md.`);
@@ -79,7 +80,9 @@ function planLines(steps, ir, depth) {
79
80
  out.push(`${n} **${s.id}** - for each item of \`${s.over}\`${s.order === "dependsOn" ? " in dependency waves (an item starts when its dependsOn are done; a wave runs in parallel, but two tasks with the same codebase never share a wave: the later one waits)" : " (in parallel, but two tasks with the same codebase never at the same time)"}${s.over === "handoff.tasks" ? "; if the handoff has briefs, give its agents the task's brief from \`handoff.briefs\`, verbatim, next to the handoff" : ""}:${when}`, ...planLines(s.steps, ir, depth + 1));
80
81
  break;
81
82
  case "tdd-pair":
82
- out.push(`${n} **${s.id}** (TDD pair, up to ${s.maxRounds} rounds, tests limited to ${s.testScope.join(" + ")})${when}:`, `${pad} - scope: ${scopeLine(ir, s.testScope)}`, `${pad} - red: ${ref(s.test)} writes failing tests and proves they fail; behaviour the handoff leaves undecided comes back as \`questions\` -> stop, needs-upstream;`, `${pad} - green: ${ref(s.impl)} makes them pass without weakening them;`, `${pad} - verify: ${ref(s.verify)} runs them and reports each command with its exit code. Not green, or no passing command for a level in scope -> feed the failures back to green. Still red after the last round -> stop, failed.`, exitsLine(pad, s, down(s)));
83
+ out.push(`${n} **${s.id}** (TDD pair, up to ${s.maxRounds} rounds, tests limited to ${s.testScope.join(" + ")})${when}:`, `${pad} - scope: ${scopeLine(ir, s.testScope)}`, `${pad} - red: ${ref(s.test)} writes failing tests and proves they fail; behaviour the handoff leaves undecided comes back as \`questions\` -> stop, needs-upstream;`, `${pad} - green: ${ref(s.impl)} makes them pass without weakening them;`, `${pad} - verify: ${ref(s.verify)} runs them and reports each command with its exit code. Not green, or no passing command for a level in scope -> feed the failures back to green. Still red after the last round -> stop, failed.`, ...((s.impl.allowedTaskKinds ?? []).includes("document")
84
+ ? [`${pad} - a task with taskKind \`document\` (an ADR, a guide) has no tests: skip red; green writes the document, and verify runs only the static level and checks each acceptance criterion against it (decision 62).`]
85
+ : []), exitsLine(pad, s, down(s)));
83
86
  break;
84
87
  case "integration-loop":
85
88
  out.push(`${n} **${s.id}** (integration loop, up to ${s.maxRounds} rounds)${when}:`, `${pad} - per stack, ${ref(s.integrate)} wires the composition roots and runs the full pyramid (${s.testScope.join(" -> ")}). It fixes nothing: every failure or gap comes back as a follow-up task with the lowest level that reproduces it.`, `${pad} - all green and no follow-ups -> done. Otherwise each follow-up task, in dependency waves, goes through:`, ...planLines(s.followup, ir, depth + 2), `${pad} - then integration runs again. Follow-ups left after round ${s.maxRounds} -> stop, failed, with the list.`, exitsLine(pad, s, down(s)));
@@ -117,6 +120,9 @@ export function renderPlan(w, ir) {
117
120
  if (w.retro) {
118
121
  lines.push(`${lines.length ? w.steps.length + 1 : 1}. **retro** (after every finished run, whatever its status; not between question rounds) - ${who(w.retro, ir)} writes docs/friday/<workId>/retro.md: stops, reversed answers, red rounds and causes, upstream returns, and proposed Friday improvements.`);
119
122
  }
123
+ // The project's documented decisions and the join on them, upstream (decision 64).
124
+ if (w.stream === "upstream" && ir.decisions.length)
125
+ lines.push("", P.documentedDecisionsText(ir.decisions), "", P.DECISION_JOIN);
120
126
  return lines.join("\n");
121
127
  }
122
128
  /** Where Friday's own improvements go. */
@@ -163,8 +169,8 @@ function closeOutRules(w) {
163
169
  if (w.closeOutFromRound) {
164
170
  out.push(`
165
171
  **Close-out.** From round ${w.closeOutFromRound} on, before asking, offer once: "Close out: from now on
166
- only blocking items or contradictions come to you; the rest take
167
- the recommended option. Turn it on?" (Turn on / Keep asking everything). If the user turns it
172
+ only items that change what is built or how it behaves, and contradictions, come to you; the
173
+ rest (technical details) take the recommended option. Turn it on?" (Turn on / Keep asking everything). If the user turns it
168
174
  on, pass \`closeOut: true\` and record the choice in answers.yaml. The run returns what it took in
169
175
  \`autoAnswers\`: append them to \`answers\` (they keep \`by: close-out\`) and list them to the user.`);
170
176
  }
@@ -234,7 +240,7 @@ user's behalf, never skip one, never fill a gap with a guess.
234
240
  one back, record what they say about it as an answer.` : ""}
235
241
  ${w.deferNonBlocking ? "Do not ask about an item explicitly marked \`blocking: false\`; defer it to \`scope.outOfScope\` and continue. Contradictions and items that block writing or testing a task still require an answer. " : ""}Keep asking until every blocking item has an answer. Append each answer to \`answers\`
236
242
  (\`{ id, question, answer, interpretation }\`, with the id exactly as returned) and each gap, with its
237
- \`resolution\`, to \`gapResolutions\`.
243
+ \`resolution\` and its \`step\` as returned, to \`gapResolutions\`.
238
244
  **Record answers faithfully.** \`answer\` is the user's own words, verbatim (or the option
239
245
  label they picked); what you take it to mean goes in a separate \`interpretation\` line. Never
240
246
  fold an option, a detail or a safeguard the user did not pick into the answer.
@@ -245,7 +251,12 @@ user's behalf, never skip one, never fill a gap with a guess.
245
251
  when the question is about the server: it does not answer it, so record it as a note and ask
246
252
  the question again in the same turn). Only an answer closes the item. Save them${bounded ? " and the round state" : ""} to \`docs/friday/<workId>/answers.yaml\` after
247
253
  every round, then go back to step 2. A re-run sees every answer, so new questions are
248
- follow-ups, not repeats. When the lists grow (more than about 20 items), pass
254
+ follow-ups, not repeats.
255
+ **Re-run from the earliest step the answers concern** (decision 59). An answer belongs to the
256
+ step its id starts with (\`<step>.<id>\`), a gap resolution to its \`step\`; a directive, or an
257
+ answer with no step, belongs to every step. Each step sees only the answers of its own step and
258
+ the steps before it, so every step before the earliest step this round's answers belong to has
259
+ the same input as the round before. ${opts.rerun ?? "Keep those steps' results from the round before and start the plan at that step."} When the lists grow (more than about 20 items), pass
249
260
  \`answersFile: docs/friday/<workId>/answers.yaml\` with \`answeredIds\` and \`resolvedIds\` (the ids
250
261
  only) instead of the full \`answers\` and \`gapResolutions\`; save the file first.${roundRules(w)}${closeOutRules(w)}${approvalRules(w, opts)}
251
262
  4. **status: awaiting-approval.** ${bounded ? "If \`deferred\` is not empty, show it first: these are non-blocking or scope-frozen items moved to follow-up work. " : ""}Run
@@ -271,8 +282,14 @@ export function downstreamDriver(w, opts, pack) {
271
282
 
272
283
  1. Find \`docs/friday/<workId>/handoff.yaml\` (ask the user for the workId if it is not clear).
273
284
  2. Run \`${CLI} handoff check docs/friday/<workId>/handoff.yaml\`. Any failure -> stop; tell the user
274
- to finish the upstream workflow first. Do not fix the handoff yourself.
275
- 3. ${opts.run} with \`{ workId, handoff, commands }\`, where \`handoff\` is the YAML parsed to an object.
285
+ to finish the upstream workflow first. Do not fix the handoff yourself. It prints an
286
+ \`estimate:\` line, the run's worst-case prompt tokens of handoff and agent calls (decision 61):
287
+ show it to the user before the run, with any warning about it.
288
+ 3. ${opts.run} with \`{ workId, handoff, commands, maxPromptTokens, maxAgentCalls }\`, where \`handoff\` is the YAML parsed to an object.
289
+ \`maxPromptTokens\` and \`maxAgentCalls\` cap the run while it goes: by default the estimate's
290
+ tokens and calls, or what the user sets; leave them out only when the user asks for no cap.
291
+ A run stopped at a cap returns \`failed\` with its \`usage\`: show it, and resume the same run
292
+ (\`resumeFromRunId\`) with a higher cap and its \`doneTasks\` only when the user says so; its replayed calls count again.
276
293
  \`commands\` is the repository's command map (pyramid level -> commands). Use the handoff's
277
294
  \`commands\` if it has them; otherwise build the map from the repository: the package manager
278
295
  from \`packageManager\` or the lockfile (pnpm-lock.yaml, package-lock.json, yarn.lock), the
@@ -280,13 +297,23 @@ export function downstreamDriver(w, opts, pack) {
280
297
  \`pnpm check:architecture\`). The pack's commands in the plan above are only the default.
281
298
  Pass \`git: { pr, draft, linkHandoff }\` only when the user asked for something other than the
282
299
  handoff's \`git\` settings (default: open a ready PR that links the handoff; an uncommitted
283
- handoff is never linked).
300
+ handoff is never linked).${w.steps.some((s) => s.type === "preflight") ? `
301
+ Pass \`branch\` (or \`worktrees: [{ path, branch }]\` when the run spans working trees) to have the
302
+ preflight stop a working tree that is on another branch; it reports uncommitted changes either way.` : ""}${w.requires?.includes("handoff") && w.steps.some((s) => s.type === "foreach" && s.over === "handoff.tasks") ? `
303
+ A task's agents get the handoff scoped to their task, not the whole of it (decision 60). Pass
304
+ \`sliceScoped: false\` only when the user asks for the whole handoff in every task's prompt.` : ""}
284
305
  4. **status: needs-upstream.** A downstream agent found something the handoff does not settle.
285
- Do not answer it and do not guess. Show the user the step, the reason and the questions.
306
+ Do not answer it and do not guess. Show the user the step, the reason and the questions; with
307
+ \`parked\`, every parked blocker with the tasks it held back (the other tasks already ran).
286
308
  If the user answers them now, **resume the same run** (\`resumeFromRunId\`) with the same args
287
- plus \`midRunAnswers: [{ step, item, question, answer, interpretation }]\` (step and item as
288
- returned). Keep the \`handoff\` argument exactly as it was: changing it gives every step a new
289
- prompt and restarts the workflow, while midRunAnswers reach only the step that asked and every
309
+ plus \`midRunAnswers: [{ step, item, question, answer, interpretation, amends }]\` (step and item as
310
+ returned, per parked blocker). \`amends\` lists the ids of every approved decision, acceptance
311
+ criterion or recorded answer the answer changes; leave it out only when it changes none. Those
312
+ answers come back in the result's \`amendments\` and the retro's reversed answers.
313
+ Pass the result's \`doneTasks\` back as \`doneTasks\`, exactly as returned: those tasks are not
314
+ built again unless an answer amends what they rely on (decision 63).
315
+ Keep the \`handoff\` argument exactly as it was: changing it gives every step a new prompt and
316
+ restarts the workflow, while midRunAnswers reach only the step that asked and every
290
317
  finished step replays from the cache. Afterwards, record the answers in the handoff file as an
291
318
  amendment (decisions), so the next run starts with them. If the questions change the scope,
292
319
  send the user back to the upstream workflow for this workId instead.
@@ -10,6 +10,7 @@ import { withFrontmatter } from "../../frontmatter.js";
10
10
  import { effortGuidance } from "../../ir.js";
11
11
  import { STEP_SCHEMAS } from "../../step-schemas.js";
12
12
  import { emits } from "../../types.js";
13
+ import * as P from "../../prompts.js";
13
14
  import { CONFIG_DIR_TOKEN, defaultHome, } from "../adapter.js";
14
15
  import { downstreamDriver, releaseDriver, renderPlan, retroRule, upstreamDriver } from "../drivers.js";
15
16
  import { renderSkill } from "../skill.js";
@@ -144,7 +145,7 @@ function orchestrator(w, ir) {
144
145
  const persona = ir.agentIndex[w.orchestrator] ?? {};
145
146
  const kind = persona.decide ? "decide" : (Object.keys(persona)[0] ?? "decide");
146
147
  const up = w.stream === "upstream";
147
- const run = "Execute the step plan above yourself, in order, delegating every step to the named subagent with the task tool. Give each subagent the work id, the request or the handoff, every answer, every resolved gap and the results of earlier steps (only the steps a plan step says it reads, when it says so; for a task, its own results whole, its dependencies' summarized without raw output, evidence or failures, and no other task's: decision 55), and tell it which JSON shape to return (below). Steps marked parallel or in one wave may be delegated at the same time. Never do a step's work yourself and never use a different subagent or model than the plan names";
148
+ const run = "Execute the step plan above yourself, in order, delegating every step to the named subagent with the task tool. Give each subagent the work id, the request or the handoff (for a step on a task, " + P.TASK_SLICE + ", decision 60), the answers and resolved gaps it sees (upstream: those of its own step and the steps before it, decision 59) and the results of earlier steps (only the steps a plan step says it reads, when it says so; for a task, its own results whole, its dependencies' summarized without raw output, evidence or failures, and no other task's: decision 55), and tell it which JSON shape to return (below). Steps marked parallel or in one wave may be delegated at the same time. Never do a step's work yourself and never use a different subagent or model than the plan names";
148
149
  const ask = "the question tool (one question per call, as many calls as needed)";
149
150
  const driver = up
150
151
  ? upstreamDriver(w, { run, ask }, ir.pack.id)
@@ -2,6 +2,7 @@ import * as P from "../prompts.js";
2
2
  import { FIELD_GUIDES, LEAN_SCHEMAS } from "../step-schemas.js";
3
3
  import { emits } from "../types.js";
4
4
  import { approves, downstreamDriver, releaseDriver, renderPlan, retroRule, upstreamDriver } from "./drivers.js";
5
+ import { canPark } from "../flow.js";
5
6
  export const DEFAULT_MAX_AGENTS = 6;
6
7
  /** The agent names a reference resolves to (templates expand to every candidate). */
7
8
  function agentsOf(ref, ir) {
@@ -161,7 +162,9 @@ function runSection(w, t, ir) {
161
162
  w.requires?.includes("handoff")
162
163
  ? "Approved handoff (the only source of truth; anything it does not settle is a blocker, not a guess):"
163
164
  : "Run arguments (anything they and the repository do not settle is a blocker, not a guess):",
164
- "<the handoff or the run arguments>",
165
+ w.requires?.includes("handoff")
166
+ ? `<for a step on a task, ${P.TASK_SLICE} (decision 60; the whole handoff only when the run passes sliceScoped: false); for any other step, the whole handoff>`
167
+ : "<the run arguments>",
165
168
  "Results of earlier steps: <step id -> its result, as section 3 scopes them>",
166
169
  ];
167
170
  return [
@@ -185,7 +188,12 @@ function runSection(w, t, ir) {
185
188
  up
186
189
  ? `\nCollect every question, assumption and gap a step returns, with its id and step. Ids are
187
190
  \`<step>.<id>\` so two steps never clash.${w.deferNonBlocking ? " An item marked `blocking: false` goes to `deferred` instead." : ""}`
188
- : "\nA step that returns `status: blocked` stops the plan: that is `needs-upstream` (or `blocked`\nwithout a handoff). A step that says tests or checks passed counts as green only with each\ncommand it ran and its exit code (decision 44); without them, run it again or report it as not green.",
191
+ : "\nA step that returns `status: blocked` stops the plan: that is `needs-upstream` (or `blocked`\nwithout a handoff)." +
192
+ // Parking only where the orchestration check says this workflow parks (decisions 56, 58).
193
+ (canPark(w)
194
+ ? " Until the task loop over the handoff's tasks is over, a blocker that names the\ntasks it affects (`blocked.tasks`, or the task whose step blocked) parks only them and the tasks that\ndepend on them; the others go on, and after the loop the run stops once with every parked blocker\n(decision 56). The preflight never parks."
195
+ : "") +
196
+ " A step that says tests or checks passed counts as green only with each\ncommand it ran and its exit code (decision 44); without them, run it again or report it as not green.",
189
197
  "",
190
198
  ...(up ? [checkpointSection(w, ir), ""] : []),
191
199
  ].join("\n");
package/dist/cli.js CHANGED
@@ -10,6 +10,9 @@ import { Command, CommanderError } from "commander";
10
10
  import { buildBundles, bundleName, unzipBundle, writeBundleDir, zipBundle } from "./build.js";
11
11
  import { checkHandoff, requiredApprovals, requiredBriefs, requiredCheckpoints, writeReadable } from "./handoff.js";
12
12
  import { orchestrationGraph, renderMermaid, renderTerminals } from "./graph.js";
13
+ import { orchestrationBudget } from "./flow.js";
14
+ import { contractSchema } from "./contracts.js";
15
+ import { parse as parseYaml } from "yaml";
13
16
  import { installBundle } from "./install.js";
14
17
  import { PACKAGE_ROOT } from "./paths.js";
15
18
  import { projectSpecialization, resolveSpecialization } from "./specialize.js";
@@ -41,13 +44,17 @@ program
41
44
  .command("validate")
42
45
  .description("Validate Friday's pack against the schemas, cross-references, model policy and test pyramid")
43
46
  .option("--with <spec>", WITH, collect, [])
47
+ .option("--pack <dir>", "validate another pack directory (pack authors, tests)")
44
48
  .option("--json", "machine-readable output")
45
49
  .action((o) => {
46
- const r = validatePack(undefined, specsOf(o.with));
50
+ const r = validatePack(o.pack, specsOf(o.with));
47
51
  for (const i of r.issues)
48
52
  say(`${i.level === "error" ? "error" : "warn "} ${i.file}: ${i.message}`);
53
+ // The orchestration check's worst-case agent calls (decision 58).
54
+ for (const b of r.budgets ?? [])
55
+ say(`budget ${b.orchestration}: ${b.text}`);
49
56
  say(r.ok ? "ok: the pack is valid" : `invalid: ${r.issues.filter((i) => i.level === "error").length} error(s)`);
50
- emit(!!o.json, { ok: r.ok, issues: r.issues });
57
+ emit(!!o.json, { ok: r.ok, issues: r.issues, budgets: r.budgets ?? [] });
51
58
  process.exitCode = r.ok ? 0 : 1;
52
59
  });
53
60
  program
@@ -142,17 +149,42 @@ program
142
149
  .argument("[orchestration]", "orchestration id; all of them when left out")
143
150
  .option("--with <spec>", WITH, collect, [])
144
151
  .option("--json", "machine-readable output")
152
+ .option("-o, --out <file>", "also write the Markdown to a file (CI attaches it to the pull request)")
145
153
  .action((id, o) => {
146
154
  const lp = loadPack(undefined, specsOf(o.with));
147
155
  const ws = id ? lp.orchestrations.filter((w) => w.id === id) : lp.orchestrations;
148
156
  if (id && !ws.length)
149
157
  throw new Error(`friday: no orchestration ${id} (${lp.orchestrations.map((w) => w.id).join(", ")})`);
150
158
  const graphs = ws.map(orchestrationGraph);
151
- if (o.json)
152
- emit(true, { graphs });
159
+ // The worst-case agent calls of each, from the orchestration check (decision 58).
160
+ const budgets = ws.map((w) => orchestrationBudget(w, lp.pack.agentCallBudget));
161
+ if (o.json) {
162
+ emit(true, { graphs, budgets });
163
+ return;
164
+ }
165
+ const md = graphs
166
+ .map((g, i) => `## ${g.id} (${g.stream})\n\n**Budget:** ${budgets[i].text}.\n\n\`\`\`mermaid\n${renderMermaid(g)}\n\`\`\`\n\n${renderTerminals(g)}\n\n`)
167
+ .join("");
168
+ process.stdout.write(md);
169
+ if (o.out)
170
+ writeFileSync(o.out, `# Friday orchestration graphs\n\nGenerated by \`friday graph\` from the pack (decisions 46, 58).\n\n${md}`);
171
+ });
172
+ // DSL first, code after (decision 65): the handoff's data shapes as JSON Schema, for contract tests
173
+ // in any language.
174
+ program
175
+ .command("contracts")
176
+ .description("Work with a handoff's interface contract DSL (decision 65)")
177
+ .command("schema")
178
+ .description("Write the handoff's shapes as one JSON Schema document ($defs), for contract tests in any language")
179
+ .argument("<file>", "docs/friday/<workId>/handoff.yaml")
180
+ .option("-o, --out <file>", "write it to a file instead of stdout")
181
+ .action((file, o) => {
182
+ const h = parseYaml(readFileSync(file, "utf8"));
183
+ const doc = JSON.stringify(contractSchema(h.shapes ?? {}), null, 2) + "\n";
184
+ if (o.out)
185
+ writeFileSync(o.out, doc);
153
186
  else
154
- for (const g of graphs)
155
- process.stdout.write(`## ${g.id} (${g.stream})\n\n\`\`\`mermaid\n${renderMermaid(g)}\n\`\`\`\n\n${renderTerminals(g)}\n\n`);
187
+ process.stdout.write(doc);
156
188
  });
157
189
  const handoff = program.command("handoff").description("Work with upstream handoffs");
158
190
  handoff
@@ -167,11 +199,14 @@ handoff
167
199
  const stacks = Object.fromEntries(Object.entries(lp.pack.stacks).map(([s, pid]) => [s, lp.personas.find((p) => p.id === pid)?.taskKinds ?? []]));
168
200
  // Every prompt pyramid level the orchestration stops for was approved by its role.
169
201
  // The person approves handoff.md, so it must be the render of exactly this yaml (decision 38).
170
- const r = checkHandoff(file, { ...(o.pending ? { pending: true } : {}), stacks, approvals: requiredApprovals(lp), checkpoints: requiredCheckpoints(lp), briefs: requiredBriefs(lp), readable: true });
202
+ const r = checkHandoff(file, { ...(o.pending ? { pending: true } : {}), stacks, approvals: requiredApprovals(lp), checkpoints: requiredCheckpoints(lp), briefs: requiredBriefs(lp), readable: true, budget: { orchestrations: lp.orchestrations, pack: lp.pack } });
171
203
  for (const p of r.problems)
172
204
  say(`problem: ${p}`);
173
205
  for (const w of r.warnings)
174
206
  say(`warning: ${w}`);
207
+ // What the delivery run will spend on the handoff; pass maxPromptTokens to cap it (decision 61).
208
+ if (r.estimate)
209
+ say(`estimate: ${r.estimate.text}`);
175
210
  say(r.ok ? `ok: handoff ${r.status}` : "handoff not ready");
176
211
  emit(!!o.json, r);
177
212
  process.exitCode = r.ok ? 0 : 1;