ex-workflow 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +64 -31
  3. package/dist/adapters/index.cjs +1 -1
  4. package/dist/adapters/index.d.cts +1 -1
  5. package/dist/adapters/index.d.ts +1 -1
  6. package/dist/adapters/index.mjs +1 -1
  7. package/dist/{budget-CezCinPF.d.cts → budget-Bm839Qw0.d.cts} +8 -7
  8. package/dist/{budget-Bd8KpGIr.d.ts → budget-Gckmqj74.d.ts} +8 -7
  9. package/dist/chunk-32NVJV5C.mjs +2 -0
  10. package/dist/chunk-32NVJV5C.mjs.map +1 -0
  11. package/dist/chunk-3GKYL6VB.mjs +6 -0
  12. package/dist/chunk-3GKYL6VB.mjs.map +1 -0
  13. package/dist/chunk-3O5MPAJT.cjs +2 -0
  14. package/dist/chunk-3O5MPAJT.cjs.map +1 -0
  15. package/dist/{chunk-C2IYMWE6.cjs → chunk-43GLYYA2.cjs} +3 -3
  16. package/dist/chunk-43GLYYA2.cjs.map +1 -0
  17. package/dist/chunk-4HG6A3SF.mjs +2 -0
  18. package/dist/chunk-4HG6A3SF.mjs.map +1 -0
  19. package/dist/chunk-6D6FL3XK.mjs +2 -0
  20. package/dist/chunk-6D6FL3XK.mjs.map +1 -0
  21. package/dist/chunk-7EF47R2J.mjs +2 -0
  22. package/dist/chunk-7EF47R2J.mjs.map +1 -0
  23. package/dist/chunk-BBI7AKJK.cjs +2 -0
  24. package/dist/chunk-BBI7AKJK.cjs.map +1 -0
  25. package/dist/{chunk-KLWZEXZU.mjs → chunk-BD76VFI4.mjs} +3 -3
  26. package/dist/chunk-BD76VFI4.mjs.map +1 -0
  27. package/dist/chunk-BHAEPYRJ.cjs +2 -0
  28. package/dist/chunk-BHAEPYRJ.cjs.map +1 -0
  29. package/dist/chunk-BYPFTO7P.mjs +2 -0
  30. package/dist/chunk-BYPFTO7P.mjs.map +1 -0
  31. package/dist/chunk-C4ISBUZR.mjs +2 -0
  32. package/dist/chunk-C4ISBUZR.mjs.map +1 -0
  33. package/dist/chunk-FDZB73PH.mjs +2 -0
  34. package/dist/chunk-FDZB73PH.mjs.map +1 -0
  35. package/dist/chunk-GKN5M4B7.cjs +2 -0
  36. package/dist/chunk-GKN5M4B7.cjs.map +1 -0
  37. package/dist/chunk-IDZ435YZ.mjs +2 -0
  38. package/dist/{chunk-KIQOUUEZ.mjs.map → chunk-IDZ435YZ.mjs.map} +1 -1
  39. package/dist/chunk-IIEKK2S3.cjs +2 -0
  40. package/dist/chunk-IIEKK2S3.cjs.map +1 -0
  41. package/dist/chunk-JNLWI4JM.mjs +2 -0
  42. package/dist/chunk-JNLWI4JM.mjs.map +1 -0
  43. package/dist/chunk-K4VSMIJZ.cjs +2 -0
  44. package/dist/chunk-K4VSMIJZ.cjs.map +1 -0
  45. package/dist/chunk-LCN4UNYK.cjs +2 -0
  46. package/dist/chunk-LCN4UNYK.cjs.map +1 -0
  47. package/dist/chunk-LIATP6LY.mjs +2 -0
  48. package/dist/chunk-LIATP6LY.mjs.map +1 -0
  49. package/dist/chunk-MB465DI4.mjs +2 -0
  50. package/dist/chunk-MB465DI4.mjs.map +1 -0
  51. package/dist/chunk-OSHBJIYD.cjs +2 -0
  52. package/dist/chunk-OSHBJIYD.cjs.map +1 -0
  53. package/dist/chunk-OVR5CK3R.cjs +2 -0
  54. package/dist/chunk-OVR5CK3R.cjs.map +1 -0
  55. package/dist/chunk-OZAYOPLB.mjs +2 -0
  56. package/dist/chunk-OZAYOPLB.mjs.map +1 -0
  57. package/dist/chunk-PNWRA4JU.cjs +2 -0
  58. package/dist/{chunk-PO2SPQJP.cjs.map → chunk-PNWRA4JU.cjs.map} +1 -1
  59. package/dist/chunk-QAENYYU6.cjs +2 -0
  60. package/dist/chunk-QAENYYU6.cjs.map +1 -0
  61. package/dist/chunk-RXY434DX.cjs +6 -0
  62. package/dist/chunk-RXY434DX.cjs.map +1 -0
  63. package/dist/chunk-SFYUJQYW.cjs +2 -0
  64. package/dist/chunk-SFYUJQYW.cjs.map +1 -0
  65. package/dist/chunk-TQR3VFZU.mjs +2 -0
  66. package/dist/chunk-TQR3VFZU.mjs.map +1 -0
  67. package/dist/chunk-U3RU5LOF.cjs +2 -0
  68. package/dist/chunk-U3RU5LOF.cjs.map +1 -0
  69. package/dist/chunk-UUWDQVIJ.mjs +2 -0
  70. package/dist/chunk-UUWDQVIJ.mjs.map +1 -0
  71. package/dist/chunk-VXOZIP77.cjs +2 -0
  72. package/dist/chunk-VXOZIP77.cjs.map +1 -0
  73. package/dist/chunk-W2P27645.cjs +2 -0
  74. package/dist/chunk-W2P27645.cjs.map +1 -0
  75. package/dist/chunk-WPVL27G4.mjs +2 -0
  76. package/dist/chunk-WPVL27G4.mjs.map +1 -0
  77. package/dist/chunk-YS6CXERQ.mjs +2 -0
  78. package/dist/chunk-YS6CXERQ.mjs.map +1 -0
  79. package/dist/chunk-Z43GUETW.cjs +2 -0
  80. package/dist/chunk-Z43GUETW.cjs.map +1 -0
  81. package/dist/cli/bin.cjs +1 -1
  82. package/dist/cli/bin.cjs.map +1 -1
  83. package/dist/cli/bin.mjs +1 -1
  84. package/dist/cli/bin.mjs.map +1 -1
  85. package/dist/cli/index.cjs +1 -1
  86. package/dist/cli/index.mjs +1 -1
  87. package/dist/experimentation/index.cjs +1 -1
  88. package/dist/experimentation/index.d.cts +2 -2
  89. package/dist/experimentation/index.d.ts +2 -2
  90. package/dist/experimentation/index.mjs +1 -1
  91. package/dist/index.cjs +1 -1
  92. package/dist/index.cjs.map +1 -1
  93. package/dist/index.d.cts +143 -15
  94. package/dist/index.d.ts +143 -15
  95. package/dist/index.mjs +1 -1
  96. package/dist/index.mjs.map +1 -1
  97. package/dist/investigation/index.cjs +1 -1
  98. package/dist/investigation/index.d.cts +2 -2
  99. package/dist/investigation/index.d.ts +2 -2
  100. package/dist/investigation/index.mjs +1 -1
  101. package/dist/kanban/index.cjs +1 -1
  102. package/dist/kanban/index.d.cts +2 -1
  103. package/dist/kanban/index.d.ts +2 -1
  104. package/dist/kanban/index.mjs +1 -1
  105. package/dist/registry/index.cjs +2 -0
  106. package/dist/registry/index.cjs.map +1 -0
  107. package/dist/registry/index.d.cts +25 -0
  108. package/dist/registry/index.d.ts +25 -0
  109. package/dist/registry/index.mjs +2 -0
  110. package/dist/registry/index.mjs.map +1 -0
  111. package/dist/schema/index.cjs +1 -1
  112. package/dist/schema/index.d.cts +2 -0
  113. package/dist/schema/index.d.ts +2 -0
  114. package/dist/schema/index.mjs +1 -1
  115. package/dist/scrum/index.cjs +1 -1
  116. package/dist/scrum/index.d.cts +3 -3
  117. package/dist/scrum/index.d.ts +3 -3
  118. package/dist/scrum/index.mjs +1 -1
  119. package/dist/{types-BScHXlRx.d.ts → types-DjePDfms.d.cts} +61 -22
  120. package/dist/{types-BScHXlRx.d.cts → types-DjePDfms.d.ts} +61 -22
  121. package/dist/types.cjs +1 -1
  122. package/dist/types.d.cts +1 -1
  123. package/dist/types.d.ts +1 -1
  124. package/dist/types.mjs +1 -1
  125. package/dist/waterfall/index.cjs +1 -1
  126. package/dist/waterfall/index.d.cts +1 -1
  127. package/dist/waterfall/index.d.ts +1 -1
  128. package/dist/waterfall/index.mjs +1 -1
  129. package/package.json +17 -3
  130. package/dist/chunk-2FRRD6A3.mjs +0 -2
  131. package/dist/chunk-2FRRD6A3.mjs.map +0 -1
  132. package/dist/chunk-6P3OKXSK.mjs +0 -2
  133. package/dist/chunk-6P3OKXSK.mjs.map +0 -1
  134. package/dist/chunk-7FS6KWTG.cjs +0 -2
  135. package/dist/chunk-7FS6KWTG.cjs.map +0 -1
  136. package/dist/chunk-7QQY4KJ2.mjs +0 -2
  137. package/dist/chunk-7QQY4KJ2.mjs.map +0 -1
  138. package/dist/chunk-AD4Z3JBL.cjs +0 -2
  139. package/dist/chunk-AD4Z3JBL.cjs.map +0 -1
  140. package/dist/chunk-ATCJ4IHP.mjs +0 -2
  141. package/dist/chunk-ATCJ4IHP.mjs.map +0 -1
  142. package/dist/chunk-C2IYMWE6.cjs.map +0 -1
  143. package/dist/chunk-EACZBAP3.cjs +0 -2
  144. package/dist/chunk-EACZBAP3.cjs.map +0 -1
  145. package/dist/chunk-EFCUM6DK.mjs +0 -2
  146. package/dist/chunk-EFCUM6DK.mjs.map +0 -1
  147. package/dist/chunk-EHBQBXWA.cjs +0 -2
  148. package/dist/chunk-EHBQBXWA.cjs.map +0 -1
  149. package/dist/chunk-FTS75UIU.mjs +0 -2
  150. package/dist/chunk-FTS75UIU.mjs.map +0 -1
  151. package/dist/chunk-HCRVWMG4.cjs +0 -2
  152. package/dist/chunk-HCRVWMG4.cjs.map +0 -1
  153. package/dist/chunk-KIQOUUEZ.mjs +0 -2
  154. package/dist/chunk-KLWZEXZU.mjs.map +0 -1
  155. package/dist/chunk-NDCQTRIV.mjs +0 -2
  156. package/dist/chunk-NDCQTRIV.mjs.map +0 -1
  157. package/dist/chunk-PMUGU5UJ.cjs +0 -2
  158. package/dist/chunk-PMUGU5UJ.cjs.map +0 -1
  159. package/dist/chunk-PO2SPQJP.cjs +0 -2
  160. package/dist/chunk-QZ6HD6DE.mjs +0 -6
  161. package/dist/chunk-QZ6HD6DE.mjs.map +0 -1
  162. package/dist/chunk-RL27372B.cjs +0 -2
  163. package/dist/chunk-RL27372B.cjs.map +0 -1
  164. package/dist/chunk-S3BXVHO7.cjs +0 -2
  165. package/dist/chunk-S3BXVHO7.cjs.map +0 -1
  166. package/dist/chunk-SP5MC7RR.mjs +0 -2
  167. package/dist/chunk-SP5MC7RR.mjs.map +0 -1
  168. package/dist/chunk-SVGTSPZF.cjs +0 -2
  169. package/dist/chunk-SVGTSPZF.cjs.map +0 -1
  170. package/dist/chunk-SYLO7FUL.mjs +0 -2
  171. package/dist/chunk-SYLO7FUL.mjs.map +0 -1
  172. package/dist/chunk-T3V5UE34.mjs +0 -2
  173. package/dist/chunk-T3V5UE34.mjs.map +0 -1
  174. package/dist/chunk-TS66RAJR.cjs +0 -2
  175. package/dist/chunk-TS66RAJR.cjs.map +0 -1
  176. package/dist/chunk-U23FUYPD.cjs +0 -6
  177. package/dist/chunk-U23FUYPD.cjs.map +0 -1
  178. package/dist/chunk-U6GHFKKE.mjs +0 -2
  179. package/dist/chunk-U6GHFKKE.mjs.map +0 -1
  180. package/dist/chunk-YJQ5YJ7S.cjs +0 -2
  181. package/dist/chunk-YJQ5YJ7S.cjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.0 (2026-11-03)
4
+
5
+ Layered architecture: the engine is split into four code layers (core → common → interface → methodologies) under one written set of principles, so a methodology, built-in or custom, is a composition of shared pieces; the decisions are in the design spec, section 26. Every change is additive.
6
+
7
+ - Principles: `docs/principles.md` lists the engine invariants as numbered rules, each naming the file that enforces it and the test that pins it.
8
+ - Layout: the kernel moves to `src/core/`, the five methodologies to `src/methodologies/<name>/`; `src/common/` and `src/interface/` are new. `src/core/items.ts` and `src/core/roles.ts` are split into one responsibility per file (`items/{stage,record,move,evidence,blockers}.ts`, `roles/{lookup,registry,guards}.ts`); the Investigation and Experimentation record types move to `src/core/records/` and are re-exported from their entries unchanged. Package `exports` and `dist/<entry>/index.*` paths are unchanged.
9
+ - Layer check: `scripts/check-layers.mjs` (`pnpm run check:layers`, run by `pnpm run ci` and the pre-commit hook) reads every module specifier with TypeScript's parser (static and type-only imports, `export … from`, dynamic `import()`, `require()`, `import("…")` types; comments and strings never hide or create one) and fails on an import that goes to a higher layer, naming both files (the resolved file, extensionless specifiers included) and both layers, or on a `node:` built-in or package other than `ex-flow` and `exsorted` (the exact name or a real subpath; `ex-flow/../x` fails) imported from `src/core`, `src/common`, `src/interface` or `src/methodologies`; it reads every `.ts`, `.mts`, `.cts`, `.tsx`, `.js`, `.mjs` and `.cjs` file under `src/` (declaration files and tests excepted) and warns above five runtime exports per file (the generated `src/schema/generated.ts` excepted). In the same four directories `pnpm lint` refuses `Date.now`, `Math.random`, `fetch`, `process`, `crypto`, `performance`, `setTimeout` and `setInterval` (an oxlint override), so rule 1 of `docs/principles.md` ("Core is pure") is checked for imports and these globals; it states what stays unchecked. `CONTRIBUTING.md` section 9 gains the layer, placement and file rules; a root `AGENTS.md` links to it.
10
+ - Custom methodology names: `WorkflowState`, `Methodology`, `Rule`, `Ceremony`, `ApplyResult`, `NextResult`, `PlanResult`, `LessonOutcome`, `InitInput` and `CreateStateInput` take an optional name parameter `N extends string = MethodologyName`; the default is the 1.1 type exactly, and `MethodologyName` itself is unchanged. Kernel functions that return a state are generic in `N`; `createState` and `init` keep the 1.1 signature as their first overload, every now-generic public kernel function repeats its 1.1 signature as its last overload, and so does every read-only kernel function that takes `WorkflowState<string>` (`getItem`, `checkGate`, `openIteration`, `canDo` and the 18 other exported readers), so `Parameters<typeof fn>` and `ReturnType<typeof fn>` of every exported function read the 1.1 types and a wrapper typed through them compiles unchanged. `test/types-compat.test.ts` proves both, and that a `Methodology<Cfg, "triage">` runs `init`, a ceremony, `next` and `complete`.
11
+ - Extension state: `WorkflowState.ext` (optional), read and written through the new root exports `readExt(state, key)` and `writeExt(state, key, value)` (type `LegacyExtRecords`). Investigation and Experimentation store their record in `ext.investigation` / `ext.experimentation` and mirror it to the top-level `state.investigation` / `state.experimentation`, now deprecated, for SDK code that reads those fields. The mirror is in memory and for SDK readers; on disk only `ext` is written: `saveState` leaves the legacy field out when `ext.<name>` exists and `loadState` sets it back to the same record (when a file carries both, `ext` wins). The mirrors are read-only: once `ext.<name>` exists, a write to the legacy field is ignored. A state without `ext` is read through the legacy field. The state schema validates `ext.investigation` / `ext.experimentation` as their records (new type `WorkflowExt`); other `ext` keys hold any JSON value.
12
+ - Registry: the new entry `ex-workflow/registry` exports `registerMethodology`, `methodologyFactory` and `registeredMethodologies`, with the five built-ins pre-registered (types `MethodologyFactory`, `MethodologyRegistry`). A taken or unknown name fails `invalid-input`; the unknown-name fix lists the known names. The CLI resolves `exwf init <name>` and a loaded state's methodology through it. It is its own entry so that core plus one methodology does not carry the other four.
13
+ - Common checks: `independenceConflicts(verifiers, workers)` and `frozenChanges(frozen, supplied, keys?)`, exported from the root entry, replace the inline independence and frozen-input checks of Investigation and Experimentation; error codes, messages and fixes are unchanged.
14
+ - Dependency: `ex-flow` `^1.1.0` → `^1.1.1`, which detects a long dependency cycle instead of overflowing the stack ([ex-flow#2](https://github.com/Ink01101011/ex-flow/issues/2)); `next` on a state whose items form a cycle of thousands of nodes now throws `WorkflowError` `planner-error` instead of a `RangeError`.
15
+ - Known limitation: no downgrade for Investigation and Experimentation; 1.1.x cannot load a state 1.2 wrote for them, because the 1.1 state schema rejects `ext`.
16
+ - Known limitation: a state whose `methodology` is a custom name cannot go through `saveState`, `loadState` or any `exwf` command, because the state schema keeps `methodology` as the five built-in names; a host running a custom methodology persists its state itself.
17
+ - Size: budgets re-recorded at measured size, owner approved (layering 2026-11-03, fix wave 2026-11-04): `dist/index.mjs` 1189 → 1330 B, `dist/kanban/index.mjs` 818 → 848 B, `dist/waterfall/index.mjs` 964 → 994 B, `dist/investigation/index.mjs` 216 → 276 B, `dist/experimentation/index.mjs` 385 → 445 B, `core+scrum` 60085 → 61031 B, `core+kanban` 67785 → 68951 B, `core+waterfall` 68220 → 69379 B, `core+investigation` 52521 → 53566 B, `core+experimentation` 56091 → 57058 B, `schema` 28690 → 28942 B (the accessors, the two common checks, the schema annotations and `WorkflowExt`, then the fixes listed below: stricter `assertId`, own-property lookups, loaded-state guards, the registry factory check, frozen default constants, the `writeExt` and `frozenChanges` edge cases, the registry's wrapped factory error); `dist/registry/index.mjs` (542 B) and `core+registry` (159765 B) seeded at measured size.
18
+
19
+ Fixed (security and robustness review of 1.2.0, spec 26 rows "U12"):
20
+
21
+ - `loadState` validates `ext.investigation` and `ext.experimentation`: a crafted record (`rounds: null`, `candidates: null`) fails `invalid-input` instead of a later `TypeError` in `status`, `metrics`, `stop` or `report`.
22
+ - `state.json` no longer stores the Investigation / Experimentation record twice (see Extension state above), which halves its size and its schema validation for those runs.
23
+ - Kanban `metrics` and `operations-review` no longer crash on a column whose id is an `Object.prototype` member name (`toString`); the Kanban replenishment rule, Waterfall metrics and config defaults, the Scrum daily report and the role-manifest merge in `loadState` look ids up as own properties too.
24
+ - Ids: `assertId` (items, roles, candidates, columns, phases, ext keys, methodology names) also refuses ids longer than 128 characters, Windows device names (`CON`, `PRN`, `AUX`, `NUL`, `COM1`-`COM9`, `LPT1`-`LPT9`, any case, with or without an extension) and every `Object.prototype` member name (`toString`, `valueOf`, `hasOwnProperty`, ...), with `invalid-input`. No id in the compatibility fixtures or the tests is affected. The rules apply to an id being created: an id a 1.1 repo already holds (a stored item, a role manifest) is not re-checked when it is loaded, gets a brief or a handoff.
25
+ - File adapter: a stale lock that cannot be removed fails `invalid-input` naming the lock after the retries instead of looping forever. These also fail `invalid-input`: `mkdir` / `open` failures of the lock, an item stored under a key other than its id, a deeply nested value (instead of the stack-overflow `RangeError`; any other `RangeError` is rethrown as it is), a `saveBrief` / `saveHandoff` id that is not a safe file name (empty, `/`, `\`, NUL, `..`, a leading `.`, or a path outside `.workflow/`: `a/b`, `a..b`; an id such as `my item`, which 1.1.1 dispatched, still gets its brief and handoff). A role manifest with id `__proto__` is skipped, as in 1.1.1, so it neither pollutes `roles` nor fails a command, and a handoff `seq` that is not a non-negative integer. `saveBrief` refuses an item id that differs from an existing brief's only in letter case, because the two files are one on macOS and Windows; `exwf next` checks every brief name of the batch before writing any, so such a clash writes no brief and leaves the state unchanged.
26
+ - CLI: `exwf complete --duration-ms` must be a number of milliseconds that dates the start (`1e17` and `1e300` fail `invalid-input` instead of a `RangeError`; a fraction such as `1.5` is accepted as before, and a negative value still fails `accounting-invalid`); `exwf validate` with an action file that is not an object with a string `type` fails `invalid-input` instead of a `TypeError`.
27
+ - Investigation and Experimentation: a damaged or hand-edited state (a phase with no round, a round with no result, no `investigation` iteration, a review with no conclusion, a `replayOf` naming no round, a `selected` naming no candidate) fails `invalid-input` naming the inconsistency instead of a `TypeError`.
28
+ - `registerMethodology` calls a custom factory once and refuses a result that is not a `Methodology` named as registered (`invalid-input`); a factory that throws fails `invalid-input` with its original message (a `WorkflowError` it throws passes through); a thrown null-prototype value no longer escapes as a raw `TypeError`.
29
+ - Exported defaults are frozen with the same values and types: `ZERO_SPENT`, `SCRUM_VOCABULARY`, `KANBAN_VOCABULARY`, `WATERFALL_VOCABULARY`, and deeply `DEFAULT_COLUMNS`, `KANBAN_CADENCES`, `CLASSES`, `DEFAULT_PHASE_IDS`, `DEFAULT_DELIVERABLES`, `DEFAULT_DELIVER_BY`; a validated Kanban config gets a deep copy of the default columns.
30
+ - `writeExt(state, key, undefined)` on a state with no `ext` no longer adds an empty `ext: {}`.
31
+ - `frozenChanges` reads only own fields of the supplied record, so an inherited member equal to the frozen value no longer passes as unchanged; its documentation now states the missing-field rule it applies (a missing field reads as `undefined`, a change unless the frozen value is `undefined` too). The engine's own calls are unaffected.
32
+ - Investigation `plan` / `next` read the investigation record once per call instead of once per item (`candidates` on 10,000 items: 1.48 → 1.07 ms median).
33
+ - `docs/principles.md`: rule 1 names what checks it (imports and the lint override) and what does not; rule 6 names `checkGate` as the enforcer of the author check, since the `conflict-of-interest` entry in `src/core/rules.ts` applies only to a direct `validateAction` call with action type `complete`.
34
+ - Regression test for the ex-flow cycle fix: a 5,000-item cycle closed through `editItem` makes `next` fail `planner-error`.
35
+
36
+ Compatibility: additive. `state.json` gains one optional field, `ext`; Investigation and Experimentation write their record there and, in memory, to the legacy `investigation` / `experimentation` fields (dual-write); on disk only `ext.<name>` is written and `loadState` restores the mirror, so a 1.2 `state.json` of those two methodologies has no top-level legacy field once a ceremony has run (a file that has both loads with `ext` winning). The legacy fields stay in the state type and the schema and are marked deprecated; 2.0 removes them. The mirrors serve SDK code reading `state.investigation` / `state.experimentation`; they do not let 1.1.x load a state 1.2 wrote for those two methodologies, because the 1.1 root schema rejects `ext` (no downgrade). A `.workflow/state.json` written by any earlier release loads unchanged; `test/compat.test.ts` loads the 1.1.1 fixtures, which have no `ext`, runs a ceremony, saves, reloads and finds the legacy field to be the `ext.<name>` record, with no legacy key in the file. Schema documents: still ten; `workflowStateSchema` gains `ext` (definition `WorkflowExt`: `investigation` and `experimentation` validated as their records, any other key open) and `deprecated: true` on the two legacy fields, and `JsonSchema` gains the optional annotation `deprecated`, which the validator ignores. Event kinds: unchanged (69). Exports: the root entry gains `readExt`, `writeExt`, `independenceConflicts` and `frozenChanges` (and the type `LegacyExtRecords`); the new entry `ex-workflow/registry` exports `registerMethodology`, `methodologyFactory` and `registeredMethodologies`; nothing is removed. CLI: `USAGE` is unchanged and an unregistered `init` name still prints the usage (exit 2); `complete --duration-ms` now refuses a value whose start time `Date` cannot hold (`1e17`, `1e300`; a fraction is still accepted) and `validate` requires an object action with a string `type` (both `invalid-input`, where 1.1 crashed). Input validation is tighter, as listed under Fixed: `assertId` refuses over-long ids, Windows device names and `Object.prototype` member names for ids being created (a `.workflow/` written by 1.1 loads and dispatches as before; the refusals left are an item id that is not a safe file name (`/`, `\`, NUL, `..`, a leading `.`, empty, which 1.1.1 also could not write safely) and, in one `exwf next` batch, ids that differ only in letter case, which 1.1.1 let overwrite one brief silently and 1.2 refuses before writing any), and `registerMethodology` checks the factory's result; every new refusal uses the existing code `invalid-input`, so the error codes are unchanged. Exported default constants are frozen: a write to one throws in strict mode instead of changing the default process-wide. Types: new `WorkflowExt` (the type of `ext`). No behaviour change for any built-in methodology; `Parameters<typeof fn>` and `ReturnType<typeof fn>` of every exported function read the 1.1 types (each generic or widened function repeats its 1.1 signature as its last overload); a check of every exported function of every entry against the 1.1.1 types finds no difference. Runtime dependencies: `ex-flow` `^1.1.0` → `^1.1.1`; `exsorted` unchanged. `VERSION` is `"1.2.0"`.
37
+
3
38
  ## 1.1.1 (2026-10-30)
4
39
 
5
40
  Fix wave for the ten findings of the 1.1.0 code review (Investigation and Experimentation); the decisions are in the design spec, section 25. No new ceremony, key, export, event kind or schema document.
package/README.md CHANGED
@@ -8,17 +8,18 @@
8
8
  - Every error names the rule, the item and a concrete fix.
9
9
  - Two runtime dependencies: [`ex-flow`](https://www.npmjs.com/package/ex-flow) (DAG planner) and [`exsorted`](https://www.npmjs.com/package/exsorted).
10
10
  - Works with any LLM host: the engine hands out **briefs**, you run them with your agents and hand back **handoffs**.
11
+ - The invariants the engine enforces, each with the file and the test behind it: [docs/principles.md](docs/principles.md).
11
12
 
12
13
  ## Contents
13
14
 
14
- 1. [Install](#install)
15
- 2. [Pick a methodology](#pick-a-methodology)
16
- 3. [How a run works](#how-a-run-works)
17
- 4. [Quick start: Scrum](#quick-start-scrum)
18
- 5. [Quick start: Kanban](#quick-start-kanban)
19
- 6. [Quick start: Waterfall](#quick-start-waterfall)
20
- 7. [Standalone investigation and experimentation](#standalone-investigation-and-experimentation)
21
- 8. [Persisting state](#persisting-state)
15
+ 1. [Pick a methodology](#pick-a-methodology)
16
+ 2. [How a run works](#how-a-run-works)
17
+ 3. [Quick start: Scrum](#quick-start-scrum)
18
+ 4. [Quick start: Kanban](#quick-start-kanban)
19
+ 5. [Quick start: Waterfall](#quick-start-waterfall)
20
+ 6. [Standalone investigation and experimentation](#standalone-investigation-and-experimentation)
21
+ 7. [Persisting state](#persisting-state)
22
+ 8. [Custom methodologies and extension state](#custom-methodologies-and-extension-state)
22
23
  9. [CLI reference (`exwf`)](#cli-reference-exwf)
23
24
  10. [Configuration](#configuration)
24
25
  11. [Ceremonies](#ceremonies)
@@ -31,29 +32,18 @@
31
32
  18. [Contributing](#contributing)
32
33
  19. [License](#license)
33
34
 
34
- ## Install
35
-
36
- ```sh
37
- npm install ex-workflow # or: pnpm add ex-workflow
38
- npx exwf # prints the CLI usage
39
- ```
40
-
41
- `latest` is the supported line (1.1.1). Pre-releases, when any, are published under the `stage` dist-tag.
42
-
43
35
  ## Pick a methodology
44
36
 
45
- | | Scrum (`ex-workflow/scrum`) | Kanban (`ex-workflow/kanban`) | Waterfall (`ex-workflow/waterfall`) |
46
- |---|---|---|---|
47
- | Fits | a goal delivered in budgeted sprints | a continuous flow of requests | a phase-gated project with a frozen baseline |
48
- | Unit of control | sprint budget (tokens, turns, wall-clock) | WIP limits per column, classes of service | human-approved gate per phase |
49
- | Flow | backlog → sprint → review | options → ready → dev → review → done | work → review → done, inside each phase |
50
- | Preset roles | product-owner, scrum-master, developer | service-request-manager, service-delivery-manager, worker | project-manager, business-analyst, architect, developer, qa, release-manager |
51
- | Ceremonies | refine, plan, commit, uncommit, daily, review, retro, cancel | replenishment, delivery-planning, service-delivery-review, operations-review, risk-review, strategy-review | kickoff, gateReview, changeControlBoard, phaseRetrospective |
52
- | Metrics | velocity, cost per point, budget utilisation | lead and cycle time, throughput, WIP, flow efficiency, aging, CFD, SLE compliance | phase report, requirement coverage, traceability matrix |
53
-
54
- Scrum, Kanban and Waterfall share one core: the same item model, the same brief and handoff contracts, the same CLI and the same `.workflow/` files. Roles are data (capabilities, not names), so you can replace or extend the presets with `exwf role add`.
37
+ | | Scrum (`ex-workflow/scrum`) | Kanban (`ex-workflow/kanban`) | Waterfall (`ex-workflow/waterfall`) | Investigation (`ex-workflow/investigation`) | Experimentation (`ex-workflow/experimentation`) |
38
+ |---|---|---|---|---|---|
39
+ | Fits | a goal delivered in budgeted sprints | a continuous flow of requests | a phase-gated project with a frozen baseline | one bounded question answered from preregistered experiments | competing candidates compared against a frozen baseline and harness |
40
+ | Unit of control | sprint budget (tokens, turns, wall-clock) | WIP limits per column, classes of service | human-approved gate per phase | round limit and budget, independent replay and conclusion review | concurrency cap, per-candidate and total budgets, independent validation at the exact SHA |
41
+ | Flow | backlog → sprint → review | options → ready → dev → review → done | work → review → done, inside each phase | intake → execute → observed | candidate → building → validation → done |
42
+ | Preset roles | product-owner, scrum-master, developer | service-request-manager, service-delivery-manager, worker | project-manager, business-analyst, architect, developer, qa, release-manager | investigator, replay-worker, conclusion-reviewer | coordinator, builder, validator, integrator |
43
+ | Ceremonies | refine, plan, commit, uncommit, daily, review, retro, cancel | replenishment, delivery-planning, service-delivery-review, operations-review, risk-review, strategy-review | kickoff, gateReview, changeControlBoard, phaseRetrospective | intake, hypotheses, preregister, observe, update-belief, conclude, review-conclusion, stop | freeze, provision, start, submit, validate, compare, integrate, validate-integration, terminate, stop, cleanup |
44
+ | Metrics | velocity, cost per point, budget utilisation | lead and cycle time, throughput, WIP, flow efficiency, aging, CFD, SLE compliance | phase report, requirement coverage, traceability matrix | rounds, valid and invalid runs | candidates by outcome, spent, tokens per candidate |
55
45
 
56
- Standalone [Investigation and Experimentation](#standalone-investigation-and-experimentation) add evidence-driven inquiry and isolated candidate comparison; each runs in its own state.
46
+ All five share one core: the same item model, the same brief and handoff contracts, the same CLI and the same `.workflow/` files. Roles are data (capabilities, not names), so you can replace or extend the presets with `exwf role add`. [Investigation and Experimentation](#standalone-investigation-and-experimentation) each run alone, in their own `.workflow/`.
57
47
 
58
48
  ## How a run works
59
49
 
@@ -217,6 +207,42 @@ Layout under the project root:
217
207
 
218
208
  The lock is created exclusively, retried for about two seconds and taken over when older than 60 s. Read-only commands do not lock. If a crashed process left a lock behind and a command reports that another `exwf` holds it, delete the file.
219
209
 
210
+ ## Custom methodologies and extension state
211
+
212
+ `Methodology` and `WorkflowState` take the methodology name as an optional second type parameter. It defaults to the five built-in names, so code written for the built-ins type-checks unchanged; a custom methodology declares its own name and runs on the same core:
213
+
214
+ ```ts
215
+ import { init, next, complete, type Methodology } from "ex-workflow";
216
+
217
+ function triage(): Methodology<TriageConfig, "triage"> {
218
+ return { name: "triage", /* vocabulary, stages, roles, ceremonies, rules, metrics, ... */ };
219
+ }
220
+ let { state } = init({ methodology: triage(), config: { queue: "support" } }); // WorkflowState<"triage">
221
+ ```
222
+
223
+ `ex-workflow/registry` maps names to factories, with the five built-ins pre-registered. Use it to resolve a loaded state's `methodology`, or to register your own:
224
+
225
+ ```ts
226
+ import { methodologyFactory, registerMethodology, registeredMethodologies } from "ex-workflow/registry";
227
+
228
+ const m = methodologyFactory(state.methodology)(); // unknown name: invalid-input, the fix lists the known names
229
+ registerMethodology("triage", triage); // calls triage() once to check it; a taken name or a non-Methodology result: invalid-input
230
+ registeredMethodologies(); // ["scrum", "kanban", "waterfall", "investigation", "experimentation", "triage"]
231
+ ```
232
+
233
+ The registry is its own entry so that importing core plus one methodology does not pull in the other four. Custom methodologies are SDK-only in 1.2: `exwf init <name>` resolves through the same registry, but the `exwf` binary cannot load third-party modules, and the file adapter only accepts the five built-in names (see [Known limitations](#known-limitations)).
234
+
235
+ A methodology keeps its own record in `state.ext`, keyed by its name, and reads and writes it only through the accessors:
236
+
237
+ ```ts
238
+ import { readExt, writeExt } from "ex-workflow";
239
+
240
+ const queue = readExt<string[]>(state, "triage") ?? [];
241
+ state = writeExt(state, "triage", [...queue, "T-1"]); // returns a new state; undefined removes the key
242
+ ```
243
+
244
+ Investigation and Experimentation store their record under `ext.investigation` / `ext.experimentation` and mirror it to the deprecated top-level `state.investigation` / `state.experimentation` in memory, so SDK code that reads those fields keeps working. On disk only `ext` is stored: `saveState` leaves the mirror out and `loadState` sets it back to the same record (if a hand-edited `state.json` carries both, `ext` wins). The mirrors are read-only: once `ext.<name>` exists the engine reads only it, and a write to the legacy field is ignored; write through `writeExt`. `readExt(state, "investigation")` (or `"experimentation"`) is typed, and on a state written before 1.2, which has no `ext`, it reads the legacy field.
245
+
220
246
  ## CLI reference (`exwf`)
221
247
 
222
248
  Run from the directory that holds `.workflow/`. Every command prints JSON on stdout. Exit 0 = ok, exit 1 = `{ ok: false, error }`, exit 2 = usage. `--by` defaults to `human`. Flags take `--flag value` (not `--flag=value`); a value that starts with `--` must come through a JSON input file.
@@ -403,30 +429,37 @@ The CLI validates state, role manifests, items, patches and handoffs with these
403
429
 
404
430
  | Import | Contents |
405
431
  |---|---|
406
- | `ex-workflow` | core: `init`, `addItem`, `editItem`, `next`, `complete`, `decide`, `applyAction`, `validateAction`, `changeConfig`, `correctAccounting`, `clearBlocker`, `raiseBlocker`, `registerRole`, `openQuestions`, `WorkflowError`, `VERSION`, … |
432
+ | `ex-workflow` | core: `init`, `addItem`, `editItem`, `next`, `complete`, `decide`, `applyAction`, `validateAction`, `changeConfig`, `correctAccounting`, `clearBlocker`, `raiseBlocker`, `registerRole`, `openQuestions`, `readExt`, `writeExt`, `independenceConflicts`, `frozenChanges`, `WorkflowError`, `VERSION`, … |
407
433
  | `ex-workflow/scrum` | `scrum()`, `scrumMetrics`, `dailyReport`, `closeSprint`, presets |
408
434
  | `ex-workflow/kanban` | `kanban()`, `board`, `kanbanMetrics`, `opsReport`, `riskReport`, `cadencesDue`, `DEFAULT_COLUMNS`, presets |
409
435
  | `ex-workflow/waterfall` | `waterfall()`, `phaseReport`, `traceabilityMatrix`, `waterfallMetrics`, `baselinePhase`, `reopenPhases`, presets |
410
436
  | `ex-workflow/investigation` | `investigation()`, `validateInvestigationConfig`; types `InvestigationConfig`, `InvestigationState`, `InvestigationRound`, `InvestigationConclusion`, `Hypothesis`, `Experiment`, `Observation`, `BeliefUpdate` |
411
437
  | `ex-workflow/experimentation` | `experimentation()`, `validateExperimentationConfig`, `experimentationCeremonies`, `experimentationMetrics`, `experimentationReport`, `experimentationRoles`, `experimentationRules`, `experimentationStages`; types `ExperimentationConfig`, `ExperimentationState`, `ExperimentCandidate` |
438
+ | `ex-workflow/registry` | `registerMethodology`, `methodologyFactory`, `registeredMethodologies` (five built-ins pre-registered); types `MethodologyFactory`, `MethodologyRegistry` |
412
439
  | `ex-workflow/adapters` | `loadState`, `saveState`, `saveBrief`, `saveHandoff`, `withStateLock`, `WORKFLOW_DIR` |
413
440
  | `ex-workflow/schema` | the ten schema documents, `validate`, `assertValid` |
414
441
  | `ex-workflow/cli` | `runCommand`, `parseArgs`, `USAGE`: the `exwf` command as a library |
415
442
  | `ex-workflow/types` | every public type |
416
443
 
417
- Each entry ships ESM, CommonJS and `.d.ts`. Core plus one methodology is about 51–68 kB minified.
444
+ Each entry ships ESM, CommonJS and `.d.ts`. Core plus one methodology is about 53–69 kB minified.
418
445
 
419
446
  ## Compatibility and versioning
420
447
 
421
448
  - Semver from 1.0.0. The public surface (exports of every entry point, the CLI commands, the ten schema documents, the 69 event kinds) is frozen by test: a removal is a major version, an addition a minor one.
422
449
  - A `.workflow/state.json` written by any earlier release loads unchanged; the test suite replays state files from every published pre-release.
450
+ - **Deprecated in 1.2:** the top-level `state.investigation` and `state.experimentation` fields. They are still set in memory and for SDK readers, as read-only mirrors of `ext.investigation` / `ext.experimentation` (on disk only `ext` is written; `loadState` restores the mirror), so SDK code reading `state.investigation` / `state.experimentation` sees the same record; once `ext.<name>` exists a write to the legacy field is ignored. Read with `readExt` and write with `writeExt` instead. The mirrors do not make a 1.2 state loadable by 1.1.x (see [Known limitations](#known-limitations)). 2.0 removes the mirrors.
423
451
  - Behaviour changes are listed per release in [CHANGELOG.md](CHANGELOG.md).
424
452
 
425
453
  ## Known limitations
426
454
 
427
455
  Deliberate, documented, and stable within 1.x.
428
456
 
429
- - **Stale lock takeover** narrows the race to the gap between the stat and the unlink; no portable call closes it. On file systems without inodes (FAT, exFAT, some shares) only the mtime is compared. If a stale lock cannot be unlinked (read-only directory, EPERM), delete it by hand.
457
+ - **A custom methodology's state cannot go through the file adapter or the CLI.** The state schema accepts only the five built-in names in `methodology`, so `saveState`, `loadState` and every `exwf` command refuse it. Keep such a state through the SDK and persist it yourself.
458
+ - **No downgrade for Investigation and Experimentation.** 1.1.x cannot load a state that 1.2 wrote for those two methodologies: the 1.1 state schema rejects the `ext` field, and the legacy mirrors do not change that. Keep a run on 1.2 once 1.2 has saved it.
459
+
460
+ - **Stale lock takeover** narrows the race to the gap between the stat and the unlink; no portable call closes it. On file systems without inodes (FAT, exFAT, some shares) only the mtime is compared. If a stale lock cannot be unlinked (read-only directory, EPERM), the command gives up after its retries with `invalid-input` naming the lock file; delete it by hand.
461
+ - **Item ids that differ only in letter case cannot both get a brief file.** On macOS and Windows `briefs/A.json` and `briefs/a.json` are one file, so `exwf next` checks every brief name of the batch first and, when an item's id differs from another item's (in the same batch, or with an existing brief) only in case, refuses the whole dispatch with `invalid-input` naming both: no brief is written and the state is unchanged. `saveBrief` refuses such an id the same way. Give ids that differ by more than case (re-add one item under a new id).
462
+ - **An id long enough to hit the OS file-name limit fails at write time.** `exwf next` writes `briefs/<id>.json` per item, so such an id fails `invalid-input` when its brief is written, possibly after earlier briefs of the batch were written. 1.1.1 behaved the same.
430
463
  - **Blockers are owned by a human.** Finishing a follow-up does not clear its blocker; `unblock` does.
431
464
  - **Direct primitives bypass the baseline.** `addItem` and `editItem` called directly do not check `baseline-immutable`; `applyAction` and the CLI do.
432
465
  - **Kanban cadences count turns, not time.** The engine has no clock; wall-clock schedules are the host's job. `wipBypass` is a column total.
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkU23FUYPD_cjs=require('../chunk-U23FUYPD.cjs');require('../chunk-C2IYMWE6.cjs'),require('../chunk-S3BXVHO7.cjs');Object.defineProperty(exports,"WORKFLOW_DIR",{enumerable:true,get:function(){return chunkU23FUYPD_cjs.a}});Object.defineProperty(exports,"loadState",{enumerable:true,get:function(){return chunkU23FUYPD_cjs.e}});Object.defineProperty(exports,"saveBrief",{enumerable:true,get:function(){return chunkU23FUYPD_cjs.f}});Object.defineProperty(exports,"saveHandoff",{enumerable:true,get:function(){return chunkU23FUYPD_cjs.g}});Object.defineProperty(exports,"saveState",{enumerable:true,get:function(){return chunkU23FUYPD_cjs.d}});Object.defineProperty(exports,"statePath",{enumerable:true,get:function(){return chunkU23FUYPD_cjs.b}});Object.defineProperty(exports,"withStateLock",{enumerable:true,get:function(){return chunkU23FUYPD_cjs.c}});//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var chunkRXY434DX_cjs=require('../chunk-RXY434DX.cjs');require('../chunk-BBI7AKJK.cjs'),require('../chunk-43GLYYA2.cjs'),require('../chunk-OSHBJIYD.cjs');Object.defineProperty(exports,"WORKFLOW_DIR",{enumerable:true,get:function(){return chunkRXY434DX_cjs.a}});Object.defineProperty(exports,"loadState",{enumerable:true,get:function(){return chunkRXY434DX_cjs.e}});Object.defineProperty(exports,"saveBrief",{enumerable:true,get:function(){return chunkRXY434DX_cjs.g}});Object.defineProperty(exports,"saveHandoff",{enumerable:true,get:function(){return chunkRXY434DX_cjs.h}});Object.defineProperty(exports,"saveState",{enumerable:true,get:function(){return chunkRXY434DX_cjs.d}});Object.defineProperty(exports,"statePath",{enumerable:true,get:function(){return chunkRXY434DX_cjs.b}});Object.defineProperty(exports,"withStateLock",{enumerable:true,get:function(){return chunkRXY434DX_cjs.c}});//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1,4 +1,4 @@
1
- import { W as WorkflowState, B as Brief, H as Handoff } from '../types-BScHXlRx.cjs';
1
+ import { W as WorkflowState, B as Brief, H as Handoff } from '../types-DjePDfms.cjs';
2
2
 
3
3
  declare const WORKFLOW_DIR = ".workflow";
4
4
  declare function statePath(root: string): string;
@@ -1,4 +1,4 @@
1
- import { W as WorkflowState, B as Brief, H as Handoff } from '../types-BScHXlRx.js';
1
+ import { W as WorkflowState, B as Brief, H as Handoff } from '../types-DjePDfms.js';
2
2
 
3
3
  declare const WORKFLOW_DIR = ".workflow";
4
4
  declare function statePath(root: string): string;
@@ -1,2 +1,2 @@
1
- export{a as WORKFLOW_DIR,e as loadState,f as saveBrief,g as saveHandoff,d as saveState,b as statePath,c as withStateLock}from'../chunk-QZ6HD6DE.mjs';import'../chunk-KLWZEXZU.mjs';import'../chunk-2FRRD6A3.mjs';//# sourceMappingURL=index.mjs.map
1
+ export{a as WORKFLOW_DIR,e as loadState,g as saveBrief,h as saveHandoff,d as saveState,b as statePath,c as withStateLock}from'../chunk-3GKYL6VB.mjs';import'../chunk-TQR3VFZU.mjs';import'../chunk-BD76VFI4.mjs';import'../chunk-YS6CXERQ.mjs';//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1,21 +1,22 @@
1
- import { W as WorkflowState, R as Role, C as Capability, a as Budget, A as Accounting } from './types-BScHXlRx.cjs';
1
+ import { W as WorkflowState, C as Capability, R as Role, a as Budget, A as Accounting } from './types-DjePDfms.cjs';
2
2
 
3
- declare function registerRole(state: WorkflowState, role: Role, by: string, now?: string): WorkflowState;
4
- declare function retireRole(state: WorkflowState, roleId: string, by: string, now?: string): WorkflowState;
5
- declare function hasCapability(role: Role, cap: Capability): boolean;
6
- declare function rolesWith(state: WorkflowState, cap: Capability): Role[];
7
- declare function approversFor(state: WorkflowState, gateId: string): Role[];
3
+ declare function requireCapabilities(state: WorkflowState<string>, required: Capability[], exclusive: Capability[]): void;
8
4
  declare function requireCapabilities(state: WorkflowState, required: Capability[], exclusive: Capability[]): void;
5
+ declare function separationLost(state: WorkflowState<string>, required: Capability[]): Role[];
9
6
  declare function separationLost(state: WorkflowState, required: Capability[]): Role[];
10
7
  /** `human` may do anything; a role must hold at least one of `caps`; unknown ids may do nothing. */
8
+ declare function canDo(state: WorkflowState<string>, by: string, ...caps: Capability[]): boolean;
11
9
  declare function canDo(state: WorkflowState, by: string, ...caps: Capability[]): boolean;
10
+ declare function requireCap(state: WorkflowState<string>, by: string, ...caps: Capability[]): void;
12
11
  declare function requireCap(state: WorkflowState, by: string, ...caps: Capability[]): void;
13
12
 
13
+ /** Frozen: shared by every caller; copy it (`{ ...ZERO_SPENT }`) to get a mutable record. */
14
14
  declare const ZERO_SPENT: Required<Budget>;
15
15
  declare function addSpent(spent: Required<Budget>, acc: Accounting): Required<Budget>;
16
16
  declare function remaining(budget: Budget, spent: Required<Budget>): Budget;
17
17
  declare function isExhausted(budget: Budget, spent: Required<Budget>): boolean;
18
18
  type EstimateMode = "per-weight" | "per-call";
19
+ declare function estimateTokens(state: WorkflowState<string>, weight: number | undefined, fallbackPerWeight?: number, mode?: EstimateMode): number;
19
20
  declare function estimateTokens(state: WorkflowState, weight: number | undefined, fallbackPerWeight?: number, mode?: EstimateMode): number;
20
21
 
21
- export { type EstimateMode as E, ZERO_SPENT as Z, addSpent as a, approversFor as b, canDo as c, remaining as d, estimateTokens as e, requireCap as f, requireCapabilities as g, hasCapability as h, isExhausted as i, retireRole as j, rolesWith as k, registerRole as r, separationLost as s };
22
+ export { type EstimateMode as E, ZERO_SPENT as Z, addSpent as a, requireCap as b, canDo as c, requireCapabilities as d, estimateTokens as e, isExhausted as i, remaining as r, separationLost as s };
@@ -1,21 +1,22 @@
1
- import { W as WorkflowState, R as Role, C as Capability, a as Budget, A as Accounting } from './types-BScHXlRx.js';
1
+ import { W as WorkflowState, C as Capability, R as Role, a as Budget, A as Accounting } from './types-DjePDfms.js';
2
2
 
3
- declare function registerRole(state: WorkflowState, role: Role, by: string, now?: string): WorkflowState;
4
- declare function retireRole(state: WorkflowState, roleId: string, by: string, now?: string): WorkflowState;
5
- declare function hasCapability(role: Role, cap: Capability): boolean;
6
- declare function rolesWith(state: WorkflowState, cap: Capability): Role[];
7
- declare function approversFor(state: WorkflowState, gateId: string): Role[];
3
+ declare function requireCapabilities(state: WorkflowState<string>, required: Capability[], exclusive: Capability[]): void;
8
4
  declare function requireCapabilities(state: WorkflowState, required: Capability[], exclusive: Capability[]): void;
5
+ declare function separationLost(state: WorkflowState<string>, required: Capability[]): Role[];
9
6
  declare function separationLost(state: WorkflowState, required: Capability[]): Role[];
10
7
  /** `human` may do anything; a role must hold at least one of `caps`; unknown ids may do nothing. */
8
+ declare function canDo(state: WorkflowState<string>, by: string, ...caps: Capability[]): boolean;
11
9
  declare function canDo(state: WorkflowState, by: string, ...caps: Capability[]): boolean;
10
+ declare function requireCap(state: WorkflowState<string>, by: string, ...caps: Capability[]): void;
12
11
  declare function requireCap(state: WorkflowState, by: string, ...caps: Capability[]): void;
13
12
 
13
+ /** Frozen: shared by every caller; copy it (`{ ...ZERO_SPENT }`) to get a mutable record. */
14
14
  declare const ZERO_SPENT: Required<Budget>;
15
15
  declare function addSpent(spent: Required<Budget>, acc: Accounting): Required<Budget>;
16
16
  declare function remaining(budget: Budget, spent: Required<Budget>): Budget;
17
17
  declare function isExhausted(budget: Budget, spent: Required<Budget>): boolean;
18
18
  type EstimateMode = "per-weight" | "per-call";
19
+ declare function estimateTokens(state: WorkflowState<string>, weight: number | undefined, fallbackPerWeight?: number, mode?: EstimateMode): number;
19
20
  declare function estimateTokens(state: WorkflowState, weight: number | undefined, fallbackPerWeight?: number, mode?: EstimateMode): number;
20
21
 
21
- export { type EstimateMode as E, ZERO_SPENT as Z, addSpent as a, approversFor as b, canDo as c, remaining as d, estimateTokens as e, requireCap as f, requireCapabilities as g, hasCapability as h, isExhausted as i, retireRole as j, rolesWith as k, registerRole as r, separationLost as s };
22
+ export { type EstimateMode as E, ZERO_SPENT as Z, addSpent as a, requireCap as b, canDo as c, requireCapabilities as d, estimateTokens as e, isExhausted as i, remaining as r, separationLost as s };
@@ -0,0 +1,2 @@
1
+ import {a,b as b$1}from'./chunk-4HG6A3SF.mjs';import {N as N$1,K as K$1,m,h,r,l,c,L,U as U$1,a as a$1,s,u,x,q,t,C,n,B,M}from'./chunk-UUWDQVIJ.mjs';import {b}from'./chunk-YS6CXERQ.mjs';import {timSort}from'exsorted';var ye=["todo","in_progress","blocked","review","awaiting_human","done","dropped"];function be(o){let n=o.events.filter(i=>i.type==="sprint.closed"&&i.payload.reason!=="cancel");return n.length===0?null:n.reduce((i,r)=>i+r.payload.doneWeight,0)/n.length}function ae(o){let n=N$1(o),i=Object.fromEntries(ye.map(t=>[t,0])),r=[],g=0;for(let t of n?.committed??[]){let e=Object.hasOwn(o.items,t)?o.items[t]:void 0;if(e){i[e.status]+=1,e.status!=="done"&&(g+=e.weight??0);for(let s of e.blockers)s.clearedAt||r.push({item:t,blocker:s.id,owner:s.owner,reason:s.reason});}}let p=n?.spent??{tokens:0,turns:0,wallclockMs:0},f=n?K$1(n.budget,n.spent):{},y=be(o),k="unknown";if(n&&y!==null&&n.budget.tokens){let t=(f.tokens??0)/n.budget.tokens;k=g<=y*t?"on-track":"at-risk";}let d=o.lessons.filter(t=>t.status==="raised").length;return {sprint:n?.id??null,goal:n?.goal??null,byStatus:i,blockers:r,spent:p,remaining:f,remainingWeight:g,raisedLessons:d,velocity:y,forecast:k}}function U(o){for(let n=o.iterations.length-1;n>=0;n--){let i=o.iterations[n];if(i.endedAt!==void 0)return i}}function F(o,n){return o.events.find(i=>i.type==="sprint.closed"&&i.payload.id===n)?.seq??Number.POSITIVE_INFINITY}function he(o){let n=new Set(U(o)?.carryover??[]),i=Object.values(o.items).filter(r=>r.stage==="backlog"&&r.status==="todo"&&r.type!=="question");return timSort([...i],(r,g)=>{let p=n.has(r.id)?1:0,f=n.has(g.id)?1:0;return p!==f?f-p:(g.priority??0)-(r.priority??0)})}function re(o,n$1){let i=r(o,n$1);(i.stage!=="backlog"||i.status!=="todo")&&b("invalid-input",`item "${n$1}" is not in the Product Backlog (${i.stage}/${i.status})`,"only backlog items can be committed",{items:[n$1]}),C(o,i,n(o,"backlog").exitPolicy,"enter the Sprint Backlog");}function se(o,n,i,r,g){let p=o;for(let f of Object.values(o.items))f.type!=="question"||f.parent===void 0||!n.includes(f.parent)||f.status==="done"||f.status==="dropped"||((f.stage!=="sprint"||f.status!=="todo")&&(p=u(p,f.id,{stage:"sprint",status:"todo"},r,g)),p=q(p,f.id,y=>({...y,iteration:i})));return p}function N(o,n){return {...o,config:{...W(o),definitionOfDone:n},stages:o.stages.map(i=>i.id==="review"?{...i,exitPolicy:n}:i)}}function ke(o,n$1){let i=W(o),r=[],g=[],p=n(o,"backlog").exitPolicy,f=0;for(let y of he(o)){let k=B(o,y,p);if(k.length>0){g.push({id:y.id,reason:"policy",detail:k.map(d=>d.message).join("; ")});continue}if(n$1.turns!==void 0&&r.length>=n$1.turns){g.push({id:y.id,reason:"budget",detail:"turns budget full"});continue}if(n$1.tokens!==void 0){let d=M(o,y.weight,i.fallbackTokensPerWeight,i.estimateMode);if(f+d>n$1.tokens){g.push({id:y.id,reason:"budget",detail:`needs about ${d} tokens, ${n$1.tokens-f} left`});continue}f+=d;}r.push(y.id);}return {ids:r,skipped:g}}function K(o){let n=(t,e,s,m)=>U$1(t,o(),{type:e,by:s.by,payload:s},c=>m(c,a$1(s.now)));return {refine:(t$1,e)=>{m(t$1,e.by,"define-acceptance","deliver");let s$1=e.items??[],m$1=e.split??[],c$1=e.reestimate??[];(!Array.isArray(c$1)||!c$1.every(u=>typeof u=="string"))&&b("invalid-input","refine.reestimate must be a list of item ids",'pass reestimate: ["A"]');let l=c$1;s$1.length===0&&m$1.length===0&&l.length===0&&b("invalid-input","refine needs items[], split[] or reestimate[]","pass at least one patch, split or reestimate");for(let u of l){let h=r(t$1,u);(h.stage!=="backlog"||h.status!=="todo"||h.weight===void 0)&&b("invalid-input",`item "${u}" has no weight to confirm in the Product Backlog`,"refine it with a patch { weight } instead",{items:[u]});}return n(t$1,"ceremony.refine",e,(u$1,h)=>{for(let{id:a,patch:w}of s$1)u$1=t(u$1,a,w,e.by,h);for(let a of l)u$1=c(u$1,"item.reestimated",e.by,{id:a,weight:r(u$1,a).weight},h);for(let a of m$1){r(u$1,a.from);for(let w of a.into)u$1=s(u$1,{...w,parent:a.from},e.by,h);u$1=u(u$1,a.from,{status:"dropped"},e.by,h);}return c(u$1,"ceremony.refine",e.by,{edited:s$1.map(a=>a.id),split:m$1.map(a=>({from:a.from,into:a.into.map(w=>w.id)})),reestimated:l},h)})},plan:(t,e)=>{m(t,e.by,"facilitate");let s=e.goal;(typeof s!="string"||s.trim()==="")&&b("invalid-input","sprint planning needs a non-empty goal","state the Sprint Goal in one sentence");let m$1=W(t),c$1=e.budget??m$1.sprintBudget,l=e.items==="auto"?ke(t,c$1):void 0,u$1=l?.skipped??[],h=l?l.ids:e.items;Array.isArray(h)||b("invalid-input",'sprint planning needs items: string[] or "auto"','pass ["A","B"] or "auto"'),h.length===0&&b("invalid-input",`no backlog items fit the sprint${u$1.length?`; skipped: ${u$1.map(a=>`${a.id} (${a.reason}: ${a.detail})`).join(", ")}`:""}`,"refine the backlog (acceptance + estimates) or raise the budget with exwf config set");for(let a of h)re(t,a);return n(t,"ceremony.plan",e,(a,w)=>{let C=`S${a.iterations.length+1}`,M=U(a),O=h.filter(A=>M?.carryover.includes(A)),B=[];for(let A of h){let T=j(r(a,A),a);T&&B.push(A),a=u(a,A,T?{stage:T,status:"review"}:{stage:"sprint",status:"todo"},e.by,w),a=q(a,A,fe=>({...fe,iteration:C}));}a=se(a,h,C,e.by,w);let J=h.reduce((A,T)=>A+(a.items[T]?.weight??0),0);return a={...a,iterations:[...a.iterations,{id:C,goal:s,budget:c$1,spent:{tokens:0,turns:0,wallclockMs:0},startedAt:w,committed:[...h],carryover:O}]},c(a,"sprint.opened",e.by,{id:C,goal:s,committed:h,committedWeight:J,budget:c$1,skipped:u$1,resumed:B},w)})},commit:(t,e)=>{let s=N$1(t);s||b("invalid-input","no open sprint to commit into","run the plan ceremony first");let m=e.items;(!Array.isArray(m)||m.length===0)&&b("invalid-input","commit needs items[]",'pass ["A"]');let c$1=new Set;for(let l of m)c$1.has(l)&&b("invalid-input",`item "${l}" appears twice in items[]`,"list each item once",{items:[l]}),c$1.add(l),r(t,l),s.committed.includes(l)&&b("invalid-input",`item "${l}" is already committed to ${s.id}`,"nothing to do",{items:[l]}),re(t,l);return n(t,"ceremony.commit",e,(l,u$1)=>{let h=[];for(let a of m){let w=j(r(l,a),l);w&&h.push(a),l=u(l,a,w?{stage:w,status:"review"}:{stage:"sprint",status:"todo"},e.by,u$1),l=q(l,a,C=>({...C,iteration:s.id}));}return l=se(l,m,s.id,e.by,u$1),l={...l,iterations:l.iterations.map(a=>a.id===s.id?{...a,committed:[...a.committed,...m]}:a)},c(l,"sprint.committed",e.by,{id:s.id,items:m,goalImpact:e.goalImpact??null,resumed:h},u$1)})},uncommit:(t,e)=>{m(t,e.by,"order-backlog");let s=N$1(t);s||b("invalid-input","no open sprint","nothing to uncommit from");let m$1=e.items;(!Array.isArray(m$1)||m$1.length===0)&&b("invalid-input","uncommit needs items[]",'pass ["A"]');for(let c of m$1)r(t,c).status==="done"&&b("invalid-input",`item "${c}" is done`,"finished work cannot be uncommitted",{items:[c]});for(let c of m$1)s.committed.includes(c)||b("invalid-input",`item "${c}" is not committed to ${s.id}`,`committed: ${s.committed.join(", ")}`,{items:[c]});return n(t,"ceremony.uncommit",e,(c$1,l)=>{for(let u$1 of m$1)c$1=u(c$1,u$1,{stage:"backlog",status:"todo"},e.by,l),c$1=x(c$1,u$1,["iteration","role"]);return c$1={...c$1,iterations:c$1.iterations.map(u=>u.id===s.id?{...u,committed:u.committed.filter(h=>!m$1.includes(h))}:u)},c(c$1,"sprint.uncommitted",e.by,{id:s.id,items:m$1,reason:e.reason??""},l)})},daily:(t,e)=>n(t,"ceremony.daily",e,(s,m)=>c(s,"daily",e.by,ae(s),m)),review:(t,e)=>{let s$1=N$1(t);s$1||b("invalid-input","no open sprint to review","run the plan ceremony first");let m=h(t,"sprint-review");e.by!=="human"&&!m.includes(e.by)&&b("gate-unmet",`"${e.by}" may not accept the Sprint Review`,`run review as "human" or as ${m.join(", ")||"a role with canApprove sprint-review"}`,{rule:"sprint-review"});let c$1=e.feedback??[];return n(t,"ceremony.review",e,(l,u)=>{for(let a of c$1)l=s(l,{...a,stage:"backlog"},e.by,u);let h=s$1.committed.filter(a=>l.items[a]?.status==="done");return l=c(l,"increment",e.by,{sprint:s$1.id,done:h,goalMet:e.goalMet===true,accepted:e.accepted===true,feedback:c$1.map(a=>a.id)},u),E(l,"review",u)})},retro:(t,e)=>{m(t,e.by,"facilitate");let s$1=U(t);s$1||b("invalid-input","no closed sprint to retrospect","close the sprint (review or cancel) first"),N$1(t)&&b("invalid-input","a sprint is still open","retro runs between sprints; review or cancel the open one");let m$1=F(t,s$1.id);t.events.some(u=>u.type==="retro"&&u.seq>m$1)&&b("invalid-input",`sprint ${s$1.id} already has a retrospective`,"plan the next sprint");let c$1=a(t,e,"retro"),l=e.dodChanges;return n(t,"ceremony.retro",e,(u,h)=>{let a=[],w=false,C=b$1(u,c$1,e.by,h,(M,O)=>{if(O.kind==="dod"){let B=W(M).definitionOfDone;return B.some(J=>JSON.stringify(J)===JSON.stringify(O.policy))?M:(w=true,N(M,[...B,O.policy]))}return O.kind==="backlog"?(a.push(O.item.id),s(M,{...O.item,stage:"backlog",tags:[...O.item.tags??[],"retro"]},e.by,h)):M});return u=C.state,l&&(w=true,u=N(u,l)),c(u,"retro",e.by,{sprint:s$1.id,adopted:C.adopted,dismissed:C.dismissed,agreements:C.agreements,retired:C.retired,dodChanged:w,backlogAdded:a},h)})},cancel:(t,e)=>{m(t,e.by,"order-backlog");let s=N$1(t);return s||b("invalid-input","no open sprint to cancel","nothing to do"),n(t,"ceremony.cancel",e,(m,c$1)=>(m=c(m,"sprint.cancelled",e.by,{id:s.id,reason:e.reason??""},c$1),E(m,"cancel",c$1)))}}}var ve=new Set(["never","po-only","any"]);function ce(o){let n=o??{},i=n.sprintBudget;(!i||typeof i!="object"||i.tokens===void 0&&i.turns===void 0&&i.wallclockMs===void 0)&&b("config-invalid","scrum config.sprintBudget must define tokens, turns or wallclockMs",'e.g. { "sprintBudget": { "tokens": 400000, "turns": 60 } }'),(typeof n.productGoal!="string"||n.productGoal.trim()==="")&&b("config-invalid","scrum config.productGoal must be a non-empty string","state the Product Goal in one sentence"),Array.isArray(n.definitionOfDone)||b("config-invalid","scrum config.definitionOfDone must be a Policy[]",'e.g. [{ "kind": "evidence", "evidenceKind": "test-output" }]');let r=n.refinementSharePct??10;(typeof r!="number"||r<0||r>100)&&b("config-invalid","scrum config.refinementSharePct must be 0..100","omit it for the default 10");let g=n.allowMidSprintAdd??"po-only";(typeof g!="string"||!ve.has(g))&&b("config-invalid",`scrum config.allowMidSprintAdd must be never | po-only | any (got ${JSON.stringify(g)})`,'use "po-only" unless you have a reason');let p=n.inProgressWipLimit;p!==void 0&&(typeof p!="number"||p<1)&&b("config-invalid","scrum config.inProgressWipLimit must be a positive number","omit it for no limit");let f=n.autoClose;f!==void 0&&typeof f!="boolean"&&b("config-invalid","scrum config.autoClose must be true or false","omit it for the default true");let y=n.estimateMode;y!==void 0&&y!=="per-weight"&&y!=="per-call"&&b("config-invalid",`scrum config.estimateMode must be per-weight | per-call (got ${JSON.stringify(y)})`,'use "per-weight" (the default) or "per-call"');let k=n.fallbackTokensPerWeight;k!==void 0&&(typeof k!="number"||!Number.isFinite(k)||k<=0)&&b("config-invalid","scrum config.fallbackTokensPerWeight must be a positive finite number","omit it for the default 20000");let d={sprintBudget:i,productGoal:n.productGoal,definitionOfDone:n.definitionOfDone,refinementSharePct:r,allowMidSprintAdd:g};return p!==void 0&&(d.inProgressWipLimit=p),f!==void 0&&(d.autoClose=f),y!==void 0&&(d.estimateMode=y),k!==void 0&&(d.fallbackTokensPerWeight=k),d}var $=(o,n)=>n===0?0:o/n;function de(o){let n=o.events.filter(t=>t.type==="accounting.corrected"),i=o.events.filter(t=>t.type==="sprint.closed").map(t=>{let e=t.payload,s=n.filter(m=>m.seq>t.seq&&e.id!==void 0&&m.payload.iteration===e.id).reduce((m,c)=>m+c.payload.delta.tokens,0);return s===0?e:{...e,spent:{...e.spent,tokens:e.spent.tokens+s}}}),r=i.filter(t=>t.reason!=="cancel"),g=r.map(t=>t.doneWeight),p=r.reduce((t,e)=>t+e.doneWeight,0),f=r.reduce((t,e)=>t+e.committedWeight,0),y=o.events.filter(t=>t.type==="increment").map(t=>t.payload),k=i.filter(t=>t.budget.tokens!==void 0),d=r.reduce((t,e)=>t+e.spent.tokens,0);return {velocity:g,meanVelocity:$(g.reduce((t,e)=>t+e,0),g.length),burndown:o.events.filter(t=>t.type==="daily").map(t=>t.payload.remainingWeight),commitmentReliability:$(p,f),sprintGoalHitRate:$(y.filter(t=>t.goalMet).length,y.length),carryoverRatio:$(i.reduce((t,e)=>t+e.carryover.length,0),i.reduce((t,e)=>t+e.done.length+e.carryover.length,0)),budgetUtilisation:$(k.reduce((t,e)=>t+e.spent.tokens,0),k.reduce((t,e)=>t+(e.budget.tokens??0),0)),costPerPoint:$(d,p),current:we(o)}}function we(o){let n=N$1(o),i=(n?.committed??[]).map(k=>o.items[k]).filter(k=>k!==void 0),r=k=>k.reduce((d,t)=>d+(t.weight??0),0),g=r(i),p=r(i.filter(k=>k.status==="done")),f=n?.spent.tokens??0,y=n?.budget.tokens??0;return {spentTokens:f,spentTurns:n?.spent.turns??0,budgetTokens:y,committedWeight:g,doneWeight:p,remainingWeight:g-p,costPerPoint:$(f,p),budgetUtilisation:$(f,y)}}function le(){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 I=(o,n,i,r,g)=>g?{rule:o,severity:n,item:g,message:i,fix:r}:{rule:o,severity:n,message:i,fix:r};function me(o){for(let n=o.iterations.length-1;n>=0;n--){let i=o.iterations[n];if(i.endedAt!==void 0)return i}}var H=o=>o.kind==="evidence"?`evidence:${o.evidenceKind}`:o.kind==="custom"?`custom:${o.id}`:o.kind;function ue(){return [{id:"one-open-sprint",severity:"error",check:(d,t)=>t.type==="ceremony.plan"&&N$1(d)?[I("one-open-sprint","error",`sprint ${N$1(d).id} is still open`,"review or cancel it before planning the next sprint")]:[]},{id:"retro-before-plan",severity:"error",check:(d,t)=>{if(t.type!=="ceremony.plan")return [];let e=me(d);if(!e)return [];let s=F(d,e.id);if(d.events.some(c=>c.type==="retro"&&c.seq>s))return [];let m=e.outcome==="cancelled"?"warning":"error";return [I("retro-before-plan",m,`sprint ${e.id} has no retrospective yet`,"run the retro ceremony first (lessons may be empty)")]}},{id:"sprint-budget-fixed",severity:"error",check:(d,t)=>{if(t.type!=="ceremony.plan")return [];let e=t.payload?.budget;return e===void 0||JSON.stringify(e)===JSON.stringify(W(d).sprintBudget)?[]:[I("sprint-budget-fixed","error","sprint length is fixed by config.sprintBudget","change sprintBudget between sprints with changeConfig / exwf config set, not per plan")]}},{id:"sprint-closing",severity:"error",check:(d,t)=>{let e=N$1(d);return t.type==="ceremony.commit"&&e?.closing?[I("sprint-closing","error",`sprint ${e.id} is closing: its budget is spent and no new work can start`,"run ceremony review or cancel first, then plan the next sprint")]:[]}},{id:"scrum-stage-ids",severity:"error",check:(d,t)=>{if(t.type!=="init")return [];let e=["backlog","sprint","review"].filter(s=>!d.stages.some(m=>m.id===s));return e.length&&b("config-invalid",`scrum stages lack the required id(s): ${e.join(", ")}`,"keep the stages backlog, sprint and review (omit stages to use the defaults), then run exwf init scrum again"),[]}},{id:"scope-protects-goal",severity:"error",check:(d,t)=>{if(t.type!=="ceremony.commit")return [];let e=W(d),s=t.payload??{};return e.allowMidSprintAdd==="never"?[I("scope-protects-goal","error","mid-sprint additions are disabled",'set allowMidSprintAdd to "po-only" or wait for the next sprint')]:e.allowMidSprintAdd==="po-only"&&!l(d,t.by,"order-backlog")?[I("scope-protects-goal","error",`"${t.by}" may not add work mid-sprint`,"ask the Product Owner (order-backlog) to commit it")]:s.goalImpact!=="none"?[I("scope-protects-goal","error",`adding work with goalImpact "${s.goalImpact??"unset"}" endangers the Sprint Goal`,'only commit items with goalImpact: "none"; otherwise cancel and re-plan')]:[]}},{id:"po-orders-backlog",severity:"error",check:(d,t)=>t.type!=="ceremony.refine"||l(d,t.by,"order-backlog")?[]:((t.payload??{}).items??[]).filter(s=>s.patch.priority!==void 0).map(s=>I("po-orders-backlog","error",`"${t.by}" may not change the priority of "${s.id}"`,"only the Product Owner orders the backlog; drop priority from the patch",s.id))},{id:"dod-not-weakened",severity:"error",check:(d,t)=>{if(t.type!=="ceremony.retro")return [];let e=t.payload??{};if(e.dodChanges===void 0)return [];if(N$1(d))return [I("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")];if(!Array.isArray(e.dodChanges)||e.allowWeaken===true)return [];let s=e.dodChanges,m=new Set(s.map(H)),c=W(d).definitionOfDone.filter(u=>!m.has(H(u)));if(c.length===0)return [];let l=c.map(u=>H(u).replace(":"," "));return [I("dod-not-weakened","error",`retro dodChanges drops ${c.length} Definition of Done policy(ies): ${l.join(", ")}`,'keep them in dodChanges (it replaces the whole list; suggestedChange { kind: "dod" } appends one), or pass allowWeaken: true to weaken the Definition of Done knowingly')]}},{id:"carryover-reestimated",severity:"error",check:(d,t)=>{if(t.type!=="ceremony.plan")return [];let e=t.payload?.items;if(!Array.isArray(e))return [];let s=me(d);if(!s)return [];let m=F(d,s.id);return e.filter(c=>s.carryover.includes(c)&&!(d.items[c]&&j(d.items[c],d)!==void 0)&&!d.events.some(l=>l.seq>m&&l.payload.id===c&&(l.type==="item.edited"&&l.payload.changed.includes("weight")||l.type==="item.reestimated"))).map(c=>I("carryover-reestimated","error",`carried-over item "${c}" was not re-estimated after ${s.id}`,"refine it with a new weight before committing",c))}}]}function pe(o){let n={id:"in_progress",name:"In progress",entryPolicy:[{kind:"dependencies-done"}],exitPolicy:[]};return o.inProgressWipLimit!==void 0&&(n.wipLimit=o.inProgressWipLimit),[{id:"backlog",name:"Product Backlog",entryPolicy:[],exitPolicy:[{kind:"acceptance-written"},{kind:"estimate-present"}]},{id:"sprint",name:"Sprint Backlog",entryPolicy:[],exitPolicy:[]},n,{id:"review",name:"Review",entryPolicy:[],exitPolicy:o.definitionOfDone,review:true},{id:"done",name:"Increment",entryPolicy:[],exitPolicy:[]}]}var Se=Object.freeze({backlog:"Product Backlog",item:"Product Backlog Item",stage:"Column",iteration:"Sprint",increment:"Increment",ceremony:"Scrum Event",gate:"Sprint Review"});function W(o){return o.config}function j(o,n){let i=o.transitions.at(-1);return !i||i.by!=="system"||i.to.stage!=="backlog"||i.to.status!=="todo"?void 0:n?n.stages.find(g=>g.id===i.from.stage)?.review||i.from.status==="review"?i.from.stage:void 0:i.from.status==="review"?i.from.stage:void 0}function Pe(o,n,i){let r$1=o,g=r(r$1,n).blockers.filter(f=>!f.clearedAt);if(g.length){r$1=q(r$1,n,f=>({...f,blockers:f.blockers.map(y=>y.clearedAt?y:{...y,clearedAt:i})}));for(let f of g)r$1=c(r$1,"blocker.cleared","system",{id:n,blocker:f.id,reason:"sprint closed"},i);}for(let f of r$1.pending.filter(y=>y.item===n))r$1={...r$1,pending:r$1.pending.filter(y=>y.id!==f.id)},r$1=c(r$1,"pending.dropped","system",{id:f.id,item:n,reason:"sprint closed"},i);let p=r(r$1,n);return (p.stage!=="backlog"||p.status!=="todo")&&(r$1=u(r$1,n,{stage:"backlog",status:"todo"},"system",i)),x(r$1,n,p.type==="question"?["iteration"]:["iteration","role"])}function E(o,n,i){let r$1=N$1(o);if(!r$1)return o;let g=r$1.committed.map(e=>r(o,e)),p=g.filter(e=>e.status==="done").map(e=>e.id),f=g.filter(e=>e.status==="dropped").map(e=>e.id),y=g.filter(e=>e.status!=="done"&&e.status!=="dropped").map(e=>e.id),k=Object.values(o.items).filter(e=>e.type==="question"&&e.parent!==void 0&&y.includes(e.parent)&&e.status!=="done"&&e.status!=="dropped").map(e=>e.id),d=o;for(let e of [...y,...k])d=Pe(d,e,i);let t=e=>e.reduce((s,m)=>s+(o.items[m]?.weight??0),0);return d={...d,iterations:d.iterations.map(e=>{if(e.id!==r$1.id)return e;let{closing:s,...m}=e;return {...m,endedAt:i,outcome:n==="cancel"?"cancelled":"completed",carryover:y}})},c(d,"sprint.closed","system",{id:r$1.id,reason:n,done:p,carryover:y,carriedQuestions:k,dropped:f,doneWeight:t(p),committedWeight:t(r$1.committed),spent:r$1.spent,budget:r$1.budget},i)}function We(){return {name:"scrum",vocabulary:Se,validateConfig:ce,defaultStages:pe,defaultRoles:le,requiredCapabilities:["order-backlog","facilitate","deliver"],exclusiveCapabilities:["order-backlog"],plannerOptions(o){let n=W(o),i={schedulerMode:"level",dispatchStage:"in_progress"};return n.inProgressWipLimit!==void 0&&(i.concurrencyCap=n.inProgressWipLimit),n.estimateMode!==void 0&&(i.estimateMode=n.estimateMode),n.fallbackTokensPerWeight!==void 0&&(i.fallbackTokensPerWeight=n.fallbackTokensPerWeight),i},candidates(o){let n=N$1(o);return !n||n.closing?[]:Object.values(o.items).filter(i=>i.iteration===n.id&&(i.status==="todo"||i.status==="review")&&(i.stage==="sprint"||i.stage==="review"))},invariants(o,n){let i=N$1(o),r=W(o),g=i?K$1(i.budget,i.spent):{};return [`Sprint Goal: ${i?.goal??"(no open sprint)"}; Product Goal: ${r.productGoal}`,`Budget remaining: ${JSON.stringify(g)}; stop and hand off when it is gone`,`Definition of Done: ${r.definitionOfDone.map(p=>p.kind==="evidence"?`evidence ${p.evidenceKind}`:p.kind).join(", ")||"(none)"}`,`Do not change the scope of "${n.id}" or its acceptance criteria; raise open_questions instead`]},ceremonies:K(We),rules:ue(),metrics:o=>({...de(o)}),report(o){let n=N$1(o);return {closing:n?.closing===true,sprint:n?.id??null,reason:n?.closing?"budget":null,inFlight:n?Object.values(o.items).filter(i=>(i.iteration===n.id||n.committed.includes(i.id))&&i.status==="in_progress").map(i=>i.id):[]}},humanDefaults:{gates:["sprint-review"]},afterConfigChange(o){return N(o,W(o).definitionOfDone)},afterComplete(o,n,i){let r=N$1(o);return !r||!r.closing&&!L(r.budget,r.spent)?o:!Object.values(o.items).some(p=>(p.iteration===r.id||r.committed.includes(p.id))&&p.status==="in_progress")&&W(o).autoClose!==false?E(o,"budget",i):r.closing?o:c({...o,iterations:o.iterations.map(p=>p.id===r.id?{...p,closing:true}:p)},"sprint.closing","system",{id:r.id},i)}}}export{ae as a,K as b,ce as c,de as d,le as e,ue as f,pe as g,Se as h,W as i,j,E as k,We as l};//# sourceMappingURL=chunk-32NVJV5C.mjs.map
2
+ //# sourceMappingURL=chunk-32NVJV5C.mjs.map