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
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkEACZBAP3_cjs=require('./chunk-EACZBAP3.cjs'),chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs');function v(t,n){return [...new Set([...t.events.filter(u=>u.type==="item.completed"&&u.payload.id===n).map(u=>u.by),...(t.items[n]?.transitions??[]).filter(u=>u.to.status==="in_progress").map(u=>u.by)])]}function W(t,n){let u;for(let d=t.events.length-1;d>=0;d--){let s=t.events[d];if(s.type==="item.completed"&&s.payload.id===n){u=s.payload;break}}return u&&["done","needs-review"].includes(u.verdict)?u.produced.filter(d=>d.kind==="experiment-output").map(d=>d.ref):[]}function x(t){let n=t;return (!n||typeof n!="object"||Array.isArray(n)||typeof n.question!="string"||!n.question.trim()||!Number.isSafeInteger(n.maxRounds)||n.maxRounds<1||!n.budget||typeof n.budget!="object"||Array.isArray(n.budget)||!Object.keys(n.budget).length||Object.entries(n.budget).some(([u,d])=>!["tokens","turns","wallclockMs"].includes(u)||typeof d!="number"||!Number.isFinite(d)||d<=0))&&chunkS3BXVHO7_cjs.b("config-invalid","investigation requires question, positive maxRounds and a finite positive budget","provide bounded investigation config"),{question:n.question,maxRounds:n.maxRounds,budget:{...n.budget}}}function C(t,n,u,d){let s=t.investigation;return chunkS3BXVHO7_cjs.b("invalid-input",`${n} (phase ${s?.phase??"intake"}): ${u}`,d,{items:s?[s.item,...s.rounds.at(-1)?[s.rounds.at(-1).item]:[]]:[]})}var E=(t,n)=>!!t&&!!n&&t.id===n.id&&t.claim===n.claim&&t.falsifiedBy===n.falsifiedBy,m=t=>typeof t=="string"&&t.trim().length>0,A=t=>Array.isArray(t)&&t.length>0&&t.every(m)&&new Set(t).size===t.length,H=(t,n)=>t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).find(u=>!n.includes(u)):void 0,O=(t,n)=>Array.isArray(t)?t.map(u=>H(u,n)).find(Boolean):void 0;function D(t,n,u){chunkEACZBAP3_cjs.e(t,n)?.capabilities.includes(u)||chunkS3BXVHO7_cjs.b("missing-capability",`${n} needs ${u}`,"use a registered role with the required capability");}function h(t,n,u,d){return chunkEACZBAP3_cjs.c({...t,investigation:n},`investigation.${d}`,u.by,{...n},chunkEACZBAP3_cjs.a(u.now))}function R(t,n,u,d,s){let e=chunkEACZBAP3_cjs.a(u.now),i=h(t,{...n,phase:"closed",outcome:d,...s?{stopReason:s}:{}},u,d);i={...i,iterations:i.iterations.map(p=>p.id==="investigation"?{...p,endedAt:e,outcome:d==="stopped"?"cancelled":"completed"}:p)};for(let p of Object.values(i.items).filter(r=>r.id===n.item||n.rounds.some(a=>a.item===r.id)))p.status!=="done"&&p.status!=="dropped"&&(i=chunkEACZBAP3_cjs.x(i,p.id,{status:d==="resolved"&&p.id===n.item?"done":"dropped"},u.by,e));return i}function M(t){let n,u=()=>n??=t(),d=(s,e,i,p)=>(r,a)=>{D(r,a.by,e);let o=r.investigation;return (!o||o.phase==="closed")&&C(r,s,"no active investigation","start a new investigation with intake {item}"),i&&o.phase!==i&&!(s==="hypotheses"&&o.phase==="preregister")&&C(r,s,`expected ${i}, got ${o.phase}`,`finish phase ${o.phase} before calling ${s}; ${s} requires phase ${i}`),chunkEACZBAP3_cjs.W(r,u(),{type:`ceremony.${s}`,by:a.by,payload:a},()=>p(r,o,a,(l,g)=>C(r,s,l,g)))};return {intake(s,e){D(s,e.by,"facilitate");let i=(r,a)=>C(s,"intake",r,a);s.methodology!=="investigation"&&i(`workflow methodology is ${s.methodology}, not investigation`,"init a workflow with the investigation methodology before intake"),s.investigation&&i("investigation already started","use the existing investigation or initialize a new workflow"),m(e.item)||i("item is required","set intake.item to a unique investigation item ID");let p=x(s.config);return chunkEACZBAP3_cjs.W(s,u(),{type:"ceremony.intake",by:e.by,payload:e},()=>{let r=chunkEACZBAP3_cjs.v(s,{id:e.item,title:p.question,acceptance:["Independent evidence-based conclusion"],stage:"intake"},e.by,e.now);return r={...r,iterations:[...r.iterations,{id:"investigation",goal:p.question,budget:{...p.budget},spent:{tokens:0,turns:0,wallclockMs:0},startedAt:chunkEACZBAP3_cjs.a(e.now),committed:[],carryover:[]}]},h(r,{item:e.item,phase:"hypotheses",hypotheses:[],rounds:[],contributors:[e.by]},e,"intake")})},hypotheses:d("hypotheses","define-acceptance","hypotheses",(s,e,i,p)=>{let r=i.hypotheses,a=O(r,["id","claim","falsifiedBy"]);return a&&p(`unknown key "${a}" in a hypotheses entry`,"use only id, claim and falsifiedBy in each hypotheses entry"),(!Array.isArray(r)||!r.length||r.some(o=>!o||!m(o.id)||!m(o.claim)||!m(o.falsifiedBy))||new Set(r.map(o=>o.id)).size!==r.length||r.length<2&&!m(i.singleHypothesisRationale))&&p("provide competing falsifiable hypotheses or single-testable rationale","set hypotheses to unique {id, claim, falsifiedBy} entries; supply singleHypothesisRationale when there is only one"),h(s,{...e,hypotheses:r.map(o=>({id:o.id,claim:o.claim,falsifiedBy:o.falsifiedBy})),...m(i.singleHypothesisRationale)?{singleHypothesisRationale:i.singleHypothesisRationale}:{},contributors:[...new Set([...e.contributors,i.by])],phase:"preregister"},i,"hypotheses")}),preregister:d("preregister","define-acceptance","preregister",(s,e,i,p)=>{let r=x(s.config),a=s.iterations.find(c=>c.id==="investigation");(e.rounds.length>=r.maxRounds||!a||chunkEACZBAP3_cjs.N(r.budget,a.spent))&&p(`round limit or budget exhausted (${e.rounds.length} of ${r.maxRounds} rounds used)`,"call stop {reason} to close this investigation, or start a new one with a larger maxRounds or budget");let o=i.experiment,l=H(o,["id","procedureRef","predictions","replayOf"])??O(o?.predictions,["hypothesis","prediction"]);if(l&&p(`unknown key "${l}" in experiment`,"use only id, procedureRef, predictions [{hypothesis, prediction}] and replayOf in experiment"),(!o||!m(o.id)||!m(o.procedureRef)||e.rounds.some(c=>c.experiment.id===o.id)||!Array.isArray(o.predictions)||o.predictions.length!==e.hypotheses.length||e.hypotheses.some(c=>o.predictions.filter(y=>y?.hypothesis===c.id&&m(y.prediction)).length!==1)||new Set(o.predictions.map(c=>c.prediction)).size!==o.predictions.length)&&p("preregister unique experiment with differing predictions for every hypothesis","set experiment.id to a new ID, experiment.procedureRef, and one distinct experiment.predictions entry per hypothesis"),o.replayOf){let c=e.rounds.find(y=>y.experiment.id===o.replayOf&&y.result?.valid);(!c||c.experiment.procedureRef!==o.procedureRef||c.hypotheses.length!==e.hypotheses.length||e.hypotheses.some(y=>!E(y,c.hypotheses.find(k=>k.id===y.id)))||o.predictions.some(y=>!c.experiment.predictions.some(k=>k.hypothesis===y.hypothesis&&k.prediction===y.prediction)))&&p("replay must repeat the procedure, predictions and hypotheses of a prior valid experiment","set experiment.replayOf to a valid prior experiment with identical procedureRef, predictions and hypothesis definitions");}let g=`${e.item}-run-${e.rounds.length+1}`,f=chunkEACZBAP3_cjs.v(s,{id:g,title:`Experiment ${o.id}`,stage:"execute",acceptance:[o.procedureRef],iteration:"investigation"},i.by,i.now);return f={...f,iterations:f.iterations.map(c=>c.id==="investigation"?{...c,committed:[...c.committed,g]}:c)},h(f,{...e,phase:"observe",rounds:[...e.rounds,{experiment:{id:o.id,procedureRef:o.procedureRef,predictions:o.predictions.map(c=>({hypothesis:c.hypothesis,prediction:c.prediction})),...o.replayOf?{replayOf:o.replayOf}:{}},hypotheses:e.hypotheses.map(c=>({...c})),item:g,by:i.by}],contributors:[...new Set([...e.contributors,i.by])]},i,"preregister")}),observe:d("observe","verify","observe",(s,e,i,p)=>{let r=e.rounds.at(-1),a=i.result,o=H(a,["id","valid","summary","provenanceRefs"]);return o&&p(`unknown key "${o}" in result`,"use only id, valid, summary and provenanceRefs in result"),(i.experiment!==r.experiment.id||!a||!m(a.id)||typeof a.valid!="boolean"||!m(a.summary)||!A(a.provenanceRefs)||e.rounds.some(l=>l.result?.id===a.id))&&p("observation needs current experiment, unique result and provenance","set experiment to the active experiment ID and result to {id, valid, summary, provenanceRefs} with a new result.id"),s.items[r.item]?.status!=="done"&&p("complete experiment execution before recording observations","dispatch and complete the active experiment item before calling observe"),W(s,r.item).some(l=>a.provenanceRefs.includes(l))||p("observation must link fresh experiment-output evidence from the latest completion",`include an experiment-output ref produced by the latest successful completion of item "${r.item}" in result.provenanceRefs`),h(s,{...e,phase:"update-belief",rounds:e.rounds.map(l=>l===r?{...l,result:{id:a.id,valid:a.valid,summary:a.summary,provenanceRefs:[...a.provenanceRefs]}}:l),contributors:[...new Set([...e.contributors,i.by,...v(s,r.item)])]},i,"observe")}),"update-belief":d("update-belief","define-acceptance","update-belief",(s,e,i,p)=>{let r=e.rounds.at(-1),a=i.assessments,o=O(a,["hypothesis","assessment","reason"]);o&&p(`unknown key "${o}" in an assessments entry`,"use only hypothesis, assessment and reason in each assessments entry"),(i.result!==r.result?.id||!Array.isArray(a)||a.length!==e.hypotheses.length||e.hypotheses.some(f=>a.filter(c=>c?.hypothesis===f.id&&["supported","refuted","uncertain"].includes(c.assessment)&&m(c.reason)).length!==1)||!["round","conclusion"].includes(i.next))&&p("belief update must assess every hypothesis against current result","set result to the latest result ID, assessments to one {hypothesis, assessment, reason} per hypothesis, and next to round or conclusion"),!r.result.valid&&a.some(f=>f.assessment!=="uncertain")&&p("invalid experiments cannot support beliefs","set every assessment to uncertain for an invalid experiment result");let l=h(s,{...e,phase:i.next==="round"?"preregister":"conclusion",rounds:e.rounds.map(f=>f===r?{...f,update:{result:i.result,assessments:a.map(c=>({hypothesis:c.hypothesis,assessment:c.assessment,reason:c.reason}))}}:f),contributors:[...new Set([...e.contributors,i.by])]},i,"belief-updated"),g=l.iterations.find(f=>f.id==="investigation");return i.next==="round"&&(e.rounds.length>=x(s.config).maxRounds||chunkEACZBAP3_cjs.N(g.budget,g.spent))&&(l=R(l,l.investigation,i,"stopped","budget or round limit exhausted")),l}),conclude:d("conclude","define-acceptance","conclusion",(s,e,i,p)=>{let r=i;return (!["resolved","inconclusive"].includes(r.outcome)||!m(r.summary)||!A(r.evidenceRefs)||r.evidenceRefs.some(a=>!e.rounds.some(o=>o.result?.provenanceRefs.includes(a))))&&p("conclusion needs observed evidence references","set outcome, summary and evidenceRefs to references preserved in recorded observations"),r.outcome==="resolved"&&(!m(r.supportedHypothesis)||!e.rounds.slice(-1).some(a=>a.result?.valid&&a.update?.assessments.some(o=>o.hypothesis===r.supportedHypothesis&&o.assessment==="supported")))&&p("resolved conclusion needs a supported hypothesis","set supportedHypothesis to a hypothesis supported by the latest valid round, or choose outcome inconclusive"),h(s,{...e,phase:"review",conclusion:{outcome:r.outcome,summary:r.summary,evidenceRefs:[...r.evidenceRefs],...r.supportedHypothesis?{supportedHypothesis:r.supportedHypothesis}:{},by:i.by},contributors:[...new Set([...e.contributors,i.by])]},i,"conclusion")}),"review-conclusion":d("review-conclusion","review","review",(s,e,i,p)=>{if(e.contributors.includes(i.by)&&p("conclusion reviewer must be independent of investigation contributors","use a review-capable role that did not contribute to or execute this investigation"),(typeof i.approve!="boolean"||!m(i.reason))&&p("review needs approval and reason","set approve to a boolean and reason to a nonempty review explanation"),!i.approve){let a=i.next??"conclusion";a!=="round"&&a!=="conclusion"&&p("review rejection next must be round or conclusion","set next to round for more evidence or conclusion for a revised conclusion");let o=h(s,{...e,phase:a==="round"?"preregister":"conclusion",reviewHistory:[...e.reviewHistory??[],{by:i.by,reason:i.reason,approve:false,next:a,replayRefs:[]}]},i,"review-rejected"),l=s.iterations.find(g=>g.id==="investigation");return a==="round"&&(e.rounds.length>=x(s.config).maxRounds||chunkEACZBAP3_cjs.N(l.budget,l.spent))?R(o,o.investigation,i,"stopped","budget or round limit exhausted after review requested another round"):o}let r=Array.isArray(i.replayRefs)?i.replayRefs:[];return e.conclusion.outcome==="resolved"&&(!A(r)||!e.rounds.some(a=>a.experiment.replayOf&&!v(s,a.item).some(o=>v(s,e.rounds.find(l=>l.experiment.id===a.experiment.replayOf).item).includes(o))&&E(a.hypotheses.find(o=>o.id===e.conclusion.supportedHypothesis),e.rounds.at(-1).hypotheses.find(o=>o.id===e.conclusion.supportedHypothesis))&&a.result?.valid&&r.includes(a.result.id)&&a.update?.assessments.some(o=>o.hypothesis===e.conclusion.supportedHypothesis&&o.assessment==="supported")))&&p("resolved conclusion requires valid replay result and supporting belief update","set replayRefs to a valid independent replay result supporting the latest supported hypothesis definition, or reject with next round"),R(s,{...e,review:{by:i.by,reason:i.reason,replayRefs:r},reviewHistory:[...e.reviewHistory??[],{by:i.by,reason:i.reason,approve:true,replayRefs:r}]},i,e.conclusion.outcome)}),stop:d("stop","facilitate",void 0,(s,e,i,p)=>(m(i.reason)||p("stop needs reason","set reason to a nonempty explanation for stopping this investigation"),R(s,e,i,"stopped",i.reason)))}}function P(){return [{id:"independent-replay",severity:"error",check(t,n){if(n.type!=="item.complete")return [];let u=t.investigation?.rounds.find(s=>s.item===n.payload?.item),d=t.investigation?.rounds.find(s=>s.experiment.id===u?.experiment.replayOf);return d&&v(t,d.item).includes(n.by)?[{rule:"independent-replay",item:u.item,severity:"error",message:"Replay executor also executed the original experiment",fix:"assign a different deliver-capable role"}]:[]}},{id:"investigation-execution-only",severity:"error",check(t,n){if(n.type!=="item.complete")return [];let u=n.payload,d=t.investigation;return d?.phase==="observe"&&d.rounds.at(-1)?.item===u.item?[]:[{rule:"investigation-execution-only",item:u.item,severity:"error",message:"Only the active preregistered experiment can complete",fix:`complete only the active experiment item in phase observe; current phase is ${d?.phase??"intake"}`}]}}]}function z(){return [{id:"replay-worker",name:"Independent replay worker",modelTier:"small",capabilities:["deliver","verify"],canApprove:[],inputs:["preregistered-experiment"],outputs:["experiment-output"],do_not:["Do not change the replay procedure"]},{id:"investigator",name:"Investigator",modelTier:"large",capabilities:["facilitate","define-acceptance","deliver","verify"],canApprove:[],inputs:["question","prior-results"],outputs:["hypotheses","preregistered-experiment","belief-update"],do_not:["Do not revise predictions after execution","Do not approve your own conclusions"]},{id:"conclusion-reviewer",name:"Independent conclusion reviewer",modelTier:"large",capabilities:["review"],canApprove:["investigation-conclusion"],inputs:["evidence","replay","conclusion"],outputs:["conclusion-review"],do_not:["Do not approve unsupported conclusions"]}]}function K(){return [{id:"intake",name:"Intake",entryPolicy:[],exitPolicy:[{kind:"acceptance-written"}]},{id:"execute",name:"Execute preregistered experiment",entryPolicy:[{kind:"acceptance-written"},{kind:"no-open-blockers"}],exitPolicy:[{kind:"evidence",evidenceKind:"experiment-output"}]},{id:"observed",name:"Execution recorded",entryPolicy:[],exitPolicy:[]}]}function T(){return {name:"investigation",validateConfig:x,lockedConfigKeys:["question","maxRounds","budget"],vocabulary:{backlog:"Questions",item:"Investigation artifact",stage:"Investigation phase",iteration:"Investigation budget",increment:"Conclusion",ceremony:"Investigation ceremony",gate:"Independent conclusion review"},defaultStages:K,defaultRoles:z,requiredCapabilities:["facilitate","define-acceptance","deliver","verify","review"],exclusiveCapabilities:[],humanDefaults:{gates:"none"},ceremonies:M(T),plannerOptions:t=>({schedulerMode:"level",concurrencyCap:1,roleFor:n=>{let u=t.investigation?.rounds.find(p=>p.item===n.id),d=t.investigation?.rounds.find(p=>p.experiment.id===u?.experiment.replayOf),s=d?v(t,d.item):[],e=Object.values(t.roles),i=(d?void 0:e.find(p=>p.capabilities.includes("deliver")&&p.capabilities.includes("define-acceptance")))??e.find(p=>p.capabilities.includes("deliver")&&!s.includes(p.id));return i||chunkS3BXVHO7_cjs.b("missing-capability",`No eligible executor for experiment item "${n.id}"`,d?`register an independent deliver-capable role that did not execute "${d.item}"`:"register a role with deliver capability",{items:[n.id]}),i.id},estimateMode:"per-call",fallbackTokensPerWeight:1}),candidates:t=>t.investigation?.phase==="observe"&&!chunkEACZBAP3_cjs.N(t.config.budget,t.iterations.find(n=>n.id==="investigation").spent)?Object.values(t.items).filter(n=>n.id===t.investigation.rounds.at(-1)?.item&&n.stage==="execute"&&n.status==="todo"):[],afterComplete:(t,n,u)=>{let d=t.investigation,s=t.iterations.find(e=>e.id==="investigation");return d?.phase!=="observe"||d.rounds.at(-1)?.item!==n||t.items[n]?.status==="done"||!s||!chunkEACZBAP3_cjs.N(s.budget,s.spent)?t:R(t,d,{by:"investigation",now:u},"stopped",`budget exhausted before experiment item "${n}" completed; start a new investigation with sufficient budget`)},invariants:t=>[`Question: ${t.config.question}`,"Execute only the preregistered procedure; retain raw observation provenance; report invalid runs."],rules:P(),metrics:t=>({rounds:t.investigation?.rounds.length??0,validRuns:t.investigation?.rounds.filter(n=>n.result?.valid).length??0,invalidRuns:t.investigation?.rounds.filter(n=>n.result&&!n.result.valid).length??0}),report:t=>({phase:t.investigation?.phase??"intake",outcome:t.investigation?.outcome??null,rounds:t.investigation?.rounds.length??0,conclusion:t.investigation?.conclusion??null,stopReason:t.investigation?.stopReason??null})}}exports.a=x;exports.b=T;//# sourceMappingURL=chunk-SVGTSPZF.cjs.map
2
- //# sourceMappingURL=chunk-SVGTSPZF.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/investigation/execution.ts","../src/investigation/config.ts","../src/investigation/ceremonies.ts","../src/investigation/rules.ts","../src/investigation/roles.ts","../src/investigation/stages.ts","../src/investigation/index.ts"],"names":["executionActors","state","item","event","transition","freshOutputRefs","completion","index","output","validateInvestigationConfig","raw","c","k","v","fail","reject","s","name","message","fix","x","sameHypothesis","a","b","text","refs","extraKey","keys","extraKeyIn","list","authorize","by","cap","roleOf","save","i","appendEvent","nowOf","closeInvestigation","outcome","reason","at","n","it","candidate","r","moveItem","investigationCeremonies","factory","built","methodology","make","phase","fn","applyAction","bad","addItem","h","extra","isExhausted","e","extraExperiment","p","prior","q","id","iteration","o","ref","entry","target","replayRefs","actor","investigationRules","round","investigationRoles","investigationStages","investigation","excluded","roles","selected","role","now"],"mappings":"qHASO,SAASA,EAAgBC,CAAAA,CAAsBC,CAAAA,CAAwB,CAC5E,OAAO,CACL,GAAG,IAAI,GAAA,CAAI,CACT,GAAGD,EAAM,MAAA,CACN,MAAA,CACEE,GAAUA,CAAAA,CAAM,IAAA,GAAS,kBAAqBA,CAAAA,CAAM,OAAA,CAAuB,EAAA,GAAOD,CACrF,EACC,GAAA,CAAKC,CAAAA,EAAUA,EAAM,EAAE,CAAA,CAC1B,IAAIF,CAAAA,CAAM,KAAA,CAAMC,CAAI,CAAA,EAAG,aAAe,EAAC,EACpC,OAAQE,CAAAA,EAAeA,CAAAA,CAAW,GAAG,MAAA,GAAW,aAAa,CAAA,CAC7D,GAAA,CAAKA,GAAeA,CAAAA,CAAW,EAAE,CACtC,CAAC,CACH,CACF,CAGO,SAASC,CAAAA,CAAgBJ,CAAAA,CAAsBC,EAAwB,CAC5E,IAAII,EACJ,IAAA,IAASC,CAAAA,CAAQN,EAAM,MAAA,CAAO,MAAA,CAAS,CAAA,CAAGM,CAAAA,EAAS,EAAGA,CAAAA,EAAAA,CAAS,CAC7D,IAAMJ,CAAAA,CAAQF,CAAAA,CAAM,OAAOM,CAAK,CAAA,CAChC,GAAIJ,CAAAA,CAAM,OAAS,gBAAA,EAAqBA,CAAAA,CAAM,QAAuB,EAAA,GAAOD,CAAAA,CAAM,CAChFI,CAAAA,CAAaH,CAAAA,CAAM,OAAA,CACnB,KACF,CACF,CAC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AClD,CACF,CAAA,CACA,UAAA,CAAac,GAAM,CACjB,CAAA,UAAA,EAAcA,CAAAA,CAAE,MAAA,CAA+B,QAAQ,CAAA,CAAA,CACvD,mGACF,EACA,KAAA,CAAOyD,CAAAA,GACP,OAAA,CAAUzD,CAAAA,GAAO,CACf,MAAA,CAAQA,EAAE,aAAA,EAAe,MAAA,CAAO,QAAU,CAAA,CAC1C,SAAA,CAAWA,EAAE,aAAA,EAAe,MAAA,CAAO,MAAA,CAAQ6B,CAAAA,EAAMA,EAAE,MAAA,EAAQ,KAAK,EAAE,MAAA,EAAU,CAAA,CAC5E,YAAa7B,CAAAA,CAAE,aAAA,EAAe,MAAA,CAAO,MAAA,CAAQ6B,GAAMA,CAAAA,CAAE,MAAA,EAAU,CAACA,CAAAA,CAAE,MAAA,CAAO,KAAK,CAAA,CAAE,MAAA,EAAU,CAC5F,CAAA,CAAA,CACA,OAAS7B,CAAAA,GAAO,CACd,MAAOA,CAAAA,CAAE,aAAA,EAAe,OAAS,QAAA,CACjC,OAAA,CAASA,CAAAA,CAAE,aAAA,EAAe,SAAW,IAAA,CACrC,MAAA,CAAQA,EAAE,aAAA,EAAe,MAAA,CAAO,QAAU,CAAA,CAC1C,UAAA,CAAYA,EAAE,aAAA,EAAe,UAAA,EAAc,KAC3C,UAAA,CAAYA,CAAAA,CAAE,eAAe,UAAA,EAAc,IAC7C,EACF,CACF","file":"chunk-SVGTSPZF.cjs","sourcesContent":["import type { Handoff, Verdict, WorkflowState } from \"../types.ts\";\n\ninterface Completion {\n id: string;\n verdict: Verdict;\n produced: Handoff[\"produced\"];\n}\n\n/** Completion actors come from validated handoffs, never caller-supplied accounting identity. */\nexport function executionActors(state: WorkflowState, item: string): string[] {\n return [\n ...new Set([\n ...state.events\n .filter(\n (event) => event.type === \"item.completed\" && (event.payload as Completion).id === item,\n )\n .map((event) => event.by),\n ...(state.items[item]?.transitions ?? [])\n .filter((transition) => transition.to.status === \"in_progress\")\n .map((transition) => transition.by),\n ]),\n ];\n}\n\n/** Only outputs of the latest successful completion can establish observation provenance. */\nexport function freshOutputRefs(state: WorkflowState, item: string): string[] {\n let completion: Completion | undefined;\n for (let index = state.events.length - 1; index >= 0; index--) {\n const event = state.events[index]!;\n if (event.type === \"item.completed\" && (event.payload as Completion).id === item) {\n completion = event.payload as Completion;\n break;\n }\n }\n return completion && [\"done\", \"needs-review\"].includes(completion.verdict)\n ? completion.produced\n .filter((output) => output.kind === \"experiment-output\")\n .map((output) => output.ref)\n : [];\n}\n","import { fail } from \"../errors.ts\";\nimport type { Budget } from \"../types.ts\";\nexport interface InvestigationConfig {\n question: string;\n maxRounds: number;\n budget: Budget;\n}\nexport function validateInvestigationConfig(raw: unknown): InvestigationConfig {\n const c = raw as InvestigationConfig;\n if (\n !c ||\n typeof c !== \"object\" ||\n Array.isArray(c) ||\n typeof c.question !== \"string\" ||\n !c.question.trim() ||\n !Number.isSafeInteger(c.maxRounds) ||\n c.maxRounds < 1 ||\n !c.budget ||\n typeof c.budget !== \"object\" ||\n Array.isArray(c.budget) ||\n !Object.keys(c.budget).length ||\n Object.entries(c.budget).some(\n ([k, v]) =>\n ![\"tokens\", \"turns\", \"wallclockMs\"].includes(k) ||\n typeof v !== \"number\" ||\n !Number.isFinite(v) ||\n v <= 0,\n )\n )\n fail(\n \"config-invalid\",\n \"investigation requires question, positive maxRounds and a finite positive budget\",\n \"provide bounded investigation config\",\n );\n return { question: c.question, maxRounds: c.maxRounds, budget: { ...c.budget } };\n}\n","import { executionActors, freshOutputRefs } from \"./execution.ts\";\nimport { fail } from \"../errors.ts\";\nimport { roleOf } from \"../roles.ts\";\nimport { addItem, moveItem } from \"../items.ts\";\nimport { applyAction } from \"../methodology.ts\";\nimport { appendEvent, nowOf } from \"../state.ts\";\nimport { isExhausted } from \"../budget.ts\";\nimport type { Capability, Ceremony, CeremonyInput, Methodology, WorkflowState } from \"../types.ts\";\nimport { validateInvestigationConfig, type InvestigationConfig } from \"./config.ts\";\nimport type {\n BeliefUpdate,\n Experiment,\n Hypothesis,\n InvestigationConclusion,\n InvestigationState,\n Observation,\n} from \"./state.ts\";\nfunction reject(s: WorkflowState, name: string, message: string, fix: string): never {\n const x = s.investigation;\n return fail(\"invalid-input\", `${name} (phase ${x?.phase ?? \"intake\"}): ${message}`, fix, {\n items: x ? [x.item, ...(x.rounds.at(-1) ? [x.rounds.at(-1)!.item] : [])] : [],\n });\n}\nconst sameHypothesis = (a: Hypothesis | undefined, b: Hypothesis | undefined) =>\n !!a && !!b && a.id === b.id && a.claim === b.claim && a.falsifiedBy === b.falsifiedBy;\nconst text = (v: unknown): v is string => typeof v === \"string\" && v.trim().length > 0;\nconst refs = (v: unknown): v is string[] =>\n Array.isArray(v) && v.length > 0 && v.every(text) && new Set(v).size === v.length;\n/** First key of a caller record outside its contract; stored records are closed objects (state schema). */\nconst extraKey = (v: unknown, keys: readonly string[]): string | undefined =>\n v && typeof v === \"object\" && !Array.isArray(v)\n ? Object.keys(v).find((k) => !keys.includes(k))\n : undefined;\nconst extraKeyIn = (list: unknown, keys: readonly string[]): string | undefined =>\n Array.isArray(list) ? list.map((v) => extraKey(v, keys)).find(Boolean) : undefined;\nfunction authorize(s: WorkflowState, by: string, cap: Capability) {\n if (!roleOf(s, by)?.capabilities.includes(cap))\n fail(\n \"missing-capability\",\n `${by} needs ${cap}`,\n \"use a registered role with the required capability\",\n );\n}\nfunction save(s: WorkflowState, x: InvestigationState, i: CeremonyInput, name: string) {\n return appendEvent(\n { ...s, investigation: x },\n `investigation.${name}`,\n i.by,\n { ...x },\n nowOf(i.now),\n );\n}\nexport function closeInvestigation(\n s: WorkflowState,\n x: InvestigationState,\n i: CeremonyInput,\n outcome: \"stopped\" | \"resolved\" | \"inconclusive\",\n reason?: string,\n) {\n const at = nowOf(i.now);\n let n = save(\n s,\n { ...x, phase: \"closed\", outcome, ...(reason ? { stopReason: reason } : {}) },\n i,\n outcome,\n );\n n = {\n ...n,\n iterations: n.iterations.map((it) =>\n it.id === \"investigation\"\n ? { ...it, endedAt: at, outcome: outcome === \"stopped\" ? \"cancelled\" : \"completed\" }\n : it,\n ),\n };\n for (const item of Object.values(n.items).filter(\n (candidate) => candidate.id === x.item || x.rounds.some((r) => r.item === candidate.id),\n ))\n if (item.status !== \"done\" && item.status !== \"dropped\")\n n = moveItem(\n n,\n item.id,\n { status: outcome === \"resolved\" && item.id === x.item ? \"done\" : \"dropped\" },\n i.by,\n at,\n );\n return n;\n}\nexport function investigationCeremonies(\n factory: () => Methodology<InvestigationConfig>,\n): Record<string, Ceremony> {\n let built: Methodology<InvestigationConfig> | undefined;\n const methodology = () => (built ??= factory());\n const make =\n (\n name: string,\n cap: Capability,\n phase: string | undefined,\n fn: (\n s: WorkflowState,\n x: InvestigationState,\n i: CeremonyInput,\n bad: (message: string, fix: string) => never,\n ) => WorkflowState,\n ): Ceremony =>\n (s, i) => {\n authorize(s, i.by, cap);\n const x = s.investigation;\n if (!x || x.phase === \"closed\")\n reject(s, name, \"no active investigation\", \"start a new investigation with intake {item}\");\n if (phase && x.phase !== phase && !(name === \"hypotheses\" && x.phase === \"preregister\"))\n reject(\n s,\n name,\n `expected ${phase}, got ${x.phase}`,\n `finish phase ${x.phase} before calling ${name}; ${name} requires phase ${phase}`,\n );\n return applyAction(s, methodology(), { type: `ceremony.${name}`, by: i.by, payload: i }, () =>\n fn(s, x, i, (message, fix) => reject(s, name, message, fix)),\n );\n };\n return {\n intake(s, i) {\n authorize(s, i.by, \"facilitate\");\n const bad = (message: string, fix: string) => reject(s, \"intake\", message, fix);\n if (s.methodology !== \"investigation\")\n bad(\n `workflow methodology is ${s.methodology}, not investigation`,\n \"init a workflow with the investigation methodology before intake\",\n );\n if (s.investigation)\n bad(\n \"investigation already started\",\n \"use the existing investigation or initialize a new workflow\",\n );\n if (!text(i.item))\n bad(\"item is required\", \"set intake.item to a unique investigation item ID\");\n const c = validateInvestigationConfig(s.config);\n return applyAction(\n s,\n methodology(),\n { type: \"ceremony.intake\", by: i.by, payload: i },\n () => {\n let n = addItem(\n s,\n {\n id: i.item as string,\n title: c.question,\n acceptance: [\"Independent evidence-based conclusion\"],\n stage: \"intake\",\n },\n i.by,\n i.now,\n );\n n = {\n ...n,\n iterations: [\n ...n.iterations,\n {\n id: \"investigation\",\n goal: c.question,\n budget: { ...c.budget },\n spent: { tokens: 0, turns: 0, wallclockMs: 0 },\n startedAt: nowOf(i.now),\n committed: [],\n carryover: [],\n },\n ],\n };\n return save(\n n,\n {\n item: i.item as string,\n phase: \"hypotheses\",\n hypotheses: [],\n rounds: [],\n contributors: [i.by],\n },\n i,\n \"intake\",\n );\n },\n );\n },\n hypotheses: make(\"hypotheses\", \"define-acceptance\", \"hypotheses\", (s, x, i, bad) => {\n const h = i.hypotheses as Hypothesis[];\n const extra = extraKeyIn(h, [\"id\", \"claim\", \"falsifiedBy\"]);\n if (extra)\n bad(\n `unknown key \"${extra}\" in a hypotheses entry`,\n \"use only id, claim and falsifiedBy in each hypotheses entry\",\n );\n if (\n !Array.isArray(h) ||\n !h.length ||\n h.some((v) => !v || !text(v.id) || !text(v.claim) || !text(v.falsifiedBy)) ||\n new Set(h.map((v) => v.id)).size !== h.length ||\n (h.length < 2 && !text(i.singleHypothesisRationale))\n )\n bad(\n \"provide competing falsifiable hypotheses or single-testable rationale\",\n \"set hypotheses to unique {id, claim, falsifiedBy} entries; supply singleHypothesisRationale when there is only one\",\n );\n return save(\n s,\n {\n ...x,\n hypotheses: h.map((v) => ({ id: v.id, claim: v.claim, falsifiedBy: v.falsifiedBy })),\n ...(text(i.singleHypothesisRationale)\n ? { singleHypothesisRationale: i.singleHypothesisRationale }\n : {}),\n contributors: [...new Set([...x.contributors, i.by])],\n phase: \"preregister\",\n },\n i,\n \"hypotheses\",\n );\n }),\n preregister: make(\"preregister\", \"define-acceptance\", \"preregister\", (s, x, i, bad) => {\n const c = validateInvestigationConfig(s.config),\n it = s.iterations.find((v) => v.id === \"investigation\");\n if (x.rounds.length >= c.maxRounds || !it || isExhausted(c.budget, it.spent))\n bad(\n `round limit or budget exhausted (${x.rounds.length} of ${c.maxRounds} rounds used)`,\n \"call stop {reason} to close this investigation, or start a new one with a larger maxRounds or budget\",\n );\n const e = i.experiment as Experiment;\n const extraExperiment =\n extraKey(e, [\"id\", \"procedureRef\", \"predictions\", \"replayOf\"]) ??\n extraKeyIn(e?.predictions, [\"hypothesis\", \"prediction\"]);\n if (extraExperiment)\n bad(\n `unknown key \"${extraExperiment}\" in experiment`,\n \"use only id, procedureRef, predictions [{hypothesis, prediction}] and replayOf in experiment\",\n );\n if (\n !e ||\n !text(e.id) ||\n !text(e.procedureRef) ||\n x.rounds.some((r) => r.experiment.id === e.id) ||\n !Array.isArray(e.predictions) ||\n e.predictions.length !== x.hypotheses.length ||\n x.hypotheses.some(\n (h) =>\n e.predictions.filter((p) => p?.hypothesis === h.id && text(p.prediction)).length !== 1,\n ) ||\n new Set(e.predictions.map((p) => p.prediction)).size !== e.predictions.length\n )\n bad(\n \"preregister unique experiment with differing predictions for every hypothesis\",\n \"set experiment.id to a new ID, experiment.procedureRef, and one distinct experiment.predictions entry per hypothesis\",\n );\n if (e.replayOf) {\n const prior = x.rounds.find((r) => r.experiment.id === e.replayOf && r.result?.valid);\n if (\n !prior ||\n prior.experiment.procedureRef !== e.procedureRef ||\n prior.hypotheses.length !== x.hypotheses.length ||\n x.hypotheses.some(\n (h) =>\n !sameHypothesis(\n h,\n prior.hypotheses.find((p) => p.id === h.id),\n ),\n ) ||\n e.predictions.some(\n (p) =>\n !prior.experiment.predictions.some(\n (q) => q.hypothesis === p.hypothesis && q.prediction === p.prediction,\n ),\n )\n )\n bad(\n \"replay must repeat the procedure, predictions and hypotheses of a prior valid experiment\",\n \"set experiment.replayOf to a valid prior experiment with identical procedureRef, predictions and hypothesis definitions\",\n );\n }\n const id = `${x.item}-run-${x.rounds.length + 1}`;\n let n = addItem(\n s,\n {\n id,\n title: `Experiment ${e.id}`,\n stage: \"execute\",\n acceptance: [e.procedureRef],\n iteration: \"investigation\",\n },\n i.by,\n i.now,\n );\n n = {\n ...n,\n iterations: n.iterations.map((iteration) =>\n iteration.id === \"investigation\"\n ? { ...iteration, committed: [...iteration.committed, id] }\n : iteration,\n ),\n };\n return save(\n n,\n {\n ...x,\n phase: \"observe\",\n rounds: [\n ...x.rounds,\n {\n experiment: {\n id: e.id,\n procedureRef: e.procedureRef,\n predictions: e.predictions.map((p) => ({\n hypothesis: p.hypothesis,\n prediction: p.prediction,\n })),\n ...(e.replayOf ? { replayOf: e.replayOf } : {}),\n },\n hypotheses: x.hypotheses.map((v) => ({ ...v })),\n item: id,\n by: i.by,\n },\n ],\n contributors: [...new Set([...x.contributors, i.by])],\n },\n i,\n \"preregister\",\n );\n }),\n observe: make(\"observe\", \"verify\", \"observe\", (s, x, i, bad) => {\n const r = x.rounds.at(-1)!,\n o = i.result as Observation;\n const extra = extraKey(o, [\"id\", \"valid\", \"summary\", \"provenanceRefs\"]);\n if (extra)\n bad(\n `unknown key \"${extra}\" in result`,\n \"use only id, valid, summary and provenanceRefs in result\",\n );\n if (\n i.experiment !== r.experiment.id ||\n !o ||\n !text(o.id) ||\n typeof o.valid !== \"boolean\" ||\n !text(o.summary) ||\n !refs(o.provenanceRefs) ||\n x.rounds.some((prior) => prior.result?.id === o.id)\n )\n bad(\n \"observation needs current experiment, unique result and provenance\",\n \"set experiment to the active experiment ID and result to {id, valid, summary, provenanceRefs} with a new result.id\",\n );\n if (s.items[r.item]?.status !== \"done\")\n bad(\n \"complete experiment execution before recording observations\",\n \"dispatch and complete the active experiment item before calling observe\",\n );\n if (!freshOutputRefs(s, r.item).some((ref) => o.provenanceRefs.includes(ref)))\n bad(\n \"observation must link fresh experiment-output evidence from the latest completion\",\n `include an experiment-output ref produced by the latest successful completion of item \"${r.item}\" in result.provenanceRefs`,\n );\n return save(\n s,\n {\n ...x,\n phase: \"update-belief\",\n rounds: x.rounds.map((v) =>\n v === r\n ? {\n ...v,\n result: {\n id: o.id,\n valid: o.valid,\n summary: o.summary,\n provenanceRefs: [...o.provenanceRefs],\n },\n }\n : v,\n ),\n contributors: [...new Set([...x.contributors, i.by, ...executionActors(s, r.item)])],\n },\n i,\n \"observe\",\n );\n }),\n \"update-belief\": make(\"update-belief\", \"define-acceptance\", \"update-belief\", (s, x, i, bad) => {\n const r = x.rounds.at(-1)!,\n a = i.assessments as BeliefUpdate[\"assessments\"];\n const extra = extraKeyIn(a, [\"hypothesis\", \"assessment\", \"reason\"]);\n if (extra)\n bad(\n `unknown key \"${extra}\" in an assessments entry`,\n \"use only hypothesis, assessment and reason in each assessments entry\",\n );\n if (\n i.result !== r.result?.id ||\n !Array.isArray(a) ||\n a.length !== x.hypotheses.length ||\n x.hypotheses.some(\n (h) =>\n a.filter(\n (v) =>\n v?.hypothesis === h.id &&\n [\"supported\", \"refuted\", \"uncertain\"].includes(v.assessment) &&\n text(v.reason),\n ).length !== 1,\n ) ||\n ![\"round\", \"conclusion\"].includes(i.next as string)\n )\n bad(\n \"belief update must assess every hypothesis against current result\",\n \"set result to the latest result ID, assessments to one {hypothesis, assessment, reason} per hypothesis, and next to round or conclusion\",\n );\n if (!r.result!.valid && a.some((v) => v.assessment !== \"uncertain\"))\n bad(\n \"invalid experiments cannot support beliefs\",\n \"set every assessment to uncertain for an invalid experiment result\",\n );\n let n = save(\n s,\n {\n ...x,\n phase: i.next === \"round\" ? \"preregister\" : \"conclusion\",\n rounds: x.rounds.map((v) =>\n v === r\n ? {\n ...v,\n update: {\n result: i.result as string,\n assessments: a.map((entry) => ({\n hypothesis: entry.hypothesis,\n assessment: entry.assessment,\n reason: entry.reason,\n })),\n },\n }\n : v,\n ),\n contributors: [...new Set([...x.contributors, i.by])],\n },\n i,\n \"belief-updated\",\n );\n const it = n.iterations.find((v) => v.id === \"investigation\")!;\n if (\n i.next === \"round\" &&\n (x.rounds.length >= validateInvestigationConfig(s.config).maxRounds ||\n isExhausted(it.budget, it.spent))\n )\n n = closeInvestigation(\n n,\n n.investigation!,\n i,\n \"stopped\",\n \"budget or round limit exhausted\",\n );\n return n;\n }),\n conclude: make(\"conclude\", \"define-acceptance\", \"conclusion\", (s, x, i, bad) => {\n const c = i as unknown as InvestigationConclusion;\n if (\n ![\"resolved\", \"inconclusive\"].includes(c.outcome) ||\n !text(c.summary) ||\n !refs(c.evidenceRefs) ||\n c.evidenceRefs.some((ref) => !x.rounds.some((r) => r.result?.provenanceRefs.includes(ref)))\n )\n bad(\n \"conclusion needs observed evidence references\",\n \"set outcome, summary and evidenceRefs to references preserved in recorded observations\",\n );\n if (\n c.outcome === \"resolved\" &&\n (!text(c.supportedHypothesis) ||\n !x.rounds\n .slice(-1)\n .some(\n (r) =>\n r.result?.valid &&\n r.update?.assessments.some(\n (a) => a.hypothesis === c.supportedHypothesis && a.assessment === \"supported\",\n ),\n ))\n )\n bad(\n \"resolved conclusion needs a supported hypothesis\",\n \"set supportedHypothesis to a hypothesis supported by the latest valid round, or choose outcome inconclusive\",\n );\n return save(\n s,\n {\n ...x,\n phase: \"review\",\n conclusion: {\n outcome: c.outcome,\n summary: c.summary,\n evidenceRefs: [...c.evidenceRefs],\n ...(c.supportedHypothesis ? { supportedHypothesis: c.supportedHypothesis } : {}),\n by: i.by,\n },\n contributors: [...new Set([...x.contributors, i.by])],\n },\n i,\n \"conclusion\",\n );\n }),\n \"review-conclusion\": make(\"review-conclusion\", \"review\", \"review\", (s, x, i, bad) => {\n if (x.contributors.includes(i.by))\n bad(\n \"conclusion reviewer must be independent of investigation contributors\",\n \"use a review-capable role that did not contribute to or execute this investigation\",\n );\n if (typeof i.approve !== \"boolean\" || !text(i.reason))\n bad(\n \"review needs approval and reason\",\n \"set approve to a boolean and reason to a nonempty review explanation\",\n );\n if (!i.approve) {\n const target = i.next ?? \"conclusion\";\n if (target !== \"round\" && target !== \"conclusion\")\n bad(\n \"review rejection next must be round or conclusion\",\n \"set next to round for more evidence or conclusion for a revised conclusion\",\n );\n const n = save(\n s,\n {\n ...x,\n phase: target === \"round\" ? \"preregister\" : \"conclusion\",\n reviewHistory: [\n ...(x.reviewHistory ?? []),\n {\n by: i.by,\n reason: i.reason as string,\n approve: false,\n next: target as \"round\" | \"conclusion\",\n replayRefs: [],\n },\n ],\n },\n i,\n \"review-rejected\",\n );\n const iteration = s.iterations.find((it) => it.id === \"investigation\")!;\n if (\n target === \"round\" &&\n (x.rounds.length >= validateInvestigationConfig(s.config).maxRounds ||\n isExhausted(iteration.budget, iteration.spent))\n )\n return closeInvestigation(\n n,\n n.investigation!,\n i,\n \"stopped\",\n \"budget or round limit exhausted after review requested another round\",\n );\n return n;\n }\n const replayRefs = Array.isArray(i.replayRefs) ? i.replayRefs : [];\n if (\n x.conclusion!.outcome === \"resolved\" &&\n (!refs(replayRefs) ||\n !x.rounds.some(\n (r) =>\n r.experiment.replayOf &&\n !executionActors(s, r.item).some((actor) =>\n executionActors(\n s,\n x.rounds.find((p) => p.experiment.id === r.experiment.replayOf)!.item,\n ).includes(actor),\n ) &&\n sameHypothesis(\n r.hypotheses.find((h) => h.id === x.conclusion!.supportedHypothesis),\n x.rounds.at(-1)!.hypotheses.find((h) => h.id === x.conclusion!.supportedHypothesis),\n ) &&\n r.result?.valid &&\n replayRefs.includes(r.result.id) &&\n r.update?.assessments.some(\n (a) =>\n a.hypothesis === x.conclusion!.supportedHypothesis &&\n a.assessment === \"supported\",\n ),\n ))\n )\n bad(\n \"resolved conclusion requires valid replay result and supporting belief update\",\n \"set replayRefs to a valid independent replay result supporting the latest supported hypothesis definition, or reject with next round\",\n );\n return closeInvestigation(\n s,\n {\n ...x,\n review: { by: i.by, reason: i.reason as string, replayRefs: replayRefs as string[] },\n reviewHistory: [\n ...(x.reviewHistory ?? []),\n {\n by: i.by,\n reason: i.reason as string,\n approve: true,\n replayRefs: replayRefs as string[],\n },\n ],\n },\n i,\n x.conclusion!.outcome,\n );\n }),\n stop: make(\"stop\", \"facilitate\", undefined, (s, x, i, bad) => {\n if (!text(i.reason))\n bad(\n \"stop needs reason\",\n \"set reason to a nonempty explanation for stopping this investigation\",\n );\n return closeInvestigation(s, x, i, \"stopped\", i.reason as string);\n }),\n };\n}\n","import { executionActors } from \"./execution.ts\";\nimport type { Rule } from \"../types.ts\";\nexport function investigationRules(): Rule[] {\n return [\n {\n id: \"independent-replay\",\n severity: \"error\",\n check(s, a) {\n if (a.type !== \"item.complete\") return [];\n const round = s.investigation?.rounds.find(\n (r) => r.item === (a.payload as { item?: string })?.item,\n );\n const prior = s.investigation?.rounds.find(\n (r) => r.experiment.id === round?.experiment.replayOf,\n );\n return prior && executionActors(s, prior.item).includes(a.by)\n ? [\n {\n rule: \"independent-replay\",\n item: round!.item,\n severity: \"error\",\n message: \"Replay executor also executed the original experiment\",\n fix: \"assign a different deliver-capable role\",\n },\n ]\n : [];\n },\n },\n {\n id: \"investigation-execution-only\",\n severity: \"error\",\n check(s, a) {\n if (a.type !== \"item.complete\") return [];\n const p = a.payload as { item: string };\n const x = s.investigation;\n return x?.phase === \"observe\" && x.rounds.at(-1)?.item === p.item\n ? []\n : [\n {\n rule: \"investigation-execution-only\",\n item: p.item,\n severity: \"error\",\n message: \"Only the active preregistered experiment can complete\",\n fix: `complete only the active experiment item in phase observe; current phase is ${x?.phase ?? \"intake\"}`,\n },\n ];\n },\n },\n ];\n}\n","import type { Role } from \"../types.ts\";\nexport function investigationRoles(): Role[] {\n return [\n {\n id: \"replay-worker\",\n name: \"Independent replay worker\",\n modelTier: \"small\",\n capabilities: [\"deliver\", \"verify\"],\n canApprove: [],\n inputs: [\"preregistered-experiment\"],\n outputs: [\"experiment-output\"],\n do_not: [\"Do not change the replay procedure\"],\n },\n {\n id: \"investigator\",\n name: \"Investigator\",\n modelTier: \"large\",\n capabilities: [\"facilitate\", \"define-acceptance\", \"deliver\", \"verify\"],\n canApprove: [],\n inputs: [\"question\", \"prior-results\"],\n outputs: [\"hypotheses\", \"preregistered-experiment\", \"belief-update\"],\n do_not: [\"Do not revise predictions after execution\", \"Do not approve your own conclusions\"],\n },\n {\n id: \"conclusion-reviewer\",\n name: \"Independent conclusion reviewer\",\n modelTier: \"large\",\n capabilities: [\"review\"],\n canApprove: [\"investigation-conclusion\"],\n inputs: [\"evidence\", \"replay\", \"conclusion\"],\n outputs: [\"conclusion-review\"],\n do_not: [\"Do not approve unsupported conclusions\"],\n },\n ];\n}\n","import type { Stage } from \"../types.ts\";\nexport function investigationStages(): Stage[] {\n return [\n {\n id: \"intake\",\n name: \"Intake\",\n entryPolicy: [],\n exitPolicy: [{ kind: \"acceptance-written\" }],\n },\n {\n id: \"execute\",\n name: \"Execute preregistered experiment\",\n entryPolicy: [{ kind: \"acceptance-written\" }, { kind: \"no-open-blockers\" }],\n exitPolicy: [{ kind: \"evidence\", evidenceKind: \"experiment-output\" }],\n },\n { id: \"observed\", name: \"Execution recorded\", entryPolicy: [], exitPolicy: [] },\n ];\n}\n","import { fail } from \"../errors.ts\";\nimport { executionActors } from \"./execution.ts\";\nimport { closeInvestigation, investigationCeremonies } from \"./ceremonies.ts\";\nimport { investigationRules } from \"./rules.ts\";\nimport { investigationRoles } from \"./roles.ts\";\nimport { investigationStages } from \"./stages.ts\";\nimport { isExhausted } from \"../budget.ts\";\nimport type { Methodology } from \"../types.ts\";\nimport { validateInvestigationConfig, type InvestigationConfig } from \"./config.ts\";\nexport { validateInvestigationConfig };\nexport type { InvestigationConfig };\nexport type * from \"./state.ts\";\nexport function investigation(): Methodology<InvestigationConfig> {\n return {\n name: \"investigation\",\n validateConfig: validateInvestigationConfig,\n lockedConfigKeys: [\"question\", \"maxRounds\", \"budget\"],\n vocabulary: {\n backlog: \"Questions\",\n item: \"Investigation artifact\",\n stage: \"Investigation phase\",\n iteration: \"Investigation budget\",\n increment: \"Conclusion\",\n ceremony: \"Investigation ceremony\",\n gate: \"Independent conclusion review\",\n },\n defaultStages: investigationStages,\n defaultRoles: investigationRoles,\n requiredCapabilities: [\"facilitate\", \"define-acceptance\", \"deliver\", \"verify\", \"review\"],\n exclusiveCapabilities: [],\n humanDefaults: { gates: \"none\" },\n ceremonies: investigationCeremonies(investigation),\n plannerOptions: (state) => ({\n schedulerMode: \"level\",\n concurrencyCap: 1,\n roleFor: (item) => {\n const r = state.investigation?.rounds.find((candidate) => candidate.item === item.id);\n const prior = state.investigation?.rounds.find(\n (p) => p.experiment.id === r?.experiment.replayOf,\n );\n const excluded = prior ? executionActors(state, prior.item) : [];\n const roles = Object.values(state.roles);\n const selected =\n (!prior\n ? roles.find(\n (role) =>\n role.capabilities.includes(\"deliver\") &&\n role.capabilities.includes(\"define-acceptance\"),\n )\n : undefined) ??\n roles.find(\n (role) => role.capabilities.includes(\"deliver\") && !excluded.includes(role.id),\n );\n if (!selected)\n fail(\n \"missing-capability\",\n `No eligible executor for experiment item \"${item.id}\"`,\n prior\n ? `register an independent deliver-capable role that did not execute \"${prior.item}\"`\n : \"register a role with deliver capability\",\n { items: [item.id] },\n );\n return selected.id;\n },\n estimateMode: \"per-call\",\n fallbackTokensPerWeight: 1,\n }),\n candidates: (s) =>\n s.investigation?.phase === \"observe\" &&\n !isExhausted(\n (s.config as InvestigationConfig).budget,\n s.iterations.find((it) => it.id === \"investigation\")!.spent,\n )\n ? Object.values(s.items).filter(\n (i) =>\n i.id === s.investigation!.rounds.at(-1)?.item &&\n i.stage === \"execute\" &&\n i.status === \"todo\",\n )\n : [],\n afterComplete: (state, item, now) => {\n const x = state.investigation;\n const iteration = state.iterations.find((it) => it.id === \"investigation\");\n if (\n x?.phase !== \"observe\" ||\n x.rounds.at(-1)?.item !== item ||\n state.items[item]?.status === \"done\" ||\n !iteration ||\n !isExhausted(iteration.budget, iteration.spent)\n )\n return state;\n return closeInvestigation(\n state,\n x,\n { by: \"investigation\", now },\n \"stopped\",\n `budget exhausted before experiment item \"${item}\" completed; start a new investigation with sufficient budget`,\n );\n },\n invariants: (s) => [\n `Question: ${(s.config as InvestigationConfig).question}`,\n \"Execute only the preregistered procedure; retain raw observation provenance; report invalid runs.\",\n ],\n rules: investigationRules(),\n metrics: (s) => ({\n rounds: s.investigation?.rounds.length ?? 0,\n validRuns: s.investigation?.rounds.filter((r) => r.result?.valid).length ?? 0,\n invalidRuns: s.investigation?.rounds.filter((r) => r.result && !r.result.valid).length ?? 0,\n }),\n report: (s) => ({\n phase: s.investigation?.phase ?? \"intake\",\n outcome: s.investigation?.outcome ?? null,\n rounds: s.investigation?.rounds.length ?? 0,\n conclusion: s.investigation?.conclusion ?? null,\n stopReason: s.investigation?.stopReason ?? null,\n }),\n };\n}\n"]}
@@ -1,2 +0,0 @@
1
- import {a as a$1,b as b$2}from'./chunk-FTS75UIU.mjs';import {c,u,x,o,n,i,j as j$1,G as G$1,P as P$1,L as L$1,W,a,I,K as K$1}from'./chunk-6P3OKXSK.mjs';import {b as b$1,c as c$1}from'./chunk-2FRRD6A3.mjs';import {timSort}from'exsorted';var De=["requirements","design","implementation","verification","deployment","maintenance"],pe={requirements:["srs"],design:["design-doc","interface-spec"],implementation:["code-baseline"],verification:["test-report","traceability-matrix"],deployment:["release-notes","deployment-record"],maintenance:["change-log"]},fe={requirements:"business-analyst",design:"architect",deployment:"release-manager"},ue=e=>`${e}-gate`,me="change-control",je=["order-backlog","define-acceptance","facilitate","deliver","review","verify","approve-gate","manage-flow","control-change","escalate"],Be=e=>e.charAt(0).toUpperCase()+e.slice(1);function Me(){return De.map(e=>{let t={id:e,name:Be(e),deliverables:[...pe[e]??[]],gate:{id:ue(e),requires:[{capability:"approve-gate"}],evidence:[],onFail:{action:"block"}}},n=fe[e];return n!==void 0&&(t.deliverBy=n),t})}function w(e){return e.config}var G=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),re=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.trim()!=="");function Ye(e,t){if(e===void 0)return;G(e)||b$1("config-invalid",`${t}.budget must be an object`,'e.g. { "tokens": 400000 }');let n={};for(let a of ["tokens","turns","wallclockMs"]){let p=e[a];p!==void 0&&((typeof p!="number"||!Number.isFinite(p)||p<0)&&b$1("config-invalid",`${t}.budget.${a} must be a non-negative number`,"omit it for no limit"),n[a]=p);}return n}function Ge(e,t){return (!Array.isArray(e)||e.length===0)&&b$1("config-invalid",`${t} must be a non-empty array of "human" | { capability }`,'e.g. ["human", { "capability": "approve-gate" }]'),e.map(n=>n==="human"?"human":G(n)&&typeof n.capability=="string"&&je.includes(n.capability)?{capability:n.capability}:b$1("config-invalid",`${t} entry ${JSON.stringify(n)} is not "human" or a known capability`,`use "human" or { "capability": one of ${je.join(", ")} }`))}function Ee(e,t,n){let a=`waterfall config.phases[${t}]`;G(e)||b$1("config-invalid",`${a} must be an object`,'e.g. { "id": "design" }'),c$1(e.id,`${a}.id`);let p=e.id,c=e.deliverables??pe[p]??[];re(c)||b$1("config-invalid",`${a}.deliverables must be a string[] of evidence kinds`,'e.g. ["srs"]');let o;if(e.gate===void 0)o={id:ue(p),requires:[{capability:"approve-gate"}],evidence:[],onFail:{action:"block"}};else {let l=e.gate;(!G(l)||typeof l.id!="string"||l.id.trim()==="")&&b$1("config-invalid",`${a}.gate must be a Gate with an id`,'e.g. { "id": "design-gate", "requires": [{ "capability": "approve-gate" }], "evidence": [] }');let f=l.evidence??[];re(f)||b$1("config-invalid",`${a}.gate.evidence must be a string[]`,"list evidence kinds or omit it"),o={id:l.id,requires:Ge(l.requires??[{capability:"approve-gate"}],`${a}.gate.requires`),evidence:[...f],onFail:{action:"block"}};}n(p)&&!o.requires.includes("human")&&(o.requires=["human",...o.requires]);let d={id:p,name:typeof e.name=="string"&&e.name.trim()!==""?e.name:Be(p),deliverables:[...c],gate:o},i=Ye(e.budget,a);i!==void 0&&(d.budget=i);let s=e.deliverBy??fe[p];return s!==void 0&&((typeof s!="string"||s.trim()==="")&&b$1("config-invalid",`${a}.deliverBy must be a role id`,"name the role that delivers this phase or omit it"),d.deliverBy=s),d}function ge(e){let t=e??{};t.phases!==void 0&&!Array.isArray(t.phases)&&b$1("config-invalid","waterfall config.phases must be an array of phases","omit phases for the six classic phases");let n=t.humanGates??"all";n!=="all"&&!re(n)&&b$1("config-invalid",'waterfall config.humanGates must be "all" or a string[] of phase ids','omit it for "all"');let a=n==="all"?()=>true:r=>n.includes(r),p=t.phases===void 0?Me().map((r,m)=>Ee(r,m,a)):t.phases.map((r,m)=>Ee(r,m,a));p.length===0&&b$1("config-invalid","waterfall config.phases needs at least one phase",'e.g. [{ "id": "requirements" }]');let c=p.map(r=>r.id),o=c.find((r,m)=>c.indexOf(r)!==m);if(o!==void 0&&b$1("config-invalid",`duplicate phase id "${o}"`,"give every phase a unique id"),n!=="all")for(let r of n)c.includes(r)||b$1("config-invalid",`waterfall config.humanGates names unknown phase "${r}"`,`phases are: ${c.join(", ")}`);let d=t.changeControl??{};G(d)||b$1("config-invalid","waterfall config.changeControl must be an object",'e.g. { "requiresImpactAnalysis": true, "approvers": ["human"] }'),d.requiresImpactAnalysis!==void 0&&typeof d.requiresImpactAnalysis!="boolean"&&b$1("config-invalid","waterfall config.changeControl.requiresImpactAnalysis must be a boolean","omit it for true");let i={requiresImpactAnalysis:d.requiresImpactAnalysis===void 0?true:d.requiresImpactAnalysis,approvers:Ge(d.approvers??["human",{capability:"control-change"}],"waterfall config.changeControl.approvers")},s=t.traceability,l;if(s===void 0)l=c.includes("requirements")&&c.includes("design")&&c.includes("verification")?{from:"requirements",to:["design","verification"]}:{from:c[0],to:[]};else {(!G(s)||typeof s.from!="string"||!c.includes(s.from))&&b$1("config-invalid","waterfall config.traceability.from must be a phase id",`phases are: ${c.join(", ")}`);let r=s.to??[];re(r)||b$1("config-invalid","waterfall config.traceability.to must be a string[] of phase ids",`phases are: ${c.join(", ")}`);for(let m of r)c.includes(m)||b$1("config-invalid",`waterfall config.traceability.to names unknown phase "${m}"`,`phases are: ${c.join(", ")}`),c.indexOf(m)<=c.indexOf(s.from)&&b$1("config-invalid",`waterfall config.traceability.to phase "${m}" must come after "${s.from}"`,"trace forward only: from an earlier phase to later ones");l={from:s.from,to:[...r]};}let f=t.fallbackTokensPerWeight;f!==void 0&&(typeof f!="number"||!Number.isFinite(f)||f<=0)&&b$1("config-invalid","waterfall config.fallbackTokensPerWeight must be a positive finite number","omit it for the default 20000");let u={phases:p,changeControl:i,traceability:l,humanGates:n==="all"?"all":[...n]};return f!==void 0&&(u.fallbackTokensPerWeight=f),u}var L="work",V="review",H="done";function b(e){return e.phases?e.phases:w(e).phases.map(t=>{let n={id:t.id,name:t.name,deliverables:[...t.deliverables],gate:t.gate,status:"pending"};return t.budget&&(n.budget=t.budget),n})}function j(e,t){return {...e,phases:t}}function E(e,t){let n=b(e).findIndex(a=>a.id===t);return n<0&&b$1("config-invalid",`unknown phase "${t}"`,`phases are: ${b(e).map(a=>a.id).join(" \u2192 ")}`),n}function _(e,t){return b(e)[E(e,t)]}function q(e,t){let n=new Set,a=t;for(;a&&!n.has(a.id);){if(a.phase!==void 0)return a.phase;n.add(a.id),a=a.parent!==void 0&&Object.hasOwn(e.items,a.parent)?e.items[a.parent]:void 0;}}function P(e,t){return Object.values(e.items).filter(n=>n.status!=="dropped"&&q(e,n)===t)}function D(e){return b(e).find(t=>t.status==="open")}function he(e){return b(e).find(t=>t.status!=="baselined")}function Je(e,t){let n=q(e,t);return n!==void 0&&b(e).find(a=>a.id===n)?.status==="baselined"}function _e(e,t){let n=new Set((t.produced??[]).map(a=>a.kind));for(let a of P(e,t.id))for(let p of a.evidence)n.add(p.kind);return n}function U(e,t,n=[]){let a=_e(e,t);for(let c of n)a.add(c);let p=[];for(let c of [...t.deliverables,...t.gate.evidence])p.includes(c)||p.push(c);return p.filter(c=>!a.has(c))}function B(e){let t=b(e).map(a=>a.id),n=w(e).traceability.to.filter(a=>t.includes(a));if(n.length!==0)return n.reduce((a,p)=>t.indexOf(a)>=t.indexOf(p)?a:p)}function Fe(e,t,n,a){let p=P$1(e);return !p||!p.id.startsWith(`${t}#`)?e:{...e,iterations:e.iterations.map(c=>c.id===p.id?{...c,endedAt:a,outcome:n}:c)}}function ae(e,t,n,a){let p=_(e,t);p.status!=="open"&&b$1("invalid-transition",`phase "${t}" is ${p.status}, not open`,p.status==="baselined"?"it is already baselined; a change-request reopens it":"kickoff the phase first");let c$1=P(e,t),o={};for(let l of c$1)o[l.id]=l;let d=(e.baselines??[]).filter(l=>l.phase===t).length,i={phase:t,version:d+1,at:a,approvedBy:n,itemSnapshot:o},s=j(e,b(e).map(l=>l.id===t?{...l,status:"baselined"}:l));return s={...s,baseline:i,baselines:[...s.baselines??[],i]},s=Fe(s,t,"completed",a),c(s,"phase.baselined",n[n.length-1]??"system",{phase:t,version:i.version,approvedBy:n,items:c$1.map(l=>l.id)},a)}function ye(e,t,n){let a=[];for(let d of t){let i=_(e,d);i.status==="pending"&&b$1("invalid-input",`phase "${d}" was never baselined; there is nothing to reopen`,"remove it from impactAnalysis.reopen"),i.status==="baselined"&&!a.includes(d)&&a.push(d);}let p=b(e).map(d=>a.includes(d.id)?{...d,status:"reopened"}:d),c=null,o=e;if(a.length){let d=Math.min(...a.map(s=>E(e,s))),i=p.find((s,l)=>s.status==="open"&&l>d);i&&(c=i.id,p=p.map(s=>s.id===i.id?{...s,status:"reopened"}:s),o=Fe(o,i.id,"cancelled",n));}return {state:j(o,p),reopened:a,suspended:c}}function z(e,t,n,a,p){let c$1=u(e,t),o=c$1.impactAnalysis,d=ye(e,o?.reopen??[],p),i=x(d.state,t,{stage:H,status:"done"},n,p);for(let s of d.reopened)i=c(i,"phase.reopened",n,{phase:s,change:t},p);return d.suspended!==null&&(i=c(i,"phase.suspended",n,{phase:d.suspended,change:t},p)),c(i,"change.decided",n,{change:t,decision:"approve",by:n,note:a,reopened:d.reopened,suspended:d.suspended,weight:o?.weight??0,affects:c$1.affects??[]},p)}function K(e,t,n,a,p){let c$1=u(e,t),o=x(e,t,{status:"dropped"},n,p);return c(o,"change.decided",n,{change:t,decision:"reject",by:n,note:a,reopened:[],suspended:null,weight:0,affects:c$1.affects??[]},p)}function Ne(e){return (t,n)=>{o(t,n.by,"facilitate");let a$2=n.phase===void 0?void 0:Y(t,n,"phaseRetrospective"),p=a$1(t,n,"phaseRetrospective");return W(t,e(),{type:"ceremony.phaseRetrospective",by:n.by,payload:n},c$1=>{let o=c$1,d=a(n.now),i=b$2(o,p,n.by,d);return o=i.state,c(o,"phase.retrospective",n.by,{phase:a$2?.id??null,lessons:i.created,adopted:i.adopted.slice(i.created.length),dismissed:i.dismissed,agreements:i.agreements,retired:i.retired},d)})}}var Ze=(e,t)=>e.id<t.id?-1:e.id>t.id?1:0,Le=(e,t)=>timSort(P(e,t).filter(n=>n.type!=="question"&&n.type!=="change-request"),Ze),Xe=(e,t)=>(e.traces??[]).includes(t.id)||(t.traces??[]).includes(e.id);function O(e){let t=w(e).traceability,n=b(e).map(o=>o.id),a=t.to.filter(o=>n.includes(o)),p=Le(e,t.from).map(o=>{let d={};for(let i of a)d[i]=Le(e,i).filter(s=>Xe(o,s)).map(s=>s.id);return {item:o.id,links:d}}),c=p.map(o=>({item:o.item,phases:a.filter(d=>o.links[d].length===0)})).filter(o=>o.phases.length>0);return {from:t.from,to:a,rows:p,missing:c,coverage:{traced:p.length-c.length,total:p.length}}}function J(e,t){return O(e).rows.filter(n=>(n.links[t]??[]).length===0).map(n=>n.item)}var et=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Y(e,t,n){let a=t.phase;return (typeof a!="string"||a.trim()==="")&&b$1("invalid-input",`${n} needs phase: string`,`pass one of: ${b(e).map(p=>p.id).join(", ")}`),_(e,a)}function Ve(e,t,n,a,p,c$1){let o=j(e,b(e).map(d=>d.id===t?{...d,produced:[...d.produced??[],{kind:n,ref:a,by:p,at:c$1}]}:d));return c(o,"phase.deliverable",p,{phase:t,kind:n,ref:a},c$1)}function be(e){let t=(c,o,d,i)=>W(c,e(),{type:o,by:d.by,payload:d},s=>i(s,a(d.now)));return {kickoff:(c$1,o$1)=>{o(c$1,o$1.by,"facilitate");let d=Y(c$1,o$1,"kickoff");return t(c$1,"ceremony.kickoff",o$1,(i,s)=>{let l=i.events.filter(r=>r.type==="phase.opened"&&r.payload.phase===d.id).length+1,f=P(i,d.id).filter(r=>r.status!=="done").map(r=>r.id);i=j(i,b(i).map(r=>r.id===d.id?{...r,status:"open"}:r));let u=d.budget??{};return i={...i,iterations:[...i.iterations,{id:`${d.id}#${l}`,goal:d.name,budget:u,spent:K$1,startedAt:s,committed:f,carryover:[]}]},c(i,"phase.opened",o$1.by,{phase:d.id,version:l,items:f,budget:u},s)})},gateReview:(c$1,o)=>{let d=Y(c$1,o,"gateReview");d.status!=="open"&&b$1("invalid-transition",`phase "${d.id}" is ${d.status}, not open`,d.status==="baselined"?"it is already baselined; a change-request reopens it":`kickoff "${d.id}" first`);let i=d.gate,s=j$1(c$1,i.id,"approve-gate");o.by!=="human"&&!s.includes(o.by)&&b$1("gate-unmet",`"${o.by}" may not review gate "${i.id}"`,`review as one of: human${s.map(r=>`, ${r}`).join("")}`,{rule:"gate"});let l=c$1.pending.find(r=>r.kind==="gate"&&r.item===void 0&&r.gate===i.id);l&&b$1("no-op",`gate "${i.id}" is already awaiting a decision (${l.id})`,`decide ${l.id} approve|reject`);let f=o.deliverables??[];(!Array.isArray(f)||!f.every(r=>et(r)&&typeof r.kind=="string"&&r.kind.trim()!==""&&typeof r.ref=="string"))&&b$1("invalid-input","gateReview.deliverables must be [{ kind, ref }]",'e.g. { "deliverables": [{ "kind": "srs", "ref": "docs/srs.md" }] }');let u=f;return t(c$1,"ceremony.gateReview",o,(r,m)=>{for(let h of u)r=Ve(r,d.id,h.kind,h.ref,o.by,m);if(w(r).traceability.to.includes(d.id)){let h=O(r);r=c(r,"traceability.computed",o.by,{phase:d.id,from:h.from,to:h.to,coverage:h.coverage,missing:h.missing,rows:h.rows},m),d.id===B(r)&&h.missing.length===0&&(r=Ve(r,d.id,"traceability-matrix",`traceability.computed#${r.events[r.events.length-1].seq}`,o.by,m));}if(i.requires.includes("human")&&o.by!=="human"){r=I(r,{kind:"gate",gate:i.id,question:`Approve gate "${i.id}" and baseline phase "${d.name}"?`},m);let h=r.pending[r.pending.length-1].id;return c(r,"phase.gate-pending",o.by,{phase:d.id,gate:i.id,by:o.by,pending:h},m)}return ae(r,d.id,[o.by],m)})},changeControlBoard:(c$1,o$1)=>{o(c$1,o$1.by,"control-change");let d=o$1.change;(typeof d!="string"||d.trim()==="")&&b$1("invalid-input","changeControlBoard needs change: string (a change-request id)",'e.g. { "change": "CR-1", "decision": "approve", "note": "why" }');let i$1=u(c$1,d);if(i$1.type!=="change-request"&&b$1("invalid-input",`item "${d}" is a ${i$1.type}, not a change-request`,"only change-request items go through the board",{items:[d]}),(i$1.status==="done"||i$1.status==="dropped")&&b$1("invalid-transition",`change "${d}" is already ${i$1.status==="done"?"approved":"rejected"}`,"raise a new change-request",{items:[d]}),i$1.status==="awaiting_human"){let r=c$1.pending.find(m=>m.item===d);b$1("no-op",`change "${d}" is awaiting the human decision${r?` (${r.id})`:""}`,`decide ${r?.id??"<pending id>"} approve|reject`,{items:[d]});}let s=o$1.decision;s!=="approve"&&s!=="reject"&&b$1("invalid-input",'changeControlBoard.decision must be "approve" or "reject"',"state the board's decision");let l=typeof o$1.note=="string"?o$1.note:"",f=w(c$1).changeControl.approvers;for(let r of f)r==="human"||o$1.by==="human"||n(c$1,o$1.by,r.capability)||b$1("gate-unmet",`"${o$1.by}" lacks capability "${r.capability}" required by change control`,`decide as one of: human${i(c$1,r.capability).map(m=>`, ${m.id}`).join("")}`,{rule:"change-control",items:[d]});let u$1=f.includes("human")&&o$1.by!=="human";return t(c$1,"ceremony.changeControlBoard",o$1,(r,m)=>{if(u$1){r=I(r,{kind:"decision",item:d,question:`Change "${d}" (${i$1.title}): the board (${o$1.by}) recommends ${s}${l?`: ${l}`:""}. Approve or reject the change?`},m);let h=r.pending[r.pending.length-1].id;return c(r,"change.recommended",o$1.by,{change:d,decision:s,note:l,pending:h},m)}return s==="approve"?z(r,d,o$1.by,l,m):K(r,d,o$1.by,l,m)})},phaseRetrospective:Ne(e)}}function ve(e,t,n,a,p,c$1){if(t.kind==="gate"&&t.item===void 0&&t.gate!==void 0){let o=b(e).find(s=>s.gate.id===t.gate);if(!o)return e;a!=="human"&&b$1("gate-unmet",`"${a}" may not decide phase gate "${t.gate}" (${t.id}); it awaits a human`,`decide ${t.id} as human`,{rule:"gate"});let d;for(let s=e.events.length-1;s>=0;s--){let l=e.events[s];if(l.type==="phase.gate-pending"&&l.payload.pending===t.id){d=l.by;break}}let i=d!==void 0&&d!==a?[d,a]:[a];return n==="approve"?ae(e,o.id,i,c$1):c(e,"phase.gate-failed",a,{phase:o.id,gate:t.gate,note:p},c$1)}if(t.kind==="decision"&&t.item!==void 0&&Object.hasOwn(e.items,t.item)){let o=e.items[t.item];return o.type!=="change-request"?e:(a!=="human"&&b$1("gate-unmet",`"${a}" may not decide change "${o.id}" (${t.id}); change control awaits a human`,`decide ${t.id} as human`,{rule:"change-control",items:[o.id]}),n==="approve"?z(e,o.id,a,p,c$1):K(e,o.id,a,p,c$1))}return e}function ke(e){let t=w(e).phases.map($=>$.id),n=()=>Object.fromEntries(t.map($=>[$,0])),a=n(),p=n(),c=n(),o=n(),d=n(),i=new Map,s=new Map,l=new Map,f=0,u=0,r=0,m=0,h=0,v=$=>{let W=s.get($),y=i.get($);return W!=="question"&&W!=="change-request"&&y!==void 0&&y in a};for(let $ of e.events){let W=$.payload??{};switch($.type){case "item.added":{let y=W,T=y.phase??(y.parent!==null?i.get(y.parent):void 0);i.set(y.id,T),s.set(y.id,y.type),l.set(y.id,"todo"),y.type==="change-request"&&(f+=1),v(y.id)&&(a[T]+=1,y.type==="bug"&&(d[T]+=1));break}case "item.transition":{let y=W.id,T=W.to.status,Pe=l.get(y);if(l.set(y,T),!v(y))break;let de=i.get(y);T==="done"&&Pe!=="done"&&(p[de]+=1),T==="dropped"&&(a[de]-=1,Pe==="done"&&(p[de]-=1));break}case "item.completed":{let y=i.get(W.id);y!==void 0&&y in o&&(o[y]+=W.tokens??0);break}case "phase.opened":{let y=W.phase;y in c&&(c[y]=(W.budget??{}).tokens??0);break}case "change.decided":{W.decision==="approve"?(u+=1,m+=W.weight??0,h+=(W.reopened??[]).length):r+=1;break}}}let Z=n(),I=n();for(let $ of t){let W=a[$]??0;Z[$]=W===0?0:(p[$]??0)/W*100,I[$]=o[$]-c[$];}let{traced:x,total:se}=O(e).coverage,Re=u+r;return {phaseCompletion:Z,budgetPlanned:c,budgetSpent:o,scheduleVariance:I,requirementCoverage:se===0?0:x/se,requirementsTraced:x,requirementsTotal:se,defectsPerPhase:d,changeRequests:f,changesApproved:u,changesRejected:r,changeApprovalRate:Re===0?0:u/Re,reworkWeight:m,phasesReopened:h}}function we(e){let t=e.phases.map(n=>n.gate.id);return [{id:"project-manager",name:"Project Manager",modelTier:"large",capabilities:["facilitate","control-change","approve-gate","escalate"],canApprove:[...t,me],inputs:["phase-plan","deliverables","change-requests"],outputs:["gate-decisions","baselines","change-decisions"],do_not:["do not implement items yourself","do not reopen a phase without an approved change-request"]},{id:"developer",name:"Developer",modelTier:"small",capabilities:["deliver"],canApprove:[],inputs:["design-doc","interface-spec","brief"],outputs:["code","code-baseline","test-output"],do_not:["do not change requirements or designs; raise a change-request","do not approve your own work"]},{id:"business-analyst",name:"Business Analyst",modelTier:"medium",capabilities:["define-acceptance","deliver"],canApprove:[],inputs:["stakeholder-needs"],outputs:["srs","acceptance-criteria"],do_not:["do not design or implement","do not edit a baselined requirement; raise a change-request"]},{id:"architect",name:"Architect",modelTier:"medium",capabilities:["deliver"],canApprove:[],inputs:["srs"],outputs:["design-doc","interface-spec"],do_not:["do not change requirements; raise a change-request","do not implement"]},{id:"qa",name:"QA",modelTier:"small",capabilities:["verify","review"],canApprove:[],inputs:["srs","design-doc","code-baseline"],outputs:["test-report","review-notes"],do_not:["do not fix defects yourself; raise bugs","do not approve phase gates"]},{id:"release-manager",name:"Release Manager",modelTier:"small",capabilities:["deliver"],canApprove:[],inputs:["code-baseline","test-report"],outputs:["release-notes","deployment-record"],do_not:["do not deploy an unbaselined verification phase"]}]}var k=(e,t,n,a)=>a?{rule:e,severity:"error",item:a,message:t,fix:n}:{rule:e,severity:"error",message:t,fix:n},R=e=>e.payload??{},C=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Q=e=>{let t=R(e).phase;return typeof t=="string"?t:void 0},S=(e,t)=>b(e).find(n=>n.id===t),oe=e=>b(e).map(t=>t.id).join(", "),M=(e,t)=>typeof t=="string"&&Object.hasOwn(e.items,t)?e.items[t]:void 0;function He(e,t){if(t.phase!==void 0)return t.phase;let n=M(e,t.parent);return n?q(e,n):void 0}var Ue=e=>e.type!=="change-request"&&e.type!=="question",ze=(e,t)=>`raise a change-request: addItem({ type: "change-request", affects: ["${e}"], impactAnalysis: { summary, reopen: ["${t}"], weight } }) and decide it in changeControlBoard`;function Ke(e,t){let n=M(e,R(t).change);return n&&n.type==="change-request"?n:void 0}function $e(e,t,n){let a="change-needs-impact-analysis",p=`editItem("${t}", { impactAnalysis: { summary: "what changes and why", reopen: ["<phase>"], weight: <points> } })`;if(n===void 0)return w(e).changeControl.requiresImpactAnalysis?[k(a,`change "${t}" has no impact analysis`,p,t)]:[];let c=[],o=C(n)?n:{};return (typeof o.summary!="string"||o.summary.trim()==="")&&c.push(k(a,`change "${t}" impactAnalysis.summary is empty`,p,t)),(!Array.isArray(o.reopen)||!o.reopen.every(d=>typeof d=="string"))&&c.push(k(a,`change "${t}" impactAnalysis.reopen must be a string[] of phase ids`,p,t)),(typeof o.weight!="number"||!Number.isFinite(o.weight)||o.weight<0)&&c.push(k(a,`change "${t}" impactAnalysis.weight must be a non-negative number`,p,t)),c}function We(){return [{id:"phase-sequential",severity:"error",check(i,s){let l=[];if(s.type==="ceremony.kickoff"){let f=Q(s),u=f===void 0?void 0:S(i,f);if(!u)return [];u.status==="open"&&l.push(k("phase-sequential",`phase "${u.id}" is already open`,`gateReview "${u.id}" when its work is done`)),u.status==="baselined"&&l.push(k("phase-sequential",`phase "${u.id}" is baselined`,"only an approved change-request reopens a baselined phase"));let r=D(i);r&&r.id!==u.id&&l.push(k("phase-sequential",`phase "${r.id}" is still open`,`pass its gate (gateReview "${r.id}") before opening "${u.id}"`));}else if(s.type==="item.add"){let f=R(s).item;if(!C(f)||!Ue(f))return [];let u=He(i,f);u===void 0?l.push(k("phase-sequential",`item "${f.id}" belongs to no phase`,`set phase to one of: ${oe(i)}`,f.id)):S(i,u)||l.push(k("phase-sequential",`item "${f.id}" names unknown phase "${u}"`,`phases are: ${oe(i)}`,f.id));}else if(s.type==="item.edit"){let f=R(s).id,u=R(s).patch,r=M(i,f);if(!r||!C(u)||u.phase===void 0||u.phase===r.phase)return [];l.push(k("phase-sequential",`item "${r.id}" cannot move from phase "${r.phase??"(none)"}" to "${String(u.phase)}"`,`drop "${r.id}" and add a new item in phase "${String(u.phase)}"`,r.id));}return l}},{id:"gate-before-next-phase",severity:"error",check(i,s){if(s.type!=="ceremony.kickoff")return [];let l=Q(s),f=b(i),u=l===void 0?-1:f.findIndex(m=>m.id===l);if(u<0)return [];let r=f.slice(0,u).filter(m=>m.status!=="baselined").map(m=>m.id);return r.length===0?[]:[k("gate-before-next-phase",`phase(s) ${r.join(", ")} before "${l}" are not baselined`,`kickoff and gateReview them in order, starting with "${r[0]}"`)]}},{id:"baseline-immutable",severity:"error",check(i,s){let l=f=>(i.baselines??[]).filter(u=>u.phase===f).length||1;if(s.type==="item.edit"){let f=M(i,R(s).id);if(!f)return [];let u=q(i,f);return u===void 0||S(i,u)?.status!=="baselined"?[]:[k("baseline-immutable",`item "${f.id}" is frozen: phase "${u}" is baselined (v${l(u)})`,ze(f.id,u),f.id)]}if(s.type==="item.add"){let f=R(s).item;if(!C(f)||!Ue(f))return [];let u=He(i,f);return u===void 0||S(i,u)?.status!=="baselined"?[]:[k("baseline-immutable",`cannot add "${f.id}" to baselined phase "${u}" (v${l(u)})`,ze(f.id,u),f.id)]}return []}},{id:"change-needs-impact-analysis",severity:"error",check(i,s){if(s.type==="item.add"){let r=R(s).item;return !C(r)||r.type!=="change-request"?[]:$e(i,String(r.id),r.impactAnalysis)}if(s.type==="item.edit"){let r=R(s).patch,m=M(i,R(s).id);return !m||m.type!=="change-request"||!C(r)||!("impactAnalysis"in r)?[]:$e(i,m.id,r.impactAnalysis)}if(s.type!=="ceremony.changeControlBoard")return [];let l=Ke(i,s);if(!l)return [];let f=$e(i,l.id,l.impactAnalysis);if(f.length||l.impactAnalysis===void 0)return f;let u=R(s).decision==="approve";for(let r of l.impactAnalysis.reopen){let m=S(i,r);m?u&&m.status==="pending"&&f.push(k("change-needs-impact-analysis",`phase "${r}" was never baselined; it cannot be reopened`,`remove "${r}" from impactAnalysis.reopen`,l.id)):f.push(k("change-needs-impact-analysis",`change "${l.id}" impactAnalysis.reopen names unknown phase "${r}"`,`phases are: ${oe(i)}`,l.id));}return f}},{id:"requirement-traced",severity:"error",check(i,s){if(s.type!=="ceremony.gateReview")return [];let l=Q(s),f=w(i).traceability;return l===void 0||!f.to.includes(l)||!S(i,l)?[]:J(i,l).map(u=>k("requirement-traced",`item "${u}" of phase "${f.from}" has no trace into "${l}"`,`editItem a "${l}" item with traces: ["${u}"] (or editItem("${u}", { traces: [...] }) while "${f.from}" is not baselined)`,u))}},{id:"deliverables-present",severity:"error",check(i,s){if(s.type!=="ceremony.gateReview")return [];let l=Q(s),f=l===void 0?void 0:S(i,l);if(!f)return [];let u=[],r=P(i,f.id).filter(v=>v.status!=="done").map(v=>v.id);r.length&&u.push(k("deliverables-present",`${r.length} item(s) in phase "${f.id}" are not done: ${r.join(", ")}`,"finish them (next/complete) or drop them before the gate"));let m=R(s).deliverables,h=Array.isArray(m)?m.filter(v=>C(v)&&typeof v.kind=="string").map(v=>v.kind):[];f.id===B(i)&&h.push("traceability-matrix");for(let v of U(i,f,h))u.push(k("deliverables-present",`phase "${f.id}" has no deliverable "${v}"`,`pass deliverables: [{ "kind": "${v}", "ref": "<where it lives>" }] to gateReview, or attach evidence of kind "${v}" on an item of the phase`));return u}},{id:"approver-not-author",severity:"error",check(i$1,s){if(s.by==="human")return [];if(s.type==="ceremony.gateReview"){let l=Q(s),f=l===void 0?void 0:S(i$1,l);if(!f)return [];let u=P(i$1,f.id).filter(m=>G$1(i$1,m)===s.by).map(m=>m.id);if(u.length===0)return [];let r=j$1(i$1,f.gate.id,"approve-gate",s.by);return [k("approver-not-author",`"${s.by}" authored ${u.join(", ")} in phase "${f.id}" and may not approve its gate`,`review the gate as one of: human${r.map(m=>`, ${m}`).join("")}`)]}if(s.type==="ceremony.changeControlBoard"){let l=Ke(i$1,s);if(!l)return [];let f=i$1.events.find(r=>r.type==="item.added"&&r.payload.id===l.id);if(!f||f.by!==s.by)return [];let u=i(i$1,"control-change").map(r=>r.id).filter(r=>r!==s.by);return [k("approver-not-author",`"${s.by}" raised change "${l.id}" and may not decide it`,`decide as human${u.map(r=>`, ${r}`).join("")}`,l.id)]}return []}},{id:"trace-ids-valid",severity:"error",check(i,s){let l,f,u,r;if(s.type==="item.add"){let h=R(s).item;if(!C(h))return [];l=String(h.id),f=h.traces,u=h.impactAnalysis,r=h.type==="change-request";}else if(s.type==="item.edit"){let h=M(i,R(s).id),v=R(s).patch;if(!h||!C(v))return [];l=h.id,f=v.traces,u=v.impactAnalysis,r=h.type==="change-request";}else return [];let m=[];if(Array.isArray(f)){let h=w(i).traceability,v=[h.from,...h.to].flatMap(I=>P(i,I).filter(x=>x.type!=="question"&&x.type!=="change-request").map(x=>x.id)),Z=`traceable items: ${v.length?v.join(", "):"(none yet)"}`;for(let I of f){if(typeof I!="string")continue;let x=M(i,I);(!x||x.status==="dropped")&&m.push(k("trace-ids-valid",`item "${l}" traces unknown item "${I}"`,Z,l));}}if(r&&C(u)&&Array.isArray(u.reopen))for(let h of u.reopen)typeof h=="string"&&!S(i,h)&&m.push(k("trace-ids-valid",`change "${l}" impactAnalysis.reopen names unknown phase "${h}"`,`phases are: ${oe(i)}`,l));return m}}]}function Ae(e){return [{id:L,name:"Work",entryPolicy:[{kind:"dependencies-done"}],exitPolicy:[]},{id:V,name:"Review",entryPolicy:[],exitPolicy:[{kind:"no-open-blockers"}],review:true},{id:H,name:"Done",entryPolicy:[],exitPolicy:[]}]}var tt={backlog:"Requirements Baseline",item:"Work Package",stage:"Step",iteration:"Phase",increment:"Deliverable",ceremony:"Review",gate:"Phase Gate"};function nt(e,t){let n=q(e,t);if(n!==void 0)return w(e).phases.find(a=>a.id===n)?.deliverBy}function it(e){return {phases:b(e).map(n=>{let a=P(e,n.id),p=a.filter(s=>s.status==="done").length,o=w(e).traceability.to.includes(n.id)?J(e,n.id):[],d=n.id===B(e)&&o.length===0?["traceability-matrix"]:[],i=U(e,n,d);return {id:n.id,name:n.name,status:n.status,items:a.length,done:p,missingDeliverables:i,missingTraces:o,readyForGate:n.status==="open"&&p===a.length&&i.length===0&&o.length===0}}),current:he(e)?.id??null,open:D(e)?.id??null,pendingGates:e.pending.filter(n=>n.kind==="gate"&&n.item===void 0&&n.gate!==void 0).map(n=>({pending:n.id,gate:n.gate}))}}function rt(){return {name:"waterfall",vocabulary:tt,validateConfig:ge,defaultStages:Ae,defaultRoles:we,requiredCapabilities:["facilitate","control-change","approve-gate","deliver","verify"],exclusiveCapabilities:[],plannerOptions(e){let t={schedulerMode:"level",roleFor:a=>a.status==="todo"&&a.type!=="question"?nt(e,a):void 0},n=w(e).fallbackTokensPerWeight;return n!==void 0&&(t.fallbackTokensPerWeight=n),t},candidates(e){let t=D(e);return t?Object.values(e.items).filter(n=>(n.status==="todo"||n.status==="review")&&(n.stage===L||n.stage===V)&&n.type!=="change-request"&&q(e,n)===t.id):[]},invariants(e,t){let n=w(e),a=b(e),p=q(e,t),c=p===void 0?void 0:a[E(e,p)],o=a.filter(i=>i.status==="baselined").map(i=>i.id),d=c?.gate.requires.includes("human");return [c?`Phase "${c.name}" (${E(e,c.id)+1}/${a.length}); deliverables: ${c.deliverables.join(", ")||"(none)"}; gate "${c.gate.id}"${d?" needs human approval":""}`:"This item belongs to no phase; it is dispatched only through its parent's phase",`Baselined phases are frozen: ${o.join(", ")||"(none yet)"}; to change their items, raise a change-request with an impact analysis`,n.traceability.to.length?`Traceability: every item of phase "${n.traceability.from}" must trace to an item in ${n.traceability.to.join(", ")} (set traces on either side)`:"Traceability: none configured",`Do not change the scope of "${t.id}" or its acceptance criteria; raise open_questions instead`]},ceremonies:be(rt),rules:We(),metrics:e=>({...ke(e)}),humanDefaults:{gates:"all"},lockedConfigKeys:["phases","traceability","humanGates"],report:e=>({...it(e),coverage:O(e).coverage}),afterDecide:ve,afterComplete(e,t,n){let a=P$1(e),p=D(e);if(!a||!p||a.committed.includes(t))return e;let c=e.items[t];if(!c||q(e,c)!==p.id)return e;let o=e.accounting[e.accounting.length-1];return !o||o.item!==t?e:{...e,iterations:e.iterations.map(d=>d.id===a.id?{...d,committed:[...d.committed,t],spent:L$1(d.spent,o)}:d)}}}}export{K as A,O as B,J as C,Y as D,be as E,ve as F,ke as G,we as H,We as I,Ae as J,tt as K,nt as L,it as M,rt as N,De as a,pe as b,fe as c,ue as d,me as e,Me as f,w as g,ge as h,L as i,V as j,H as k,b as l,j as m,E as n,_ as o,q as p,P as q,D as r,he as s,Je as t,_e as u,U as v,B as w,ae as x,ye as y,z};//# sourceMappingURL=chunk-SYLO7FUL.mjs.map
2
- //# sourceMappingURL=chunk-SYLO7FUL.mjs.map