@digital-agora/friday 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +6 -3
  2. package/bundles/friday-claude-0.1.0.zip +0 -0
  3. package/bundles/friday-opencode-0.1.0.zip +0 -0
  4. package/dist/adapters/claude/index.js +2 -1
  5. package/dist/adapters/claude/runtime.js +293 -49
  6. package/dist/adapters/claude/workflows.js +91 -36
  7. package/dist/adapters/drivers.js +41 -14
  8. package/dist/adapters/opencode/index.js +2 -1
  9. package/dist/adapters/skill.js +10 -2
  10. package/dist/cli.js +42 -7
  11. package/dist/contracts.js +200 -0
  12. package/dist/flow.js +227 -0
  13. package/dist/graph.js +11 -5
  14. package/dist/handoff.js +76 -3
  15. package/dist/ir.js +1 -0
  16. package/dist/load.js +3 -0
  17. package/dist/prompts.js +81 -5
  18. package/dist/reads.js +1 -1
  19. package/dist/slice.js +90 -0
  20. package/dist/specialize.js +10 -0
  21. package/dist/step-schemas.js +28 -3
  22. package/dist/validate.js +38 -20
  23. package/pack/model-policy.yaml +5 -0
  24. package/pack/orchestrations/architecture-decision.yaml +5 -0
  25. package/pack/orchestrations/bugfix-tdd.yaml +1 -1
  26. package/pack/orchestrations/discovery.yaml +16 -3
  27. package/pack/orchestrations/feature-delivery.yaml +11 -3
  28. package/pack/orchestrations/prompt-delivery.yaml +13 -5
  29. package/pack/orchestrations/prompt-discovery.yaml +3 -0
  30. package/pack/pack.yaml +12 -2
  31. package/pack/personas/backend-engineer.yaml +1 -1
  32. package/pack/personas/devops-engineer.yaml +1 -1
  33. package/pack/personas/frontend-engineer.yaml +1 -1
  34. package/package.json +1 -1
  35. package/schemas/decisions.schema.yaml +28 -0
  36. package/schemas/handoff.schema.yaml +66 -4
  37. package/schemas/orchestration.schema.yaml +10 -4
  38. package/schemas/pack.schema.yaml +25 -0
package/dist/prompts.js CHANGED
@@ -1,3 +1,34 @@
1
+ /**
2
+ * Every option offered to a person is a complete rule (decision 56): choosing a vague option ("linear
3
+ * interpolation", "each field optional") left a narrower question behind, and delivery stopped again.
4
+ */
5
+ export const COMPLETE_OPTIONS = [
6
+ "Write every option as the complete rule the code will follow: the exact formula, merge, default,",
7
+ "allowed range or threshold, not a family of rules. Trace it through every contract that touches it",
8
+ "(merges, comparisons, ordering, parsers, alerts) and complete or split an option that would leave a",
9
+ "follow-up question once chosen.",
10
+ ].join("\n");
11
+ /**
12
+ * What a task's agents get of the handoff (decision 60): its slice, by default. The Claude runtime
13
+ * cuts it in sliceOf (src/adapters/claude/runtime.ts); a skill or the OpenCode orchestrator cuts it
14
+ * by this text.
15
+ */
16
+ export const TASK_SLICE = "the handoff scoped to that task: its workId and scope summary, the task and the tasks it depends on, the decisions whose `where` names its codebase or no place, the acceptance criteria it covers, the contracts that list it or no task, the interface contracts its brief names (all when it names none), the standards, its build-plan entry, the red tests it owns, the data classification, the commands and the delivery policy";
17
+ /**
18
+ * The project's documented decisions, for every upstream step (decision 64). The join settles an
19
+ * open item by topic; these lines make the agents label items with the decisions' topics, so it can.
20
+ */
21
+ export const documentedDecisionsText = (ds) => [
22
+ "Documented decisions of this project (settled: build on them and never ask about them again). Give an item about one of them",
23
+ "that decision's topic. If the request, an answer or a finding contradicts one, keep the item and name the decision's id in",
24
+ "contradicts. The handoff records each one the work relies on in decisions, with its source.",
25
+ ...ds.map((d) => `- ${d.id} [${d.topics.join(", ")}]: ${d.decision} (source: ${d.source})`),
26
+ ].join("\n");
27
+ /** The join on documented decisions (decision 64), as a skill or the OpenCode orchestrator applies it. */
28
+ export const DECISION_JOIN = "Join the open items on the documented decisions by topic: an item whose topic a decision lists is settled by it; drop it, with the reason \"topic <topic> is settled by documented decision <id> (<source>)\", unless it names that decision in contradicts. Such an item stays, and the gap analysis reports the contradiction with the decision as one side. Items with no matching topic are asked as before.";
29
+ /** DSL first, code after (decision 65): the one re-run a step whose contracts fail their checks gets. */
30
+ export const CONTRACT_RETRY = "Your interface contracts are not yet a DSL delivery can code from. Return them complete, fixing each problem below; change nothing else:";
31
+ export const CONTRACT_GAP_WHY = "Delivery codes the interfaces from this DSL and nothing else (decision 65): an incomplete contract would be guessed.";
1
32
  export const CLARIFY = (topic) => [
2
33
  `Clarify: ${topic}`,
3
34
  "",
@@ -14,6 +45,8 @@ export const CLARIFY = (topic) => [
14
45
  "decides it, that is not an assumption: put it in `result` and cite the convention. Do not ask",
15
46
  "about edge cases beyond the acceptance criteria, wording, or nice-to-haves.",
16
47
  "",
48
+ COMPLETE_OPTIONS,
49
+ "",
17
50
  "Give every item a `topic` (short kebab-case subject; reuse the topic another step or an answer",
18
51
  "already uses for the same subject), `blocking`, `changesBehaviour`, and, if it conflicts with a",
19
52
  "recorded answer, `contradicts` with that answer's id.",
@@ -42,6 +75,20 @@ export const GAP_ANALYSIS = [
42
75
  "Mark a gap blocking only when a downstream agent could not safely write or test a task without",
43
76
  "closing it. Defer other useful details. What a loaded convention or an earlier answer already",
44
77
  "decides is not a gap.",
78
+ "",
79
+ "Always blocking gaps (decision 56); each one stopped a delivery run that had passed discovery:",
80
+ "- A new setting or flag without its default, its allowed values or range, and the value that keeps",
81
+ " today's behaviour.",
82
+ "- An optional field or a group of optional fields without saying whether they are present all",
83
+ " together or each on its own, and, when each on its own, how partial sets combine in every place",
84
+ " that merges, compares or orders them.",
85
+ "- A numeric target (latency, throughput, error rate, quality score) that names only its statistic.",
86
+ " It needs the exact formula (for a percentile, the method), the timestamp that places a sample in",
87
+ " a window, where the windows come from, what an empty window counts as, how retries and cold starts",
88
+ " count, and every alert threshold.",
89
+ "- A task that depends on something in scope.outOfScope or deferred: bring it into scope, change the",
90
+ " task, or defer the task with it.",
91
+ COMPLETE_OPTIONS,
45
92
  ].join("\n");
46
93
  export const CONSOLIDATE = [
47
94
  "You are this round's single list of open items: the user sees only what you return.",
@@ -57,6 +104,8 @@ export const CONSOLIDATE = [
57
104
  " plus the least each side must add to meet the acceptance criteria; then each side as it",
58
105
  " stands. Recommend the sweet spot unless the overlap is empty or cannot meet an acceptance",
59
106
  " criterion (say which in why). Do not pick one yourself: the user does.",
107
+ " A documented decision, when the context lists any, is a source like an answer (decision 64):",
108
+ " its id goes in between, and the first option keeps it unless the request explicitly changes it.",
60
109
  " State in premise the assumption every option rests on (decision 54), and end the options",
61
110
  " with \"None of these: the premise is wrong\", which asks the user for their design.",
62
111
  "4. Add the gaps you find yourself. A scope (result.scopes) whose expected outcome the user has",
@@ -76,11 +125,13 @@ export const HANDOFF = (workflow) => [
76
125
  " its check passed where the delivery agents run, not just \"published\"), every question with",
77
126
  " its answer (the answers above), and every gap with its resolution (the resolved gaps above,",
78
127
  " including why, impact, solutions and the recommended index).",
79
- " Include the architect's `contracts` and `standards`, the technical lead's `interfaceContracts`,",
128
+ " Include the architect's `contracts` and `standards`, the technical lead's `interfaceContracts` and `shapes` (the DSL, decision 65, as returned),",
80
129
  " QA's `testPlan`, and the senior developer's `plan` and `expectedRed` from earlier steps.",
81
130
  " Add `deliveryPolicy.maySettle`: the kinds of decision delivery may take itself (test-fixture",
82
131
  " fixes, pruning stale lint suppressions, named exceptions for existing repo facts, command",
83
- " mapping), from the user's answers; leave it empty if the user did not allow any.",
132
+ " mapping, answer-detail: the exact formula, merge rule or edge case an answer already given",
133
+ " implies, other: anything else the user allowed, limited in `notes`), from the user's answers;",
134
+ " leave it empty if the user did not allow any.",
84
135
  " Add `commands`: the repository's command map per test pyramid level (static, unit,",
85
136
  " integration, e2e), detected from its packageManager field or lockfile, its package.json",
86
137
  " scripts and its AGENTS.md / CLAUDE.md, e.g. `npm run typecheck` and `npm run test:architecture`.",
@@ -141,6 +192,14 @@ export function scopeText(pyramid, scope, loop) {
141
192
  }
142
193
  export const TDD_TEST = "Write the failing tests for this task first: one test per acceptance criterion and permission rule, at the lowest pyramid level that can prove it (unit with in-memory adapters where possible). Do not repeat a criterion at every level: a higher level only for what a lower one cannot prove. Report each test's level in levels. Do not decide behaviour the handoff leaves open (error types, helper signatures, option names, retry semantics): return each as a question in `questions`, with options and your recommendation, never as a note in the summary; a non-empty list stops the run and goes back upstream. Run them and report the output that proves they fail for the right reason. Do not implement. If a criterion can only be proven above the loop's scope (the task's lowestLevel), write that test but do not run it; integration will. If the acceptance is already met (for example a resumed run) and existing tests prove every criterion and pass, do not write new tests and do not return blocked: return status done with alreadyMet: true, those tests in testFiles and their passing output as proof in failureOutput.";
143
194
  export const TDD_IMPL = "Make the failing tests for this task pass by changing the code, never the tests: do not edit, weaken, skip or delete a test, and do not change an assertion to match what the code does. Run them before reporting, within the test scope only. Only if a new test contradicts an existing test or a repository fact (so no correct code can pass both) report it in testConflict, naming the test, what it contradicts and why; do not change either and do not return blocked. It goes back to test-design, which decides.";
195
+ /** A document task (decision 62): no failing tests come first; the writer writes the document. */
196
+ export const TDD_DOCUMENT = "This task only writes documents (an ADR, a guide, a README): there are no failing tests for it, and you write none. Write or update exactly the documents the task and its acceptance criteria name, from what the handoff and the repository decide; change no code and no test. Follow the repository's conventions for where the document lives and how it is laid out. Run the static checks in scope (lint, format, links) before reporting. Anything the handoff does not settle is a blocker: return it, do not guess.";
197
+ /** Verify for a document task (decision 62): the static level and the acceptance criteria. */
198
+ export const TDD_VERIFY_DOCUMENT = [
199
+ "This task only writes documents, so there are no tests of its own. Run the static checks in scope and report each command in evidence, verbatim, with its exit code.",
200
+ "Then check every acceptance criterion against the document as written; an unmet criterion is a failure in failures, naming the criterion and what is missing. Do not edit anything.",
201
+ "A test written by another task may be red on purpose: report it in foreignFailures with its owner, not in failures.",
202
+ ].join(" ");
144
203
  export const TDD_TEST_CONFLICT = [
145
204
  "The implementer says one of your tests contradicts an existing test or a repository fact. Decide first; a test is not changed to let the code pass.",
146
205
  "Check the claim against the acceptance criterion and the repository. If the test follows the criterion and the conflict is not real (the code can pass it), keep the test unchanged: return testChange { kept: true, criterion, justification } with why it stands, and the failure output as it is.",
@@ -194,6 +253,9 @@ export const PREFLIGHT = [
194
253
  "2. Prerequisites: run or verify the `check` of every prerequisite in the handoff, here.",
195
254
  "3. Version pins: every package version the handoff's tasks or prerequisites name must be in the",
196
255
  " lockfile and installed, or installable from this environment (a bump task will install it).",
256
+ "4. Working trees: for every working tree the run uses, report its path, its current branch and its",
257
+ " uncommitted changes (git status --porcelain) in worktrees, with the expected branch when the run",
258
+ " names one below. Do not switch branches, stash or commit.",
197
259
  "Report each prerequisite and pin with resolved true or false and the evidence. If any cannot be",
198
260
  "resolved here, return status blocked with the reason and one question per item (for example: who",
199
261
  "with registry access refreshes the lockfile and the store). Never change a pin to make it resolve.",
@@ -224,7 +286,21 @@ export const RETRO = [
224
286
  export const DECIDE_BLOCKER = [
225
287
  "A delivery agent is blocked on the question below. You decide for delivery, under the handoff's",
226
288
  "standing policy (deliveryPolicy) and its decisions; you never ask the user. Settle it (settled:",
227
- "true, with the decision and why) only when the policy allows that kind of decision and the",
228
- "handoff and repository facts support one answer. Product behaviour, user-facing copy and anything",
229
- "that widens security or data access are never yours: return settled: false with that kind.",
289
+ "true, with the decision and why) only when deliveryPolicy.maySettle lists that kind of decision",
290
+ "and the handoff and repository facts support one answer; a kind it does not list is not applied.",
291
+ "A technical detail an answer already given implies (the exact formula, merge rule or edge case of",
292
+ "the chosen option) is kind answer-detail. Product behaviour, user-facing copy and anything that",
293
+ "widens security or data access are never yours: return settled: false with that kind.",
294
+ ].join("\n");
295
+ /**
296
+ * Told to every downstream step (decision 57): the order that settles a conflict between the
297
+ * handoff's own artefacts, so no step invents one mid-run.
298
+ */
299
+ export const PRECEDENCE = [
300
+ "When the handoff's own artefacts disagree, the more specific one wins, in this order: an answer",
301
+ "(recorded in the handoff or given mid-run) over everything it amends; then a task's acceptance",
302
+ "criteria; then the interface contracts; then the decisions; then the architect's contracts and",
303
+ "standards. Report every conflict you settled this way in your summary (the artefacts and which",
304
+ "one won); never settle one silently. A conflict this order does not settle, or one that changes",
305
+ "product behaviour, user-facing copy or security, is a blocker.",
230
306
  ].join("\n");
package/dist/reads.js CHANGED
@@ -34,7 +34,7 @@ export function readIssue(w, places, step, entry) {
34
34
  if (!there)
35
35
  return `reads "${entry}", which is not a step of ${w.id}`;
36
36
  if (entry === step.id)
37
- return `reads itself; its own results for the current item are always visible`;
37
+ return `reads "${entry}", itself; its own results for the current item are always visible`;
38
38
  if (here.ancestors.includes(entry))
39
39
  return `reads "${entry}", a step that holds it; its results are not finished yet`;
40
40
  if (there.order > here.order)
package/dist/slice.js ADDED
@@ -0,0 +1,90 @@
1
+ // What a task's agents get of the handoff (decision 60): one function for every place that needs it.
2
+ // The Claude runtime embeds its source in each generated workflow script (handoffSlice.toString()),
3
+ // and `friday handoff check` calls it to estimate a run's prompt tokens (decision 61), so the slice
4
+ // a run sends and the slice the estimate counts cannot drift. It must stay self-contained: no
5
+ // imports, no closures over module state, and plain JavaScript once the types are stripped.
6
+ /**
7
+ * A task's agents get its task and the tasks it depends on, the decisions whose `where` names its
8
+ * codebase (or no place), the criteria it covers, the contracts that list it (or no task), the
9
+ * interface contracts its brief names (all when it names none), the standards, its build-plan
10
+ * entry, the red tests it owns, the data classification, the commands and the delivery policy;
11
+ * with its interface contracts, the ones they realize and the data shapes they name (decision 65).
12
+ */
13
+ export function handoffSlice(handoff, item, commands) {
14
+ // "AC1" covers "AC1: ..." but not "AC12: ..." (coversCriterion in src/handoff.ts).
15
+ function covers(entry, criterion) {
16
+ const e = String(entry).trim();
17
+ const c = String(criterion).trim();
18
+ if (!e)
19
+ return false;
20
+ return c === e || (c.indexOf(e) === 0 && !/[A-Za-z0-9]/.test(c.charAt(e.length)));
21
+ }
22
+ const deps = item.dependsOn || [];
23
+ const tasks = (handoff.tasks || []).filter(function (t) { return t.id === item.id || deps.indexOf(t.id) >= 0; });
24
+ const decisions = (handoff.decisions || []).filter(function (d) {
25
+ return !d.where || String(d.where).indexOf(item.codebase) >= 0 || String(item.codebase).indexOf(d.where) >= 0;
26
+ });
27
+ const own = item.covers || [];
28
+ const acceptance = ((handoff.scope || {}).acceptance || []).filter(function (ac) { return own.some(function (e) { return covers(e, ac); }); });
29
+ const brief = (handoff.briefs || []).find(function (b) { return b.task === item.id; }) || {};
30
+ const named = brief.interfaces || [];
31
+ const slice = {
32
+ workId: handoff.workId,
33
+ scope: { summary: (handoff.scope || {}).summary, acceptance: acceptance },
34
+ tasks: tasks,
35
+ decisions: decisions,
36
+ dataClassification: handoff.dataClassification || [],
37
+ commands: commands,
38
+ deliveryPolicy: handoff.deliveryPolicy || null,
39
+ };
40
+ const parts = {
41
+ contracts: (handoff.contracts || []).filter(function (c) { return !(c.tasks || []).length || c.tasks.indexOf(item.id) >= 0; }),
42
+ standards: handoff.standards || [],
43
+ interfaceContracts: (handoff.interfaceContracts || []).filter(function (c) { return !named.length || named.indexOf(c.id) >= 0; }),
44
+ plan: (handoff.plan || []).filter(function (p) { return p.task === item.id; }),
45
+ expectedRed: (handoff.expectedRed || []).filter(function (r) { return r.owner === item.id; }),
46
+ };
47
+ // DSL first, code after (decision 65): the inner contracts its contracts realize, and every data
48
+ // shape they name, followed through fields, items and refs.
49
+ const all = handoff.interfaceContracts || [];
50
+ const kept = parts.interfaceContracts;
51
+ for (let i = 0; i < kept.length; i++) {
52
+ (kept[i].realizes || []).forEach(function (r) {
53
+ const inner = all.find(function (c) { return c.id === r; });
54
+ if (inner && kept.indexOf(inner) < 0)
55
+ kept.push(inner);
56
+ });
57
+ }
58
+ const shapes = handoff.shapes || {};
59
+ const want = {};
60
+ function shape(s) {
61
+ if (!s)
62
+ return;
63
+ if (s.type === "ref")
64
+ name(s.ref);
65
+ if (s.items)
66
+ shape(s.items);
67
+ Object.keys(s.fields || {}).forEach(function (f) { shape(s.fields[f]); });
68
+ }
69
+ function name(n) {
70
+ if (typeof n !== "string" || !Object.prototype.hasOwnProperty.call(shapes, n) || want[n])
71
+ return;
72
+ want[n] = shapes[n];
73
+ shape(shapes[n]);
74
+ }
75
+ kept.forEach(function (c) {
76
+ (c.operations || []).forEach(function (op) { name(op.input); name(op.output); });
77
+ name(c.payload);
78
+ name(c.shape);
79
+ });
80
+ Object.keys(parts).forEach(function (k) { if (parts[k].length)
81
+ slice[k] = parts[k]; });
82
+ if (Object.keys(want).length)
83
+ slice.shapes = want;
84
+ return slice;
85
+ }
86
+ /** Tokens of a prompt, estimated at 4 characters a token (decision 61); the runtime uses the same rule. */
87
+ export function estimateTokens(text) {
88
+ const n = text.length + 3;
89
+ return (n - (n % 4)) / 4;
90
+ }
@@ -224,6 +224,16 @@ export function applySpecializations(raw, dirs) {
224
224
  if (existsSync(join(dir, folder)))
225
225
  raw.parseErrors.push({ file: `${label}:${folder}/`, message: "a specialization cannot change orchestrations" });
226
226
  }
227
+ // Documented decisions (decision 64): validated with the rest, merged by id in order (the last wins).
228
+ if (existsSync(join(dir, "decisions.yaml"))) {
229
+ const f = `${label}:decisions.yaml`;
230
+ try {
231
+ raw.docs.push({ kind: "decisions", file: f, data: parse(readFileSync(join(dir, "decisions.yaml"), "utf8")) });
232
+ }
233
+ catch (err) {
234
+ raw.parseErrors.push({ file: f, message: err.message });
235
+ }
236
+ }
227
237
  if (existsSync(join(dir, "model-policy.yaml")))
228
238
  raw.parseErrors.push({ file: `${label}:model-policy.yaml`, message: "a specialization cannot change the model policy" });
229
239
  // A specialization shipped as a package carries the package's version.
@@ -122,7 +122,10 @@ export const TASK = {
122
122
  stack: str,
123
123
  codebase: str,
124
124
  scope: { type: "string", description: "Id of the scope this task delivers, one of the scopes the scope step inferred." },
125
- taskKind: { enum: ["implement", "scaffold", "adapter"] },
125
+ taskKind: {
126
+ enum: ["implement", "scaffold", "adapter", "document"],
127
+ description: "document: the task only writes documents (an ADR, a guide, a README); it gets no tests, and verify checks it at the static level against its acceptance (decision 62).",
128
+ },
126
129
  acceptance: { type: "array", minItems: 1, items: str },
127
130
  dependsOn: strs,
128
131
  conventions: strs,
@@ -194,7 +197,17 @@ const blocked = {
194
197
  type: "object",
195
198
  description: "Set with status blocked: what is missing. It goes back upstream; never guess.",
196
199
  required: ["reason"],
197
- properties: { reason: str, questions: strs },
200
+ properties: {
201
+ reason: str,
202
+ questions: {
203
+ ...strs,
204
+ description: "Every open question you found, not only the first: finish the whole sweep before you return. Write each option as the complete rule the code would follow (the exact formula, merge, default or threshold), checked against every contract that touches it, so choosing it leaves no follow-up question.",
205
+ },
206
+ tasks: {
207
+ ...strs,
208
+ description: "Ids of the handoff tasks the blocker affects. Only they and the tasks that depend on them wait; the others go on. Leave it out when every task is affected.",
209
+ },
210
+ },
198
211
  };
199
212
  export const RESULT = {
200
213
  type: "object",
@@ -331,7 +344,10 @@ export const DECISION = {
331
344
  required: ["settled", "kind", "summary"],
332
345
  properties: {
333
346
  settled: { type: "boolean", description: "true when the standing policy lets delivery settle it; the step re-runs with the decision." },
334
- kind: { enum: ["product", "copy", "security-widening", "test-fixture", "lint-suppression", "repo-fact-exception", "command-mapping", "other"] },
347
+ kind: {
348
+ enum: ["product", "copy", "security-widening", "test-fixture", "lint-suppression", "repo-fact-exception", "command-mapping", "answer-detail", "other"],
349
+ description: "answer-detail: the technical detail an answer already given implies (the exact formula, merge rule or edge case of the option the user chose), when the handoff and the repository support one reading. A kind the handoff's deliveryPolicy.maySettle does not list is never applied.",
350
+ },
335
351
  decision: { type: "string", description: "What delivery does, when settled." },
336
352
  why: str,
337
353
  summary: str,
@@ -388,6 +404,15 @@ export const PREFLIGHT = {
388
404
  },
389
405
  prerequisites: { ...resolvedItems({ id: str }, ["id"]), description: "One per handoff prerequisite; evidence is the check you ran and what it printed." },
390
406
  pins: { ...resolvedItems({ package: str, version: str, task: str }, ["package", "version"]), description: "One per package version the handoff's tasks or prerequisites name." },
407
+ worktrees: {
408
+ type: "array",
409
+ description: "One per working tree the run uses: its path, the branch it is on, the branch it should be on (when the run names one) and its uncommitted changes (git status --porcelain), verbatim.",
410
+ items: {
411
+ type: "object",
412
+ required: ["path", "branch", "changes"],
413
+ properties: { path: str, branch: str, expected: str, changes: strs },
414
+ },
415
+ },
391
416
  blocked,
392
417
  },
393
418
  };
package/dist/validate.js CHANGED
@@ -6,7 +6,7 @@ import { SCHEMAS_DIR } from "./paths.js";
6
6
  import { loadRawPack } from "./load.js";
7
7
  import { applySpecializations } from "./specialize.js";
8
8
  import { SKILL_STEP_TYPES, emits } from "./types.js";
9
- import { CONTAINER_TYPES, readIssue, stepPlaces } from "./reads.js";
9
+ import { flowMessage, orchestrationCheck } from "./flow.js";
10
10
  const SCHEMA_FILES = {
11
11
  pack: "pack.schema.yaml",
12
12
  "model-policy": "model-policy.schema.yaml",
@@ -14,6 +14,7 @@ const SCHEMA_FILES = {
14
14
  convention: "convention.schema.yaml",
15
15
  orchestration: "orchestration.schema.yaml",
16
16
  handoff: "handoff.schema.yaml",
17
+ decisions: "decisions.schema.yaml",
17
18
  };
18
19
  let validators;
19
20
  export function schemaValidator(kind) {
@@ -57,7 +58,7 @@ export function walkSteps(steps, visit, foreachOver = []) {
57
58
  walkSteps(step.followup, visit, [...foreachOver, `${step.id}.followups.tasks`]);
58
59
  }
59
60
  }
60
- function crossRefIssues(lp, files) {
61
+ function crossRefIssues(lp, files, budgets = []) {
61
62
  const issues = [];
62
63
  const err = (file, message) => issues.push({ level: "error", file, message });
63
64
  const warn = (file, message) => issues.push({ level: "warning", file, message });
@@ -352,22 +353,13 @@ function crossRefIssues(lp, files) {
352
353
  }
353
354
  }
354
355
  });
355
- // What each step's agents read from earlier steps (decision 55).
356
- const places = stepPlaces(w);
357
- for (const [id, p] of places) {
358
- const r = p.step.reads;
359
- if (!r)
360
- continue;
361
- if (CONTAINER_TYPES.has(p.step.type) || p.step.type === "approval") {
362
- err(f, `step ${id}: reads applies to agent steps; ${p.step.type === "approval" ? "no agent runs an approval" : `set it on the steps ${p.step.type} holds`}`);
363
- continue;
364
- }
365
- for (const e of r) {
366
- const why = readIssue(w, places, p.step, e);
367
- if (why)
368
- err(f, `step ${id}: ${why}`);
369
- }
370
- }
356
+ // The orchestration check (decision 58): reads name earlier steps (decision 55), every loop
357
+ // has a limit, the worst-case agent calls, and parking has a top-level task loop (decision 56).
358
+ const check = orchestrationCheck(w, pack);
359
+ for (const i of check.issues)
360
+ (i.level === "error" ? err : warn)(f, flowMessage(i));
361
+ if (check.budget)
362
+ budgets.push(check.budget);
371
363
  approvalIssues(w, pack, upstreamApprovals, err.bind(null, f));
372
364
  if (w.retro)
373
365
  checkRef(f, "retro", w.retro, []);
@@ -547,6 +539,10 @@ function sourceIssues(lp, files) {
547
539
  if (l.source && bad(l.source))
548
540
  issues.push({ level: "error", file: files.get(lp.pack) ?? "pack.yaml", message: `testPyramid level ${l.id}: ${msg(l.source)}` });
549
541
  }
542
+ for (const d of lp.decisions ?? []) {
543
+ if (bad(d.source))
544
+ issues.push({ level: "error", file: files.get(d) ?? "decisions.yaml", message: `decision ${d.id}: ${msg(d.source)}` });
545
+ }
550
546
  return issues;
551
547
  }
552
548
  /**
@@ -570,6 +566,26 @@ export function validatePack(packArg, specs = []) {
570
566
  files.set(d.data, d.file);
571
567
  return d.data;
572
568
  });
569
+ // Documented decisions (decision 64): the pack's, then each specialization's, merged by id; one
570
+ // topic names one decision, or the join that settles open items by topic would be ambiguous.
571
+ const merged = new Map();
572
+ for (const d of raw.docs.filter((x) => x.kind === "decisions")) {
573
+ for (const e of d.data.decisions) {
574
+ files.set(e, d.file);
575
+ merged.set(e.id, e);
576
+ }
577
+ }
578
+ const decisions = [...merged.values()];
579
+ const owner = new Map();
580
+ for (const d of decisions) {
581
+ for (const t of d.topics) {
582
+ const other = owner.get(t);
583
+ if (other)
584
+ issues.push({ level: "error", file: files.get(d) ?? "decisions.yaml", message: `decision ${d.id}: topic "${t}" is already ${other}'s; one topic names one documented decision` });
585
+ else
586
+ owner.set(t, d.id);
587
+ }
588
+ }
573
589
  const lp = {
574
590
  dir: raw.dir,
575
591
  pack: of("pack")[0],
@@ -578,10 +594,12 @@ export function validatePack(packArg, specs = []) {
578
594
  conventions: of("convention"),
579
595
  orchestrations: of("orchestration"),
580
596
  specializations: applied,
597
+ ...(decisions.length ? { decisions } : {}),
581
598
  };
582
- issues.push(...crossRefIssues(lp, files), ...sourceIssues(lp, files));
599
+ const budgets = [];
600
+ issues.push(...crossRefIssues(lp, files, budgets), ...sourceIssues(lp, files));
583
601
  const ok = !issues.some((i) => i.level === "error");
584
- return ok ? { ok, issues, pack: lp } : { ok, issues };
602
+ return ok ? { ok, issues, pack: lp, budgets } : { ok, issues, budgets };
585
603
  }
586
604
  export function loadPack(packArg, specs = []) {
587
605
  const r = validatePack(packArg, specs);
@@ -9,6 +9,11 @@ taskKinds:
9
9
  effort: medium
10
10
  why: Make an existing failing test pass, or apply a fully specified change.
11
11
  contract: Change only what the failing test or the spec needs. No new design decisions; if one is needed, return blocked with the question.
12
+ document:
13
+ model: haiku
14
+ effort: medium
15
+ why: Write or update a document the handoff fully specifies (an ADR, a guide, a README); it has no tests (decision 62).
16
+ contract: Write only the documents the task names, from what the handoff and the repository decide. No code, no tests. Anything the handoff does not settle is a blocker.
12
17
  verify:
13
18
  model: haiku
14
19
  effort: low
@@ -9,6 +9,11 @@ inputs:
9
9
  glossary: { description: "Optional. Domain words and what they mean here (term -> meaning), shown to every step." }
10
10
  environmentFacts: { description: "Optional. Facts the orchestrator verified (registry access, emulators, tools), shown to every step." }
11
11
  answersFile: { description: "Optional. Path to answers.yaml; agents read the answers there and only answeredIds/resolvedIds travel inline." }
12
+ # Question rounds before the user freezes the scope or allows more (decision 58: every loop is bounded).
13
+ maxRounds: 5
14
+ # From round 3 the driver offers the close-out rule once: only items that change behaviour or
15
+ # contradict an answer still go to the user, the rest take the recommended option (decision 59).
16
+ closeOutFromRound: 3
12
17
  # Every finished run ends in a retro: docs/friday/<workId>/retro.md and proposed Friday improvements.
13
18
  retro: { persona: architect, taskKind: decide }
14
19
  steps:
@@ -21,7 +21,7 @@ steps:
21
21
  - id: tdd
22
22
  type: tdd-pair
23
23
  test: { persona: qa-engineer, taskKind: test-design }
24
- impl: { persona: "{{stack}}", taskKind: "{{task.taskKind}}", allowedTaskKinds: [implement, scaffold, adapter] }
24
+ impl: { persona: "{{stack}}", taskKind: "{{task.taskKind}}", allowedTaskKinds: [implement, scaffold, adapter, document] }
25
25
  verify: { persona: qa-engineer, taskKind: verify }
26
26
  # The task loop stays at the bottom of the pyramid; integration runs the rest.
27
27
  testScope: [static, unit]
@@ -27,6 +27,9 @@ sizing:
27
27
  large: 10
28
28
  maxAgentsPerWorkflow: 6
29
29
  maxRounds: 5
30
+ # From round 3 the driver offers the close-out rule once: only items that change behaviour or
31
+ # contradict an answer still go to the user, the rest take the recommended option (decision 59).
32
+ closeOutFromRound: 3
30
33
  deferNonBlocking: true
31
34
  # A real run returned 30-60 items a round, the same subject asked by 3-5 perspectives. Items are
32
35
  # merged by topic and at most this many blocking items are shown per round.
@@ -129,8 +132,11 @@ steps:
129
132
  versioning) in result.standards. A trade-off the user has not accepted is a question with
130
133
  options, never a silent choice. Ask only a question that blocks a safe, testable plan; mark
131
134
  non-blocking details blocking: false.
135
+ # DSL first, code after (decision 65): the contracts are data a person approves and delivery
136
+ # codes from; their checks run before the round goes on.
132
137
  - id: interface-contracts
133
138
  type: agent
139
+ output: interfaces
134
140
  persona: lead-developer
135
141
  taskKind: decide
136
142
  prompt: >-
@@ -138,9 +144,16 @@ steps:
138
144
  by the recommended approach: names, responsibilities, inputs/outputs, provider/consumer
139
145
  relationships, and compatibility constraints. Specify contracts, not concrete adapter or
140
146
  feature implementations, following the architect's result.contracts and result.standards. Put
141
- them in result.interfaceContracts, each with its owner context and the work ids or contexts
142
- that consume it; an interface another work item already owns is referenced, not redefined.
143
- Use repository conventions and architecture decisions; ask only about an unresolved blocker.
147
+ them in result.interfaceContracts, each with its owner codebase and the work ids or contexts
148
+ that consume it, and say for each whether the work adds it (change: new), changes it
149
+ (changed) or only uses one another work item owns (existing: referenced, not redefined).
150
+ Write every new or changed contract in the DSL, first: its kind (port, callable, event,
151
+ type, http, async); for a port or callable its operations, each with its input and output
152
+ shapes and every error it returns; for an event its payload; for a type its shape; for an
153
+ http or async contract the OpenAPI or AsyncAPI document in the repository (spec.file) that
154
+ is the contract. Declare every data shape in result.shapes (fields, required, items, enum
155
+ values), language-neutral: no language's types. Use repository conventions and architecture
156
+ decisions; ask only about an unresolved blocker.
144
157
  - id: test-plan
145
158
  type: agent
146
159
  persona: qa-engineer
@@ -36,7 +36,11 @@ steps:
36
36
  interface already exists, name it and keep its shape. Put them in result.contracts (one
37
37
  entry per interface, with the task ids that use it) and result.standards (the cross-cutting
38
38
  rules: naming, error, audit, logging and versioning). Write no code. Anything the handoff does
39
- not settle is a blocker: return blocked with the question.
39
+ not settle is a blocker, but one blocker does not end the step: go through every task first,
40
+ then return blocked once, with every question in blocked.questions and the ids of the tasks
41
+ they affect in blocked.tasks, so the other tasks go on (decision 56). Write each option as the
42
+ complete rule the code would follow (the exact formula, merge, default or threshold) and trace
43
+ it through every contract that touches it, so choosing it leaves no follow-up question.
40
44
  - id: interfaces
41
45
  type: agent
42
46
  reads: [contracts]
@@ -45,7 +49,11 @@ steps:
45
49
  prompt: >-
46
50
  Code the interfaces the contracts step defined, and only those: contracts, schemas, event
47
51
  types, port interfaces and shared types, in the repository's contract and core packages, with
48
- no behaviour. They must compile, and every contract gets a contract or schema test. Run the
52
+ no behaviour. DSL first, code after (decision 65): code every new or changed interface
53
+ contract from the approved DSL (the handoff's interfaceContracts and shapes, or the OpenAPI or
54
+ AsyncAPI document its spec names) exactly, in the codebase's own language: as types where it
55
+ has them, as the validators it uses where it has none. Add no field, operation or error the
56
+ DSL does not have; a contract it cannot express is a blocker. They must compile, and every contract gets a contract or schema test, against the JSON Schema `friday contracts schema` writes from the shapes. Run the
49
57
  static checks and the unit tests of the packages you touched. They must be green: an
50
58
  interface that would make another test red is a blocker. Commit them as one commit. From now
51
59
  on they are frozen. List every file and exported name in result.interfaces, with the task ids
@@ -76,7 +84,7 @@ steps:
76
84
  type: tdd-pair
77
85
  reads: [contracts, interfaces, orchestration]
78
86
  test: { persona: qa-engineer, taskKind: test-design }
79
- impl: { persona: "{{stack}}", taskKind: "{{task.taskKind}}", allowedTaskKinds: [implement, scaffold, adapter] }
87
+ impl: { persona: "{{stack}}", taskKind: "{{task.taskKind}}", allowedTaskKinds: [implement, scaffold, adapter, document] }
80
88
  verify: { persona: qa-engineer, taskKind: verify }
81
89
  # The task loop stays at the bottom of the pyramid; integration runs the rest.
82
90
  testScope: [static, unit]
@@ -31,16 +31,24 @@ steps:
31
31
  its owner context and consumers, and the trade-offs it accepts. The approved prompt pyramid
32
32
  levels (handoff promptPyramid.levels and their files) are fixed: the prompt, examples and
33
33
  eval cases are used exactly as approved. Put them in result.contracts and result.standards.
34
- Write no code. Anything the handoff does not settle is a blocker: return blocked with the
35
- question.
34
+ Write no code. Anything the handoff does not settle is a blocker, but one blocker does not end
35
+ the step: go through every task first, then return blocked once, with every question in
36
+ blocked.questions and the ids of the tasks they affect in blocked.tasks, so the other tasks go
37
+ on (decision 56). Write each option as the complete rule the code would follow (the exact
38
+ formula, merge, default or threshold) and trace it through every contract that touches it, so
39
+ choosing it leaves no follow-up question.
36
40
  - id: interfaces
37
41
  type: agent
38
42
  reads: [contracts]
39
43
  persona: lead-developer
40
44
  taskKind: integrate
41
45
  prompt: >-
42
- Code the interfaces the contracts step defined, and only those, with no behaviour. They must
43
- compile, and every contract gets a contract or schema test. Run the static checks and the unit
46
+ Code the interfaces the contracts step defined, and only those, with no behaviour. DSL
47
+ first, code after (decision 65): code every new or changed interface contract from the
48
+ approved DSL (the handoff's interfaceContracts and shapes, or the OpenAPI or AsyncAPI document
49
+ its spec names) exactly, in the codebase's own language: as types where it has them, as the
50
+ validators it uses where it has none. Add no field, operation or error the DSL does not have;
51
+ a contract it cannot express is a blocker. They must compile, and every contract gets a contract or schema test, against the JSON Schema `friday contracts schema` writes from the shapes. Run the static checks and the unit
44
52
  tests of the packages you touched; they must be green. Commit them as one commit; from now on
45
53
  they are frozen. List every file and exported name in result.interfaces, with the task ids
46
54
  that consume each.
@@ -67,7 +75,7 @@ steps:
67
75
  type: tdd-pair
68
76
  reads: [contracts, interfaces, orchestration]
69
77
  test: { persona: qa-engineer, taskKind: test-design }
70
- impl: { persona: "{{stack}}", taskKind: "{{task.taskKind}}", allowedTaskKinds: [implement, scaffold, adapter] }
78
+ impl: { persona: "{{stack}}", taskKind: "{{task.taskKind}}", allowedTaskKinds: [implement, scaffold, adapter, document] }
71
79
  verify: { persona: qa-engineer, taskKind: verify }
72
80
  testScope: [static, unit]
73
81
  maxRounds: 3
@@ -20,6 +20,9 @@ sizing:
20
20
  large: 10
21
21
  maxAgentsPerWorkflow: 6
22
22
  maxRounds: 5
23
+ # From round 3 the driver offers the close-out rule once: only items that change behaviour or
24
+ # contradict an answer still go to the user, the rest take the recommended option (decision 59).
25
+ closeOutFromRound: 3
23
26
  deferNonBlocking: true
24
27
  maxItemsPerRound: 15
25
28
  inputs:
package/pack/pack.yaml CHANGED
@@ -102,16 +102,26 @@ checkpoints:
102
102
  description: The request brief, the structured prompt discovery starts from (goal, who, today, wanted, constraints, acceptance, out of scope, facts checked, unknowns)
103
103
  approver: requester
104
104
  source: decision 39 (friday docs/decisions.md)
105
+ # The orchestration check (decision 58) computes every orchestration's worst-case agent calls from
106
+ # its loop limits and warns above warnAbove for a handoff of this size. Today's largest delivery
107
+ # (prompt-delivery) is 472 at this size.
108
+ agentCallBudget:
109
+ warnAbove: 500
110
+ # friday handoff check estimates the run's prompt tokens spent on the handoff from the real
111
+ # handoff and warns above this (decision 61). A 22-task handoff of about 120,000 tokens comes to
112
+ # about 13 million in the worst case even with task slices; at 5 million it warns.
113
+ warnPromptTokensAbove: 5000000
114
+ assume: { task: 10, stack: 3, followup: 3, item: 10 }
105
115
  # Rules the agents cannot break: checked before each tool call, not only stated in the prompt.
106
116
  # Skills and prompts advise; these hooks enforce (The AI-native SDLC playbook, Build and Test).
107
117
  guardrails:
108
118
  # Every agent kind that runs inside a TDD pair. integrate is left out: it runs the integration
109
119
  # loop, the one place the whole pyramid runs.
110
120
  loopCommands:
111
- taskKinds: [test-design, implement, scaffold, adapter, verify]
121
+ taskKinds: [test-design, implement, scaffold, adapter, verify, document]
112
122
  # QA writes the failing test; the implementer makes it pass without touching it.
113
123
  protectedTests:
114
- taskKinds: [implement]
124
+ taskKinds: [implement, document]
115
125
  patterns:
116
126
  - '(^|/)(test|tests|__tests__|e2e)/'
117
127
  - '\.(test|spec)\.[cm]?[jt]sx?$'
@@ -2,7 +2,7 @@ id: backend-engineer
2
2
  name: Backend Engineer
3
3
  role: Implements the core, adapters, functions and services.
4
4
  description: Implements tasks in the core, its adapters, functions and services in TDD with the QA engineer.
5
- taskKinds: [implement, scaffold, adapter, integrate]
5
+ taskKinds: [implement, scaffold, adapter, integrate, document]
6
6
  tools: [Read, Edit, Write, Grep, Glob, Bash]
7
7
  conventions: [hexagonal, typescript-node, testing, security-code, config-secrets]
8
8
  pairsWith: qa-engineer