ex-workflow 0.2.0-stage → 0.3.0-stage

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +10 -1
  2. package/README.md +39 -10
  3. package/dist/chunk-23P7C25E.cjs +2 -0
  4. package/dist/chunk-23P7C25E.cjs.map +1 -0
  5. package/dist/chunk-2IKIBB73.cjs +2 -0
  6. package/dist/chunk-2IKIBB73.cjs.map +1 -0
  7. package/dist/{chunk-472WEDPJ.cjs → chunk-4A4TD4MH.cjs} +2 -2
  8. package/dist/{chunk-472WEDPJ.cjs.map → chunk-4A4TD4MH.cjs.map} +1 -1
  9. package/dist/{chunk-D4HNETUL.cjs → chunk-7HZXZF3L.cjs} +2 -2
  10. package/dist/{chunk-D4HNETUL.cjs.map → chunk-7HZXZF3L.cjs.map} +1 -1
  11. package/dist/chunk-AUZIQPFT.cjs +2 -0
  12. package/dist/chunk-AUZIQPFT.cjs.map +1 -0
  13. package/dist/chunk-BJEOTG6P.mjs +2 -0
  14. package/dist/chunk-BJEOTG6P.mjs.map +1 -0
  15. package/dist/chunk-FLCYD2QF.mjs +2 -0
  16. package/dist/chunk-FLCYD2QF.mjs.map +1 -0
  17. package/dist/{chunk-DBR24RTX.cjs → chunk-NN3XJUHP.cjs} +2 -2
  18. package/dist/{chunk-DBR24RTX.cjs.map → chunk-NN3XJUHP.cjs.map} +1 -1
  19. package/dist/chunk-P4P4JTE5.mjs +2 -0
  20. package/dist/chunk-P4P4JTE5.mjs.map +1 -0
  21. package/dist/{chunk-IBRC36PE.mjs → chunk-R27STIER.mjs} +2 -2
  22. package/dist/{chunk-IBRC36PE.mjs.map → chunk-R27STIER.mjs.map} +1 -1
  23. package/dist/chunk-TMKCALFT.cjs +2 -0
  24. package/dist/chunk-TMKCALFT.cjs.map +1 -0
  25. package/dist/{chunk-XSXHEEJX.mjs → chunk-UOGNVWVO.mjs} +2 -2
  26. package/dist/{chunk-XSXHEEJX.mjs.map → chunk-UOGNVWVO.mjs.map} +1 -1
  27. package/dist/{chunk-VN2UYV2O.mjs → chunk-WOKNWJKU.mjs} +2 -2
  28. package/dist/{chunk-VN2UYV2O.mjs.map → chunk-WOKNWJKU.mjs.map} +1 -1
  29. package/dist/chunk-ZX4DAMTG.mjs +2 -0
  30. package/dist/chunk-ZX4DAMTG.mjs.map +1 -0
  31. package/dist/cli/bin.cjs +1 -1
  32. package/dist/cli/bin.cjs.map +1 -1
  33. package/dist/cli/bin.mjs +1 -1
  34. package/dist/cli/bin.mjs.map +1 -1
  35. package/dist/cli/index.cjs +1 -1
  36. package/dist/cli/index.mjs +1 -1
  37. package/dist/index.cjs +1 -1
  38. package/dist/index.cjs.map +1 -1
  39. package/dist/index.d.cts +6 -6
  40. package/dist/index.d.ts +6 -6
  41. package/dist/index.mjs +1 -1
  42. package/dist/index.mjs.map +1 -1
  43. package/dist/kanban/index.cjs +1 -1
  44. package/dist/kanban/index.mjs +1 -1
  45. package/dist/scrum/index.cjs +1 -1
  46. package/dist/scrum/index.mjs +1 -1
  47. package/dist/types.d.cts +30 -1
  48. package/dist/types.d.ts +30 -1
  49. package/dist/waterfall/index.cjs +2 -0
  50. package/dist/waterfall/index.cjs.map +1 -0
  51. package/dist/waterfall/index.d.cts +148 -0
  52. package/dist/waterfall/index.d.ts +148 -0
  53. package/dist/waterfall/index.mjs +2 -0
  54. package/dist/waterfall/index.mjs.map +1 -0
  55. package/package.json +14 -1
  56. package/dist/chunk-JDVE7DQR.cjs +0 -2
  57. package/dist/chunk-JDVE7DQR.cjs.map +0 -1
  58. package/dist/chunk-NQU5TH3A.mjs +0 -2
  59. package/dist/chunk-NQU5TH3A.mjs.map +0 -1
  60. package/dist/chunk-NRAPI3GV.cjs +0 -2
  61. package/dist/chunk-NRAPI3GV.cjs.map +0 -1
  62. package/dist/chunk-PD5FBDN7.mjs +0 -2
  63. package/dist/chunk-PD5FBDN7.mjs.map +0 -1
  64. package/dist/chunk-QDT35LXB.cjs +0 -2
  65. package/dist/chunk-QDT35LXB.cjs.map +0 -1
  66. package/dist/chunk-YJNDBKIG.mjs +0 -2
  67. package/dist/chunk-YJNDBKIG.mjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,6 +1,15 @@
1
1
  # Changelog
2
2
 
3
- ## 0.2.0-stage (unreleased)
3
+ ## 0.3.0-stage (unreleased)
4
+
5
+ Pre-release under the `stage` dist-tag.
6
+
7
+ - Waterfall module (`ex-workflow/waterfall`): ordered phases with deliverables and gates, kickoff / gateReview / changeControlBoard / phaseRetrospective ceremonies, human-approved baselines with versions (`state.baselines`), change-requests with impact analysis that reopen exactly the listed phases (and suspend a later open phase), bidirectional traceability with an engine-generated `traceability-matrix`, seven rules, and phase metrics from events (completion, budget variance, requirement coverage, defects per phase, change-request counts, rework weight).
8
+ - Core: `WorkItem.phase` / `impactAnalysis`, `Phase.budget` / `produced`, `WorkflowState.baselines`, planner hook `roleFor`, `Methodology.afterDecide` with `decide(..., methodology?)`, `item.added` payload carries `phase` and `parent`.
9
+ - CLI: `exwf init waterfall`; `add` and `edit` run through the methodology rules; `decide` runs the methodology's `afterDecide`; `status` prints the phase report.
10
+ - Size: `core+waterfall` measured and budgeted next to `core+scrum` and `core+kanban` (set at measured size; see size-budget.json).
11
+
12
+ ## 0.2.0-stage (2026-10-22)
4
13
 
5
14
  Pre-release under the `stage` dist-tag.
6
15
 
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # ex-workflow
2
2
 
3
- Methodology engine for AI teams. Scrum, Kanban and Waterfall (Scrum and Kanban today; Waterfall follows) are modelled as data (stages, roles, policies, gates, ceremonies) and driven by a pure state machine on top of the [`ex-flow`](https://www.npmjs.com/package/ex-flow) DAG planner. The program decides, the LLM executes: which item may move, who may approve, whether a sprint may close is enforced by the engine, not by a prompt.
3
+ Methodology engine for AI teams. Scrum, Kanban and Waterfall are modelled as data (stages, roles, policies, gates, ceremonies) and driven by a pure state machine on top of the [`ex-flow`](https://www.npmjs.com/package/ex-flow) DAG planner. The program decides, the LLM executes: which item may move, who may approve, whether a sprint may close is enforced by the engine, not by a prompt.
4
4
 
5
5
  State is plain JSON, every operation is `(state, action) -> state`, and every error names the rule, the item and a concrete fix. Core performs no I/O; a small file adapter and the `exwf` CLI sit on top. Runtime dependencies are exactly `ex-flow` and `exsorted`.
6
6
 
@@ -10,7 +10,7 @@ State is plain JSON, every operation is `(state, action) -> state`, and every er
10
10
  pnpm add ex-workflow@stage
11
11
  ```
12
12
 
13
- Pre-releases are published under the `stage` dist-tag (currently `0.2.0-stage`); `latest` is reserved for 0.1.0.
13
+ Pre-releases are published under the `stage` dist-tag (currently `0.3.0-stage`); `latest` is reserved for 0.1.0.
14
14
 
15
15
  Node >= 18. Runs on macOS, Linux and Windows.
16
16
 
@@ -65,20 +65,45 @@ 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
+ ### Waterfall
69
+
70
+ ```ts
71
+ import { init, addItem, applyAction, next, complete, decide } from "ex-workflow";
72
+ import { waterfall } from "ex-workflow/waterfall";
73
+
74
+ const m = waterfall();
75
+ let { state } = init({ methodology: m, config: {} }); // six classic phases, every gate human-approved
76
+ const r1 = { id: "R1", title: "login", phase: "requirements", acceptance: ["user can log in"] };
77
+ state = applyAction(state, m, { type: "item.add", by: "business-analyst", payload: { item: r1 } }, (s) =>
78
+ addItem(s, r1, "business-analyst"),
79
+ ).state;
80
+ state = m.ceremonies["kickoff"]!(state, { by: "project-manager", phase: "requirements" }).state;
81
+ // next() → complete() as with any methodology; items go work → review → done
82
+ state = m.ceremonies["gateReview"]!(state, { by: "project-manager", phase: "requirements" }).state; // pending decision
83
+ state = decide(state, state.pending[0]!.id, "approve", "human", "ok", undefined, m); // baselines the phase
84
+ ```
85
+
86
+ Phases open one at a time (`kickoff`), close through a gate (`gateReview`, human-approved by default) that
87
+ baselines their items, and reopen only through an approved change-request (`changeControlBoard`, with an
88
+ impact analysis). Requirements must trace to design and verification items before those gates; the engine
89
+ generates the `traceability-matrix` deliverable. Edits to baselined items are refused by the rules when
90
+ they go through `applyAction` or the CLI. `test/waterfall.e2e.test.ts` is a full project with a
91
+ change-request that reopens two baselined phases.
92
+
68
93
  ## CLI
69
94
 
70
95
  State lives in `.workflow/`. Every command prints JSON; errors exit 1, bad usage exits 2.
71
96
 
72
97
  | Command | Returns |
73
98
  |---|---|
74
- | `init <scrum\|kanban> --config <file> [--roles <file>]` | `{ ok, state: { methodology, stages, roles } }` |
75
- | `add <item.json>` | `{ ok, item }` |
76
- | `edit <id> <patch.json>` | `{ ok, item }` |
99
+ | `init <scrum\|kanban\|waterfall> --config <file> [--roles <file>]` | `{ ok, state: { methodology, stages, roles } }` |
100
+ | `add <item.json>` | `{ ok, warnings, item }` (checked by the methodology rules) |
101
+ | `edit <id> <patch.json>` | `{ ok, warnings, item }` (checked by the methodology rules) |
77
102
  | `next [--max n]` | `{ ok, reason, skipped, briefs }`; writes `.workflow/briefs/<id>.json` |
78
103
  | `complete <id> <handoff.json> --tokens-in n --tokens-out n --duration-ms n --model m [--role r]` | `{ ok, item, warnings }` |
79
104
  | `ceremony <name> [input.json] [--by who]` | `{ ok, warnings, lastEvent }` |
80
- | `decide <pendingId> approve\|reject --by who [--note text]` | `{ ok, item }` |
81
- | `status` | `{ ok, methodology, openIteration, counts, pending, lastEvent, report }` (`report` is the methodology's own status, e.g. Kanban's cadences due; `null` for Scrum) |
105
+ | `decide <pendingId> approve\|reject --by who [--note text]` | `{ ok, item }` (runs the methodology's `afterDecide`, e.g. a Waterfall phase baseline) |
106
+ | `status` | `{ ok, methodology, openIteration, counts, pending, lastEvent, report }` (`report` is the methodology's own status: Kanban's cadences due, Waterfall's phases, pending gates and traceability coverage; `null` for Scrum) |
82
107
  | `board` | `{ ok, columns }` |
83
108
  | `metrics` | `{ ok, metrics }` |
84
109
  | `pending` / `lessons` | the arrays |
@@ -104,11 +129,11 @@ This package is L0. All layers read and write the same `.workflow/` files.
104
129
 
105
130
  ## Status
106
131
 
107
- 0.2.0-stage adds the Kanban module. Waterfall follows. Design: [docs/superpowers/specs/2026-10-19-ex-workflow-design.md](docs/superpowers/specs/2026-10-19-ex-workflow-design.md).
132
+ 0.3.0-stage adds the Waterfall module; all three methodologies ship. `ex-workflow/schema` is still pending. Design: [docs/superpowers/specs/2026-10-19-ex-workflow-design.md](docs/superpowers/specs/2026-10-19-ex-workflow-design.md).
108
133
 
109
134
  ## Known backlog
110
135
 
111
- Minor items deferred past 0.2.0-stage:
136
+ Minor items deferred past 0.3.0-stage:
112
137
 
113
138
  - Stale-lock takeover can race when a lock is older than 60 s.
114
139
  - `decide(approve)` ignores a `needs-review` verdict.
@@ -122,6 +147,10 @@ Minor items deferred past 0.2.0-stage:
122
147
  - Kanban `wipBypass` is the total number of extra slots a column grants while any expedite is active, not one per expedite.
123
148
  - Kanban cadences use `item.completed` counts as turns; a wall-clock cadence schedule is the host's job.
124
149
  - Minor test gaps: retro duplicate-ref rejection, `writeAtomic` failure path, thin CLI usage and `decide` tests.
150
+ - Waterfall traceability is keyed by phase ids, not item types (spec §10 wording); links are read in both directions.
151
+ - Waterfall `editItem`/`addItem` called directly (not through `applyAction` or the CLI) bypass `baseline-immutable`.
152
+ - Waterfall phase budgets reuse `Iteration`; `exwf status` shows the open phase as `openIteration`. With no accounting history the planner estimates 20000 tokens per weight unit, so a small phase budget dispatches nothing until `next({ fallbackTokensPerWeight })` is passed or history exists.
153
+ - Phase retrospective applies `agreement` lessons only; other suggested changes are stored for the host.
125
154
 
126
155
  ## Development gate
127
156
 
@@ -142,7 +171,7 @@ pnpm run ci && npm publish --tag stage
142
171
 
143
172
  ## Design principles
144
173
 
145
- 1. One engine, three methodologies (Scrum and Kanban today; Waterfall follows), 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).
174
+ 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).
146
175
  2. The program decides, the LLM executes. Which item may move, who may approve, whether a stage may start: engine, not prompt.
147
176
  3. Roles are data. Methodologies reference capabilities, never role names.
148
177
  4. Pure, serialisable state. Every operation is `(state, action) -> state` or `(state) -> view`. No I/O in core.
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs');function h(t){return t??new Date().toISOString()}function q(t){let e=new Set;for(let n of t.stages)e.has(n.id)&&chunkS3BXVHO7_cjs.b("config-invalid",`duplicate stage id "${n.id}"`,"give every stage a unique id"),e.add(n.id);let o={};for(let n of t.roles)chunkS3BXVHO7_cjs.c(n.id,"role id"),Object.hasOwn(o,n.id)&&chunkS3BXVHO7_cjs.b("duplicate-role",`duplicate role id "${n.id}"`,"give every role a unique id"),o[n.id]=n;let i=h(t.now);return {version:1,methodology:t.methodology,config:t.config,items:{},stages:t.stages,roles:o,iterations:[],events:[{seq:1,at:i,type:"state.created",by:"system",payload:{methodology:t.methodology}}],accounting:[],pending:[],lessons:[],agreements:[]}}function p(t,e,o,i,n){let s={seq:(t.events[t.events.length-1]?.seq??0)+1,at:h(n),type:e,by:o,payload:i};return {...t,events:[...t.events,s]}}function te(t,e){for(let o=t.events.length-1;o>=0;o--){let i=t.events[o];if(e===void 0||i.type===e)return i}}function R(t,e){return Object.hasOwn(t.roles,e)?t.roles[e]:void 0}var H=new Set(["in_progress","review","blocked"]);function re(t,e,o,i){chunkS3BXVHO7_cjs.c(e.id,"role id"),R(t,e.id)&&chunkS3BXVHO7_cjs.b("duplicate-role",`role "${e.id}" already exists`,`use a different id or retireRole("${e.id}") first`);let n={...t,roles:{...t.roles,[e.id]:e}};return p(n,"role.registered",o,{role:e.id,capabilities:e.capabilities},i)}function se(t,e,o,i){R(t,e)||chunkS3BXVHO7_cjs.b("unknown-role",`role "${e}" does not exist`,`registered roles: ${Object.keys(t.roles).join(", ")||"(none)"}`);let n=Object.values(t.items).filter(s=>s.role===e&&H.has(s.status)).map(s=>s.id);n.length&&chunkS3BXVHO7_cjs.b("role-has-open-items",`role "${e}" still holds ${n.length} open item(s)`,`complete or reassign ${n.join(", ")} before retiring the role`,{items:n});let r={...t.roles};return delete r[e],p({...t,roles:r},"role.retired",o,{role:e},i)}function x(t,e){return t.capabilities.includes(e)}function j(t,e){return Object.values(t.roles).filter(o=>x(o,e))}function v(t,e,o,i){return Object.values(t.roles).filter(n=>n.id!==i&&n.canApprove.includes(e)&&(o===void 0||n.capabilities.includes(o))).map(n=>n.id)}function ae(t,e){return j(t,"approve-gate").filter(o=>o.canApprove.includes(e))}function P(t,e,o){for(let i of e)j(t,i).length===0&&chunkS3BXVHO7_cjs.b("missing-capability",`no registered role has capability "${i}"`,`register a role whose capabilities include "${i}" (registerRole) before init`);for(let i of o){let n=j(t,i);n.length>1&&chunkS3BXVHO7_cjs.b("exclusive-capability",`capability "${i}" must belong to exactly one role but is held by ${n.map(r=>r.id).join(", ")}`,`remove "${i}" from all but one role`);}}function E(t,e){return e.length===0?[]:Object.values(t.roles).filter(o=>e.every(i=>x(o,i)))}function G(t,e,...o){if(e==="human")return true;let i=R(t,e);return !!i&&o.some(n=>x(i,n))}function le(t,e,...o){if(!G(t,e,...o)){let i=Object.values(t.roles).filter(n=>o.some(r=>x(n,r))).map(n=>n.id);chunkS3BXVHO7_cjs.b("missing-capability",`"${e}" lacks capability ${o.map(n=>`"${n}"`).join(" or ")}`,`run this as one of: human${i.map(n=>`, ${n}`).join("")}`);}}function I(t,e){let o=t.stages.find(i=>i.id===e);return o||chunkS3BXVHO7_cjs.b("unknown-stage",`stage "${e}" does not exist`,`stages are: ${t.stages.map(i=>i.id).join(" \u2192 ")}`),o}function K(t,e){let o=t.stages.findIndex(i=>i.id===e);return o<0&&I(t,e),t.stages[o+1]}function J(t,e){return t.stages[t.stages.length-1]?.id===e}function y(t,e){return {...t,items:{...t.items,[e.id]:e}}}function L(t,e,o){return y(t,o(w(t,e)))}function z(t,e,o){return L(t,e,i=>{let n={...i};for(let r of o)delete n[r];return n})}function w(t,e){let o=Object.hasOwn(t.items,e)?t.items[e]:void 0;return o||chunkS3BXVHO7_cjs.b("unknown-item",`item "${e}" does not exist`,`add it with addItem first; known items: ${Object.keys(t.items).join(", ")||"(none)"}`,{items:[e]}),o}function S(t,e,o){let i=e.filter(n=>!Object.hasOwn(t.items,n));i.length&&chunkS3BXVHO7_cjs.b("unknown-item",`${o} refers to unknown item(s) ${i.join(", ")}`,"add those items first or remove the reference",{items:i});}function ue(t,e,o,i){chunkS3BXVHO7_cjs.c(e.id,"item id"),Object.hasOwn(t.items,e.id)&&chunkS3BXVHO7_cjs.b("duplicate-item",`item "${e.id}" already exists`,"use editItem to change it, or pick a new id",{items:[e.id]});let n=t.stages[0];n||chunkS3BXVHO7_cjs.b("config-invalid","state has no stages","create the state with at least one stage");let r=e.stage??n.id;I(t,r),S(t,e.dependsOn??[],`item "${e.id}".dependsOn`),e.affects&&S(t,e.affects,`item "${e.id}".affects`),e.parent!==void 0&&S(t,[e.parent],`item "${e.id}".parent`),e.role!==void 0&&!Object.hasOwn(t.roles,e.role)&&chunkS3BXVHO7_cjs.b("unknown-role",`role "${e.role}" does not exist`,`registered roles: ${Object.keys(t.roles).join(", ")}`);let{stage:s,...a}=e,l={type:"task",acceptance:[],dependsOn:[],...a,id:e.id,title:e.title,stage:r,status:"todo",evidence:[],blockers:[],transitions:[]},c=y(t,l);return p(c,"item.added",o,{id:l.id,type:l.type,stage:l.stage,weight:l.weight??null,priority:l.priority??null,phase:l.phase??null,parent:l.parent??null},i)}function ge(t,e,o,i,n){let r=w(t,e);o.dependsOn&&S(t,o.dependsOn,`item "${e}".dependsOn`),o.affects&&S(t,o.affects,`item "${e}".affects`),o.parent!==void 0&&S(t,[o.parent],`item "${e}".parent`),o.role!==void 0&&!Object.hasOwn(t.roles,o.role)&&chunkS3BXVHO7_cjs.b("unknown-role",`role "${o.role}" does not exist`,`registered roles: ${Object.keys(t.roles).join(", ")}`);let s=Object.keys(o).filter(c=>JSON.stringify(o[c])!==JSON.stringify(r[c]));s.length===0&&chunkS3BXVHO7_cjs.b("no-op",`editItem("${e}") changes nothing`,"pass at least one field with a different value",{items:[e]});let a={...r};for(let c of s)a[c]=o[c];let l=y(t,a);return p(l,"item.edited",i,{id:e,changed:s},n)}function W(t,e,o,i,n){let r=w(t,e),s=o.stage??r.stage;I(t,s),(r.status==="done"||r.status==="dropped")&&chunkS3BXVHO7_cjs.b("invalid-transition",`item "${e}" is ${r.status} and cannot move`,"create a new item (or a change-request) instead of reopening a finished one",{items:[e]}),s===r.stage&&o.status===r.status&&chunkS3BXVHO7_cjs.b("no-op",`item "${e}" is already ${r.status} in "${s}"`,"choose a different stage or status",{items:[e]});let a=h(n),l={...r,stage:s,status:o.status,transitions:[...r.transitions,{from:{stage:r.stage,status:r.status},to:{stage:s,status:o.status},at:a,by:i}]},c=y(t,l);return p(c,"item.transition",i,{id:e,from:{stage:r.stage,status:r.status},to:{stage:s,status:o.status}},a)}function pe(t,e,o,i){let n=w(t,e),r=h(i),s={...n,evidence:[...n.evidence,{...o,at:r}]},a=y(t,s);return p(a,"item.evidence",o.by,{id:e,kind:o.kind,ref:o.ref},r)}function V(t,e,o,i,n,r){let s=w(t,e),a=h(r),l=`${e}-b${s.blockers.length+1}`,c=s.status==="blocked"?null:{from:{stage:s.stage,status:s.status},to:{stage:s.stage,status:"blocked"},at:a,by:n},g={...s,status:"blocked",blockers:[...s.blockers,{id:l,reason:o,owner:i,raisedAt:a}],transitions:c?[...s.transitions,c]:s.transitions},u=y(t,g);return p(u,"blocker.raised",n,{id:e,blocker:l,reason:o,owner:i,transition:c&&{from:c.from,to:c.to}},a)}function M(t,e){for(let o=t.transitions.length-1;o>=0;o--){let i=t.transitions[o];if(i.to.status===e)return i}}function me(t,e,o,i,n){let r=w(t,e),s=r.blockers.findIndex(k=>k.id===o&&!k.clearedAt);s<0&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${e}" has no open blocker "${o}"`,`open blockers: ${r.blockers.filter(k=>!k.clearedAt).map(k=>k.id).join(", ")||"(none)"}`,{items:[e]});let a=h(n),l=r.blockers.map((k,F)=>F===s?{...k,clearedAt:a}:k),c=l.some(k=>!k.clearedAt),g=M(r,"blocked")?.from.status??"todo",u=r.stage,f=g,m=false;g==="in_progress"?(f="todo",u=M(r,"in_progress")?.from.stage??r.stage):g==="awaiting_human"&&(f=I(t,r.stage).review?"review":"todo",m=true);let{role:O,...N}=r,b=c?null:{from:{stage:r.stage,status:"blocked"},to:{stage:u,status:f},at:a,by:i},B={...m&&!c?N:r,blockers:l,stage:c?r.stage:u,status:c?"blocked":f,transitions:b?[...r.transitions,b]:r.transitions},D=y(t,B);return p(D,"blocker.cleared",i,{id:e,blocker:o,transition:b&&{from:b.from,to:b.to}},a)}function A(t,e){return z(t,e,["role"])}function _(t,e,o,i,n){let r=w(t,e),s=K(t,r.stage);if(!s)return W(t,e,{status:"done"},o,n);if(J(t,s.id))return W(t,e,{stage:s.id,status:"done"},o,n);let a=i||s.review===true?"review":"todo";return A(W(t,e,{stage:s.id,status:a},o,n),e)}function Q(t,e,o){let i=[],n=(r,s,a)=>i.push({rule:r,severity:"error",item:e.id,message:s,fix:a});for(let r of o)switch(r.kind){case "evidence":e.evidence.some(s=>s.kind===r.evidenceKind)||n("policy:evidence",`item "${e.id}" has no evidence of kind "${r.evidenceKind}"`,`attach evidence { kind: "${r.evidenceKind}" } via addEvidence or in the handoff.produced`);break;case "acceptance-written":e.acceptance.length===0&&n("policy:acceptance-written",`item "${e.id}" has no acceptance criteria`,"editItem with a non-empty acceptance[] (needs define-acceptance)");break;case "estimate-present":e.weight===void 0&&n("policy:estimate-present",`item "${e.id}" has no weight`,"editItem with a weight (story points)");break;case "no-open-blockers":{let s=e.blockers.filter(a=>!a.clearedAt);s.length&&n("policy:no-open-blockers",`item "${e.id}" has ${s.length} open blocker(s)`,`clearBlocker ${s.map(a=>a.id).join(", ")}`);break}case "dependencies-done":{let s=e.dependsOn.filter(a=>t.items[a]?.status!=="done");s.length&&n("policy:dependencies-done",`item "${e.id}" depends on unfinished ${s.join(", ")}`,`finish ${s.join(", ")} first`);break}case "custom":e.evidence.some(s=>s.kind===`policy:${r.id}`)||n(`policy:custom:${r.id}`,`item "${e.id}" has not satisfied "${r.description}"`,`attach evidence { kind: "policy:${r.id}" } when it is satisfied`);break}return i}function we(t,e,o,i){let n=Q(t,e,o);n.length&&chunkS3BXVHO7_cjs.b("policy-unmet",`item "${e.id}" cannot ${i}: ${n.length} polic${n.length===1?"y":"ies"} unmet`,n.map(r=>r.fix).join("; "),{items:[e.id]});}function U(t,e){let o=new Map(t.stages.map((n,r)=>[n.id,r])),i=o.get(e.stage);if(i!==void 0)for(let n=e.transitions.length-1;n>=0;n--){let r=e.transitions[n],s=o.get(r.from.stage);if(r.to.status==="in_progress"&&s!==void 0&&s<i)return r}}function C(t,e){let o=U(t,e);if(o)return o.by;for(let i=e.transitions.length-1;i>=0;i--){let n=e.transitions[i];if(n.to.status==="in_progress")return n.by}}function X(t,e,o,i){let n=[];for(let s of o.evidence)e.evidence.some(a=>a.kind===s)||n.push({rule:"gate:evidence",severity:"error",item:e.id,message:`gate "${o.id}" needs evidence "${s}" on item "${e.id}"`,fix:`attach evidence { kind: "${s}" } before approving`});if(n.length)return {outcome:"fail",violations:n};let r=false;for(let s of o.requires){if(s==="human"){i!=="human"&&(r=true);continue}if(!v(t,o.id,s.capability).includes(i)){n.push({rule:"gate:capability",severity:"error",item:e.id,message:`"${i}" may not approve gate "${o.id}" (needs capability "${s.capability}" and canApprove "${o.id}")`,fix:`approve as one of: ${v(t,o.id,s.capability).join(", ")||"(no role qualifies; register one)"}`});continue}let l=C(t,e);if(l!==void 0&&l===i){let c=v(t,o.id,s.capability,i);n.push({rule:"conflict-of-interest",severity:"error",item:e.id,message:`role "${i}" did the work on "${e.id}" and may not approve it`,fix:`approve as a different role: ${c.join(", ")||"(register another approver)"}`});}}return n.length?{outcome:"fail",violations:n}:r?{outcome:"human"}:{outcome:"pass"}}function be(t,e,o){let i=h(o),n=`p${t.events.filter(a=>a.type==="pending.raised").length+1}`,r={...e,id:n,raisedAt:i},s={...t,pending:[...t.pending,r]};return e.item&&w(s,e.item).status!=="awaiting_human"&&(s=W(s,e.item,{status:"awaiting_human"},"system",i)),p(s,"pending.raised","system",{id:n,kind:e.kind,item:e.item??null,gate:e.gate??null},i)}function xe(t,e,o,i,n,r,s){o!=="approve"&&o!=="reject"&&chunkS3BXVHO7_cjs.b("invalid-input",`decision must be "approve" or "reject" (got ${JSON.stringify(o)})`,"pass approve or reject");let a=t.pending.find(f=>f.id===e);a||chunkS3BXVHO7_cjs.b("unknown-pending",`no pending decision "${e}"`,`open decisions: ${t.pending.map(f=>f.id).join(", ")||"(none)"}`);let l=a.kind==="gate"&&a.item?w(t,a.item):void 0,c=l&&(t.stages.find(f=>a.gate!==void 0&&f.gate?.id===a.gate)?.gate??t.stages.find(f=>f.id===l.stage)?.gate);l&&c&&i!=="human"&&(c.requires.includes("human")?void 0:X(t,l,c,i))?.outcome!=="pass"&&chunkS3BXVHO7_cjs.b("gate-unmet",`"${i}" may not decide gate "${c.id}" on "${l.id}"`,`decide as one of: human${c.requires.flatMap(m=>m==="human"?[]:v(t,c.id,m.capability)).map(m=>`, ${m}`).join("")}`,{items:[l.id],rule:"gate"});let g=h(r),u={...t,pending:t.pending.filter(f=>f.id!==e)};if(u=p(u,"pending.decided",i,{id:e,decision:o,note:n,item:a.item??null,gate:a.gate??null},g),l){let f=l.id,m=a.gate??c?.id??null;if(o==="approve")u=_(u,f,i,false,g),u=p(u,"gate.passed",i,{item:f,gate:m},g);else {let O=c?.onFail??{action:"block"};O.action==="return-to"?u=A(W(u,f,{stage:O.stage,status:"todo"},i,g),f):u=V(u,f,`gate "${m??"?"}" rejected: ${n||"no reason given"}`,i,i,g),u=p(u,"gate.failed",i,{item:f,gate:m,note:n},g);}}return s?.afterDecide&&(u=s.afterDecide(u,a,o,i,n,g)),u}function T(t){return [{id:"separation-lost",severity:"warning",check(i,n){return n.type!=="init"&&n.type!=="role.register"?[]:E(i,t.requiredCapabilities).map(r=>({rule:"separation-lost",severity:"warning",message:`role "${r.id}" holds every required capability (${t.requiredCapabilities.join(", ")}); no separation of duties`,fix:"fine for a solo operator; otherwise split capabilities across roles"}))}},{id:"conflict-of-interest",severity:"error",check(i,n){if(n.type!=="complete")return [];let r=n.payload?.handoff;if(!r)return [];let s=r.verdict??"done";if(s!=="done"&&s!=="needs-review")return [];let a=i.items[r.item];if(!a)return [];let l=i.stages.find(g=>g.id===a.stage)?.gate;if(!l||!l.requires.some(g=>g!=="human"))return [];if(C(i,a)!==r.role)return [];let c=v(i,l.id,void 0,r.role);return [{rule:"conflict-of-interest",severity:"error",item:a.id,message:`role "${r.role}" authored "${a.id}" and may not pass gate "${l.id}" on it`,fix:`hand the gate to another approver: ${c.join(", ")||"(register one)"}`}]}}]}function Y(t,e,o){let i=[];for(let n of [...T(e),...e.rules])i.push(...n.check(t,o));return i}function Z(t,e,o,i){let n=Y(t,e,o),r=n.filter(s=>s.severity==="error");return r.length&&chunkS3BXVHO7_cjs.b("rule-violation",`${o.type} violates ${r.map(s=>s.rule).join(", ")}: ${r.map(s=>s.message).join("; ")}`,r.map(s=>s.fix).join("; "),{rule:r[0].rule,items:r.map(s=>s.item).filter(s=>!!s)}),{state:i(t),warnings:n.filter(s=>s.severity==="warning")}}function Ee(t){let e=t.methodology,o=e.validateConfig(t.config),i=t.stages??e.defaultStages(o),n=t.roles??e.defaultRoles(o),r=t.now!==void 0?{methodology:e.name,config:o,stages:i,roles:n,now:t.now}:{methodology:e.name,config:o,stages:i,roles:n},s=q(r);return P(s,e.requiredCapabilities,e.exclusiveCapabilities),Z(s,e,{type:"init",by:t.by??"system"},a=>a)}exports.A=me;exports.B=A;exports.C=_;exports.D=Q;exports.E=we;exports.F=U;exports.G=C;exports.H=X;exports.I=be;exports.J=xe;exports.K=T;exports.L=Y;exports.M=Z;exports.N=Ee;exports.a=h;exports.b=q;exports.c=p;exports.d=te;exports.e=R;exports.f=re;exports.g=se;exports.h=x;exports.i=j;exports.j=v;exports.k=ae;exports.l=P;exports.m=E;exports.n=G;exports.o=le;exports.p=I;exports.q=K;exports.r=J;exports.s=L;exports.t=z;exports.u=w;exports.v=ue;exports.w=ge;exports.x=W;exports.y=pe;exports.z=V;//# sourceMappingURL=chunk-23P7C25E.cjs.map
2
+ //# sourceMappingURL=chunk-23P7C25E.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/state.ts","../src/roles.ts","../src/items.ts","../src/policies.ts","../src/gates.ts","../src/rules.ts","../src/methodology.ts"],"names":["nowOf","now","createState","input","seenStages","st","fail","roles","r","assertId","at","appendEvent","state","type","by","payload","ev","lastEvent","i","roleOf","id","OPEN","registerRole","role","next","retireRole","roleId","open","hasCapability","cap","rolesWith","approverIds","gateId","except","approversFor","requireCapabilities","required","exclusive","holders","separationLost","c","canDo","caps","requireCap","h","stageOf","stageId","s","nextStageOf","idx","isTerminalStage","putItem","item","patchItem","fn","getItem","stripItemFields","keys","copy","k","it","assertKnownItems","ids","what","missing","d","addItem","firstStage","_s","rest","editItem","patch","changed","updated","moveItem","to","toStage","addEvidence","evidence","raiseBlocker","reason","owner","blockerId","t","lastTransitionTo","status","clearBlocker","b","blockers","stillBlocked","prev","toStatus","dropRole","_r","noRole","clearRole","itemId","advanceItem","wantsReview","evaluatePolicies","policies","out","v","rule","message","fix","p","e","notDone","assertPolicies","context","unmet","u","lastDispatchBefore","order","here","from","authorOf","before","checkGate","gate","violations","kind","needsHuman","req","author","others","raisePending","pending","entry","decide","pendingId","decision","note","methodology","item0","q","onFail","coreRulesFor","action","handoff","verdict","validateAction","applyAction","reduce","errors","x","init","m","config","stages","stateInput"],"mappings":"mEAGO,SAASA,CAAAA,CAAMC,EAAsB,CAC1C,OAAOA,GAAO,IAAI,IAAA,GAAO,WAAA,EAC3B,CAUO,SAASC,CAAAA,CAAYC,EAAwC,CAClE,IAAMC,EAAa,IAAI,GAAA,CACvB,IAAA,IAAWC,CAAAA,IAAMF,CAAAA,CAAM,MAAA,CACjBC,EAAW,GAAA,CAAIC,CAAAA,CAAG,EAAE,CAAA,EACtBC,mBAAAA,CAAK,iBAAkB,CAAA,oBAAA,EAAuBD,CAAAA,CAAG,EAAE,CAAA,CAAA,CAAA,CAAK,8BAA8B,CAAA,CACxFD,EAAW,GAAA,CAAIC,CAAAA,CAAG,EAAE,CAAA,CAEtB,IAAME,EAA8B,EAAC,CACrC,IAAA,IAAWC,CAAAA,IAAKL,CAAAA,CAAM,KAAA,CACpBM,oBAASD,CAAAA,CAAE,EAAA,CAAI,SAAS,CAAA,CACpB,MAAA,CAAO,OAAOD,CAAAA,CAAOC,CAAAA,CAAE,EAAE,CAAA,EAC3BF,mBAAAA,CAAK,iBAAkB,CAAA,mBAAA,EAAsBE,CAAAA,CAAE,EAAE,CAAA,CAAA,CAAA,CAAK,6BAA6B,EACrFD,CAAAA,CAAMC,CAAAA,CAAE,EAAE,CAAA,CAAIA,CAAAA,CAEhB,IAAME,EAAKV,CAAAA,CAAMG,CAAAA,CAAM,GAAG,CAAA,CAC1B,OAAO,CACL,OAAA,CAAS,CAAA,CACT,WAAA,CAAaA,CAAAA,CAAM,WAAA,CACnB,MAAA,CAAQA,EAAM,MAAA,CACd,KAAA,CAAO,EAAC,CACR,MAAA,CAAQA,EAAM,MAAA,CACd,KAAA,CAAAI,CAAAA,CACA,UAAA,CAAY,EAAC,CACb,OAAQ,CACN,CACE,IA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chunk-23P7C25E.cjs","sourcesContent":["import { assertId, fail } from \"./errors.ts\";\nimport type { Event, MethodologyName, Role, Stage, WorkflowState } from \"./types.ts\";\n\nexport function nowOf(now?: string): string {\n return now ?? new Date().toISOString();\n}\n\nexport interface CreateStateInput {\n methodology: MethodologyName;\n config: unknown;\n stages: Stage[];\n roles: Role[];\n now?: string;\n}\n\nexport function createState(input: CreateStateInput): WorkflowState {\n const seenStages = new Set<string>();\n for (const st of input.stages) {\n if (seenStages.has(st.id))\n fail(\"config-invalid\", `duplicate stage id \"${st.id}\"`, \"give every stage a unique id\");\n seenStages.add(st.id);\n }\n const roles: Record<string, Role> = {};\n for (const r of input.roles) {\n assertId(r.id, \"role id\");\n if (Object.hasOwn(roles, r.id))\n fail(\"duplicate-role\", `duplicate role id \"${r.id}\"`, \"give every role a unique id\");\n roles[r.id] = r;\n }\n const at = nowOf(input.now);\n return {\n version: 1,\n methodology: input.methodology,\n config: input.config,\n items: {},\n stages: input.stages,\n roles,\n iterations: [],\n events: [\n {\n seq: 1,\n at,\n type: \"state.created\",\n by: \"system\",\n payload: { methodology: input.methodology },\n },\n ],\n accounting: [],\n pending: [],\n lessons: [],\n agreements: [],\n };\n}\n\nexport function appendEvent(\n state: WorkflowState,\n type: string,\n by: string,\n payload: unknown,\n now?: string,\n): WorkflowState {\n const last = state.events[state.events.length - 1];\n const ev: Event = { seq: (last?.seq ?? 0) + 1, at: nowOf(now), type, by, payload };\n return { ...state, events: [...state.events, ev] };\n}\n\nexport function lastEvent(state: WorkflowState, type?: string): Event | undefined {\n for (let i = state.events.length - 1; i >= 0; i--) {\n const ev = state.events[i]!;\n if (type === undefined || ev.type === type) return ev;\n }\n return undefined;\n}\n","import { assertId, fail } from \"./errors.ts\";\nimport { appendEvent } from \"./state.ts\";\nimport type { Capability, Role, WorkflowState } from \"./types.ts\";\n\n/** Own-property role lookup (ids such as \"constructor\" never hit the prototype). */\nexport function roleOf(state: WorkflowState, id: string): Role | undefined {\n return Object.hasOwn(state.roles, id) ? state.roles[id] : undefined;\n}\n\nconst OPEN: ReadonlySet<string> = new Set([\"in_progress\", \"review\", \"blocked\"]);\n\nexport function registerRole(\n state: WorkflowState,\n role: Role,\n by: string,\n now?: string,\n): WorkflowState {\n assertId(role.id, \"role id\");\n if (roleOf(state, role.id))\n fail(\n \"duplicate-role\",\n `role \"${role.id}\" already exists`,\n `use a different id or retireRole(\"${role.id}\") first`,\n );\n const next = { ...state, roles: { ...state.roles, [role.id]: role } };\n return appendEvent(\n next,\n \"role.registered\",\n by,\n { role: role.id, capabilities: role.capabilities },\n now,\n );\n}\n\nexport function retireRole(\n state: WorkflowState,\n roleId: string,\n by: string,\n now?: string,\n): WorkflowState {\n if (!roleOf(state, roleId))\n fail(\n \"unknown-role\",\n `role \"${roleId}\" does not exist`,\n `registered roles: ${Object.keys(state.roles).join(\", \") || \"(none)\"}`,\n );\n const open = Object.values(state.items)\n .filter((i) => i.role === roleId && OPEN.has(i.status))\n .map((i) => i.id);\n if (open.length)\n fail(\n \"role-has-open-items\",\n `role \"${roleId}\" still holds ${open.length} open item(s)`,\n `complete or reassign ${open.join(\", \")} before retiring the role`,\n { items: open },\n );\n const roles = { ...state.roles };\n delete roles[roleId];\n return appendEvent({ ...state, roles }, \"role.retired\", by, { role: roleId }, now);\n}\n\nexport function hasCapability(role: Role, cap: Capability): boolean {\n return role.capabilities.includes(cap);\n}\n\nexport function rolesWith(state: WorkflowState, cap: Capability): Role[] {\n return Object.values(state.roles).filter((r) => hasCapability(r, cap));\n}\n\n/** Ids of roles that may approve `gateId`, optionally holding `cap` and excluding one id. */\nexport function approverIds(\n state: WorkflowState,\n gateId: string,\n cap?: string,\n except?: string,\n): string[] {\n return Object.values(state.roles)\n .filter(\n (r) =>\n r.id !== except &&\n r.canApprove.includes(gateId) &&\n (cap === undefined || (r.capabilities as readonly string[]).includes(cap)),\n )\n .map((r) => r.id);\n}\n\nexport function approversFor(state: WorkflowState, gateId: string): Role[] {\n return rolesWith(state, \"approve-gate\").filter((r) => r.canApprove.includes(gateId));\n}\n\nexport function requireCapabilities(\n state: WorkflowState,\n required: Capability[],\n exclusive: Capability[],\n): void {\n for (const cap of required) {\n if (rolesWith(state, cap).length === 0) {\n fail(\n \"missing-capability\",\n `no registered role has capability \"${cap}\"`,\n `register a role whose capabilities include \"${cap}\" (registerRole) before init`,\n );\n }\n }\n for (const cap of exclusive) {\n const holders = rolesWith(state, cap);\n if (holders.length > 1) {\n fail(\n \"exclusive-capability\",\n `capability \"${cap}\" must belong to exactly one role but is held by ${holders.map((r) => r.id).join(\", \")}`,\n `remove \"${cap}\" from all but one role`,\n );\n }\n }\n}\n\nexport function separationLost(state: WorkflowState, required: Capability[]): Role[] {\n if (required.length === 0) return [];\n return Object.values(state.roles).filter((r) => required.every((c) => hasCapability(r, c)));\n}\n\n/** `human` may do anything; a role must hold at least one of `caps`; unknown ids may do nothing. */\nexport function canDo(state: WorkflowState, by: string, ...caps: Capability[]): boolean {\n if (by === \"human\") return true;\n const role = roleOf(state, by);\n return !!role && caps.some((c) => hasCapability(role, c));\n}\n\nexport function requireCap(state: WorkflowState, by: string, ...caps: Capability[]): void {\n if (!canDo(state, by, ...caps)) {\n const holders = Object.values(state.roles)\n .filter((r) => caps.some((c) => hasCapability(r, c)))\n .map((r) => r.id);\n fail(\n \"missing-capability\",\n `\"${by}\" lacks capability ${caps.map((c) => `\"${c}\"`).join(\" or \")}`,\n `run this as one of: human${holders.map((h) => `, ${h}`).join(\"\")}`,\n );\n }\n}\n","import { assertId, fail } from \"./errors.ts\";\n\nexport { assertId };\nimport { appendEvent, nowOf } from \"./state.ts\";\nimport type {\n Evidence,\n ItemStatus,\n NewItem,\n Stage,\n Transition,\n WorkItem,\n WorkflowState,\n} from \"./types.ts\";\n\nexport function stageOf(state: WorkflowState, stageId: string): Stage {\n const st = state.stages.find((s) => s.id === stageId);\n if (!st)\n fail(\n \"unknown-stage\",\n `stage \"${stageId}\" does not exist`,\n `stages are: ${state.stages.map((s) => s.id).join(\" → \")}`,\n );\n return st;\n}\n\nexport function nextStageOf(state: WorkflowState, stageId: string): Stage | undefined {\n const idx = state.stages.findIndex((s) => s.id === stageId);\n if (idx < 0) stageOf(state, stageId);\n return state.stages[idx + 1];\n}\n\nexport function isTerminalStage(state: WorkflowState, stageId: string): boolean {\n return state.stages[state.stages.length - 1]?.id === stageId;\n}\n\nfunction putItem(state: WorkflowState, item: WorkItem): WorkflowState {\n return { ...state, items: { ...state.items, [item.id]: item } };\n}\n\n/** Replace one item with `fn(item)`; no event. */\nexport function patchItem(\n state: WorkflowState,\n id: string,\n fn: (item: WorkItem) => WorkItem,\n): WorkflowState {\n return putItem(state, fn(getItem(state, id)));\n}\n\n/** Drop optional fields (iteration, role, ...) from one item; no event. */\nexport function stripItemFields(\n state: WorkflowState,\n id: string,\n keys: Array<\"iteration\" | \"role\">,\n): WorkflowState {\n return patchItem(state, id, (item) => {\n const copy = { ...item };\n for (const k of keys) delete copy[k];\n return copy;\n });\n}\n\nexport function getItem(state: WorkflowState, id: string): WorkItem {\n const it = Object.hasOwn(state.items, id) ? state.items[id] : undefined;\n if (!it)\n fail(\n \"unknown-item\",\n `item \"${id}\" does not exist`,\n `add it with addItem first; known items: ${Object.keys(state.items).join(\", \") || \"(none)\"}`,\n { items: [id] },\n );\n return it;\n}\n\nfunction assertKnownItems(state: WorkflowState, ids: string[], what: string): void {\n const missing = ids.filter((d) => !Object.hasOwn(state.items, d));\n if (missing.length)\n fail(\n \"unknown-item\",\n `${what} refers to unknown item(s) ${missing.join(\", \")}`,\n \"add those items first or remove the reference\",\n { items: missing },\n );\n}\n\nexport function addItem(\n state: WorkflowState,\n input: NewItem,\n by: string,\n now?: string,\n): WorkflowState {\n assertId(input.id, \"item id\");\n if (Object.hasOwn(state.items, input.id))\n fail(\n \"duplicate-item\",\n `item \"${input.id}\" already exists`,\n \"use editItem to change it, or pick a new id\",\n { items: [input.id] },\n );\n const firstStage = state.stages[0];\n if (!firstStage)\n fail(\"config-invalid\", \"state has no stages\", \"create the state with at least one stage\");\n const stageId = input.stage ?? firstStage.id;\n stageOf(state, stageId);\n assertKnownItems(state, input.dependsOn ?? [], `item \"${input.id}\".dependsOn`);\n if (input.affects) assertKnownItems(state, input.affects, `item \"${input.id}\".affects`);\n if (input.parent !== undefined)\n assertKnownItems(state, [input.parent], `item \"${input.id}\".parent`);\n if (input.role !== undefined && !Object.hasOwn(state.roles, input.role))\n fail(\n \"unknown-role\",\n `role \"${input.role}\" does not exist`,\n `registered roles: ${Object.keys(state.roles).join(\", \")}`,\n );\n\n const { stage: _s, ...rest } = input;\n const item: WorkItem = {\n type: \"task\",\n acceptance: [],\n dependsOn: [],\n ...rest,\n id: input.id,\n title: input.title,\n stage: stageId,\n status: \"todo\",\n evidence: [],\n blockers: [],\n transitions: [],\n };\n const next = putItem(state, item);\n return appendEvent(\n next,\n \"item.added\",\n by,\n {\n id: item.id,\n type: item.type,\n stage: item.stage,\n weight: item.weight ?? null,\n priority: item.priority ?? null,\n phase: item.phase ?? null,\n parent: item.parent ?? null,\n },\n now,\n );\n}\n\nexport type ItemPatch = Partial<\n Omit<WorkItem, \"id\" | \"stage\" | \"status\" | \"transitions\" | \"evidence\" | \"blockers\">\n>;\n\nexport function editItem(\n state: WorkflowState,\n id: string,\n patch: ItemPatch,\n by: string,\n now?: string,\n): WorkflowState {\n const item = getItem(state, id);\n if (patch.dependsOn) assertKnownItems(state, patch.dependsOn, `item \"${id}\".dependsOn`);\n if (patch.affects) assertKnownItems(state, patch.affects, `item \"${id}\".affects`);\n if (patch.parent !== undefined) assertKnownItems(state, [patch.parent], `item \"${id}\".parent`);\n if (patch.role !== undefined && !Object.hasOwn(state.roles, patch.role))\n fail(\n \"unknown-role\",\n `role \"${patch.role}\" does not exist`,\n `registered roles: ${Object.keys(state.roles).join(\", \")}`,\n );\n const changed = (Object.keys(patch) as Array<keyof ItemPatch>).filter(\n (k) => JSON.stringify(patch[k]) !== JSON.stringify(item[k]),\n );\n if (changed.length === 0)\n fail(\n \"no-op\",\n `editItem(\"${id}\") changes nothing`,\n \"pass at least one field with a different value\",\n { items: [id] },\n );\n const updated: WorkItem = { ...item };\n for (const k of changed) (updated as unknown as Record<string, unknown>)[k] = patch[k];\n const next = putItem(state, updated);\n return appendEvent(next, \"item.edited\", by, { id, changed }, now);\n}\n\nexport function moveItem(\n state: WorkflowState,\n id: string,\n to: { stage?: string; status: ItemStatus },\n by: string,\n now?: string,\n): WorkflowState {\n const item = getItem(state, id);\n const toStage = to.stage ?? item.stage;\n stageOf(state, toStage);\n if (item.status === \"done\" || item.status === \"dropped\") {\n fail(\n \"invalid-transition\",\n `item \"${id}\" is ${item.status} and cannot move`,\n \"create a new item (or a change-request) instead of reopening a finished one\",\n { items: [id] },\n );\n }\n if (toStage === item.stage && to.status === item.status)\n fail(\n \"no-op\",\n `item \"${id}\" is already ${item.status} in \"${toStage}\"`,\n \"choose a different stage or status\",\n { items: [id] },\n );\n const at = nowOf(now);\n const updated: WorkItem = {\n ...item,\n stage: toStage,\n status: to.status,\n transitions: [\n ...item.transitions,\n {\n from: { stage: item.stage, status: item.status },\n to: { stage: toStage, status: to.status },\n at,\n by,\n },\n ],\n };\n const next = putItem(state, updated);\n return appendEvent(\n next,\n \"item.transition\",\n by,\n {\n id,\n from: { stage: item.stage, status: item.status },\n to: { stage: toStage, status: to.status },\n },\n at,\n );\n}\n\nexport function addEvidence(\n state: WorkflowState,\n id: string,\n evidence: Omit<Evidence, \"at\">,\n now?: string,\n): WorkflowState {\n const item = getItem(state, id);\n const at = nowOf(now);\n const updated: WorkItem = { ...item, evidence: [...item.evidence, { ...evidence, at }] };\n const next = putItem(state, updated);\n return appendEvent(\n next,\n \"item.evidence\",\n evidence.by,\n { id, kind: evidence.kind, ref: evidence.ref },\n at,\n );\n}\n\nexport function raiseBlocker(\n state: WorkflowState,\n id: string,\n reason: string,\n owner: string,\n by: string,\n now?: string,\n): WorkflowState {\n const item = getItem(state, id);\n const at = nowOf(now);\n const blockerId = `${id}-b${item.blockers.length + 1}`;\n const t: Transition | null =\n item.status === \"blocked\"\n ? null\n : {\n from: { stage: item.stage, status: item.status },\n to: { stage: item.stage, status: \"blocked\" },\n at,\n by,\n };\n const updated: WorkItem = {\n ...item,\n status: \"blocked\",\n blockers: [...item.blockers, { id: blockerId, reason, owner, raisedAt: at }],\n transitions: t ? [...item.transitions, t] : item.transitions,\n };\n const next = putItem(state, updated);\n return appendEvent(\n next,\n \"blocker.raised\",\n by,\n { id, blocker: blockerId, reason, owner, transition: t && { from: t.from, to: t.to } },\n at,\n );\n}\n\nfunction lastTransitionTo(item: WorkItem, status: ItemStatus): Transition | undefined {\n for (let i = item.transitions.length - 1; i >= 0; i--) {\n const t = item.transitions[i]!;\n if (t.to.status === status) return t;\n }\n return undefined;\n}\n\nexport function clearBlocker(\n state: WorkflowState,\n id: string,\n blockerId: string,\n by: string,\n now?: string,\n): WorkflowState {\n const item = getItem(state, id);\n const idx = item.blockers.findIndex((b) => b.id === blockerId && !b.clearedAt);\n if (idx < 0)\n fail(\n \"invalid-input\",\n `item \"${id}\" has no open blocker \"${blockerId}\"`,\n `open blockers: ${\n item.blockers\n .filter((b) => !b.clearedAt)\n .map((b) => b.id)\n .join(\", \") || \"(none)\"\n }`,\n { items: [id] },\n );\n const at = nowOf(now);\n const blockers = item.blockers.map((b, i) => (i === idx ? { ...b, clearedAt: at } : b));\n const stillBlocked = blockers.some((b) => !b.clearedAt);\n const prev = lastTransitionTo(item, \"blocked\")?.from.status ?? \"todo\";\n let toStage = item.stage;\n let toStatus: ItemStatus = prev;\n let dropRole = false;\n if (prev === \"in_progress\") {\n toStatus = \"todo\";\n toStage = lastTransitionTo(item, \"in_progress\")?.from.stage ?? item.stage;\n } else if (prev === \"awaiting_human\") {\n // a rejected human gate: the work is re-dispatched in the current stage\n toStatus = stageOf(state, item.stage).review ? \"review\" : \"todo\";\n dropRole = true;\n }\n const { role: _r, ...noRole } = item;\n const t: Transition | null = stillBlocked\n ? null\n : {\n from: { stage: item.stage, status: \"blocked\" },\n to: { stage: toStage, status: toStatus },\n at,\n by,\n };\n const updated: WorkItem = {\n ...(dropRole && !stillBlocked ? (noRole as WorkItem) : item),\n blockers,\n stage: stillBlocked ? item.stage : toStage,\n status: stillBlocked ? \"blocked\" : toStatus,\n transitions: t ? [...item.transitions, t] : item.transitions,\n };\n const next = putItem(state, updated);\n return appendEvent(\n next,\n \"blocker.cleared\",\n by,\n { id, blocker: blockerId, transition: t && { from: t.from, to: t.to } },\n at,\n );\n}\n\n/** Entering a new stage is a new assignment: the role that finished the previous stage is cleared so the planner picks the right one (a reviewer, not the author). */\nexport function clearRole(state: WorkflowState, itemId: string): WorkflowState {\n return stripItemFields(state, itemId, [\"role\"]);\n}\n\n/** Move an item to the next stage (done at the end, review/todo otherwise) and clear its role. */\nexport function advanceItem(\n state: WorkflowState,\n itemId: string,\n by: string,\n wantsReview: boolean,\n now: string,\n): WorkflowState {\n const item = getItem(state, itemId);\n const to = nextStageOf(state, item.stage);\n if (!to) return moveItem(state, itemId, { status: \"done\" }, by, now);\n if (isTerminalStage(state, to.id))\n return moveItem(state, itemId, { stage: to.id, status: \"done\" }, by, now);\n const status = wantsReview || to.review === true ? \"review\" : \"todo\";\n return clearRole(moveItem(state, itemId, { stage: to.id, status }, by, now), itemId);\n}\n","import { fail } from \"./errors.ts\";\nimport type { Policy, Violation, WorkItem, WorkflowState } from \"./types.ts\";\n\nexport function evaluatePolicies(\n state: WorkflowState,\n item: WorkItem,\n policies: Policy[],\n): Violation[] {\n const out: Violation[] = [];\n const v = (rule: string, message: string, fix: string) =>\n out.push({ rule, severity: \"error\", item: item.id, message, fix });\n for (const p of policies) {\n switch (p.kind) {\n case \"evidence\":\n if (!item.evidence.some((e) => e.kind === p.evidenceKind))\n v(\n \"policy:evidence\",\n `item \"${item.id}\" has no evidence of kind \"${p.evidenceKind}\"`,\n `attach evidence { kind: \"${p.evidenceKind}\" } via addEvidence or in the handoff.produced`,\n );\n break;\n case \"acceptance-written\":\n if (item.acceptance.length === 0)\n v(\n \"policy:acceptance-written\",\n `item \"${item.id}\" has no acceptance criteria`,\n \"editItem with a non-empty acceptance[] (needs define-acceptance)\",\n );\n break;\n case \"estimate-present\":\n if (item.weight === undefined)\n v(\n \"policy:estimate-present\",\n `item \"${item.id}\" has no weight`,\n \"editItem with a weight (story points)\",\n );\n break;\n case \"no-open-blockers\": {\n const open = item.blockers.filter((b) => !b.clearedAt);\n if (open.length)\n v(\n \"policy:no-open-blockers\",\n `item \"${item.id}\" has ${open.length} open blocker(s)`,\n `clearBlocker ${open.map((b) => b.id).join(\", \")}`,\n );\n break;\n }\n case \"dependencies-done\": {\n const notDone = item.dependsOn.filter((d) => state.items[d]?.status !== \"done\");\n if (notDone.length)\n v(\n \"policy:dependencies-done\",\n `item \"${item.id}\" depends on unfinished ${notDone.join(\", \")}`,\n `finish ${notDone.join(\", \")} first`,\n );\n break;\n }\n case \"custom\":\n if (!item.evidence.some((e) => e.kind === `policy:${p.id}`))\n v(\n `policy:custom:${p.id}`,\n `item \"${item.id}\" has not satisfied \"${p.description}\"`,\n `attach evidence { kind: \"policy:${p.id}\" } when it is satisfied`,\n );\n break;\n }\n }\n return out;\n}\n\nexport function assertPolicies(\n state: WorkflowState,\n item: WorkItem,\n policies: Policy[],\n context: string,\n): void {\n const unmet = evaluatePolicies(state, item, policies);\n if (unmet.length) {\n fail(\n \"policy-unmet\",\n `item \"${item.id}\" cannot ${context}: ${unmet.length} polic${unmet.length === 1 ? \"y\" : \"ies\"} unmet`,\n unmet.map((u) => u.fix).join(\"; \"),\n { items: [item.id] },\n );\n }\n}\n","import { fail } from \"./errors.ts\";\nimport { advanceItem, clearRole, getItem, moveItem, raiseBlocker } from \"./items.ts\";\nimport { approverIds } from \"./roles.ts\";\nimport { appendEvent, nowOf } from \"./state.ts\";\nimport type {\n Gate,\n Methodology,\n PendingHuman,\n Transition,\n Violation,\n WorkItem,\n WorkflowState,\n} from \"./types.ts\";\n\nexport type GateResult =\n | { outcome: \"pass\" }\n | { outcome: \"human\" }\n | { outcome: \"fail\"; violations: Violation[] };\n\n/** Last in_progress dispatch made from a stage that comes STRICTLY BEFORE the item's current stage in `state.stages` order (unknown stage ids count as not-before). */\nexport function lastDispatchBefore(state: WorkflowState, item: WorkItem): Transition | undefined {\n const order = new Map(state.stages.map((s, i) => [s.id, i] as const));\n const here = order.get(item.stage);\n if (here === undefined) return undefined;\n for (let i = item.transitions.length - 1; i >= 0; i--) {\n const t = item.transitions[i]!;\n const from = order.get(t.from.stage);\n if (t.to.status === \"in_progress\" && from !== undefined && from < here) return t;\n }\n return undefined;\n}\n\n/** Role that did the work the gate guards: the last dispatch made from a stage strictly before the current one (so a reviewer dispatched into the gated stage is not its author); else the last dispatch of any stage; undefined if never dispatched. */\nexport function authorOf(state: WorkflowState, item: WorkItem): string | undefined {\n const before = lastDispatchBefore(state, item);\n if (before) return before.by;\n for (let i = item.transitions.length - 1; i >= 0; i--) {\n const t = item.transitions[i]!;\n if (t.to.status === \"in_progress\") return t.by;\n }\n return undefined;\n}\n\nexport function checkGate(\n state: WorkflowState,\n item: WorkItem,\n gate: Gate,\n by: string,\n): GateResult {\n const violations: Violation[] = [];\n for (const kind of gate.evidence) {\n if (!item.evidence.some((e) => e.kind === kind)) {\n violations.push({\n rule: \"gate:evidence\",\n severity: \"error\",\n item: item.id,\n message: `gate \"${gate.id}\" needs evidence \"${kind}\" on item \"${item.id}\"`,\n fix: `attach evidence { kind: \"${kind}\" } before approving`,\n });\n }\n }\n if (violations.length) return { outcome: \"fail\", violations };\n\n let needsHuman = false;\n for (const req of gate.requires) {\n if (req === \"human\") {\n if (by !== \"human\") needsHuman = true;\n continue;\n }\n const ok = approverIds(state, gate.id, req.capability).includes(by);\n if (!ok) {\n violations.push({\n rule: \"gate:capability\",\n severity: \"error\",\n item: item.id,\n message: `\"${by}\" may not approve gate \"${gate.id}\" (needs capability \"${req.capability}\" and canApprove \"${gate.id}\")`,\n fix: `approve as one of: ${approverIds(state, gate.id, req.capability).join(\", \") || \"(no role qualifies; register one)\"}`,\n });\n continue;\n }\n const author = authorOf(state, item);\n if (author !== undefined && author === by) {\n const others = approverIds(state, gate.id, req.capability, by);\n violations.push({\n rule: \"conflict-of-interest\",\n severity: \"error\",\n item: item.id,\n message: `role \"${by}\" did the work on \"${item.id}\" and may not approve it`,\n fix: `approve as a different role: ${others.join(\", \") || \"(register another approver)\"}`,\n });\n }\n }\n if (violations.length) return { outcome: \"fail\", violations };\n return needsHuman ? { outcome: \"human\" } : { outcome: \"pass\" };\n}\n\nexport function raisePending(\n state: WorkflowState,\n pending: Omit<PendingHuman, \"id\" | \"raisedAt\">,\n now?: string,\n): WorkflowState {\n const at = nowOf(now);\n const id = `p${state.events.filter((e) => e.type === \"pending.raised\").length + 1}`;\n const entry: PendingHuman = { ...pending, id, raisedAt: at };\n let next: WorkflowState = { ...state, pending: [...state.pending, entry] };\n if (pending.item) {\n const item = getItem(next, pending.item);\n if (item.status !== \"awaiting_human\")\n next = moveItem(next, pending.item, { status: \"awaiting_human\" }, \"system\", at);\n }\n return appendEvent(\n next,\n \"pending.raised\",\n \"system\",\n { id, kind: pending.kind, item: pending.item ?? null, gate: pending.gate ?? null },\n at,\n );\n}\n\nexport function decide(\n state: WorkflowState,\n pendingId: string,\n decision: \"approve\" | \"reject\",\n by: string,\n note: string,\n now?: string,\n methodology?: Methodology,\n): WorkflowState {\n if (decision !== \"approve\" && decision !== \"reject\")\n fail(\n \"invalid-input\",\n `decision must be \"approve\" or \"reject\" (got ${JSON.stringify(decision)})`,\n \"pass approve or reject\",\n );\n const entry = state.pending.find((p) => p.id === pendingId);\n if (!entry)\n fail(\n \"unknown-pending\",\n `no pending decision \"${pendingId}\"`,\n `open decisions: ${state.pending.map((p) => p.id).join(\", \") || \"(none)\"}`,\n );\n const item0 = entry.kind === \"gate\" && entry.item ? getItem(state, entry.item) : undefined;\n const gate =\n item0 &&\n (state.stages.find((s) => entry.gate !== undefined && s.gate?.id === entry.gate)?.gate ??\n state.stages.find((s) => s.id === item0.stage)?.gate);\n if (item0 && gate && by !== \"human\") {\n const res = gate.requires.includes(\"human\") ? undefined : checkGate(state, item0, gate, by);\n if (res?.outcome !== \"pass\")\n fail(\n \"gate-unmet\",\n `\"${by}\" may not decide gate \"${gate.id}\" on \"${item0.id}\"`,\n `decide as one of: human${gate.requires\n .flatMap((q) => (q === \"human\" ? [] : approverIds(state, gate.id, q.capability)))\n .map((r) => `, ${r}`)\n .join(\"\")}`,\n { items: [item0.id], rule: \"gate\" },\n );\n }\n const at = nowOf(now);\n let next: WorkflowState = { ...state, pending: state.pending.filter((p) => p.id !== pendingId) };\n next = appendEvent(\n next,\n \"pending.decided\",\n by,\n { id: pendingId, decision, note, item: entry.item ?? null, gate: entry.gate ?? null },\n at,\n );\n if (item0) {\n const id = item0.id;\n const gateId = entry.gate ?? gate?.id ?? null;\n if (decision === \"approve\") {\n next = advanceItem(next, id, by, false, at);\n next = appendEvent(next, \"gate.passed\", by, { item: id, gate: gateId }, at);\n } else {\n const onFail = gate?.onFail ?? { action: \"block\" as const };\n if (onFail.action === \"return-to\")\n next = clearRole(moveItem(next, id, { stage: onFail.stage, status: \"todo\" }, by, at), id);\n else\n next = raiseBlocker(\n next,\n id,\n `gate \"${gateId ?? \"?\"}\" rejected: ${note || \"no reason given\"}`,\n by,\n by,\n at,\n );\n next = appendEvent(next, \"gate.failed\", by, { item: id, gate: gateId, note }, at);\n }\n }\n if (methodology?.afterDecide) next = methodology.afterDecide(next, entry, decision, by, note, at);\n return next;\n}\n","import { authorOf } from \"./gates.ts\";\nimport { approverIds, separationLost } from \"./roles.ts\";\nimport type { Action, Handoff, Methodology, Rule, Violation } from \"./types.ts\";\n\nexport function coreRulesFor(methodology: Pick<Methodology, \"requiredCapabilities\">): Rule[] {\n const separation: Rule = {\n id: \"separation-lost\",\n severity: \"warning\",\n check(state, action: Action): Violation[] {\n if (action.type !== \"init\" && action.type !== \"role.register\") return [];\n return separationLost(state, methodology.requiredCapabilities).map((r) => ({\n rule: \"separation-lost\",\n severity: \"warning\" as const,\n message: `role \"${r.id}\" holds every required capability (${methodology.requiredCapabilities.join(\", \")}); no separation of duties`,\n fix: \"fine for a solo operator; otherwise split capabilities across roles\",\n }));\n },\n };\n const coi: Rule = {\n id: \"conflict-of-interest\",\n severity: \"error\",\n check(state, action: Action): Violation[] {\n if (action.type !== \"complete\") return [];\n const handoff = (action.payload as { handoff?: Handoff } | undefined)?.handoff;\n if (!handoff) return [];\n const verdict = handoff.verdict ?? \"done\";\n if (verdict !== \"done\" && verdict !== \"needs-review\") return [];\n const item = state.items[handoff.item];\n if (!item) return [];\n const gate = state.stages.find((s) => s.id === item.stage)?.gate;\n if (!gate || !gate.requires.some((q) => q !== \"human\")) return [];\n if (authorOf(state, item) !== handoff.role) return [];\n const others = approverIds(state, gate.id, undefined, handoff.role);\n return [\n {\n rule: \"conflict-of-interest\",\n severity: \"error\",\n item: item.id,\n message: `role \"${handoff.role}\" authored \"${item.id}\" and may not pass gate \"${gate.id}\" on it`,\n fix: `hand the gate to another approver: ${others.join(\", \") || \"(register one)\"}`,\n },\n ];\n },\n };\n return [separation, coi];\n}\n","import { fail } from \"./errors.ts\";\nimport { requireCapabilities } from \"./roles.ts\";\nimport { coreRulesFor } from \"./rules.ts\";\nimport { createState } from \"./state.ts\";\nimport type {\n Action,\n ApplyResult,\n Methodology,\n Role,\n Stage,\n Violation,\n WorkflowState,\n} from \"./types.ts\";\n\nexport function validateAction(\n state: WorkflowState,\n methodology: Methodology,\n action: Action,\n): Violation[] {\n const out: Violation[] = [];\n for (const rule of [...coreRulesFor(methodology), ...methodology.rules])\n out.push(...rule.check(state, action));\n return out;\n}\n\nexport function applyAction(\n state: WorkflowState,\n methodology: Methodology,\n action: Action,\n reduce: (s: WorkflowState) => WorkflowState,\n): ApplyResult {\n const violations = validateAction(state, methodology, action);\n const errors = violations.filter((v) => v.severity === \"error\");\n if (errors.length) {\n fail(\n \"rule-violation\",\n `${action.type} violates ${errors.map((e) => e.rule).join(\", \")}: ${errors.map((e) => e.message).join(\"; \")}`,\n errors.map((e) => e.fix).join(\"; \"),\n { rule: errors[0]!.rule, items: errors.map((e) => e.item).filter((x): x is string => !!x) },\n );\n }\n return { state: reduce(state), warnings: violations.filter((v) => v.severity === \"warning\") };\n}\n\nexport interface InitInput<C> {\n methodology: Methodology<C>;\n config: unknown;\n roles?: Role[];\n stages?: Stage[];\n by?: string;\n now?: string;\n}\n\nexport function init<C>(input: InitInput<C>): ApplyResult {\n const m = input.methodology;\n const config = m.validateConfig(input.config);\n const stages = input.stages ?? m.defaultStages(config);\n const roles = input.roles ?? m.defaultRoles(config);\n const stateInput =\n input.now !== undefined\n ? { methodology: m.name, config, stages, roles, now: input.now }\n : { methodology: m.name, config, stages, roles };\n const state = createState(stateInput);\n requireCapabilities(state, m.requiredCapabilities, m.exclusiveCapabilities);\n return applyAction(state, m as Methodology, { type: \"init\", by: input.by ?? \"system\" }, (s) => s);\n}\n"]}
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunk23P7C25E_cjs=require('./chunk-23P7C25E.cjs'),chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs'),exFlow=require('ex-flow');var U={tokens:0,turns:0,wallclockMs:0};function V(e,t){return {tokens:e.tokens+t.tokensIn+t.tokensOut,turns:e.turns+1,wallclockMs:e.wallclockMs+t.durationMs}}function q(e,t){let r={};return e.tokens!==void 0&&(r.tokens=Math.max(0,e.tokens-t.tokens)),e.turns!==void 0&&(r.turns=Math.max(0,e.turns-t.turns)),e.wallclockMs!==void 0&&(r.wallclockMs=Math.max(0,e.wallclockMs-t.wallclockMs)),r}function X(e,t){return e.tokens!==void 0&&t.tokens>=e.tokens||e.turns!==void 0&&t.turns>=e.turns||e.wallclockMs!==void 0&&t.wallclockMs>=e.wallclockMs}function F(e,t,r=2e4){let u=t??1,a=[];for(let i of e.accounting){let d=e.items[i.item]?.weight;d===void 0||d<=0||a.push((i.tokensIn+i.tokensOut)/d);}if(a.length===0)return r*u;a.sort((i,d)=>i-d);let o=Math.floor(a.length/2),p=a.length%2?a[o]:(a[o-1]+a[o])/2;return Math.round(p*u)}function K(e){return e.iterations.find(t=>t.endedAt===void 0)}function A(e,t,r){if(t.role){let o=chunk23P7C25E_cjs.e(e,t.role);return o||chunkS3BXVHO7_cjs.b("unknown-role",`item "${t.id}" is assigned to unknown role "${t.role}"`,"editItem with an existing role id"),o}let u=r?r(t):void 0;if(u!==void 0){let o=chunk23P7C25E_cjs.e(e,u);return o||chunkS3BXVHO7_cjs.b("unknown-role",`the methodology picked unknown role "${u}" for item "${t.id}"`,`registered roles: ${Object.keys(e.roles).join(", ")||"(none)"}`,{items:[t.id]}),o}if(t.status==="review"){let o=chunk23P7C25E_cjs.G(e,t),p=chunk23P7C25E_cjs.i(e,"review"),d=p.find(w=>w.id!==o)??(p.length===1?p[0]:void 0);return d||chunkS3BXVHO7_cjs.b("missing-capability",`no role has capability "review" for item "${t.id}"`,"register a role with capability review",{items:[t.id]}),d}let a=chunk23P7C25E_cjs.i(e,"deliver")[0];return a||chunkS3BXVHO7_cjs.b("missing-capability",`no role has capability "deliver" for item "${t.id}"`,"register a role with capability deliver",{items:[t.id]}),a}function T(e){let t={};for(let r of Object.values(e.roles))r.maxConcurrent!==void 0&&(t[r.resourceClass??r.id]=r.maxConcurrent);return t}function Q(e,t,r,u){let a=new Set(e.map(o=>o.id));return e.map(o=>{let p=A(t,o,u),i={id:o.id,data:{id:o.id},dependsOn:o.dependsOn.filter(w=>a.has(w)),resourceClass:p.resourceClass??p.id},d=r?r(o):o.priority;return d!==void 0&&(i.priority=d),o.weight!==void 0&&(i.weight=o.weight),o.deadline!==void 0&&(i.deadline=Date.parse(o.deadline)),i})}function ae(e,t,r={}){let u=chunk23P7C25E_cjs.a(r.now),a=t.candidates(e),o=a.filter(n=>n.dependsOn.every(s=>e.items[s]?.status==="done"||a.some(c=>c.id===s))),p=a.filter(n=>n.dependsOn.every(s=>e.items[s]?.status==="done"));if(o.length===0)return {state:e,dispatched:[],skipped:[],reason:"no-candidates"};let i=t.plannerOptions(e),d={schedulerMode:i.schedulerMode,resourceCaps:T(e)};if(i.concurrencyCap!==void 0&&(d.concurrencyCap=i.concurrencyCap),i.fairnessPolicy!==void 0&&(d.fairnessPolicy=i.fairnessPolicy),i.maxDeferralRounds!==void 0&&(d.maxDeferralRounds=i.maxDeferralRounds),i.deadlineStrategy!==void 0&&(d.deadlineStrategy=i.deadlineStrategy),i.weightStrategy!==void 0&&(d.weightStrategy=i.weightStrategy),i.tieBreaker!==void 0){let n=i.tieBreaker;d.tieBreaker=(s,c)=>n(e.items[s.data.id],e.items[c.data.id]);}let w,P;try{let n=new exFlow.ExFlow(d);for(let c of Q(o,e,i.priorityOf,i.roleFor))n.addEntity(c);let s=n.resolveExecutionDetails();w=(s.plan.batches[0]??[]).map(c=>c.id),P=s.metrics;}catch(n){throw n instanceof exFlow.ExFlowRuntimeError&&chunkS3BXVHO7_cjs.b("planner-error",`ex-flow refused the graph: [${n.code}] ${n.message}`,"fix the item graph (cycles, duplicate ids) with editItem; see diagnostics in the message",{items:o.map(s=>s.id)}),n}let L=w.map(n=>e.items[n]).filter(n=>n.dependsOn.every(s=>e.items[s]?.status==="done")),_=Object.values(e.items).filter(n=>n.status==="in_progress"),H=new Set(i.wipCounts??["in_progress"]),Z=Object.values(e.items).filter(n=>H.has(n.status)),S={};for(let n of _){let s=n.role?chunk23P7C25E_cjs.e(e,n.role):void 0,c=s?s.resourceClass??s.id:"?";S[c]=(S[c]??0)+1;}let M=T(e),R=K(e),b=R?q(R.budget,R.spent).tokens:void 0,z=Math.min(r.max??1/0,i.concurrencyCap??1/0),g=[],h=[],l,f=e;for(let n of L){if(g.length>=z){l="wip-full";break}let s=typeof i.dispatchStage=="function"?i.dispatchStage(n):i.dispatchStage,c=n.status==="todo"&&s!==void 0?s:n.stage,y=chunk23P7C25E_cjs.p(e,c),C=n.type==="question"?[]:chunk23P7C25E_cjs.D(e,n,y.entryPolicy);if(C.length>0){h.push({id:n.id,reason:"entry-policy",detail:C.map(m=>m.message).join("; ")});continue}let W=i.wipLimitOf?i.wipLimitOf(y,n):y.wipLimit;if(W!==void 0&&Z.filter(m=>m.stage===y.id&&m.id!==n.id).length+g.filter(m=>m.stage===y.id).length>=W){l="wip-full",h.push({id:n.id,reason:"wip",detail:`stage "${y.id}" is at its WIP limit of ${W}`});continue}let O=A(e,n,i.roleFor),k=O.resourceClass??O.id;if(M[k]!==void 0&&(S[k]??0)>=M[k]){l="wip-full",h.push({id:n.id,reason:"resource-cap",detail:`resource class "${k}" is at its cap of ${M[k]}`});continue}if(b!==void 0){let m=F(e,n.weight,r.fallbackTokensPerWeight);if(m>b){l="budget-exhausted",h.push({id:n.id,reason:"budget",detail:`needs about ${m} tokens, ${b} left in the iteration`});continue}b-=m;}S[k]=(S[k]??0)+1,f=chunk23P7C25E_cjs.x(f,n.id,{stage:c,status:"in_progress"},O.id,u),f={...f,items:{...f.items,[n.id]:{...f.items[n.id],role:O.id}}},g.push(f.items[n.id]);}return l===void 0&&h.some(n=>n.reason==="entry-policy")&&(l="policy-blocked"),l===void 0&&g.length<p.length&&(l="wip-full"),g.length===0&&l===void 0&&(l="no-candidates"),f=chunk23P7C25E_cjs.c(f,"planner.resolved","planner",{dispatched:g.map(n=>n.id),reason:l??null,skipped:h,metrics:P},u),l?{state:f,dispatched:g,skipped:h,reason:l}:{state:f,dispatched:g,skipped:h}}exports.a=U;exports.b=V;exports.c=q;exports.d=X;exports.e=F;exports.f=K;exports.g=A;exports.h=T;exports.i=Q;exports.j=ae;//# sourceMappingURL=chunk-2IKIBB73.cjs.map
2
+ //# sourceMappingURL=chunk-2IKIBB73.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/budget.ts","../src/planner.ts"],"names":["ZERO_SPENT","addSpent","spent","acc","remaining","budget","out","isExhausted","estimateTokens","state","weight","fallbackPerWeight","w","samples","a","iw","x","y","mid","median","openIteration","it","assignRole","item","roleFor","r","roleOf","fail","picked","author","authorOf","reviewers","rolesWith","resourceCapsFor","caps","toExNodes","items","priorityOf","present","i","role","node","d","pr","plan","methodology","opts","at","nowOf","all","candidates","readyAll","po","options","tb","b","firstBatch","metrics","flow","ExFlow","n","details","e","ExFlowRuntimeError","c","ready","id","inProgress","wipCounts","occupying","perClass","cls","iteration","tokensLeft","limit","dispatched","skipped","reason","next","pulledTo","target","stage","stageOf","violations","evaluatePolicies","v","limitHere","est","moveItem","appendEvent"],"mappings":"+IAEO,IAAMA,CAAAA,CAA+B,CAAE,MAAA,CAAQ,CAAA,CAAG,MAAO,CAAA,CAAG,WAAA,CAAa,CAAE,EAE3E,SAASC,CAAAA,CAASC,CAAAA,CAAyBC,CAAAA,CAAmC,CACnF,OAAO,CACL,MAAA,CAAQD,CAAAA,CAAM,MAAA,CAASC,CAAAA,CAAI,QAAA,CAAWA,CAAAA,CAAI,UAC1C,KAAA,CAAOD,CAAAA,CAAM,KAAA,CAAQ,CAAA,CACrB,YAAaA,CAAAA,CAAM,WAAA,CAAcC,CAAAA,CAAI,UACvC,CACF,CAEO,SAASC,CAAAA,CAAUC,CAAAA,CAAgBH,CAAAA,CAAiC,CACzE,IAAMI,CAAAA,CAAc,EAAC,CACrB,OAAID,CAAAA,CAAO,MAAA,GAAW,SAAWC,CAAAA,CAAI,MAAA,CAAS,IAAA,CAAK,GAAA,CAAI,EAAGD,CAAAA,CAAO,MAAA,CAASH,CAAAA,CAAM,MAAM,CAAA,CAAA,CAClFG,CAAAA,CAAO,KAAA,GAAU,MAAA,GAAWC,EAAI,KAAA,CAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,CAAGD,EAAO,KAAA,CAAQH,CAAAA,CAAM,KAAK,CAAA,CAAA,CAC9EG,EAAO,WAAA,GAAgB,MAAA,GACzBC,CAAAA,CAAI,WAAA,CAAc,IAAA,CAAK,GAAA,CAAI,CAAA,CAAGD,CAAAA,CAAO,YAAcH,CAAAA,CAAM,WAAW,CAAA,CAAA,CAC/DI,CACT,CAEO,SAASC,CAAAA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,KAAA,CAAO,CAAE,GAAGA,EAAK,KAAA,CAAO,CAACvD,CAAAA,CAAK,EAAE,EAAG,CAAE,GAAGuD,CAAAA,CAAK,MAAMvD,CAAAA,CAAK,EAAE,CAAA,CAAI,IAAA,CAAMiB,EAAK,EAAG,CAAE,CAChF,CAAA,CACAmC,EAAW,IAAA,CAAKG,CAAAA,CAAK,KAAA,CAAMvD,CAAAA,CAAK,EAAE,CAAE,EACtC,CACA,OAAIsD,CAAAA,GAAW,MAAA,EAAaD,CAAAA,CAAQ,IAAA,CAAM5D,GAAMA,CAAAA,CAAE,MAAA,GAAW,cAAc,CAAA,GACzE6D,EAAS,gBAAA,CAAA,CACPA,CAAAA,GAAW,MAAA,EAAaF,CAAAA,CAAW,MAAA,CAASxB,CAAAA,CAAS,MAAA,GAAQ0B,CAAAA,CAAS,YACtEF,CAAAA,CAAW,MAAA,GAAW,CAAA,EAAKE,CAAAA,GAAW,SAAWA,CAAAA,CAAS,eAAA,CAAA,CAC9DC,CAAAA,CAAOW,mBAAAA,CACLX,EACA,kBAAA,CACA,SAAA,CACA,CAAE,UAAA,CAAYH,CAAAA,CAAW,GAAA,CAAKjC,CAAAA,EAAMA,CAAAA,CAAE,EAAE,CAAA,CAAG,MAAA,CAAQmC,CAAAA,EAAU,IAAA,CAAM,QAAAD,CAAAA,CAAS,OAAA,CAAAnB,CAAQ,CAAA,CACpFV,CACF,CAAA,CACO8B,CAAAA,CACH,CAAE,KAAA,CAAOC,CAAAA,CAAM,UAAA,CAAAH,CAAAA,CAAY,OAAA,CAAAC,EAAS,MAAA,CAAAC,CAAO,CAAA,CAC3C,CAAE,MAAOC,CAAAA,CAAM,UAAA,CAAAH,CAAAA,CAAY,OAAA,CAAAC,CAAQ,CACzC","file":"chunk-2IKIBB73.cjs","sourcesContent":["import type { Accounting, Budget, WorkflowState } from \"./types.ts\";\n\nexport const ZERO_SPENT: Required<Budget> = { tokens: 0, turns: 0, wallclockMs: 0 };\n\nexport function addSpent(spent: Required<Budget>, acc: Accounting): Required<Budget> {\n return {\n tokens: spent.tokens + acc.tokensIn + acc.tokensOut,\n turns: spent.turns + 1,\n wallclockMs: spent.wallclockMs + acc.durationMs,\n };\n}\n\nexport function remaining(budget: Budget, spent: Required<Budget>): Budget {\n const out: Budget = {};\n if (budget.tokens !== undefined) out.tokens = Math.max(0, budget.tokens - spent.tokens);\n if (budget.turns !== undefined) out.turns = Math.max(0, budget.turns - spent.turns);\n if (budget.wallclockMs !== undefined)\n out.wallclockMs = Math.max(0, budget.wallclockMs - spent.wallclockMs);\n return out;\n}\n\nexport function isExhausted(budget: Budget, spent: Required<Budget>): boolean {\n return (\n (budget.tokens !== undefined && spent.tokens >= budget.tokens) ||\n (budget.turns !== undefined && spent.turns >= budget.turns) ||\n (budget.wallclockMs !== undefined && spent.wallclockMs >= budget.wallclockMs)\n );\n}\n\nexport function estimateTokens(\n state: WorkflowState,\n weight: number | undefined,\n fallbackPerWeight = 20000,\n): number {\n const w = weight ?? 1;\n const samples: number[] = [];\n for (const a of state.accounting) {\n const iw = state.items[a.item]?.weight;\n if (iw === undefined || iw <= 0) continue;\n samples.push((a.tokensIn + a.tokensOut) / iw);\n }\n if (samples.length === 0) return fallbackPerWeight * w;\n samples.sort((x, y) => x - y);\n const mid = Math.floor(samples.length / 2);\n const median = samples.length % 2 ? samples[mid]! : (samples[mid - 1]! + samples[mid]!) / 2;\n return Math.round(median * w);\n}\n","import { ExFlow, ExFlowRuntimeError, type ExFlowOptions, type ExNode } from \"ex-flow\";\nimport { estimateTokens, remaining } from \"./budget.ts\";\nimport { fail } from \"./errors.ts\";\nimport { authorOf } from \"./gates.ts\";\nimport { moveItem, stageOf } from \"./items.ts\";\nimport { evaluatePolicies } from \"./policies.ts\";\nimport { roleOf, rolesWith } from \"./roles.ts\";\nimport { appendEvent, nowOf } from \"./state.ts\";\nimport type { ItemStatus, Iteration, Methodology, Role, WorkItem, WorkflowState } from \"./types.ts\";\n\ntype NodeData = { id: string };\n\nexport function openIteration(state: WorkflowState): Iteration | undefined {\n return state.iterations.find((it) => it.endedAt === undefined);\n}\n\nexport function assignRole(\n state: WorkflowState,\n item: WorkItem,\n roleFor?: (item: WorkItem) => string | undefined,\n): Role {\n if (item.role) {\n const r = roleOf(state, item.role);\n if (!r)\n fail(\n \"unknown-role\",\n `item \"${item.id}\" is assigned to unknown role \"${item.role}\"`,\n \"editItem with an existing role id\",\n );\n return r;\n }\n const picked = roleFor ? roleFor(item) : undefined;\n if (picked !== undefined) {\n const r = roleOf(state, picked);\n if (!r)\n fail(\n \"unknown-role\",\n `the methodology picked unknown role \"${picked}\" for item \"${item.id}\"`,\n `registered roles: ${Object.keys(state.roles).join(\", \") || \"(none)\"}`,\n { items: [item.id] },\n );\n return r;\n }\n if (item.status === \"review\") {\n const author = authorOf(state, item);\n const reviewers = rolesWith(state, \"review\");\n const other = reviewers.find((r) => r.id !== author);\n const r = other ?? (reviewers.length === 1 ? reviewers[0] : undefined);\n if (!r)\n fail(\n \"missing-capability\",\n `no role has capability \"review\" for item \"${item.id}\"`,\n \"register a role with capability review\",\n { items: [item.id] },\n );\n return r;\n }\n const r = rolesWith(state, \"deliver\")[0];\n if (!r)\n fail(\n \"missing-capability\",\n `no role has capability \"deliver\" for item \"${item.id}\"`,\n \"register a role with capability deliver\",\n { items: [item.id] },\n );\n return r;\n}\n\nexport function resourceCapsFor(state: WorkflowState): Record<string, number> {\n const caps: Record<string, number> = {};\n for (const r of Object.values(state.roles)) {\n if (r.maxConcurrent !== undefined) caps[r.resourceClass ?? r.id] = r.maxConcurrent;\n }\n return caps;\n}\n\nexport function toExNodes(\n items: WorkItem[],\n state: WorkflowState,\n priorityOf?: (item: WorkItem) => number | undefined,\n roleFor?: (item: WorkItem) => string | undefined,\n): ExNode<NodeData>[] {\n const present = new Set(items.map((i) => i.id));\n return items.map((i) => {\n const role = assignRole(state, i, roleFor);\n const node: ExNode<NodeData> = {\n id: i.id,\n data: { id: i.id },\n dependsOn: i.dependsOn.filter((d) => present.has(d)),\n resourceClass: role.resourceClass ?? role.id,\n };\n const pr = priorityOf ? priorityOf(i) : i.priority;\n if (pr !== undefined) node.priority = pr;\n if (i.weight !== undefined) node.weight = i.weight;\n if (i.deadline !== undefined) node.deadline = Date.parse(i.deadline);\n return node;\n });\n}\n\nexport interface PlanOptions {\n max?: number;\n now?: string;\n fallbackTokensPerWeight?: number;\n}\nexport type PlanReason = \"no-candidates\" | \"budget-exhausted\" | \"wip-full\" | \"policy-blocked\";\n/** A ready item the planner did not pull, and why. */\nexport interface Skipped {\n id: string;\n reason: \"entry-policy\" | \"wip\" | \"resource-cap\" | \"budget\";\n detail: string;\n}\nexport interface PlanResult {\n state: WorkflowState;\n dispatched: WorkItem[];\n skipped: Skipped[];\n reason?: PlanReason;\n}\n\nexport function plan(\n state: WorkflowState,\n methodology: Methodology,\n opts: PlanOptions = {},\n): PlanResult {\n const at = nowOf(opts.now);\n // an item may enter the graph only if every dependency is done or is itself a candidate (so ex-flow orders it)\n const all = methodology.candidates(state);\n const candidates = all.filter((i) =>\n i.dependsOn.every((d) => state.items[d]?.status === \"done\" || all.some((c) => c.id === d)),\n );\n const readyAll = all.filter((i) => i.dependsOn.every((d) => state.items[d]?.status === \"done\"));\n if (candidates.length === 0)\n return { state, dispatched: [], skipped: [], reason: \"no-candidates\" };\n\n const po = methodology.plannerOptions(state);\n const options: ExFlowOptions<NodeData> = {\n schedulerMode: po.schedulerMode,\n resourceCaps: resourceCapsFor(state),\n };\n if (po.concurrencyCap !== undefined) options.concurrencyCap = po.concurrencyCap;\n if (po.fairnessPolicy !== undefined) options.fairnessPolicy = po.fairnessPolicy;\n if (po.maxDeferralRounds !== undefined) options.maxDeferralRounds = po.maxDeferralRounds;\n if (po.deadlineStrategy !== undefined) options.deadlineStrategy = po.deadlineStrategy;\n if (po.weightStrategy !== undefined) options.weightStrategy = po.weightStrategy;\n if (po.tieBreaker !== undefined) {\n const tb = po.tieBreaker;\n options.tieBreaker = (a, b) => tb(state.items[a.data.id]!, state.items[b.data.id]!);\n }\n\n let firstBatch: string[];\n let metrics: unknown;\n try {\n const flow = new ExFlow<NodeData>(options);\n for (const n of toExNodes(candidates, state, po.priorityOf, po.roleFor)) flow.addEntity(n);\n const details = flow.resolveExecutionDetails();\n firstBatch = (details.plan.batches[0] ?? []).map((r) => r.id);\n metrics = details.metrics;\n } catch (e) {\n if (e instanceof ExFlowRuntimeError) {\n fail(\n \"planner-error\",\n `ex-flow refused the graph: [${e.code}] ${e.message}`,\n \"fix the item graph (cycles, duplicate ids) with editItem; see diagnostics in the message\",\n { items: candidates.map((c) => c.id) },\n );\n }\n throw e;\n }\n\n // ready = first batch, but only items whose deps are really done (deps inside the batch are impossible by construction)\n const ready = firstBatch\n .map((id) => state.items[id]!)\n .filter((i) => i.dependsOn.every((d) => state.items[d]?.status === \"done\"));\n const inProgress = Object.values(state.items).filter((i) => i.status === \"in_progress\");\n const wipCounts = new Set<ItemStatus>(po.wipCounts ?? [\"in_progress\"]);\n const occupying = Object.values(state.items).filter((i) => wipCounts.has(i.status));\n const perClass: Record<string, number> = {};\n for (const i of inProgress) {\n const r = i.role ? roleOf(state, i.role) : undefined;\n const cls = r ? (r.resourceClass ?? r.id) : \"?\";\n perClass[cls] = (perClass[cls] ?? 0) + 1;\n }\n const caps = resourceCapsFor(state);\n const iteration = openIteration(state);\n let tokensLeft = iteration ? remaining(iteration.budget, iteration.spent).tokens : undefined;\n const limit = Math.min(opts.max ?? Infinity, po.concurrencyCap ?? Infinity);\n\n const dispatched: WorkItem[] = [];\n const skipped: Skipped[] = [];\n let reason: PlanReason | undefined;\n let next = state;\n for (const item of ready) {\n if (dispatched.length >= limit) {\n reason = \"wip-full\";\n break;\n }\n const pulledTo =\n typeof po.dispatchStage === \"function\" ? po.dispatchStage(item) : po.dispatchStage;\n const target = item.status === \"todo\" && pulledTo !== undefined ? pulledTo : item.stage;\n const stage = stageOf(state, target);\n // questions are answered, not delivered: like exit policies and gates, entry policies do not apply\n const violations =\n item.type === \"question\" ? [] : evaluatePolicies(state, item, stage.entryPolicy);\n if (violations.length > 0) {\n skipped.push({\n id: item.id,\n reason: \"entry-policy\",\n detail: violations.map((v) => v.message).join(\"; \"),\n });\n continue;\n }\n const limitHere = po.wipLimitOf ? po.wipLimitOf(stage, item) : stage.wipLimit;\n if (\n limitHere !== undefined &&\n occupying.filter((i) => i.stage === stage.id && i.id !== item.id).length +\n dispatched.filter((d) => d.stage === stage.id).length >=\n limitHere\n ) {\n reason = \"wip-full\";\n skipped.push({\n id: item.id,\n reason: \"wip\",\n detail: `stage \"${stage.id}\" is at its WIP limit of ${limitHere}`,\n });\n continue;\n }\n const role = assignRole(state, item, po.roleFor);\n const cls = role.resourceClass ?? role.id;\n if (caps[cls] !== undefined && (perClass[cls] ?? 0) >= caps[cls]!) {\n reason = \"wip-full\";\n skipped.push({\n id: item.id,\n reason: \"resource-cap\",\n detail: `resource class \"${cls}\" is at its cap of ${caps[cls]}`,\n });\n continue;\n }\n if (tokensLeft !== undefined) {\n const est = estimateTokens(state, item.weight, opts.fallbackTokensPerWeight);\n if (est > tokensLeft) {\n reason = \"budget-exhausted\";\n skipped.push({\n id: item.id,\n reason: \"budget\",\n detail: `needs about ${est} tokens, ${tokensLeft} left in the iteration`,\n });\n continue;\n }\n tokensLeft -= est;\n }\n perClass[cls] = (perClass[cls] ?? 0) + 1;\n next = moveItem(next, item.id, { stage: target, status: \"in_progress\" }, role.id, at);\n next = {\n ...next,\n items: { ...next.items, [item.id]: { ...next.items[item.id]!, role: role.id } },\n };\n dispatched.push(next.items[item.id]!);\n }\n if (reason === undefined && skipped.some((x) => x.reason === \"entry-policy\"))\n reason = \"policy-blocked\";\n if (reason === undefined && dispatched.length < readyAll.length) reason = \"wip-full\";\n if (dispatched.length === 0 && reason === undefined) reason = \"no-candidates\";\n next = appendEvent(\n next,\n \"planner.resolved\",\n \"planner\",\n { dispatched: dispatched.map((d) => d.id), reason: reason ?? null, skipped, metrics },\n at,\n );\n return reason\n ? { state: next, dispatched, skipped, reason }\n : { state: next, dispatched, skipped };\n}\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkQDT35LXB_cjs=require('./chunk-QDT35LXB.cjs'),chunkJDVE7DQR_cjs=require('./chunk-JDVE7DQR.cjs'),chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs'),exsorted=require('exsorted');var ue=["todo","in_progress","blocked","review","awaiting_human","done","dropped"];function fe(o){let t=o.events.filter(r=>r.type==="sprint.closed"&&r.payload.reason!=="cancel");return t.length===0?null:t.reduce((r,i)=>r+i.payload.doneWeight,0)/t.length}function ie(o){let t=chunkQDT35LXB_cjs.f(o),r=Object.fromEntries(ue.map(n=>[n,0])),i=[],y=0;for(let n of t?.committed??[]){let e=o.items[n];if(e){r[e.status]+=1,e.status!=="done"&&(y+=e.weight??0);for(let a of e.blockers)a.clearedAt||i.push({item:n,blocker:a.id,owner:a.owner,reason:a.reason});}}let u=t?.spent??{tokens:0,turns:0,wallclockMs:0},g=t?chunkQDT35LXB_cjs.c(t.budget,t.spent):{},m=fe(o),h="unknown";if(t&&m!==null&&t.budget.tokens){let n=(g.tokens??0)/t.budget.tokens;h=y<=m*n?"on-track":"at-risk";}let s=o.lessons.filter(n=>n.status==="raised").length;return {sprint:t?.id??null,goal:t?.goal??null,byStatus:r,blockers:i,spent:u,remaining:g,remainingWeight:y,raisedLessons:s,velocity:m,forecast:h}}function V(o){for(let t=o.iterations.length-1;t>=0;t--){let r=o.iterations[t];if(r.endedAt!==void 0)return r}}function F(o,t){return o.events.find(r=>r.type==="sprint.closed"&&r.payload.id===t)?.seq??Number.POSITIVE_INFINITY}function ge(o){let t=new Set(V(o)?.carryover??[]),r=Object.values(o.items).filter(i=>i.stage==="backlog"&&i.status==="todo"&&i.type!=="question");return exsorted.timSort([...r],(i,y)=>{let u=t.has(i.id)?1:0,g=t.has(y.id)?1:0;return u!==g?g-u:(y.priority??0)-(i.priority??0)})}function ne(o,t){let r=chunkJDVE7DQR_cjs.u(o,t);(r.stage!=="backlog"||r.status!=="todo")&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${t}" is not in the Product Backlog (${r.stage}/${r.status})`,"only backlog items can be committed",{items:[t]}),chunkJDVE7DQR_cjs.E(o,r,chunkJDVE7DQR_cjs.p(o,"backlog").exitPolicy,"enter the Sprint Backlog");}function oe(o,t,r,i,y){let u=o;for(let g of Object.values(o.items))g.type!=="question"||g.parent===void 0||!t.includes(g.parent)||g.status==="done"||g.status==="dropped"||((g.stage!=="sprint"||g.status!=="todo")&&(u=chunkJDVE7DQR_cjs.x(u,g.id,{stage:"sprint",status:"todo"},i,y)),u=chunkJDVE7DQR_cjs.s(u,g.id,m=>({...m,iteration:r})));return u}function re(o,t){return {...o,config:{...O(o),definitionOfDone:t},stages:o.stages.map(r=>r.id==="review"?{...r,exitPolicy:t}:r)}}function ye(o,t){let r=[],i=0;for(let y of ge(o)){if(t.tokens!==void 0){let u=chunkQDT35LXB_cjs.e(o,y.weight);if(i+u>t.tokens)break;i+=u;}else if(t.turns!==void 0&&r.length>=t.turns)break;r.push(y.id);}return r}function J(o){let t=(n,e,a,l)=>chunkJDVE7DQR_cjs.M(n,o(),{type:e,by:a.by,payload:a},p=>l(p,chunkJDVE7DQR_cjs.a(a.now)));return {refine:(n,e)=>{chunkJDVE7DQR_cjs.o(n,e.by,"define-acceptance","deliver");let a=e.items??[],l=e.split??[];return a.length===0&&l.length===0&&chunkS3BXVHO7_cjs.b("invalid-input","refine needs items[] or split[]","pass at least one patch or split"),t(n,"ceremony.refine",e,(p,c)=>{for(let{id:d,patch:v}of a)p=chunkJDVE7DQR_cjs.w(p,d,v,e.by,c);for(let d of l){chunkJDVE7DQR_cjs.u(p,d.from);for(let v of d.into)p=chunkJDVE7DQR_cjs.v(p,{...v,parent:d.from},e.by,c);p=chunkJDVE7DQR_cjs.x(p,d.from,{status:"dropped"},e.by,c);}return chunkJDVE7DQR_cjs.c(p,"ceremony.refine",e.by,{edited:a.map(d=>d.id),split:l.map(d=>({from:d.from,into:d.into.map(v=>v.id)}))},c)})},plan:(n,e)=>{chunkJDVE7DQR_cjs.o(n,e.by,"facilitate");let a=e.goal;(typeof a!="string"||a.trim()==="")&&chunkS3BXVHO7_cjs.b("invalid-input","sprint planning needs a non-empty goal","state the Sprint Goal in one sentence");let l=O(n),p=e.budget??l.sprintBudget,c=e.items==="auto"?ye(n,p):e.items;Array.isArray(c)||chunkS3BXVHO7_cjs.b("invalid-input",'sprint planning needs items: string[] or "auto"','pass ["A","B"] or "auto"'),c.length===0&&chunkS3BXVHO7_cjs.b("invalid-input","no backlog items fit the sprint","refine the backlog (acceptance + estimates) or raise the budget in config");for(let d of c)ne(n,d);return t(n,"ceremony.plan",e,(d,v)=>{let w=`S${d.iterations.length+1}`,q=V(d),f=c.filter(S=>q?.carryover.includes(S));for(let S of c)d=chunkJDVE7DQR_cjs.x(d,S,{stage:"sprint",status:"todo"},e.by,v),d=chunkJDVE7DQR_cjs.s(d,S,B=>({...B,iteration:w}));d=oe(d,c,w,e.by,v);let W=c.reduce((S,B)=>S+(d.items[B]?.weight??0),0);return d={...d,iterations:[...d.iterations,{id:w,goal:a,budget:p,spent:{tokens:0,turns:0,wallclockMs:0},startedAt:v,committed:[...c],carryover:f}]},chunkJDVE7DQR_cjs.c(d,"sprint.opened",e.by,{id:w,goal:a,committed:c,committedWeight:W,budget:p},v)})},commit:(n,e)=>{let a=chunkQDT35LXB_cjs.f(n);a||chunkS3BXVHO7_cjs.b("invalid-input","no open sprint to commit into","run the plan ceremony first");let l=e.items;(!Array.isArray(l)||l.length===0)&&chunkS3BXVHO7_cjs.b("invalid-input","commit needs items[]",'pass ["A"]');let p=new Set;for(let c of l)p.has(c)&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${c}" appears twice in items[]`,"list each item once",{items:[c]}),p.add(c),chunkJDVE7DQR_cjs.u(n,c),a.committed.includes(c)&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${c}" is already committed to ${a.id}`,"nothing to do",{items:[c]}),ne(n,c);return t(n,"ceremony.commit",e,(c,d)=>{for(let v of l)c=chunkJDVE7DQR_cjs.x(c,v,{stage:"sprint",status:"todo"},e.by,d),c=chunkJDVE7DQR_cjs.s(c,v,w=>({...w,iteration:a.id}));return c=oe(c,l,a.id,e.by,d),c={...c,iterations:c.iterations.map(v=>v.id===a.id?{...v,committed:[...v.committed,...l]}:v)},chunkJDVE7DQR_cjs.c(c,"sprint.committed",e.by,{id:a.id,items:l,goalImpact:e.goalImpact??null},d)})},uncommit:(n,e)=>{chunkJDVE7DQR_cjs.o(n,e.by,"order-backlog");let a=chunkQDT35LXB_cjs.f(n);a||chunkS3BXVHO7_cjs.b("invalid-input","no open sprint","nothing to uncommit from");let l=e.items;(!Array.isArray(l)||l.length===0)&&chunkS3BXVHO7_cjs.b("invalid-input","uncommit needs items[]",'pass ["A"]');for(let p of l)chunkJDVE7DQR_cjs.u(n,p).status==="done"&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${p}" is done`,"finished work cannot be uncommitted",{items:[p]});for(let p of l)a.committed.includes(p)||chunkS3BXVHO7_cjs.b("invalid-input",`item "${p}" is not committed to ${a.id}`,`committed: ${a.committed.join(", ")}`,{items:[p]});return t(n,"ceremony.uncommit",e,(p,c)=>{for(let d of l)p=chunkJDVE7DQR_cjs.x(p,d,{stage:"backlog",status:"todo"},e.by,c),p=chunkJDVE7DQR_cjs.t(p,d,["iteration","role"]);return p={...p,iterations:p.iterations.map(d=>d.id===a.id?{...d,committed:d.committed.filter(v=>!l.includes(v))}:d)},chunkJDVE7DQR_cjs.c(p,"sprint.uncommitted",e.by,{id:a.id,items:l,reason:e.reason??""},c)})},daily:(n,e)=>t(n,"ceremony.daily",e,(a,l)=>chunkJDVE7DQR_cjs.c(a,"daily",e.by,ie(a),l)),review:(n,e)=>{let a=chunkQDT35LXB_cjs.f(n);a||chunkS3BXVHO7_cjs.b("invalid-input","no open sprint to review","run the plan ceremony first");let l=chunkJDVE7DQR_cjs.j(n,"sprint-review");e.by!=="human"&&!l.includes(e.by)&&chunkS3BXVHO7_cjs.b("gate-unmet",`"${e.by}" may not accept the Sprint Review`,`run review as "human" or as ${l.join(", ")||"a role with canApprove sprint-review"}`,{rule:"sprint-review"});let p=e.feedback??[];return t(n,"ceremony.review",e,(c,d)=>{for(let w of p)c=chunkJDVE7DQR_cjs.v(c,{...w,stage:"backlog"},e.by,d);let v=a.committed.filter(w=>c.items[w]?.status==="done");return c=chunkJDVE7DQR_cjs.c(c,"increment",e.by,{sprint:a.id,done:v,goalMet:e.goalMet===true,accepted:e.accepted===true,feedback:p.map(w=>w.id)},d),T(c,"review",d)})},retro:(n,e)=>{chunkJDVE7DQR_cjs.o(n,e.by,"facilitate");let a=V(n);a||chunkS3BXVHO7_cjs.b("invalid-input","no closed sprint to retrospect","close the sprint (review or cancel) first"),chunkQDT35LXB_cjs.f(n)&&chunkS3BXVHO7_cjs.b("invalid-input","a sprint is still open","retro runs between sprints; review or cancel the open one");let l=F(n,a.id);n.events.some(f=>f.type==="retro"&&f.seq>l)&&chunkS3BXVHO7_cjs.b("invalid-input",`sprint ${a.id} already has a retrospective`,"plan the next sprint");let p=e.lessons??[],c=e.adopt??[],d=e.dismiss??[],v=e.dodChanges,w=[...c.map(f=>f.id),...d],q=w.find((f,W)=>w.indexOf(f)!==W);q&&chunkS3BXVHO7_cjs.b("invalid-input",`lesson "${q}" is referenced more than once`,"adopt or dismiss each lesson once");for(let f of w){let W=n.lessons.find(S=>S.id===f);W||chunkS3BXVHO7_cjs.b("invalid-input",`no lesson "${f}"`,`raised lessons: ${n.lessons.filter(S=>S.status==="raised").map(S=>S.id).join(", ")||"(none)"}`),W.status!=="raised"&&chunkS3BXVHO7_cjs.b("invalid-input",`lesson "${f}" is already ${W.status}`,"only raised lessons can be adopted or dismissed");}return t(n,"ceremony.retro",e,(f,W)=>{let S=[],B=[],U=[],E=false,H=k=>{if(k)if(k.kind==="agreement")f.agreements.includes(k.text)||(f={...f,agreements:[...f.agreements,k.text]}),B.push(k.text);else if(k.kind==="dod"){let I=O(f).definitionOfDone;I.some(_=>JSON.stringify(_)===JSON.stringify(k.policy))||(E=true,f=re(f,[...I,k.policy]));}else k.kind==="backlog"&&(f=chunkJDVE7DQR_cjs.v(f,{...k.item,stage:"backlog",tags:[...k.item.tags??[],"retro"]},e.by,W),U.push(k.item.id));};for(let k of p){let I=`L${f.lessons.length+1}`,_={id:I,at:W,text:k.text,scope:k.scope,status:"adopted",from:e.by};k.suggestedChange&&(_.suggestedChange=k.suggestedChange),f={...f,lessons:[...f.lessons,_]},S.push(I),H(k.suggestedChange);}for(let k of c)f={...f,lessons:f.lessons.map(I=>I.id===k.id?{...I,status:"adopted",...k.suggestedChange?{suggestedChange:k.suggestedChange}:{}}:I)},S.push(k.id),H(k.suggestedChange??f.lessons.find(I=>I.id===k.id)?.suggestedChange);for(let k of d)f={...f,lessons:f.lessons.map(I=>I.id===k?{...I,status:"dismissed"}:I)};return v&&(E=true,f=re(f,v)),chunkJDVE7DQR_cjs.c(f,"retro",e.by,{sprint:a.id,adopted:S,dismissed:d,agreements:B,dodChanged:E,backlogAdded:U},W)})},cancel:(n,e)=>{chunkJDVE7DQR_cjs.o(n,e.by,"order-backlog");let a=chunkQDT35LXB_cjs.f(n);return a||chunkS3BXVHO7_cjs.b("invalid-input","no open sprint to cancel","nothing to do"),t(n,"ceremony.cancel",e,(l,p)=>(l=chunkJDVE7DQR_cjs.c(l,"sprint.cancelled",e.by,{id:a.id,reason:e.reason??""},p),T(l,"cancel",p)))}}}var he=new Set(["never","po-only","any"]);function se(o){let t=o??{},r=t.sprintBudget;(!r||typeof r!="object"||r.tokens===void 0&&r.turns===void 0&&r.wallclockMs===void 0)&&chunkS3BXVHO7_cjs.b("config-invalid","scrum config.sprintBudget must define tokens, turns or wallclockMs",'e.g. { "sprintBudget": { "tokens": 400000, "turns": 60 } }'),(typeof t.productGoal!="string"||t.productGoal.trim()==="")&&chunkS3BXVHO7_cjs.b("config-invalid","scrum config.productGoal must be a non-empty string","state the Product Goal in one sentence"),Array.isArray(t.definitionOfDone)||chunkS3BXVHO7_cjs.b("config-invalid","scrum config.definitionOfDone must be a Policy[]",'e.g. [{ "kind": "evidence", "evidenceKind": "test-output" }]');let i=t.refinementSharePct??10;(typeof i!="number"||i<0||i>100)&&chunkS3BXVHO7_cjs.b("config-invalid","scrum config.refinementSharePct must be 0..100","omit it for the default 10");let y=t.allowMidSprintAdd??"po-only";(typeof y!="string"||!he.has(y))&&chunkS3BXVHO7_cjs.b("config-invalid",`scrum config.allowMidSprintAdd must be never | po-only | any (got ${JSON.stringify(y)})`,'use "po-only" unless you have a reason');let u=t.inProgressWipLimit;u!==void 0&&(typeof u!="number"||u<1)&&chunkS3BXVHO7_cjs.b("config-invalid","scrum config.inProgressWipLimit must be a positive number","omit it for no limit");let g={sprintBudget:r,productGoal:t.productGoal,definitionOfDone:t.definitionOfDone,refinementSharePct:i,allowMidSprintAdd:y};return u!==void 0&&(g.inProgressWipLimit=u),g}var D=(o,t)=>t===0?0:o/t;function ae(o){let t=o.events.filter(s=>s.type==="sprint.closed").map(s=>s.payload),r=t.filter(s=>s.reason!=="cancel"),i=r.map(s=>s.doneWeight),y=r.reduce((s,n)=>s+n.doneWeight,0),u=r.reduce((s,n)=>s+n.committedWeight,0),g=o.events.filter(s=>s.type==="increment").map(s=>s.payload),m=t.filter(s=>s.budget.tokens!==void 0),h=r.reduce((s,n)=>s+n.spent.tokens,0);return {velocity:i,meanVelocity:D(i.reduce((s,n)=>s+n,0),i.length),burndown:o.events.filter(s=>s.type==="daily").map(s=>s.payload.remainingWeight),commitmentReliability:D(y,u),sprintGoalHitRate:D(g.filter(s=>s.goalMet).length,g.length),carryoverRatio:D(t.reduce((s,n)=>s+n.carryover.length,0),t.reduce((s,n)=>s+n.done.length+n.carryover.length,0)),budgetUtilisation:D(m.reduce((s,n)=>s+n.spent.tokens,0),m.reduce((s,n)=>s+(n.budget.tokens??0),0)),costPerPoint:D(h,y)}}function ce(){return [{id:"product-owner",name:"Product Owner",modelTier:"large",capabilities:["order-backlog","define-acceptance","escalate"],canApprove:["sprint-review"],inputs:["stakeholder-needs","product-goal"],outputs:["ordered-backlog","acceptance-criteria"],do_not:["do not implement items yourself"]},{id:"scrum-master",name:"Scrum Master",modelTier:"large",capabilities:["facilitate","escalate"],canApprove:[],inputs:["board","blockers"],outputs:["ceremony-records","lessons"],do_not:["do not reorder the Product Backlog","do not assign work; the planner pulls"]},{id:"developer",name:"Developer",modelTier:"small",capabilities:["deliver","review","verify"],canApprove:[],inputs:["brief"],outputs:["code","test-output"],do_not:["do not change acceptance criteria","do not touch items outside your brief"]}]}var R=(o,t,r,i,y)=>y?{rule:o,severity:t,item:y,message:r,fix:i}:{rule:o,severity:t,message:r,fix:i};function de(o){for(let t=o.iterations.length-1;t>=0;t--){let r=o.iterations[t];if(r.endedAt!==void 0)return r}}function le(){return [{id:"one-open-sprint",severity:"error",check:(m,h)=>h.type==="ceremony.plan"&&chunkQDT35LXB_cjs.f(m)?[R("one-open-sprint","error",`sprint ${chunkQDT35LXB_cjs.f(m).id} is still open`,"review or cancel it before planning the next sprint")]:[]},{id:"retro-before-plan",severity:"error",check:(m,h)=>{if(h.type!=="ceremony.plan")return [];let s=de(m);if(!s)return [];let n=F(m,s.id);if(m.events.some(a=>a.type==="retro"&&a.seq>n))return [];let e=s.outcome==="cancelled"?"warning":"error";return [R("retro-before-plan",e,`sprint ${s.id} has no retrospective yet`,"run the retro ceremony first (lessons may be empty)")]}},{id:"sprint-budget-fixed",severity:"error",check:(m,h)=>{if(h.type!=="ceremony.plan")return [];let s=h.payload?.budget;return s===void 0||JSON.stringify(s)===JSON.stringify(O(m).sprintBudget)?[]:[R("sprint-budget-fixed","error","sprint length is fixed by config.sprintBudget","change sprintBudget in the config between sprints instead of per plan")]}},{id:"scope-protects-goal",severity:"error",check:(m,h)=>{if(h.type!=="ceremony.commit")return [];let s=O(m),n=h.payload??{};return s.allowMidSprintAdd==="never"?[R("scope-protects-goal","error","mid-sprint additions are disabled",'set allowMidSprintAdd to "po-only" or wait for the next sprint')]:s.allowMidSprintAdd==="po-only"&&!chunkJDVE7DQR_cjs.n(m,h.by,"order-backlog")?[R("scope-protects-goal","error",`"${h.by}" may not add work mid-sprint`,"ask the Product Owner (order-backlog) to commit it")]:n.goalImpact!=="none"?[R("scope-protects-goal","error",`adding work with goalImpact "${n.goalImpact??"unset"}" endangers the Sprint Goal`,'only commit items with goalImpact: "none"; otherwise cancel and re-plan')]:[]}},{id:"po-orders-backlog",severity:"error",check:(m,h)=>h.type!=="ceremony.refine"||chunkJDVE7DQR_cjs.n(m,h.by,"order-backlog")?[]:((h.payload??{}).items??[]).filter(n=>n.patch.priority!==void 0).map(n=>R("po-orders-backlog","error",`"${h.by}" may not change the priority of "${n.id}"`,"only the Product Owner orders the backlog; drop priority from the patch",n.id))},{id:"dod-not-weakened",severity:"error",check:(m,h)=>h.type==="ceremony.retro"&&h.payload?.dodChanges!==void 0&&chunkQDT35LXB_cjs.f(m)?[R("dod-not-weakened","error","Definition of Done cannot change while a sprint is open","close the sprint first; DoD changes apply to the next sprint")]:[]},{id:"carryover-reestimated",severity:"error",check:(m,h)=>{if(h.type!=="ceremony.plan")return [];let s=h.payload?.items;if(!Array.isArray(s))return [];let n=de(m);if(!n)return [];let e=F(m,n.id);return s.filter(a=>n.carryover.includes(a)&&!m.events.some(l=>l.type==="item.edited"&&l.seq>e&&l.payload.id===a&&l.payload.changed.includes("weight"))).map(a=>R("carryover-reestimated","error",`carried-over item "${a}" was not re-estimated after ${n.id}`,"refine it with a new weight before committing",a))}}]}function me(o){let t={id:"in_progress",name:"In progress",entryPolicy:[{kind:"dependencies-done"}],exitPolicy:[]};return o.inProgressWipLimit!==void 0&&(t.wipLimit=o.inProgressWipLimit),[{id:"backlog",name:"Product Backlog",entryPolicy:[],exitPolicy:[{kind:"acceptance-written"},{kind:"estimate-present"}]},{id:"sprint",name:"Sprint Backlog",entryPolicy:[],exitPolicy:[]},t,{id:"review",name:"Review",entryPolicy:[],exitPolicy:o.definitionOfDone,review:true},{id:"done",name:"Increment",entryPolicy:[],exitPolicy:[]}]}var be={backlog:"Product Backlog",item:"Product Backlog Item",stage:"Column",iteration:"Sprint",increment:"Increment",ceremony:"Scrum Event",gate:"Sprint Review"};function O(o){return o.config}function ke(o,t,r){let i=o,y=chunkJDVE7DQR_cjs.u(i,t).blockers.filter(g=>!g.clearedAt);if(y.length){i=chunkJDVE7DQR_cjs.s(i,t,g=>({...g,blockers:g.blockers.map(m=>m.clearedAt?m:{...m,clearedAt:r})}));for(let g of y)i=chunkJDVE7DQR_cjs.c(i,"blocker.cleared","system",{id:t,blocker:g.id,reason:"sprint closed"},r);}for(let g of i.pending.filter(m=>m.item===t))i={...i,pending:i.pending.filter(m=>m.id!==g.id)},i=chunkJDVE7DQR_cjs.c(i,"pending.dropped","system",{id:g.id,item:t,reason:"sprint closed"},r);let u=chunkJDVE7DQR_cjs.u(i,t);return (u.stage!=="backlog"||u.status!=="todo")&&(i=chunkJDVE7DQR_cjs.x(i,t,{stage:"backlog",status:"todo"},"system",r)),chunkJDVE7DQR_cjs.t(i,t,u.type==="question"?["iteration"]:["iteration","role"])}function T(o,t,r){let i=chunkQDT35LXB_cjs.f(o);if(!i)return o;let y=i.committed.map(e=>chunkJDVE7DQR_cjs.u(o,e)),u=y.filter(e=>e.status==="done").map(e=>e.id),g=y.filter(e=>e.status==="dropped").map(e=>e.id),m=y.filter(e=>e.status!=="done"&&e.status!=="dropped").map(e=>e.id),h=Object.values(o.items).filter(e=>e.type==="question"&&e.parent!==void 0&&m.includes(e.parent)&&e.status!=="done"&&e.status!=="dropped").map(e=>e.id),s=o;for(let e of [...m,...h])s=ke(s,e,r);let n=e=>e.reduce((a,l)=>a+(o.items[l]?.weight??0),0);return s={...s,iterations:s.iterations.map(e=>{if(e.id!==i.id)return e;let{closing:a,...l}=e;return {...l,endedAt:r,outcome:t==="cancel"?"cancelled":"completed",carryover:m}})},chunkJDVE7DQR_cjs.c(s,"sprint.closed","system",{id:i.id,reason:t,done:u,carryover:m,carriedQuestions:h,dropped:g,doneWeight:n(u),committedWeight:n(i.committed),spent:i.spent,budget:i.budget},r)}function ve(){return {name:"scrum",vocabulary:be,validateConfig:se,defaultStages:me,defaultRoles:ce,requiredCapabilities:["order-backlog","facilitate","deliver"],exclusiveCapabilities:["order-backlog"],plannerOptions(o){let t=O(o).inProgressWipLimit;return t===void 0?{schedulerMode:"level",dispatchStage:"in_progress"}:{schedulerMode:"level",dispatchStage:"in_progress",concurrencyCap:t}},candidates(o){let t=chunkQDT35LXB_cjs.f(o);return !t||t.closing?[]:Object.values(o.items).filter(r=>r.iteration===t.id&&(r.status==="todo"||r.status==="review")&&(r.stage==="sprint"||r.stage==="review"))},invariants(o,t){let r=chunkQDT35LXB_cjs.f(o),i=O(o),y=r?chunkQDT35LXB_cjs.c(r.budget,r.spent):{};return [`Sprint Goal: ${r?.goal??"(no open sprint)"}; Product Goal: ${i.productGoal}`,`Budget remaining: ${JSON.stringify(y)}; stop and hand off when it is gone`,`Definition of Done: ${i.definitionOfDone.map(u=>u.kind==="evidence"?`evidence ${u.evidenceKind}`:u.kind).join(", ")||"(none)"}`,`Do not change the scope of "${t.id}" or its acceptance criteria; raise open_questions instead`]},ceremonies:J(ve),rules:le(),metrics:o=>({...ae(o)}),humanDefaults:{gates:["sprint-review"]},afterComplete(o,t,r){let i=chunkQDT35LXB_cjs.f(o);return !i||!i.closing&&!chunkQDT35LXB_cjs.d(i.budget,i.spent)?o:Object.values(o.items).some(u=>u.iteration===i.id&&u.status==="in_progress")?i.closing?o:chunkJDVE7DQR_cjs.c({...o,iterations:o.iterations.map(u=>u.id===i.id?{...u,closing:true}:u)},"sprint.closing","system",{id:i.id},r):T(o,"budget",r)}}}exports.a=ie;exports.b=J;exports.c=se;exports.d=ae;exports.e=ce;exports.f=le;exports.g=me;exports.h=be;exports.i=O;exports.j=T;exports.k=ve;//# sourceMappingURL=chunk-472WEDPJ.cjs.map
2
- //# sourceMappingURL=chunk-472WEDPJ.cjs.map
1
+ 'use strict';var chunk2IKIBB73_cjs=require('./chunk-2IKIBB73.cjs'),chunk23P7C25E_cjs=require('./chunk-23P7C25E.cjs'),chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs'),exsorted=require('exsorted');var ue=["todo","in_progress","blocked","review","awaiting_human","done","dropped"];function fe(o){let t=o.events.filter(r=>r.type==="sprint.closed"&&r.payload.reason!=="cancel");return t.length===0?null:t.reduce((r,i)=>r+i.payload.doneWeight,0)/t.length}function ie(o){let t=chunk2IKIBB73_cjs.f(o),r=Object.fromEntries(ue.map(n=>[n,0])),i=[],y=0;for(let n of t?.committed??[]){let e=o.items[n];if(e){r[e.status]+=1,e.status!=="done"&&(y+=e.weight??0);for(let a of e.blockers)a.clearedAt||i.push({item:n,blocker:a.id,owner:a.owner,reason:a.reason});}}let u=t?.spent??{tokens:0,turns:0,wallclockMs:0},g=t?chunk2IKIBB73_cjs.c(t.budget,t.spent):{},m=fe(o),h="unknown";if(t&&m!==null&&t.budget.tokens){let n=(g.tokens??0)/t.budget.tokens;h=y<=m*n?"on-track":"at-risk";}let s=o.lessons.filter(n=>n.status==="raised").length;return {sprint:t?.id??null,goal:t?.goal??null,byStatus:r,blockers:i,spent:u,remaining:g,remainingWeight:y,raisedLessons:s,velocity:m,forecast:h}}function V(o){for(let t=o.iterations.length-1;t>=0;t--){let r=o.iterations[t];if(r.endedAt!==void 0)return r}}function F(o,t){return o.events.find(r=>r.type==="sprint.closed"&&r.payload.id===t)?.seq??Number.POSITIVE_INFINITY}function ge(o){let t=new Set(V(o)?.carryover??[]),r=Object.values(o.items).filter(i=>i.stage==="backlog"&&i.status==="todo"&&i.type!=="question");return exsorted.timSort([...r],(i,y)=>{let u=t.has(i.id)?1:0,g=t.has(y.id)?1:0;return u!==g?g-u:(y.priority??0)-(i.priority??0)})}function ne(o,t){let r=chunk23P7C25E_cjs.u(o,t);(r.stage!=="backlog"||r.status!=="todo")&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${t}" is not in the Product Backlog (${r.stage}/${r.status})`,"only backlog items can be committed",{items:[t]}),chunk23P7C25E_cjs.E(o,r,chunk23P7C25E_cjs.p(o,"backlog").exitPolicy,"enter the Sprint Backlog");}function oe(o,t,r,i,y){let u=o;for(let g of Object.values(o.items))g.type!=="question"||g.parent===void 0||!t.includes(g.parent)||g.status==="done"||g.status==="dropped"||((g.stage!=="sprint"||g.status!=="todo")&&(u=chunk23P7C25E_cjs.x(u,g.id,{stage:"sprint",status:"todo"},i,y)),u=chunk23P7C25E_cjs.s(u,g.id,m=>({...m,iteration:r})));return u}function re(o,t){return {...o,config:{...O(o),definitionOfDone:t},stages:o.stages.map(r=>r.id==="review"?{...r,exitPolicy:t}:r)}}function ye(o,t){let r=[],i=0;for(let y of ge(o)){if(t.tokens!==void 0){let u=chunk2IKIBB73_cjs.e(o,y.weight);if(i+u>t.tokens)break;i+=u;}else if(t.turns!==void 0&&r.length>=t.turns)break;r.push(y.id);}return r}function J(o){let t=(n,e,a,l)=>chunk23P7C25E_cjs.M(n,o(),{type:e,by:a.by,payload:a},p=>l(p,chunk23P7C25E_cjs.a(a.now)));return {refine:(n,e)=>{chunk23P7C25E_cjs.o(n,e.by,"define-acceptance","deliver");let a=e.items??[],l=e.split??[];return a.length===0&&l.length===0&&chunkS3BXVHO7_cjs.b("invalid-input","refine needs items[] or split[]","pass at least one patch or split"),t(n,"ceremony.refine",e,(p,c)=>{for(let{id:d,patch:v}of a)p=chunk23P7C25E_cjs.w(p,d,v,e.by,c);for(let d of l){chunk23P7C25E_cjs.u(p,d.from);for(let v of d.into)p=chunk23P7C25E_cjs.v(p,{...v,parent:d.from},e.by,c);p=chunk23P7C25E_cjs.x(p,d.from,{status:"dropped"},e.by,c);}return chunk23P7C25E_cjs.c(p,"ceremony.refine",e.by,{edited:a.map(d=>d.id),split:l.map(d=>({from:d.from,into:d.into.map(v=>v.id)}))},c)})},plan:(n,e)=>{chunk23P7C25E_cjs.o(n,e.by,"facilitate");let a=e.goal;(typeof a!="string"||a.trim()==="")&&chunkS3BXVHO7_cjs.b("invalid-input","sprint planning needs a non-empty goal","state the Sprint Goal in one sentence");let l=O(n),p=e.budget??l.sprintBudget,c=e.items==="auto"?ye(n,p):e.items;Array.isArray(c)||chunkS3BXVHO7_cjs.b("invalid-input",'sprint planning needs items: string[] or "auto"','pass ["A","B"] or "auto"'),c.length===0&&chunkS3BXVHO7_cjs.b("invalid-input","no backlog items fit the sprint","refine the backlog (acceptance + estimates) or raise the budget in config");for(let d of c)ne(n,d);return t(n,"ceremony.plan",e,(d,v)=>{let w=`S${d.iterations.length+1}`,q=V(d),f=c.filter(S=>q?.carryover.includes(S));for(let S of c)d=chunk23P7C25E_cjs.x(d,S,{stage:"sprint",status:"todo"},e.by,v),d=chunk23P7C25E_cjs.s(d,S,B=>({...B,iteration:w}));d=oe(d,c,w,e.by,v);let W=c.reduce((S,B)=>S+(d.items[B]?.weight??0),0);return d={...d,iterations:[...d.iterations,{id:w,goal:a,budget:p,spent:{tokens:0,turns:0,wallclockMs:0},startedAt:v,committed:[...c],carryover:f}]},chunk23P7C25E_cjs.c(d,"sprint.opened",e.by,{id:w,goal:a,committed:c,committedWeight:W,budget:p},v)})},commit:(n,e)=>{let a=chunk2IKIBB73_cjs.f(n);a||chunkS3BXVHO7_cjs.b("invalid-input","no open sprint to commit into","run the plan ceremony first");let l=e.items;(!Array.isArray(l)||l.length===0)&&chunkS3BXVHO7_cjs.b("invalid-input","commit needs items[]",'pass ["A"]');let p=new Set;for(let c of l)p.has(c)&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${c}" appears twice in items[]`,"list each item once",{items:[c]}),p.add(c),chunk23P7C25E_cjs.u(n,c),a.committed.includes(c)&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${c}" is already committed to ${a.id}`,"nothing to do",{items:[c]}),ne(n,c);return t(n,"ceremony.commit",e,(c,d)=>{for(let v of l)c=chunk23P7C25E_cjs.x(c,v,{stage:"sprint",status:"todo"},e.by,d),c=chunk23P7C25E_cjs.s(c,v,w=>({...w,iteration:a.id}));return c=oe(c,l,a.id,e.by,d),c={...c,iterations:c.iterations.map(v=>v.id===a.id?{...v,committed:[...v.committed,...l]}:v)},chunk23P7C25E_cjs.c(c,"sprint.committed",e.by,{id:a.id,items:l,goalImpact:e.goalImpact??null},d)})},uncommit:(n,e)=>{chunk23P7C25E_cjs.o(n,e.by,"order-backlog");let a=chunk2IKIBB73_cjs.f(n);a||chunkS3BXVHO7_cjs.b("invalid-input","no open sprint","nothing to uncommit from");let l=e.items;(!Array.isArray(l)||l.length===0)&&chunkS3BXVHO7_cjs.b("invalid-input","uncommit needs items[]",'pass ["A"]');for(let p of l)chunk23P7C25E_cjs.u(n,p).status==="done"&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${p}" is done`,"finished work cannot be uncommitted",{items:[p]});for(let p of l)a.committed.includes(p)||chunkS3BXVHO7_cjs.b("invalid-input",`item "${p}" is not committed to ${a.id}`,`committed: ${a.committed.join(", ")}`,{items:[p]});return t(n,"ceremony.uncommit",e,(p,c)=>{for(let d of l)p=chunk23P7C25E_cjs.x(p,d,{stage:"backlog",status:"todo"},e.by,c),p=chunk23P7C25E_cjs.t(p,d,["iteration","role"]);return p={...p,iterations:p.iterations.map(d=>d.id===a.id?{...d,committed:d.committed.filter(v=>!l.includes(v))}:d)},chunk23P7C25E_cjs.c(p,"sprint.uncommitted",e.by,{id:a.id,items:l,reason:e.reason??""},c)})},daily:(n,e)=>t(n,"ceremony.daily",e,(a,l)=>chunk23P7C25E_cjs.c(a,"daily",e.by,ie(a),l)),review:(n,e)=>{let a=chunk2IKIBB73_cjs.f(n);a||chunkS3BXVHO7_cjs.b("invalid-input","no open sprint to review","run the plan ceremony first");let l=chunk23P7C25E_cjs.j(n,"sprint-review");e.by!=="human"&&!l.includes(e.by)&&chunkS3BXVHO7_cjs.b("gate-unmet",`"${e.by}" may not accept the Sprint Review`,`run review as "human" or as ${l.join(", ")||"a role with canApprove sprint-review"}`,{rule:"sprint-review"});let p=e.feedback??[];return t(n,"ceremony.review",e,(c,d)=>{for(let w of p)c=chunk23P7C25E_cjs.v(c,{...w,stage:"backlog"},e.by,d);let v=a.committed.filter(w=>c.items[w]?.status==="done");return c=chunk23P7C25E_cjs.c(c,"increment",e.by,{sprint:a.id,done:v,goalMet:e.goalMet===true,accepted:e.accepted===true,feedback:p.map(w=>w.id)},d),T(c,"review",d)})},retro:(n,e)=>{chunk23P7C25E_cjs.o(n,e.by,"facilitate");let a=V(n);a||chunkS3BXVHO7_cjs.b("invalid-input","no closed sprint to retrospect","close the sprint (review or cancel) first"),chunk2IKIBB73_cjs.f(n)&&chunkS3BXVHO7_cjs.b("invalid-input","a sprint is still open","retro runs between sprints; review or cancel the open one");let l=F(n,a.id);n.events.some(f=>f.type==="retro"&&f.seq>l)&&chunkS3BXVHO7_cjs.b("invalid-input",`sprint ${a.id} already has a retrospective`,"plan the next sprint");let p=e.lessons??[],c=e.adopt??[],d=e.dismiss??[],v=e.dodChanges,w=[...c.map(f=>f.id),...d],q=w.find((f,W)=>w.indexOf(f)!==W);q&&chunkS3BXVHO7_cjs.b("invalid-input",`lesson "${q}" is referenced more than once`,"adopt or dismiss each lesson once");for(let f of w){let W=n.lessons.find(S=>S.id===f);W||chunkS3BXVHO7_cjs.b("invalid-input",`no lesson "${f}"`,`raised lessons: ${n.lessons.filter(S=>S.status==="raised").map(S=>S.id).join(", ")||"(none)"}`),W.status!=="raised"&&chunkS3BXVHO7_cjs.b("invalid-input",`lesson "${f}" is already ${W.status}`,"only raised lessons can be adopted or dismissed");}return t(n,"ceremony.retro",e,(f,W)=>{let S=[],B=[],U=[],E=false,H=k=>{if(k)if(k.kind==="agreement")f.agreements.includes(k.text)||(f={...f,agreements:[...f.agreements,k.text]}),B.push(k.text);else if(k.kind==="dod"){let I=O(f).definitionOfDone;I.some(_=>JSON.stringify(_)===JSON.stringify(k.policy))||(E=true,f=re(f,[...I,k.policy]));}else k.kind==="backlog"&&(f=chunk23P7C25E_cjs.v(f,{...k.item,stage:"backlog",tags:[...k.item.tags??[],"retro"]},e.by,W),U.push(k.item.id));};for(let k of p){let I=`L${f.lessons.length+1}`,_={id:I,at:W,text:k.text,scope:k.scope,status:"adopted",from:e.by};k.suggestedChange&&(_.suggestedChange=k.suggestedChange),f={...f,lessons:[...f.lessons,_]},S.push(I),H(k.suggestedChange);}for(let k of c)f={...f,lessons:f.lessons.map(I=>I.id===k.id?{...I,status:"adopted",...k.suggestedChange?{suggestedChange:k.suggestedChange}:{}}:I)},S.push(k.id),H(k.suggestedChange??f.lessons.find(I=>I.id===k.id)?.suggestedChange);for(let k of d)f={...f,lessons:f.lessons.map(I=>I.id===k?{...I,status:"dismissed"}:I)};return v&&(E=true,f=re(f,v)),chunk23P7C25E_cjs.c(f,"retro",e.by,{sprint:a.id,adopted:S,dismissed:d,agreements:B,dodChanged:E,backlogAdded:U},W)})},cancel:(n,e)=>{chunk23P7C25E_cjs.o(n,e.by,"order-backlog");let a=chunk2IKIBB73_cjs.f(n);return a||chunkS3BXVHO7_cjs.b("invalid-input","no open sprint to cancel","nothing to do"),t(n,"ceremony.cancel",e,(l,p)=>(l=chunk23P7C25E_cjs.c(l,"sprint.cancelled",e.by,{id:a.id,reason:e.reason??""},p),T(l,"cancel",p)))}}}var he=new Set(["never","po-only","any"]);function se(o){let t=o??{},r=t.sprintBudget;(!r||typeof r!="object"||r.tokens===void 0&&r.turns===void 0&&r.wallclockMs===void 0)&&chunkS3BXVHO7_cjs.b("config-invalid","scrum config.sprintBudget must define tokens, turns or wallclockMs",'e.g. { "sprintBudget": { "tokens": 400000, "turns": 60 } }'),(typeof t.productGoal!="string"||t.productGoal.trim()==="")&&chunkS3BXVHO7_cjs.b("config-invalid","scrum config.productGoal must be a non-empty string","state the Product Goal in one sentence"),Array.isArray(t.definitionOfDone)||chunkS3BXVHO7_cjs.b("config-invalid","scrum config.definitionOfDone must be a Policy[]",'e.g. [{ "kind": "evidence", "evidenceKind": "test-output" }]');let i=t.refinementSharePct??10;(typeof i!="number"||i<0||i>100)&&chunkS3BXVHO7_cjs.b("config-invalid","scrum config.refinementSharePct must be 0..100","omit it for the default 10");let y=t.allowMidSprintAdd??"po-only";(typeof y!="string"||!he.has(y))&&chunkS3BXVHO7_cjs.b("config-invalid",`scrum config.allowMidSprintAdd must be never | po-only | any (got ${JSON.stringify(y)})`,'use "po-only" unless you have a reason');let u=t.inProgressWipLimit;u!==void 0&&(typeof u!="number"||u<1)&&chunkS3BXVHO7_cjs.b("config-invalid","scrum config.inProgressWipLimit must be a positive number","omit it for no limit");let g={sprintBudget:r,productGoal:t.productGoal,definitionOfDone:t.definitionOfDone,refinementSharePct:i,allowMidSprintAdd:y};return u!==void 0&&(g.inProgressWipLimit=u),g}var D=(o,t)=>t===0?0:o/t;function ae(o){let t=o.events.filter(s=>s.type==="sprint.closed").map(s=>s.payload),r=t.filter(s=>s.reason!=="cancel"),i=r.map(s=>s.doneWeight),y=r.reduce((s,n)=>s+n.doneWeight,0),u=r.reduce((s,n)=>s+n.committedWeight,0),g=o.events.filter(s=>s.type==="increment").map(s=>s.payload),m=t.filter(s=>s.budget.tokens!==void 0),h=r.reduce((s,n)=>s+n.spent.tokens,0);return {velocity:i,meanVelocity:D(i.reduce((s,n)=>s+n,0),i.length),burndown:o.events.filter(s=>s.type==="daily").map(s=>s.payload.remainingWeight),commitmentReliability:D(y,u),sprintGoalHitRate:D(g.filter(s=>s.goalMet).length,g.length),carryoverRatio:D(t.reduce((s,n)=>s+n.carryover.length,0),t.reduce((s,n)=>s+n.done.length+n.carryover.length,0)),budgetUtilisation:D(m.reduce((s,n)=>s+n.spent.tokens,0),m.reduce((s,n)=>s+(n.budget.tokens??0),0)),costPerPoint:D(h,y)}}function ce(){return [{id:"product-owner",name:"Product Owner",modelTier:"large",capabilities:["order-backlog","define-acceptance","escalate"],canApprove:["sprint-review"],inputs:["stakeholder-needs","product-goal"],outputs:["ordered-backlog","acceptance-criteria"],do_not:["do not implement items yourself"]},{id:"scrum-master",name:"Scrum Master",modelTier:"large",capabilities:["facilitate","escalate"],canApprove:[],inputs:["board","blockers"],outputs:["ceremony-records","lessons"],do_not:["do not reorder the Product Backlog","do not assign work; the planner pulls"]},{id:"developer",name:"Developer",modelTier:"small",capabilities:["deliver","review","verify"],canApprove:[],inputs:["brief"],outputs:["code","test-output"],do_not:["do not change acceptance criteria","do not touch items outside your brief"]}]}var R=(o,t,r,i,y)=>y?{rule:o,severity:t,item:y,message:r,fix:i}:{rule:o,severity:t,message:r,fix:i};function de(o){for(let t=o.iterations.length-1;t>=0;t--){let r=o.iterations[t];if(r.endedAt!==void 0)return r}}function le(){return [{id:"one-open-sprint",severity:"error",check:(m,h)=>h.type==="ceremony.plan"&&chunk2IKIBB73_cjs.f(m)?[R("one-open-sprint","error",`sprint ${chunk2IKIBB73_cjs.f(m).id} is still open`,"review or cancel it before planning the next sprint")]:[]},{id:"retro-before-plan",severity:"error",check:(m,h)=>{if(h.type!=="ceremony.plan")return [];let s=de(m);if(!s)return [];let n=F(m,s.id);if(m.events.some(a=>a.type==="retro"&&a.seq>n))return [];let e=s.outcome==="cancelled"?"warning":"error";return [R("retro-before-plan",e,`sprint ${s.id} has no retrospective yet`,"run the retro ceremony first (lessons may be empty)")]}},{id:"sprint-budget-fixed",severity:"error",check:(m,h)=>{if(h.type!=="ceremony.plan")return [];let s=h.payload?.budget;return s===void 0||JSON.stringify(s)===JSON.stringify(O(m).sprintBudget)?[]:[R("sprint-budget-fixed","error","sprint length is fixed by config.sprintBudget","change sprintBudget in the config between sprints instead of per plan")]}},{id:"scope-protects-goal",severity:"error",check:(m,h)=>{if(h.type!=="ceremony.commit")return [];let s=O(m),n=h.payload??{};return s.allowMidSprintAdd==="never"?[R("scope-protects-goal","error","mid-sprint additions are disabled",'set allowMidSprintAdd to "po-only" or wait for the next sprint')]:s.allowMidSprintAdd==="po-only"&&!chunk23P7C25E_cjs.n(m,h.by,"order-backlog")?[R("scope-protects-goal","error",`"${h.by}" may not add work mid-sprint`,"ask the Product Owner (order-backlog) to commit it")]:n.goalImpact!=="none"?[R("scope-protects-goal","error",`adding work with goalImpact "${n.goalImpact??"unset"}" endangers the Sprint Goal`,'only commit items with goalImpact: "none"; otherwise cancel and re-plan')]:[]}},{id:"po-orders-backlog",severity:"error",check:(m,h)=>h.type!=="ceremony.refine"||chunk23P7C25E_cjs.n(m,h.by,"order-backlog")?[]:((h.payload??{}).items??[]).filter(n=>n.patch.priority!==void 0).map(n=>R("po-orders-backlog","error",`"${h.by}" may not change the priority of "${n.id}"`,"only the Product Owner orders the backlog; drop priority from the patch",n.id))},{id:"dod-not-weakened",severity:"error",check:(m,h)=>h.type==="ceremony.retro"&&h.payload?.dodChanges!==void 0&&chunk2IKIBB73_cjs.f(m)?[R("dod-not-weakened","error","Definition of Done cannot change while a sprint is open","close the sprint first; DoD changes apply to the next sprint")]:[]},{id:"carryover-reestimated",severity:"error",check:(m,h)=>{if(h.type!=="ceremony.plan")return [];let s=h.payload?.items;if(!Array.isArray(s))return [];let n=de(m);if(!n)return [];let e=F(m,n.id);return s.filter(a=>n.carryover.includes(a)&&!m.events.some(l=>l.type==="item.edited"&&l.seq>e&&l.payload.id===a&&l.payload.changed.includes("weight"))).map(a=>R("carryover-reestimated","error",`carried-over item "${a}" was not re-estimated after ${n.id}`,"refine it with a new weight before committing",a))}}]}function me(o){let t={id:"in_progress",name:"In progress",entryPolicy:[{kind:"dependencies-done"}],exitPolicy:[]};return o.inProgressWipLimit!==void 0&&(t.wipLimit=o.inProgressWipLimit),[{id:"backlog",name:"Product Backlog",entryPolicy:[],exitPolicy:[{kind:"acceptance-written"},{kind:"estimate-present"}]},{id:"sprint",name:"Sprint Backlog",entryPolicy:[],exitPolicy:[]},t,{id:"review",name:"Review",entryPolicy:[],exitPolicy:o.definitionOfDone,review:true},{id:"done",name:"Increment",entryPolicy:[],exitPolicy:[]}]}var be={backlog:"Product Backlog",item:"Product Backlog Item",stage:"Column",iteration:"Sprint",increment:"Increment",ceremony:"Scrum Event",gate:"Sprint Review"};function O(o){return o.config}function ke(o,t,r){let i=o,y=chunk23P7C25E_cjs.u(i,t).blockers.filter(g=>!g.clearedAt);if(y.length){i=chunk23P7C25E_cjs.s(i,t,g=>({...g,blockers:g.blockers.map(m=>m.clearedAt?m:{...m,clearedAt:r})}));for(let g of y)i=chunk23P7C25E_cjs.c(i,"blocker.cleared","system",{id:t,blocker:g.id,reason:"sprint closed"},r);}for(let g of i.pending.filter(m=>m.item===t))i={...i,pending:i.pending.filter(m=>m.id!==g.id)},i=chunk23P7C25E_cjs.c(i,"pending.dropped","system",{id:g.id,item:t,reason:"sprint closed"},r);let u=chunk23P7C25E_cjs.u(i,t);return (u.stage!=="backlog"||u.status!=="todo")&&(i=chunk23P7C25E_cjs.x(i,t,{stage:"backlog",status:"todo"},"system",r)),chunk23P7C25E_cjs.t(i,t,u.type==="question"?["iteration"]:["iteration","role"])}function T(o,t,r){let i=chunk2IKIBB73_cjs.f(o);if(!i)return o;let y=i.committed.map(e=>chunk23P7C25E_cjs.u(o,e)),u=y.filter(e=>e.status==="done").map(e=>e.id),g=y.filter(e=>e.status==="dropped").map(e=>e.id),m=y.filter(e=>e.status!=="done"&&e.status!=="dropped").map(e=>e.id),h=Object.values(o.items).filter(e=>e.type==="question"&&e.parent!==void 0&&m.includes(e.parent)&&e.status!=="done"&&e.status!=="dropped").map(e=>e.id),s=o;for(let e of [...m,...h])s=ke(s,e,r);let n=e=>e.reduce((a,l)=>a+(o.items[l]?.weight??0),0);return s={...s,iterations:s.iterations.map(e=>{if(e.id!==i.id)return e;let{closing:a,...l}=e;return {...l,endedAt:r,outcome:t==="cancel"?"cancelled":"completed",carryover:m}})},chunk23P7C25E_cjs.c(s,"sprint.closed","system",{id:i.id,reason:t,done:u,carryover:m,carriedQuestions:h,dropped:g,doneWeight:n(u),committedWeight:n(i.committed),spent:i.spent,budget:i.budget},r)}function ve(){return {name:"scrum",vocabulary:be,validateConfig:se,defaultStages:me,defaultRoles:ce,requiredCapabilities:["order-backlog","facilitate","deliver"],exclusiveCapabilities:["order-backlog"],plannerOptions(o){let t=O(o).inProgressWipLimit;return t===void 0?{schedulerMode:"level",dispatchStage:"in_progress"}:{schedulerMode:"level",dispatchStage:"in_progress",concurrencyCap:t}},candidates(o){let t=chunk2IKIBB73_cjs.f(o);return !t||t.closing?[]:Object.values(o.items).filter(r=>r.iteration===t.id&&(r.status==="todo"||r.status==="review")&&(r.stage==="sprint"||r.stage==="review"))},invariants(o,t){let r=chunk2IKIBB73_cjs.f(o),i=O(o),y=r?chunk2IKIBB73_cjs.c(r.budget,r.spent):{};return [`Sprint Goal: ${r?.goal??"(no open sprint)"}; Product Goal: ${i.productGoal}`,`Budget remaining: ${JSON.stringify(y)}; stop and hand off when it is gone`,`Definition of Done: ${i.definitionOfDone.map(u=>u.kind==="evidence"?`evidence ${u.evidenceKind}`:u.kind).join(", ")||"(none)"}`,`Do not change the scope of "${t.id}" or its acceptance criteria; raise open_questions instead`]},ceremonies:J(ve),rules:le(),metrics:o=>({...ae(o)}),humanDefaults:{gates:["sprint-review"]},afterComplete(o,t,r){let i=chunk2IKIBB73_cjs.f(o);return !i||!i.closing&&!chunk2IKIBB73_cjs.d(i.budget,i.spent)?o:Object.values(o.items).some(u=>u.iteration===i.id&&u.status==="in_progress")?i.closing?o:chunk23P7C25E_cjs.c({...o,iterations:o.iterations.map(u=>u.id===i.id?{...u,closing:true}:u)},"sprint.closing","system",{id:i.id},r):T(o,"budget",r)}}}exports.a=ie;exports.b=J;exports.c=se;exports.d=ae;exports.e=ce;exports.f=le;exports.g=me;exports.h=be;exports.i=O;exports.j=T;exports.k=ve;//# sourceMappingURL=chunk-4A4TD4MH.cjs.map
2
+ //# sourceMappingURL=chunk-4A4TD4MH.cjs.map