@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,329 @@
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { parse, stringify } from "yaml";
3
+ import { schemaValidator } from "./validate.js";
4
+ /** The orchestrations whose handoff must carry one task brief per task (decision 40). */
5
+ export function requiredBriefs(lp) {
6
+ return new Set(lp.orchestrations.filter((w) => w.steps.some((s) => s.type === "agent" && s.output === "briefs")).map((w) => w.id));
7
+ }
8
+ /** The checkpoints and approver roles each orchestration's handoff must record (decision 39). */
9
+ export function requiredCheckpoints(lp) {
10
+ const out = {};
11
+ for (const w of lp.orchestrations) {
12
+ const ids = w.steps.flatMap((s) => (s.type === "approval" && s.checkpoint ? [s.checkpoint] : []));
13
+ if (!ids.length)
14
+ continue;
15
+ out[w.id] = ids.map((checkpoint) => ({
16
+ checkpoint,
17
+ role: lp.pack.checkpoints?.find((c) => c.id === checkpoint)?.approver ?? "",
18
+ }));
19
+ }
20
+ return out;
21
+ }
22
+ /** The levels and approver roles each orchestration with approval steps needs (decision 33). */
23
+ export function requiredApprovals(lp) {
24
+ const out = {};
25
+ for (const w of lp.orchestrations) {
26
+ const levels = w.steps.flatMap((s) => (s.type === "approval" && s.level ? [s.level] : []));
27
+ if (!levels.length)
28
+ continue;
29
+ out[w.id] = levels.map((level) => ({
30
+ level,
31
+ role: lp.pack.promptPyramid?.levels.find((l) => l.id === level)?.approver ?? "",
32
+ }));
33
+ }
34
+ return out;
35
+ }
36
+ /**
37
+ * A task's `covers` entry names an acceptance criterion by its id (AC12) or the start of its
38
+ * text, cut at a word boundary: "AC1" covers "AC1: ..." but not "AC12: ..." (decision 50). The
39
+ * generated workflow runtime applies the same rule to the breakdown.
40
+ */
41
+ export function coversCriterion(entry, criterion) {
42
+ const e = entry.trim();
43
+ const c = criterion.trim();
44
+ if (!e)
45
+ return false;
46
+ return c === e || (c.startsWith(e) && !/[A-Za-z0-9]/.test(c.charAt(e.length)));
47
+ }
48
+ /**
49
+ * The gate between upstream and downstream. Downstream needs status approved; --pending accepts
50
+ * awaiting-approval (used before asking the user to approve). With `stacks` (stack -> the task kinds
51
+ * of its engineer), every task must name a stack whose engineer can do its taskKind.
52
+ */
53
+ export function checkHandoff(file, opts = {}) {
54
+ let data;
55
+ try {
56
+ data = parse(readFileSync(file, "utf8"));
57
+ }
58
+ catch (err) {
59
+ return { ok: false, problems: [`cannot read ${file}: ${err.message}`], warnings: [] };
60
+ }
61
+ const v = schemaValidator("handoff");
62
+ const problems = [];
63
+ const warnings = [];
64
+ if (!v(data)) {
65
+ for (const e of v.errors ?? [])
66
+ problems.push(`${e.instancePath || "/"} ${e.message ?? "is invalid"}`);
67
+ return { ok: false, problems, warnings };
68
+ }
69
+ const h = data;
70
+ const allowed = opts.pending ? ["awaiting-approval", "approved"] : ["approved"];
71
+ if (!allowed.includes(h.status))
72
+ problems.push(`status is ${h.status}; need ${allowed.join(" or ")}`);
73
+ const ids = new Set();
74
+ for (const t of h.tasks) {
75
+ if (ids.has(t.id))
76
+ problems.push(`duplicate task id ${t.id}`);
77
+ ids.add(t.id);
78
+ if (opts.stacks) {
79
+ const kinds = opts.stacks[t.stack];
80
+ if (!kinds)
81
+ problems.push(`task ${t.id}: unknown stack ${t.stack} (${Object.keys(opts.stacks).join(", ")})`);
82
+ else if (!kinds.includes(t.taskKind))
83
+ problems.push(`task ${t.id}: the ${t.stack} engineer has no taskKind ${t.taskKind} (${kinds.join(", ")})`);
84
+ }
85
+ }
86
+ for (const t of h.tasks) {
87
+ for (const d of t.dependsOn)
88
+ if (!ids.has(d))
89
+ problems.push(`task ${t.id} depends on unknown task ${d}`);
90
+ // A task that breaks other codebases names the tasks that make them green again (decision 50).
91
+ if (t.breaks?.length && !t.closedBy?.length)
92
+ problems.push(`task ${t.id} breaks ${t.breaks.join(", ")} but names no closedBy tasks`);
93
+ for (const c of t.closedBy ?? [])
94
+ if (!ids.has(c))
95
+ problems.push(`task ${t.id}: closedBy names unknown task ${c}`);
96
+ }
97
+ // Every scope acceptance criterion maps to at least one task (decision 50). Handoffs written
98
+ // before tasks had `covers` are still ready, with a warning.
99
+ const acceptance = h.scope.acceptance;
100
+ if (h.tasks.some((t) => t.covers?.length)) {
101
+ for (const ac of acceptance) {
102
+ if (!h.tasks.some((t) => (t.covers ?? []).some((e) => coversCriterion(e, ac))))
103
+ problems.push(`acceptance criterion not covered by any task: ${ac}`);
104
+ }
105
+ for (const t of h.tasks) {
106
+ for (const e of t.covers ?? []) {
107
+ if (!acceptance.some((ac) => coversCriterion(e, ac)))
108
+ problems.push(`task ${t.id} covers "${e}", which is no scope acceptance criterion`);
109
+ }
110
+ }
111
+ }
112
+ else {
113
+ warnings.push("no task declares covers; acceptance coverage was not checked");
114
+ }
115
+ // "Published" is not "installable where the agents run": the preflight checks met ones again (decision 48).
116
+ for (const p of h.prerequisites ?? []) {
117
+ if (p.status !== "met")
118
+ problems.push(`prerequisite ${p.id} is unmet: ${p.description} (check: ${p.check})`);
119
+ }
120
+ for (const q of h.questions)
121
+ if (!q.answer.trim())
122
+ problems.push(`question ${q.id} has no answer`);
123
+ // Scopes: an expected outcome is the user's, never assumed; every task delivers a known scope.
124
+ const scopes = h.scope.scopes;
125
+ if (scopes?.length) {
126
+ const scopeIds = new Set();
127
+ const answered = new Set(h.questions.filter((q) => q.answer.trim()).map((q) => q.id));
128
+ for (const sc of scopes) {
129
+ if (scopeIds.has(sc.id))
130
+ problems.push(`duplicate scope id ${sc.id}`);
131
+ scopeIds.add(sc.id);
132
+ if (sc.outcomeSource === "answer" && !(sc.answerId && answered.has(sc.answerId))) {
133
+ problems.push(`scope ${sc.id}: its expected outcome comes from an answer, but ${sc.answerId ? `question ${sc.answerId} is not answered` : "it names no answerId"}`);
134
+ }
135
+ }
136
+ for (const t of h.tasks) {
137
+ if (!t.scope)
138
+ problems.push(`task ${t.id} names no scope (${[...scopeIds].join(", ")})`);
139
+ else if (!scopeIds.has(t.scope))
140
+ problems.push(`task ${t.id}: unknown scope ${t.scope}`);
141
+ }
142
+ }
143
+ for (const g of h.gaps) {
144
+ if (g.recommended >= g.solutions.length)
145
+ problems.push(`gap ${g.id}: recommended index out of range`);
146
+ }
147
+ // Prompt pyramid: every level the orchestration stops for was approved by its role, in order.
148
+ const need = opts.approvals?.[h.workflow];
149
+ if (need) {
150
+ const got = h.promptPyramid?.levels ?? [];
151
+ for (const n of need) {
152
+ const l = got.find((g) => g.id === n.level);
153
+ if (!l)
154
+ problems.push(`promptPyramid: level ${n.level} was never approved`);
155
+ else if (l.approvedBy !== n.role)
156
+ problems.push(`promptPyramid: level ${n.level} was approved by ${l.approvedBy}; the pyramid needs ${n.role}`);
157
+ }
158
+ const order = need.map((n) => n.level);
159
+ const seen = got.map((g) => g.id).filter((id) => order.includes(id));
160
+ if (seen.some((id, i) => id !== order.filter((o) => seen.includes(o))[i])) {
161
+ problems.push(`promptPyramid.levels must follow the pyramid, bottom first (${order.join(" < ")})`);
162
+ }
163
+ }
164
+ // Task briefs (decision 40): one per task, naming only what the handoff holds.
165
+ if (opts.briefs?.has(h.workflow) || h.briefs) {
166
+ const taskIds = new Set(h.tasks.map((t) => t.id));
167
+ const briefed = new Set((h.briefs ?? []).map((b) => b.task));
168
+ for (const t of h.tasks)
169
+ if (!briefed.has(t.id))
170
+ problems.push(`task ${t.id} has no brief`);
171
+ const ids = (xs) => new Set((xs ?? []).map((x) => x.id));
172
+ const known = { decision: ids(h.decisions), contract: ids(h.contracts), interface: ids(h.interfaceContracts) };
173
+ for (const b of h.briefs ?? []) {
174
+ if (!taskIds.has(b.task)) {
175
+ problems.push(`brief ${b.task}: unknown task`);
176
+ continue;
177
+ }
178
+ for (const d of b.decisions ?? [])
179
+ if (!known.decision.has(d))
180
+ problems.push(`brief ${b.task}: unknown decision ${d}`);
181
+ for (const c of b.contracts ?? [])
182
+ if (!known.contract.has(c))
183
+ problems.push(`brief ${b.task}: unknown contract ${c}`);
184
+ for (const i of b.interfaces ?? [])
185
+ if (!known.interface.has(i))
186
+ problems.push(`brief ${b.task}: unknown interface ${i}`);
187
+ const plan = h.plan?.find((p) => p.task === b.task);
188
+ if (h.plan) {
189
+ for (const f of b.files ?? [])
190
+ if (!plan?.files?.includes(f))
191
+ problems.push(`brief ${b.task}: ${f} is not in the build plan for ${b.task}`);
192
+ for (const f of b.testFiles ?? [])
193
+ if (!plan?.testFiles?.includes(f))
194
+ problems.push(`brief ${b.task}: ${f} is not a test file the build plan gives ${b.task}`);
195
+ }
196
+ }
197
+ }
198
+ // Checkpoints: every one the orchestration stops for was approved by its role (decision 39).
199
+ for (const n of opts.checkpoints?.[h.workflow] ?? []) {
200
+ const c = h.checkpoints?.find((x) => x.id === n.checkpoint);
201
+ if (!c)
202
+ problems.push(`checkpoints: ${n.checkpoint} was never approved`);
203
+ else if (c.approvedBy !== n.role)
204
+ problems.push(`checkpoints: ${n.checkpoint} was approved by ${c.approvedBy}; it needs ${n.role}`);
205
+ }
206
+ // The readable handoff (decision 38): the person approves handoff.md, so it must be the render
207
+ // of exactly this yaml.
208
+ if (opts.readable) {
209
+ const md = readablePath(file);
210
+ if (!existsSync(md))
211
+ problems.push("handoff.md is missing: run friday handoff render (the person approves handoff.md)");
212
+ else if (readFileSync(md, "utf8") !== renderHandoff(data)) {
213
+ problems.push("handoff.md does not match handoff.yaml: run friday handoff render (never edit handoff.md)");
214
+ }
215
+ }
216
+ return { ok: problems.length === 0, status: h.status, problems, warnings };
217
+ }
218
+ /** Where the readable handoff lives: next to the yaml, same name, .md. */
219
+ export function readablePath(file) {
220
+ return file.replace(/\.ya?ml$/, "") + ".md";
221
+ }
222
+ /** Tasks in dependency order; ties keep the handoff's order. */
223
+ function dependencyOrder(tasks) {
224
+ const done = new Set();
225
+ const out = [];
226
+ const left = [...tasks];
227
+ while (left.length) {
228
+ const i = left.findIndex((t) => t.dependsOn.every((d) => done.has(d) || !tasks.some((x) => x.id === d)));
229
+ const [next] = left.splice(i < 0 ? 0 : i, 1); // a cycle (refused by the check) keeps the order
230
+ out.push(next);
231
+ done.add(next.id);
232
+ }
233
+ return out;
234
+ }
235
+ /** One sentence ending in exactly one full stop, whatever the yaml text ends with. */
236
+ const sentence = (v) => v.trim().replace(/[.\s]+$/, "") + ".";
237
+ const cell = (v) => String(v ?? "").replace(/\|/g, "\\|").replace(/\n/g, " ");
238
+ const list = (items) => (items ?? []).map((i) => `- ${i}`);
239
+ /** Fields with their own section; every other field is shown as YAML, so nothing is hidden. */
240
+ const LAID_OUT = new Set(["workId", "status", "workflow", "approvedBy", "checkpoints", "briefs", "scope", "decisions", "dataClassification", "promptPyramid", "prerequisites", "tasks", "questions", "gaps", "openQuestions"]);
241
+ /** handoff.md: the text a person reads and approves, rendered deterministically from the yaml. */
242
+ export function renderHandoff(h) {
243
+ const out = [
244
+ `# Handoff: ${h.workId}`,
245
+ "",
246
+ "Rendered by `friday handoff render` from handoff.yaml. Do not edit: change the yaml and render again.",
247
+ "",
248
+ `Status: ${h.status}. Workflow: ${h.workflow}.${h.approvedBy ? ` Approved by: ${h.approvedBy}.` : ""}`,
249
+ "",
250
+ ];
251
+ if (h.checkpoints?.length) {
252
+ out.push("## Approved checkpoints", "", "| Checkpoint | Approved by (role) | What was approved | File |", "| --- | --- | --- | --- |");
253
+ for (const c of h.checkpoints)
254
+ out.push(`| ${cell(c.id)} | ${cell(c.approvedBy)} | ${cell(c.summary)} | ${cell(c.file)} |`);
255
+ out.push("");
256
+ }
257
+ out.push("## Scope", "", h.scope.summary);
258
+ if (h.scope.scopes?.length) {
259
+ out.push("", "Scopes, each with the outcome the user expects:", "");
260
+ for (const sc of h.scope.scopes) {
261
+ const from = sc.outcomeSource === "answer" ? `answer ${sc.answerId ?? "?"}` : "the request";
262
+ out.push(`- **${sc.id}** ${sc.title}: ${sc.expectedOutcome} (from ${from})`);
263
+ }
264
+ }
265
+ out.push("", "Acceptance:", "", ...list(h.scope.acceptance));
266
+ if (h.scope.inScope?.length)
267
+ out.push("", "In scope:", "", ...list(h.scope.inScope));
268
+ if (h.scope.outOfScope?.length)
269
+ out.push("", "Out of scope (follow-up work):", "", ...list(h.scope.outOfScope));
270
+ out.push("", "## Decisions", "");
271
+ for (const d of h.decisions)
272
+ out.push(`- **${d.id}** ${sentence(d.decision)} Why: ${sentence(d.why)}${d.where ? ` Where: ${sentence(d.where)}` : ""}`);
273
+ out.push("", "## Data classification", "", "| Entity | Class | Owner | Retention | Fields |", "| --- | --- | --- | --- | --- |");
274
+ for (const c of h.dataClassification)
275
+ out.push(`| ${cell(c.entity)} | ${cell(c.class)} | ${cell(c.owner)} | ${cell(c.retention)} | ${cell((c.fields ?? []).join(", "))} |`);
276
+ if (h.promptPyramid?.levels.length) {
277
+ out.push("", "## Approved prompt pyramid levels", "", "| Level | Approved by (role) | What was approved | File |", "| --- | --- | --- | --- |");
278
+ for (const l of h.promptPyramid.levels)
279
+ out.push(`| ${cell(l.id)} | ${cell(l.approvedBy)} | ${cell(l.summary)} | ${cell(l.file)} |`);
280
+ }
281
+ if (h.prerequisites?.length) {
282
+ out.push("", "## Prerequisites", "", "Checked again by the delivery preflight where the agents run.", "", "| Id | Kind | What | Check | Status |", "| --- | --- | --- | --- | --- |");
283
+ for (const p of h.prerequisites)
284
+ out.push(`| ${cell(p.id)} | ${cell(p.kind)} | ${cell(p.description)} | ${cell(p.check)} | ${cell(p.status)} |`);
285
+ }
286
+ out.push("", "## Tasks", "", "In dependency order.");
287
+ for (const t of dependencyOrder(h.tasks)) {
288
+ out.push("", `### ${t.id}: ${t.title}`, "", `Stack: ${t.stack}. Codebase: ${t.codebase}. Kind: ${t.taskKind}.${t.scope ? ` Scope: ${t.scope}.` : ""}${t.lowestLevel ? ` Lowest test level: ${t.lowestLevel}.` : ""}`, t.dependsOn.length ? `Depends on: ${t.dependsOn.join(", ")}.` : "Depends on nothing.", ...(t.conventions?.length ? [`Conventions: ${t.conventions.join(", ")}.`] : []), ...(t.covers?.length ? [`Covers: ${t.covers.join(", ")}.`] : []), ...(t.needs?.length ? [`Needs: ${t.needs.join(", ")}.`] : []), ...(t.breaks?.length ? [`Breaks ${t.breaks.join(", ")} until ${(t.closedBy ?? []).join(", ") || "?"} are done.`] : []), "", "Acceptance:", "", ...list(t.acceptance));
289
+ const b = h.briefs?.find((x) => x.task === t.id);
290
+ if (b) {
291
+ const uses = [
292
+ ["decisions", b.decisions],
293
+ ["contracts", b.contracts],
294
+ ["interfaces", b.interfaces],
295
+ ["files", b.files],
296
+ ["test files", b.testFiles],
297
+ ].filter(([, v]) => v?.length);
298
+ out.push("", "Brief (what its agents receive):", "", "```text", b.text.trimEnd(), "```");
299
+ if (uses.length)
300
+ out.push("", `Uses: ${uses.map(([k, v]) => `${k} ${v.join(", ")}`).join("; ")}.`);
301
+ }
302
+ }
303
+ out.push("", "## Questions and answers", "");
304
+ for (const q of h.questions) {
305
+ out.push(`- **${q.id}** ${q.question}`, ` Answer: ${q.answer}`, ...(q.interpretation ? [` Read as: ${q.interpretation}`] : []));
306
+ }
307
+ if (!h.questions.length)
308
+ out.push("None.");
309
+ out.push("", "## Gaps and resolutions", "");
310
+ for (const g of h.gaps) {
311
+ out.push(`- **${g.id}** ${g.gap} (${g.area}, impact ${g.impact})`, ` Why: ${g.why}`);
312
+ g.solutions.forEach((sol, i) => out.push(` ${i + 1}. ${sol.option}: ${sol.tradeoff}${i === g.recommended ? " (recommended)" : ""}`));
313
+ out.push(` Resolution: ${g.resolution}`);
314
+ }
315
+ if (!h.gaps.length)
316
+ out.push("None.");
317
+ for (const key of Object.keys(h)) {
318
+ if (LAID_OUT.has(key))
319
+ continue;
320
+ out.push("", `## ${key}`, "", "```yaml", stringify(h[key]).trimEnd(), "```");
321
+ }
322
+ return out.join("\n") + "\n";
323
+ }
324
+ /** Render handoff.md next to the yaml and return its path. */
325
+ export function writeReadable(file) {
326
+ const md = readablePath(file);
327
+ writeFileSync(md, renderHandoff(parse(readFileSync(file, "utf8"))));
328
+ return md;
329
+ }
@@ -0,0 +1,137 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join, relative, resolve } from "node:path";
3
+ import { ADAPTERS } from "./adapters/index.js";
4
+ import { CONFIG_DIR_TOKEN, defaultHome } from "./adapters/adapter.js";
5
+ import { sha256 } from "./build.js";
6
+ function lockPath(scope, dir, home) {
7
+ return join(scope === "global" ? home : dir, ".friday", "lock.json");
8
+ }
9
+ function readLock(p) {
10
+ if (!existsSync(p))
11
+ return { version: 1, files: {} };
12
+ return JSON.parse(readFileSync(p, "utf8"));
13
+ }
14
+ export function markerBlock(pack, content) {
15
+ // One block per pack; Friday's own pack is plain "friday".
16
+ const tag = pack === "friday" ? "friday" : `friday:${pack}`;
17
+ const start = `<!-- ${tag}:start -->`;
18
+ const end = `<!-- ${tag}:end -->`;
19
+ return { start, end, block: `${start}\n${content.trimEnd()}\n${end}\n` };
20
+ }
21
+ export function mergeMarker(current, pack, content) {
22
+ const { start, end, block } = markerBlock(pack, content);
23
+ const i = current.indexOf(start);
24
+ const k = current.indexOf(end);
25
+ if (i >= 0 && k > i) {
26
+ const after = current.slice(k + end.length).replace(/^\n/, "");
27
+ return current.slice(0, i) + block + after;
28
+ }
29
+ if (!current.trim())
30
+ return block;
31
+ return current.replace(/\n*$/, "\n\n") + block;
32
+ }
33
+ /** Objects merge key by key, arrays are unioned (existing order first), scalars from `add` win. */
34
+ export function deepMerge(base, add) {
35
+ if (Array.isArray(base) && Array.isArray(add)) {
36
+ const out = [...base];
37
+ for (const v of add)
38
+ if (!out.some((o) => JSON.stringify(o) === JSON.stringify(v)))
39
+ out.push(v);
40
+ return out;
41
+ }
42
+ if (base && add && typeof base === "object" && typeof add === "object" && !Array.isArray(base) && !Array.isArray(add)) {
43
+ const out = { ...base };
44
+ for (const [k, v] of Object.entries(add))
45
+ out[k] = k in out ? deepMerge(out[k], v) : v;
46
+ return out;
47
+ }
48
+ return add;
49
+ }
50
+ export function installBundle(bundle, opts) {
51
+ const adapter = ADAPTERS[bundle.manifest.target];
52
+ const home = opts.home ?? defaultHome();
53
+ const dir = resolve(opts.dir ?? ".");
54
+ const roots = adapter.roots(opts.scope, dir, home);
55
+ // Project files reference the config dir relatively, so the folder can move; global ones absolutely.
56
+ const configRef = opts.scope === "global" ? roots.config : relative(roots.base, roots.config) || ".";
57
+ const lp = lockPath(opts.scope, dir, home);
58
+ const lock = readLock(lp);
59
+ const results = [];
60
+ const writes = [];
61
+ const { pack, version, target } = bundle.manifest;
62
+ for (const f of bundle.files) {
63
+ const abs = join(f.root === "config" ? roots.config : roots.base, f.path);
64
+ const content = f.content.split(CONFIG_DIR_TOKEN).join(configRef);
65
+ const exists = existsSync(abs);
66
+ const current = exists ? readFileSync(abs, "utf8") : "";
67
+ if (f.merge === "marker") {
68
+ const next = mergeMarker(current, pack, content);
69
+ results.push({ path: abs, action: next === current ? "unchanged" : exists ? "merged" : "created" });
70
+ if (next !== current)
71
+ writes.push([abs, next]);
72
+ continue;
73
+ }
74
+ if (f.merge === "json") {
75
+ let base = {};
76
+ if (exists) {
77
+ try {
78
+ base = JSON.parse(current);
79
+ }
80
+ catch {
81
+ results.push({ path: abs, action: "conflict", reason: "existing file is not valid JSON; not touched" });
82
+ continue;
83
+ }
84
+ }
85
+ const next = JSON.stringify(deepMerge(base, JSON.parse(content)), null, 2) + "\n";
86
+ const same = exists && JSON.stringify(JSON.parse(current)) === JSON.stringify(JSON.parse(next));
87
+ results.push({ path: abs, action: same ? "unchanged" : exists ? "merged" : "created" });
88
+ if (!same)
89
+ writes.push([abs, next]);
90
+ continue;
91
+ }
92
+ const hash = sha256(content);
93
+ const entry = { sha256: hash, pack, target, version };
94
+ if (!exists) {
95
+ results.push({ path: abs, action: "created" });
96
+ writes.push([abs, content]);
97
+ lock.files[abs] = entry;
98
+ }
99
+ else if (current === content) {
100
+ results.push({ path: abs, action: "unchanged" });
101
+ lock.files[abs] = entry;
102
+ }
103
+ else if (lock.files[abs]?.sha256 === sha256(current)) {
104
+ // Still exactly what Friday wrote last time: safe to update.
105
+ results.push({ path: abs, action: "updated" });
106
+ writes.push([abs, content]);
107
+ lock.files[abs] = entry;
108
+ }
109
+ else if (opts.force) {
110
+ results.push({ path: abs, action: "forced", reason: "local changes overwritten (--force)" });
111
+ writes.push([abs, content]);
112
+ lock.files[abs] = entry;
113
+ }
114
+ else {
115
+ results.push({ path: abs, action: "conflict", reason: "changed locally or not written by Friday; kept (use --force)" });
116
+ }
117
+ }
118
+ if (!opts.dryRun) {
119
+ for (const [abs, content] of writes) {
120
+ mkdirSync(dirname(abs), { recursive: true });
121
+ writeFileSync(abs, content);
122
+ }
123
+ mkdirSync(dirname(lp), { recursive: true });
124
+ writeFileSync(lp, JSON.stringify(lock, null, 2) + "\n");
125
+ }
126
+ return {
127
+ pack,
128
+ version,
129
+ target,
130
+ scope: opts.scope,
131
+ roots,
132
+ dryRun: !!opts.dryRun,
133
+ files: results,
134
+ conflicts: results.filter((r) => r.action === "conflict").length,
135
+ ...(adapter.reloadNote && results.some((r) => r.action !== "unchanged" && r.action !== "conflict") ? { note: adapter.reloadNote } : {}),
136
+ };
137
+ }
package/dist/ir.js ADDED
@@ -0,0 +1,177 @@
1
+ export function agentGuards(pack, kind) {
2
+ const g = pack.guardrails;
3
+ return {
4
+ blockedCommands: g?.loopCommands?.taskKinds.includes(kind) ? (pack.testPyramid?.forbiddenInLoop ?? []) : [],
5
+ protectedPaths: g?.protectedTests?.taskKinds.includes(kind) ? g.protectedTests.patterns : [],
6
+ writeOncePaths: g?.approvedPrompts?.taskKinds.includes(kind) ? g.approvedPrompts.patterns : [],
7
+ };
8
+ }
9
+ export function effortGuidance(effort = "medium") {
10
+ switch (effort) {
11
+ case "low":
12
+ return "Keep the work bounded; follow the explicit task and checks without expanding scope.";
13
+ case "medium":
14
+ return "Work thoroughly within scope and validate the assumptions that affect the result.";
15
+ case "high":
16
+ return "Trace relevant dependencies, compare trade-offs, and check cross-component effects and edge cases without expanding scope.";
17
+ case "xhigh":
18
+ return "Do a deep end-to-end analysis of dependencies, failure modes, and alternatives; verify the plan against acceptance criteria without expanding scope.";
19
+ case "max":
20
+ return "Exhaustively analyze critical interactions, failure modes, and alternatives; give explicit evidence for decisions and validation while keeping the requested scope.";
21
+ }
22
+ }
23
+ export function agentName(persona, taskKind) {
24
+ return `${persona}--${taskKind}`;
25
+ }
26
+ export function renderConvention(c) {
27
+ const out = [`# ${c.id}`, "", c.description, ""];
28
+ if (c.appliesTo)
29
+ out.push(`Applies to: ${c.appliesTo.paths.map((p) => `\`${p}\``).join(", ")}`, "");
30
+ if (c.regions) {
31
+ out.push("## Regions", "", "| Runtime | Region |", "| --- | --- |");
32
+ for (const [k, v] of Object.entries(c.regions)) {
33
+ out.push(`| ${k} | ${typeof v === "string" ? `\`${v}\`` : formatRegion(v)} |`);
34
+ }
35
+ out.push("");
36
+ }
37
+ if (c.layout)
38
+ out.push("## Layout", "", "```text", c.layout.trimEnd(), "```", "");
39
+ out.push("## Rules", "");
40
+ for (const r of c.rules) {
41
+ out.push(`- **${r.id}.** ${r.rule}`);
42
+ if (r.why)
43
+ out.push(` - Why: ${r.why}`);
44
+ if (r.source)
45
+ out.push(` - Source: \`${r.source}\``);
46
+ }
47
+ return out.join("\n") + "\n";
48
+ }
49
+ function formatRegion(v) {
50
+ if (v && typeof v === "object") {
51
+ const o = v;
52
+ const parts = [];
53
+ if (o["choose-once"])
54
+ parts.push("chosen once, permanent");
55
+ if (o.default)
56
+ parts.push(`default \`${String(o.default)}\``);
57
+ if (Array.isArray(o.allowed))
58
+ parts.push(`allowed: ${o.allowed.map((a) => `\`${String(a)}\``).join(", ")}`);
59
+ return parts.join("; ");
60
+ }
61
+ return String(v);
62
+ }
63
+ function agentBody(lp, p, kind) {
64
+ const k = lp.policy.taskKinds[kind];
65
+ const convs = (p.conventions ?? [])
66
+ .map((id) => lp.conventions.find((c) => c.id === id))
67
+ .filter((c) => !!c);
68
+ const out = [
69
+ `# ${p.name} (${kind})`,
70
+ "",
71
+ `Role: ${p.role}`,
72
+ "",
73
+ p.prompt.trimEnd(),
74
+ "",
75
+ `## Effort profile: ${k.effort ?? "medium"}`,
76
+ "",
77
+ effortGuidance(k.effort),
78
+ "",
79
+ `## This agent: ${kind}`,
80
+ "",
81
+ k.contract,
82
+ ];
83
+ const note = p.taskKindNotes?.[kind];
84
+ if (note)
85
+ out.push("", note);
86
+ if (p.dataAccess !== "none") {
87
+ out.push("", "## Data access", "", p.dataAccess === "pii"
88
+ ? "You may handle personal data only through personal-data-safe use cases, and output aggregates or pseudonymised identifiers only."
89
+ : "You must not handle personal data. If an input is pii or unclassified, stop and return blocked.");
90
+ }
91
+ if (convs.length) {
92
+ out.push("", "## Conventions", "", "Follow these conventions (loaded as skills or rules):", "");
93
+ for (const c of convs)
94
+ out.push(`- \`${c.id}\`: ${c.description}`);
95
+ }
96
+ const guards = agentGuards(lp.pack, kind);
97
+ if (guards.blockedCommands.length || guards.protectedPaths.length || guards.writeOncePaths.length) {
98
+ out.push("", "## Guardrails (enforced)", "", "These are checked before each tool call; a blocked call is refused, not retried:", "");
99
+ if (guards.blockedCommands.length) {
100
+ out.push(`- You work inside a task loop: commands containing ${guards.blockedCommands.map((c) => `\`${c}\``).join(", ")} are blocked. Integration runs them once, at the end.`);
101
+ }
102
+ if (guards.protectedPaths.length) {
103
+ out.push(`- You make tests pass; you do not change them. Files matching ${guards.protectedPaths.map((p) => `\`${p}\``).join(", ")} are protected. A test that is wrong is a blocker: return blocked with the question.`);
104
+ }
105
+ if (guards.writeOncePaths.length) {
106
+ out.push(`- Approved prompt files are write-once: files matching ${guards.writeOncePaths.map((p) => `\`${p}\``).join(", ")} hold a prompt pyramid level a person approved. Create one only by copying its approved level file exactly, when it does not exist yet; never change one that exists. A stale or wrong one is a blocker: return blocked naming the level, and a person replaces it.`);
107
+ }
108
+ }
109
+ if (lp.pack.contract)
110
+ out.push("", lp.pack.contract.trimEnd());
111
+ return out.join("\n") + "\n";
112
+ }
113
+ export function buildIR(lp) {
114
+ const agents = [];
115
+ const agentIndex = {};
116
+ const skillIds = new Set(lp.conventions.filter((c) => c.emit.includes("skill")).map((c) => c.id));
117
+ for (const p of lp.personas) {
118
+ agentIndex[p.id] = {};
119
+ for (const kind of p.taskKinds) {
120
+ const k = lp.policy.taskKinds[kind];
121
+ const name = agentName(p.id, kind);
122
+ agentIndex[p.id][kind] = name;
123
+ agents.push({
124
+ name,
125
+ persona: p,
126
+ taskKind: kind,
127
+ tier: k.model,
128
+ ...(k.effort ? { effort: k.effort } : {}),
129
+ description: `${p.name} (${kind}). ${p.description}`,
130
+ body: agentBody(lp, p, kind),
131
+ skills: (p.conventions ?? []).filter((c) => skillIds.has(c)),
132
+ conventions: p.conventions ?? [],
133
+ deniedTools: p.dataAccess === "non-pii" ? (lp.pack.dataAccess?.piiTools ?? []) : [],
134
+ guards: agentGuards(lp.pack, kind),
135
+ });
136
+ }
137
+ }
138
+ return {
139
+ pack: lp.pack,
140
+ policy: lp.policy,
141
+ agents,
142
+ conventions: lp.conventions.map((c) => ({ convention: c, body: renderConvention(c) })),
143
+ orchestrations: lp.orchestrations,
144
+ agentIndex,
145
+ instructions: renderInstructions(lp),
146
+ };
147
+ }
148
+ function renderInstructions(lp) {
149
+ const { pack, policy } = lp;
150
+ const out = [
151
+ `# ${pack.name} (Friday pack ${pack.id} v${pack.version})`,
152
+ "",
153
+ pack.description,
154
+ "",
155
+ "## How work flows",
156
+ "",
157
+ "- **Upstream** orchestrations (" +
158
+ lp.orchestrations.filter((w) => w.stream === "upstream").map((w) => `\`${w.id}\``).join(", ") +
159
+ ") resolve blockers and end in `docs/friday/<workId>/handoff.yaml`.",
160
+ "- **Downstream** orchestrations (" +
161
+ lp.orchestrations.filter((w) => w.stream === "downstream").map((w) => `\`${w.id}\``).join(", ") +
162
+ ") start only from an approved handoff and never guess: missing information goes back upstream.",
163
+ "",
164
+ "## Models by kind of work",
165
+ "",
166
+ "| Task kind | Model | Effort | Why |",
167
+ "| --- | --- | --- | --- |",
168
+ ...Object.entries(policy.taskKinds).map(([k, v]) => `| ${k} | ${v.model} | ${v.effort ?? "medium"} | ${v.why} |`),
169
+ "",
170
+ "## Agents",
171
+ "",
172
+ ...lp.personas.map((p) => `- \`${p.id}\` (${p.taskKinds.join(", ")}): ${p.role}`),
173
+ ];
174
+ if (pack.contract)
175
+ out.push("", pack.contract.trimEnd());
176
+ return out.join("\n") + "\n";
177
+ }