@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
package/dist/cli.js ADDED
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env node
2
+ // friday: validate | build | bundle | install | list | graph | handoff check | handoff render
3
+ // friday graph [orchestration] shows an orchestration as a graph (decision 46).
4
+ // validate, build, bundle, install, list and graph take --with <specialization> (decision 41).
5
+ // --json prints one document on stdout; people's output goes to stderr.
6
+ // Exit codes: 0 ok, 1 error (invalid pack, failed check), 2 usage, 3 install conflicts kept.
7
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
8
+ import { join, resolve } from "node:path";
9
+ import { Command, CommanderError } from "commander";
10
+ import { buildBundles, bundleName, unzipBundle, writeBundleDir, zipBundle } from "./build.js";
11
+ import { checkHandoff, requiredApprovals, requiredBriefs, requiredCheckpoints, writeReadable } from "./handoff.js";
12
+ import { orchestrationGraph, renderMermaid, renderTerminals } from "./graph.js";
13
+ import { installBundle } from "./install.js";
14
+ import { PACKAGE_ROOT } from "./paths.js";
15
+ import { projectSpecialization, resolveSpecialization } from "./specialize.js";
16
+ import { loadPack, validatePack } from "./validate.js";
17
+ import { outputsOf } from "./types.js";
18
+ const version = JSON.parse(readFileSync(join(PACKAGE_ROOT, "package.json"), "utf8")).version;
19
+ const say = (msg) => process.stderr.write(msg + "\n");
20
+ const emit = (json, doc) => {
21
+ if (json)
22
+ process.stdout.write(JSON.stringify(doc, null, 2) + "\n");
23
+ };
24
+ async function readBundleSource(from) {
25
+ if (/^https?:\/\//.test(from)) {
26
+ const res = await fetch(from);
27
+ if (!res.ok)
28
+ throw new Error(`friday: download failed: HTTP ${res.status}`);
29
+ return unzipBundle(new Uint8Array(await res.arrayBuffer()));
30
+ }
31
+ return unzipBundle(new Uint8Array(readFileSync(resolve(from))));
32
+ }
33
+ // --with may be given more than once; specializations apply in the order given (decision 41).
34
+ const collect = (v, prev) => prev.concat([v]);
35
+ const WITH = "specialization to apply: a folder with specialization.yaml or a package name (repeatable; the later one wins)";
36
+ const specsOf = (refs, from) => (refs ?? []).map((r) => resolveSpecialization(r, from));
37
+ const program = new Command();
38
+ program.name("friday").description("Install Friday's SDLC agents, orchestrations and conventions into Claude Code and OpenCode.").version(version);
39
+ program.exitOverride();
40
+ program
41
+ .command("validate")
42
+ .description("Validate Friday's pack against the schemas, cross-references, model policy and test pyramid")
43
+ .option("--with <spec>", WITH, collect, [])
44
+ .option("--json", "machine-readable output")
45
+ .action((o) => {
46
+ const r = validatePack(undefined, specsOf(o.with));
47
+ for (const i of r.issues)
48
+ say(`${i.level === "error" ? "error" : "warn "} ${i.file}: ${i.message}`);
49
+ 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 });
51
+ process.exitCode = r.ok ? 0 : 1;
52
+ });
53
+ program
54
+ .command("build")
55
+ .description("Compile into unpacked bundles (<out>/friday-<target>/)")
56
+ .option("-t, --target <target>", "claude, opencode or all", "all")
57
+ .option("-o, --out <dir>", "output directory", "build")
58
+ .option("--with <spec>", WITH, collect, [])
59
+ .option("--json", "machine-readable output")
60
+ .action((o) => {
61
+ const out = buildBundles(o.target, undefined, specsOf(o.with)).map((b) => ({ target: b.manifest.target, dir: writeBundleDir(b, resolve(o.out)), files: b.files.length }));
62
+ for (const r of out)
63
+ say(`built ${r.target}: ${r.files} files in ${r.dir}`);
64
+ emit(!!o.json, { ok: true, bundles: out });
65
+ });
66
+ program
67
+ .command("bundle")
68
+ .description("Compile into installable zips (friday-<target>-<version>.zip)")
69
+ .option("-t, --target <target>", "claude, opencode or all", "all")
70
+ .option("-o, --out <dir>", "output directory", "bundles")
71
+ .option("--with <spec>", WITH, collect, [])
72
+ .option("--json", "machine-readable output")
73
+ .action((o) => {
74
+ mkdirSync(resolve(o.out), { recursive: true });
75
+ const out = buildBundles(o.target, undefined, specsOf(o.with)).map((b) => {
76
+ const file = join(resolve(o.out), bundleName(b));
77
+ writeFileSync(file, zipBundle(b));
78
+ return { target: b.manifest.target, file, files: b.files.length };
79
+ });
80
+ for (const r of out)
81
+ say(`bundled ${r.target}: ${r.file}`);
82
+ emit(!!o.json, { ok: true, bundles: out });
83
+ });
84
+ program
85
+ .command("install")
86
+ .description("Install Friday for Claude Code and/or OpenCode, globally or into a folder")
87
+ .option("-t, --target <target>", "claude, opencode or all", "all")
88
+ .option("-g, --global", "install for the user (~/.claude, ~/.config/opencode)")
89
+ .option("-d, --dir <dir>", "project folder to install into", ".")
90
+ .option("--from <zipOrUrl>", "install a bundle zip (file or https URL) instead of the bundled pack")
91
+ .option("--with <spec>", WITH, collect, [])
92
+ .option("--no-project-conventions", "do not apply the project's own .friday/ specialization")
93
+ .option("--force", "overwrite files changed locally")
94
+ .option("--dry-run", "show what would change, write nothing")
95
+ .option("--json", "machine-readable output")
96
+ .action(async (o) => {
97
+ // The project's own .friday/ goes last, so the project wins over every other specialization.
98
+ const own = !o.global && o.projectConventions ? projectSpecialization(o.dir) : null;
99
+ if (o.from && (o.with.length || own))
100
+ throw new Error("friday: --from installs a built bundle; --with and .friday/ need the pack (drop --from, or use --no-project-conventions)");
101
+ const specs = [...specsOf(o.with, o.dir), ...(own ? [own] : [])];
102
+ if (own)
103
+ say(`applying the project's conventions from ${own}`);
104
+ const bundles = o.from ? [await readBundleSource(o.from)] : buildBundles(o.target, undefined, specs);
105
+ if (o.from && o.target !== "all" && bundles[0].manifest.target !== o.target) {
106
+ throw new Error(`friday: bundle is for ${bundles[0].manifest.target}, not ${o.target}`);
107
+ }
108
+ const results = bundles.map((b) => installBundle(b, { scope: o.global ? "global" : "project", dir: o.dir, force: !!o.force, dryRun: !!o.dryRun }));
109
+ for (const r of results) {
110
+ say(`${r.dryRun ? "[dry-run] " : ""}${r.target} (${r.scope}) -> ${r.roots.config}`);
111
+ for (const f of r.files)
112
+ if (f.action !== "unchanged")
113
+ say(` ${f.action.padEnd(9)} ${f.path}${f.reason ? ` (${f.reason})` : ""}`);
114
+ const n = (a) => r.files.filter((f) => f.action === a).length;
115
+ say(` ${n("created")} created, ${n("updated") + n("forced")} updated, ${n("merged")} merged, ${n("unchanged")} unchanged, ${r.conflicts} conflicts`);
116
+ if (r.note && !r.dryRun)
117
+ say(` note: ${r.note}`);
118
+ }
119
+ const conflicts = results.reduce((s, r) => s + r.conflicts, 0);
120
+ emit(!!o.json, { ok: conflicts === 0, results });
121
+ process.exitCode = conflicts ? 3 : 0;
122
+ });
123
+ program
124
+ .command("list")
125
+ .description("List the agents (with their models and effort profiles) and orchestrations (with their outputs)")
126
+ .option("--with <spec>", WITH, collect, [])
127
+ .option("--json", "machine-readable output")
128
+ .action((o) => {
129
+ const lp = loadPack(undefined, specsOf(o.with));
130
+ for (const sp of lp.specializations ?? [])
131
+ say(`specialization ${sp.id}${sp.version ? ` ${sp.version}` : ""}`);
132
+ const agents = lp.personas.flatMap((p) => p.taskKinds.map((k) => ({ agent: `${p.id}--${k}`, model: lp.policy.taskKinds[k].model, effort: lp.policy.taskKinds[k].effort ?? "medium" })));
133
+ for (const a of agents)
134
+ say(`${a.agent.padEnd(36)} ${a.model.padEnd(8)} ${a.effort}`);
135
+ for (const w of lp.orchestrations)
136
+ say(`orchestration ${w.id.padEnd(24)} ${w.stream.padEnd(10)} -> ${outputsOf(w).join(" + ")}`);
137
+ emit(!!o.json, { agents, orchestrations: lp.orchestrations.map((w) => ({ id: w.id, stream: w.stream, outputs: outputsOf(w) })) });
138
+ });
139
+ program
140
+ .command("graph")
141
+ .description("Show an orchestration as a graph: its steps, routes, loops and every way a run can end (decision 46)")
142
+ .argument("[orchestration]", "orchestration id; all of them when left out")
143
+ .option("--with <spec>", WITH, collect, [])
144
+ .option("--json", "machine-readable output")
145
+ .action((id, o) => {
146
+ const lp = loadPack(undefined, specsOf(o.with));
147
+ const ws = id ? lp.orchestrations.filter((w) => w.id === id) : lp.orchestrations;
148
+ if (id && !ws.length)
149
+ throw new Error(`friday: no orchestration ${id} (${lp.orchestrations.map((w) => w.id).join(", ")})`);
150
+ const graphs = ws.map(orchestrationGraph);
151
+ if (o.json)
152
+ emit(true, { graphs });
153
+ 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`);
156
+ });
157
+ const handoff = program.command("handoff").description("Work with upstream handoffs");
158
+ handoff
159
+ .command("check")
160
+ .description("Check a handoff is valid and approved (downstream may start)")
161
+ .argument("<file>", "docs/friday/<workId>/handoff.yaml")
162
+ .option("--pending", "also accept status awaiting-approval")
163
+ .option("--json", "machine-readable output")
164
+ .action((file, o) => {
165
+ // Every task must name a stack whose engineer can do its taskKind.
166
+ const lp = loadPack();
167
+ const stacks = Object.fromEntries(Object.entries(lp.pack.stacks).map(([s, pid]) => [s, lp.personas.find((p) => p.id === pid)?.taskKinds ?? []]));
168
+ // Every prompt pyramid level the orchestration stops for was approved by its role.
169
+ // 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 });
171
+ for (const p of r.problems)
172
+ say(`problem: ${p}`);
173
+ for (const w of r.warnings)
174
+ say(`warning: ${w}`);
175
+ say(r.ok ? `ok: handoff ${r.status}` : "handoff not ready");
176
+ emit(!!o.json, r);
177
+ process.exitCode = r.ok ? 0 : 1;
178
+ });
179
+ handoff
180
+ .command("render")
181
+ .description("Render the readable handoff.md next to handoff.yaml (the text a person approves)")
182
+ .argument("<file>", "docs/friday/<workId>/handoff.yaml")
183
+ .action((file) => {
184
+ say(`wrote ${writeReadable(file)}`);
185
+ });
186
+ try {
187
+ await program.parseAsync(process.argv);
188
+ }
189
+ catch (err) {
190
+ if (err instanceof CommanderError) {
191
+ process.exitCode = err.exitCode === 0 ? 0 : 2;
192
+ }
193
+ else {
194
+ say(err.message);
195
+ process.exitCode = 1;
196
+ }
197
+ }
@@ -0,0 +1,16 @@
1
+ import { stringify } from "yaml";
2
+ /** Markdown with YAML frontmatter. Undefined values and empty arrays are dropped. */
3
+ export function withFrontmatter(meta, body) {
4
+ const clean = {};
5
+ for (const [k, v] of Object.entries(meta)) {
6
+ if (v === undefined)
7
+ continue;
8
+ if (Array.isArray(v) && v.length === 0)
9
+ continue;
10
+ if (v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).length === 0)
11
+ continue;
12
+ clean[k] = v;
13
+ }
14
+ const yaml = stringify(clean, { lineWidth: 0 }).trimEnd();
15
+ return `---\n${yaml}\n---\n\n${body.trimStart()}`;
16
+ }
package/dist/graph.js ADDED
@@ -0,0 +1,218 @@
1
+ import { outputsOf } from "./types.js";
2
+ const n = (k, one, many) => `${k} ${k === 1 ? one : many}`;
3
+ /** `handoff`: the run has a handoff to go back to (downstream, not release from changesets). */
4
+ export function loopExits(step, handoff = true) {
5
+ const escalation = handoff
6
+ ? "an agent returns blocked -> the delivery decider settles it or the run stops with needs-upstream"
7
+ : "an agent returns blocked -> the run stops with blocked";
8
+ switch (step.type) {
9
+ case "tdd-pair":
10
+ return {
11
+ success: `verify is green with evidence: the static checks and each level the task's tests are at (one test per criterion, at the lowest level that proves it, within ${step.testScope.join(", ")}) ran with exit code 0, no forbidden command, no failure of this task's own tests`,
12
+ failure: `still not green after round ${step.maxRounds}`,
13
+ budget: `${n(step.maxRounds, "round", "rounds")} of green + verify; a test conflict goes to test design, which keeps the test or changes it with a justification`,
14
+ escalation: `${escalation}; test design returns questions, or a test changed without naming its criterion and why it was wrong -> ${handoff ? "needs-upstream" : "blocked"}`,
15
+ };
16
+ case "gate":
17
+ return {
18
+ success: "the review passes",
19
+ failure: step.onFail ? `still failing after ${n(step.maxLoops, "fix loop", "fix loops")} (the findings are returned)` : "the review fails (the findings are returned)",
20
+ budget: step.onFail ? `${n(step.maxLoops, "fix loop", "fix loops")} by ${step.onFail.persona}--${step.onFail.taskKind}` : "no fixer: one review, pass or fail",
21
+ escalation,
22
+ };
23
+ case "integration-loop":
24
+ return {
25
+ success: `every stack green, every level in scope (${step.testScope.join(", ")}) reported with no failed suite, and no follow-ups`,
26
+ failure: `red with no follow-ups, or follow-ups left after round ${step.maxRounds}`,
27
+ budget: `${n(step.maxRounds, "integration round", "integration rounds")}; each round's follow-ups go through the task loop`,
28
+ escalation,
29
+ };
30
+ }
31
+ }
32
+ function labelOf(s) {
33
+ switch (s.type) {
34
+ case "tdd-pair":
35
+ return `${s.id}: TDD pair`;
36
+ case "integration-loop":
37
+ return `${s.id}: integration`;
38
+ case "foreach":
39
+ return `${s.id}: for each ${s.over}`;
40
+ case "approval":
41
+ return `${s.id}: approval of ${s.level ?? s.checkpoint}`;
42
+ default:
43
+ return `${s.id}: ${s.type}`;
44
+ }
45
+ }
46
+ /** The graph of one orchestration. */
47
+ export function orchestrationGraph(w) {
48
+ const g = { id: w.id, stream: w.stream, nodes: [], edges: [], terminals: [], agentExits: [] };
49
+ const down = w.stream === "downstream";
50
+ const handoff = down && !w.requires?.includes("changesets");
51
+ const route = (status, from, when) => g.terminals.push({ status, from, when });
52
+ const edge = (from, to, label, back) => g.edges.push({ from, to, ...(label ? { label } : {}), ...(back ? { back } : {}) });
53
+ const node = (n) => {
54
+ g.nodes.push(n);
55
+ return n.id;
56
+ };
57
+ node({ id: "start", label: "start", kind: "start" });
58
+ if (handoff)
59
+ route("blocked", "start", "no approved handoff with no open questions");
60
+ if (!down && emitsWorkflow(w))
61
+ route("needs-input", "start", "no workId or request");
62
+ const at = (...ids) => ids.map((from) => ({ from }));
63
+ const chain = (steps, entry) => {
64
+ let here = entry;
65
+ for (const s of steps)
66
+ here = step(s, here);
67
+ return here;
68
+ };
69
+ const step = (s, entry) => {
70
+ const id = node({
71
+ id: s.id,
72
+ label: labelOf(s),
73
+ kind: s.type,
74
+ ...(s.type === "tdd-pair" || s.type === "integration-loop" ? { loop: { max: s.maxRounds, unit: "rounds" } } : {}),
75
+ ...(s.type === "gate" ? { loop: { max: s.maxLoops, unit: "fix loops" } } : {}),
76
+ });
77
+ for (const e of entry)
78
+ edge(e.from, id, e.label);
79
+ // `when` skips the step (and all it holds) for the other data class: the route goes around it.
80
+ const skip = s.when ? entry.map((e) => ({ from: e.from, label: `no ${s.when === "pii" ? "pii" : "non-pii"} data: skip ${id}` })) : [];
81
+ let exits;
82
+ switch (s.type) {
83
+ case "clarify":
84
+ exits = at(id);
85
+ break;
86
+ case "gap-analysis":
87
+ checkpoint(id, "open questions, assumptions, gaps or contradictions");
88
+ exits = at(id);
89
+ break;
90
+ case "agent":
91
+ if (!down && s.output === "tasks")
92
+ checkpoint(id, "open items, or a new guard test that already fails");
93
+ exits = at(id);
94
+ break;
95
+ case "handoff":
96
+ checkpoint(id, "anything still open before the handoff is written");
97
+ exits = at(id);
98
+ break;
99
+ case "preflight":
100
+ route(handoff ? "needs-upstream" : "blocked", id, "an unmet prerequisite, or a prerequisite or version pin that cannot be resolved where the agents run");
101
+ route("failed", id, "the install failed");
102
+ exits = at(id);
103
+ break;
104
+ case "approval":
105
+ route("needs-approval", id, `always: a person in the approver role approves ${s.level ? `level ${s.level}` : `checkpoint ${s.checkpoint}`}`);
106
+ exits = at(id);
107
+ break;
108
+ case "parallel": {
109
+ const join = node({ id: `${id}:join`, label: "join", kind: "join" });
110
+ for (const k of s.steps)
111
+ for (const e of step(k, at(id)))
112
+ edge(e.from, join, e.label);
113
+ exits = at(join);
114
+ break;
115
+ }
116
+ case "sequential":
117
+ exits = chain(s.steps, at(id));
118
+ break;
119
+ case "foreach": {
120
+ route("failed", id, `${s.over} is empty`);
121
+ if (s.order === "dependsOn")
122
+ route("failed", id, "a dependency cycle between the items");
123
+ const join = node({ id: `${id}:join`, label: s.order === "dependsOn" ? "wave done" : "all done", kind: "join" });
124
+ for (const e of chain(s.steps, at(id)))
125
+ edge(e.from, join, e.label);
126
+ edge(join, id, "next wave", true);
127
+ exits = at(join);
128
+ break;
129
+ }
130
+ case "tdd-pair": {
131
+ const x = loopExits(s, handoff);
132
+ edge(id, id, `not green, ≤ ${n(s.maxRounds, "round", "rounds")}`, true);
133
+ route("failed", id, x.failure);
134
+ route(handoff ? "needs-upstream" : "blocked", id, "a test changed after a test conflict without naming its criterion and why it was wrong");
135
+ route(handoff ? "needs-upstream" : "blocked", id, "the tests need behaviour the handoff leaves undecided (test design returned questions)");
136
+ exits = at(id);
137
+ break;
138
+ }
139
+ case "gate": {
140
+ const x = loopExits(s, handoff);
141
+ if (s.onFail) {
142
+ const fix = node({ id: `${id}:fix`, label: `${id}: fix (${s.onFail.persona})`, kind: "fix" });
143
+ edge(id, fix, "fail");
144
+ edge(fix, id, `≤ ${n(s.maxLoops, "fix loop", "fix loops")}`, true);
145
+ }
146
+ route("failed", id, x.failure);
147
+ exits = at(id);
148
+ break;
149
+ }
150
+ case "integration-loop": {
151
+ const x = loopExits(s, handoff);
152
+ const f = node({ id: `${id}:followups`, label: `${id}: follow-up tasks`, kind: "followups" });
153
+ edge(id, f, "follow-ups");
154
+ for (const e of chain(s.followup, at(f)))
155
+ edge(e.from, id, `≤ ${n(s.maxRounds, "round", "rounds")}`, true);
156
+ route("failed", id, x.failure);
157
+ exits = at(id);
158
+ break;
159
+ }
160
+ }
161
+ return [...exits, ...skip];
162
+ };
163
+ const checkpoint = (id, what) => {
164
+ route("needs-input", id, `checkpoint: ${what}`);
165
+ if (w.maxRounds)
166
+ route("round-limit", id, `checkpoint after round ${w.maxRounds} (+ extraRounds): the user freezes the scope, extends or stops`);
167
+ };
168
+ const last = chain(w.steps, at("start"));
169
+ const end = down ? "done" : "awaiting-approval";
170
+ for (const e of last)
171
+ route(end, e.from, down ? "every step finished" : "the handoff is written; a person approves it");
172
+ g.agentExits.push({ status: "failed", from: "any agent step", when: "the agent returned no result, or no agent exists for the persona and task kind" });
173
+ g.agentExits.push({
174
+ status: handoff ? "needs-upstream" : "blocked",
175
+ from: "any agent step",
176
+ when: handoff ? "the agent is blocked and the delivery decider cannot settle it (product, copy, security-widening)" : "the agent is blocked",
177
+ });
178
+ return g;
179
+ }
180
+ const emitsWorkflow = (w) => outputsOf(w).includes("workflow");
181
+ // Node ids get a prefix, so a step named like a Mermaid keyword (end, graph) cannot break the chart.
182
+ const mid = (id) => `n_${id.replace(/[^A-Za-z0-9_]/g, "_")}`;
183
+ const tid = (status) => `t_${status.replace(/[^A-Za-z0-9_]/g, "_")}`;
184
+ const esc = (s) => s.replace(/"/g, "'");
185
+ /** A Mermaid flowchart: steps, routes, loop back-edges and the terminals each step reaches. */
186
+ export function renderMermaid(g) {
187
+ const lines = ["flowchart TD"];
188
+ for (const n of g.nodes) {
189
+ const label = esc(n.loop ? `${n.label} (≤ ${n.loop.max} ${n.loop.max === 1 ? n.loop.unit.replace(/s$/, "") : n.loop.unit})` : n.label);
190
+ const shape = n.kind === "start" ? `(["${label}"])` : n.kind === "join" ? `{{"${label}"}}` : `["${label}"]`;
191
+ lines.push(` ${mid(n.id)}${shape}`);
192
+ }
193
+ const statuses = [...new Set([...g.terminals, ...g.agentExits].map((t) => t.status))];
194
+ for (const s of statuses)
195
+ lines.push(` ${tid(s)}((("${s}")))`);
196
+ for (const e of g.edges) {
197
+ const arrow = e.back ? "-.->" : "-->";
198
+ lines.push(` ${mid(e.from)} ${arrow}${e.label ? `|"${esc(e.label)}"|` : ""} ${mid(e.to)}`);
199
+ }
200
+ const seen = new Set();
201
+ for (const t of g.terminals) {
202
+ const k = `${t.from}>${t.status}`;
203
+ if (seen.has(k))
204
+ continue;
205
+ seen.add(k);
206
+ lines.push(` ${mid(t.from)} ==> ${tid(t.status)}`);
207
+ }
208
+ // What any agent call can end the run with, drawn once rather than from every step.
209
+ lines.push(` n__any_agent[["any agent step"]]`);
210
+ for (const t of g.agentExits)
211
+ lines.push(` n__any_agent -.->|"${esc(t.when.split(",")[0])}"| ${tid(t.status)}`);
212
+ return lines.join("\n");
213
+ }
214
+ /** A markdown table of every terminal, the step that reaches it and the condition. */
215
+ export function renderTerminals(g) {
216
+ const rows = [...g.terminals, ...g.agentExits].map((t) => `| \`${t.status}\` | ${t.from} | ${t.when.replace(/\|/g, "\\|")} |`);
217
+ return ["| Terminal | From | When |", "| --- | --- | --- |", ...rows].join("\n");
218
+ }