@digital-agora/friday 0.0.0-stage → 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.
Files changed (67) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +275 -2
  3. package/bundles/friday-claude-0.1.0.zip +0 -0
  4. package/bundles/friday-opencode-0.1.0.zip +0 -0
  5. package/dist/adapters/adapter.js +6 -0
  6. package/dist/adapters/claude/guards.js +40 -0
  7. package/dist/adapters/claude/index.js +161 -0
  8. package/dist/adapters/claude/runtime.js +645 -0
  9. package/dist/adapters/claude/workflows.js +323 -0
  10. package/dist/adapters/drivers.js +294 -0
  11. package/dist/adapters/index.js +16 -0
  12. package/dist/adapters/opencode/index.js +232 -0
  13. package/dist/adapters/skill.js +327 -0
  14. package/dist/build.js +77 -0
  15. package/dist/cli.js +197 -0
  16. package/dist/frontmatter.js +16 -0
  17. package/dist/graph.js +218 -0
  18. package/dist/handoff.js +329 -0
  19. package/dist/install.js +137 -0
  20. package/dist/ir.js +177 -0
  21. package/dist/load.js +42 -0
  22. package/dist/paths.js +24 -0
  23. package/dist/prompts.js +228 -0
  24. package/dist/specialize.js +201 -0
  25. package/dist/step-schemas.js +440 -0
  26. package/dist/types.js +8 -0
  27. package/dist/validate.js +576 -0
  28. package/pack/conventions/changesets.yaml +20 -0
  29. package/pack/conventions/ci-workflows.yaml +16 -0
  30. package/pack/conventions/config-secrets.yaml +16 -0
  31. package/pack/conventions/data-classification.yaml +16 -0
  32. package/pack/conventions/decisions.yaml +13 -0
  33. package/pack/conventions/git.yaml +28 -0
  34. package/pack/conventions/hexagonal.yaml +31 -0
  35. package/pack/conventions/security-code.yaml +17 -0
  36. package/pack/conventions/testing.yaml +44 -0
  37. package/pack/conventions/typescript-node.yaml +16 -0
  38. package/pack/model-policy.yaml +80 -0
  39. package/pack/orchestrations/architecture-decision.yaml +52 -0
  40. package/pack/orchestrations/bugfix-tdd.yaml +67 -0
  41. package/pack/orchestrations/data-analysis.yaml +23 -0
  42. package/pack/orchestrations/discovery.yaml +204 -0
  43. package/pack/orchestrations/feature-delivery.yaml +129 -0
  44. package/pack/orchestrations/prompt-delivery.yaml +155 -0
  45. package/pack/orchestrations/prompt-discovery.yaml +201 -0
  46. package/pack/orchestrations/release.yaml +40 -0
  47. package/pack/pack.yaml +137 -0
  48. package/pack/personas/architect.yaml +18 -0
  49. package/pack/personas/backend-engineer.yaml +21 -0
  50. package/pack/personas/data-analyst-non-pii.yaml +14 -0
  51. package/pack/personas/data-analyst-pii.yaml +28 -0
  52. package/pack/personas/devops-engineer.yaml +19 -0
  53. package/pack/personas/frontend-engineer.yaml +18 -0
  54. package/pack/personas/git-steward.yaml +24 -0
  55. package/pack/personas/lead-developer.yaml +23 -0
  56. package/pack/personas/prompt-engineer.yaml +38 -0
  57. package/pack/personas/qa-engineer.yaml +24 -0
  58. package/pack/personas/security-steward.yaml +20 -0
  59. package/package.json +47 -4
  60. package/schemas/convention.schema.yaml +46 -0
  61. package/schemas/handoff.schema.yaml +303 -0
  62. package/schemas/model-policy.schema.yaml +33 -0
  63. package/schemas/orchestration.schema.yaml +224 -0
  64. package/schemas/pack.schema.yaml +168 -0
  65. package/schemas/persona.schema.yaml +41 -0
  66. package/schemas/specialization-patch.schema.yaml +39 -0
  67. package/schemas/specialization.schema.yaml +51 -0
@@ -0,0 +1,323 @@
1
+ import { FIELD_GUIDES, LEAN_SCHEMAS } from "../../step-schemas.js";
2
+ import * as P from "../../prompts.js";
3
+ import { RUNTIME } from "./runtime.js";
4
+ const j = (v) => JSON.stringify(v);
5
+ function refLit(r) {
6
+ return j(r);
7
+ }
8
+ function stepRef(step) {
9
+ return refLit({
10
+ persona: step.persona,
11
+ taskKind: step.taskKind,
12
+ ...(step.model ? { model: step.model } : {}),
13
+ ...(step.effort ? { effort: step.effort } : {}),
14
+ });
15
+ }
16
+ /** Emits a function for the step and returns its name. Each function takes the current item. */
17
+ function compileStep(step, phase, ctx) {
18
+ const name = `s${ctx.n++}_${step.id.replace(/[^a-z0-9]/g, "_")}`;
19
+ const ph = j(phase);
20
+ const id = j(step.id);
21
+ const guard = [
22
+ " if (halted()) return;",
23
+ ...(step.when ? [` if (${step.when === "pii" ? "!HAS_PII" : "HAS_PII"}) { trace(${id}, item, null, "skipped", ${j(`no ${step.when} data`)}); return; }`] : []),
24
+ ];
25
+ let body;
26
+ const up = ctx.wf.stream === "upstream";
27
+ switch (step.type) {
28
+ case "clarify":
29
+ body = [
30
+ ` const out = await call(${id}, ${stepRef(step)}, ${j(P.CLARIFY(step.topic))}, SCHEMAS.UPSTREAM, item, ${ph});`,
31
+ ` collect(${id}, out);`,
32
+ ];
33
+ break;
34
+ case "gap-analysis":
35
+ body = [
36
+ ...(step.consolidate
37
+ ? [
38
+ ` const out = await call(${id}, ${stepRef(step)}, ${j(P.GAP_ANALYSIS + "\n\n" + P.CONSOLIDATE)} + openItemsText(), SCHEMAS.CONSOLIDATED, item, ${ph});`,
39
+ ` consolidate(${id}, out);`,
40
+ ]
41
+ : [
42
+ ` const out = await call(${id}, ${stepRef(step)}, ${j(P.GAP_ANALYSIS)}, SCHEMAS.UPSTREAM, item, ${ph});`,
43
+ ` collect(${id}, out);`,
44
+ ]),
45
+ " // Checkpoint: nothing downstream of an open question, assumption or gap is worth running.",
46
+ ` if (!halted() && openCount() > 0) needsInput(${id});`,
47
+ ];
48
+ break;
49
+ case "agent": {
50
+ const schema = step.output === "tasks" ? "TASKS"
51
+ : step.output === "briefs" ? "BRIEFS"
52
+ : step.output === "review" ? "REVIEW"
53
+ : step.output === "git" ? "GIT"
54
+ : up ? "UPSTREAM" : "RESULT";
55
+ body = [
56
+ ` const out = await call(${id}, ${stepRef(step)}, ${j(step.prompt)}${step.output === "git" ? " + gitText()" : ""}, SCHEMAS.${schema}, item, ${ph});`,
57
+ up ? ` collect(${id}, out);` : ` if (out) state.outputs[key(${id}, item)] = out;`,
58
+ ];
59
+ if (up && step.output === "tasks") {
60
+ body[0] = body[0].replace(j(step.prompt), () => j(step.prompt + "\n\n" + P.GUARD_CHECKS + "\n\n" + P.BREAKDOWN));
61
+ body.push(` guardGaps(${id}, out);`);
62
+ body.push(" // Every scope acceptance criterion maps to a task; an uncovered one is an open gap (decision 50).");
63
+ body.push(` coverageGaps(${id}, out);`);
64
+ body.push(` if (!halted() && openCount() > 0) needsInput(${id});`);
65
+ }
66
+ break;
67
+ }
68
+ case "approval":
69
+ // Validation refuses approval steps outside a skill-only orchestration: a script cannot wait
70
+ // for a person between steps.
71
+ throw new Error(`${ctx.wf.id}: step ${step.id}: approval steps run only in a skill (outputs: [skill])`);
72
+ case "handoff":
73
+ body = [
74
+ ` if (openCount() > 0) { needsInput(${id}); if (halted()) return; }`,
75
+ ` const out = await call(${id}, ${stepRef(step)}, ${j(P.HANDOFF(ctx.wf))}, SCHEMAS.HANDOFF_RESULT, item, ${ph});`,
76
+ " if (out) state.handoff = out;",
77
+ ];
78
+ break;
79
+ case "preflight":
80
+ body = [
81
+ " // A prerequisite the handoff itself marks unmet goes back upstream before any agent runs (decision 48).",
82
+ ' const unmet = ((HANDOFF && HANDOFF.prerequisites) || []).filter((p) => p.status !== "met");',
83
+ ` if (unmet.length) { needsUpstream(${id}, null, "the handoff has unmet prerequisites", unmet.map((p) => p.id + ": " + p.description + " (check: " + p.check + ")")); return; }`,
84
+ ` const out = await call(${id}, ${stepRef(step)}, ${j(P.PREFLIGHT)}, SCHEMAS.PREFLIGHT, item, ${ph});`,
85
+ " if (!out || halted()) return;",
86
+ ` state.outputs[${id}] = out;`,
87
+ ` if (out.status === "failed") { stop({ status: "failed", step: ${id}, reason: out.summary }); return; }`,
88
+ " const missing = (out.prerequisites || []).concat(out.pins || []).filter((x) => !x.resolved);",
89
+ ` 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; }`,
90
+ ` trace(${id}, null, null, "ready", ((out.bootstrap || {}).commands || []).join("; "));`,
91
+ " state.bootstrapped = true;",
92
+ ];
93
+ break;
94
+ case "parallel":
95
+ case "sequential": {
96
+ const kids = step.steps.map((s) => compileStep(s, phase, ctx));
97
+ body =
98
+ step.type === "parallel"
99
+ ? [` await parallel([${kids.map((k) => `() => ${k}(item)`).join(", ")}]);`]
100
+ : kids.map((k) => ` await ${k}(item);`);
101
+ break;
102
+ }
103
+ case "foreach": {
104
+ const kids = step.steps.map((s) => compileStep(s, phase, ctx));
105
+ body = [
106
+ ` const items = listFor(${j(step.over)});`,
107
+ ` if (!items.length) { stop({ status: "failed", step: ${id}, reason: ${j(`${step.over} is empty`)} }); return; }`,
108
+ " // Waves follow dependsOn; items in a wave run concurrently. A barrier between waves is",
109
+ " // required because a task may only start once the tasks it depends on are done.",
110
+ ` for (const wave of waves(items, ${j(step.order ?? "none")})) {`,
111
+ " if (halted()) return;",
112
+ ` trace(${id}, null, null, "wave", wave.map((it) => it.id).join(", "));`,
113
+ ` await parallel(wave.map((it) => async () => { ${kids.map((k) => `await ${k}(it);`).join(" ")} }));`,
114
+ " }",
115
+ ];
116
+ break;
117
+ }
118
+ case "tdd-pair": {
119
+ const scope = j("\n\n" + P.scopeText(ctx.pyramid, step.testScope, true));
120
+ body = [
121
+ " markSeen(item);",
122
+ ` 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});`,
123
+ " if (!red || halted()) return;",
124
+ ` state.outputs[key(${j(step.id + ".test")}, item)] = red;`,
125
+ " // Behaviour the tests would have to decide goes back upstream, never into a note (decision 52).",
126
+ ` if ((red.questions || []).length) { needsUpstream(${j(step.id + ".test")}, item, "the tests need behaviour the handoff leaves undecided", red.questions); return; }`,
127
+ " ownTests(item, red.testFiles);",
128
+ " recordLevels(item, red.levels);",
129
+ " // Resume-safe: acceptance already met by passing tests -> one independent verify, no impl round.",
130
+ " if (red.alreadyMet) {",
131
+ ` const v0 = await call(${j(step.id + ".verify")}, ${refLit(step.verify)}, ${j(P.TDD_VERIFY)} + ${scope} + ownersText(item), SCHEMAS.VERIFY, item, ${ph});`,
132
+ " if (!v0 || halted()) return;",
133
+ " const bad0 = violations(evidenceCommands(v0));",
134
+ ` recordViolations(${j(step.id)}, item, bad0);`,
135
+ ` const gaps0 = evidenceGaps(v0, ${j(step.testScope)}, item);`,
136
+ ` trace(${id}, item, 0, v0.green && !bad0.length && !gaps0.length && foreignOk(v0, item) ? "already met" : "not met", gaps0.join("; "));`,
137
+ ` 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; }`,
138
+ " }",
139
+ ' let feedback = "Failing tests: " + (red.testFiles || []).join(", ") + "\\n" + red.failureOutput;',
140
+ " let bad = violations(red.commands);",
141
+ ` recordViolations(${j(step.id + ".test")}, item, bad);`,
142
+ ' if (bad.length) feedback += "\\nPyramid violation while writing the tests: " + bad.join("; ");',
143
+ ` for (let round = 1; round <= ${step.maxRounds}; round++) {`,
144
+ ` 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});`,
145
+ " if (!impl || halted()) return;",
146
+ " // A wrong test goes back to test-design inside the loop, not upstream.",
147
+ " // A test is not changed to let the code pass (decision 47): test-design decides, and keeps",
148
+ " // the test unless it shows the test is wrong.",
149
+ " if (impl.testConflict) {",
150
+ ` 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});`,
151
+ " if (!fixed || halted()) return;",
152
+ ` if ((fixed.questions || []).length) { needsUpstream(${j(step.id + ".test")}, item, "the tests need behaviour the handoff leaves undecided", fixed.questions); return; }`,
153
+ " const change = fixed.testChange || {};",
154
+ " const justified = !!(change.justification && String(change.justification).trim() && (change.kept || (change.criterion && String(change.criterion).trim())));",
155
+ ` 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 || [] });`,
156
+ ` trace(${id}, item, round, change.kept ? "test kept" : justified ? "test changed" : "test changed without justification", change.justification || impl.testConflict.why);`,
157
+ " if (!justified) {",
158
+ " const why = \"a test was changed after a test conflict without naming the criterion it proves and why it was wrong\";",
159
+ ` if (HANDOFF) needsUpstream(${j(step.id + ".test")}, item, why, [], { conflict: impl.testConflict });`,
160
+ ` else stop({ status: "blocked", step: ${j(step.id + ".test")}, item: item && item.id, reason: why, questions: [], conflict: impl.testConflict });`,
161
+ " return;",
162
+ " }",
163
+ " ownTests(item, fixed.testFiles);",
164
+ " recordLevels(item, fixed.levels);",
165
+ " feedback = change.kept",
166
+ ' ? "test-design kept the test: " + change.justification + "\\nMake it pass by changing the code, not the test.\\n" + feedback',
167
+ ' : "Failing tests (changed after a test conflict: " + change.justification + "): " + (fixed.testFiles || []).join(", ") + "\\n" + fixed.failureOutput;',
168
+ " continue;",
169
+ " }",
170
+ ` const v = await call(${j(step.id + ".verify")}, ${refLit(step.verify)}, ${j(P.TDD_VERIFY)} + ${scope} + ownersText(item), SCHEMAS.VERIFY, item, ${ph});`,
171
+ " if (!v || halted()) return;",
172
+ " // Another task's red test in the shared tree is reported as owned by it, not as this task's failure.",
173
+ " if (!foreignOk(v, item)) v.green = false;",
174
+ " (v.foreignFailures || []).forEach(function (x) { state.foreign.push({ step: " + j(step.id) + ", item: item && item.id, test: x.test, owner: x.owner }); });",
175
+ " // A round that ran an emulator or e2e suite is not green, whatever the result.",
176
+ " bad = violations((impl.checks || []).map((c) => c.command).concat(evidenceCommands(v)));",
177
+ ` recordViolations(${j(step.id)}, item, bad);`,
178
+ " // Evidence before green (decision 44): verify's word alone does not make the round green.",
179
+ ` const gaps = v.green ? evidenceGaps(v, ${j(step.testScope)}, item) : [];`,
180
+ " const green = v.green && !bad.length && !gaps.length;",
181
+ ` state.outputs[key(${id}, item)] = { summary: impl.summary, green: green, rounds: round, files: impl.files || [], violations: bad, evidence: v.evidence || [] };`,
182
+ ` trace(${id}, item, round, green ? "green" : "red", (v.failures || []).concat(gaps, bad.map((c) => "forbidden: " + c)).join("; "));`,
183
+ " if (green) { markDone(item); return; }",
184
+ ` state.red = (state.red || []).concat([{ step: ${id}, item: item && item.id, round: round, failures: (v.failures || []).concat(gaps), violations: bad }]);`,
185
+ ' feedback = "Round " + round + " is not green:\\n" + (v.failures || []).concat(gaps).join("\\n");',
186
+ ' if (bad.length) feedback += "\\nPyramid violation: you ran " + bad.join("; ") + ". The task loop runs only the scope above; integration runs the rest.";',
187
+ " }",
188
+ ` stop({ status: "failed", step: ${id}, item: item && item.id, reason: ${j(`not green within the test scope after ${step.maxRounds} rounds`)} });`,
189
+ ];
190
+ break;
191
+ }
192
+ case "integration-loop": {
193
+ const kids = step.followup.map((s) => compileStep(s, phase, ctx));
194
+ const kinds = Object.entries(ctx.stacks)
195
+ .map(([st, ks]) => `${st}: ${ks.join(", ")}`)
196
+ .join("; ");
197
+ const scope = j("\n\n" + P.scopeText(ctx.pyramid, step.testScope, false) + `\n\nFollow-up taskKind per stack (only these exist): ${kinds}.`);
198
+ body = [
199
+ " let followups = [];",
200
+ ` for (let round = 1; round <= ${step.maxRounds}; round++) {`,
201
+ " const stacks = integrationItems(followups);",
202
+ ' const done = followups.length ? "\\n\\nFollow-up tasks done since the last integration round:\\n" + JSON.stringify(followups) : "";',
203
+ ` const rs = (await parallel(stacks.map((st) => () => call(${j(step.id + ".run")}, ${refLit(step.integrate)}, ${j(P.INTEGRATE)} + ${scope} + done, SCHEMAS.INTEGRATION, st, ${ph})))).filter(Boolean);`,
204
+ " if (halted()) return;",
205
+ ` state.outputs[${j(step.id)} + ".round" + round] = rs.map((r) => ({ summary: r.summary, green: r.green, suites: r.suites }));`,
206
+ " const found = renameFollowups(rs.flatMap((r) => r.followups || []), round);",
207
+ " // Evidence before green (decision 44): every level in scope reported, none failed.",
208
+ ` const gaps = rs.flatMap((r) => suiteGaps(r, ${j(step.testScope)}));`,
209
+ " const green = rs.length === stacks.length && rs.every((r) => r.green) && !gaps.length;",
210
+ ` trace(${id}, null, round, green && !found.length ? "green" : found.length ? "follow-ups" : "red", gaps.concat(found.map((t) => t.id)).join("; "));`,
211
+ " if (green && !found.length) {",
212
+ ` state.outputs[${id}] = { green: true, rounds: round, followups: followups };`,
213
+ " return;",
214
+ " }",
215
+ ` if (!found.length) { stop({ status: "failed", step: ${id}, reason: "integration is red but proposed no follow-up tasks", suites: rs.flatMap((r) => r.suites || []), gaps: gaps }); return; }`,
216
+ ` if (round === ${step.maxRounds}) { stop({ status: "failed", step: ${id}, reason: ${j(`gaps remain after ${step.maxRounds} integration rounds`)}, followups: found }); return; }`,
217
+ " followups = followups.concat(found);",
218
+ " // Follow-ups go through the bottom-of-pyramid task loop, in dependency waves.",
219
+ ' for (const wave of waves(found, "dependsOn")) {',
220
+ " if (halted()) return;",
221
+ ` await parallel(wave.map((it) => async () => { ${kids.map((k) => `await ${k}(it);`).join(" ")} }));`,
222
+ " }",
223
+ " }",
224
+ ];
225
+ break;
226
+ }
227
+ case "gate": {
228
+ // Gate fixes are small changes: they stay at the bottom of the pyramid too.
229
+ const gateScope = ctx.pyramid ? "\n\n" + P.scopeText(ctx.pyramid, ctx.pyramid.loopLevels, true) + "\n\n" : "\n";
230
+ body = [
231
+ ` for (let loop = 0; loop <= ${step.maxLoops}; loop++) {`,
232
+ ` const r = await call(${id}, ${stepRef(step)}, ${j(step.prompt)}, SCHEMAS.REVIEW, item, ${ph});`,
233
+ " if (!r || halted()) return;",
234
+ ` state.outputs[key(${id}, item)] = r;`,
235
+ ` trace(${id}, item, loop, r.pass ? "pass" : "fail", (r.findings || []).map((f) => f.severity + ": " + f.issue).join("; "));`,
236
+ " if (r.pass) return;",
237
+ step.onFail
238
+ ? [
239
+ ` if (loop < ${step.maxLoops}) {`,
240
+ ' const findings = r.findings.map((f) => "- [" + f.severity + "] " + (f.file || "") + " " + f.issue + " -> " + f.fix).join("\\n");',
241
+ ` await call(${j(step.id + ".fix")}, ${refLit(step.onFail)}, ${j(P.GATE_FIX)} + ${j(gateScope)} + "\\n" + findings, SCHEMAS.RESULT, item, ${ph});`,
242
+ " if (halted()) return;",
243
+ " }",
244
+ ].join("\n")
245
+ : "",
246
+ " }",
247
+ ` stop({ status: "failed", step: ${id}, reason: "gate did not pass", findings: (state.outputs[key(${id}, item)] || {}).findings });`,
248
+ ].filter(Boolean);
249
+ break;
250
+ }
251
+ }
252
+ ctx.fns.push([`async function ${name}(item) {`, ...guard, ...body, "}"].join("\n"));
253
+ return name;
254
+ }
255
+ export function compileClaudeWorkflow(w, ir) {
256
+ const impl = ["scaffold", "adapter", "implement"];
257
+ const stacks = Object.fromEntries(Object.entries(ir.pack.stacks).map(([st, pid]) => [st, impl.filter((k) => ir.agentIndex[pid]?.[k])]));
258
+ const ctx = { wf: w, pyramid: ir.pack.testPyramid, stacks, fns: [], n: 0 };
259
+ const top = w.steps.map((s) => ({ name: compileStep(s, s.title ?? s.id, ctx), step: s }));
260
+ const meta = {
261
+ name: w.id,
262
+ description: w.description,
263
+ whenToUse: w.stream === "upstream"
264
+ ? `Upstream (asks questions). Run through the friday-${w.id} skill, which loops on the user's answers.`
265
+ : `Downstream (needs an approved handoff). Run through the friday-${w.id} skill.`,
266
+ phases: [...w.steps.map((s) => ({ title: s.title ?? s.id, detail: s.type })), ...(w.retro ? [{ title: "retro", detail: "retro" }] : [])],
267
+ };
268
+ const models = Object.fromEntries(Object.entries(ir.policy.taskKinds).map(([k, v]) => [k, v.effort ? { model: v.model, effort: v.effort } : { model: v.model }]));
269
+ const guard = w.stream === "downstream" && w.requires?.includes("changesets")
270
+ ? ["// Starts from pending changesets, not a handoff: the first step checks there are some."]
271
+ : w.stream === "downstream"
272
+ ? [
273
+ "if (!HANDOFF || HANDOFF.status !== \"approved\" || (HANDOFF.openQuestions || []).length) {",
274
+ ' return { status: "blocked", reason: "an approved handoff with no open questions is required; run the upstream workflow first" };',
275
+ "}",
276
+ ]
277
+ : [
278
+ "if (!A.workId || !A.request) {",
279
+ ' return { status: "needs-input", questions: [{ id: "start", question: "What is the work id and the request?", why: "Every upstream run needs args.workId and args.request.", options: [{ label: "Provide them", description: "Short kebab-case id plus the request as stated" }, { label: "Cancel", description: "Do not start" }], recommended: 0 }], assumptions: [], gaps: [] };',
280
+ "}",
281
+ ];
282
+ const retro = w.retro ? [`const RETRO = await retro(${j(w.retro)}, ${j(P.RETRO)});`] : ["const RETRO = null;"];
283
+ const finish = w.stream === "upstream"
284
+ ? [
285
+ "if (state.halt) return Object.assign({}, state.halt, { trace: state.trace }, RETRO ? { retro: RETRO } : {});",
286
+ 'if (!state.handoff) return { status: "failed", reason: "handoff step did not run" };',
287
+ '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 };',
288
+ ]
289
+ : [
290
+ "if (state.halt) return Object.assign({}, state.halt, { pyramidViolations: state.violations, decisions: state.decisions, testChanges: state.testChanges, trace: state.trace, retro: RETRO });",
291
+ '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 };',
292
+ ];
293
+ return [
294
+ `export const meta = ${j(meta)}`,
295
+ "",
296
+ `// Generated by friday from pack ${ir.pack.id} v${ir.pack.version}, workflow ${w.id}. Do not edit:`,
297
+ "// change the YAML and rebuild.",
298
+ `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 } : {}) })};`,
299
+ `const MODELS = ${j(models)};`,
300
+ `const AGENTS = ${j(ir.agentIndex)};`,
301
+ `const STACKS = ${j(ir.pack.stacks)};`,
302
+ `const ANALYSTS = ${j(ir.pack.analysts ?? {})};`,
303
+ // Shapes only (auto mode caps an agent's output schema at 4096 characters); the field
304
+ // descriptions go into the prompt, see step-schemas.ts.
305
+ `const SCHEMAS = ${j(LEAN_SCHEMAS)};`,
306
+ `const FIELD_GUIDES = ${j(FIELD_GUIDES)};`,
307
+ `const FORBIDDEN_IN_LOOP = ${j(ir.pack.testPyramid?.forbiddenInLoop ?? [])};`,
308
+ `const LEVELS = ${j(Object.fromEntries((ir.pack.testPyramid?.levels ?? []).map((l) => [l.id, l.commands])))};`,
309
+ `const DECIDE_BLOCKER = ${j(P.DECIDE_BLOCKER)};`,
310
+ `const BOOTSTRAPPED = ${j(P.BOOTSTRAPPED)};`,
311
+ `const DECIDER = ${j(w.stream === "downstream" ? { persona: "lead-developer", taskKind: "decide" } : null)};`,
312
+ `const LOOP_LEVELS = ${j(ir.pack.testPyramid?.loopLevels ?? [])};`,
313
+ RUNTIME,
314
+ ...ctx.fns,
315
+ "",
316
+ ...guard,
317
+ ...top.map((t) => `phase(${j(t.step.title ?? t.step.id)});\nawait ${t.name}(null);`),
318
+ ...(w.retro ? ['phase("retro");'] : []),
319
+ ...retro,
320
+ ...finish,
321
+ "",
322
+ ].join("\n");
323
+ }
@@ -0,0 +1,294 @@
1
+ import { loopExits } from "../graph.js";
2
+ export const CLI = "npx -y @digital-agora/friday";
3
+ function who(ref, ir) {
4
+ const kinds = ref.taskKind === "{{task.taskKind}}" ? (ref.allowedTaskKinds ?? []) : [ref.taskKind];
5
+ const model = (k) => {
6
+ const p = ir.policy.taskKinds[k];
7
+ return `${p?.model ?? "?"}, ${p?.effort ?? "medium"} effort`;
8
+ };
9
+ const personas = ref.persona === "{{stack}}" ? Object.entries(ir.pack.stacks).map(([s, p]) => ({ label: `${s}: `, p }))
10
+ : ref.persona === "{{analyst}}" ? Object.entries(ir.pack.analysts ?? {}).map(([s, p]) => ({ label: `${s}: `, p }))
11
+ : [{ label: "", p: ref.persona }];
12
+ // Only agents that exist: a stack engineer without a kind has no variant for it.
13
+ const names = personas.flatMap(({ label, p }) => kinds.filter((k) => ir.agentIndex[p]?.[k]).map((k) => `${label}\`${p}--${k}\` (${model(k)})`));
14
+ const pick = ref.persona === "{{stack}}" ? "the task's stack" + (kinds.length > 1 ? " and taskKind" : "")
15
+ : ref.persona === "{{analyst}}" ? "the handoff's data class (any pii -> pii)"
16
+ : "";
17
+ return pick ? `the agent for ${pick} [${names.join("; ")}]` : names.join(", ");
18
+ }
19
+ function scopeLine(ir, scope) {
20
+ const p = ir.pack.testPyramid;
21
+ if (!p)
22
+ return scope.join(", ");
23
+ const run = p.levels.filter((l) => scope.includes(l.id)).flatMap((l) => l.commands.map((c) => `\`${c}\``));
24
+ return `run only ${run.join(", ")}; never anything containing ${p.forbiddenInLoop.map((f) => `\`${f}\``).join(", ")} (integration runs those). A round that runs one is not green.`;
25
+ }
26
+ // A loop's exits, as the runtime implements them (decision 44, 46): the prose a skill or OpenCode
27
+ // follows says exactly what the compiled script does.
28
+ function exitsLine(pad, s, down) {
29
+ const x = loopExits(s, down);
30
+ return `${pad} - exits: green when ${x.success}; failed when ${x.failure}; budget ${x.budget}; ${x.escalation}.`;
31
+ }
32
+ function planLines(steps, ir, depth) {
33
+ const pad = " ".repeat(depth);
34
+ // Has a handoff to send a blocker back to: downstream, except a release from changesets.
35
+ const down = (s) => {
36
+ const w = ir.orchestrations.find((o) => containsStep(o.steps, s));
37
+ return !!w && w.stream === "downstream" && !w.requires?.includes("changesets");
38
+ };
39
+ const out = [];
40
+ steps.forEach((s, i) => {
41
+ const n = `${pad}${i + 1}.`;
42
+ const start = out.length;
43
+ const when = s.when ? ` (only when the handoff ${s.when === "pii" ? "holds" : "holds no"} pii)` : "";
44
+ const ref = (r) => who(r, ir);
45
+ switch (s.type) {
46
+ case "clarify":
47
+ out.push(`${n} **${s.id}** (clarify) - ${ref(s)}: ${s.topic} Collect its questions, assumptions and gaps.${when}`);
48
+ break;
49
+ case "gap-analysis":
50
+ out.push(s.consolidate
51
+ ? `${n} **${s.id}** (gaps and contradictions) - ${ref(s)} turns every open item of the steps above into one list: merges duplicates, drops what is settled or not blocking (with the reason), adds its own gaps and reports contradictions. Every earlier item is kept, merged or dropped; one it skips stays open. Checkpoint: if anything is open, stop here and ask the user.${when}`
52
+ : `${n} **${s.id}** (gap analysis) - ${ref(s)}. Checkpoint: if anything is open, stop here and ask the user.${when}`);
53
+ break;
54
+ case "agent":
55
+ 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}`);
56
+ break;
57
+ case "preflight":
58
+ 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}`);
59
+ break;
60
+ case "handoff":
61
+ out.push(`${n} **${s.id}** (handoff) - ${ref(s)} writes docs/friday/<workId>/handoff.yaml and gap-analysis.md.`);
62
+ break;
63
+ case "approval": {
64
+ if (s.checkpoint) {
65
+ const cr = ir.pack.checkpoints?.find((c) => c.id === s.checkpoint)?.approver ?? "?";
66
+ out.push(`${n} **${s.id}** (approval of checkpoint \`${s.checkpoint}\`, by the \`${cr}\` role) - no agent. Checkpoint: always stop here, even when nothing is open: **needs-approval**. A person in the \`${cr}\` role approves it or asks for a change (section 4).`);
67
+ break;
68
+ }
69
+ const role = ir.pack.promptPyramid?.levels.find((l) => l.id === s.level)?.approver ?? "?";
70
+ out.push(`${n} **${s.id}** (approval of level \`${s.level}\`, by the \`${role}\` role) - no agent. Checkpoint: always stop here, even when nothing is open: **needs-approval**. A person in the \`${role}\` role approves the level or asks for a change (section 4).`);
71
+ break;
72
+ }
73
+ case "parallel":
74
+ case "sequential":
75
+ out.push(`${n} **${s.id}** - run ${s.type === "parallel" ? "these at the same time" : "in order"}:${when}`, ...planLines(s.steps, ir, depth + 1));
76
+ break;
77
+ case "foreach":
78
+ 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));
79
+ break;
80
+ case "tdd-pair":
81
+ 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)));
82
+ break;
83
+ case "integration-loop":
84
+ 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)));
85
+ break;
86
+ case "gate":
87
+ out.push(`${n} **${s.id}** (gate, up to ${s.maxLoops} fix loops) - ${ref(s)}: ${s.prompt}${s.onFail ? ` On fail, ${ref(s.onFail)} fixes the findings and the gate runs again.` : ""}${when}`, exitsLine(pad, s, down(s)));
88
+ break;
89
+ }
90
+ if (s.checkpoint && s.type !== "approval" && out[start]) {
91
+ out[start] += ` Builds checkpoint \`${s.checkpoint}\`: a person approves it before the next step reads it.`;
92
+ }
93
+ if (s.level && s.type !== "approval" && out[start]) {
94
+ const base = ir.pack.promptPyramid?.levels[0]?.id === s.level;
95
+ out[start] += base
96
+ ? ` Builds level \`${s.level}\`, the base of the prompt pyramid.`
97
+ : ` Builds level \`${s.level}\` from the approved levels below it only; never changes an approved level.`;
98
+ }
99
+ });
100
+ return out;
101
+ }
102
+ function containsStep(steps, s) {
103
+ return steps.some((x) => x === s ||
104
+ ((x.type === "parallel" || x.type === "sequential" || x.type === "foreach") && containsStep(x.steps, s)) ||
105
+ (x.type === "integration-loop" && containsStep(x.followup, s)));
106
+ }
107
+ export function renderPlan(w, ir) {
108
+ const lines = planLines(w.steps, ir, 0);
109
+ if (w.retro) {
110
+ 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.`);
111
+ }
112
+ return lines.join("\n");
113
+ }
114
+ /** Where Friday's own improvements go. */
115
+ export const FRIDAY_REPO = "Digital-Agora/friday";
116
+ export function retroRule(w) {
117
+ if (!w.retro)
118
+ return "";
119
+ return `
120
+ ## After the run: retro
121
+
122
+ The run returns \`retro\` (\`path\`, \`improvements\`) whenever it finished (not between question
123
+ rounds). Tell the user where retro.md is. If \`improvements\` is not empty, list them and offer to
124
+ open a draft pull request on the Friday repository (\`${FRIDAY_REPO}\`) proposing them. Open it
125
+ only if the user agrees; keep it to generic lessons (no personal data, tokens or names from this
126
+ repository).
127
+ `;
128
+ }
129
+ function consolidates(w) {
130
+ const any = (steps) => steps.some((s) => (s.type === "gap-analysis" && !!s.consolidate) || ("steps" in s && any(s.steps)));
131
+ return any(w.steps);
132
+ }
133
+ function roundRules(w) {
134
+ if (!w.maxRounds)
135
+ return "";
136
+ return `
137
+ **Round limit: ${w.maxRounds}.** \`round\` starts at 1 and goes up by one on every re-run; the
138
+ limit is ${w.maxRounds} + \`extraRounds\`. When the run returns \`status: round-limit\` (still
139
+ open after the last round), show the user the open items, then ask: "Discovery reached its
140
+ round limit with these still open. How do you want to continue?" with options:
141
+ - **Freeze the scope (Recommended)**: answer the items shown now; set \`scopeFrozen: true\`.
142
+ The next run asks nothing more: anything still unsettled is deferred to a follow-up work
143
+ item, listed in the handoff's \`scope.outOfScope\`.
144
+ - **Allow ${w.maxRounds} more rounds**: answer the items shown now; add ${w.maxRounds} to \`extraRounds\`.
145
+ - **Stop**: save answers.yaml and end; nothing is handed off.
146
+ Record the choice in answers.yaml; never pick it for the user.`;
147
+ }
148
+ function closeOutRules(w) {
149
+ const out = [];
150
+ if (w.maxItemsPerRound) {
151
+ out.push(`
152
+ **At most ${w.maxItemsPerRound} items per round** (\`maxItemsPerRound\`). Items the run held back are
153
+ in \`heldBack\`: say how many, they come back next round.`);
154
+ }
155
+ if (w.closeOutFromRound) {
156
+ out.push(`
157
+ **Close-out.** From round ${w.closeOutFromRound} on, before asking, offer once: "Close out: from now on
158
+ only blocking items or contradictions come to you; the rest take
159
+ the recommended option. Turn it on?" (Turn on / Keep asking everything). If the user turns it
160
+ on, pass \`closeOut: true\` and record the choice in answers.yaml. The run returns what it took in
161
+ \`autoAnswers\`: append them to \`answers\` (they keep \`by: close-out\`) and list them to the user.`);
162
+ }
163
+ return out.join("");
164
+ }
165
+ /** Whether the orchestration stops for a person to approve prompt pyramid levels. */
166
+ export function approves(w) {
167
+ return w.steps.some((s) => s.type === "approval");
168
+ }
169
+ function approvalRules(w, opts) {
170
+ if (!approves(w))
171
+ return "";
172
+ return `
173
+ 3a. **status: needs-approval.** The run stopped at an approval step: a prompt pyramid level or a
174
+ checkpoint (e.g. the request brief). Show the user the level or checkpoint, the role that
175
+ approves it and the results of the steps that built it (in full: the
176
+ person approves what they read, not a summary). Then list the level's proposals, one line each:
177
+ "<question>: <recommended option> (or: <the other options>)". Ask with ${opts.ask}:
178
+ "Approve level <level> with these proposals?" (for a checkpoint: "Approve the <checkpoint> with
179
+ these proposals?") with options **Approve all** / **Change some** / **Stop**.
180
+ Ask who answers only if it is unclear that they hold the role; record the role, never a name.
181
+ - Approve all: record each proposal as an answer (\`{ id, question, answer, interpretation,
182
+ acceptedAt }\`: \`answer\` is the recommended option's label, \`acceptedAt\` the approval step id),
183
+ append \`{ level, role, round }\` (or \`{ checkpoint, role, round }\`) to \`approvals\` in answers.yaml and go back to step 2. The level is
184
+ approved as shown: its steps do not run again, and the run goes on from the next step.
185
+ - Change some: ask which proposals, or what else, to change. Ask each named proposal as a
186
+ question (its options, the recommended one first); accept the others as above; record
187
+ anything else the user says, verbatim, as an answer to the level (id
188
+ \`<approval step id>.change-<n>\`). The level loses its approval, and so does every level above
189
+ it: remove them from \`approvals\` and go back to step 2; the run builds them again from the
190
+ first step of the level, and the level stops for approval again. A change to a checkpoint
191
+ reopens it and every approval after it in the plan, levels included.
192
+ - Stop: save answers.yaml and end; nothing is handed off.
193
+ Never approve a level for the user, and never skip one.`;
194
+ }
195
+ export function upstreamDriver(w, opts, pack) {
196
+ const bounded = !!w.maxRounds;
197
+ return `## Upstream loop: assumptions kill
198
+
199
+ You drive this loop yourself, and only you talk to the user. Never answer a question on the
200
+ user's behalf, never skip one, never fill a gap with a guess.
201
+
202
+ 1. **Start.** You need \`workId\` (short kebab-case) and \`request\`. Ask for either one if missing.
203
+ If \`docs/friday/<workId>/answers.yaml\` exists, load its ${bounded ? "\`answers\`, \`gapResolutions\`, \`round\`, \`extraRounds\` and \`scopeFrozen\`" : "\`answers\` and \`gapResolutions\`"}: this
204
+ is a resumed run.${approves(w) ? " Load its \`approvals\` too: the levels already approved, each with its role." : ""}
205
+ Ask once, before the first run, for a short **glossary** of the domain words the request uses
206
+ (term -> meaning) and pass it as \`glossary\`; save it in answers.yaml.
207
+ **Verify factual blockers yourself.** Before asking the user about a fact (registry or
208
+ package access, a token being present, a tool or emulator installed), check it with one
209
+ command. Record what you verified in \`environmentFacts\` (passed to every step); ask the user
210
+ only what a check cannot settle.
211
+ 2. **Run.** ${opts.run} with \`{ workId, request, answers, gapResolutions${bounded ? ", round, extraRounds, scopeFrozen" : ""}${w.closeOutFromRound ? ", closeOut" : ""}${approves(w) ? ", approvals" : ""}, glossary, environmentFacts }\`.
212
+ 3. **status: needs-input${bounded ? " (or round-limit)" : ""}.** Ask the user everything returned, using ${opts.ask}:
213
+ ${w.deferNonBlocking ? "Items marked \`blocking: false\` are already deferred; do not ask about them. " : ""}
214
+ - each **question**: its text, plus one line on why it matters; its options with the
215
+ recommended one first, marked "(Recommended)";
216
+ - each **assumption**: "Is it right that <assumption>?" with options Confirm / Correct it;
217
+ - each **gap**: "<gap>. Why: <why>. Impact: <impact>." with its solutions as options
218
+ (each with its trade-off), the recommended one first.${consolidates(w) ? `
219
+ - each **contradiction**: "Contradiction: <conflict> (between <between>). Why: <why>. Both
220
+ sides agree on: <overlap>." with its options, the inner-join sweet spot (the overlap plus the
221
+ least each side must add) first, marked "(Recommended)" when it is. Never pick for the user. Record the answer with
222
+ \`supersedes\`: the ids in \`between\` that are answers; the run then reads only the new one.
223
+ - **dropped**: list each in one line with its reason, after the questions. If the user wants
224
+ one back, record what they say about it as an answer.` : ""}
225
+ ${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\`
226
+ (\`{ id, question, answer, interpretation }\`, with the id exactly as returned) and each gap, with its
227
+ \`resolution\`, to \`gapResolutions\`.
228
+ **Record answers faithfully.** \`answer\` is the user's own words, verbatim (or the option
229
+ label they picked); what you take it to mean goes in a separate \`interpretation\` line. Never
230
+ fold an option, a detail or a safeguard the user did not pick into the answer. When an answer
231
+ addresses a different layer than the question (e.g. the UI when the question is about the
232
+ server), it does not answer it: record it as a note and re-ask the question in the same turn. Save them${bounded ? " and the round state" : ""} to \`docs/friday/<workId>/answers.yaml\` after
233
+ every round, then go back to step 2. A re-run sees every answer, so new questions are
234
+ follow-ups, not repeats. When the lists grow (more than about 20 items), pass
235
+ \`answersFile: docs/friday/<workId>/answers.yaml\` with \`answeredIds\` and \`resolvedIds\` (the ids
236
+ only) instead of the full \`answers\` and \`gapResolutions\`; save the file first.${roundRules(w)}${closeOutRules(w)}${approvalRules(w, opts)}
237
+ 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
238
+ \`${CLI} handoff render docs/friday/<workId>/handoff.yaml\` (it writes handoff.md next to the
239
+ yaml), then \`${CLI} handoff check docs/friday/<workId>/handoff.yaml --pending\` and fix whatever
240
+ it reports (re-run step 2 with the problems as answers if the content is wrong).
241
+ Show the user \`docs/friday/<workId>/handoff.md\` in full: it is the handoff they approve, rendered
242
+ from the yaml, with every gap's solutions, recommendation and resolution. Never show or edit the
243
+ yaml in its place; the full gap write-up is in \`docs/friday/<workId>/gap-analysis.md\` if asked.
244
+ 5. **Approve.** Ask: "Approve the handoff for <workId>?" with options Approve / Request changes /
245
+ Reject. Approve: set \`status: approved\` and \`approvedBy\` in handoff.yaml, run
246
+ \`${CLI} handoff render docs/friday/<workId>/handoff.yaml\` again and then
247
+ \`${CLI} handoff check docs/friday/<workId>/handoff.yaml\`; it must pass. Request changes:
248
+ record what to change as answers and go back to step 2. Reject: set \`status: rejected\` and
249
+ render again.
250
+ 6. **Other statuses** (failed): report the step and reason exactly as returned.
251
+
252
+ After approval, tell the user which downstream workflow to run next.
253
+ `;
254
+ }
255
+ export function downstreamDriver(w, opts, pack) {
256
+ return `## Downstream run: start from an approved handoff only
257
+
258
+ 1. Find \`docs/friday/<workId>/handoff.yaml\` (ask the user for the workId if it is not clear).
259
+ 2. Run \`${CLI} handoff check docs/friday/<workId>/handoff.yaml\`. Any failure -> stop; tell the user
260
+ to finish the upstream workflow first. Do not fix the handoff yourself.
261
+ 3. ${opts.run} with \`{ workId, handoff, commands }\`, where \`handoff\` is the YAML parsed to an object.
262
+ \`commands\` is the repository's command map (pyramid level -> commands). Use the handoff's
263
+ \`commands\` if it has them; otherwise build the map from the repository: the package manager
264
+ from \`packageManager\` or the lockfile (pnpm-lock.yaml, package-lock.json, yarn.lock), the
265
+ script names from package.json and AGENTS.md (e.g. \`npm run test:architecture\` instead of
266
+ \`pnpm check:architecture\`). The pack's commands in the plan above are only the default.
267
+ Pass \`git: { pr, draft, linkHandoff }\` only when the user asked for something other than the
268
+ handoff's \`git\` settings (default: open a ready PR that links the handoff; an uncommitted
269
+ handoff is never linked).
270
+ 4. **status: needs-upstream.** A downstream agent found something the handoff does not settle.
271
+ Do not answer it and do not guess. Show the user the step, the reason and the questions.
272
+ If the user answers them now, **resume the same run** (\`resumeFromRunId\`) with the same args
273
+ plus \`midRunAnswers: [{ step, item, question, answer, interpretation }]\` (step and item as
274
+ returned). Keep the \`handoff\` argument exactly as it was: changing it gives every step a new
275
+ prompt and restarts the workflow, while midRunAnswers reach only the step that asked and every
276
+ finished step replays from the cache. Afterwards, record the answers in the handoff file as an
277
+ amendment (decisions), so the next run starts with them. If the questions change the scope,
278
+ send the user back to the upstream workflow for this workId instead.
279
+ 5. **status: failed or blocked.** Report the step, the reason and any findings exactly as returned.
280
+ 6. **status: done.** Report what was built, the checks that ran and the PR or tag.
281
+ `;
282
+ }
283
+ export function releaseDriver(w, opts) {
284
+ return `## Release run: from pending changesets
285
+
286
+ 1. ${opts.run} with \`{ workId }\` (e.g. \`release-<date>\`; ask the user if they want a specific bump or
287
+ date). No handoff is needed: the changesets are the release's input.
288
+ 2. **status: blocked.** Usually no pending changesets, or staging is not green for the commit.
289
+ Report the reason exactly; do not create a changeset or a version yourself.
290
+ 3. **status: failed.** Report the step, the reason and any findings exactly as returned.
291
+ 4. **status: done.** Show the release PR, the version and the changelog. After it is merged, a
292
+ maintainer tags \`vX.Y.Z\` on the merge commit; production deploys that tag.
293
+ `;
294
+ }