ex-workflow 0.6.0-stage → 1.0.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 (70) hide show
  1. package/CHANGELOG.md +17 -2
  2. package/README.md +12 -6
  3. package/dist/chunk-3KFQPSRX.mjs +2 -0
  4. package/dist/chunk-3KFQPSRX.mjs.map +1 -0
  5. package/dist/{chunk-MH66G5KV.cjs → chunk-5PHK72VM.cjs} +2 -2
  6. package/dist/{chunk-MH66G5KV.cjs.map → chunk-5PHK72VM.cjs.map} +1 -1
  7. package/dist/chunk-CYXVGHQM.cjs +2 -0
  8. package/dist/chunk-CYXVGHQM.cjs.map +1 -0
  9. package/dist/chunk-FKTCGQYB.cjs +2 -0
  10. package/dist/chunk-FKTCGQYB.cjs.map +1 -0
  11. package/dist/chunk-HIHMBMB5.cjs +2 -0
  12. package/dist/chunk-HIHMBMB5.cjs.map +1 -0
  13. package/dist/{chunk-KF5VQH3M.mjs → chunk-MQWMQ4PD.mjs} +2 -2
  14. package/dist/{chunk-KF5VQH3M.mjs.map → chunk-MQWMQ4PD.mjs.map} +1 -1
  15. package/dist/chunk-QDMEM62U.mjs +2 -0
  16. package/dist/chunk-QDMEM62U.mjs.map +1 -0
  17. package/dist/chunk-U3OXAO67.mjs +2 -0
  18. package/dist/chunk-U3OXAO67.mjs.map +1 -0
  19. package/dist/chunk-UZQV73X7.mjs +2 -0
  20. package/dist/chunk-UZQV73X7.mjs.map +1 -0
  21. package/dist/chunk-VXH2FAKV.cjs +2 -0
  22. package/dist/chunk-VXH2FAKV.cjs.map +1 -0
  23. package/dist/chunk-XMO2RCXB.cjs +2 -0
  24. package/dist/chunk-XMO2RCXB.cjs.map +1 -0
  25. package/dist/chunk-YBHHICTZ.mjs +2 -0
  26. package/dist/chunk-YBHHICTZ.mjs.map +1 -0
  27. package/dist/{chunk-3CLDZCHN.cjs → chunk-YJN4JEJU.cjs} +2 -2
  28. package/dist/{chunk-3CLDZCHN.cjs.map → chunk-YJN4JEJU.cjs.map} +1 -1
  29. package/dist/chunk-Z2G7DGDF.mjs +2 -0
  30. package/dist/{chunk-TEPK5Y36.mjs.map → chunk-Z2G7DGDF.mjs.map} +1 -1
  31. package/dist/cli/bin.cjs +1 -1
  32. package/dist/cli/bin.mjs +1 -1
  33. package/dist/cli/index.cjs +1 -1
  34. package/dist/cli/index.mjs +1 -1
  35. package/dist/index.cjs +1 -1
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.d.cts +1 -1
  38. package/dist/index.d.ts +1 -1
  39. package/dist/index.mjs +1 -1
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/kanban/index.cjs +1 -1
  42. package/dist/kanban/index.mjs +1 -1
  43. package/dist/scrum/index.cjs +1 -1
  44. package/dist/scrum/index.mjs +1 -1
  45. package/dist/waterfall/index.cjs +1 -1
  46. package/dist/waterfall/index.d.cts +2 -1
  47. package/dist/waterfall/index.d.ts +2 -1
  48. package/dist/waterfall/index.mjs +1 -1
  49. package/package.json +1 -1
  50. package/dist/chunk-2OVYXXNV.cjs +0 -2
  51. package/dist/chunk-2OVYXXNV.cjs.map +0 -1
  52. package/dist/chunk-7CDGPTEJ.mjs +0 -2
  53. package/dist/chunk-7CDGPTEJ.mjs.map +0 -1
  54. package/dist/chunk-GT57PLUT.mjs +0 -2
  55. package/dist/chunk-GT57PLUT.mjs.map +0 -1
  56. package/dist/chunk-IHE5K4X3.mjs +0 -2
  57. package/dist/chunk-IHE5K4X3.mjs.map +0 -1
  58. package/dist/chunk-N3QB2S7R.cjs +0 -2
  59. package/dist/chunk-N3QB2S7R.cjs.map +0 -1
  60. package/dist/chunk-NA53TZE4.mjs +0 -2
  61. package/dist/chunk-NA53TZE4.mjs.map +0 -1
  62. package/dist/chunk-TEPK5Y36.mjs +0 -2
  63. package/dist/chunk-UBFIKDIP.cjs +0 -2
  64. package/dist/chunk-UBFIKDIP.cjs.map +0 -1
  65. package/dist/chunk-UUOMQMWT.cjs +0 -2
  66. package/dist/chunk-UUOMQMWT.cjs.map +0 -1
  67. package/dist/chunk-Z3PU6EBI.mjs +0 -2
  68. package/dist/chunk-Z3PU6EBI.mjs.map +0 -1
  69. package/dist/chunk-ZTE7LREB.cjs +0 -2
  70. package/dist/chunk-ZTE7LREB.cjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,6 +1,21 @@
1
1
  # Changelog
2
2
 
3
- ## 0.6.0-stage (unreleased)
3
+ ## 1.0.0 (2026-10-24)
4
+
5
+ First stable release, published to `latest`. Phase 7 fixes the five engine gaps the workflowAI S2 dogfood raised (#23-#27) and closes the 1.0 definition; the decisions are in the design spec, section 23.
6
+
7
+ - Trace and reopen ids (#23): a Waterfall `item.add` or `item.edit` is refused (`rule-violation`) when a `traces` id does not name an existing, non-dropped item, or when a change-request's `impactAnalysis.reopen` names a phase that is not configured; the fix lists the ids or phases that are valid.
8
+ - Impact analysis at add (#24): with `changeControl.requiresImpactAnalysis: true`, a change-request without an impact analysis is refused at `item.add` and `item.edit`, and a present one is shape-checked (`summary`, `reopen`, `weight`).
9
+ - Coverage recount (#25): the traceability matrix no longer counts change-requests; `waterfallMetrics.requirementsTraced`, `requirementsTotal` and `requirementCoverage` are computed from the same matrix as `status.report.coverage`, so the two agree.
10
+ - `readyForGate` (#26): `readyForGate` is true as soon as the gate would pass; `PhaseReportRow` gains `missingTraces`, and the generated `traceability-matrix` counts as present for the last traced phase when nothing is missing.
11
+ - Kanban lessons (#27): `service-delivery-review` takes `lessons`, `adopt`, `dismiss` and `retire` with the Scrum retro semantics for agreements; the `cadence.service-delivery-review` payload gains five arrays (`lessons`, `adopted`, `dismissed`, `agreements`, `retired`).
12
+ - Shared lesson helper: the Scrum `retro`, the Waterfall `phaseRetrospective` and the Kanban review share one core helper (`src/lessons.ts`), so a malformed `lessons[]` or `adopt[]` entry on the Scrum retro is refused `invalid-input` (`retro.lessons entries need a text and a scope`) where it was silently accepted before; valid inputs, payloads and messages are unchanged.
13
+ - Compatibility test: `test/compat.test.ts` loads `state.json` fixtures written by the published 0.1.0, 0.2.0, 0.3.0, 0.4.0 and 0.6.0 stage releases (`test/fixtures/compat`, regenerated by `scripts/gen-compat-fixtures.mjs`) and runs `status`, `metrics` and `next` on each; 0.5.0-stage was never published.
14
+ - API-surface freeze: `test/api-surface.test.ts` compares the runtime exports of the five entry points, the CLI `USAGE` lines (10), the schema documents (8) and the event kinds (52) with `test/api-surface.json`; a removal is now a major version, an addition a minor one.
15
+
16
+ Migration: from any 0.N.0-stage a `.workflow/state.json` loads unchanged; the compatibility test proves it for every stage release. Coming from an earlier stage, the behaviour changes of 0.5.0 and 0.6.0 listed below apply. New in 1.0.0: a Waterfall `add` or `edit` is refused for an unknown `traces` or `reopen` id and for a change-request without an impact analysis when the config requires one (#23, #24); `status.report.coverage` and `metrics.requirements*` no longer count change-requests and agree with each other (#25); `readyForGate` is true as soon as the gate would pass (#26); Kanban `service-delivery-review` takes lessons (#27); a malformed `lessons[]`, `adopt[]` or `dismiss[]` entry on the Scrum `retro` is refused `invalid-input` (shared helper); `PhaseReportRow.missingTraces` is added and the `cadence.service-delivery-review` payload gains five arrays. No schema document, event kind or `state.json` change. Versioning from here: semver, `latest`.
17
+
18
+ ## 0.6.0-stage (2026-10-24)
4
19
 
5
20
  Pre-release under the `stage` dist-tag. Phase 6 (backlog zero) fixes or explicitly accepts all 24 items the 1.0 definition named; the decisions are in the design spec, section 22, and the accepted limitations are in the README.
6
21
 
@@ -21,7 +36,7 @@ Pre-release under the `stage` dist-tag. Phase 6 (backlog zero) fixes or explicit
21
36
 
22
37
  Compatibility: no `state.json` schema change and no new event kind; every `.workflow/state.json` written by an earlier stage loads unchanged. The generated `WaterfallConfig` schema document gains one optional key, `fallbackTokensPerWeight`. Behaviour changes, all deliberate: rules run on `item.complete` (B02); custom rules on `item.complete` can refuse a completion (`rule-violation`) and their warnings are returned; `decide(approve)` honours `needs-review` (B05); `ceremony commit` is refused into a closing sprint (B07); a freshly reworked item needs fresh evidence before it passes (B10); a blocked or awaiting-human carryover in review resumes at review (B22); `plan auto` applies tokens and turns together (B20); a value-taking flag without a value is refused (B24); Scrum's `status.report` is no longer `null`.
23
38
 
24
- ## 0.5.0-stage (unreleased)
39
+ ## 0.5.0-stage (unreleased; never published, shipped inside 0.6.0-stage)
25
40
 
26
41
  Pre-release under the `stage` dist-tag. Phase 5 closes the engine gaps the workflowAI scrum-master dogfood raised (issues #8–#21); the decisions are in the design spec, section 21.
27
42
 
package/README.md CHANGED
@@ -7,10 +7,10 @@ State is plain JSON, every operation is `(state, action) -> state`, and every er
7
7
  ## Install
8
8
 
9
9
  ```sh
10
- pnpm add ex-workflow@stage
10
+ npm install ex-workflow
11
11
  ```
12
12
 
13
- Pre-releases are published under the `stage` dist-tag (currently `0.6.0-stage`); `latest` is reserved for 0.1.0.
13
+ `npm install ex-workflow` resolves to 1.0.0 (`pnpm add ex-workflow` likewise). Stage pre-releases may still appear under the `stage` dist-tag.
14
14
 
15
15
  Node >= 18. Runs on macOS, Linux and Windows.
16
16
 
@@ -65,6 +65,8 @@ Cadences are ceremonies: `replenishment`, `delivery-planning`, `service-delivery
65
65
 
66
66
  `next()` also returns `skipped`: each ready card it did not pull, with `reason` (`entry-policy`, `wip`, `resource-cap` or `budget`) and a `detail`; the commitment column's policies gate the pull out of it (escalation `question` cards are exempt, as from exit policies and gates). Ordering is by class band (question, expedite, fixed-date, standard, intangible) and, with `fairness.aging` on (the default), priority stays primary inside a window of `fairness.maxDeferralRounds` passes (default 5); each full window a card is passed over promotes it one step above any priority difference, and an intangible card reaching the first window is ranked as standard, so nothing is starved.
67
67
 
68
+ `service-delivery-review` also takes `lessons`, `adopt`, `dismiss` and `retire`, with the Scrum retro semantics for agreements.
69
+
68
70
  ### Waterfall
69
71
 
70
72
  ```ts
@@ -90,6 +92,8 @@ generates the `traceability-matrix` deliverable. Edits to baselined items are re
90
92
  they go through `applyAction` or the CLI. `test/waterfall.e2e.test.ts` is a full project with a
91
93
  change-request that reopens two baselined phases.
92
94
 
95
+ `add` and `edit` validate `traces` ids and the impact analysis of a change-request, and `status` phase rows carry `missingTraces`.
96
+
93
97
  ## CLI
94
98
 
95
99
  State lives in `.workflow/`. Every command prints JSON; errors exit 1, bad usage exits 2.
@@ -167,7 +171,7 @@ This package is L0. All layers read and write the same `.workflow/` files.
167
171
 
168
172
  ## Status
169
173
 
170
- 0.6.0-stage closes the Phase 6 backlog: every item the 1.0 definition named is either fixed or an accepted limitation (see [Accepted limitations](#accepted-limitations)). 0.5.0-stage closes the engine gaps from the workflowAI dogfood (Scrum budget gates, configuration between iterations, accounting corrections, agreements that can be replaced or retired, question briefs with their parent); see [CHANGELOG.md](CHANGELOG.md). 0.4.0-stage added `ex-workflow/schema` (JSON Schema documents and a validator, checked by `exwf` on load and on input). 0.3.0-stage added the Waterfall module; all three methodologies ship. Design: [docs/superpowers/specs/2026-10-19-ex-workflow-design.md](docs/superpowers/specs/2026-10-19-ex-workflow-design.md).
174
+ 1.0.0 (2026-10-24) closes the Phase 7 engine gaps (#23-#27) and freezes the public API (exports, CLI commands, schema documents, event kinds — test/api-surface.json) with a compatibility test over state files from every stage release; from here versioning is semver and `latest` is the supported line. 0.6.0-stage closed the Phase 6 backlog: every item the 1.0 definition named is either fixed or an accepted limitation (see [Accepted limitations](#accepted-limitations)). 0.5.0-stage closes the engine gaps from the workflowAI dogfood (Scrum budget gates, configuration between iterations, accounting corrections, agreements that can be replaced or retired, question briefs with their parent); see [CHANGELOG.md](CHANGELOG.md). 0.4.0-stage added `ex-workflow/schema` (JSON Schema documents and a validator, checked by `exwf` on load and on input). 0.3.0-stage added the Waterfall module; all three methodologies ship. Design: [docs/superpowers/specs/2026-10-19-ex-workflow-design.md](docs/superpowers/specs/2026-10-19-ex-workflow-design.md).
171
175
 
172
176
  ## Accepted limitations
173
177
 
@@ -202,16 +206,18 @@ There is no hosted CI. A husky pre-commit hook runs the local gate on every comm
202
206
  minified build, the dist identity check and the size ratchet, and `prepublishOnly` runs it
203
207
  before any publish. oxfmt and oxlint need Node ^20.19 or >=22.12 on the developer machine; the
204
208
  package itself supports Node >=18 (verified on ubuntu, macOS and Windows x Node 18/20/22
205
- before the hosted workflow was removed). Schema drift is guarded by `pnpm schema:check` alone, not by a test, because the generator needs Node >=22 and the test suite must run on >=18.
209
+ before the hosted workflow was removed). `pnpm test` includes the compatibility fixtures (`test/fixtures/compat`, `state.json` files written by the published 0.1.0, 0.2.0, 0.3.0, 0.4.0 and 0.6.0 stage releases; 0.5.0-stage was never published); `node scripts/gen-compat-fixtures.mjs` regenerates them (network needed). Schema drift is guarded by `pnpm schema:check` alone, not by a test, because the generator needs Node >=22 and the test suite must run on >=18.
206
210
 
207
211
  ## Publishing
208
212
 
209
- For the owner. The `stage` dist-tag keeps `latest` free for 0.1.0:
213
+ For the owner. A release moves `latest`:
210
214
 
211
215
  ```sh
212
- pnpm run ci && npm publish --tag stage
216
+ pnpm run ci && npm publish
213
217
  ```
214
218
 
219
+ Use `npm publish --tag stage` only for a pre-release.
220
+
215
221
  ## Design principles
216
222
 
217
223
  1. One engine, three methodologies, modelled as completely as the canonical texts describe them (Scrum Guide 2020; the Kanban Method's six practices, cadences, classes of service and flow metrics; classic phase-gate Waterfall with change control and traceability).
@@ -0,0 +1,2 @@
1
+ import {a as a$1,b as b$2}from'./chunk-U3OXAO67.mjs';import {c,u,x,o,n,i,j as j$1,I,R as R$1,N,Y as Y$1,a,K as K$1,M as M$1}from'./chunk-YBHHICTZ.mjs';import {b as b$1,c as c$1}from'./chunk-2FRRD6A3.mjs';import {timSort}from'exsorted';var De=["requirements","design","implementation","verification","deployment","maintenance"],pe={requirements:["srs"],design:["design-doc","interface-spec"],implementation:["code-baseline"],verification:["test-report","traceability-matrix"],deployment:["release-notes","deployment-record"],maintenance:["change-log"]},fe={requirements:"business-analyst",design:"architect",deployment:"release-manager"},ue=e=>`${e}-gate`,me="change-control",je=["order-backlog","define-acceptance","facilitate","deliver","review","verify","approve-gate","manage-flow","control-change","escalate"],Be=e=>e.charAt(0).toUpperCase()+e.slice(1);function Me(){return De.map(e=>{let t={id:e,name:Be(e),deliverables:[...pe[e]??[]],gate:{id:ue(e),requires:[{capability:"approve-gate"}],evidence:[],onFail:{action:"block"}}},n=fe[e];return n!==void 0&&(t.deliverBy=n),t})}function w(e){return e.config}var G=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),re=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.trim()!=="");function Ye(e,t){if(e===void 0)return;G(e)||b$1("config-invalid",`${t}.budget must be an object`,'e.g. { "tokens": 400000 }');let n={};for(let a of ["tokens","turns","wallclockMs"]){let p=e[a];p!==void 0&&((typeof p!="number"||!Number.isFinite(p)||p<0)&&b$1("config-invalid",`${t}.budget.${a} must be a non-negative number`,"omit it for no limit"),n[a]=p);}return n}function Ge(e,t){return (!Array.isArray(e)||e.length===0)&&b$1("config-invalid",`${t} must be a non-empty array of "human" | { capability }`,'e.g. ["human", { "capability": "approve-gate" }]'),e.map(n=>n==="human"?"human":G(n)&&typeof n.capability=="string"&&je.includes(n.capability)?{capability:n.capability}:b$1("config-invalid",`${t} entry ${JSON.stringify(n)} is not "human" or a known capability`,`use "human" or { "capability": one of ${je.join(", ")} }`))}function Ee(e,t,n){let a=`waterfall config.phases[${t}]`;G(e)||b$1("config-invalid",`${a} must be an object`,'e.g. { "id": "design" }'),c$1(e.id,`${a}.id`);let p=e.id,c=e.deliverables??pe[p]??[];re(c)||b$1("config-invalid",`${a}.deliverables must be a string[] of evidence kinds`,'e.g. ["srs"]');let o;if(e.gate===void 0)o={id:ue(p),requires:[{capability:"approve-gate"}],evidence:[],onFail:{action:"block"}};else {let l=e.gate;(!G(l)||typeof l.id!="string"||l.id.trim()==="")&&b$1("config-invalid",`${a}.gate must be a Gate with an id`,'e.g. { "id": "design-gate", "requires": [{ "capability": "approve-gate" }], "evidence": [] }');let f=l.evidence??[];re(f)||b$1("config-invalid",`${a}.gate.evidence must be a string[]`,"list evidence kinds or omit it"),o={id:l.id,requires:Ge(l.requires??[{capability:"approve-gate"}],`${a}.gate.requires`),evidence:[...f],onFail:{action:"block"}};}n(p)&&!o.requires.includes("human")&&(o.requires=["human",...o.requires]);let d={id:p,name:typeof e.name=="string"&&e.name.trim()!==""?e.name:Be(p),deliverables:[...c],gate:o},i=Ye(e.budget,a);i!==void 0&&(d.budget=i);let s=e.deliverBy??fe[p];return s!==void 0&&((typeof s!="string"||s.trim()==="")&&b$1("config-invalid",`${a}.deliverBy must be a role id`,"name the role that delivers this phase or omit it"),d.deliverBy=s),d}function ge(e){let t=e??{};t.phases!==void 0&&!Array.isArray(t.phases)&&b$1("config-invalid","waterfall config.phases must be an array of phases","omit phases for the six classic phases");let n=t.humanGates??"all";n!=="all"&&!re(n)&&b$1("config-invalid",'waterfall config.humanGates must be "all" or a string[] of phase ids','omit it for "all"');let a=n==="all"?()=>true:r=>n.includes(r),p=t.phases===void 0?Me().map((r,m)=>Ee(r,m,a)):t.phases.map((r,m)=>Ee(r,m,a));p.length===0&&b$1("config-invalid","waterfall config.phases needs at least one phase",'e.g. [{ "id": "requirements" }]');let c=p.map(r=>r.id),o=c.find((r,m)=>c.indexOf(r)!==m);if(o!==void 0&&b$1("config-invalid",`duplicate phase id "${o}"`,"give every phase a unique id"),n!=="all")for(let r of n)c.includes(r)||b$1("config-invalid",`waterfall config.humanGates names unknown phase "${r}"`,`phases are: ${c.join(", ")}`);let d=t.changeControl??{};G(d)||b$1("config-invalid","waterfall config.changeControl must be an object",'e.g. { "requiresImpactAnalysis": true, "approvers": ["human"] }'),d.requiresImpactAnalysis!==void 0&&typeof d.requiresImpactAnalysis!="boolean"&&b$1("config-invalid","waterfall config.changeControl.requiresImpactAnalysis must be a boolean","omit it for true");let i={requiresImpactAnalysis:d.requiresImpactAnalysis===void 0?true:d.requiresImpactAnalysis,approvers:Ge(d.approvers??["human",{capability:"control-change"}],"waterfall config.changeControl.approvers")},s=t.traceability,l;if(s===void 0)l=c.includes("requirements")&&c.includes("design")&&c.includes("verification")?{from:"requirements",to:["design","verification"]}:{from:c[0],to:[]};else {(!G(s)||typeof s.from!="string"||!c.includes(s.from))&&b$1("config-invalid","waterfall config.traceability.from must be a phase id",`phases are: ${c.join(", ")}`);let r=s.to??[];re(r)||b$1("config-invalid","waterfall config.traceability.to must be a string[] of phase ids",`phases are: ${c.join(", ")}`);for(let m of r)c.includes(m)||b$1("config-invalid",`waterfall config.traceability.to names unknown phase "${m}"`,`phases are: ${c.join(", ")}`),c.indexOf(m)<=c.indexOf(s.from)&&b$1("config-invalid",`waterfall config.traceability.to phase "${m}" must come after "${s.from}"`,"trace forward only: from an earlier phase to later ones");l={from:s.from,to:[...r]};}let f=t.fallbackTokensPerWeight;f!==void 0&&(typeof f!="number"||!Number.isFinite(f)||f<=0)&&b$1("config-invalid","waterfall config.fallbackTokensPerWeight must be a positive finite number","omit it for the default 20000");let u={phases:p,changeControl:i,traceability:l,humanGates:n==="all"?"all":[...n]};return f!==void 0&&(u.fallbackTokensPerWeight=f),u}var L="work",V="review",H="done";function b(e){return e.phases?e.phases:w(e).phases.map(t=>{let n={id:t.id,name:t.name,deliverables:[...t.deliverables],gate:t.gate,status:"pending"};return t.budget&&(n.budget=t.budget),n})}function j(e,t){return {...e,phases:t}}function E(e,t){let n=b(e).findIndex(a=>a.id===t);return n<0&&b$1("config-invalid",`unknown phase "${t}"`,`phases are: ${b(e).map(a=>a.id).join(" \u2192 ")}`),n}function _(e,t){return b(e)[E(e,t)]}function q(e,t){let n=new Set,a=t;for(;a&&!n.has(a.id);){if(a.phase!==void 0)return a.phase;n.add(a.id),a=a.parent!==void 0&&Object.hasOwn(e.items,a.parent)?e.items[a.parent]:void 0;}}function P(e,t){return Object.values(e.items).filter(n=>n.status!=="dropped"&&q(e,n)===t)}function D(e){return b(e).find(t=>t.status==="open")}function he(e){return b(e).find(t=>t.status!=="baselined")}function Je(e,t){let n=q(e,t);return n!==void 0&&b(e).find(a=>a.id===n)?.status==="baselined"}function _e(e,t){let n=new Set((t.produced??[]).map(a=>a.kind));for(let a of P(e,t.id))for(let p of a.evidence)n.add(p.kind);return n}function U(e,t,n=[]){let a=_e(e,t);for(let c of n)a.add(c);let p=[];for(let c of [...t.deliverables,...t.gate.evidence])p.includes(c)||p.push(c);return p.filter(c=>!a.has(c))}function B(e){let t=b(e).map(a=>a.id),n=w(e).traceability.to.filter(a=>t.includes(a));if(n.length!==0)return n.reduce((a,p)=>t.indexOf(a)>=t.indexOf(p)?a:p)}function Fe(e,t,n,a){let p=R$1(e);return !p||!p.id.startsWith(`${t}#`)?e:{...e,iterations:e.iterations.map(c=>c.id===p.id?{...c,endedAt:a,outcome:n}:c)}}function ae(e,t,n,a){let p=_(e,t);p.status!=="open"&&b$1("invalid-transition",`phase "${t}" is ${p.status}, not open`,p.status==="baselined"?"it is already baselined; a change-request reopens it":"kickoff the phase first");let c$1=P(e,t),o={};for(let l of c$1)o[l.id]=l;let d=(e.baselines??[]).filter(l=>l.phase===t).length,i={phase:t,version:d+1,at:a,approvedBy:n,itemSnapshot:o},s=j(e,b(e).map(l=>l.id===t?{...l,status:"baselined"}:l));return s={...s,baseline:i,baselines:[...s.baselines??[],i]},s=Fe(s,t,"completed",a),c(s,"phase.baselined",n[n.length-1]??"system",{phase:t,version:i.version,approvedBy:n,items:c$1.map(l=>l.id)},a)}function ye(e,t,n){let a=[];for(let d of t){let i=_(e,d);i.status==="pending"&&b$1("invalid-input",`phase "${d}" was never baselined; there is nothing to reopen`,"remove it from impactAnalysis.reopen"),i.status==="baselined"&&!a.includes(d)&&a.push(d);}let p=b(e).map(d=>a.includes(d.id)?{...d,status:"reopened"}:d),c=null,o=e;if(a.length){let d=Math.min(...a.map(s=>E(e,s))),i=p.find((s,l)=>s.status==="open"&&l>d);i&&(c=i.id,p=p.map(s=>s.id===i.id?{...s,status:"reopened"}:s),o=Fe(o,i.id,"cancelled",n));}return {state:j(o,p),reopened:a,suspended:c}}function z(e,t,n,a,p){let c$1=u(e,t),o=c$1.impactAnalysis,d=ye(e,o?.reopen??[],p),i=x(d.state,t,{stage:H,status:"done"},n,p);for(let s of d.reopened)i=c(i,"phase.reopened",n,{phase:s,change:t},p);return d.suspended!==null&&(i=c(i,"phase.suspended",n,{phase:d.suspended,change:t},p)),c(i,"change.decided",n,{change:t,decision:"approve",by:n,note:a,reopened:d.reopened,suspended:d.suspended,weight:o?.weight??0,affects:c$1.affects??[]},p)}function K(e,t,n,a,p){let c$1=u(e,t),o=x(e,t,{status:"dropped"},n,p);return c(o,"change.decided",n,{change:t,decision:"reject",by:n,note:a,reopened:[],suspended:null,weight:0,affects:c$1.affects??[]},p)}function Ne(e){return (t,n)=>{o(t,n.by,"facilitate");let a$2=n.phase===void 0?void 0:Y(t,n,"phaseRetrospective"),p=a$1(t,n,"phaseRetrospective");return Y$1(t,e(),{type:"ceremony.phaseRetrospective",by:n.by,payload:n},c$1=>{let o=c$1,d=a(n.now),i=b$2(o,p,n.by,d);return o=i.state,c(o,"phase.retrospective",n.by,{phase:a$2?.id??null,lessons:i.created,adopted:i.adopted.slice(i.created.length),dismissed:i.dismissed,agreements:i.agreements,retired:i.retired},d)})}}var Ze=(e,t)=>e.id<t.id?-1:e.id>t.id?1:0,Le=(e,t)=>timSort(P(e,t).filter(n=>n.type!=="question"&&n.type!=="change-request"),Ze),Xe=(e,t)=>(e.traces??[]).includes(t.id)||(t.traces??[]).includes(e.id);function O(e){let t=w(e).traceability,n=b(e).map(o=>o.id),a=t.to.filter(o=>n.includes(o)),p=Le(e,t.from).map(o=>{let d={};for(let i of a)d[i]=Le(e,i).filter(s=>Xe(o,s)).map(s=>s.id);return {item:o.id,links:d}}),c=p.map(o=>({item:o.item,phases:a.filter(d=>o.links[d].length===0)})).filter(o=>o.phases.length>0);return {from:t.from,to:a,rows:p,missing:c,coverage:{traced:p.length-c.length,total:p.length}}}function J(e,t){return O(e).rows.filter(n=>(n.links[t]??[]).length===0).map(n=>n.item)}var et=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Y(e,t,n){let a=t.phase;return (typeof a!="string"||a.trim()==="")&&b$1("invalid-input",`${n} needs phase: string`,`pass one of: ${b(e).map(p=>p.id).join(", ")}`),_(e,a)}function Ve(e,t,n,a,p,c$1){let o=j(e,b(e).map(d=>d.id===t?{...d,produced:[...d.produced??[],{kind:n,ref:a,by:p,at:c$1}]}:d));return c(o,"phase.deliverable",p,{phase:t,kind:n,ref:a},c$1)}function be(e){let t=(c,o,d,i)=>Y$1(c,e(),{type:o,by:d.by,payload:d},s=>i(s,a(d.now)));return {kickoff:(c$1,o$1)=>{o(c$1,o$1.by,"facilitate");let d=Y(c$1,o$1,"kickoff");return t(c$1,"ceremony.kickoff",o$1,(i,s)=>{let l=i.events.filter(r=>r.type==="phase.opened"&&r.payload.phase===d.id).length+1,f=P(i,d.id).filter(r=>r.status!=="done").map(r=>r.id);i=j(i,b(i).map(r=>r.id===d.id?{...r,status:"open"}:r));let u=d.budget??{};return i={...i,iterations:[...i.iterations,{id:`${d.id}#${l}`,goal:d.name,budget:u,spent:M$1,startedAt:s,committed:f,carryover:[]}]},c(i,"phase.opened",o$1.by,{phase:d.id,version:l,items:f,budget:u},s)})},gateReview:(c$1,o)=>{let d=Y(c$1,o,"gateReview");d.status!=="open"&&b$1("invalid-transition",`phase "${d.id}" is ${d.status}, not open`,d.status==="baselined"?"it is already baselined; a change-request reopens it":`kickoff "${d.id}" first`);let i=d.gate,s=j$1(c$1,i.id,"approve-gate");o.by!=="human"&&!s.includes(o.by)&&b$1("gate-unmet",`"${o.by}" may not review gate "${i.id}"`,`review as one of: human${s.map(r=>`, ${r}`).join("")}`,{rule:"gate"});let l=c$1.pending.find(r=>r.kind==="gate"&&r.item===void 0&&r.gate===i.id);l&&b$1("no-op",`gate "${i.id}" is already awaiting a decision (${l.id})`,`decide ${l.id} approve|reject`);let f=o.deliverables??[];(!Array.isArray(f)||!f.every(r=>et(r)&&typeof r.kind=="string"&&r.kind.trim()!==""&&typeof r.ref=="string"))&&b$1("invalid-input","gateReview.deliverables must be [{ kind, ref }]",'e.g. { "deliverables": [{ "kind": "srs", "ref": "docs/srs.md" }] }');let u=f;return t(c$1,"ceremony.gateReview",o,(r,m)=>{for(let h of u)r=Ve(r,d.id,h.kind,h.ref,o.by,m);if(w(r).traceability.to.includes(d.id)){let h=O(r);r=c(r,"traceability.computed",o.by,{phase:d.id,from:h.from,to:h.to,coverage:h.coverage,missing:h.missing,rows:h.rows},m),d.id===B(r)&&h.missing.length===0&&(r=Ve(r,d.id,"traceability-matrix",`traceability.computed#${r.events[r.events.length-1].seq}`,o.by,m));}if(i.requires.includes("human")&&o.by!=="human"){r=K$1(r,{kind:"gate",gate:i.id,question:`Approve gate "${i.id}" and baseline phase "${d.name}"?`},m);let h=r.pending[r.pending.length-1].id;return c(r,"phase.gate-pending",o.by,{phase:d.id,gate:i.id,by:o.by,pending:h},m)}return ae(r,d.id,[o.by],m)})},changeControlBoard:(c$1,o$1)=>{o(c$1,o$1.by,"control-change");let d=o$1.change;(typeof d!="string"||d.trim()==="")&&b$1("invalid-input","changeControlBoard needs change: string (a change-request id)",'e.g. { "change": "CR-1", "decision": "approve", "note": "why" }');let i$1=u(c$1,d);if(i$1.type!=="change-request"&&b$1("invalid-input",`item "${d}" is a ${i$1.type}, not a change-request`,"only change-request items go through the board",{items:[d]}),(i$1.status==="done"||i$1.status==="dropped")&&b$1("invalid-transition",`change "${d}" is already ${i$1.status==="done"?"approved":"rejected"}`,"raise a new change-request",{items:[d]}),i$1.status==="awaiting_human"){let r=c$1.pending.find(m=>m.item===d);b$1("no-op",`change "${d}" is awaiting the human decision${r?` (${r.id})`:""}`,`decide ${r?.id??"<pending id>"} approve|reject`,{items:[d]});}let s=o$1.decision;s!=="approve"&&s!=="reject"&&b$1("invalid-input",'changeControlBoard.decision must be "approve" or "reject"',"state the board's decision");let l=typeof o$1.note=="string"?o$1.note:"",f=w(c$1).changeControl.approvers;for(let r of f)r==="human"||o$1.by==="human"||n(c$1,o$1.by,r.capability)||b$1("gate-unmet",`"${o$1.by}" lacks capability "${r.capability}" required by change control`,`decide as one of: human${i(c$1,r.capability).map(m=>`, ${m.id}`).join("")}`,{rule:"change-control",items:[d]});let u$1=f.includes("human")&&o$1.by!=="human";return t(c$1,"ceremony.changeControlBoard",o$1,(r,m)=>{if(u$1){r=K$1(r,{kind:"decision",item:d,question:`Change "${d}" (${i$1.title}): the board (${o$1.by}) recommends ${s}${l?`: ${l}`:""}. Approve or reject the change?`},m);let h=r.pending[r.pending.length-1].id;return c(r,"change.recommended",o$1.by,{change:d,decision:s,note:l,pending:h},m)}return s==="approve"?z(r,d,o$1.by,l,m):K(r,d,o$1.by,l,m)})},phaseRetrospective:Ne(e)}}function ve(e,t,n,a,p,c$1){if(t.kind==="gate"&&t.item===void 0&&t.gate!==void 0){let o=b(e).find(s=>s.gate.id===t.gate);if(!o)return e;a!=="human"&&b$1("gate-unmet",`"${a}" may not decide phase gate "${t.gate}" (${t.id}); it awaits a human`,`decide ${t.id} as human`,{rule:"gate"});let d;for(let s=e.events.length-1;s>=0;s--){let l=e.events[s];if(l.type==="phase.gate-pending"&&l.payload.pending===t.id){d=l.by;break}}let i=d!==void 0&&d!==a?[d,a]:[a];return n==="approve"?ae(e,o.id,i,c$1):c(e,"phase.gate-failed",a,{phase:o.id,gate:t.gate,note:p},c$1)}if(t.kind==="decision"&&t.item!==void 0&&Object.hasOwn(e.items,t.item)){let o=e.items[t.item];return o.type!=="change-request"?e:(a!=="human"&&b$1("gate-unmet",`"${a}" may not decide change "${o.id}" (${t.id}); change control awaits a human`,`decide ${t.id} as human`,{rule:"change-control",items:[o.id]}),n==="approve"?z(e,o.id,a,p,c$1):K(e,o.id,a,p,c$1))}return e}function ke(e){let t=w(e).phases.map($=>$.id),n=()=>Object.fromEntries(t.map($=>[$,0])),a=n(),p=n(),c=n(),o=n(),d=n(),i=new Map,s=new Map,l=new Map,f=0,u=0,r=0,m=0,h=0,v=$=>{let W=s.get($),y=i.get($);return W!=="question"&&W!=="change-request"&&y!==void 0&&y in a};for(let $ of e.events){let W=$.payload??{};switch($.type){case "item.added":{let y=W,T=y.phase??(y.parent!==null?i.get(y.parent):void 0);i.set(y.id,T),s.set(y.id,y.type),l.set(y.id,"todo"),y.type==="change-request"&&(f+=1),v(y.id)&&(a[T]+=1,y.type==="bug"&&(d[T]+=1));break}case "item.transition":{let y=W.id,T=W.to.status,Pe=l.get(y);if(l.set(y,T),!v(y))break;let de=i.get(y);T==="done"&&Pe!=="done"&&(p[de]+=1),T==="dropped"&&(a[de]-=1,Pe==="done"&&(p[de]-=1));break}case "item.completed":{let y=i.get(W.id);y!==void 0&&y in o&&(o[y]+=W.tokens??0);break}case "phase.opened":{let y=W.phase;y in c&&(c[y]=(W.budget??{}).tokens??0);break}case "change.decided":{W.decision==="approve"?(u+=1,m+=W.weight??0,h+=(W.reopened??[]).length):r+=1;break}}}let Z=n(),I=n();for(let $ of t){let W=a[$]??0;Z[$]=W===0?0:(p[$]??0)/W*100,I[$]=o[$]-c[$];}let{traced:x,total:se}=O(e).coverage,Re=u+r;return {phaseCompletion:Z,budgetPlanned:c,budgetSpent:o,scheduleVariance:I,requirementCoverage:se===0?0:x/se,requirementsTraced:x,requirementsTotal:se,defectsPerPhase:d,changeRequests:f,changesApproved:u,changesRejected:r,changeApprovalRate:Re===0?0:u/Re,reworkWeight:m,phasesReopened:h}}function we(e){let t=e.phases.map(n=>n.gate.id);return [{id:"project-manager",name:"Project Manager",modelTier:"large",capabilities:["facilitate","control-change","approve-gate","escalate"],canApprove:[...t,me],inputs:["phase-plan","deliverables","change-requests"],outputs:["gate-decisions","baselines","change-decisions"],do_not:["do not implement items yourself","do not reopen a phase without an approved change-request"]},{id:"developer",name:"Developer",modelTier:"small",capabilities:["deliver"],canApprove:[],inputs:["design-doc","interface-spec","brief"],outputs:["code","code-baseline","test-output"],do_not:["do not change requirements or designs; raise a change-request","do not approve your own work"]},{id:"business-analyst",name:"Business Analyst",modelTier:"medium",capabilities:["define-acceptance","deliver"],canApprove:[],inputs:["stakeholder-needs"],outputs:["srs","acceptance-criteria"],do_not:["do not design or implement","do not edit a baselined requirement; raise a change-request"]},{id:"architect",name:"Architect",modelTier:"medium",capabilities:["deliver"],canApprove:[],inputs:["srs"],outputs:["design-doc","interface-spec"],do_not:["do not change requirements; raise a change-request","do not implement"]},{id:"qa",name:"QA",modelTier:"small",capabilities:["verify","review"],canApprove:[],inputs:["srs","design-doc","code-baseline"],outputs:["test-report","review-notes"],do_not:["do not fix defects yourself; raise bugs","do not approve phase gates"]},{id:"release-manager",name:"Release Manager",modelTier:"small",capabilities:["deliver"],canApprove:[],inputs:["code-baseline","test-report"],outputs:["release-notes","deployment-record"],do_not:["do not deploy an unbaselined verification phase"]}]}var k=(e,t,n,a)=>a?{rule:e,severity:"error",item:a,message:t,fix:n}:{rule:e,severity:"error",message:t,fix:n},R=e=>e.payload??{},C=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Q=e=>{let t=R(e).phase;return typeof t=="string"?t:void 0},S=(e,t)=>b(e).find(n=>n.id===t),oe=e=>b(e).map(t=>t.id).join(", "),M=(e,t)=>typeof t=="string"&&Object.hasOwn(e.items,t)?e.items[t]:void 0;function He(e,t){if(t.phase!==void 0)return t.phase;let n=M(e,t.parent);return n?q(e,n):void 0}var Ue=e=>e.type!=="change-request"&&e.type!=="question",ze=(e,t)=>`raise a change-request: addItem({ type: "change-request", affects: ["${e}"], impactAnalysis: { summary, reopen: ["${t}"], weight } }) and decide it in changeControlBoard`;function Ke(e,t){let n=M(e,R(t).change);return n&&n.type==="change-request"?n:void 0}function $e(e,t,n){let a="change-needs-impact-analysis",p=`editItem("${t}", { impactAnalysis: { summary: "what changes and why", reopen: ["<phase>"], weight: <points> } })`;if(n===void 0)return w(e).changeControl.requiresImpactAnalysis?[k(a,`change "${t}" has no impact analysis`,p,t)]:[];let c=[],o=C(n)?n:{};return (typeof o.summary!="string"||o.summary.trim()==="")&&c.push(k(a,`change "${t}" impactAnalysis.summary is empty`,p,t)),(!Array.isArray(o.reopen)||!o.reopen.every(d=>typeof d=="string"))&&c.push(k(a,`change "${t}" impactAnalysis.reopen must be a string[] of phase ids`,p,t)),(typeof o.weight!="number"||!Number.isFinite(o.weight)||o.weight<0)&&c.push(k(a,`change "${t}" impactAnalysis.weight must be a non-negative number`,p,t)),c}function We(){return [{id:"phase-sequential",severity:"error",check(i,s){let l=[];if(s.type==="ceremony.kickoff"){let f=Q(s),u=f===void 0?void 0:S(i,f);if(!u)return [];u.status==="open"&&l.push(k("phase-sequential",`phase "${u.id}" is already open`,`gateReview "${u.id}" when its work is done`)),u.status==="baselined"&&l.push(k("phase-sequential",`phase "${u.id}" is baselined`,"only an approved change-request reopens a baselined phase"));let r=D(i);r&&r.id!==u.id&&l.push(k("phase-sequential",`phase "${r.id}" is still open`,`pass its gate (gateReview "${r.id}") before opening "${u.id}"`));}else if(s.type==="item.add"){let f=R(s).item;if(!C(f)||!Ue(f))return [];let u=He(i,f);u===void 0?l.push(k("phase-sequential",`item "${f.id}" belongs to no phase`,`set phase to one of: ${oe(i)}`,f.id)):S(i,u)||l.push(k("phase-sequential",`item "${f.id}" names unknown phase "${u}"`,`phases are: ${oe(i)}`,f.id));}else if(s.type==="item.edit"){let f=R(s).id,u=R(s).patch,r=M(i,f);if(!r||!C(u)||u.phase===void 0||u.phase===r.phase)return [];l.push(k("phase-sequential",`item "${r.id}" cannot move from phase "${r.phase??"(none)"}" to "${String(u.phase)}"`,`drop "${r.id}" and add a new item in phase "${String(u.phase)}"`,r.id));}return l}},{id:"gate-before-next-phase",severity:"error",check(i,s){if(s.type!=="ceremony.kickoff")return [];let l=Q(s),f=b(i),u=l===void 0?-1:f.findIndex(m=>m.id===l);if(u<0)return [];let r=f.slice(0,u).filter(m=>m.status!=="baselined").map(m=>m.id);return r.length===0?[]:[k("gate-before-next-phase",`phase(s) ${r.join(", ")} before "${l}" are not baselined`,`kickoff and gateReview them in order, starting with "${r[0]}"`)]}},{id:"baseline-immutable",severity:"error",check(i,s){let l=f=>(i.baselines??[]).filter(u=>u.phase===f).length||1;if(s.type==="item.edit"){let f=M(i,R(s).id);if(!f)return [];let u=q(i,f);return u===void 0||S(i,u)?.status!=="baselined"?[]:[k("baseline-immutable",`item "${f.id}" is frozen: phase "${u}" is baselined (v${l(u)})`,ze(f.id,u),f.id)]}if(s.type==="item.add"){let f=R(s).item;if(!C(f)||!Ue(f))return [];let u=He(i,f);return u===void 0||S(i,u)?.status!=="baselined"?[]:[k("baseline-immutable",`cannot add "${f.id}" to baselined phase "${u}" (v${l(u)})`,ze(f.id,u),f.id)]}return []}},{id:"change-needs-impact-analysis",severity:"error",check(i,s){if(s.type==="item.add"){let r=R(s).item;return !C(r)||r.type!=="change-request"?[]:$e(i,String(r.id),r.impactAnalysis)}if(s.type==="item.edit"){let r=R(s).patch,m=M(i,R(s).id);return !m||m.type!=="change-request"||!C(r)||!("impactAnalysis"in r)?[]:$e(i,m.id,r.impactAnalysis)}if(s.type!=="ceremony.changeControlBoard")return [];let l=Ke(i,s);if(!l)return [];let f=$e(i,l.id,l.impactAnalysis);if(f.length||l.impactAnalysis===void 0)return f;let u=R(s).decision==="approve";for(let r of l.impactAnalysis.reopen){let m=S(i,r);m?u&&m.status==="pending"&&f.push(k("change-needs-impact-analysis",`phase "${r}" was never baselined; it cannot be reopened`,`remove "${r}" from impactAnalysis.reopen`,l.id)):f.push(k("change-needs-impact-analysis",`change "${l.id}" impactAnalysis.reopen names unknown phase "${r}"`,`phases are: ${oe(i)}`,l.id));}return f}},{id:"requirement-traced",severity:"error",check(i,s){if(s.type!=="ceremony.gateReview")return [];let l=Q(s),f=w(i).traceability;return l===void 0||!f.to.includes(l)||!S(i,l)?[]:J(i,l).map(u=>k("requirement-traced",`item "${u}" of phase "${f.from}" has no trace into "${l}"`,`editItem a "${l}" item with traces: ["${u}"] (or editItem("${u}", { traces: [...] }) while "${f.from}" is not baselined)`,u))}},{id:"deliverables-present",severity:"error",check(i,s){if(s.type!=="ceremony.gateReview")return [];let l=Q(s),f=l===void 0?void 0:S(i,l);if(!f)return [];let u=[],r=P(i,f.id).filter(v=>v.status!=="done").map(v=>v.id);r.length&&u.push(k("deliverables-present",`${r.length} item(s) in phase "${f.id}" are not done: ${r.join(", ")}`,"finish them (next/complete) or drop them before the gate"));let m=R(s).deliverables,h=Array.isArray(m)?m.filter(v=>C(v)&&typeof v.kind=="string").map(v=>v.kind):[];f.id===B(i)&&h.push("traceability-matrix");for(let v of U(i,f,h))u.push(k("deliverables-present",`phase "${f.id}" has no deliverable "${v}"`,`pass deliverables: [{ "kind": "${v}", "ref": "<where it lives>" }] to gateReview, or attach evidence of kind "${v}" on an item of the phase`));return u}},{id:"approver-not-author",severity:"error",check(i$1,s){if(s.by==="human")return [];if(s.type==="ceremony.gateReview"){let l=Q(s),f=l===void 0?void 0:S(i$1,l);if(!f)return [];let u=P(i$1,f.id).filter(m=>I(i$1,m)===s.by).map(m=>m.id);if(u.length===0)return [];let r=j$1(i$1,f.gate.id,"approve-gate",s.by);return [k("approver-not-author",`"${s.by}" authored ${u.join(", ")} in phase "${f.id}" and may not approve its gate`,`review the gate as one of: human${r.map(m=>`, ${m}`).join("")}`)]}if(s.type==="ceremony.changeControlBoard"){let l=Ke(i$1,s);if(!l)return [];let f=i$1.events.find(r=>r.type==="item.added"&&r.payload.id===l.id);if(!f||f.by!==s.by)return [];let u=i(i$1,"control-change").map(r=>r.id).filter(r=>r!==s.by);return [k("approver-not-author",`"${s.by}" raised change "${l.id}" and may not decide it`,`decide as human${u.map(r=>`, ${r}`).join("")}`,l.id)]}return []}},{id:"trace-ids-valid",severity:"error",check(i,s){let l,f,u,r;if(s.type==="item.add"){let h=R(s).item;if(!C(h))return [];l=String(h.id),f=h.traces,u=h.impactAnalysis,r=h.type==="change-request";}else if(s.type==="item.edit"){let h=M(i,R(s).id),v=R(s).patch;if(!h||!C(v))return [];l=h.id,f=v.traces,u=v.impactAnalysis,r=h.type==="change-request";}else return [];let m=[];if(Array.isArray(f)){let h=w(i).traceability,v=[h.from,...h.to].flatMap(I=>P(i,I).filter(x=>x.type!=="question"&&x.type!=="change-request").map(x=>x.id)),Z=`traceable items: ${v.length?v.join(", "):"(none yet)"}`;for(let I of f){if(typeof I!="string")continue;let x=M(i,I);(!x||x.status==="dropped")&&m.push(k("trace-ids-valid",`item "${l}" traces unknown item "${I}"`,Z,l));}}if(r&&C(u)&&Array.isArray(u.reopen))for(let h of u.reopen)typeof h=="string"&&!S(i,h)&&m.push(k("trace-ids-valid",`change "${l}" impactAnalysis.reopen names unknown phase "${h}"`,`phases are: ${oe(i)}`,l));return m}}]}function Ae(e){return [{id:L,name:"Work",entryPolicy:[{kind:"dependencies-done"}],exitPolicy:[]},{id:V,name:"Review",entryPolicy:[],exitPolicy:[{kind:"no-open-blockers"}],review:true},{id:H,name:"Done",entryPolicy:[],exitPolicy:[]}]}var tt={backlog:"Requirements Baseline",item:"Work Package",stage:"Step",iteration:"Phase",increment:"Deliverable",ceremony:"Review",gate:"Phase Gate"};function nt(e,t){let n=q(e,t);if(n!==void 0)return w(e).phases.find(a=>a.id===n)?.deliverBy}function it(e){return {phases:b(e).map(n=>{let a=P(e,n.id),p=a.filter(s=>s.status==="done").length,o=w(e).traceability.to.includes(n.id)?J(e,n.id):[],d=n.id===B(e)&&o.length===0?["traceability-matrix"]:[],i=U(e,n,d);return {id:n.id,name:n.name,status:n.status,items:a.length,done:p,missingDeliverables:i,missingTraces:o,readyForGate:n.status==="open"&&p===a.length&&i.length===0&&o.length===0}}),current:he(e)?.id??null,open:D(e)?.id??null,pendingGates:e.pending.filter(n=>n.kind==="gate"&&n.item===void 0&&n.gate!==void 0).map(n=>({pending:n.id,gate:n.gate}))}}function rt(){return {name:"waterfall",vocabulary:tt,validateConfig:ge,defaultStages:Ae,defaultRoles:we,requiredCapabilities:["facilitate","control-change","approve-gate","deliver","verify"],exclusiveCapabilities:[],plannerOptions(e){let t={schedulerMode:"level",roleFor:a=>a.status==="todo"&&a.type!=="question"?nt(e,a):void 0},n=w(e).fallbackTokensPerWeight;return n!==void 0&&(t.fallbackTokensPerWeight=n),t},candidates(e){let t=D(e);return t?Object.values(e.items).filter(n=>(n.status==="todo"||n.status==="review")&&(n.stage===L||n.stage===V)&&n.type!=="change-request"&&q(e,n)===t.id):[]},invariants(e,t){let n=w(e),a=b(e),p=q(e,t),c=p===void 0?void 0:a[E(e,p)],o=a.filter(i=>i.status==="baselined").map(i=>i.id),d=c?.gate.requires.includes("human");return [c?`Phase "${c.name}" (${E(e,c.id)+1}/${a.length}); deliverables: ${c.deliverables.join(", ")||"(none)"}; gate "${c.gate.id}"${d?" needs human approval":""}`:"This item belongs to no phase; it is dispatched only through its parent's phase",`Baselined phases are frozen: ${o.join(", ")||"(none yet)"}; to change their items, raise a change-request with an impact analysis`,n.traceability.to.length?`Traceability: every item of phase "${n.traceability.from}" must trace to an item in ${n.traceability.to.join(", ")} (set traces on either side)`:"Traceability: none configured",`Do not change the scope of "${t.id}" or its acceptance criteria; raise open_questions instead`]},ceremonies:be(rt),rules:We(),metrics:e=>({...ke(e)}),humanDefaults:{gates:"all"},lockedConfigKeys:["phases","traceability","humanGates"],report:e=>({...it(e),coverage:O(e).coverage}),afterDecide:ve,afterComplete(e,t,n){let a=R$1(e),p=D(e);if(!a||!p||a.committed.includes(t))return e;let c=e.items[t];if(!c||q(e,c)!==p.id)return e;let o=e.accounting[e.accounting.length-1];return !o||o.item!==t?e:{...e,iterations:e.iterations.map(d=>d.id===a.id?{...d,committed:[...d.committed,t],spent:N(d.spent,o)}:d)}}}}export{K as A,O as B,J as C,Y as D,be as E,ve as F,ke as G,we as H,We as I,Ae as J,tt as K,nt as L,it as M,rt as N,De as a,pe as b,fe as c,ue as d,me as e,Me as f,w as g,ge as h,L as i,V as j,H as k,b as l,j as m,E as n,_ as o,q as p,P as q,D as r,he as s,Je as t,_e as u,U as v,B as w,ae as x,ye as y,z};//# sourceMappingURL=chunk-3KFQPSRX.mjs.map
2
+ //# sourceMappingURL=chunk-3KFQPSRX.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/waterfall/config.ts","../src/waterfall/phases.ts","../src/waterfall/baseline.ts","../src/waterfall/change.ts","../src/waterfall/retro.ts","../src/waterfall/traceability.ts","../src/waterfall/ceremonies.ts","../src/waterfall/metrics.ts","../src/waterfall/roles.ts","../src/waterfall/rules.ts","../src/waterfall/stages.ts","../src/waterfall/index.ts"],"names":["DEFAULT_PHASE_IDS","DEFAULT_DELIVERABLES","DEFAULT_DELIVER_BY","GATE_ID","id","CHANGE_GATE","CAPABILITIES","title","defaultPhases","p","by","configOf","state","isObj","x","strings","s","budget","raw","where","fail","out","k","v","requirements","q","phase","i","human","assertId","deliverables","gate","g","evidence","b","validateWaterfallConfig","c","hg","phases","ids","dupe","cc","changeControl","tr","traceability","to","t","fallback","WORK","REVIEW","DONE","phasesOf","ph","withPhases","phaseIndex","idx","getPhase","phaseOf","item","seen","cur","itemsInPhase","phaseId","openPhase","currentPhase","isFrozen","producedKinds","kinds","it","e","missingDeliverables","extra","have","wanted","lastToPhase","order","closeIteration","prefix","outcome","now","openIteration","baselinePhase","approvedBy","items","itemSnapshot","earlier","baseline","appendEvent","reopenPhases","reopened","suspended","earliest","open","approveChange","changeId","note","cr","getItem","ia","r","moveItem","rejectChange","phaseRetrospective","methodology","input","requireCap","wantPhase","parsed","parseLessonInput","applyAction","s0","nowOf","applyLessonInput","byId","a","artefacts","timSort","linked","traceabilityMatrix","cfg","rows","f","links","missing","m","missingTraces","toPhase","ceremony","recordDeliverable","kind","ref","waterfallCeremonies","act","type","reduce","version","ZERO_SPENT","approvers","approverIds","already","given","d","raisePending","pending","decision","canDo","rolesWith","needsHuman","waterfallAfterDecide","entry","reviewer","waterfallMetrics","zero","total","done","planned","spent","defects","typeOf","status","changeRequests","approved","rejected","reworkWeight","phasesReopened","counted","ev","was","completion","variance","n","traced","reqTotal","decided","waterfallRoles","config","gates","rule","message","fix","payloadOf","phaseArg","phaseById","phaseIds","itemById","phaseOfNew","parent","governed","frozenFix","changeOf","impactShape","waterfallRules","patch","approve","mine","authorOf","others","added","traces","isCr","ok","target","waterfallStages","_config","WATERFALL_VOCABULARY","deliverRoleFor","phaseReport","waterfall","po","frozen","itemId","_now","acc","addSpent"],"mappings":"2OAsBO,IAAMA,GAAuC,CAClD,cAAA,CACA,SACA,gBAAA,CACA,cAAA,CACA,aACA,aACF,CAAA,CACaC,GAAiD,CAC5D,YAAA,CAAc,CAAC,KAAK,CAAA,CACpB,OAAQ,CAAC,YAAA,CAAc,gBAAgB,CAAA,CACvC,cAAA,CAAgB,CAAC,eAAe,CAAA,CAChC,aAAc,CAAC,aAAA,CAAe,qBAAqB,CAAA,CACnD,UAAA,CAAY,CAAC,eAAA,CAAiB,mBAAmB,EACjD,WAAA,CAAa,CAAC,YAAY,CAC5B,CAAA,CACaC,GAA6C,CACxD,YAAA,CAAc,mBACd,MAAA,CAAQ,WAAA,CACR,UAAA,CAAY,iBACd,EACaC,EAAAA,CAAWC,CAAAA,EAAuB,GAAGA,CAAE,CAAA,KAAA,CAAA,CACvCC,GAAc,gBAAA,CACdC,EAAAA,CAAkC,CAC7C,eAAA,CACA,mBAAA,CACA,aACA,SAAA,CACA,QAAA,CACA,SACA,cAAA,CACA,aAAA,CACA,iBACA,UACF,CAAA,CAEMC,GAASH,CAAAA,EAAeA,CAAAA,CAAG,OAAO,CAAC,CAAA,CAAE,aAAY,CAAIA,CAAAA,CAAG,MAAM,CAAC,EAE9D,SAASI,EAAAA,EAAwC,CACtD,OAAOR,EAAAA,CAAkB,GAAA,CAAKI,GAAO,CACnC,IAAMK,EAA0B,CAC9B,EAAA,CAAAL,CAAAA,CACA,IAAA,CAAMG,GAAMH,CAAE,CAAA,CACd,aAAc,CAAC,GAAIH,GAAqBG,CAAE,CAAA,EAAK,EAAG,CAAA,CAClD,KAAM,CACJ,EAAA,CAAID,GAAQC,CAAE,CAAA,CACd,SAAU,CAAC,CAAE,WAAY,cAAe,CAAC,EACzC,QAAA,CAAU,GACV,MAAA,CAAQ,CAAE,OAAQ,OAAQ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AA,CAC1F,WAAA,CAAawI,EAAAA,CACb,aAAA,CAAcxI,EAAOsM,CAAAA,CAAQC,CAAAA,CAAM,CAEjC,IAAM/I,CAAAA,CAAKY,IAAcpE,CAAK,CAAA,CACxBgF,EAAO7B,CAAAA,CAAUnD,CAAK,EAC5B,GAAI,CAACwD,GAAM,CAACwB,CAAAA,EAAQxB,EAAG,SAAA,CAAU,QAAA,CAAS8I,CAAM,CAAA,CAAG,OAAOtM,EAC1D,IAAM8C,CAAAA,CAAO9C,EAAM,KAAA,CAAMsM,CAAM,EAC/B,GAAI,CAACxJ,GAAQD,CAAAA,CAAQ7C,CAAAA,CAAO8C,CAAI,CAAA,GAAMkC,CAAAA,CAAK,GAAI,OAAOhF,CAAAA,CACtD,IAAMwM,CAAAA,CAAMxM,CAAAA,CAAM,WAAWA,CAAAA,CAAM,UAAA,CAAW,OAAS,CAAC,CAAA,CACxD,OAAI,CAACwM,CAAAA,EAAOA,EAAI,IAAA,GAASF,CAAAA,CAAetM,EACjC,CACL,GAAGA,EACH,UAAA,CAAYA,CAAAA,CAAM,WAAW,GAAA,CAAKE,CAAAA,EAChCA,EAAE,EAAA,GAAOsD,CAAAA,CAAG,GACR,CAAE,GAAGtD,EAAG,SAAA,CAAW,CAAC,GAAGA,CAAAA,CAAE,SAAA,CAAWoM,CAAM,CAAA,CAAG,KAAA,CAAOG,EAASvM,CAAAA,CAAE,KAAA,CAAOsM,CAAG,CAAE,CAAA,CAC3EtM,CACN,CACF,CACF,CACF,CACF","file":"chunk-3KFQPSRX.mjs","sourcesContent":["import { assertId, fail } from \"../errors.ts\";\nimport type { Budget, Gate, GateRequirement, WorkflowState } from \"../types.ts\";\n\nexport interface WaterfallPhaseConfig {\n id: string;\n name: string;\n deliverables: string[];\n gate: Gate;\n budget?: Budget;\n /** role id that delivers this phase's items; default: the first role with \"deliver\" */\n deliverBy?: string;\n}\nexport interface WaterfallConfig {\n phases: WaterfallPhaseConfig[];\n changeControl: { requiresImpactAnalysis: boolean; approvers: GateRequirement[] };\n /** phase ids: every item of `from` must trace to an item of each `to` phase before that phase's gate */\n traceability: { from: string; to: string[] };\n humanGates: \"all\" | string[];\n /** tokens per weight unit when there is no accounting history (default 20000, as Scrum) */\n fallbackTokensPerWeight?: number;\n}\n\nexport const DEFAULT_PHASE_IDS: readonly string[] = [\n \"requirements\",\n \"design\",\n \"implementation\",\n \"verification\",\n \"deployment\",\n \"maintenance\",\n];\nexport const DEFAULT_DELIVERABLES: Record<string, string[]> = {\n requirements: [\"srs\"],\n design: [\"design-doc\", \"interface-spec\"],\n implementation: [\"code-baseline\"],\n verification: [\"test-report\", \"traceability-matrix\"],\n deployment: [\"release-notes\", \"deployment-record\"],\n maintenance: [\"change-log\"],\n};\nexport const DEFAULT_DELIVER_BY: Record<string, string> = {\n requirements: \"business-analyst\",\n design: \"architect\",\n deployment: \"release-manager\",\n};\nexport const GATE_ID = (id: string): string => `${id}-gate`;\nexport const CHANGE_GATE = \"change-control\";\nexport const CAPABILITIES: readonly string[] = [\n \"order-backlog\",\n \"define-acceptance\",\n \"facilitate\",\n \"deliver\",\n \"review\",\n \"verify\",\n \"approve-gate\",\n \"manage-flow\",\n \"control-change\",\n \"escalate\",\n];\n\nconst title = (id: string) => id.charAt(0).toUpperCase() + id.slice(1);\n\nexport function defaultPhases(): WaterfallPhaseConfig[] {\n return DEFAULT_PHASE_IDS.map((id) => {\n const p: WaterfallPhaseConfig = {\n id,\n name: title(id),\n deliverables: [...(DEFAULT_DELIVERABLES[id] ?? [])],\n gate: {\n id: GATE_ID(id),\n requires: [{ capability: \"approve-gate\" }],\n evidence: [],\n onFail: { action: \"block\" },\n },\n };\n const by = DEFAULT_DELIVER_BY[id];\n if (by !== undefined) p.deliverBy = by;\n return p;\n });\n}\n\nexport function configOf(state: WorkflowState): WaterfallConfig {\n return state.config as WaterfallConfig;\n}\n\nconst isObj = (x: unknown): x is Record<string, unknown> =>\n typeof x === \"object\" && x !== null && !Array.isArray(x);\nconst strings = (x: unknown): x is string[] =>\n Array.isArray(x) && x.every((s) => typeof s === \"string\" && s.trim() !== \"\");\n\nfunction budget(raw: unknown, where: string): Budget | undefined {\n if (raw === undefined) return undefined;\n if (!isObj(raw))\n fail(\"config-invalid\", `${where}.budget must be an object`, 'e.g. { \"tokens\": 400000 }');\n const out: Budget = {};\n for (const k of [\"tokens\", \"turns\", \"wallclockMs\"] as const) {\n const v = raw[k];\n if (v === undefined) continue;\n if (typeof v !== \"number\" || !Number.isFinite(v) || v < 0)\n fail(\n \"config-invalid\",\n `${where}.budget.${k} must be a non-negative number`,\n \"omit it for no limit\",\n );\n out[k] = v;\n }\n return out;\n}\n\nfunction requirements(raw: unknown, where: string): GateRequirement[] {\n if (!Array.isArray(raw) || raw.length === 0)\n fail(\n \"config-invalid\",\n `${where} must be a non-empty array of \"human\" | { capability }`,\n 'e.g. [\"human\", { \"capability\": \"approve-gate\" }]',\n );\n return raw.map((q: unknown): GateRequirement => {\n if (q === \"human\") return \"human\";\n if (isObj(q) && typeof q[\"capability\"] === \"string\" && CAPABILITIES.includes(q[\"capability\"]))\n return { capability: q[\"capability\"] };\n return fail(\n \"config-invalid\",\n `${where} entry ${JSON.stringify(q)} is not \"human\" or a known capability`,\n `use \"human\" or { \"capability\": one of ${CAPABILITIES.join(\", \")} }`,\n );\n });\n}\n\nfunction phase(raw: unknown, i: number, human: (id: string) => boolean): WaterfallPhaseConfig {\n const where = `waterfall config.phases[${i}]`;\n if (!isObj(raw)) fail(\"config-invalid\", `${where} must be an object`, 'e.g. { \"id\": \"design\" }');\n assertId(raw[\"id\"], `${where}.id`);\n const id = raw[\"id\"] as string;\n const deliverables = raw[\"deliverables\"] ?? DEFAULT_DELIVERABLES[id] ?? [];\n if (!strings(deliverables))\n fail(\n \"config-invalid\",\n `${where}.deliverables must be a string[] of evidence kinds`,\n 'e.g. [\"srs\"]',\n );\n let gate: Gate;\n if (raw[\"gate\"] === undefined) {\n gate = {\n id: GATE_ID(id),\n requires: [{ capability: \"approve-gate\" }],\n evidence: [],\n onFail: { action: \"block\" },\n };\n } else {\n const g = raw[\"gate\"];\n if (!isObj(g) || typeof g[\"id\"] !== \"string\" || g[\"id\"].trim() === \"\")\n fail(\n \"config-invalid\",\n `${where}.gate must be a Gate with an id`,\n 'e.g. { \"id\": \"design-gate\", \"requires\": [{ \"capability\": \"approve-gate\" }], \"evidence\": [] }',\n );\n const evidence = g[\"evidence\"] ?? [];\n if (!strings(evidence))\n fail(\n \"config-invalid\",\n `${where}.gate.evidence must be a string[]`,\n \"list evidence kinds or omit it\",\n );\n gate = {\n id: g[\"id\"],\n requires: requirements(\n g[\"requires\"] ?? [{ capability: \"approve-gate\" }],\n `${where}.gate.requires`,\n ),\n evidence: [...evidence],\n onFail: { action: \"block\" },\n };\n }\n if (human(id) && !gate.requires.includes(\"human\")) gate.requires = [\"human\", ...gate.requires];\n const out: WaterfallPhaseConfig = {\n id,\n name: typeof raw[\"name\"] === \"string\" && raw[\"name\"].trim() !== \"\" ? raw[\"name\"] : title(id),\n deliverables: [...deliverables],\n gate,\n };\n const b = budget(raw[\"budget\"], where);\n if (b !== undefined) out.budget = b;\n const by = raw[\"deliverBy\"] ?? DEFAULT_DELIVER_BY[id];\n if (by !== undefined) {\n if (typeof by !== \"string\" || by.trim() === \"\")\n fail(\n \"config-invalid\",\n `${where}.deliverBy must be a role id`,\n \"name the role that delivers this phase or omit it\",\n );\n out.deliverBy = by;\n }\n return out;\n}\n\nexport function validateWaterfallConfig(raw: unknown): WaterfallConfig {\n const c = (raw ?? {}) as Record<string, unknown>;\n if (c[\"phases\"] !== undefined && !Array.isArray(c[\"phases\"]))\n fail(\n \"config-invalid\",\n \"waterfall config.phases must be an array of phases\",\n \"omit phases for the six classic phases\",\n );\n const hg = c[\"humanGates\"] ?? \"all\";\n if (hg !== \"all\" && !strings(hg))\n fail(\n \"config-invalid\",\n 'waterfall config.humanGates must be \"all\" or a string[] of phase ids',\n 'omit it for \"all\"',\n );\n const human = hg === \"all\" ? () => true : (id: string) => (hg as string[]).includes(id);\n const phases =\n c[\"phases\"] === undefined\n ? defaultPhases().map((p, i) => phase(p, i, human))\n : (c[\"phases\"] as unknown[]).map((p, i) => phase(p, i, human));\n if (phases.length === 0)\n fail(\n \"config-invalid\",\n \"waterfall config.phases needs at least one phase\",\n 'e.g. [{ \"id\": \"requirements\" }]',\n );\n const ids = phases.map((p) => p.id);\n const dupe = ids.find((id, i) => ids.indexOf(id) !== i);\n if (dupe !== undefined)\n fail(\"config-invalid\", `duplicate phase id \"${dupe}\"`, \"give every phase a unique id\");\n if (hg !== \"all\")\n for (const id of hg as string[])\n if (!ids.includes(id))\n fail(\n \"config-invalid\",\n `waterfall config.humanGates names unknown phase \"${id}\"`,\n `phases are: ${ids.join(\", \")}`,\n );\n const cc = c[\"changeControl\"] ?? {};\n if (!isObj(cc))\n fail(\n \"config-invalid\",\n \"waterfall config.changeControl must be an object\",\n 'e.g. { \"requiresImpactAnalysis\": true, \"approvers\": [\"human\"] }',\n );\n if (\n cc[\"requiresImpactAnalysis\"] !== undefined &&\n typeof cc[\"requiresImpactAnalysis\"] !== \"boolean\"\n )\n fail(\n \"config-invalid\",\n \"waterfall config.changeControl.requiresImpactAnalysis must be a boolean\",\n \"omit it for true\",\n );\n const changeControl: WaterfallConfig[\"changeControl\"] = {\n requiresImpactAnalysis:\n cc[\"requiresImpactAnalysis\"] === undefined ? true : (cc[\"requiresImpactAnalysis\"] as boolean),\n approvers: requirements(\n cc[\"approvers\"] ?? [\"human\", { capability: \"control-change\" }],\n \"waterfall config.changeControl.approvers\",\n ),\n };\n const tr = c[\"traceability\"];\n let traceability: WaterfallConfig[\"traceability\"];\n if (tr === undefined) {\n traceability =\n ids.includes(\"requirements\") && ids.includes(\"design\") && ids.includes(\"verification\")\n ? { from: \"requirements\", to: [\"design\", \"verification\"] }\n : { from: ids[0]!, to: [] };\n } else {\n if (!isObj(tr) || typeof tr[\"from\"] !== \"string\" || !ids.includes(tr[\"from\"]))\n fail(\n \"config-invalid\",\n \"waterfall config.traceability.from must be a phase id\",\n `phases are: ${ids.join(\", \")}`,\n );\n const to = tr[\"to\"] ?? [];\n if (!strings(to))\n fail(\n \"config-invalid\",\n \"waterfall config.traceability.to must be a string[] of phase ids\",\n `phases are: ${ids.join(\", \")}`,\n );\n for (const t of to) {\n if (!ids.includes(t))\n fail(\n \"config-invalid\",\n `waterfall config.traceability.to names unknown phase \"${t}\"`,\n `phases are: ${ids.join(\", \")}`,\n );\n if (ids.indexOf(t) <= ids.indexOf(tr[\"from\"]))\n fail(\n \"config-invalid\",\n `waterfall config.traceability.to phase \"${t}\" must come after \"${tr[\"from\"]}\"`,\n \"trace forward only: from an earlier phase to later ones\",\n );\n }\n traceability = { from: tr[\"from\"], to: [...to] };\n }\n const fallback = c[\"fallbackTokensPerWeight\"];\n if (\n fallback !== undefined &&\n (typeof fallback !== \"number\" || !Number.isFinite(fallback) || fallback <= 0)\n )\n fail(\n \"config-invalid\",\n \"waterfall config.fallbackTokensPerWeight must be a positive finite number\",\n \"omit it for the default 20000\",\n );\n const out: WaterfallConfig = {\n phases,\n changeControl,\n traceability,\n humanGates: hg === \"all\" ? \"all\" : [...(hg as string[])],\n };\n if (fallback !== undefined) out.fallbackTokensPerWeight = fallback;\n return out;\n}\n","import { fail } from \"../errors.ts\";\nimport type { Phase, WorkItem, WorkflowState } from \"../types.ts\";\nimport { configOf } from \"./config.ts\";\n\nexport const WORK = \"work\";\nexport const REVIEW = \"review\";\nexport const DONE = \"done\";\n\n/** state.phases, or the config phases as pending (before the first ceremony touches them). */\nexport function phasesOf(state: WorkflowState): Phase[] {\n if (state.phases) return state.phases;\n return configOf(state).phases.map((p) => {\n const ph: Phase = {\n id: p.id,\n name: p.name,\n deliverables: [...p.deliverables],\n gate: p.gate,\n status: \"pending\",\n };\n if (p.budget) ph.budget = p.budget;\n return ph;\n });\n}\n\nexport function withPhases(state: WorkflowState, phases: Phase[]): WorkflowState {\n return { ...state, phases };\n}\n\nexport function phaseIndex(state: WorkflowState, id: string): number {\n const idx = phasesOf(state).findIndex((p) => p.id === id);\n if (idx < 0)\n fail(\n \"config-invalid\",\n `unknown phase \"${id}\"`,\n `phases are: ${phasesOf(state)\n .map((p) => p.id)\n .join(\" → \")}`,\n );\n return idx;\n}\n\nexport function getPhase(state: WorkflowState, id: string): Phase {\n return phasesOf(state)[phaseIndex(state, id)]!;\n}\n\n/** The item's phase, inherited from its parent chain (questions, follow-ups, retro items). */\nexport function phaseOf(state: WorkflowState, item: WorkItem): string | undefined {\n const seen = new Set<string>();\n let cur: WorkItem | undefined = item;\n while (cur && !seen.has(cur.id)) {\n if (cur.phase !== undefined) return cur.phase;\n seen.add(cur.id);\n cur =\n cur.parent !== undefined && Object.hasOwn(state.items, cur.parent)\n ? state.items[cur.parent]\n : undefined;\n }\n return undefined;\n}\n\nexport function itemsInPhase(state: WorkflowState, phaseId: string): WorkItem[] {\n return Object.values(state.items).filter(\n (i) => i.status !== \"dropped\" && phaseOf(state, i) === phaseId,\n );\n}\n\nexport function openPhase(state: WorkflowState): Phase | undefined {\n return phasesOf(state).find((p) => p.status === \"open\");\n}\n\n/** First phase in order that is not baselined: the one to kick off (or the open one). */\nexport function currentPhase(state: WorkflowState): Phase | undefined {\n return phasesOf(state).find((p) => p.status !== \"baselined\");\n}\n\nexport function isFrozen(state: WorkflowState, item: WorkItem): boolean {\n const id = phaseOf(state, item);\n return id !== undefined && phasesOf(state).find((p) => p.id === id)?.status === \"baselined\";\n}\n\nexport function producedKinds(state: WorkflowState, phase: Phase): Set<string> {\n const kinds = new Set<string>((phase.produced ?? []).map((p) => p.kind));\n for (const it of itemsInPhase(state, phase.id)) for (const e of it.evidence) kinds.add(e.kind);\n return kinds;\n}\n\n/** Deliverables (and gate evidence kinds) still missing, in declaration order. */\nexport function missingDeliverables(\n state: WorkflowState,\n phase: Phase,\n extra: string[] = [],\n): string[] {\n const have = producedKinds(state, phase);\n for (const k of extra) have.add(k);\n const wanted: string[] = [];\n for (const k of [...phase.deliverables, ...phase.gate.evidence])\n if (!wanted.includes(k)) wanted.push(k);\n return wanted.filter((k) => !have.has(k));\n}\n\n/** The traceability `to` phase that comes last in phase order (where the matrix must be complete). */\nexport function lastToPhase(state: WorkflowState): string | undefined {\n const order = phasesOf(state).map((p) => p.id);\n const to = configOf(state).traceability.to.filter((t) => order.includes(t));\n if (to.length === 0) return undefined;\n return to.reduce((a, b) => (order.indexOf(a) >= order.indexOf(b) ? a : b));\n}\n","import { fail } from \"../errors.ts\";\nimport { openIteration } from \"../planner.ts\";\nimport { appendEvent } from \"../state.ts\";\nimport type { Baseline, WorkItem, WorkflowState } from \"../types.ts\";\nimport { getPhase, itemsInPhase, phaseIndex, phasesOf, withPhases } from \"./phases.ts\";\n\nfunction closeIteration(\n state: WorkflowState,\n prefix: string,\n outcome: \"completed\" | \"cancelled\",\n now: string,\n): WorkflowState {\n const it = openIteration(state);\n if (!it || !it.id.startsWith(`${prefix}#`)) return state;\n return {\n ...state,\n iterations: state.iterations.map((x) => (x.id === it.id ? { ...x, endedAt: now, outcome } : x)),\n };\n}\n\n/** Pass the phase gate: freeze its items, record the baseline, close its iteration. */\nexport function baselinePhase(\n state: WorkflowState,\n phaseId: string,\n approvedBy: string[],\n now: string,\n): WorkflowState {\n const phase = getPhase(state, phaseId);\n if (phase.status !== \"open\")\n fail(\n \"invalid-transition\",\n `phase \"${phaseId}\" is ${phase.status}, not open`,\n phase.status === \"baselined\"\n ? \"it is already baselined; a change-request reopens it\"\n : \"kickoff the phase first\",\n );\n const items = itemsInPhase(state, phaseId);\n const itemSnapshot: Record<string, WorkItem> = {};\n for (const it of items) itemSnapshot[it.id] = it;\n const earlier = (state.baselines ?? []).filter((b) => b.phase === phaseId).length;\n const baseline: Baseline = {\n phase: phaseId,\n version: earlier + 1,\n at: now,\n approvedBy,\n itemSnapshot,\n };\n let s = withPhases(\n state,\n phasesOf(state).map((p) => (p.id === phaseId ? { ...p, status: \"baselined\" as const } : p)),\n );\n s = { ...s, baseline, baselines: [...(s.baselines ?? []), baseline] };\n s = closeIteration(s, phaseId, \"completed\", now);\n return appendEvent(\n s,\n \"phase.baselined\",\n approvedBy[approvedBy.length - 1] ?? \"system\",\n { phase: phaseId, version: baseline.version, approvedBy, items: items.map((i) => i.id) },\n now,\n );\n}\n\nexport interface ReopenResult {\n state: WorkflowState;\n reopened: string[];\n suspended: string | null;\n}\n\n/** Change-control approval: reopen the listed baselined phases; a later open phase is suspended until they are re-baselined. */\nexport function reopenPhases(state: WorkflowState, ids: string[], now: string): ReopenResult {\n const reopened: string[] = [];\n for (const id of ids) {\n const p = getPhase(state, id);\n if (p.status === \"pending\")\n fail(\n \"invalid-input\",\n `phase \"${id}\" was never baselined; there is nothing to reopen`,\n \"remove it from impactAnalysis.reopen\",\n );\n if (p.status === \"baselined\" && !reopened.includes(id)) reopened.push(id);\n }\n let phases = phasesOf(state).map((p) =>\n reopened.includes(p.id) ? { ...p, status: \"reopened\" as const } : p,\n );\n let suspended: string | null = null;\n let s = state;\n if (reopened.length) {\n const earliest = Math.min(...reopened.map((id) => phaseIndex(state, id)));\n const open = phases.find((p, i) => p.status === \"open\" && i > earliest);\n if (open) {\n suspended = open.id;\n phases = phases.map((p) => (p.id === open.id ? { ...p, status: \"reopened\" as const } : p));\n s = closeIteration(s, open.id, \"cancelled\", now);\n }\n }\n return { state: withPhases(s, phases), reopened, suspended };\n}\n","import { getItem, moveItem } from \"../items.ts\";\nimport { appendEvent } from \"../state.ts\";\nimport type { WorkflowState } from \"../types.ts\";\nimport { reopenPhases } from \"./baseline.ts\";\nimport { DONE } from \"./phases.ts\";\n\nexport function approveChange(\n state: WorkflowState,\n changeId: string,\n by: string,\n note: string,\n now: string,\n): WorkflowState {\n const cr = getItem(state, changeId);\n const ia = cr.impactAnalysis;\n const r = reopenPhases(state, ia?.reopen ?? [], now);\n let s = moveItem(r.state, changeId, { stage: DONE, status: \"done\" }, by, now);\n for (const phase of r.reopened)\n s = appendEvent(s, \"phase.reopened\", by, { phase, change: changeId }, now);\n if (r.suspended !== null)\n s = appendEvent(s, \"phase.suspended\", by, { phase: r.suspended, change: changeId }, now);\n return appendEvent(\n s,\n \"change.decided\",\n by,\n {\n change: changeId,\n decision: \"approve\",\n by,\n note,\n reopened: r.reopened,\n suspended: r.suspended,\n weight: ia?.weight ?? 0,\n affects: cr.affects ?? [],\n },\n now,\n );\n}\n\nexport function rejectChange(\n state: WorkflowState,\n changeId: string,\n by: string,\n note: string,\n now: string,\n): WorkflowState {\n const cr = getItem(state, changeId);\n const s = moveItem(state, changeId, { status: \"dropped\" }, by, now);\n return appendEvent(\n s,\n \"change.decided\",\n by,\n {\n change: changeId,\n decision: \"reject\",\n by,\n note,\n reopened: [],\n suspended: null,\n weight: 0,\n affects: cr.affects ?? [],\n },\n now,\n );\n}\n","import { applyLessonInput, parseLessonInput } from \"../lessons.ts\";\nimport { applyAction } from \"../methodology.ts\";\nimport { requireCap } from \"../roles.ts\";\nimport { appendEvent, nowOf } from \"../state.ts\";\nimport type { Ceremony, Methodology } from \"../types.ts\";\nimport { wantPhase } from \"./ceremonies.ts\";\n\n/** Lessons, adoptions and agreements; never touches items, config or baselines. */\nexport function phaseRetrospective(methodology: () => Methodology): Ceremony {\n return (state, input) => {\n requireCap(state, input.by, \"facilitate\");\n const phase =\n input[\"phase\"] === undefined ? undefined : wantPhase(state, input, \"phaseRetrospective\");\n const parsed = parseLessonInput(state, input, \"phaseRetrospective\");\n return applyAction(\n state,\n methodology(),\n { type: \"ceremony.phaseRetrospective\", by: input.by, payload: input },\n (s0) => {\n let s = s0;\n const now = nowOf(input.now);\n const out = applyLessonInput(s, parsed, input.by, now);\n s = out.state;\n return appendEvent(\n s,\n \"phase.retrospective\",\n input.by,\n {\n phase: phase?.id ?? null,\n lessons: out.created,\n adopted: out.adopted.slice(out.created.length),\n dismissed: out.dismissed,\n agreements: out.agreements,\n retired: out.retired,\n },\n now,\n );\n },\n );\n };\n}\n","import { timSort } from \"exsorted\";\nimport type { WorkItem, WorkflowState } from \"../types.ts\";\nimport { configOf } from \"./config.ts\";\nimport { itemsInPhase, phasesOf } from \"./phases.ts\";\n\nexport interface TraceRow {\n item: string;\n /** to-phase id → ids of linked items in that phase */\n links: Record<string, string[]>;\n}\nexport interface TraceabilityMatrix {\n from: string;\n to: string[];\n rows: TraceRow[];\n missing: Array<{ item: string; phases: string[] }>;\n coverage: { traced: number; total: number };\n}\n\nconst byId = (a: WorkItem, b: WorkItem) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);\nconst artefacts = (state: WorkflowState, phase: string) =>\n timSort(\n itemsInPhase(state, phase).filter((i) => i.type !== \"question\" && i.type !== \"change-request\"),\n byId,\n );\n\n/** A link exists when either side's `traces` names the other. */\nconst linked = (a: WorkItem, b: WorkItem) =>\n (a.traces ?? []).includes(b.id) || (b.traces ?? []).includes(a.id);\n\nexport function traceabilityMatrix(state: WorkflowState): TraceabilityMatrix {\n const cfg = configOf(state).traceability;\n const order = phasesOf(state).map((p) => p.id);\n const to = cfg.to.filter((t) => order.includes(t));\n const rows: TraceRow[] = artefacts(state, cfg.from).map((f) => {\n const links: Record<string, string[]> = {};\n for (const t of to)\n links[t] = artefacts(state, t)\n .filter((x) => linked(f, x))\n .map((x) => x.id);\n return { item: f.id, links };\n });\n const missing = rows\n .map((r) => ({ item: r.item, phases: to.filter((t) => r.links[t]!.length === 0) }))\n .filter((m) => m.phases.length > 0);\n return {\n from: cfg.from,\n to,\n rows,\n missing,\n coverage: { traced: rows.length - missing.length, total: rows.length },\n };\n}\n\n/** Ids of `from` items with no link into `toPhase`. */\nexport function missingTraces(state: WorkflowState, toPhase: string): string[] {\n return traceabilityMatrix(state)\n .rows.filter((r) => (r.links[toPhase] ?? []).length === 0)\n .map((r) => r.item);\n}\n","import { ZERO_SPENT } from \"../budget.ts\";\nimport { fail } from \"../errors.ts\";\nimport { raisePending } from \"../gates.ts\";\nimport { applyAction } from \"../methodology.ts\";\nimport { getItem } from \"../items.ts\";\nimport { approverIds, canDo, requireCap, rolesWith } from \"../roles.ts\";\nimport { appendEvent, nowOf } from \"../state.ts\";\nimport type {\n Capability,\n Ceremony,\n CeremonyInput,\n Methodology,\n PendingHuman,\n Phase,\n WorkflowState,\n} from \"../types.ts\";\nimport { baselinePhase } from \"./baseline.ts\";\nimport { approveChange, rejectChange } from \"./change.ts\";\nimport { configOf } from \"./config.ts\";\nimport { getPhase, itemsInPhase, lastToPhase, phasesOf, withPhases } from \"./phases.ts\";\nimport { phaseRetrospective } from \"./retro.ts\";\nimport { traceabilityMatrix } from \"./traceability.ts\";\n\nconst isObj = (x: unknown): x is Record<string, unknown> =>\n typeof x === \"object\" && x !== null && !Array.isArray(x);\n\n/** input.phase as an existing phase. */\nexport function wantPhase(state: WorkflowState, input: CeremonyInput, ceremony: string): Phase {\n const id = input[\"phase\"];\n if (typeof id !== \"string\" || id.trim() === \"\")\n fail(\n \"invalid-input\",\n `${ceremony} needs phase: string`,\n `pass one of: ${phasesOf(state)\n .map((p) => p.id)\n .join(\", \")}`,\n );\n return getPhase(state, id);\n}\n\n/** Append a deliverable to the phase and record it. */\nfunction recordDeliverable(\n state: WorkflowState,\n phaseId: string,\n kind: string,\n ref: string,\n by: string,\n now: string,\n): WorkflowState {\n const s = withPhases(\n state,\n phasesOf(state).map((p) =>\n p.id === phaseId\n ? { ...p, produced: [...(p.produced ?? []), { kind, ref, by, at: now }] }\n : p,\n ),\n );\n return appendEvent(s, \"phase.deliverable\", by, { phase: phaseId, kind, ref }, now);\n}\n\nexport { approveChange, rejectChange } from \"./change.ts\";\n\nexport function waterfallCeremonies(methodology: () => Methodology): Record<string, Ceremony> {\n const act = (\n state: WorkflowState,\n type: string,\n input: CeremonyInput,\n reduce: (s: WorkflowState, now: string) => WorkflowState,\n ) =>\n applyAction(state, methodology(), { type, by: input.by, payload: input }, (s) =>\n reduce(s, nowOf(input.now)),\n );\n\n const kickoff: Ceremony = (state, input) => {\n requireCap(state, input.by, \"facilitate\");\n const phase = wantPhase(state, input, \"kickoff\");\n return act(state, \"ceremony.kickoff\", input, (s, now) => {\n const version =\n s.events.filter(\n (e) => e.type === \"phase.opened\" && (e.payload as { phase: string }).phase === phase.id,\n ).length + 1;\n const items = itemsInPhase(s, phase.id)\n .filter((i) => i.status !== \"done\")\n .map((i) => i.id);\n s = withPhases(\n s,\n phasesOf(s).map((p) => (p.id === phase.id ? { ...p, status: \"open\" as const } : p)),\n );\n const budget = phase.budget ?? {};\n s = {\n ...s,\n iterations: [\n ...s.iterations,\n {\n id: `${phase.id}#${version}`,\n goal: phase.name,\n budget,\n spent: ZERO_SPENT,\n startedAt: now,\n committed: items,\n carryover: [],\n },\n ],\n };\n return appendEvent(\n s,\n \"phase.opened\",\n input.by,\n { phase: phase.id, version, items, budget },\n now,\n );\n });\n };\n\n const gateReview: Ceremony = (state, input) => {\n const phase = wantPhase(state, input, \"gateReview\");\n if (phase.status !== \"open\")\n fail(\n \"invalid-transition\",\n `phase \"${phase.id}\" is ${phase.status}, not open`,\n phase.status === \"baselined\"\n ? \"it is already baselined; a change-request reopens it\"\n : `kickoff \"${phase.id}\" first`,\n );\n const gate = phase.gate;\n const approvers = approverIds(state, gate.id, \"approve-gate\");\n if (input.by !== \"human\" && !approvers.includes(input.by))\n fail(\n \"gate-unmet\",\n `\"${input.by}\" may not review gate \"${gate.id}\"`,\n `review as one of: human${approvers.map((r) => `, ${r}`).join(\"\")}`,\n { rule: \"gate\" },\n );\n const already = state.pending.find(\n (p) => p.kind === \"gate\" && p.item === undefined && p.gate === gate.id,\n );\n if (already)\n fail(\n \"no-op\",\n `gate \"${gate.id}\" is already awaiting a decision (${already.id})`,\n `decide ${already.id} approve|reject`,\n );\n const given = input[\"deliverables\"] ?? [];\n if (\n !Array.isArray(given) ||\n !given.every(\n (d) =>\n isObj(d) &&\n typeof d[\"kind\"] === \"string\" &&\n d[\"kind\"].trim() !== \"\" &&\n typeof d[\"ref\"] === \"string\",\n )\n )\n fail(\n \"invalid-input\",\n \"gateReview.deliverables must be [{ kind, ref }]\",\n 'e.g. { \"deliverables\": [{ \"kind\": \"srs\", \"ref\": \"docs/srs.md\" }] }',\n );\n const deliverables = given as Array<{ kind: string; ref: string }>;\n return act(state, \"ceremony.gateReview\", input, (s, now) => {\n for (const d of deliverables)\n s = recordDeliverable(s, phase.id, d.kind, d.ref, input.by, now);\n if (configOf(s).traceability.to.includes(phase.id)) {\n const m = traceabilityMatrix(s);\n s = appendEvent(\n s,\n \"traceability.computed\",\n input.by,\n {\n phase: phase.id,\n from: m.from,\n to: m.to,\n coverage: m.coverage,\n missing: m.missing,\n rows: m.rows,\n },\n now,\n );\n if (phase.id === lastToPhase(s) && m.missing.length === 0)\n s = recordDeliverable(\n s,\n phase.id,\n \"traceability-matrix\",\n `traceability.computed#${s.events[s.events.length - 1]!.seq}`,\n input.by,\n now,\n );\n }\n if (gate.requires.includes(\"human\") && input.by !== \"human\") {\n s = raisePending(\n s,\n {\n kind: \"gate\",\n gate: gate.id,\n question: `Approve gate \"${gate.id}\" and baseline phase \"${phase.name}\"?`,\n },\n now,\n );\n const pending = s.pending[s.pending.length - 1]!.id;\n return appendEvent(\n s,\n \"phase.gate-pending\",\n input.by,\n { phase: phase.id, gate: gate.id, by: input.by, pending },\n now,\n );\n }\n return baselinePhase(s, phase.id, [input.by], now);\n });\n };\n\n const changeControlBoard: Ceremony = (state, input) => {\n requireCap(state, input.by, \"control-change\");\n const id = input[\"change\"];\n if (typeof id !== \"string\" || id.trim() === \"\")\n fail(\n \"invalid-input\",\n \"changeControlBoard needs change: string (a change-request id)\",\n 'e.g. { \"change\": \"CR-1\", \"decision\": \"approve\", \"note\": \"why\" }',\n );\n const cr = getItem(state, id);\n if (cr.type !== \"change-request\")\n fail(\n \"invalid-input\",\n `item \"${id}\" is a ${cr.type}, not a change-request`,\n \"only change-request items go through the board\",\n { items: [id] },\n );\n if (cr.status === \"done\" || cr.status === \"dropped\")\n fail(\n \"invalid-transition\",\n `change \"${id}\" is already ${cr.status === \"done\" ? \"approved\" : \"rejected\"}`,\n \"raise a new change-request\",\n { items: [id] },\n );\n if (cr.status === \"awaiting_human\") {\n const p = state.pending.find((x) => x.item === id);\n fail(\n \"no-op\",\n `change \"${id}\" is awaiting the human decision${p ? ` (${p.id})` : \"\"}`,\n `decide ${p?.id ?? \"<pending id>\"} approve|reject`,\n { items: [id] },\n );\n }\n const decision = input[\"decision\"];\n if (decision !== \"approve\" && decision !== \"reject\")\n fail(\n \"invalid-input\",\n 'changeControlBoard.decision must be \"approve\" or \"reject\"',\n \"state the board's decision\",\n );\n const note = typeof input[\"note\"] === \"string\" ? input[\"note\"] : \"\";\n const approvers = configOf(state).changeControl.approvers;\n for (const q of approvers) {\n if (\n q === \"human\" ||\n input.by === \"human\" ||\n canDo(state, input.by, q.capability as Capability)\n )\n continue;\n fail(\n \"gate-unmet\",\n `\"${input.by}\" lacks capability \"${q.capability}\" required by change control`,\n `decide as one of: human${rolesWith(state, q.capability as Capability)\n .map((r) => `, ${r.id}`)\n .join(\"\")}`,\n { rule: \"change-control\", items: [id] },\n );\n }\n const needsHuman = approvers.includes(\"human\") && input.by !== \"human\";\n return act(state, \"ceremony.changeControlBoard\", input, (s, now) => {\n if (needsHuman) {\n s = raisePending(\n s,\n {\n kind: \"decision\",\n item: id,\n question: `Change \"${id}\" (${cr.title}): the board (${input.by}) recommends ${decision}${note ? `: ${note}` : \"\"}. Approve or reject the change?`,\n },\n now,\n );\n const pending = s.pending[s.pending.length - 1]!.id;\n return appendEvent(\n s,\n \"change.recommended\",\n input.by,\n { change: id, decision, note, pending },\n now,\n );\n }\n return decision === \"approve\"\n ? approveChange(s, id, input.by, note, now)\n : rejectChange(s, id, input.by, note, now);\n });\n };\n\n return {\n kickoff,\n gateReview,\n changeControlBoard,\n phaseRetrospective: phaseRetrospective(methodology),\n };\n}\n\n/** decide() hook: a phase gate's human decision baselines the phase or records the failure. */\nexport function waterfallAfterDecide(\n state: WorkflowState,\n entry: PendingHuman,\n decision: \"approve\" | \"reject\",\n by: string,\n note: string,\n now: string,\n): WorkflowState {\n if (entry.kind === \"gate\" && entry.item === undefined && entry.gate !== undefined) {\n const phase = phasesOf(state).find((p) => p.gate.id === entry.gate);\n if (!phase) return state;\n // core decide() checks the decider only for item gates; a phase gate pending exists because the gate requires a human\n if (by !== \"human\")\n fail(\n \"gate-unmet\",\n `\"${by}\" may not decide phase gate \"${entry.gate}\" (${entry.id}); it awaits a human`,\n `decide ${entry.id} as human`,\n { rule: \"gate\" },\n );\n let reviewer: string | undefined;\n for (let i = state.events.length - 1; i >= 0; i--) {\n const e = state.events[i]!;\n if (\n e.type === \"phase.gate-pending\" &&\n (e.payload as { pending: string }).pending === entry.id\n ) {\n reviewer = e.by;\n break;\n }\n }\n const approvedBy = reviewer !== undefined && reviewer !== by ? [reviewer, by] : [by];\n if (decision === \"approve\") return baselinePhase(state, phase.id, approvedBy, now);\n return appendEvent(\n state,\n \"phase.gate-failed\",\n by,\n { phase: phase.id, gate: entry.gate, note },\n now,\n );\n }\n if (\n entry.kind === \"decision\" &&\n entry.item !== undefined &&\n Object.hasOwn(state.items, entry.item)\n ) {\n const item = state.items[entry.item]!;\n if (item.type !== \"change-request\") return state;\n if (by !== \"human\")\n fail(\n \"gate-unmet\",\n `\"${by}\" may not decide change \"${item.id}\" (${entry.id}); change control awaits a human`,\n `decide ${entry.id} as human`,\n { rule: \"change-control\", items: [item.id] },\n );\n return decision === \"approve\"\n ? approveChange(state, item.id, by, note, now)\n : rejectChange(state, item.id, by, note, now);\n }\n return state;\n}\n","import type { WorkflowState } from \"../types.ts\";\nimport { configOf } from \"./config.ts\";\nimport { traceabilityMatrix } from \"./traceability.ts\";\n\nexport interface WaterfallMetrics {\n phaseCompletion: Record<string, number>;\n budgetPlanned: Record<string, number>;\n budgetSpent: Record<string, number>;\n scheduleVariance: Record<string, number>;\n requirementCoverage: number;\n requirementsTraced: number;\n requirementsTotal: number;\n defectsPerPhase: Record<string, number>;\n changeRequests: number;\n changesApproved: number;\n changesRejected: number;\n changeApprovalRate: number;\n reworkWeight: number;\n phasesReopened: number;\n}\n\ntype Added = { id: string; type: string; phase: string | null; parent: string | null };\n\n/** Phase metrics: membership and spend replayed from events (item.added, item.completed); requirement coverage read live from the traceability matrix. */\nexport function waterfallMetrics(state: WorkflowState): WaterfallMetrics {\n const phases = configOf(state).phases.map((p) => p.id);\n const zero = () => Object.fromEntries(phases.map((p) => [p, 0])) as Record<string, number>;\n const total = zero();\n const done = zero();\n const planned = zero();\n const spent = zero();\n const defects = zero();\n const phaseOf = new Map<string, string | undefined>();\n const typeOf = new Map<string, string>();\n const status = new Map<string, string>();\n let changeRequests = 0;\n let approved = 0;\n let rejected = 0;\n let reworkWeight = 0;\n let phasesReopened = 0;\n const counted = (id: string) => {\n const t = typeOf.get(id);\n const p = phaseOf.get(id);\n return t !== \"question\" && t !== \"change-request\" && p !== undefined && p in total;\n };\n for (const ev of state.events) {\n const p = (ev.payload ?? {}) as Record<string, unknown>;\n switch (ev.type) {\n case \"item.added\": {\n const a = p as Added;\n const phase = a.phase ?? (a.parent !== null ? phaseOf.get(a.parent) : undefined);\n phaseOf.set(a.id, phase);\n typeOf.set(a.id, a.type);\n status.set(a.id, \"todo\");\n if (a.type === \"change-request\") changeRequests += 1;\n if (counted(a.id)) {\n total[phase!]! += 1;\n if (a.type === \"bug\") defects[phase!]! += 1;\n }\n break;\n }\n case \"item.transition\": {\n const id = p[\"id\"] as string;\n const to = (p[\"to\"] as { status: string }).status;\n const was = status.get(id);\n status.set(id, to);\n if (!counted(id)) break;\n const phase = phaseOf.get(id)!;\n if (to === \"done\" && was !== \"done\") done[phase]! += 1;\n if (to === \"dropped\") {\n total[phase]! -= 1;\n if (was === \"done\") done[phase]! -= 1;\n }\n break;\n }\n case \"item.completed\": {\n const phase = phaseOf.get(p[\"id\"] as string);\n if (phase !== undefined && phase in spent) spent[phase]! += (p[\"tokens\"] as number) ?? 0;\n break;\n }\n case \"phase.opened\": {\n const phase = p[\"phase\"] as string;\n if (phase in planned)\n planned[phase] = ((p[\"budget\"] as { tokens?: number }) ?? {}).tokens ?? 0;\n break;\n }\n case \"change.decided\": {\n if (p[\"decision\"] === \"approve\") {\n approved += 1;\n reworkWeight += (p[\"weight\"] as number) ?? 0;\n phasesReopened += ((p[\"reopened\"] as string[]) ?? []).length;\n } else rejected += 1;\n break;\n }\n default:\n break;\n }\n }\n const completion = zero();\n const variance = zero();\n for (const ph of phases) {\n const n = total[ph] ?? 0;\n completion[ph] = n === 0 ? 0 : ((done[ph] ?? 0) / n) * 100;\n variance[ph] = spent[ph]! - planned[ph]!;\n }\n const { traced, total: reqTotal } = traceabilityMatrix(state).coverage;\n const decided = approved + rejected;\n return {\n phaseCompletion: completion,\n budgetPlanned: planned,\n budgetSpent: spent,\n scheduleVariance: variance,\n requirementCoverage: reqTotal === 0 ? 0 : traced / reqTotal,\n requirementsTraced: traced,\n requirementsTotal: reqTotal,\n defectsPerPhase: defects,\n changeRequests,\n changesApproved: approved,\n changesRejected: rejected,\n changeApprovalRate: decided === 0 ? 0 : approved / decided,\n reworkWeight,\n phasesReopened,\n };\n}\n","import type { Role } from \"../types.ts\";\nimport { CHANGE_GATE, type WaterfallConfig } from \"./config.ts\";\n\n/** Order matters: the first role with \"deliver\" is the fallback deliverer for phases without deliverBy. */\nexport function waterfallRoles(config: WaterfallConfig): Role[] {\n const gates = config.phases.map((p) => p.gate.id);\n return [\n {\n id: \"project-manager\",\n name: \"Project Manager\",\n modelTier: \"large\",\n capabilities: [\"facilitate\", \"control-change\", \"approve-gate\", \"escalate\"],\n canApprove: [...gates, CHANGE_GATE],\n inputs: [\"phase-plan\", \"deliverables\", \"change-requests\"],\n outputs: [\"gate-decisions\", \"baselines\", \"change-decisions\"],\n do_not: [\n \"do not implement items yourself\",\n \"do not reopen a phase without an approved change-request\",\n ],\n },\n {\n id: \"developer\",\n name: \"Developer\",\n modelTier: \"small\",\n capabilities: [\"deliver\"],\n canApprove: [],\n inputs: [\"design-doc\", \"interface-spec\", \"brief\"],\n outputs: [\"code\", \"code-baseline\", \"test-output\"],\n do_not: [\n \"do not change requirements or designs; raise a change-request\",\n \"do not approve your own work\",\n ],\n },\n {\n id: \"business-analyst\",\n name: \"Business Analyst\",\n modelTier: \"medium\",\n capabilities: [\"define-acceptance\", \"deliver\"],\n canApprove: [],\n inputs: [\"stakeholder-needs\"],\n outputs: [\"srs\", \"acceptance-criteria\"],\n do_not: [\n \"do not design or implement\",\n \"do not edit a baselined requirement; raise a change-request\",\n ],\n },\n {\n id: \"architect\",\n name: \"Architect\",\n modelTier: \"medium\",\n capabilities: [\"deliver\"],\n canApprove: [],\n inputs: [\"srs\"],\n outputs: [\"design-doc\", \"interface-spec\"],\n do_not: [\"do not change requirements; raise a change-request\", \"do not implement\"],\n },\n {\n id: \"qa\",\n name: \"QA\",\n modelTier: \"small\",\n capabilities: [\"verify\", \"review\"],\n canApprove: [],\n inputs: [\"srs\", \"design-doc\", \"code-baseline\"],\n outputs: [\"test-report\", \"review-notes\"],\n do_not: [\"do not fix defects yourself; raise bugs\", \"do not approve phase gates\"],\n },\n {\n id: \"release-manager\",\n name: \"Release Manager\",\n modelTier: \"small\",\n capabilities: [\"deliver\"],\n canApprove: [],\n inputs: [\"code-baseline\", \"test-report\"],\n outputs: [\"release-notes\", \"deployment-record\"],\n do_not: [\"do not deploy an unbaselined verification phase\"],\n },\n ];\n}\n","import { authorOf } from \"../gates.ts\";\nimport { approverIds, rolesWith } from \"../roles.ts\";\nimport type { Action, NewItem, Phase, Rule, Violation, WorkflowState } from \"../types.ts\";\nimport { configOf } from \"./config.ts\";\nimport {\n itemsInPhase,\n lastToPhase,\n missingDeliverables,\n openPhase,\n phaseOf,\n phasesOf,\n} from \"./phases.ts\";\nimport { missingTraces } from \"./traceability.ts\";\n\nconst v = (rule: string, message: string, fix: string, item?: string): Violation =>\n item\n ? { rule, severity: \"error\", item, message, fix }\n : { rule, severity: \"error\", message, fix };\nconst payloadOf = (a: Action): Record<string, unknown> =>\n (a.payload ?? {}) as Record<string, unknown>;\nconst isObj = (x: unknown): x is Record<string, unknown> =>\n typeof x === \"object\" && x !== null && !Array.isArray(x);\nconst phaseArg = (a: Action): string | undefined => {\n const p = payloadOf(a)[\"phase\"];\n return typeof p === \"string\" ? p : undefined;\n};\nconst phaseById = (s: WorkflowState, id: string): Phase | undefined =>\n phasesOf(s).find((p) => p.id === id);\nconst phaseIds = (s: WorkflowState) =>\n phasesOf(s)\n .map((p) => p.id)\n .join(\", \");\nconst itemById = (s: WorkflowState, id: unknown) =>\n typeof id === \"string\" && Object.hasOwn(s.items, id) ? s.items[id] : undefined;\n\n/** Phase a NewItem would land in: its own, else its parent's. */\nfunction phaseOfNew(s: WorkflowState, item: NewItem): string | undefined {\n if (item.phase !== undefined) return item.phase;\n const parent = itemById(s, item.parent);\n return parent ? phaseOf(s, parent) : undefined;\n}\nconst governed = (item: NewItem) => item.type !== \"change-request\" && item.type !== \"question\";\n\nconst frozenFix = (item: string, phase: string) =>\n `raise a change-request: addItem({ type: \"change-request\", affects: [\"${item}\"], impactAnalysis: { summary, reopen: [\"${phase}\"], weight } }) and decide it in changeControlBoard`;\n\nfunction changeOf(s: WorkflowState, a: Action) {\n const item = itemById(s, payloadOf(a)[\"change\"]);\n return item && item.type === \"change-request\" ? item : undefined;\n}\n\n/** Shape check shared by add/edit and the change control board. */\nfunction impactShape(s: WorkflowState, id: string, ia: unknown): Violation[] {\n const rule = \"change-needs-impact-analysis\";\n const fix = `editItem(\"${id}\", { impactAnalysis: { summary: \"what changes and why\", reopen: [\"<phase>\"], weight: <points> } })`;\n if (ia === undefined) {\n return configOf(s).changeControl.requiresImpactAnalysis\n ? [v(rule, `change \"${id}\" has no impact analysis`, fix, id)]\n : [];\n }\n const out: Violation[] = [];\n const o = isObj(ia) ? ia : {};\n if (typeof o[\"summary\"] !== \"string\" || o[\"summary\"].trim() === \"\")\n out.push(v(rule, `change \"${id}\" impactAnalysis.summary is empty`, fix, id));\n if (!Array.isArray(o[\"reopen\"]) || !o[\"reopen\"].every((x) => typeof x === \"string\"))\n out.push(\n v(rule, `change \"${id}\" impactAnalysis.reopen must be a string[] of phase ids`, fix, id),\n );\n if (typeof o[\"weight\"] !== \"number\" || !Number.isFinite(o[\"weight\"]) || o[\"weight\"] < 0)\n out.push(\n v(rule, `change \"${id}\" impactAnalysis.weight must be a non-negative number`, fix, id),\n );\n return out;\n}\n\nexport function waterfallRules(): Rule[] {\n const sequential: Rule = {\n id: \"phase-sequential\",\n severity: \"error\",\n check(s, a) {\n const out: Violation[] = [];\n if (a.type === \"ceremony.kickoff\") {\n const id = phaseArg(a);\n const p = id === undefined ? undefined : phaseById(s, id);\n if (!p) return [];\n if (p.status === \"open\")\n out.push(\n v(\n \"phase-sequential\",\n `phase \"${p.id}\" is already open`,\n `gateReview \"${p.id}\" when its work is done`,\n ),\n );\n if (p.status === \"baselined\")\n out.push(\n v(\n \"phase-sequential\",\n `phase \"${p.id}\" is baselined`,\n \"only an approved change-request reopens a baselined phase\",\n ),\n );\n const open = openPhase(s);\n if (open && open.id !== p.id)\n out.push(\n v(\n \"phase-sequential\",\n `phase \"${open.id}\" is still open`,\n `pass its gate (gateReview \"${open.id}\") before opening \"${p.id}\"`,\n ),\n );\n } else if (a.type === \"item.add\") {\n const item = payloadOf(a)[\"item\"] as NewItem | undefined;\n if (!isObj(item) || !governed(item)) return [];\n const phase = phaseOfNew(s, item);\n if (phase === undefined)\n out.push(\n v(\n \"phase-sequential\",\n `item \"${item.id}\" belongs to no phase`,\n `set phase to one of: ${phaseIds(s)}`,\n item.id,\n ),\n );\n else if (!phaseById(s, phase))\n out.push(\n v(\n \"phase-sequential\",\n `item \"${item.id}\" names unknown phase \"${phase}\"`,\n `phases are: ${phaseIds(s)}`,\n item.id,\n ),\n );\n } else if (a.type === \"item.edit\") {\n const id = payloadOf(a)[\"id\"];\n const patch = payloadOf(a)[\"patch\"];\n const item = itemById(s, id);\n if (!item || !isObj(patch) || patch[\"phase\"] === undefined || patch[\"phase\"] === item.phase)\n return [];\n out.push(\n v(\n \"phase-sequential\",\n `item \"${item.id}\" cannot move from phase \"${item.phase ?? \"(none)\"}\" to \"${String(patch[\"phase\"])}\"`,\n `drop \"${item.id}\" and add a new item in phase \"${String(patch[\"phase\"])}\"`,\n item.id,\n ),\n );\n }\n return out;\n },\n };\n\n const gateBefore: Rule = {\n id: \"gate-before-next-phase\",\n severity: \"error\",\n check(s, a) {\n if (a.type !== \"ceremony.kickoff\") return [];\n const id = phaseArg(a);\n const phases = phasesOf(s);\n const idx = id === undefined ? -1 : phases.findIndex((p) => p.id === id);\n if (idx < 0) return [];\n const earlier = phases\n .slice(0, idx)\n .filter((p) => p.status !== \"baselined\")\n .map((p) => p.id);\n if (earlier.length === 0) return [];\n return [\n v(\n \"gate-before-next-phase\",\n `phase(s) ${earlier.join(\", \")} before \"${id}\" are not baselined`,\n `kickoff and gateReview them in order, starting with \"${earlier[0]}\"`,\n ),\n ];\n },\n };\n\n const immutable: Rule = {\n id: \"baseline-immutable\",\n severity: \"error\",\n check(s, a) {\n const version = (phase: string) =>\n (s.baselines ?? []).filter((b) => b.phase === phase).length || 1;\n if (a.type === \"item.edit\") {\n const item = itemById(s, payloadOf(a)[\"id\"]);\n if (!item) return [];\n const phase = phaseOf(s, item);\n if (phase === undefined || phaseById(s, phase)?.status !== \"baselined\") return [];\n return [\n v(\n \"baseline-immutable\",\n `item \"${item.id}\" is frozen: phase \"${phase}\" is baselined (v${version(phase)})`,\n frozenFix(item.id, phase),\n item.id,\n ),\n ];\n }\n if (a.type === \"item.add\") {\n const item = payloadOf(a)[\"item\"] as NewItem | undefined;\n if (!isObj(item) || !governed(item)) return [];\n const phase = phaseOfNew(s, item);\n if (phase === undefined || phaseById(s, phase)?.status !== \"baselined\") return [];\n return [\n v(\n \"baseline-immutable\",\n `cannot add \"${item.id}\" to baselined phase \"${phase}\" (v${version(phase)})`,\n frozenFix(item.id, phase),\n item.id,\n ),\n ];\n }\n return [];\n },\n };\n\n const impact: Rule = {\n id: \"change-needs-impact-analysis\",\n severity: \"error\",\n check(s, a) {\n if (a.type === \"item.add\") {\n const item = payloadOf(a)[\"item\"] as NewItem | undefined;\n if (!isObj(item) || item.type !== \"change-request\") return [];\n return impactShape(s, String(item.id), item.impactAnalysis);\n }\n if (a.type === \"item.edit\") {\n const patch = payloadOf(a)[\"patch\"];\n const cr = itemById(s, payloadOf(a)[\"id\"]);\n if (!cr || cr.type !== \"change-request\" || !isObj(patch) || !(\"impactAnalysis\" in patch))\n return [];\n return impactShape(s, cr.id, patch[\"impactAnalysis\"]);\n }\n if (a.type !== \"ceremony.changeControlBoard\") return [];\n const cr = changeOf(s, a);\n if (!cr) return [];\n const out = impactShape(s, cr.id, cr.impactAnalysis);\n if (out.length || cr.impactAnalysis === undefined) return out;\n const approve = payloadOf(a)[\"decision\"] === \"approve\";\n for (const id of cr.impactAnalysis.reopen) {\n const p = phaseById(s, id);\n if (!p)\n out.push(\n v(\n \"change-needs-impact-analysis\",\n `change \"${cr.id}\" impactAnalysis.reopen names unknown phase \"${id}\"`,\n `phases are: ${phaseIds(s)}`,\n cr.id,\n ),\n );\n else if (approve && p.status === \"pending\")\n out.push(\n v(\n \"change-needs-impact-analysis\",\n `phase \"${id}\" was never baselined; it cannot be reopened`,\n `remove \"${id}\" from impactAnalysis.reopen`,\n cr.id,\n ),\n );\n }\n return out;\n },\n };\n\n const traceIds: Rule = {\n id: \"trace-ids-valid\",\n severity: \"error\",\n check(s, a) {\n let id: string;\n let traces: unknown;\n let ia: unknown;\n let isCr: boolean;\n if (a.type === \"item.add\") {\n const item = payloadOf(a)[\"item\"] as NewItem | undefined;\n if (!isObj(item)) return [];\n id = String(item.id);\n traces = item.traces;\n ia = item.impactAnalysis;\n isCr = item.type === \"change-request\";\n } else if (a.type === \"item.edit\") {\n const cur = itemById(s, payloadOf(a)[\"id\"]);\n const patch = payloadOf(a)[\"patch\"];\n if (!cur || !isObj(patch)) return [];\n id = cur.id;\n traces = patch[\"traces\"];\n ia = patch[\"impactAnalysis\"];\n isCr = cur.type === \"change-request\";\n } else return [];\n const out: Violation[] = [];\n if (Array.isArray(traces)) {\n const cfg = configOf(s).traceability;\n const ok = [cfg.from, ...cfg.to].flatMap((p) =>\n itemsInPhase(s, p)\n .filter((i) => i.type !== \"question\" && i.type !== \"change-request\")\n .map((i) => i.id),\n );\n const fix = `traceable items: ${ok.length ? ok.join(\", \") : \"(none yet)\"}`;\n for (const t of traces) {\n if (typeof t !== \"string\") continue;\n const target = itemById(s, t);\n if (!target || target.status === \"dropped\")\n out.push(v(\"trace-ids-valid\", `item \"${id}\" traces unknown item \"${t}\"`, fix, id));\n }\n }\n if (isCr && isObj(ia) && Array.isArray(ia[\"reopen\"])) {\n for (const r of ia[\"reopen\"]) {\n if (typeof r === \"string\" && !phaseById(s, r))\n out.push(\n v(\n \"trace-ids-valid\",\n `change \"${id}\" impactAnalysis.reopen names unknown phase \"${r}\"`,\n `phases are: ${phaseIds(s)}`,\n id,\n ),\n );\n }\n }\n return out;\n },\n };\n\n const traced: Rule = {\n id: \"requirement-traced\",\n severity: \"error\",\n check(s, a) {\n if (a.type !== \"ceremony.gateReview\") return [];\n const id = phaseArg(a);\n const cfg = configOf(s).traceability;\n if (id === undefined || !cfg.to.includes(id) || !phaseById(s, id)) return [];\n return missingTraces(s, id).map((item) =>\n v(\n \"requirement-traced\",\n `item \"${item}\" of phase \"${cfg.from}\" has no trace into \"${id}\"`,\n `editItem a \"${id}\" item with traces: [\"${item}\"] (or editItem(\"${item}\", { traces: [...] }) while \"${cfg.from}\" is not baselined)`,\n item,\n ),\n );\n },\n };\n\n const deliverables: Rule = {\n id: \"deliverables-present\",\n severity: \"error\",\n check(s, a) {\n if (a.type !== \"ceremony.gateReview\") return [];\n const id = phaseArg(a);\n const p = id === undefined ? undefined : phaseById(s, id);\n if (!p) return [];\n const out: Violation[] = [];\n const open = itemsInPhase(s, p.id)\n .filter((i) => i.status !== \"done\")\n .map((i) => i.id);\n if (open.length)\n out.push(\n v(\n \"deliverables-present\",\n `${open.length} item(s) in phase \"${p.id}\" are not done: ${open.join(\", \")}`,\n \"finish them (next/complete) or drop them before the gate\",\n ),\n );\n const given = payloadOf(a)[\"deliverables\"];\n const extra = Array.isArray(given)\n ? given\n .filter((d) => isObj(d) && typeof d[\"kind\"] === \"string\")\n .map((d) => (d as { kind: string }).kind)\n : [];\n if (p.id === lastToPhase(s)) extra.push(\"traceability-matrix\");\n for (const kind of missingDeliverables(s, p, extra))\n out.push(\n v(\n \"deliverables-present\",\n `phase \"${p.id}\" has no deliverable \"${kind}\"`,\n `pass deliverables: [{ \"kind\": \"${kind}\", \"ref\": \"<where it lives>\" }] to gateReview, or attach evidence of kind \"${kind}\" on an item of the phase`,\n ),\n );\n return out;\n },\n };\n\n const notAuthor: Rule = {\n id: \"approver-not-author\",\n severity: \"error\",\n check(s, a) {\n if (a.by === \"human\") return [];\n if (a.type === \"ceremony.gateReview\") {\n const id = phaseArg(a);\n const p = id === undefined ? undefined : phaseById(s, id);\n if (!p) return [];\n const mine = itemsInPhase(s, p.id)\n .filter((i) => authorOf(s, i) === a.by)\n .map((i) => i.id);\n if (mine.length === 0) return [];\n const others = approverIds(s, p.gate.id, \"approve-gate\", a.by);\n return [\n v(\n \"approver-not-author\",\n `\"${a.by}\" authored ${mine.join(\", \")} in phase \"${p.id}\" and may not approve its gate`,\n `review the gate as one of: human${others.map((r) => `, ${r}`).join(\"\")}`,\n ),\n ];\n }\n if (a.type === \"ceremony.changeControlBoard\") {\n const cr = changeOf(s, a);\n if (!cr) return [];\n const added = s.events.find(\n (e) => e.type === \"item.added\" && (e.payload as { id: string }).id === cr.id,\n );\n if (!added || added.by !== a.by) return [];\n const others = rolesWith(s, \"control-change\")\n .map((r) => r.id)\n .filter((r) => r !== a.by);\n return [\n v(\n \"approver-not-author\",\n `\"${a.by}\" raised change \"${cr.id}\" and may not decide it`,\n `decide as human${others.map((r) => `, ${r}`).join(\"\")}`,\n cr.id,\n ),\n ];\n }\n return [];\n },\n };\n\n return [sequential, gateBefore, immutable, impact, traced, deliverables, notAuthor, traceIds];\n}\n","import type { Stage } from \"../types.ts\";\nimport type { WaterfallConfig } from \"./config.ts\";\nimport { DONE, REVIEW, WORK } from \"./phases.ts\";\n\n/** Every phase's items share the same three steps; the phase is the unit of governance. */\nexport function waterfallStages(_config: WaterfallConfig): Stage[] {\n return [\n { id: WORK, name: \"Work\", entryPolicy: [{ kind: \"dependencies-done\" }], exitPolicy: [] },\n {\n id: REVIEW,\n name: \"Review\",\n entryPolicy: [],\n exitPolicy: [{ kind: \"no-open-blockers\" }],\n review: true,\n },\n { id: DONE, name: \"Done\", entryPolicy: [], exitPolicy: [] },\n ];\n}\n","import { addSpent } from \"../budget.ts\";\nimport { openIteration } from \"../planner.ts\";\nimport type { CoreTerm, Methodology, PlannerOptions, WorkItem, WorkflowState } from \"../types.ts\";\nimport { configOf, validateWaterfallConfig, type WaterfallConfig } from \"./config.ts\";\nimport {\n REVIEW,\n WORK,\n currentPhase,\n itemsInPhase,\n lastToPhase,\n missingDeliverables,\n openPhase,\n phaseIndex,\n phaseOf,\n phasesOf,\n} from \"./phases.ts\";\nimport { waterfallAfterDecide, waterfallCeremonies } from \"./ceremonies.ts\";\nimport { waterfallMetrics } from \"./metrics.ts\";\nimport { waterfallRoles } from \"./roles.ts\";\nimport { waterfallRules } from \"./rules.ts\";\nimport { waterfallStages } from \"./stages.ts\";\nimport { missingTraces, traceabilityMatrix } from \"./traceability.ts\";\n\nexport {\n validateWaterfallConfig,\n configOf,\n defaultPhases,\n DEFAULT_PHASE_IDS,\n DEFAULT_DELIVERABLES,\n DEFAULT_DELIVER_BY,\n GATE_ID,\n CHANGE_GATE,\n} from \"./config.ts\";\nexport type { WaterfallConfig, WaterfallPhaseConfig } from \"./config.ts\";\nexport {\n WORK,\n REVIEW,\n DONE,\n phasesOf,\n withPhases,\n getPhase,\n phaseIndex,\n phaseOf,\n itemsInPhase,\n openPhase,\n currentPhase,\n isFrozen,\n producedKinds,\n missingDeliverables,\n lastToPhase,\n} from \"./phases.ts\";\nexport { waterfallStages } from \"./stages.ts\";\nexport { waterfallRoles } from \"./roles.ts\";\nexport { waterfallRules } from \"./rules.ts\";\nexport { waterfallMetrics } from \"./metrics.ts\";\nexport type { WaterfallMetrics } from \"./metrics.ts\";\nexport {\n waterfallCeremonies,\n waterfallAfterDecide,\n wantPhase,\n approveChange,\n rejectChange,\n} from \"./ceremonies.ts\";\nexport { traceabilityMatrix, missingTraces } from \"./traceability.ts\";\nexport type { TraceabilityMatrix, TraceRow } from \"./traceability.ts\";\nexport { baselinePhase, reopenPhases } from \"./baseline.ts\";\nexport type { ReopenResult } from \"./baseline.ts\";\n\nexport const WATERFALL_VOCABULARY: Record<CoreTerm, string> = {\n backlog: \"Requirements Baseline\",\n item: \"Work Package\",\n stage: \"Step\",\n iteration: \"Phase\",\n increment: \"Deliverable\",\n ceremony: \"Review\",\n gate: \"Phase Gate\",\n};\n\n/** The role that delivers the item's phase (config deliverBy); undefined = the planner's default deliverer. */\nexport function deliverRoleFor(state: WorkflowState, item: WorkItem): string | undefined {\n const id = phaseOf(state, item);\n if (id === undefined) return undefined;\n return configOf(state).phases.find((p) => p.id === id)?.deliverBy;\n}\n\nexport interface PhaseReportRow {\n id: string;\n name: string;\n status: string;\n items: number;\n done: number;\n missingDeliverables: string[];\n missingTraces: string[];\n readyForGate: boolean;\n}\nexport interface PhaseReport {\n phases: PhaseReportRow[];\n current: string | null;\n open: string | null;\n pendingGates: Array<{ pending: string; gate: string }>;\n}\n\nexport function phaseReport(state: WorkflowState): PhaseReport {\n const phases = phasesOf(state).map((p) => {\n const items = itemsInPhase(state, p.id);\n const done = items.filter((i) => i.status === \"done\").length;\n const toPhase = configOf(state).traceability.to.includes(p.id);\n const traces = toPhase ? missingTraces(state, p.id) : [];\n // the gate generates the matrix for the last `to` phase once every trace is present\n const extra = p.id === lastToPhase(state) && traces.length === 0 ? [\"traceability-matrix\"] : [];\n const missing = missingDeliverables(state, p, extra);\n return {\n id: p.id,\n name: p.name,\n status: p.status,\n items: items.length,\n done,\n missingDeliverables: missing,\n missingTraces: traces,\n readyForGate:\n p.status === \"open\" && done === items.length && missing.length === 0 && traces.length === 0,\n };\n });\n return {\n phases,\n current: currentPhase(state)?.id ?? null,\n open: openPhase(state)?.id ?? null,\n pendingGates: state.pending\n .filter((p) => p.kind === \"gate\" && p.item === undefined && p.gate !== undefined)\n .map((p) => ({ pending: p.id, gate: p.gate! })),\n };\n}\n\nexport function waterfall(): Methodology<WaterfallConfig> {\n return {\n name: \"waterfall\",\n vocabulary: WATERFALL_VOCABULARY,\n validateConfig: validateWaterfallConfig,\n defaultStages: waterfallStages,\n defaultRoles: waterfallRoles,\n requiredCapabilities: [\"facilitate\", \"control-change\", \"approve-gate\", \"deliver\", \"verify\"],\n exclusiveCapabilities: [],\n plannerOptions(state): PlannerOptions {\n const po: PlannerOptions = {\n schedulerMode: \"level\",\n // questions keep the escalation role core gave them; reviews use the planner's reviewer logic\n roleFor: (item) =>\n item.status === \"todo\" && item.type !== \"question\"\n ? deliverRoleFor(state, item)\n : undefined,\n };\n const fallback = configOf(state).fallbackTokensPerWeight;\n if (fallback !== undefined) po.fallbackTokensPerWeight = fallback;\n return po;\n },\n candidates(state): WorkItem[] {\n const open = openPhase(state);\n if (!open) return [];\n return Object.values(state.items).filter(\n (i) =>\n (i.status === \"todo\" || i.status === \"review\") &&\n (i.stage === WORK || i.stage === REVIEW) &&\n i.type !== \"change-request\" &&\n phaseOf(state, i) === open.id,\n );\n },\n invariants(state, item): string[] {\n const cfg = configOf(state);\n const phases = phasesOf(state);\n const id = phaseOf(state, item);\n const p = id === undefined ? undefined : phases[phaseIndex(state, id)];\n const frozen = phases.filter((x) => x.status === \"baselined\").map((x) => x.id);\n const human = p?.gate.requires.includes(\"human\");\n return [\n p\n ? `Phase \"${p.name}\" (${phaseIndex(state, p.id) + 1}/${phases.length}); deliverables: ${p.deliverables.join(\", \") || \"(none)\"}; gate \"${p.gate.id}\"${human ? \" needs human approval\" : \"\"}`\n : \"This item belongs to no phase; it is dispatched only through its parent's phase\",\n `Baselined phases are frozen: ${frozen.join(\", \") || \"(none yet)\"}; to change their items, raise a change-request with an impact analysis`,\n cfg.traceability.to.length\n ? `Traceability: every item of phase \"${cfg.traceability.from}\" must trace to an item in ${cfg.traceability.to.join(\", \")} (set traces on either side)`\n : \"Traceability: none configured\",\n `Do not change the scope of \"${item.id}\" or its acceptance criteria; raise open_questions instead`,\n ];\n },\n ceremonies: waterfallCeremonies(waterfall),\n rules: waterfallRules(),\n metrics: (state) => ({ ...waterfallMetrics(state) }),\n humanDefaults: { gates: \"all\" },\n lockedConfigKeys: [\"phases\", \"traceability\", \"humanGates\"],\n report: (state) => ({ ...phaseReport(state), coverage: traceabilityMatrix(state).coverage }),\n afterDecide: waterfallAfterDecide,\n afterComplete(state, itemId, _now) {\n // an item added to the phase after kickoff is not in the iteration's committed list: count its spend now\n const it = openIteration(state);\n const open = openPhase(state);\n if (!it || !open || it.committed.includes(itemId)) return state;\n const item = state.items[itemId];\n if (!item || phaseOf(state, item) !== open.id) return state;\n const acc = state.accounting[state.accounting.length - 1];\n if (!acc || acc.item !== itemId) return state;\n return {\n ...state,\n iterations: state.iterations.map((x) =>\n x.id === it.id\n ? { ...x, committed: [...x.committed, itemId], spent: addSpent(x.spent, acc) }\n : x,\n ),\n };\n },\n };\n}\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkZTE7LREB_cjs=require('./chunk-ZTE7LREB.cjs'),chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs');function Q(r,s){let e=[];for(let n of r.events)n.type==="item.completed"&&n.payload.id===s&&e.push({...n.payload,at:n.at});return e}function J(r,s){let e=Q(r,s);return e[e.length-1]}function ee(r,s,e){e.role||chunkS3BXVHO7_cjs.b("unknown-role",`item "${e.id}" has no role assigned`,"dispatch it with next() or set item.role",{items:[e.id]});let n=chunkZTE7LREB_cjs.e(r,e.role);n||chunkS3BXVHO7_cjs.b("unknown-role",`role "${e.role}" does not exist`,`registered roles: ${Object.keys(r.roles).join(", ")}`);let m=[],a=[...n.do_not],i=[...e.dependsOn,...e.type==="bug"||e.type==="change-request"?e.affects??[]:[]];for(let o of i){let d=J(r,o);if(d){m.push({item:o,produced:d.produced,notes:d.notes});for(let g of d.do_not)a.includes(g)||a.push(g);}}let l=Q(r,e.id).map(o=>({role:o.role,verdict:o.verdict,notes:o.notes,produced:o.produced,at:o.at})),t=new Set([e.id,...e.dependsOn]),p=Object.values(r.items).filter(o=>(o.type==="bug"||o.type==="change-request")&&o.id!==e.id&&o.status!=="done"&&o.status!=="dropped"&&(o.affects??[]).some(d=>t.has(d))).map(o=>({id:o.id,title:o.title,affects:o.affects??[]})),$=chunkZTE7LREB_cjs.P(r),f=chunkZTE7LREB_cjs.p(r,e.stage).gate,y={item:e,role:n,modelTier:n.modelTier,invariants:[...s.invariants(r,e),...r.agreements],do_not:a,acceptance:e.acceptance,upstream:m,priorHandoffs:l,relatedBugs:p,budgetRemaining:$?chunkZTE7LREB_cjs.M($.budget,$.spent):{}};if(f&&(y.gateAhead=f),e.type==="question"&&e.parent){let o=J(r,e.parent);if(o){y.parent={item:e.parent,role:o.role,notes:o.notes,produced:o.produced,open_questions:o.open_questions??[],do_not:o.do_not};for(let d of o.do_not)a.includes(d)||a.push(d);}}return y}function ce(r){let s=new Map;for(let e of r.events){if(e.type!=="item.completed")continue;let n=e.payload;s.delete(n.id),s.set(n.id,{...n,at:e.at});}return [...s.values()].filter(e=>(e.verdict==="done"||e.verdict==="needs-review")&&(e.open_questions??[]).length>0).map(e=>({item:e.id,role:e.role,questions:e.open_questions??[],at:e.at}))}function ue(r,s,e={}){let n=chunkZTE7LREB_cjs.T(r,s,e),m=n.dispatched.map(a=>ee(n.state,s,n.state.items[a.id]));return n.reason?{state:n.state,briefs:m,skipped:n.skipped,reason:n.reason}:{state:n.state,briefs:m,skipped:n.skipped}}var X=["done","needs-review","rework","blocked","escalate"],K=["policy","skill","memory","spec","review"],C=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),_=r=>typeof r=="string";function te(r,s,e){let n=chunkZTE7LREB_cjs.u(r,s.item);n.status!=="in_progress"&&chunkS3BXVHO7_cjs.b("invalid-transition",`item "${n.id}" is ${n.status}, not in_progress`,"only dispatched items can be completed; call next() first",{items:[n.id]}),Array.isArray(s.do_not)||chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff for "${n.id}" has no do_not array`,"set handoff.do_not to [] when there is nothing to forbid",{items:[n.id]}),(!Array.isArray(s.produced)||!Array.isArray(s.open_questions))&&chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff for "${n.id}" needs produced[] and open_questions[]`,"pass empty arrays when there is nothing",{items:[n.id]});let m=(t,p)=>chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff for "${n.id}": ${t}`,p,{items:[n.id]}),a=s.verdict??"done";X.includes(a)||m(`unknown verdict ${JSON.stringify(a)}`,`use one of: ${X.join(", ")}`),s.produced.every(t=>C(t)&&_(t.kind)&&_(t.ref))||m("produced[] entries need string kind and ref",'use { "kind": "code", "ref": "src/a.ts" }');let i=s.lessons??[];(!Array.isArray(i)||!i.every(t=>C(t)&&_(t.text)&&K.includes(t.scope)))&&m("lessons[] entries need a text and a scope",`scope is one of: ${K.join(", ")}`);let l=s.follow_ups??[];(!Array.isArray(l)||!l.every(t=>C(t)&&_(t.id)&&_(t.title)))&&m("follow_ups[] entries need a string id and title","describe each follow-up as a new item"),s.role!==n.role&&chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff role "${s.role}" differs from the dispatched role "${n.role}"`,`complete as "${n.role}" or re-dispatch`,{items:[n.id]}),(!e.model||e.model.trim()==="")&&chunkS3BXVHO7_cjs.b("accounting-invalid",`accounting for "${n.id}" has no model`,"record the model id that actually ran the work",{items:[n.id]});for(let t of ["tokensIn","tokensOut","durationMs"])(!Number.isFinite(e[t])||e[t]<0)&&chunkS3BXVHO7_cjs.b("accounting-invalid",`accounting.${t} must be a non-negative number`,`measure ${t} from the host's usage report`,{items:[n.id]});e.tokensIn+e.tokensOut===0&&e.estimate!==true&&chunkS3BXVHO7_cjs.b("accounting-invalid",`accounting for "${n.id}" records 0 tokens`,"pass the host's usage figures, or set estimate: true (CLI --estimate) to record a placeholder and correct it later with correctAccounting / exwf account",{items:[n.id]});}function Y(r){for(let s=r.transitions.length-1;s>=0;s--){let e=r.transitions[s];if(e.to.status==="in_progress")return e.from.stage}return r.stage}function oe(r,s){return chunkZTE7LREB_cjs.F(r,s)?.from.stage??Y(s)}function be(r,s,e,n,m){te(r,e,n);let a,i=chunkZTE7LREB_cjs.W(r,s,{type:"item.complete",by:e.role,payload:{item:e.item,handoff:e}},()=>(a=ne(r,s,e,n,m),a.state));return {state:i.state,warnings:[...i.warnings,...a.warnings]}}function ne(r,s,e,n,m){let a=chunkZTE7LREB_cjs.a(m),i=e.item,l=e.role,t={...r,accounting:[...r.accounting,n]};for(let o of e.produced)t=chunkZTE7LREB_cjs.y(t,i,{kind:o.kind,ref:o.ref,by:l},a);let p=chunkZTE7LREB_cjs.P(t);p&&(p.committed.includes(i)||chunkZTE7LREB_cjs.u(t,i).iteration===p.id)&&(t={...t,iterations:t.iterations.map(o=>o.id===p.id?{...o,spent:chunkZTE7LREB_cjs.L(o.spent,n)}:o)});for(let o of e.lessons??[]){let d=`L${t.lessons.length+1}`;t={...t,lessons:[...t.lessons,{id:d,at:a,text:o.text,scope:o.scope,status:"raised",from:l,item:i}]},t=chunkZTE7LREB_cjs.c(t,"lesson.raised",l,{id:d,from:l,item:i,scope:o.scope},a);}let $=[];for(let o of e.follow_ups??[]){let d=t.stages[0],{iteration:g,...k}=o;t=chunkZTE7LREB_cjs.v(t,{...k,stage:d.id,parent:i,tags:[...o.tags??[],"follow-up"]},l,a),$.push(o.id);}let f=e.verdict??"done",y=[];if((f==="done"||f==="needs-review")&&e.open_questions.length>0&&y.push({rule:"open-questions-ignored",severity:"warning",item:i,message:`"${i}" finished with ${e.open_questions.length} open question(s) nobody will see: ${e.open_questions.join(" | ")}`,fix:'use verdict "escalate" to route them to a role with capability escalate, or answer them in the next brief'}),f==="rework"){(!e.notes||e.notes.trim()==="")&&chunkS3BXVHO7_cjs.b("handoff-invalid",`rework on "${i}" needs notes`,"say what must change in handoff.notes",{items:[i]});let o=chunkZTE7LREB_cjs.u(t,i);t=chunkZTE7LREB_cjs.B(chunkZTE7LREB_cjs.x(t,i,{stage:oe(t,o),status:"todo"},l,a),i),t=chunkZTE7LREB_cjs.c(t,"item.rework",l,{id:i,by:l,notes:e.notes},a);}else if((f==="done"||f==="needs-review")&&chunkZTE7LREB_cjs.u(t,i).type==="question"){let o=t.stages[t.stages.length-1].id;t=chunkZTE7LREB_cjs.x(t,i,{stage:o,status:"done"},l,a);}else if(f==="done"||f==="needs-review"){let o=chunkZTE7LREB_cjs.u(t,i),d=chunkZTE7LREB_cjs.p(t,o.stage);if(chunkZTE7LREB_cjs.E(t,o,d.exitPolicy,`leave "${d.id}"`),d.gate){let g=chunkZTE7LREB_cjs.H(t,o,d.gate,l);g.outcome==="fail"&&chunkS3BXVHO7_cjs.b("gate-unmet",`gate "${d.gate.id}" blocks "${i}": ${g.violations.map(k=>k.message).join("; ")}`,g.violations.map(k=>k.fix).join("; "),{items:[i],rule:g.violations[0].rule}),g.outcome==="human"?t=chunkZTE7LREB_cjs.I(t,{kind:"gate",item:i,gate:d.gate.id,question:`Approve gate "${d.gate.id}" for "${o.title}" (${i})?`},a):t=chunkZTE7LREB_cjs.c(chunkZTE7LREB_cjs.C(t,i,l,f==="needs-review",a),"gate.passed",l,{item:i,gate:d.gate.id},a);}else t=chunkZTE7LREB_cjs.C(t,i,l,f==="needs-review",a);}else if(f==="blocked")t=chunkZTE7LREB_cjs.z(t,i,e.notes||"blocked by worker",l,l,a);else if(f==="escalate"){let o=chunkZTE7LREB_cjs.i(t,"escalate")[0];o||chunkS3BXVHO7_cjs.b("missing-capability",`no role has capability "escalate" to receive the question from "${i}"`,"register a role with capability escalate",{items:[i]});let d=Object.keys(t.items).filter(w=>w.startsWith(`${i}-q`)).length+1,g=`${i}-q${d}`,k=chunkZTE7LREB_cjs.u(t,i),O=Y(k),b={id:g,type:"question",title:e.open_questions.join(" | ")||e.notes||`question from ${i}`,parent:i,role:o.id,priority:Number.MAX_SAFE_INTEGER,stage:O};k.iteration!==void 0&&(b.iteration=k.iteration),t=chunkZTE7LREB_cjs.v(t,b,l,a),t=chunkZTE7LREB_cjs.x(t,i,{stage:O,status:"todo"},l,a),t=chunkZTE7LREB_cjs.s(t,i,w=>({...w,dependsOn:[...w.dependsOn,g]})),t=chunkZTE7LREB_cjs.c(t,"item.escalated",l,{id:i,question:g,to:o.id},a);}return t=chunkZTE7LREB_cjs.c(t,"item.completed",l,{id:i,role:l,verdict:f,produced:e.produced,notes:e.notes,do_not:e.do_not,open_questions:e.open_questions,followUps:$,tokens:n.tokensIn+n.tokensOut,durationMs:n.durationMs,model:n.model},a),s.afterComplete&&(t=s.afterComplete(t,i,a)),{state:t,warnings:y}}var se=[["tokensIn","tokens-in"],["tokensOut","tokens-out"],["durationMs","duration-ms"]],Z=r=>({tokensIn:r.tokensIn,tokensOut:r.tokensOut,durationMs:r.durationMs,model:r.model});function qe(r,s,e,n,m,a){chunkZTE7LREB_cjs.u(r,s);let i=[];r.accounting.forEach((u,A)=>{u.item===s&&i.push(A);}),i.length===0&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${s}" has no accounting line to correct`,`complete "${s}" first (exwf complete), then exwf account`,{items:[s]});let l=a??i.length;(!Number.isInteger(l)||l<1||l>i.length)&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${s}" has ${i.length} accounting line(s), not line ${String(a)}`,`pass --line 1..${i.length}`,{items:[s]});let t=i[l-1],p=r.accounting[t];for(let[u,A]of se){let W=e[u];W!==void 0&&(!Number.isFinite(W)||W<0)&&chunkS3BXVHO7_cjs.b("accounting-invalid",`${u} must be a non-negative number`,`pass --${A} <n> with a measured figure`,{items:[s]});}e.model!==void 0&&e.model.trim()===""&&chunkS3BXVHO7_cjs.b("accounting-invalid","model must not be empty","pass --model with the model id that ran the work",{items:[s]});let{estimate:$,...f}=p,y={...f,tokensIn:e.tokensIn??p.tokensIn,tokensOut:e.tokensOut??p.tokensOut,durationMs:e.durationMs??p.durationMs,model:e.model??p.model};y.tokensIn+y.tokensOut===0&&chunkS3BXVHO7_cjs.b("accounting-invalid",`the correction leaves "${s}" at 0 tokens`,"pass the host's usage figures with --tokens-in / --tokens-out",{items:[s]});let o=Z(p),d=Z(y);o.tokensIn===d.tokensIn&&o.tokensOut===d.tokensOut&&o.durationMs===d.durationMs&&o.model===d.model&&p.estimate!==true&&chunkS3BXVHO7_cjs.b("no-op",`accounting for "${s}" line ${l} already has these figures`,"pass at least one different value to exwf account",{items:[s]});let k={tokens:d.tokensIn+d.tokensOut-(o.tokensIn+o.tokensOut),durationMs:d.durationMs-o.durationMs},O=r.items[s],b;for(let u of r.iterations)(u.committed.includes(s)||O.iteration===u.id)&&u.startedAt<=p.endedAt&&(u.endedAt===void 0||p.endedAt<=u.endedAt)&&(b=u);let w={...r,accounting:r.accounting.map((u,A)=>A===t?y:u)};return b&&(w={...w,iterations:w.iterations.map(u=>u.id===b.id?{...u,spent:{...u.spent,tokens:Math.max(0,u.spent.tokens+k.tokens),wallclockMs:Math.max(0,u.spent.wallclockMs+k.durationMs)}}:u)}),chunkZTE7LREB_cjs.c(w,"accounting.corrected",n,{item:s,line:l,iteration:b?.id??null,before:o,after:d,delta:k},chunkZTE7LREB_cjs.a(m))}exports.a=ee;exports.b=ce;exports.c=ue;exports.d=be;exports.e=qe;//# sourceMappingURL=chunk-MH66G5KV.cjs.map
2
- //# sourceMappingURL=chunk-MH66G5KV.cjs.map
1
+ 'use strict';var chunkXMO2RCXB_cjs=require('./chunk-XMO2RCXB.cjs'),chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs');function Q(r,s){let e=[];for(let n of r.events)n.type==="item.completed"&&n.payload.id===s&&e.push({...n.payload,at:n.at});return e}function J(r,s){let e=Q(r,s);return e[e.length-1]}function ee(r,s,e){e.role||chunkS3BXVHO7_cjs.b("unknown-role",`item "${e.id}" has no role assigned`,"dispatch it with next() or set item.role",{items:[e.id]});let n=chunkXMO2RCXB_cjs.e(r,e.role);n||chunkS3BXVHO7_cjs.b("unknown-role",`role "${e.role}" does not exist`,`registered roles: ${Object.keys(r.roles).join(", ")}`);let m=[],a=[...n.do_not],i=[...e.dependsOn,...e.type==="bug"||e.type==="change-request"?e.affects??[]:[]];for(let o of i){let d=J(r,o);if(d){m.push({item:o,produced:d.produced,notes:d.notes});for(let g of d.do_not)a.includes(g)||a.push(g);}}let l=Q(r,e.id).map(o=>({role:o.role,verdict:o.verdict,notes:o.notes,produced:o.produced,at:o.at})),t=new Set([e.id,...e.dependsOn]),p=Object.values(r.items).filter(o=>(o.type==="bug"||o.type==="change-request")&&o.id!==e.id&&o.status!=="done"&&o.status!=="dropped"&&(o.affects??[]).some(d=>t.has(d))).map(o=>({id:o.id,title:o.title,affects:o.affects??[]})),$=chunkXMO2RCXB_cjs.R(r),f=chunkXMO2RCXB_cjs.p(r,e.stage).gate,y={item:e,role:n,modelTier:n.modelTier,invariants:[...s.invariants(r,e),...r.agreements],do_not:a,acceptance:e.acceptance,upstream:m,priorHandoffs:l,relatedBugs:p,budgetRemaining:$?chunkXMO2RCXB_cjs.O($.budget,$.spent):{}};if(f&&(y.gateAhead=f),e.type==="question"&&e.parent){let o=J(r,e.parent);if(o){y.parent={item:e.parent,role:o.role,notes:o.notes,produced:o.produced,open_questions:o.open_questions??[],do_not:o.do_not};for(let d of o.do_not)a.includes(d)||a.push(d);}}return y}function ce(r){let s=new Map;for(let e of r.events){if(e.type!=="item.completed")continue;let n=e.payload;s.delete(n.id),s.set(n.id,{...n,at:e.at});}return [...s.values()].filter(e=>(e.verdict==="done"||e.verdict==="needs-review")&&(e.open_questions??[]).length>0).map(e=>({item:e.id,role:e.role,questions:e.open_questions??[],at:e.at}))}function ue(r,s,e={}){let n=chunkXMO2RCXB_cjs.V(r,s,e),m=n.dispatched.map(a=>ee(n.state,s,n.state.items[a.id]));return n.reason?{state:n.state,briefs:m,skipped:n.skipped,reason:n.reason}:{state:n.state,briefs:m,skipped:n.skipped}}var X=["done","needs-review","rework","blocked","escalate"],K=["policy","skill","memory","spec","review"],C=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),_=r=>typeof r=="string";function te(r,s,e){let n=chunkXMO2RCXB_cjs.u(r,s.item);n.status!=="in_progress"&&chunkS3BXVHO7_cjs.b("invalid-transition",`item "${n.id}" is ${n.status}, not in_progress`,"only dispatched items can be completed; call next() first",{items:[n.id]}),Array.isArray(s.do_not)||chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff for "${n.id}" has no do_not array`,"set handoff.do_not to [] when there is nothing to forbid",{items:[n.id]}),(!Array.isArray(s.produced)||!Array.isArray(s.open_questions))&&chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff for "${n.id}" needs produced[] and open_questions[]`,"pass empty arrays when there is nothing",{items:[n.id]});let m=(t,p)=>chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff for "${n.id}": ${t}`,p,{items:[n.id]}),a=s.verdict??"done";X.includes(a)||m(`unknown verdict ${JSON.stringify(a)}`,`use one of: ${X.join(", ")}`),s.produced.every(t=>C(t)&&_(t.kind)&&_(t.ref))||m("produced[] entries need string kind and ref",'use { "kind": "code", "ref": "src/a.ts" }');let i=s.lessons??[];(!Array.isArray(i)||!i.every(t=>C(t)&&_(t.text)&&K.includes(t.scope)))&&m("lessons[] entries need a text and a scope",`scope is one of: ${K.join(", ")}`);let l=s.follow_ups??[];(!Array.isArray(l)||!l.every(t=>C(t)&&_(t.id)&&_(t.title)))&&m("follow_ups[] entries need a string id and title","describe each follow-up as a new item"),s.role!==n.role&&chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff role "${s.role}" differs from the dispatched role "${n.role}"`,`complete as "${n.role}" or re-dispatch`,{items:[n.id]}),(!e.model||e.model.trim()==="")&&chunkS3BXVHO7_cjs.b("accounting-invalid",`accounting for "${n.id}" has no model`,"record the model id that actually ran the work",{items:[n.id]});for(let t of ["tokensIn","tokensOut","durationMs"])(!Number.isFinite(e[t])||e[t]<0)&&chunkS3BXVHO7_cjs.b("accounting-invalid",`accounting.${t} must be a non-negative number`,`measure ${t} from the host's usage report`,{items:[n.id]});e.tokensIn+e.tokensOut===0&&e.estimate!==true&&chunkS3BXVHO7_cjs.b("accounting-invalid",`accounting for "${n.id}" records 0 tokens`,"pass the host's usage figures, or set estimate: true (CLI --estimate) to record a placeholder and correct it later with correctAccounting / exwf account",{items:[n.id]});}function Y(r){for(let s=r.transitions.length-1;s>=0;s--){let e=r.transitions[s];if(e.to.status==="in_progress")return e.from.stage}return r.stage}function oe(r,s){return chunkXMO2RCXB_cjs.H(r,s)?.from.stage??Y(s)}function be(r,s,e,n,m){te(r,e,n);let a,i=chunkXMO2RCXB_cjs.Y(r,s,{type:"item.complete",by:e.role,payload:{item:e.item,handoff:e}},()=>(a=ne(r,s,e,n,m),a.state));return {state:i.state,warnings:[...i.warnings,...a.warnings]}}function ne(r,s,e,n,m){let a=chunkXMO2RCXB_cjs.a(m),i=e.item,l=e.role,t={...r,accounting:[...r.accounting,n]};for(let o of e.produced)t=chunkXMO2RCXB_cjs.y(t,i,{kind:o.kind,ref:o.ref,by:l},a);let p=chunkXMO2RCXB_cjs.R(t);p&&(p.committed.includes(i)||chunkXMO2RCXB_cjs.u(t,i).iteration===p.id)&&(t={...t,iterations:t.iterations.map(o=>o.id===p.id?{...o,spent:chunkXMO2RCXB_cjs.N(o.spent,n)}:o)});for(let o of e.lessons??[]){let d=`L${t.lessons.length+1}`;t={...t,lessons:[...t.lessons,{id:d,at:a,text:o.text,scope:o.scope,status:"raised",from:l,item:i}]},t=chunkXMO2RCXB_cjs.c(t,"lesson.raised",l,{id:d,from:l,item:i,scope:o.scope},a);}let $=[];for(let o of e.follow_ups??[]){let d=t.stages[0],{iteration:g,...k}=o;t=chunkXMO2RCXB_cjs.v(t,{...k,stage:d.id,parent:i,tags:[...o.tags??[],"follow-up"]},l,a),$.push(o.id);}let f=e.verdict??"done",y=[];if((f==="done"||f==="needs-review")&&e.open_questions.length>0&&y.push({rule:"open-questions-ignored",severity:"warning",item:i,message:`"${i}" finished with ${e.open_questions.length} open question(s) nobody will see: ${e.open_questions.join(" | ")}`,fix:'use verdict "escalate" to route them to a role with capability escalate, or answer them in the next brief'}),f==="rework"){(!e.notes||e.notes.trim()==="")&&chunkS3BXVHO7_cjs.b("handoff-invalid",`rework on "${i}" needs notes`,"say what must change in handoff.notes",{items:[i]});let o=chunkXMO2RCXB_cjs.u(t,i);t=chunkXMO2RCXB_cjs.B(chunkXMO2RCXB_cjs.x(t,i,{stage:oe(t,o),status:"todo"},l,a),i),t=chunkXMO2RCXB_cjs.c(t,"item.rework",l,{id:i,by:l,notes:e.notes},a);}else if((f==="done"||f==="needs-review")&&chunkXMO2RCXB_cjs.u(t,i).type==="question"){let o=t.stages[t.stages.length-1].id;t=chunkXMO2RCXB_cjs.x(t,i,{stage:o,status:"done"},l,a);}else if(f==="done"||f==="needs-review"){let o=chunkXMO2RCXB_cjs.u(t,i),d=chunkXMO2RCXB_cjs.p(t,o.stage);if(chunkXMO2RCXB_cjs.G(t,o,d.exitPolicy,`leave "${d.id}"`),d.gate){let g=chunkXMO2RCXB_cjs.J(t,o,d.gate,l);g.outcome==="fail"&&chunkS3BXVHO7_cjs.b("gate-unmet",`gate "${d.gate.id}" blocks "${i}": ${g.violations.map(k=>k.message).join("; ")}`,g.violations.map(k=>k.fix).join("; "),{items:[i],rule:g.violations[0].rule}),g.outcome==="human"?t=chunkXMO2RCXB_cjs.K(t,{kind:"gate",item:i,gate:d.gate.id,question:`Approve gate "${d.gate.id}" for "${o.title}" (${i})?`},a):t=chunkXMO2RCXB_cjs.c(chunkXMO2RCXB_cjs.C(t,i,l,f==="needs-review",a),"gate.passed",l,{item:i,gate:d.gate.id},a);}else t=chunkXMO2RCXB_cjs.C(t,i,l,f==="needs-review",a);}else if(f==="blocked")t=chunkXMO2RCXB_cjs.z(t,i,e.notes||"blocked by worker",l,l,a);else if(f==="escalate"){let o=chunkXMO2RCXB_cjs.i(t,"escalate")[0];o||chunkS3BXVHO7_cjs.b("missing-capability",`no role has capability "escalate" to receive the question from "${i}"`,"register a role with capability escalate",{items:[i]});let d=Object.keys(t.items).filter(w=>w.startsWith(`${i}-q`)).length+1,g=`${i}-q${d}`,k=chunkXMO2RCXB_cjs.u(t,i),O=Y(k),b={id:g,type:"question",title:e.open_questions.join(" | ")||e.notes||`question from ${i}`,parent:i,role:o.id,priority:Number.MAX_SAFE_INTEGER,stage:O};k.iteration!==void 0&&(b.iteration=k.iteration),t=chunkXMO2RCXB_cjs.v(t,b,l,a),t=chunkXMO2RCXB_cjs.x(t,i,{stage:O,status:"todo"},l,a),t=chunkXMO2RCXB_cjs.s(t,i,w=>({...w,dependsOn:[...w.dependsOn,g]})),t=chunkXMO2RCXB_cjs.c(t,"item.escalated",l,{id:i,question:g,to:o.id},a);}return t=chunkXMO2RCXB_cjs.c(t,"item.completed",l,{id:i,role:l,verdict:f,produced:e.produced,notes:e.notes,do_not:e.do_not,open_questions:e.open_questions,followUps:$,tokens:n.tokensIn+n.tokensOut,durationMs:n.durationMs,model:n.model},a),s.afterComplete&&(t=s.afterComplete(t,i,a)),{state:t,warnings:y}}var se=[["tokensIn","tokens-in"],["tokensOut","tokens-out"],["durationMs","duration-ms"]],Z=r=>({tokensIn:r.tokensIn,tokensOut:r.tokensOut,durationMs:r.durationMs,model:r.model});function qe(r,s,e,n,m,a){chunkXMO2RCXB_cjs.u(r,s);let i=[];r.accounting.forEach((u,A)=>{u.item===s&&i.push(A);}),i.length===0&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${s}" has no accounting line to correct`,`complete "${s}" first (exwf complete), then exwf account`,{items:[s]});let l=a??i.length;(!Number.isInteger(l)||l<1||l>i.length)&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${s}" has ${i.length} accounting line(s), not line ${String(a)}`,`pass --line 1..${i.length}`,{items:[s]});let t=i[l-1],p=r.accounting[t];for(let[u,A]of se){let W=e[u];W!==void 0&&(!Number.isFinite(W)||W<0)&&chunkS3BXVHO7_cjs.b("accounting-invalid",`${u} must be a non-negative number`,`pass --${A} <n> with a measured figure`,{items:[s]});}e.model!==void 0&&e.model.trim()===""&&chunkS3BXVHO7_cjs.b("accounting-invalid","model must not be empty","pass --model with the model id that ran the work",{items:[s]});let{estimate:$,...f}=p,y={...f,tokensIn:e.tokensIn??p.tokensIn,tokensOut:e.tokensOut??p.tokensOut,durationMs:e.durationMs??p.durationMs,model:e.model??p.model};y.tokensIn+y.tokensOut===0&&chunkS3BXVHO7_cjs.b("accounting-invalid",`the correction leaves "${s}" at 0 tokens`,"pass the host's usage figures with --tokens-in / --tokens-out",{items:[s]});let o=Z(p),d=Z(y);o.tokensIn===d.tokensIn&&o.tokensOut===d.tokensOut&&o.durationMs===d.durationMs&&o.model===d.model&&p.estimate!==true&&chunkS3BXVHO7_cjs.b("no-op",`accounting for "${s}" line ${l} already has these figures`,"pass at least one different value to exwf account",{items:[s]});let k={tokens:d.tokensIn+d.tokensOut-(o.tokensIn+o.tokensOut),durationMs:d.durationMs-o.durationMs},O=r.items[s],b;for(let u of r.iterations)(u.committed.includes(s)||O.iteration===u.id)&&u.startedAt<=p.endedAt&&(u.endedAt===void 0||p.endedAt<=u.endedAt)&&(b=u);let w={...r,accounting:r.accounting.map((u,A)=>A===t?y:u)};return b&&(w={...w,iterations:w.iterations.map(u=>u.id===b.id?{...u,spent:{...u.spent,tokens:Math.max(0,u.spent.tokens+k.tokens),wallclockMs:Math.max(0,u.spent.wallclockMs+k.durationMs)}}:u)}),chunkXMO2RCXB_cjs.c(w,"accounting.corrected",n,{item:s,line:l,iteration:b?.id??null,before:o,after:d,delta:k},chunkXMO2RCXB_cjs.a(m))}exports.a=ee;exports.b=ce;exports.c=ue;exports.d=be;exports.e=qe;//# sourceMappingURL=chunk-5PHK72VM.cjs.map
2
+ //# sourceMappingURL=chunk-5PHK72VM.cjs.map