@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,16 @@
1
+ import { claudeAdapter } from "./claude/index.js";
2
+ import { opencodeAdapter } from "./opencode/index.js";
3
+ export const ADAPTERS = {
4
+ claude: claudeAdapter,
5
+ opencode: opencodeAdapter,
6
+ };
7
+ export function adaptersFor(target, packTargets) {
8
+ if (target === "all")
9
+ return packTargets.map((t) => ADAPTERS[t]);
10
+ const a = ADAPTERS[target];
11
+ if (!a)
12
+ throw new Error(`friday: unknown target "${target}" (claude, opencode, all)`);
13
+ if (!packTargets.includes(a.id))
14
+ throw new Error(`friday: the pack does not list target ${a.id}`);
15
+ return [a];
16
+ }
@@ -0,0 +1,232 @@
1
+ // OpenCode target.
2
+ // project: <dir>/.opencode/{agent,command,conventions,skill} + <dir>/opencode.json (deep merge)
3
+ // + <dir>/AGENTS.md (marker block)
4
+ // global: ~/.config/opencode/{agent,command,conventions,skill} + opencode.json + AGENTS.md
5
+ // Field names follow the OpenCode config types (@opencode-ai/sdk AgentConfig, Config): agent
6
+ // frontmatter description/mode/model/tools/permission/steps; command frontmatter
7
+ // description/agent/model/subtask; config instructions[] and skills.paths[]. See decision 4.
8
+ import { join } from "node:path";
9
+ import { withFrontmatter } from "../../frontmatter.js";
10
+ import { effortGuidance } from "../../ir.js";
11
+ import { STEP_SCHEMAS } from "../../step-schemas.js";
12
+ import { emits } from "../../types.js";
13
+ import { CONFIG_DIR_TOKEN, defaultHome, } from "../adapter.js";
14
+ import { downstreamDriver, releaseDriver, renderPlan, retroRule, upstreamDriver } from "../drivers.js";
15
+ import { renderSkill } from "../skill.js";
16
+ export const OPENCODE_DIRS = {
17
+ projectConfig: ".opencode",
18
+ globalConfig: join(".config", "opencode"),
19
+ agents: "agent",
20
+ commands: "command",
21
+ conventions: "conventions",
22
+ skills: "skill",
23
+ config: "opencode.json",
24
+ instructions: "AGENTS.md",
25
+ };
26
+ /** Claude Code tool name -> OpenCode tool key. */
27
+ const TOOL_MAP = {
28
+ Read: "read",
29
+ Edit: "edit",
30
+ Write: "write",
31
+ Grep: "grep",
32
+ Glob: "glob",
33
+ Bash: "bash",
34
+ WebFetch: "webfetch",
35
+ WebSearch: "websearch",
36
+ };
37
+ function toolsMap(a) {
38
+ const tools = {};
39
+ if (a.persona.tools) {
40
+ const allowed = new Set(a.persona.tools.map((t) => TOOL_MAP[t]).filter(Boolean));
41
+ for (const key of new Set(Object.values(TOOL_MAP)))
42
+ tools[key] = allowed.has(key);
43
+ }
44
+ for (const t of [...(a.persona.disallowedTools ?? []), ...a.deniedTools])
45
+ tools[TOOL_MAP[t] ?? t] = false;
46
+ return Object.keys(tools).length ? tools : undefined;
47
+ }
48
+ /**
49
+ * Loop guardrail as bash permission patterns: allow, then deny each forbidden command (decision
50
+ * 24). OpenCode has no per-path edit rule in the SDK types, so protected tests stay prompt-only.
51
+ */
52
+ function bashGuard(a) {
53
+ if (!a.guards.blockedCommands.length)
54
+ return {};
55
+ return { bash: Object.fromEntries([["*", "allow"], ...a.guards.blockedCommands.map((c) => [`*${c}*`, "deny"])]) };
56
+ }
57
+ function model(ir, kind) {
58
+ return ir.policy.targets.opencode[ir.policy.taskKinds[kind].model];
59
+ }
60
+ function agents(ir) {
61
+ return ir.agents.map((a) => ({
62
+ root: "config",
63
+ path: `${OPENCODE_DIRS.agents}/${a.name}.md`,
64
+ merge: "replace",
65
+ content: withFrontmatter({
66
+ description: a.description,
67
+ mode: "subagent",
68
+ model: model(ir, a.taskKind),
69
+ tools: toolsMap(a),
70
+ // Only the workflow orchestrator talks to the user; subagents return their questions.
71
+ permission: { question: "deny", ...bashGuard(a) },
72
+ steps: a.persona.maxTurns,
73
+ }, a.body +
74
+ `\nConventions are loaded from \`${CONFIG_DIR_TOKEN}/${OPENCODE_DIRS.conventions}/\`. End your answer with the JSON object your orchestrator asked for.\n`),
75
+ }));
76
+ }
77
+ function conventions(ir) {
78
+ const out = [];
79
+ for (const { convention: c, body } of ir.conventions) {
80
+ // OpenCode has no path-scoped rules: rule conventions are always-loaded instructions, and the
81
+ // "Applies to" line in the body scopes them. Skill-only conventions become skills.
82
+ if (c.emit.includes("rule")) {
83
+ out.push({ root: "config", path: `${OPENCODE_DIRS.conventions}/${c.id}.md`, merge: "replace", content: body });
84
+ }
85
+ else if (c.emit.includes("skill")) {
86
+ out.push({
87
+ root: "config",
88
+ path: `${OPENCODE_DIRS.skills}/${c.id}/SKILL.md`,
89
+ merge: "replace",
90
+ content: withFrontmatter({ name: c.id, description: `${c.description} (${c.stack} convention, ${ir.pack.name})` }, body),
91
+ });
92
+ }
93
+ }
94
+ return out;
95
+ }
96
+ function shapes() {
97
+ const names = {
98
+ UPSTREAM: "clarify, gap-analysis and upstream agent steps",
99
+ CONSOLIDATED: "gaps-and-contradictions steps (gap-analysis with consolidate); give it every open item collected this round",
100
+ TASKS: "the task breakdown",
101
+ RESULT: "downstream agent steps, TDD green and gate fixes",
102
+ TEST: "TDD red",
103
+ VERIFY: "TDD verify",
104
+ REVIEW: "gates",
105
+ GIT: "git steps",
106
+ HANDOFF_RESULT: "the handoff step",
107
+ RETRO: "the retro after a finished run",
108
+ PREFLIGHT: "the preflight step",
109
+ };
110
+ return Object.entries(STEP_SCHEMAS)
111
+ .map(([k, s]) => `- **${k}** (${names[k] ?? k}): \`${JSON.stringify(s)}\``)
112
+ .join("\n");
113
+ }
114
+ /** OpenCode has no workflow scripts: a large skill run batches task calls instead. */
115
+ const SKILL_TARGET = {
116
+ delegate: "the task tool, the agent as the subagent (its file sets the model)",
117
+ parallel: "one message with a task tool call per agent",
118
+ ask: "the question tool (one question per call, as many calls as needed)",
119
+ };
120
+ /**
121
+ * A skill output -> the skill the current agent loads, plus a command that loads it. OpenCode has
122
+ * no workflow scripts, so [workflow, skill] is the skill alone.
123
+ */
124
+ function skillOutput(w, ir) {
125
+ const name = `friday-${w.id}`;
126
+ const files = renderSkill(w, ir, SKILL_TARGET, name);
127
+ const description = `${w.stream === "upstream" ? "Upstream" : "Downstream"} Friday skill: ${w.description} Sizes the work first, then runs each step with its subagent.`;
128
+ const dir = `${OPENCODE_DIRS.skills}/${name}`;
129
+ return [
130
+ { root: "config", path: `${dir}/SKILL.md`, merge: "replace", content: withFrontmatter({ name, description }, files["SKILL.md"]) },
131
+ { root: "config", path: `${dir}/steps.md`, merge: "replace", content: files["steps.md"] },
132
+ { root: "config", path: `${dir}/shapes.md`, merge: "replace", content: files["shapes.md"] },
133
+ {
134
+ root: "config",
135
+ path: `${OPENCODE_DIRS.commands}/${name}.md`,
136
+ merge: "replace",
137
+ content: withFrontmatter({ description: `Run the Friday ${w.id} skill (${w.stream}).` }, `Load the \`${name}\` skill and follow it.\n\n$ARGUMENTS\n`),
138
+ },
139
+ ];
140
+ }
141
+ function orchestrator(w, ir) {
142
+ if (emits(w, "skill"))
143
+ return skillOutput(w, ir);
144
+ const persona = ir.agentIndex[w.orchestrator] ?? {};
145
+ const kind = persona.decide ? "decide" : (Object.keys(persona)[0] ?? "decide");
146
+ 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, 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 ask = "the question tool (one question per call, as many calls as needed)";
149
+ const driver = up
150
+ ? upstreamDriver(w, { run, ask }, ir.pack.id)
151
+ : w.requires?.includes("changesets") ? releaseDriver(w, { run, ask })
152
+ : downstreamDriver(w, { run, ask }, ir.pack.id);
153
+ const effort = ir.policy.taskKinds[kind]?.effort ?? "medium";
154
+ const name = `friday-${w.id}`;
155
+ const body = [
156
+ `# ${name} (${w.stream})`,
157
+ "",
158
+ w.description,
159
+ "",
160
+ `You orchestrate this workflow on behalf of \`${w.orchestrator}\`.`,
161
+ `Use the \`${effort}\` effort profile: ${effortGuidance(effort)}.`,
162
+ "",
163
+ "## Step plan",
164
+ "",
165
+ renderPlan(w, ir),
166
+ "",
167
+ "When an upstream step returns questions, assumptions or gaps, collect them. At a gap-analysis",
168
+ "checkpoint, defer items marked `blocking: false` to `scope.outOfScope`; only blockers",
169
+ "and contradictions stop the plan and return `needs-input` to the loop below.",
170
+ up
171
+ ? ""
172
+ : "When a downstream subagent returns `status: blocked`, stop the plan: that is `needs-upstream`.",
173
+ "",
174
+ driver,
175
+ retroRule(w),
176
+ "## Shapes subagents return",
177
+ "",
178
+ shapes(),
179
+ "",
180
+ ].join("\n");
181
+ return [
182
+ {
183
+ root: "config",
184
+ path: `${OPENCODE_DIRS.agents}/${name}.md`,
185
+ merge: "replace",
186
+ content: withFrontmatter({
187
+ description: `Friday ${w.stream} workflow: ${w.description}`,
188
+ mode: "primary",
189
+ model: model(ir, kind),
190
+ permission: { task: "allow", question: up ? "allow" : "deny", edit: up ? "allow" : "deny", bash: "allow" },
191
+ }, body),
192
+ },
193
+ {
194
+ root: "config",
195
+ path: `${OPENCODE_DIRS.commands}/${name}.md`,
196
+ merge: "replace",
197
+ content: withFrontmatter({ description: `Run the Friday ${w.id} workflow (${w.stream}).`, agent: name }, `Run the Friday \`${w.id}\` workflow as your instructions describe.\n\n$ARGUMENTS\n`),
198
+ },
199
+ ];
200
+ }
201
+ export const opencodeAdapter = {
202
+ id: "opencode",
203
+ capabilities: { workflowScripts: false, askUserTool: "question", pathScopedRules: false, skills: true },
204
+ roots(scope, dir, home = defaultHome()) {
205
+ if (scope === "global") {
206
+ const config = join(home, OPENCODE_DIRS.globalConfig);
207
+ return { config, base: config };
208
+ }
209
+ return { config: join(dir, OPENCODE_DIRS.projectConfig), base: dir };
210
+ },
211
+ reloadNote: "OpenCode reads agents, commands and config at startup: restart it to use them.",
212
+ emit(ir) {
213
+ const files = [...agents(ir), ...conventions(ir), ...ir.orchestrations.flatMap((w) => orchestrator(w, ir))];
214
+ const hasSkills = files.some((f) => f.path.startsWith(`${OPENCODE_DIRS.skills}/`));
215
+ const config = {
216
+ $schema: "https://opencode.ai/config.json",
217
+ instructions: [`${CONFIG_DIR_TOKEN}/${OPENCODE_DIRS.conventions}/*.md`],
218
+ ...(hasSkills ? { skills: { paths: [`${CONFIG_DIR_TOKEN}/${OPENCODE_DIRS.skills}`] } } : {}),
219
+ };
220
+ const commands = ir.orchestrations.map((w) => `\`/friday-${w.id}\``).join(", ");
221
+ return [
222
+ ...files,
223
+ { root: "base", path: OPENCODE_DIRS.config, merge: "json", content: JSON.stringify(config, null, 2) + "\n" },
224
+ {
225
+ root: "base",
226
+ path: OPENCODE_DIRS.instructions,
227
+ merge: "marker",
228
+ content: `${ir.instructions}\nRun work through the Friday commands: ${commands}.\n`,
229
+ },
230
+ ];
231
+ },
232
+ };
@@ -0,0 +1,327 @@
1
+ import * as P from "../prompts.js";
2
+ import { FIELD_GUIDES, LEAN_SCHEMAS } from "../step-schemas.js";
3
+ import { emits } from "../types.js";
4
+ import { approves, downstreamDriver, releaseDriver, renderPlan, retroRule, upstreamDriver } from "./drivers.js";
5
+ export const DEFAULT_MAX_AGENTS = 6;
6
+ /** The agent names a reference resolves to (templates expand to every candidate). */
7
+ function agentsOf(ref, ir) {
8
+ const personas = ref.persona === "{{stack}}" ? Object.values(ir.pack.stacks)
9
+ : ref.persona === "{{analyst}}" ? Object.values(ir.pack.analysts ?? {})
10
+ : [ref.persona];
11
+ const kinds = ref.taskKind === "{{task.taskKind}}" ? (ref.allowedTaskKinds ?? []) : [ref.taskKind];
12
+ return personas.flatMap((p) => kinds.map((k) => ir.agentIndex[p]?.[k]).filter((n) => !!n));
13
+ }
14
+ function leaves(steps) {
15
+ return steps.flatMap((s) => (s.type === "parallel" || s.type === "sequential" ? leaves(s.steps) : [s]));
16
+ }
17
+ /** Leaf steps with the prompt pyramid level they build, inherited from their group. */
18
+ function levelOf(steps, level, out = new Map()) {
19
+ for (const s of steps) {
20
+ const lv = s.level ?? s.checkpoint ?? level;
21
+ if ("steps" in s)
22
+ levelOf(s.steps, lv, out);
23
+ else if (lv && s.type !== "approval")
24
+ out.set(s.id, lv);
25
+ }
26
+ return out;
27
+ }
28
+ function briefs(w, ir) {
29
+ const up = w.stream === "upstream";
30
+ const out = [];
31
+ const levels = up ? levelOf(w.steps) : new Map();
32
+ const propose = (id, text) => (levels.has(id) ? `${text}\n\n${P.LEVEL_PROPOSALS}` : text);
33
+ for (const s of leaves(w.steps)) {
34
+ if (!("persona" in s) || !("taskKind" in s))
35
+ continue;
36
+ const agents = agentsOf(s, ir);
37
+ switch (s.type) {
38
+ case "clarify":
39
+ out.push({ id: s.id, type: "clarify", agents, shape: "UPSTREAM", text: propose(s.id, P.CLARIFY(s.topic)) });
40
+ break;
41
+ case "gap-analysis":
42
+ out.push(s.consolidate
43
+ ? {
44
+ id: s.id,
45
+ type: "gaps and contradictions",
46
+ agents,
47
+ shape: "CONSOLIDATED",
48
+ text: `${P.GAP_ANALYSIS}\n\n${P.CONSOLIDATE}\n\nOpen items of this round:\n<every open question, assumption and gap collected since the last checkpoint, with its id, step and topic>`,
49
+ }
50
+ : { id: s.id, type: "gap analysis", agents, shape: "UPSTREAM", text: P.GAP_ANALYSIS });
51
+ break;
52
+ case "agent": {
53
+ const shape = s.output === "tasks" ? "TASKS"
54
+ : s.output === "briefs" ? "BRIEFS"
55
+ : s.output === "review" ? "REVIEW"
56
+ : s.output === "git" ? "GIT"
57
+ : up ? "UPSTREAM" : "RESULT";
58
+ const text = propose(s.id, up && s.output === "tasks" ? `${s.prompt}\n\n${P.GUARD_CHECKS}\n\n${P.BREAKDOWN}` : s.prompt);
59
+ out.push({ id: s.id, type: "agent", agents, shape, text });
60
+ break;
61
+ }
62
+ case "handoff":
63
+ out.push({ id: s.id, type: "handoff", agents, shape: "HANDOFF_RESULT", text: P.HANDOFF(w) });
64
+ break;
65
+ case "preflight":
66
+ out.push({ id: s.id, type: "preflight", agents, shape: "PREFLIGHT", text: `${P.PREFLIGHT}\n\nA resolved: false item is a blocker: return status blocked. Every later step is told: ${P.BOOTSTRAPPED}` });
67
+ break;
68
+ }
69
+ }
70
+ if (w.retro)
71
+ out.push({ id: "retro", type: "retro", agents: agentsOf(w.retro, ir), shape: "RETRO", text: P.RETRO });
72
+ return out;
73
+ }
74
+ function model(ir, agent) {
75
+ const kind = agent.split("--")[1] ?? "";
76
+ const p = ir.policy.taskKinds[kind];
77
+ return `${p?.model ?? "?"}, ${p?.effort ?? "medium"} effort`;
78
+ }
79
+ function agentsTable(w, ir, bs) {
80
+ const steps = new Map();
81
+ const orchestrator = ir.agentIndex[w.orchestrator]?.decide;
82
+ for (const b of bs)
83
+ for (const a of b.agents)
84
+ steps.set(a, [...(steps.get(a) ?? []), b.id]);
85
+ const rows = [...steps].map(([a, ids]) => {
86
+ const kind = a.split("--")[1] ?? "";
87
+ const p = ir.policy.taskKinds[kind];
88
+ return `| \`${a}\` | ${p?.model ?? "?"} | ${p?.effort ?? "medium"} | ${ids.map((i) => `\`${i}\``).join(", ")} |`;
89
+ });
90
+ return [
91
+ "## Agents",
92
+ "",
93
+ "Every step's work is done by its agent, with the model and effort its agent file sets. Never do",
94
+ "a step yourself, never swap an agent and never change its model.",
95
+ "",
96
+ "| Agent | Model | Effort | Steps |",
97
+ "| --- | --- | --- | --- |",
98
+ ...rows,
99
+ "",
100
+ `You act for the orchestrator \`${w.orchestrator}\`${orchestrator ? ` (\`${orchestrator}\`)` : ""}: you size the work, pass the context,`,
101
+ "collect results, apply the checkpoints and are the only one who talks to the user.",
102
+ ].join("\n");
103
+ }
104
+ function groups(steps) {
105
+ return steps.flatMap((s) => (s.type === "parallel" ? [s.id, ...groups(s.steps)] : s.type === "sequential" ? groups(s.steps) : []));
106
+ }
107
+ function sizeSection(w, t, withScript) {
108
+ const z = w.sizing;
109
+ const cap = z.maxAgentsPerWorkflow ?? DEFAULT_MAX_AGENTS;
110
+ const gs = groups(w.steps);
111
+ const groupNames = gs.length ? gs.map((g) => `\`${g}\``).join(", ") : "none in this plan";
112
+ const large = withScript && t.script
113
+ ? `The whole run goes through the workflow script: in step 2 of the loop, ${t.script(w)} instead of running sections 2-4 yourself. It applies the checkpoints and returns the statuses of section 4 itself; the loop with the user is the same. If the script is not registered yet, run as medium.`
114
+ : `Each parallel group runs ${t.workflow ? t.workflow(w, cap) : `as medium, at most ${cap} agents at a time (this target has no workflow scripts)`}.`;
115
+ return [
116
+ "## 1. Measure the size first",
117
+ "",
118
+ "Before the first step, measure the work from the request and the repository: read the code and",
119
+ "the conventions; do not ask the user for counts. Count one point for every instance of:",
120
+ "",
121
+ ...z.signals.map((s) => `- ${s}`),
122
+ "",
123
+ `Add the points up. **Small**: below ${z.medium}. **Medium**: ${z.medium} to ${z.large - 1}. **Large**: ${z.large} or more.`,
124
+ "",
125
+ "| Size | How the plan runs |",
126
+ "| --- | --- |",
127
+ "| small | One agent at a time, in plan order, the agents of a parallel group too. |",
128
+ `| medium | The agents of a parallel group (${groupNames}) start at the same time: ${t.parallel}. Every other step runs alone, in order. |`,
129
+ `| large | ${large} Pass \`answersFile\` instead of the full answers from the first round. |`,
130
+ "",
131
+ "The size changes only how many agents run at once. It never drops a step, swaps an agent, changes",
132
+ "a model or reorders the plan. Tell the user in one line the size, the count per signal and the",
133
+ "mode, and record `size` (`points`, `counts`, `mode`) in answers.yaml. Measure again when an answer",
134
+ "changes the scope (another codebase, new personal data); if the user asks for another size, use",
135
+ "it and record it with `by: user`.",
136
+ ].join("\n");
137
+ }
138
+ function runSection(w, t, ir) {
139
+ const up = w.stream === "upstream";
140
+ const context = up
141
+ ? [
142
+ `Workflow ${w.id} (upstream), step <step id>. Round <round>${w.maxRounds ? ` of ${w.maxRounds} + extraRounds` : ""}.`,
143
+ "Work id: <workId>",
144
+ "Request:",
145
+ "<request, verbatim>",
146
+ "Glossary: <glossary> Environment facts: <environmentFacts>",
147
+ "Questions already answered by the user (do not ask them again; build on the answers; where an",
148
+ "answer lists supersedes, only it counts): <answers, or: read them in <answersFile>>",
149
+ "Gaps already resolved by the user (do not report them again): <gapResolutions>",
150
+ "Deferred items (record each in scope.outOfScope as follow-up work; plan no task for it): <deferred>",
151
+ ...(w.steps.some((s) => s.type === "approval" && s.checkpoint)
152
+ ? ["Approved checkpoints (their results are in the results of earlier steps; build on them, never change one): <checkpoint -> approving role>"]
153
+ : []),
154
+ ...(w.steps.some((s) => s.type === "approval" && s.level)
155
+ ? ["Approved prompt pyramid levels (build only from these; never change one): <level -> approving role>"]
156
+ : []),
157
+ "Results of earlier steps: <step id -> its result>",
158
+ ]
159
+ : [
160
+ `Workflow ${w.id} (downstream), step <step id>.`,
161
+ w.requires?.includes("handoff")
162
+ ? "Approved handoff (the only source of truth; anything it does not settle is a blocker, not a guess):"
163
+ : "Run arguments (anything they and the repository do not settle is a blocker, not a guess):",
164
+ "<the handoff or the run arguments>",
165
+ "Results of earlier steps: <step id -> its result>",
166
+ ];
167
+ return [
168
+ "## 3. How to run a step",
169
+ "",
170
+ `Start the step's agent with ${t.delegate}. Its prompt is the context block below, then`,
171
+ "`## Your task` and the step's brief from [steps.md](steps.md), then `## What the fields of your",
172
+ "result mean` and the field guide of its shape from [shapes.md](shapes.md). Ask it to end with",
173
+ "the JSON object of that shape and nothing after it.",
174
+ "",
175
+ "```text",
176
+ ...context,
177
+ "```",
178
+ "",
179
+ "Check each result against its shape. A missing or malformed result: start the agent once more",
180
+ "with the problem; still wrong -> stop, `failed`, with the step and the reason. Keep every",
181
+ "result by step id; later steps get them all.",
182
+ up
183
+ ? `\nCollect every question, assumption and gap a step returns, with its id and step. Ids are
184
+ \`<step>.<id>\` so two steps never clash.${w.deferNonBlocking ? " An item marked `blocking: false` goes to `deferred` instead." : ""}`
185
+ : "\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.",
186
+ "",
187
+ ...(up ? [checkpointSection(w, ir), ""] : []),
188
+ ].join("\n");
189
+ }
190
+ /** How the skill starts the consolidating gap step's agent at an approval stop. */
191
+ function consolidator(w, ir) {
192
+ const g = leaves(w.steps).find((s) => s.type === "gap-analysis" && s.consolidate);
193
+ if (!g || !("persona" in g))
194
+ return "start the consolidating gap step's agent";
195
+ const agent = ir.agentIndex[g.persona]?.[g.taskKind] ?? `${g.persona}--${g.taskKind}`;
196
+ return `start the agent of the consolidating step \`${g.id}\` (\`${agent}\`)`;
197
+ }
198
+ function checkpointSection(w, ir) {
199
+ const cap = w.maxItemsPerRound
200
+ ? ` Show at most ${w.maxItemsPerRound} items (contradictions always show, then blocking and behaviour-changing items first); the rest are \`heldBack\` and come back next round.`
201
+ : "";
202
+ return [
203
+ "## 4. Checkpoints and statuses",
204
+ "",
205
+ "No runtime does this for you. At every gap-analysis step, and after the task breakdown's guard",
206
+ "checks, count what is open: collected items that are not answered, resolved, deferred, or",
207
+ "merged or dropped by a gaps-and-contradictions step. Contradictions are never deferred.",
208
+ "After the breakdown, each criterion in its result.acceptance that no task's `covers` names (by",
209
+ "its id or the start of its text) is an open gap `G-coverage-<id>` with options: add it to a",
210
+ "task's covers, add a task, or drop it from the scope.",
211
+ "",
212
+ w.maxRounds
213
+ ? `- Open, and \`round\` is below ${w.maxRounds} + \`extraRounds\` -> stop the plan here: **needs-input**.${cap}`
214
+ : `- Open -> stop the plan here: **needs-input**.${cap}`,
215
+ ...(w.maxRounds
216
+ ? [
217
+ `- Open, and this is round ${w.maxRounds} + \`extraRounds\` -> **round-limit**.`,
218
+ "- `scopeFrozen` -> defer what is still open (except contradictions) and go on.",
219
+ ]
220
+ : []),
221
+ "- Nothing open -> go on to the next step. After the handoff step -> **awaiting-approval**.",
222
+ "- An agent fails twice -> **failed**, with the step and the reason.",
223
+ "",
224
+ "On the next round, start again from the earliest step that raised an answered item or that an",
225
+ "answer changes; steps before it keep their results. Every agent sees every answer, so its new",
226
+ "questions are follow-ups, not repeats.",
227
+ ...(approves(w)
228
+ ? [
229
+ "",
230
+ "**Approval steps.** A person sits between the levels. At an approval step, take every item the",
231
+ "level's own steps left open. If there are any,",
232
+ `${consolidator(w, ir)} with its brief over those items only:`,
233
+ "it merges duplicates, drops what is settled (with the reason) and reports contradictions.",
234
+ "Of what it returns, contradictions, assumptions, gaps and questions not marked `proposable` are",
235
+ `asked first: **needs-input**${w.maxItemsPerRound ? ` (at most ${w.maxItemsPerRound} items)` : ""}; the level's steps then run again`,
236
+ "with the answers, as in any round. Then always stop, even when nothing is open:",
237
+ "**needs-approval**, with the level, its approver role, the results of its steps and the",
238
+ "`proposable` questions as one list of proposals (each: the question, the recommended option",
239
+ "and the others). A level in `approvals` is passed: go on to the next step without stopping. When the user asks for a change",
240
+ "to a level, or an answer in a later round changes the result of a step that built an approved",
241
+ "level, that level loses its approval, and so does every level above it: they are built and",
242
+ "approved again, bottom up. No step builds a level before the level below it is approved.",
243
+ "A change to a checkpoint reopens it and every approval after it in the plan, levels",
244
+ "included: each was built on the checkpoint.",
245
+ ]
246
+ : []),
247
+ ].join("\n");
248
+ }
249
+ export function renderSkill(w, ir, t, name = `friday-${w.id}`) {
250
+ const withScript = emits(w, "workflow") && !!t.script;
251
+ const bs = briefs(w, ir);
252
+ const run = "Run the step plan yourself (sections 2-4), sizing the agents as section 1 picked, delegating every step to its agent";
253
+ const driver = w.stream === "upstream" ? upstreamDriver(w, { run, ask: t.ask }, ir.pack.id)
254
+ : w.requires?.includes("changesets") ? releaseDriver(w, { run, ask: t.ask })
255
+ : downstreamDriver(w, { run, ask: t.ask }, ir.pack.id);
256
+ const skill = [
257
+ `# ${name} (${w.stream} skill)`,
258
+ "",
259
+ w.description,
260
+ "",
261
+ withScript
262
+ ? `You run this skill yourself; only a large run goes through the workflow script \`${w.id}\`. It has three files:`
263
+ : "You run this skill yourself; there is no workflow script. It has three files:",
264
+ "",
265
+ "- this file: the agents, how to size the work, the step plan, how to run a step and the loop",
266
+ " with the user;",
267
+ "- [steps.md](steps.md): the brief every step's agent gets and the shape it returns;",
268
+ "- [shapes.md](shapes.md): every shape, with what its fields mean.",
269
+ "",
270
+ agentsTable(w, ir, bs),
271
+ "",
272
+ sizeSection(w, t, withScript),
273
+ "",
274
+ "## 2. Step plan",
275
+ "",
276
+ renderPlan(w, ir),
277
+ "",
278
+ runSection(w, t, ir),
279
+ driver,
280
+ retroRule(w),
281
+ t.notFound ?? "",
282
+ ].join("\n");
283
+ const steps = [
284
+ `# ${name}: step briefs`,
285
+ "",
286
+ "Each brief goes after the context block and `## Your task` (SKILL.md, section 3); the field",
287
+ "guide of its shape follows it.",
288
+ "",
289
+ ...bs.flatMap((b, i) => [
290
+ `## ${i + 1}. ${b.id} (${b.type})`,
291
+ "",
292
+ `Agent: ${b.agents.map((a) => `\`${a}\` (${model(ir, a)})`).join(", ")}. Returns: [${b.shape}](shapes.md#${b.shape.toLowerCase()}).`,
293
+ "",
294
+ "```text",
295
+ b.text.trimEnd(),
296
+ "```",
297
+ "",
298
+ ]),
299
+ ].join("\n");
300
+ const used = [...new Set(bs.map((b) => b.shape))];
301
+ const shapes = [
302
+ `# ${name}: shapes`,
303
+ "",
304
+ "Every agent ends its answer with one JSON object of its step's shape. The schema is the shape",
305
+ "only; the field guide below it goes into the agent's prompt.",
306
+ "",
307
+ ...used.flatMap((s) => [
308
+ `## ${s}`,
309
+ "",
310
+ `Used by: ${bs.filter((b) => b.shape === s).map((b) => `\`${b.id}\``).join(", ")}.`,
311
+ "",
312
+ "```json",
313
+ JSON.stringify(LEAN_SCHEMAS[s]),
314
+ "```",
315
+ "",
316
+ "What the fields mean:",
317
+ "",
318
+ FIELD_GUIDES[s] ?? "",
319
+ "",
320
+ ]),
321
+ ].join("\n");
322
+ return { "SKILL.md": skill, "steps.md": steps, "shapes.md": shapes };
323
+ }
324
+ /** The agent names a skill workflow delegates to, in plan order. */
325
+ export function skillAgents(w, ir) {
326
+ return [...new Set(briefs(w, ir).flatMap((b) => b.agents))];
327
+ }
package/dist/build.js ADDED
@@ -0,0 +1,77 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { strToU8, zipSync, unzipSync, strFromU8 } from "fflate";
5
+ import { adaptersFor } from "./adapters/index.js";
6
+ import { buildIR } from "./ir.js";
7
+ import { loadPack } from "./validate.js";
8
+ export const sha256 = (s) => createHash("sha256").update(s).digest("hex");
9
+ /** Compile a pack for one or all of its targets. Pure: nothing is written. */
10
+ export function buildBundles(target, packArg, specs = []) {
11
+ const lp = loadPack(packArg, specs);
12
+ const ir = buildIR(lp);
13
+ return adaptersFor(target, lp.pack.targets).map((adapter) => {
14
+ const files = adapter.emit(ir).sort((a, b) => `${a.root}/${a.path}`.localeCompare(`${b.root}/${b.path}`));
15
+ const seen = new Set();
16
+ for (const f of files) {
17
+ const k = `${f.root}/${f.path}`;
18
+ if (seen.has(k))
19
+ throw new Error(`friday: ${adapter.id} emitted ${k} twice`);
20
+ seen.add(k);
21
+ }
22
+ return {
23
+ manifest: {
24
+ friday: 1,
25
+ pack: lp.pack.id,
26
+ version: lp.pack.version,
27
+ target: adapter.id,
28
+ ...(lp.specializations?.length ? { specializations: lp.specializations.map((s) => ({ id: s.id, ...(s.version ? { version: s.version } : {}) })) } : {}),
29
+ files: files.map((f) => ({ root: f.root, path: f.path, merge: f.merge, sha256: sha256(f.content) })),
30
+ },
31
+ files,
32
+ };
33
+ });
34
+ }
35
+ export function bundleName(b) {
36
+ return `${b.manifest.pack}-${b.manifest.target}-${b.manifest.version}.zip`;
37
+ }
38
+ /** Write the bundle unpacked: <out>/<pack>-<target>/{manifest.json, files/<root>/<path>}. */
39
+ export function writeBundleDir(b, out) {
40
+ const dir = join(out, `${b.manifest.pack}-${b.manifest.target}`);
41
+ for (const f of b.files) {
42
+ const abs = join(dir, "files", f.root, f.path);
43
+ mkdirSync(dirname(abs), { recursive: true });
44
+ writeFileSync(abs, f.content);
45
+ }
46
+ writeFileSync(join(dir, "manifest.json"), JSON.stringify(b.manifest, null, 2) + "\n");
47
+ return dir;
48
+ }
49
+ // Fixed timestamp so the same pack always produces the same zip bytes.
50
+ const MTIME = new Date("2020-01-01T00:00:00Z");
51
+ export function zipBundle(b) {
52
+ const entries = {
53
+ "manifest.json": [strToU8(JSON.stringify(b.manifest, null, 2) + "\n"), { mtime: MTIME }],
54
+ };
55
+ for (const f of b.files)
56
+ entries[`files/${f.root}/${f.path}`] = [strToU8(f.content), { mtime: MTIME }];
57
+ return zipSync(entries, { level: 9 });
58
+ }
59
+ export function unzipBundle(data) {
60
+ const entries = unzipSync(data);
61
+ const m = entries["manifest.json"];
62
+ if (!m)
63
+ throw new Error("friday: not a Friday bundle (no manifest.json)");
64
+ const manifest = JSON.parse(strFromU8(m));
65
+ if (manifest.friday !== 1)
66
+ throw new Error("friday: unsupported bundle format");
67
+ const files = manifest.files.map((mf) => {
68
+ const raw = entries[`files/${mf.root}/${mf.path}`];
69
+ if (!raw)
70
+ throw new Error(`friday: bundle is missing ${mf.root}/${mf.path}`);
71
+ const content = strFromU8(raw);
72
+ if (sha256(content) !== mf.sha256)
73
+ throw new Error(`friday: checksum mismatch for ${mf.root}/${mf.path}`);
74
+ return { root: mf.root, path: mf.path, merge: mf.merge, content };
75
+ });
76
+ return { manifest, files };
77
+ }