ex-workflow 1.1.1 → 1.3.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 (193) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +209 -44
  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-Bd8KpGIr.d.ts → budget-BuQ9GWsg.d.ts} +8 -7
  8. package/dist/{budget-CezCinPF.d.cts → budget-DDqQQIgp.d.cts} +8 -7
  9. package/dist/chunk-2FBA7RBS.cjs +2 -0
  10. package/dist/chunk-2FBA7RBS.cjs.map +1 -0
  11. package/dist/chunk-3S7F5QXK.mjs +2 -0
  12. package/dist/chunk-3S7F5QXK.mjs.map +1 -0
  13. package/dist/chunk-3ZUBCA7Q.cjs +2 -0
  14. package/dist/chunk-3ZUBCA7Q.cjs.map +1 -0
  15. package/dist/chunk-4F5HZLKD.cjs +2 -0
  16. package/dist/chunk-4F5HZLKD.cjs.map +1 -0
  17. package/dist/chunk-5DCOXGRW.mjs +2 -0
  18. package/dist/chunk-5DCOXGRW.mjs.map +1 -0
  19. package/dist/chunk-5GXB6GMX.mjs +2 -0
  20. package/dist/chunk-5GXB6GMX.mjs.map +1 -0
  21. package/dist/chunk-5ZGNEY2I.mjs +2 -0
  22. package/dist/chunk-5ZGNEY2I.mjs.map +1 -0
  23. package/dist/chunk-6PFJYRM7.cjs +2 -0
  24. package/dist/chunk-6PFJYRM7.cjs.map +1 -0
  25. package/dist/chunk-BANKVCYY.cjs +2 -0
  26. package/dist/chunk-BANKVCYY.cjs.map +1 -0
  27. package/dist/chunk-BBI7AKJK.cjs +2 -0
  28. package/dist/chunk-BBI7AKJK.cjs.map +1 -0
  29. package/dist/chunk-BD665RYK.mjs +2 -0
  30. package/dist/chunk-BD665RYK.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-COPYGMHE.mjs +2 -0
  34. package/dist/chunk-COPYGMHE.mjs.map +1 -0
  35. package/dist/chunk-CVGEIXW6.cjs +2 -0
  36. package/dist/chunk-CVGEIXW6.cjs.map +1 -0
  37. package/dist/chunk-CX2E7ZTQ.mjs +2 -0
  38. package/dist/chunk-CX2E7ZTQ.mjs.map +1 -0
  39. package/dist/chunk-DVFTTBCT.cjs +3 -0
  40. package/dist/chunk-DVFTTBCT.cjs.map +1 -0
  41. package/dist/chunk-EQXYFHHD.cjs +2 -0
  42. package/dist/chunk-EQXYFHHD.cjs.map +1 -0
  43. package/dist/chunk-GKN5M4B7.cjs +2 -0
  44. package/dist/chunk-GKN5M4B7.cjs.map +1 -0
  45. package/dist/chunk-H26KXQ3I.cjs +2 -0
  46. package/dist/chunk-H26KXQ3I.cjs.map +1 -0
  47. package/dist/chunk-IDZ435YZ.mjs +2 -0
  48. package/dist/{chunk-KIQOUUEZ.mjs.map → chunk-IDZ435YZ.mjs.map} +1 -1
  49. package/dist/chunk-ILDXZWEL.mjs +2 -0
  50. package/dist/chunk-ILDXZWEL.mjs.map +1 -0
  51. package/dist/chunk-KA6DVHO5.cjs +6 -0
  52. package/dist/chunk-KA6DVHO5.cjs.map +1 -0
  53. package/dist/chunk-KLOSFZFK.cjs +2 -0
  54. package/dist/chunk-KLOSFZFK.cjs.map +1 -0
  55. package/dist/chunk-LG23WXAP.mjs +2 -0
  56. package/dist/chunk-LG23WXAP.mjs.map +1 -0
  57. package/dist/chunk-MU26QW32.cjs +2 -0
  58. package/dist/chunk-MU26QW32.cjs.map +1 -0
  59. package/dist/chunk-OEHVWRJG.mjs +2 -0
  60. package/dist/chunk-OEHVWRJG.mjs.map +1 -0
  61. package/dist/chunk-ONVAUZOD.mjs +6 -0
  62. package/dist/chunk-ONVAUZOD.mjs.map +1 -0
  63. package/dist/chunk-OSHBJIYD.cjs +2 -0
  64. package/dist/chunk-OSHBJIYD.cjs.map +1 -0
  65. package/dist/chunk-PFHVB2WT.mjs +2 -0
  66. package/dist/chunk-PFHVB2WT.mjs.map +1 -0
  67. package/dist/chunk-PNWRA4JU.cjs +2 -0
  68. package/dist/{chunk-PO2SPQJP.cjs.map → chunk-PNWRA4JU.cjs.map} +1 -1
  69. package/dist/chunk-QJMOCISZ.mjs +3 -0
  70. package/dist/chunk-QJMOCISZ.mjs.map +1 -0
  71. package/dist/chunk-RGHM3JJM.cjs +2 -0
  72. package/dist/chunk-RGHM3JJM.cjs.map +1 -0
  73. package/dist/chunk-TQR3VFZU.mjs +2 -0
  74. package/dist/chunk-TQR3VFZU.mjs.map +1 -0
  75. package/dist/chunk-UMG3WOD7.cjs +2 -0
  76. package/dist/chunk-UMG3WOD7.cjs.map +1 -0
  77. package/dist/chunk-UT7QV6CE.mjs +2 -0
  78. package/dist/chunk-UT7QV6CE.mjs.map +1 -0
  79. package/dist/chunk-WU5JELOM.mjs +2 -0
  80. package/dist/chunk-WU5JELOM.mjs.map +1 -0
  81. package/dist/chunk-YGCNLXPJ.cjs +2 -0
  82. package/dist/chunk-YGCNLXPJ.cjs.map +1 -0
  83. package/dist/chunk-YS6CXERQ.mjs +2 -0
  84. package/dist/chunk-YS6CXERQ.mjs.map +1 -0
  85. package/dist/cli/bin.cjs +1 -1
  86. package/dist/cli/bin.cjs.map +1 -1
  87. package/dist/cli/bin.mjs +1 -1
  88. package/dist/cli/bin.mjs.map +1 -1
  89. package/dist/cli/index.cjs +1 -1
  90. package/dist/cli/index.mjs +1 -1
  91. package/dist/experimentation/index.cjs +1 -1
  92. package/dist/experimentation/index.d.cts +2 -2
  93. package/dist/experimentation/index.d.ts +2 -2
  94. package/dist/experimentation/index.mjs +1 -1
  95. package/dist/index.cjs +1 -1
  96. package/dist/index.cjs.map +1 -1
  97. package/dist/index.d.cts +145 -15
  98. package/dist/index.d.ts +145 -15
  99. package/dist/index.mjs +1 -1
  100. package/dist/index.mjs.map +1 -1
  101. package/dist/investigation/index.cjs +1 -1
  102. package/dist/investigation/index.d.cts +2 -2
  103. package/dist/investigation/index.d.ts +2 -2
  104. package/dist/investigation/index.mjs +1 -1
  105. package/dist/kanban/index.cjs +1 -1
  106. package/dist/kanban/index.d.cts +2 -1
  107. package/dist/kanban/index.d.ts +2 -1
  108. package/dist/kanban/index.mjs +1 -1
  109. package/dist/policies/index.cjs +2 -0
  110. package/dist/policies/index.cjs.map +1 -0
  111. package/dist/policies/index.d.cts +199 -0
  112. package/dist/policies/index.d.ts +199 -0
  113. package/dist/policies/index.mjs +2 -0
  114. package/dist/policies/index.mjs.map +1 -0
  115. package/dist/registry/index.cjs +2 -0
  116. package/dist/registry/index.cjs.map +1 -0
  117. package/dist/registry/index.d.cts +25 -0
  118. package/dist/registry/index.d.ts +25 -0
  119. package/dist/registry/index.mjs +2 -0
  120. package/dist/registry/index.mjs.map +1 -0
  121. package/dist/schema/index.cjs +1 -1
  122. package/dist/schema/index.d.cts +2 -0
  123. package/dist/schema/index.d.ts +2 -0
  124. package/dist/schema/index.mjs +1 -1
  125. package/dist/scrum/index.cjs +1 -1
  126. package/dist/scrum/index.d.cts +3 -3
  127. package/dist/scrum/index.d.ts +3 -3
  128. package/dist/scrum/index.mjs +1 -1
  129. package/dist/{types-BScHXlRx.d.ts → types-DLOtndDY.d.cts} +121 -22
  130. package/dist/{types-BScHXlRx.d.cts → types-DLOtndDY.d.ts} +121 -22
  131. package/dist/types.cjs +1 -1
  132. package/dist/types.d.cts +1 -1
  133. package/dist/types.d.ts +1 -1
  134. package/dist/types.mjs +1 -1
  135. package/dist/waterfall/index.cjs +1 -1
  136. package/dist/waterfall/index.d.cts +1 -1
  137. package/dist/waterfall/index.d.ts +1 -1
  138. package/dist/waterfall/index.mjs +1 -1
  139. package/package.json +30 -3
  140. package/dist/chunk-2FRRD6A3.mjs +0 -2
  141. package/dist/chunk-2FRRD6A3.mjs.map +0 -1
  142. package/dist/chunk-6P3OKXSK.mjs +0 -2
  143. package/dist/chunk-6P3OKXSK.mjs.map +0 -1
  144. package/dist/chunk-7FS6KWTG.cjs +0 -2
  145. package/dist/chunk-7FS6KWTG.cjs.map +0 -1
  146. package/dist/chunk-7QQY4KJ2.mjs +0 -2
  147. package/dist/chunk-7QQY4KJ2.mjs.map +0 -1
  148. package/dist/chunk-AD4Z3JBL.cjs +0 -2
  149. package/dist/chunk-AD4Z3JBL.cjs.map +0 -1
  150. package/dist/chunk-ATCJ4IHP.mjs +0 -2
  151. package/dist/chunk-ATCJ4IHP.mjs.map +0 -1
  152. package/dist/chunk-C2IYMWE6.cjs +0 -3
  153. package/dist/chunk-C2IYMWE6.cjs.map +0 -1
  154. package/dist/chunk-EACZBAP3.cjs +0 -2
  155. package/dist/chunk-EACZBAP3.cjs.map +0 -1
  156. package/dist/chunk-EFCUM6DK.mjs +0 -2
  157. package/dist/chunk-EFCUM6DK.mjs.map +0 -1
  158. package/dist/chunk-EHBQBXWA.cjs +0 -2
  159. package/dist/chunk-EHBQBXWA.cjs.map +0 -1
  160. package/dist/chunk-FTS75UIU.mjs +0 -2
  161. package/dist/chunk-FTS75UIU.mjs.map +0 -1
  162. package/dist/chunk-HCRVWMG4.cjs +0 -2
  163. package/dist/chunk-HCRVWMG4.cjs.map +0 -1
  164. package/dist/chunk-KIQOUUEZ.mjs +0 -2
  165. package/dist/chunk-KLWZEXZU.mjs +0 -3
  166. package/dist/chunk-KLWZEXZU.mjs.map +0 -1
  167. package/dist/chunk-NDCQTRIV.mjs +0 -2
  168. package/dist/chunk-NDCQTRIV.mjs.map +0 -1
  169. package/dist/chunk-PMUGU5UJ.cjs +0 -2
  170. package/dist/chunk-PMUGU5UJ.cjs.map +0 -1
  171. package/dist/chunk-PO2SPQJP.cjs +0 -2
  172. package/dist/chunk-QZ6HD6DE.mjs +0 -6
  173. package/dist/chunk-QZ6HD6DE.mjs.map +0 -1
  174. package/dist/chunk-RL27372B.cjs +0 -2
  175. package/dist/chunk-RL27372B.cjs.map +0 -1
  176. package/dist/chunk-S3BXVHO7.cjs +0 -2
  177. package/dist/chunk-S3BXVHO7.cjs.map +0 -1
  178. package/dist/chunk-SP5MC7RR.mjs +0 -2
  179. package/dist/chunk-SP5MC7RR.mjs.map +0 -1
  180. package/dist/chunk-SVGTSPZF.cjs +0 -2
  181. package/dist/chunk-SVGTSPZF.cjs.map +0 -1
  182. package/dist/chunk-SYLO7FUL.mjs +0 -2
  183. package/dist/chunk-SYLO7FUL.mjs.map +0 -1
  184. package/dist/chunk-T3V5UE34.mjs +0 -2
  185. package/dist/chunk-T3V5UE34.mjs.map +0 -1
  186. package/dist/chunk-TS66RAJR.cjs +0 -2
  187. package/dist/chunk-TS66RAJR.cjs.map +0 -1
  188. package/dist/chunk-U23FUYPD.cjs +0 -6
  189. package/dist/chunk-U23FUYPD.cjs.map +0 -1
  190. package/dist/chunk-U6GHFKKE.mjs +0 -2
  191. package/dist/chunk-U6GHFKKE.mjs.map +0 -1
  192. package/dist/chunk-YJQ5YJ7S.cjs +0 -2
  193. package/dist/chunk-YJQ5YJ7S.cjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,65 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.3.0 (2026-11-06)
4
+
5
+ Composable policies: three opt-in policies a host adds to any methodology by wrapping it, risk-adaptive gates (#35), context-grounded entry (#36) and run comparison (#34), shipped from the new entry `ex-workflow/policies`; core gains only optional hooks that do nothing when unused. The decisions are in the design spec, section 27. Every change is additive.
6
+
7
+ - Entry point: `ex-workflow/policies` (ESM, CommonJS, `.d.ts`) exports `withRiskGate`, `recordRiskAssessment`, `riskEscalation`, `DEFAULT_RISK_TABLE`, `withContextGrounding`, `recordContextSnapshot`, `recordRepoChange`, `contextOf`, `contextGroundedViolations` and `compareRuns`, with the types `RiskLevel`, `RiskTable`, `RiskAssessmentData`, `RiskAssessmentInput`, `RiskGateOptions`, `ContextGroundingOptions`, `ContextSnapshotInput`, `RepoChangeInput`, `CompareRunsOptions`, `RunRecord`, `RunMetrics`, `VariantResult` and `RunComparison`. The root entry exports no new runtime name, so core plus one methodology does not carry the policies. The policies are SDK-only; the CLI is unchanged.
8
+ - Core hooks: `Methodology` gains three optional members, `escalateGate(state, item, gate)` (returns a `GateEscalation`), `customPolicy(state, item, policy)` (answers a `custom` stage policy) and `briefContext(state, item)` (fills the new optional `Brief.context`). `Evidence` gains the optional `data` (structured content a policy reads). `evaluatePolicies` and `assertPolicies` take an optional trailing methodology; their 1.1 signature stays the last overload. New root types `GateEscalation`, `BriefContext`, `ContextAssumption`, `ContextSnapshotData` (type-only).
9
+ - Risk-adaptive gates (#35): `recordRiskAssessment` records evidence `risk-assessment` (`data: { level, factors, subject? }`, action `risk.assess`) by `human` or an independent role with `verify`. `withRiskGate(m, { gates, table? })` makes the listed gates add the requirements of the strictest valid fresh assessment's level (`DEFAULT_RISK_TABLE`: `high` and `critical` add `"human"`; a missing, invalid or non-independent assessment counts as `critical`); a custom table must be monotone. Escalation only ever appends to the static gate (principles rule 17). `complete()` appends the new event **`gate.resolved`** `{ item, gate, requires, evidence, reason }` before `gate.passed` or `pending.raised`, and `decide()` (also `exwf decide`) judges a pending against the resolution recorded with it, so a role cannot approve a pending escalated to a human. `riskEscalation` is the resolver on its own.
10
+ - Context-grounded entry (#36): `recordContextSnapshot` records evidence `context-snapshot` (`data: { revision, assumptions }`, each assumption a `claim` with optional `required` and `source { path, lines?, hash }`, action `context.snapshot`); `recordRepoChange({ revision, paths })` appends the new event **`repo.changed`** (action `repo.change`) and warns `context-stale` for each in-flight item whose snapshot it made stale. `withContextGrounding(m, { entry, exit? })` adds the custom policy `context-grounded` to those stages: an item needs a fresh, non-stale qualifying snapshot (at least one sourced assumption, recorded by `human` or a registered role that did not work on the item) with every `required` claim sourced; `next` skips it otherwise with reason `entry-policy`, and its brief carries `context` (what was verified, what went stale, what is unverified). `contextOf` and `contextGroundedViolations` answer on their own. Paths are repository-relative POSIX paths as Git lists them (`git diff --name-only -z`), matched exactly.
11
+ - Run comparison (#34): `compareRuns(runs, { baseline, mustPass?, passTolerance?, costTolerance? })` derives per run tokens, duration, turns, human interventions, reworks, escalations and items done, ranks the variants (scenario-weighted pass rate, then cost) and names a winner only when an eligible variant beats the baseline beyond the tolerances, else `winner: null` with the reason. Scenario suites, running variants and scoring stay host-side.
12
+ - Principles: rule 5 adds the snapshot stale rule (a later `repo.changed` citing a source path, by event order); new rule 17 "Gate escalation only tightens".
13
+ - Tests: 1.2.0 compatibility fixtures (all five methodologies) load unchanged.
14
+ - Size: owner approved 2026-11-06 (spec 27), measured: `core+scrum` 61031 → 61884 B, `core+kanban` 68951 → 69804 B, `core+waterfall` 69379 → 70232 B, `core+investigation` 53566 → 54419 B, `core+experimentation` 57058 → 57911 B, `core+registry` 159765 → 160618 B (+853 B each: the three core hooks, `gate.resolved` and the `decide` lookup), `schema` 28942 → 28987 B (`Evidence.data`), `dist/index.mjs` 1330 → 1364 B, `dist/{investigation,experimentation,registry}/index.mjs` +30 B each (one more shared chunk import); `dist/policies/index.mjs` (19820 B) and `core+policies` (56597 B) seeded at measured size. The version bump changed no size.
15
+
16
+ Fixed (release gate of 1.3.0, spec 27 rows F1/F2), in code new in this release:
17
+
18
+ - Independence: both policies compare the assessor or snapshot recorder with every role dispatched on the item since its last rework, its `role` and its author (G1-1, G2-12), counting the transitions blockers append (G5-1); a snapshot qualifies only with a sourced assumption and a non-worker `human` or registered recorder, at record and at read time (G1-2, G2-1, G2-2).
19
+ - `decide` reads the `gate.resolved` recorded with its pending in one backward scan, so a resolution appended later cannot relax it and a long log costs no more than in 1.2 (G3-1, G2-5); a malformed requirement is skipped, never a `TypeError` (G1-7, G2-4).
20
+ - `recordRepoChange`, `contextOf` and the planner read the log through a cached per-log index: 10,000 in-flight items 9.6 s → 24 ms (G3-2 to G3-5, G2-6); `contextOf` returns copies (G2-9).
21
+ - Paths: control, bidirectional and non-NFC characters, surrounding whitespace and paths over 4096 characters are refused (G2-8, G4-4, G4-5).
22
+ - Risk options: one validator for `withRiskGate` and `riskEscalation` (no `TypeError` on `{}`), a monotone table required with requirements and evidence kinds compared apart, own properties only (G1-4, G1-6, G2-10, G5-4, G5-5).
23
+ - `compareRuns`: scenario-weighted pass rate (G1-3), non-finite totals refused and inputs read as own properties only (G2-7, G4-8).
24
+ - The `ex-workflow/policies` barrel is `src/policies/index.ts` (G4-3); 1.2.0 compatibility fixtures added (G4-2).
25
+
26
+ Compatibility: additive. `state.json` gains one optional field, `Evidence.data`, written only by the policy recorders; a `.workflow/state.json` written by any earlier release loads unchanged (`test/compat.test.ts` replays the fixtures through 1.2.0). No downgrade: 1.2.x cannot load a state carrying `Evidence.data`, because its schema closes `Evidence` (README Known limitations). Schema documents: still ten; `workflowStateSchema` gains the optional open `data` on `Evidence`. Event kinds: 69 → 71 (`gate.resolved`, `repo.changed`); existing payloads unchanged. Exports: the new entry `ex-workflow/policies` (ten runtime exports above); the root entry and `ex-workflow/types` gain the types `GateEscalation`, `BriefContext`, `ContextAssumption` and `ContextSnapshotData`; `Methodology` gains the optional `escalateGate`, `customPolicy` and `briefContext`, `Brief` the optional `context`; `evaluatePolicies` and `assertPolicies` an optional trailing parameter (1.1 signature last); nothing is removed (`test/api-surface.json` gains rows only). CLI: unchanged (`USAGE`, commands, flags); `exwf decide` honours an escalation an SDK run recorded, `exwf complete` checks the static gate, and without the wrapper a `context-grounded` stage falls back to the 1.2 `policy:context-grounded` evidence check. Error codes: unchanged (the recorders and options refuse with `invalid-input`; an unmet widened gate fails `gate-unmet`). Behaviour changes: none for a methodology without the hooks, so none for the built-ins and the CLI on states they wrote; `decide` on a pending raised under an escalation requires what the escalation added. Runtime dependencies: unchanged (`ex-flow`, `exsorted`). `VERSION` is `"1.3.0"`.
27
+
28
+ ## 1.2.0 (2026-11-03)
29
+
30
+ 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.
31
+
32
+ - Principles: `docs/principles.md` lists the engine invariants as numbered rules, each naming the file that enforces it and the test that pins it.
33
+ - 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.
34
+ - 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.
35
+ - 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`.
36
+ - 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.
37
+ - 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.
38
+ - 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.
39
+ - 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`.
40
+ - 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`.
41
+ - 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.
42
+ - 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.
43
+
44
+ Fixed (security and robustness review of 1.2.0, spec 26 rows "U12"):
45
+
46
+ - `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`.
47
+ - `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.
48
+ - 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.
49
+ - 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.
50
+ - 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.
51
+ - 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`.
52
+ - 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`.
53
+ - `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`.
54
+ - 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.
55
+ - `writeExt(state, key, undefined)` on a state with no `ext` no longer adds an empty `ext: {}`.
56
+ - `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.
57
+ - 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).
58
+ - `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`.
59
+ - Regression test for the ex-flow cycle fix: a 5,000-item cycle closed through `editItem` makes `next` fail `planner-error`.
60
+
61
+ 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"`.
62
+
3
63
  ## 1.1.1 (2026-10-30)
4
64
 
5
65
  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,52 +8,43 @@
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)
22
- 9. [CLI reference (`exwf`)](#cli-reference-exwf)
23
- 10. [Configuration](#configuration)
24
- 11. [Ceremonies](#ceremonies)
25
- 12. [Items, briefs, handoffs, accounting](#items-briefs-handoffs-accounting)
26
- 13. [Errors](#errors)
27
- 14. [JSON Schema](#json-schema)
28
- 15. [Package entry points](#package-entry-points)
29
- 16. [Compatibility and versioning](#compatibility-and-versioning)
30
- 17. [Known limitations](#known-limitations)
31
- 18. [Contributing](#contributing)
32
- 19. [License](#license)
33
-
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.
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)
23
+ 9. [Composable policies](#composable-policies)
24
+ 10. [CLI reference (`exwf`)](#cli-reference-exwf)
25
+ 11. [Configuration](#configuration)
26
+ 12. [Ceremonies](#ceremonies)
27
+ 13. [Items, briefs, handoffs, accounting](#items-briefs-handoffs-accounting)
28
+ 14. [Errors](#errors)
29
+ 15. [JSON Schema](#json-schema)
30
+ 16. [Package entry points](#package-entry-points)
31
+ 17. [Compatibility and versioning](#compatibility-and-versioning)
32
+ 18. [Known limitations](#known-limitations)
33
+ 19. [Contributing](#contributing)
34
+ 20. [License](#license)
42
35
 
43
36
  ## Pick a methodology
44
37
 
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 |
38
+ | | Scrum (`ex-workflow/scrum`) | Kanban (`ex-workflow/kanban`) | Waterfall (`ex-workflow/waterfall`) | Investigation (`ex-workflow/investigation`) | Experimentation (`ex-workflow/experimentation`) |
39
+ |---|---|---|---|---|---|
40
+ | 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 |
41
+ | 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 |
42
+ | Flow | backlog → sprint → review | options → ready → dev → review → done | work → review → done, inside each phase | intake → execute → observed | candidate → building → validation → done |
43
+ | 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 |
44
+ | 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 |
45
+ | 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 |
53
46
 
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`.
55
-
56
- Standalone [Investigation and Experimentation](#standalone-investigation-and-experimentation) add evidence-driven inquiry and isolated candidate comparison; each runs in its own state.
47
+ 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
48
 
58
49
  ## How a run works
59
50
 
@@ -217,6 +208,165 @@ Layout under the project root:
217
208
 
218
209
  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
210
 
211
+ ## Custom methodologies and extension state
212
+
213
+ `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:
214
+
215
+ ```ts
216
+ import { init, next, complete, type Methodology } from "ex-workflow";
217
+
218
+ function triage(): Methodology<TriageConfig, "triage"> {
219
+ return { name: "triage", /* vocabulary, stages, roles, ceremonies, rules, metrics, ... */ };
220
+ }
221
+ let { state } = init({ methodology: triage(), config: { queue: "support" } }); // WorkflowState<"triage">
222
+ ```
223
+
224
+ `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:
225
+
226
+ ```ts
227
+ import { methodologyFactory, registerMethodology, registeredMethodologies } from "ex-workflow/registry";
228
+
229
+ const m = methodologyFactory(state.methodology)(); // unknown name: invalid-input, the fix lists the known names
230
+ registerMethodology("triage", triage); // calls triage() once to check it; a taken name or a non-Methodology result: invalid-input
231
+ registeredMethodologies(); // ["scrum", "kanban", "waterfall", "investigation", "experimentation", "triage"]
232
+ ```
233
+
234
+ 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)).
235
+
236
+ A methodology keeps its own record in `state.ext`, keyed by its name, and reads and writes it only through the accessors:
237
+
238
+ ```ts
239
+ import { readExt, writeExt } from "ex-workflow";
240
+
241
+ const queue = readExt<string[]>(state, "triage") ?? [];
242
+ state = writeExt(state, "triage", [...queue, "T-1"]); // returns a new state; undefined removes the key
243
+ ```
244
+
245
+ 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.
246
+
247
+ ## Composable policies
248
+
249
+ `ex-workflow/policies` holds policies you opt into per run by wrapping a methodology. A wrapped methodology keeps every other member, its `name` included, so it runs on the same core and its state persists through the file adapter like the plain one's. The policies are SDK-only: `exwf` runs the plain built-in factory (see [Known limitations](#known-limitations)).
250
+
251
+ ### Risk-adaptive gates
252
+
253
+ A gate's requirements are static: the same approval for a typo fix and a production change. `withRiskGate` lets the item's recorded risk add to them, never take away:
254
+
255
+ ```ts
256
+ import { addItem, complete, decide, init, next } from "ex-workflow";
257
+ import { kanban } from "ex-workflow/kanban";
258
+ import { recordRiskAssessment, withRiskGate } from "ex-workflow/policies";
259
+
260
+ const m = withRiskGate(kanban(), { gates: ["code-review"] }); // only these gate ids escalate
261
+ // ... init with a review stage carrying gate { id: "code-review", requires: [{ capability: "review" }], ... }
262
+
263
+ // after the work, an independent role with capability verify (or "human") assesses the item
264
+ state = recordRiskAssessment(state, m, {
265
+ item: "CART-12",
266
+ level: "high", // "low" | "medium" | "high" | "critical"
267
+ factors: ["prod-infra", "secrets"], // free strings
268
+ ref: "risk/CART-12.md", // the host's assessment artifact
269
+ subject: "3f2c1e0", // optional: the SHA or ref assessed
270
+ by: "risk-reviewer",
271
+ }).state;
272
+
273
+ // the reviewer completes as usual: low passes on the static gate, high raises a human pending
274
+ const done = complete(state, m, handoff, accounting);
275
+ ```
276
+
277
+ - **The assessment** is evidence `risk-assessment` with `data: { level, factors, subject? }`, recorded through `applyAction` (action `risk.assess`, so your rules see it). `recordRiskAssessment` refuses `invalid-input` for an unknown key or level, a non-string factor, an empty `ref`, an assessor that is neither `human` nor a role with capability `verify`, and an assessor that worked on the item: any role that dispatched it since its last rework (every stage, not only the last), its assigned role, or its author.
278
+ - **Which assessment counts:** only fresh ones (recorded after the item's last rework), with well-formed `data`, by a qualified and independent assessor (re-checked when the gate is resolved). The strictest one wins, so a later, lower assessment does not relax an earlier one; only rework does. With none, the level is `critical`.
279
+ - **The table** says what each level adds to the static gate. `DEFAULT_RISK_TABLE`:
280
+
281
+ | Level | Adds |
282
+ |---|---|
283
+ | `low`, `medium` | nothing |
284
+ | `high`, `critical` | `"human"` |
285
+
286
+ Pass your own as `withRiskGate(m, { gates, table })`: every level needs a row `{ requires: GateRequirement[]; evidence?: string[] }`, and a stricter level must include everything the level below it adds, so a missing or rejected assessment (`critical`) never asks for less than a `low` one. E.g. `medium: { requires: [{ capability: "security-review" }], evidence: ["sbom"] }` with `high` and `critical` both `{ requires: [{ capability: "security-review" }, "human"], evidence: ["sbom"] }`. Invalid options fail `invalid-input` when you wrap.
287
+ - **`gate.resolved`**: on a gated completion, `complete()` appends `gate.resolved { item, gate, requires, evidence, reason }` before `gate.passed` or `pending.raised`, with the requirements actually checked and `reason: { level, why, assessment, by }` (`why` is `assessed`, `missing`, `invalid` or `not-independent`). A gate the policy does not name records the static gate with `reason: {}`.
288
+ - **`decide`** judges a pending gate against the `gate.resolved` that `complete()` recorded with that pending (a resolution appended later does not apply; with none, the static gate applies), so a role cannot approve an escalation to a human, also through `exwf decide`.
289
+ - **Any methodology** may implement the hook itself: `Methodology.escalateGate(state, item, gate)` returns `{ requires, evidence, reason }` or `undefined`. Core only appends what it returns to the static gate, so a hook can tighten a gate but never loosen it. `withRiskGate` keeps an existing hook and widens with both.
290
+ - `riskEscalation(state, item, gate, options)` is the resolver on its own, for hosts that want the answer without wrapping; it validates `options` the same way (`invalid-input`).
291
+
292
+ ### Context-grounded entry
293
+
294
+ A worker that starts from a stale picture of the repository builds on assumptions nobody checked. `withContextGrounding` lets an item enter a stage only with a fresh context snapshot that cites at least one source and that `human` or a registered role other than the item's workers recorded:
295
+
296
+ ```ts
297
+ import { next } from "ex-workflow";
298
+ import { kanban } from "ex-workflow/kanban";
299
+ import {
300
+ recordContextSnapshot,
301
+ recordRepoChange,
302
+ withContextGrounding,
303
+ } from "ex-workflow/policies";
304
+
305
+ const m = withContextGrounding(kanban(), { entry: ["dev"] }); // optional: exit: ["dev"]
306
+ // init with m: the dev column's entry policies gain { kind: "custom", id: "context-grounded" }
307
+
308
+ // a scout (a registered role that does not work on the item, or "human") records what it verified
309
+ state = recordContextSnapshot(state, m, {
310
+ item: "CART-12",
311
+ revision: "4f2c1e0",
312
+ assumptions: [
313
+ {
314
+ claim: "cart totals are integer cents",
315
+ required: true,
316
+ source: { path: "src/cart.ts", lines: [10, 24], hash: "9b1d…" },
317
+ },
318
+ { claim: "no caching layer in front of the cart" }, // no source: unverified
319
+ ],
320
+ ref: "ctx/CART-12.json", // the host's snapshot artifact
321
+ by: "scout", // a role registered in the state
322
+ }).state;
323
+
324
+ const { briefs } = next(state, m); // brief.context: what was verified, where, what went stale
325
+
326
+ // the host reports what each new revision changed
327
+ const changed = recordRepoChange(state, m, {
328
+ revision: "a71b2d9",
329
+ paths: ["src/cart.ts"], // as `git diff --name-only -z` lists them
330
+ by: "ci",
331
+ });
332
+ changed.warnings; // context-stale for each in-flight item whose snapshot cites a changed path
333
+ ```
334
+
335
+ - **The snapshot** is evidence `context-snapshot` with `data: { revision, assumptions }`, recorded through `applyAction` (action `context.snapshot`). An assumption is `{ claim, required?, source?: { path, lines?: [from, to], hash } }`; one without a `source` is unverified. `recordContextSnapshot` refuses `invalid-input` for a snapshot with no sourced assumption and for a `by` that is neither `human` nor a registered role, or that worked on the item (dispatched it since its last rework, is assigned to it, or authored it). The engine compares paths and hashes, it never reads a file.
336
+ - **Paths** are repository-relative POSIX paths as Git lists them, compared exactly (case included): `src/cart.ts`, not `./src/cart.ts`, `/src/cart.ts` or `src\cart.ts`. They must also be Unicode NFC (macOS file systems may hand you NFD), at most 4096 characters, with no control or bidirectional formatting character and no leading or trailing whitespace. Read them from `git diff --name-only -z` (NUL-separated and unquoted) or with `git -c core.quotePath=false`: by default Git prints a non-ASCII name quoted and escaped (`"caf\303\251.ts"`), which is refused. Both recorders refuse any other spelling with `invalid-input`.
337
+ - **`repo.changed`**: `recordRepoChange` (action `repo.change`) appends `repo.changed { revision, paths }`. A snapshot is stale when a later `repo.changed` lists a path it cites (event order, not timestamps; the revision alone does not decide). No item status changes: an item in `in_progress`, `review` or `awaiting_human` gets a `context-stale` warning in `ApplyResult.warnings` when this change made its snapshot stale, and a `todo` item is re-checked by its entry policy when the planner reaches it.
338
+ - **The policy** (`contextGroundedViolations`, rule `policy:custom:context-grounded`) fails an item with no qualifying fresh snapshot, with a stale one, or with a `required` assumption that has no source. A snapshot qualifies when its data is valid, it has at least one sourced assumption and `human` or a registered role that does not work on the item recorded it; the latest qualifying one counts, so a snapshot a worker wrote into the state by hand never replaces an independent one, and one recorded by a role that later works on the item stops counting. Rework drops every snapshot. `next` reports such a `todo` item under `skipped` with reason `entry-policy` and the message. A qualifying snapshot whose required claims are all sourced passes; unverified optional claims are listed in `brief.context.unverified`.
339
+ - **`brief.context`** is `contextOf(state, item)`: `{ revision, assumptions, snapshot, by, stale, unverified }`.
340
+ - **Any methodology** may answer custom policies itself: `Methodology.customPolicy(state, item, policy)` returns the violations, or `undefined` for the default check (evidence `policy:<id>`); `Methodology.briefContext(state, item)` fills `brief.context`. `withContextGrounding` keeps existing hooks for every other policy id and composes with `withRiskGate` in either order.
341
+
342
+ ### Comparing runs
343
+
344
+ `compareRuns` compares finished runs of two or more variants (a variant is whatever the host changed: a role's model tier, a config, a methodology). It is a pure function over `WorkflowState` values; the scenario suite, running each variant and scoring stay with the host.
345
+
346
+ ```ts
347
+ import { loadState } from "ex-workflow/adapters";
348
+ import { compareRuns } from "ex-workflow/policies";
349
+
350
+ const result = compareRuns(
351
+ [
352
+ { variant: "V0", scenario: "bug-fix-1", passed: true, state: await loadState(dirV0Bug1) },
353
+ { variant: "V1", scenario: "bug-fix-1", passed: true, state: await loadState(dirV1Bug1) },
354
+ // ... one record per variant and scenario run; a scenario may run more than once
355
+ ],
356
+ { baseline: "V0", mustPass: ["bug-fix-1"], passTolerance: 0.1, costTolerance: 0.05 },
357
+ );
358
+ result.winner; // "V1", or null when no eligible variant beats the baseline beyond the tolerances
359
+ result.reason; // why
360
+ result.variants; // ranked VariantResult[]: { variant, runs, passed, passRate, mean, regressions, missing, eligible }
361
+ ```
362
+
363
+ - **`passed`** is your scorer's verdict for that run. The engine derives the rest from the state: `mean` holds, per variant, the mean of `tokens` (accounting `tokensIn + tokensOut`, after corrections), `durationMs`, `turns` (accounting lines), `humanInterventions` (`pending.raised` plus `blocker.cleared` events), `reworks`, `escalations` and `itemsDone`.
364
+ - **`passRate`** weighs each scenario once: the mean over the scenarios the variant ran of the share of that scenario's runs that passed, so more runs of an easy scenario do not raise it; `runs` and `passed` count runs.
365
+ - **Eligible** means no `mustPass` scenario has a failing run (`regressions`) and the variant ran every scenario the baseline ran and every `mustPass` one (`missing`).
366
+ - **Ranking**: eligible first, then `passRate` descending, then mean tokens, mean duration and mean human interventions ascending, then the variant id in code-unit order. The input order of `runs` never changes the result.
367
+ - **Winner**: the first ranked eligible variant other than the baseline whose `passRate` is at least the baseline's minus `passTolerance` and that is better, by a `passRate` above the baseline's plus `passTolerance` or by mean tokens below the baseline's times `1 - costTolerance`. Tolerances are fractions in `[0, 1]`, default `0`.
368
+ - **Refused with `invalid-input`**: no runs, a non-array `runs`, an id that is not a valid id (`__proto__`, `toString` and the like included), a baseline or `mustPass` scenario no run names, a tolerance outside `[0, 1]`, a non-boolean `passed`, a state without `events`, `accounting` and `items`, a non-finite or negative token or duration figure, and token or duration totals or means that overflow to infinity. Only own properties of the options, run records and states are read (an inherited `{ __proto__: … }` value counts as absent). Variants of different methodologies compare on the same metrics.
369
+
220
370
  ## CLI reference (`exwf`)
221
371
 
222
372
  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.
@@ -356,7 +506,8 @@ Every config is validated at `init` (`config-invalid` names the key and an examp
356
506
  { item, role, modelTier, invariants, do_not, acceptance,
357
507
  upstream, // results of the items this one depends on
358
508
  priorHandoffs, // earlier attempts at this item (rework feedback)
359
- relatedBugs, budgetRemaining, gateAhead }
509
+ relatedBugs, budgetRemaining, gateAhead,
510
+ context } // with withContextGrounding: the item's context snapshot
360
511
  ```
361
512
 
362
513
  **Handoff** (what your agent gives back):
@@ -403,30 +554,44 @@ The CLI validates state, role manifests, items, patches and handoffs with these
403
554
 
404
555
  | Import | Contents |
405
556
  |---|---|
406
- | `ex-workflow` | core: `init`, `addItem`, `editItem`, `next`, `complete`, `decide`, `applyAction`, `validateAction`, `changeConfig`, `correctAccounting`, `clearBlocker`, `raiseBlocker`, `registerRole`, `openQuestions`, `WorkflowError`, `VERSION`, … |
557
+ | `ex-workflow` | core: `init`, `addItem`, `editItem`, `next`, `complete`, `decide`, `applyAction`, `validateAction`, `changeConfig`, `correctAccounting`, `clearBlocker`, `raiseBlocker`, `registerRole`, `openQuestions`, `readExt`, `writeExt`, `independenceConflicts`, `frozenChanges`, `WorkflowError`, `VERSION`, … |
407
558
  | `ex-workflow/scrum` | `scrum()`, `scrumMetrics`, `dailyReport`, `closeSprint`, presets |
408
559
  | `ex-workflow/kanban` | `kanban()`, `board`, `kanbanMetrics`, `opsReport`, `riskReport`, `cadencesDue`, `DEFAULT_COLUMNS`, presets |
409
560
  | `ex-workflow/waterfall` | `waterfall()`, `phaseReport`, `traceabilityMatrix`, `waterfallMetrics`, `baselinePhase`, `reopenPhases`, presets |
410
561
  | `ex-workflow/investigation` | `investigation()`, `validateInvestigationConfig`; types `InvestigationConfig`, `InvestigationState`, `InvestigationRound`, `InvestigationConclusion`, `Hypothesis`, `Experiment`, `Observation`, `BeliefUpdate` |
411
562
  | `ex-workflow/experimentation` | `experimentation()`, `validateExperimentationConfig`, `experimentationCeremonies`, `experimentationMetrics`, `experimentationReport`, `experimentationRoles`, `experimentationRules`, `experimentationStages`; types `ExperimentationConfig`, `ExperimentationState`, `ExperimentCandidate` |
563
+ | `ex-workflow/registry` | `registerMethodology`, `methodologyFactory`, `registeredMethodologies` (five built-ins pre-registered); types `MethodologyFactory`, `MethodologyRegistry` |
564
+ | `ex-workflow/policies` | `withRiskGate`, `recordRiskAssessment`, `riskEscalation`, `DEFAULT_RISK_TABLE`, `withContextGrounding`, `recordContextSnapshot`, `recordRepoChange`, `contextOf`, `contextGroundedViolations`, `compareRuns`; types `RiskLevel`, `RiskTable`, `RiskAssessmentData`, `RiskAssessmentInput`, `RiskGateOptions`, `ContextGroundingOptions`, `ContextSnapshotInput`, `RepoChangeInput`, `CompareRunsOptions`, `RunRecord`, `RunMetrics`, `VariantResult`, `RunComparison` (`ContextAssumption`, `ContextSnapshotData` and `BriefContext` come from the root entry) |
412
565
  | `ex-workflow/adapters` | `loadState`, `saveState`, `saveBrief`, `saveHandoff`, `withStateLock`, `WORKFLOW_DIR` |
413
566
  | `ex-workflow/schema` | the ten schema documents, `validate`, `assertValid` |
414
567
  | `ex-workflow/cli` | `runCommand`, `parseArgs`, `USAGE`: the `exwf` command as a library |
415
568
  | `ex-workflow/types` | every public type |
416
569
 
417
- Each entry ships ESM, CommonJS and `.d.ts`. Core plus one methodology is about 51–68 kB minified.
570
+ Each entry ships ESM, CommonJS and `.d.ts`. Core plus one methodology is about 53–69 kB minified.
418
571
 
419
572
  ## Compatibility and versioning
420
573
 
421
- - 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.
574
+ - Semver from 1.0.0. The public surface (exports of every entry point, the CLI commands, the ten schema documents, the 71 event kinds) is frozen by test: a removal is a major version, an addition a minor one.
422
575
  - A `.workflow/state.json` written by any earlier release loads unchanged; the test suite replays state files from every published pre-release.
576
+ - **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
577
  - Behaviour changes are listed per release in [CHANGELOG.md](CHANGELOG.md).
424
578
 
425
579
  ## Known limitations
426
580
 
427
581
  Deliberate, documented, and stable within 1.x.
428
582
 
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.
583
+ - **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.
584
+ - **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.
585
+ - **No downgrade for a state with evidence `data`.** 1.2.x cannot load a state carrying `Evidence.data` (a risk assessment or context snapshot recorded by `ex-workflow/policies`): its schema closes `Evidence`. Keep such a run on 1.3.
586
+ - **Policies are SDK-only.** `exwf` runs the plain built-in methodology, so `exwf complete` checks a gate's static requirements only. `exwf decide` does honour an escalation the SDK recorded (`gate.resolved`). Run completions of a risk-gated run through the SDK. There is no CLI command for snapshots or repository changes.
587
+ - **Without the wrapper, `context-grounded` is only as strong as the 1.2 custom-policy check.** On a stage carrying the policy, `exwf next` and `exwf complete` (and any SDK call with the plain methodology) fall back to the default check: the item passes when it carries fresh evidence of kind `policy:context-grounded`. That evidence is not tied to a snapshot, and `complete()` records every `handoff.produced` entry as evidence, so a worker can attest the policy for its own item by listing `{ kind: "policy:context-grounded", ref }` in a handoff. An item without that evidence is skipped. Plan and complete a grounded run through the SDK with `withContextGrounding`, which ignores such evidence and checks the snapshot.
588
+ - **Context grounding on an existing state, and Kanban policy changes.** `withContextGrounding` adds its policy through `defaultStages`, so it reaches a state at `init`; for a state created before wrapping, add `{ kind: "custom", id: "context-grounded", description }` to the stage's `entryPolicy` yourself. A Kanban `operations-review` that changes the commitment column's policies rewrites the next column's entry policies and drops it; add it back the same way.
589
+ - **Independence at entry needs a known worker.** The policy compares the snapshot's recorder with the roles that worked on the item. A `todo` item never dispatched and without a `role` has no worker yet (the planner picks one after the entry check), so a snapshot by the role the planner then picks passes the entry check. Once that role is dispatched its snapshot stops counting: `contextOf` falls back to the latest earlier qualifying snapshot, which may be stale (the brief carries it with its `stale` paths, and an `exit` policy fails on it), or, with none, the brief has no `context` and an `exit` policy fails. For the same reason, before dispatch that future worker can record a weaker sourced snapshot (its `required` claims dropped) that supersedes a stale independent one, and the item is then dispatched to it. Set `role` on the item, or also pass `exit`, to have the check apply before the work.
590
+ - **`checkGate` alone sees the static gate.** The risk escalation is applied by `complete()` and `decide()`; a host calling `checkGate` directly gets the 1.2 answer.
591
+
592
+ - **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.
593
+ - **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).
594
+ - **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
595
  - **Blockers are owned by a human.** Finishing a follow-up does not clear its blocker; `unblock` does.
431
596
  - **Direct primitives bypass the baseline.** `addItem` and `editItem` called directly do not check `baseline-immutable`; `applyAction` and the CLI do.
432
597
  - **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 chunkKA6DVHO5_cjs=require('../chunk-KA6DVHO5.cjs');require('../chunk-BBI7AKJK.cjs'),require('../chunk-DVFTTBCT.cjs'),require('../chunk-OSHBJIYD.cjs');Object.defineProperty(exports,"WORKFLOW_DIR",{enumerable:true,get:function(){return chunkKA6DVHO5_cjs.a}});Object.defineProperty(exports,"loadState",{enumerable:true,get:function(){return chunkKA6DVHO5_cjs.e}});Object.defineProperty(exports,"saveBrief",{enumerable:true,get:function(){return chunkKA6DVHO5_cjs.g}});Object.defineProperty(exports,"saveHandoff",{enumerable:true,get:function(){return chunkKA6DVHO5_cjs.h}});Object.defineProperty(exports,"saveState",{enumerable:true,get:function(){return chunkKA6DVHO5_cjs.d}});Object.defineProperty(exports,"statePath",{enumerable:true,get:function(){return chunkKA6DVHO5_cjs.b}});Object.defineProperty(exports,"withStateLock",{enumerable:true,get:function(){return chunkKA6DVHO5_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-DLOtndDY.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-DLOtndDY.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-ONVAUZOD.mjs';import'../chunk-TQR3VFZU.mjs';import'../chunk-QJMOCISZ.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.js';
1
+ import { W as WorkflowState, C as Capability, R as Role, a as Budget, A as Accounting } from './types-DLOtndDY.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 };
@@ -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-DLOtndDY.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 };