ex-workflow 0.3.0-stage → 0.4.0-stage

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/README.md +16 -3
  3. package/dist/adapters/index.cjs +1 -1
  4. package/dist/adapters/index.mjs +1 -1
  5. package/dist/chunk-36M6OVUJ.mjs +2 -0
  6. package/dist/chunk-36M6OVUJ.mjs.map +1 -0
  7. package/dist/{chunk-4A4TD4MH.cjs → chunk-7KF5K3L7.cjs} +2 -2
  8. package/dist/{chunk-4A4TD4MH.cjs.map → chunk-7KF5K3L7.cjs.map} +1 -1
  9. package/dist/{chunk-2IKIBB73.cjs → chunk-CWBH7H52.cjs} +2 -2
  10. package/dist/{chunk-2IKIBB73.cjs.map → chunk-CWBH7H52.cjs.map} +1 -1
  11. package/dist/chunk-DXC2RSN5.cjs +3 -0
  12. package/dist/chunk-DXC2RSN5.cjs.map +1 -0
  13. package/dist/{chunk-UOGNVWVO.mjs → chunk-GATJZYTB.mjs} +2 -2
  14. package/dist/{chunk-UOGNVWVO.mjs.map → chunk-GATJZYTB.mjs.map} +1 -1
  15. package/dist/{chunk-ZX4DAMTG.mjs → chunk-GFH2FEZH.mjs} +2 -2
  16. package/dist/{chunk-ZX4DAMTG.mjs.map → chunk-GFH2FEZH.mjs.map} +1 -1
  17. package/dist/{chunk-NN3XJUHP.cjs → chunk-HHC5EZ54.cjs} +2 -2
  18. package/dist/{chunk-NN3XJUHP.cjs.map → chunk-HHC5EZ54.cjs.map} +1 -1
  19. package/dist/{chunk-TMKCALFT.cjs → chunk-KSKEFYY7.cjs} +2 -2
  20. package/dist/{chunk-TMKCALFT.cjs.map → chunk-KSKEFYY7.cjs.map} +1 -1
  21. package/dist/chunk-KUUIAKEJ.cjs +2 -0
  22. package/dist/chunk-KUUIAKEJ.cjs.map +1 -0
  23. package/dist/{chunk-R27STIER.mjs → chunk-L2ZN6HEL.mjs} +2 -2
  24. package/dist/{chunk-R27STIER.mjs.map → chunk-L2ZN6HEL.mjs.map} +1 -1
  25. package/dist/{chunk-BJEOTG6P.mjs → chunk-NDORREWR.mjs} +2 -2
  26. package/dist/{chunk-BJEOTG6P.mjs.map → chunk-NDORREWR.mjs.map} +1 -1
  27. package/dist/{chunk-WOKNWJKU.mjs → chunk-NZ2DIDOD.mjs} +2 -2
  28. package/dist/{chunk-WOKNWJKU.mjs.map → chunk-NZ2DIDOD.mjs.map} +1 -1
  29. package/dist/chunk-OHSQ52DW.mjs +6 -0
  30. package/dist/chunk-OHSQ52DW.mjs.map +1 -0
  31. package/dist/chunk-RSKZVOYC.cjs +6 -0
  32. package/dist/chunk-RSKZVOYC.cjs.map +1 -0
  33. package/dist/chunk-S22CPYXJ.mjs +3 -0
  34. package/dist/chunk-S22CPYXJ.mjs.map +1 -0
  35. package/dist/{chunk-FLCYD2QF.mjs → chunk-SHAPFMVP.mjs} +2 -2
  36. package/dist/{chunk-FLCYD2QF.mjs.map → chunk-SHAPFMVP.mjs.map} +1 -1
  37. package/dist/{chunk-23P7C25E.cjs → chunk-SJRRQZ3R.cjs} +2 -2
  38. package/dist/{chunk-23P7C25E.cjs.map → chunk-SJRRQZ3R.cjs.map} +1 -1
  39. package/dist/{chunk-7HZXZF3L.cjs → chunk-UM5X2JHB.cjs} +2 -2
  40. package/dist/{chunk-7HZXZF3L.cjs.map → chunk-UM5X2JHB.cjs.map} +1 -1
  41. package/dist/cli/bin.cjs +1 -1
  42. package/dist/cli/bin.cjs.map +1 -1
  43. package/dist/cli/bin.mjs +1 -1
  44. package/dist/cli/bin.mjs.map +1 -1
  45. package/dist/cli/index.cjs +1 -1
  46. package/dist/cli/index.mjs +1 -1
  47. package/dist/index.cjs +1 -1
  48. package/dist/index.cjs.map +1 -1
  49. package/dist/index.d.cts +5 -5
  50. package/dist/index.d.ts +5 -5
  51. package/dist/index.mjs +1 -1
  52. package/dist/index.mjs.map +1 -1
  53. package/dist/kanban/index.cjs +1 -1
  54. package/dist/kanban/index.mjs +1 -1
  55. package/dist/schema/index.cjs +2 -0
  56. package/dist/schema/index.cjs.map +1 -0
  57. package/dist/schema/index.d.cts +57 -0
  58. package/dist/schema/index.d.ts +57 -0
  59. package/dist/schema/index.mjs +2 -0
  60. package/dist/schema/index.mjs.map +1 -0
  61. package/dist/scrum/index.cjs +1 -1
  62. package/dist/scrum/index.mjs +1 -1
  63. package/dist/types.d.cts +9 -2
  64. package/dist/types.d.ts +9 -2
  65. package/dist/waterfall/index.cjs +1 -1
  66. package/dist/waterfall/index.mjs +1 -1
  67. package/package.json +18 -2
  68. package/dist/chunk-6R3YFUUV.cjs +0 -6
  69. package/dist/chunk-6R3YFUUV.cjs.map +0 -1
  70. package/dist/chunk-AUZIQPFT.cjs +0 -2
  71. package/dist/chunk-AUZIQPFT.cjs.map +0 -1
  72. package/dist/chunk-P4P4JTE5.mjs +0 -2
  73. package/dist/chunk-P4P4JTE5.mjs.map +0 -1
  74. package/dist/chunk-VGD4V5BA.mjs +0 -6
  75. package/dist/chunk-VGD4V5BA.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- import {e,G,i,a,p,D,x,c}from'./chunk-FLCYD2QF.mjs';import {b}from'./chunk-2FRRD6A3.mjs';import {ExFlow,ExFlowRuntimeError}from'ex-flow';var U={tokens:0,turns:0,wallclockMs:0};function V(e,t){return {tokens:e.tokens+t.tokensIn+t.tokensOut,turns:e.turns+1,wallclockMs:e.wallclockMs+t.durationMs}}function q(e,t){let r={};return e.tokens!==void 0&&(r.tokens=Math.max(0,e.tokens-t.tokens)),e.turns!==void 0&&(r.turns=Math.max(0,e.turns-t.turns)),e.wallclockMs!==void 0&&(r.wallclockMs=Math.max(0,e.wallclockMs-t.wallclockMs)),r}function X(e,t){return e.tokens!==void 0&&t.tokens>=e.tokens||e.turns!==void 0&&t.turns>=e.turns||e.wallclockMs!==void 0&&t.wallclockMs>=e.wallclockMs}function F(e,t,r=2e4){let u=t??1,a=[];for(let i of e.accounting){let d=e.items[i.item]?.weight;d===void 0||d<=0||a.push((i.tokensIn+i.tokensOut)/d);}if(a.length===0)return r*u;a.sort((i,d)=>i-d);let o=Math.floor(a.length/2),p=a.length%2?a[o]:(a[o-1]+a[o])/2;return Math.round(p*u)}function K(e){return e.iterations.find(t=>t.endedAt===void 0)}function A(e$1,t,r){if(t.role){let o=e(e$1,t.role);return o||b("unknown-role",`item "${t.id}" is assigned to unknown role "${t.role}"`,"editItem with an existing role id"),o}let u=r?r(t):void 0;if(u!==void 0){let o=e(e$1,u);return o||b("unknown-role",`the methodology picked unknown role "${u}" for item "${t.id}"`,`registered roles: ${Object.keys(e$1.roles).join(", ")||"(none)"}`,{items:[t.id]}),o}if(t.status==="review"){let o=G(e$1,t),p=i(e$1,"review"),d=p.find(w=>w.id!==o)??(p.length===1?p[0]:void 0);return d||b("missing-capability",`no role has capability "review" for item "${t.id}"`,"register a role with capability review",{items:[t.id]}),d}let a=i(e$1,"deliver")[0];return a||b("missing-capability",`no role has capability "deliver" for item "${t.id}"`,"register a role with capability deliver",{items:[t.id]}),a}function T(e){let t={};for(let r of Object.values(e.roles))r.maxConcurrent!==void 0&&(t[r.resourceClass??r.id]=r.maxConcurrent);return t}function Q(e,t,r,u){let a=new Set(e.map(o=>o.id));return e.map(o=>{let p=A(t,o,u),i={id:o.id,data:{id:o.id},dependsOn:o.dependsOn.filter(w=>a.has(w)),resourceClass:p.resourceClass??p.id},d=r?r(o):o.priority;return d!==void 0&&(i.priority=d),o.weight!==void 0&&(i.weight=o.weight),o.deadline!==void 0&&(i.deadline=Date.parse(o.deadline)),i})}function ae(e$1,t,r={}){let u=a(r.now),a$1=t.candidates(e$1),o=a$1.filter(n=>n.dependsOn.every(s=>e$1.items[s]?.status==="done"||a$1.some(c=>c.id===s))),p$1=a$1.filter(n=>n.dependsOn.every(s=>e$1.items[s]?.status==="done"));if(o.length===0)return {state:e$1,dispatched:[],skipped:[],reason:"no-candidates"};let i=t.plannerOptions(e$1),d={schedulerMode:i.schedulerMode,resourceCaps:T(e$1)};if(i.concurrencyCap!==void 0&&(d.concurrencyCap=i.concurrencyCap),i.fairnessPolicy!==void 0&&(d.fairnessPolicy=i.fairnessPolicy),i.maxDeferralRounds!==void 0&&(d.maxDeferralRounds=i.maxDeferralRounds),i.deadlineStrategy!==void 0&&(d.deadlineStrategy=i.deadlineStrategy),i.weightStrategy!==void 0&&(d.weightStrategy=i.weightStrategy),i.tieBreaker!==void 0){let n=i.tieBreaker;d.tieBreaker=(s,c)=>n(e$1.items[s.data.id],e$1.items[c.data.id]);}let w,P;try{let n=new ExFlow(d);for(let c of Q(o,e$1,i.priorityOf,i.roleFor))n.addEntity(c);let s=n.resolveExecutionDetails();w=(s.plan.batches[0]??[]).map(c=>c.id),P=s.metrics;}catch(n){throw n instanceof ExFlowRuntimeError&&b("planner-error",`ex-flow refused the graph: [${n.code}] ${n.message}`,"fix the item graph (cycles, duplicate ids) with editItem; see diagnostics in the message",{items:o.map(s=>s.id)}),n}let L=w.map(n=>e$1.items[n]).filter(n=>n.dependsOn.every(s=>e$1.items[s]?.status==="done")),_=Object.values(e$1.items).filter(n=>n.status==="in_progress"),H=new Set(i.wipCounts??["in_progress"]),Z=Object.values(e$1.items).filter(n=>H.has(n.status)),S={};for(let n of _){let s=n.role?e(e$1,n.role):void 0,c=s?s.resourceClass??s.id:"?";S[c]=(S[c]??0)+1;}let M=T(e$1),R=K(e$1),b$1=R?q(R.budget,R.spent).tokens:void 0,z=Math.min(r.max??1/0,i.concurrencyCap??1/0),g=[],h=[],l,f=e$1;for(let n of L){if(g.length>=z){l="wip-full";break}let s=typeof i.dispatchStage=="function"?i.dispatchStage(n):i.dispatchStage,c=n.status==="todo"&&s!==void 0?s:n.stage,y=p(e$1,c),C=n.type==="question"?[]:D(e$1,n,y.entryPolicy);if(C.length>0){h.push({id:n.id,reason:"entry-policy",detail:C.map(m=>m.message).join("; ")});continue}let W=i.wipLimitOf?i.wipLimitOf(y,n):y.wipLimit;if(W!==void 0&&Z.filter(m=>m.stage===y.id&&m.id!==n.id).length+g.filter(m=>m.stage===y.id).length>=W){l="wip-full",h.push({id:n.id,reason:"wip",detail:`stage "${y.id}" is at its WIP limit of ${W}`});continue}let O=A(e$1,n,i.roleFor),k=O.resourceClass??O.id;if(M[k]!==void 0&&(S[k]??0)>=M[k]){l="wip-full",h.push({id:n.id,reason:"resource-cap",detail:`resource class "${k}" is at its cap of ${M[k]}`});continue}if(b$1!==void 0){let m=F(e$1,n.weight,r.fallbackTokensPerWeight);if(m>b$1){l="budget-exhausted",h.push({id:n.id,reason:"budget",detail:`needs about ${m} tokens, ${b$1} left in the iteration`});continue}b$1-=m;}S[k]=(S[k]??0)+1,f=x(f,n.id,{stage:c,status:"in_progress"},O.id,u),f={...f,items:{...f.items,[n.id]:{...f.items[n.id],role:O.id}}},g.push(f.items[n.id]);}return l===void 0&&h.some(n=>n.reason==="entry-policy")&&(l="policy-blocked"),l===void 0&&g.length<p$1.length&&(l="wip-full"),g.length===0&&l===void 0&&(l="no-candidates"),f=c(f,"planner.resolved","planner",{dispatched:g.map(n=>n.id),reason:l??null,skipped:h,metrics:P},u),l?{state:f,dispatched:g,skipped:h,reason:l}:{state:f,dispatched:g,skipped:h}}export{U as a,V as b,q as c,X as d,F as e,K as f,A as g,T as h,Q as i,ae as j};//# sourceMappingURL=chunk-ZX4DAMTG.mjs.map
2
- //# sourceMappingURL=chunk-ZX4DAMTG.mjs.map
1
+ import {e,G,i,a,p,D,x,c}from'./chunk-SHAPFMVP.mjs';import {b}from'./chunk-2FRRD6A3.mjs';import {ExFlow,ExFlowRuntimeError}from'ex-flow';var U={tokens:0,turns:0,wallclockMs:0};function V(e,t){return {tokens:e.tokens+t.tokensIn+t.tokensOut,turns:e.turns+1,wallclockMs:e.wallclockMs+t.durationMs}}function q(e,t){let r={};return e.tokens!==void 0&&(r.tokens=Math.max(0,e.tokens-t.tokens)),e.turns!==void 0&&(r.turns=Math.max(0,e.turns-t.turns)),e.wallclockMs!==void 0&&(r.wallclockMs=Math.max(0,e.wallclockMs-t.wallclockMs)),r}function X(e,t){return e.tokens!==void 0&&t.tokens>=e.tokens||e.turns!==void 0&&t.turns>=e.turns||e.wallclockMs!==void 0&&t.wallclockMs>=e.wallclockMs}function F(e,t,r=2e4){let u=t??1,a=[];for(let i of e.accounting){let d=e.items[i.item]?.weight;d===void 0||d<=0||a.push((i.tokensIn+i.tokensOut)/d);}if(a.length===0)return r*u;a.sort((i,d)=>i-d);let o=Math.floor(a.length/2),p=a.length%2?a[o]:(a[o-1]+a[o])/2;return Math.round(p*u)}function K(e){return e.iterations.find(t=>t.endedAt===void 0)}function A(e$1,t,r){if(t.role){let o=e(e$1,t.role);return o||b("unknown-role",`item "${t.id}" is assigned to unknown role "${t.role}"`,"editItem with an existing role id"),o}let u=r?r(t):void 0;if(u!==void 0){let o=e(e$1,u);return o||b("unknown-role",`the methodology picked unknown role "${u}" for item "${t.id}"`,`registered roles: ${Object.keys(e$1.roles).join(", ")||"(none)"}`,{items:[t.id]}),o}if(t.status==="review"){let o=G(e$1,t),p=i(e$1,"review"),d=p.find(w=>w.id!==o)??(p.length===1?p[0]:void 0);return d||b("missing-capability",`no role has capability "review" for item "${t.id}"`,"register a role with capability review",{items:[t.id]}),d}let a=i(e$1,"deliver")[0];return a||b("missing-capability",`no role has capability "deliver" for item "${t.id}"`,"register a role with capability deliver",{items:[t.id]}),a}function T(e){let t={};for(let r of Object.values(e.roles))r.maxConcurrent!==void 0&&(t[r.resourceClass??r.id]=r.maxConcurrent);return t}function Q(e,t,r,u){let a=new Set(e.map(o=>o.id));return e.map(o=>{let p=A(t,o,u),i={id:o.id,data:{id:o.id},dependsOn:o.dependsOn.filter(w=>a.has(w)),resourceClass:p.resourceClass??p.id},d=r?r(o):o.priority;return d!==void 0&&(i.priority=d),o.weight!==void 0&&(i.weight=o.weight),o.deadline!==void 0&&(i.deadline=Date.parse(o.deadline)),i})}function ae(e$1,t,r={}){let u=a(r.now),a$1=t.candidates(e$1),o=a$1.filter(n=>n.dependsOn.every(s=>e$1.items[s]?.status==="done"||a$1.some(c=>c.id===s))),p$1=a$1.filter(n=>n.dependsOn.every(s=>e$1.items[s]?.status==="done"));if(o.length===0)return {state:e$1,dispatched:[],skipped:[],reason:"no-candidates"};let i=t.plannerOptions(e$1),d={schedulerMode:i.schedulerMode,resourceCaps:T(e$1)};if(i.concurrencyCap!==void 0&&(d.concurrencyCap=i.concurrencyCap),i.fairnessPolicy!==void 0&&(d.fairnessPolicy=i.fairnessPolicy),i.maxDeferralRounds!==void 0&&(d.maxDeferralRounds=i.maxDeferralRounds),i.deadlineStrategy!==void 0&&(d.deadlineStrategy=i.deadlineStrategy),i.weightStrategy!==void 0&&(d.weightStrategy=i.weightStrategy),i.tieBreaker!==void 0){let n=i.tieBreaker;d.tieBreaker=(s,c)=>n(e$1.items[s.data.id],e$1.items[c.data.id]);}let w,P;try{let n=new ExFlow(d);for(let c of Q(o,e$1,i.priorityOf,i.roleFor))n.addEntity(c);let s=n.resolveExecutionDetails();w=(s.plan.batches[0]??[]).map(c=>c.id),P=s.metrics;}catch(n){throw n instanceof ExFlowRuntimeError&&b("planner-error",`ex-flow refused the graph: [${n.code}] ${n.message}`,"fix the item graph (cycles, duplicate ids) with editItem; see diagnostics in the message",{items:o.map(s=>s.id)}),n}let L=w.map(n=>e$1.items[n]).filter(n=>n.dependsOn.every(s=>e$1.items[s]?.status==="done")),_=Object.values(e$1.items).filter(n=>n.status==="in_progress"),H=new Set(i.wipCounts??["in_progress"]),Z=Object.values(e$1.items).filter(n=>H.has(n.status)),S={};for(let n of _){let s=n.role?e(e$1,n.role):void 0,c=s?s.resourceClass??s.id:"?";S[c]=(S[c]??0)+1;}let M=T(e$1),R=K(e$1),b$1=R?q(R.budget,R.spent).tokens:void 0,z=Math.min(r.max??1/0,i.concurrencyCap??1/0),g=[],h=[],l,f=e$1;for(let n of L){if(g.length>=z){l="wip-full";break}let s=typeof i.dispatchStage=="function"?i.dispatchStage(n):i.dispatchStage,c=n.status==="todo"&&s!==void 0?s:n.stage,y=p(e$1,c),C=n.type==="question"?[]:D(e$1,n,y.entryPolicy);if(C.length>0){h.push({id:n.id,reason:"entry-policy",detail:C.map(m=>m.message).join("; ")});continue}let W=i.wipLimitOf?i.wipLimitOf(y,n):y.wipLimit;if(W!==void 0&&Z.filter(m=>m.stage===y.id&&m.id!==n.id).length+g.filter(m=>m.stage===y.id).length>=W){l="wip-full",h.push({id:n.id,reason:"wip",detail:`stage "${y.id}" is at its WIP limit of ${W}`});continue}let O=A(e$1,n,i.roleFor),k=O.resourceClass??O.id;if(M[k]!==void 0&&(S[k]??0)>=M[k]){l="wip-full",h.push({id:n.id,reason:"resource-cap",detail:`resource class "${k}" is at its cap of ${M[k]}`});continue}if(b$1!==void 0){let m=F(e$1,n.weight,r.fallbackTokensPerWeight);if(m>b$1){l="budget-exhausted",h.push({id:n.id,reason:"budget",detail:`needs about ${m} tokens, ${b$1} left in the iteration`});continue}b$1-=m;}S[k]=(S[k]??0)+1,f=x(f,n.id,{stage:c,status:"in_progress"},O.id,u),f={...f,items:{...f.items,[n.id]:{...f.items[n.id],role:O.id}}},g.push(f.items[n.id]);}return l===void 0&&h.some(n=>n.reason==="entry-policy")&&(l="policy-blocked"),l===void 0&&g.length<p$1.length&&(l="wip-full"),g.length===0&&l===void 0&&(l="no-candidates"),f=c(f,"planner.resolved","planner",{dispatched:g.map(n=>n.id),reason:l??null,skipped:h,metrics:P},u),l?{state:f,dispatched:g,skipped:h,reason:l}:{state:f,dispatched:g,skipped:h}}export{U as a,V as b,q as c,X as d,F as e,K as f,A as g,T as h,Q as i,ae as j};//# sourceMappingURL=chunk-GFH2FEZH.mjs.map
2
+ //# sourceMappingURL=chunk-GFH2FEZH.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/budget.ts","../src/planner.ts"],"names":["ZERO_SPENT","addSpent","spent","acc","remaining","budget","out","isExhausted","estimateTokens","state","weight","fallbackPerWeight","w","samples","a","iw","x","y","mid","median","openIteration","it","assignRole","item","roleFor","r","roleOf","fail","picked","author","authorOf","reviewers","rolesWith","resourceCapsFor","caps","toExNodes","items","priorityOf","present","i","role","node","d","pr","plan","methodology","opts","at","nowOf","all","candidates","readyAll","po","options","tb","b","firstBatch","metrics","flow","ExFlow","n","details","e","ExFlowRuntimeError","c","ready","id","inProgress","wipCounts","occupying","perClass","cls","iteration","tokensLeft","limit","dispatched","skipped","reason","next","pulledTo","target","stage","stageOf","violations","evaluatePolicies","v","limitHere","est","moveItem","appendEvent"],"mappings":"wIAEO,IAAMA,CAAAA,CAA+B,CAAE,MAAA,CAAQ,CAAA,CAAG,MAAO,CAAA,CAAG,WAAA,CAAa,CAAE,EAE3E,SAASC,CAAAA,CAASC,CAAAA,CAAyBC,CAAAA,CAAmC,CACnF,OAAO,CACL,MAAA,CAAQD,CAAAA,CAAM,MAAA,CAASC,CAAAA,CAAI,QAAA,CAAWA,CAAAA,CAAI,UAC1C,KAAA,CAAOD,CAAAA,CAAM,KAAA,CAAQ,CAAA,CACrB,YAAaA,CAAAA,CAAM,WAAA,CAAcC,CAAAA,CAAI,UACvC,CACF,CAEO,SAASC,CAAAA,CAAUC,CAAAA,CAAgBH,CAAAA,CAAiC,CACzE,IAAMI,CAAAA,CAAc,EAAC,CACrB,OAAID,CAAAA,CAAO,MAAA,GAAW,SAAWC,CAAAA,CAAI,MAAA,CAAS,IAAA,CAAK,GAAA,CAAI,EAAGD,CAAAA,CAAO,MAAA,CAASH,CAAAA,CAAM,MAAM,CAAA,CAAA,CAClFG,CAAAA,CAAO,KAAA,GAAU,MAAA,GAAWC,EAAI,KAAA,CAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,CAAGD,EAAO,KAAA,CAAQH,CAAAA,CAAM,KAAK,CAAA,CAAA,CAC9EG,EAAO,WAAA,GAAgB,MAAA,GACzBC,CAAAA,CAAI,WAAA,CAAc,IAAA,CAAK,GAAA,CAAI,CAAA,CAAGD,CAAAA,CAAO,YAAcH,CAAAA,CAAM,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A,CAAO,CACL,GAAGA,CAAAA,CACH,KAAA,CAAO,CAAE,GAAGA,EAAK,KAAA,CAAO,CAACvD,CAAAA,CAAK,EAAE,EAAG,CAAE,GAAGuD,CAAAA,CAAK,MAAMvD,CAAAA,CAAK,EAAE,CAAA,CAAI,IAAA,CAAMiB,EAAK,EAAG,CAAE,CAChF,CAAA,CACAmC,EAAW,IAAA,CAAKG,CAAAA,CAAK,KAAA,CAAMvD,CAAAA,CAAK,EAAE,CAAE,EACtC,CACA,OAAIsD,CAAAA,GAAW,MAAA,EAAaD,CAAAA,CAAQ,IAAA,CAAM5D,GAAMA,CAAAA,CAAE,MAAA,GAAW,cAAc,CAAA,GACzE6D,EAAS,gBAAA,CAAA,CACPA,CAAAA,GAAW,MAAA,EAAaF,CAAAA,CAAW,MAAA,CAASxB,GAAAA,CAAS,MAAA,GAAQ0B,CAAAA,CAAS,YACtEF,CAAAA,CAAW,MAAA,GAAW,CAAA,EAAKE,CAAAA,GAAW,SAAWA,CAAAA,CAAS,eAAA,CAAA,CAC9DC,CAAAA,CAAOW,CAAAA,CACLX,EACA,kBAAA,CACA,SAAA,CACA,CAAE,UAAA,CAAYH,CAAAA,CAAW,GAAA,CAAKjC,CAAAA,EAAMA,CAAAA,CAAE,EAAE,CAAA,CAAG,MAAA,CAAQmC,CAAAA,EAAU,IAAA,CAAM,QAAAD,CAAAA,CAAS,OAAA,CAAAnB,CAAQ,CAAA,CACpFV,CACF,CAAA,CACO8B,CAAAA,CACH,CAAE,KAAA,CAAOC,CAAAA,CAAM,UAAA,CAAAH,CAAAA,CAAY,OAAA,CAAAC,EAAS,MAAA,CAAAC,CAAO,CAAA,CAC3C,CAAE,MAAOC,CAAAA,CAAM,UAAA,CAAAH,CAAAA,CAAY,OAAA,CAAAC,CAAQ,CACzC","file":"chunk-ZX4DAMTG.mjs","sourcesContent":["import type { Accounting, Budget, WorkflowState } from \"./types.ts\";\n\nexport const ZERO_SPENT: Required<Budget> = { tokens: 0, turns: 0, wallclockMs: 0 };\n\nexport function addSpent(spent: Required<Budget>, acc: Accounting): Required<Budget> {\n return {\n tokens: spent.tokens + acc.tokensIn + acc.tokensOut,\n turns: spent.turns + 1,\n wallclockMs: spent.wallclockMs + acc.durationMs,\n };\n}\n\nexport function remaining(budget: Budget, spent: Required<Budget>): Budget {\n const out: Budget = {};\n if (budget.tokens !== undefined) out.tokens = Math.max(0, budget.tokens - spent.tokens);\n if (budget.turns !== undefined) out.turns = Math.max(0, budget.turns - spent.turns);\n if (budget.wallclockMs !== undefined)\n out.wallclockMs = Math.max(0, budget.wallclockMs - spent.wallclockMs);\n return out;\n}\n\nexport function isExhausted(budget: Budget, spent: Required<Budget>): boolean {\n return (\n (budget.tokens !== undefined && spent.tokens >= budget.tokens) ||\n (budget.turns !== undefined && spent.turns >= budget.turns) ||\n (budget.wallclockMs !== undefined && spent.wallclockMs >= budget.wallclockMs)\n );\n}\n\nexport function estimateTokens(\n state: WorkflowState,\n weight: number | undefined,\n fallbackPerWeight = 20000,\n): number {\n const w = weight ?? 1;\n const samples: number[] = [];\n for (const a of state.accounting) {\n const iw = state.items[a.item]?.weight;\n if (iw === undefined || iw <= 0) continue;\n samples.push((a.tokensIn + a.tokensOut) / iw);\n }\n if (samples.length === 0) return fallbackPerWeight * w;\n samples.sort((x, y) => x - y);\n const mid = Math.floor(samples.length / 2);\n const median = samples.length % 2 ? samples[mid]! : (samples[mid - 1]! + samples[mid]!) / 2;\n return Math.round(median * w);\n}\n","import { ExFlow, ExFlowRuntimeError, type ExFlowOptions, type ExNode } from \"ex-flow\";\nimport { estimateTokens, remaining } from \"./budget.ts\";\nimport { fail } from \"./errors.ts\";\nimport { authorOf } from \"./gates.ts\";\nimport { moveItem, stageOf } from \"./items.ts\";\nimport { evaluatePolicies } from \"./policies.ts\";\nimport { roleOf, rolesWith } from \"./roles.ts\";\nimport { appendEvent, nowOf } from \"./state.ts\";\nimport type { ItemStatus, Iteration, Methodology, Role, WorkItem, WorkflowState } from \"./types.ts\";\n\ntype NodeData = { id: string };\n\nexport function openIteration(state: WorkflowState): Iteration | undefined {\n return state.iterations.find((it) => it.endedAt === undefined);\n}\n\nexport function assignRole(\n state: WorkflowState,\n item: WorkItem,\n roleFor?: (item: WorkItem) => string | undefined,\n): Role {\n if (item.role) {\n const r = roleOf(state, item.role);\n if (!r)\n fail(\n \"unknown-role\",\n `item \"${item.id}\" is assigned to unknown role \"${item.role}\"`,\n \"editItem with an existing role id\",\n );\n return r;\n }\n const picked = roleFor ? roleFor(item) : undefined;\n if (picked !== undefined) {\n const r = roleOf(state, picked);\n if (!r)\n fail(\n \"unknown-role\",\n `the methodology picked unknown role \"${picked}\" for item \"${item.id}\"`,\n `registered roles: ${Object.keys(state.roles).join(\", \") || \"(none)\"}`,\n { items: [item.id] },\n );\n return r;\n }\n if (item.status === \"review\") {\n const author = authorOf(state, item);\n const reviewers = rolesWith(state, \"review\");\n const other = reviewers.find((r) => r.id !== author);\n const r = other ?? (reviewers.length === 1 ? reviewers[0] : undefined);\n if (!r)\n fail(\n \"missing-capability\",\n `no role has capability \"review\" for item \"${item.id}\"`,\n \"register a role with capability review\",\n { items: [item.id] },\n );\n return r;\n }\n const r = rolesWith(state, \"deliver\")[0];\n if (!r)\n fail(\n \"missing-capability\",\n `no role has capability \"deliver\" for item \"${item.id}\"`,\n \"register a role with capability deliver\",\n { items: [item.id] },\n );\n return r;\n}\n\nexport function resourceCapsFor(state: WorkflowState): Record<string, number> {\n const caps: Record<string, number> = {};\n for (const r of Object.values(state.roles)) {\n if (r.maxConcurrent !== undefined) caps[r.resourceClass ?? r.id] = r.maxConcurrent;\n }\n return caps;\n}\n\nexport function toExNodes(\n items: WorkItem[],\n state: WorkflowState,\n priorityOf?: (item: WorkItem) => number | undefined,\n roleFor?: (item: WorkItem) => string | undefined,\n): ExNode<NodeData>[] {\n const present = new Set(items.map((i) => i.id));\n return items.map((i) => {\n const role = assignRole(state, i, roleFor);\n const node: ExNode<NodeData> = {\n id: i.id,\n data: { id: i.id },\n dependsOn: i.dependsOn.filter((d) => present.has(d)),\n resourceClass: role.resourceClass ?? role.id,\n };\n const pr = priorityOf ? priorityOf(i) : i.priority;\n if (pr !== undefined) node.priority = pr;\n if (i.weight !== undefined) node.weight = i.weight;\n if (i.deadline !== undefined) node.deadline = Date.parse(i.deadline);\n return node;\n });\n}\n\nexport interface PlanOptions {\n max?: number;\n now?: string;\n fallbackTokensPerWeight?: number;\n}\nexport type PlanReason = \"no-candidates\" | \"budget-exhausted\" | \"wip-full\" | \"policy-blocked\";\n/** A ready item the planner did not pull, and why. */\nexport interface Skipped {\n id: string;\n reason: \"entry-policy\" | \"wip\" | \"resource-cap\" | \"budget\";\n detail: string;\n}\nexport interface PlanResult {\n state: WorkflowState;\n dispatched: WorkItem[];\n skipped: Skipped[];\n reason?: PlanReason;\n}\n\nexport function plan(\n state: WorkflowState,\n methodology: Methodology,\n opts: PlanOptions = {},\n): PlanResult {\n const at = nowOf(opts.now);\n // an item may enter the graph only if every dependency is done or is itself a candidate (so ex-flow orders it)\n const all = methodology.candidates(state);\n const candidates = all.filter((i) =>\n i.dependsOn.every((d) => state.items[d]?.status === \"done\" || all.some((c) => c.id === d)),\n );\n const readyAll = all.filter((i) => i.dependsOn.every((d) => state.items[d]?.status === \"done\"));\n if (candidates.length === 0)\n return { state, dispatched: [], skipped: [], reason: \"no-candidates\" };\n\n const po = methodology.plannerOptions(state);\n const options: ExFlowOptions<NodeData> = {\n schedulerMode: po.schedulerMode,\n resourceCaps: resourceCapsFor(state),\n };\n if (po.concurrencyCap !== undefined) options.concurrencyCap = po.concurrencyCap;\n if (po.fairnessPolicy !== undefined) options.fairnessPolicy = po.fairnessPolicy;\n if (po.maxDeferralRounds !== undefined) options.maxDeferralRounds = po.maxDeferralRounds;\n if (po.deadlineStrategy !== undefined) options.deadlineStrategy = po.deadlineStrategy;\n if (po.weightStrategy !== undefined) options.weightStrategy = po.weightStrategy;\n if (po.tieBreaker !== undefined) {\n const tb = po.tieBreaker;\n options.tieBreaker = (a, b) => tb(state.items[a.data.id]!, state.items[b.data.id]!);\n }\n\n let firstBatch: string[];\n let metrics: unknown;\n try {\n const flow = new ExFlow<NodeData>(options);\n for (const n of toExNodes(candidates, state, po.priorityOf, po.roleFor)) flow.addEntity(n);\n const details = flow.resolveExecutionDetails();\n firstBatch = (details.plan.batches[0] ?? []).map((r) => r.id);\n metrics = details.metrics;\n } catch (e) {\n if (e instanceof ExFlowRuntimeError) {\n fail(\n \"planner-error\",\n `ex-flow refused the graph: [${e.code}] ${e.message}`,\n \"fix the item graph (cycles, duplicate ids) with editItem; see diagnostics in the message\",\n { items: candidates.map((c) => c.id) },\n );\n }\n throw e;\n }\n\n // ready = first batch, but only items whose deps are really done (deps inside the batch are impossible by construction)\n const ready = firstBatch\n .map((id) => state.items[id]!)\n .filter((i) => i.dependsOn.every((d) => state.items[d]?.status === \"done\"));\n const inProgress = Object.values(state.items).filter((i) => i.status === \"in_progress\");\n const wipCounts = new Set<ItemStatus>(po.wipCounts ?? [\"in_progress\"]);\n const occupying = Object.values(state.items).filter((i) => wipCounts.has(i.status));\n const perClass: Record<string, number> = {};\n for (const i of inProgress) {\n const r = i.role ? roleOf(state, i.role) : undefined;\n const cls = r ? (r.resourceClass ?? r.id) : \"?\";\n perClass[cls] = (perClass[cls] ?? 0) + 1;\n }\n const caps = resourceCapsFor(state);\n const iteration = openIteration(state);\n let tokensLeft = iteration ? remaining(iteration.budget, iteration.spent).tokens : undefined;\n const limit = Math.min(opts.max ?? Infinity, po.concurrencyCap ?? Infinity);\n\n const dispatched: WorkItem[] = [];\n const skipped: Skipped[] = [];\n let reason: PlanReason | undefined;\n let next = state;\n for (const item of ready) {\n if (dispatched.length >= limit) {\n reason = \"wip-full\";\n break;\n }\n const pulledTo =\n typeof po.dispatchStage === \"function\" ? po.dispatchStage(item) : po.dispatchStage;\n const target = item.status === \"todo\" && pulledTo !== undefined ? pulledTo : item.stage;\n const stage = stageOf(state, target);\n // questions are answered, not delivered: like exit policies and gates, entry policies do not apply\n const violations =\n item.type === \"question\" ? [] : evaluatePolicies(state, item, stage.entryPolicy);\n if (violations.length > 0) {\n skipped.push({\n id: item.id,\n reason: \"entry-policy\",\n detail: violations.map((v) => v.message).join(\"; \"),\n });\n continue;\n }\n const limitHere = po.wipLimitOf ? po.wipLimitOf(stage, item) : stage.wipLimit;\n if (\n limitHere !== undefined &&\n occupying.filter((i) => i.stage === stage.id && i.id !== item.id).length +\n dispatched.filter((d) => d.stage === stage.id).length >=\n limitHere\n ) {\n reason = \"wip-full\";\n skipped.push({\n id: item.id,\n reason: \"wip\",\n detail: `stage \"${stage.id}\" is at its WIP limit of ${limitHere}`,\n });\n continue;\n }\n const role = assignRole(state, item, po.roleFor);\n const cls = role.resourceClass ?? role.id;\n if (caps[cls] !== undefined && (perClass[cls] ?? 0) >= caps[cls]!) {\n reason = \"wip-full\";\n skipped.push({\n id: item.id,\n reason: \"resource-cap\",\n detail: `resource class \"${cls}\" is at its cap of ${caps[cls]}`,\n });\n continue;\n }\n if (tokensLeft !== undefined) {\n const est = estimateTokens(state, item.weight, opts.fallbackTokensPerWeight);\n if (est > tokensLeft) {\n reason = \"budget-exhausted\";\n skipped.push({\n id: item.id,\n reason: \"budget\",\n detail: `needs about ${est} tokens, ${tokensLeft} left in the iteration`,\n });\n continue;\n }\n tokensLeft -= est;\n }\n perClass[cls] = (perClass[cls] ?? 0) + 1;\n next = moveItem(next, item.id, { stage: target, status: \"in_progress\" }, role.id, at);\n next = {\n ...next,\n items: { ...next.items, [item.id]: { ...next.items[item.id]!, role: role.id } },\n };\n dispatched.push(next.items[item.id]!);\n }\n if (reason === undefined && skipped.some((x) => x.reason === \"entry-policy\"))\n reason = \"policy-blocked\";\n if (reason === undefined && dispatched.length < readyAll.length) reason = \"wip-full\";\n if (dispatched.length === 0 && reason === undefined) reason = \"no-candidates\";\n next = appendEvent(\n next,\n \"planner.resolved\",\n \"planner\",\n { dispatched: dispatched.map((d) => d.id), reason: reason ?? null, skipped, metrics },\n at,\n );\n return reason\n ? { state: next, dispatched, skipped, reason }\n : { state: next, dispatched, skipped };\n}\n"]}
1
+ {"version":3,"sources":["../src/budget.ts","../src/planner.ts"],"names":["ZERO_SPENT","addSpent","spent","acc","remaining","budget","out","isExhausted","estimateTokens","state","weight","fallbackPerWeight","w","samples","a","iw","x","y","mid","median","openIteration","it","assignRole","item","roleFor","r","roleOf","fail","picked","author","authorOf","reviewers","rolesWith","resourceCapsFor","caps","toExNodes","items","priorityOf","present","i","role","node","d","pr","plan","methodology","opts","at","nowOf","all","candidates","readyAll","po","options","tb","b","firstBatch","metrics","flow","ExFlow","n","details","e","ExFlowRuntimeError","c","ready","id","inProgress","wipCounts","occupying","perClass","cls","iteration","tokensLeft","limit","dispatched","skipped","reason","next","pulledTo","target","stage","stageOf","violations","evaluatePolicies","v","limitHere","est","moveItem","appendEvent"],"mappings":"wIAEO,IAAMA,CAAAA,CAA+B,CAAE,MAAA,CAAQ,CAAA,CAAG,MAAO,CAAA,CAAG,WAAA,CAAa,CAAE,EAE3E,SAASC,CAAAA,CAASC,CAAAA,CAAyBC,CAAAA,CAAmC,CACnF,OAAO,CACL,MAAA,CAAQD,CAAAA,CAAM,MAAA,CAASC,CAAAA,CAAI,QAAA,CAAWA,CAAAA,CAAI,UAC1C,KAAA,CAAOD,CAAAA,CAAM,KAAA,CAAQ,CAAA,CACrB,YAAaA,CAAAA,CAAM,WAAA,CAAcC,CAAAA,CAAI,UACvC,CACF,CAEO,SAASC,CAAAA,CAAUC,CAAAA,CAAgBH,CAAAA,CAAiC,CACzE,IAAMI,CAAAA,CAAc,EAAC,CACrB,OAAID,CAAAA,CAAO,MAAA,GAAW,SAAWC,CAAAA,CAAI,MAAA,CAAS,IAAA,CAAK,GAAA,CAAI,EAAGD,CAAAA,CAAO,MAAA,CAASH,CAAAA,CAAM,MAAM,CAAA,CAAA,CAClFG,CAAAA,CAAO,KAAA,GAAU,MAAA,GAAWC,EAAI,KAAA,CAAQ,IAAA,CAAK,GAAA,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AC3C,CAAE,MAAOC,CAAAA,CAAM,UAAA,CAAAH,CAAAA,CAAY,OAAA,CAAAC,CAAQ,CACzC","file":"chunk-GFH2FEZH.mjs","sourcesContent":["import type { Accounting, Budget, WorkflowState } from \"./types.ts\";\n\nexport const ZERO_SPENT: Required<Budget> = { tokens: 0, turns: 0, wallclockMs: 0 };\n\nexport function addSpent(spent: Required<Budget>, acc: Accounting): Required<Budget> {\n return {\n tokens: spent.tokens + acc.tokensIn + acc.tokensOut,\n turns: spent.turns + 1,\n wallclockMs: spent.wallclockMs + acc.durationMs,\n };\n}\n\nexport function remaining(budget: Budget, spent: Required<Budget>): Budget {\n const out: Budget = {};\n if (budget.tokens !== undefined) out.tokens = Math.max(0, budget.tokens - spent.tokens);\n if (budget.turns !== undefined) out.turns = Math.max(0, budget.turns - spent.turns);\n if (budget.wallclockMs !== undefined)\n out.wallclockMs = Math.max(0, budget.wallclockMs - spent.wallclockMs);\n return out;\n}\n\nexport function isExhausted(budget: Budget, spent: Required<Budget>): boolean {\n return (\n (budget.tokens !== undefined && spent.tokens >= budget.tokens) ||\n (budget.turns !== undefined && spent.turns >= budget.turns) ||\n (budget.wallclockMs !== undefined && spent.wallclockMs >= budget.wallclockMs)\n );\n}\n\nexport function estimateTokens(\n state: WorkflowState,\n weight: number | undefined,\n fallbackPerWeight = 20000,\n): number {\n const w = weight ?? 1;\n const samples: number[] = [];\n for (const a of state.accounting) {\n const iw = state.items[a.item]?.weight;\n if (iw === undefined || iw <= 0) continue;\n samples.push((a.tokensIn + a.tokensOut) / iw);\n }\n if (samples.length === 0) return fallbackPerWeight * w;\n samples.sort((x, y) => x - y);\n const mid = Math.floor(samples.length / 2);\n const median = samples.length % 2 ? samples[mid]! : (samples[mid - 1]! + samples[mid]!) / 2;\n return Math.round(median * w);\n}\n","import { ExFlow, ExFlowRuntimeError, type ExFlowOptions, type ExNode } from \"ex-flow\";\nimport { estimateTokens, remaining } from \"./budget.ts\";\nimport { fail } from \"./errors.ts\";\nimport { authorOf } from \"./gates.ts\";\nimport { moveItem, stageOf } from \"./items.ts\";\nimport { evaluatePolicies } from \"./policies.ts\";\nimport { roleOf, rolesWith } from \"./roles.ts\";\nimport { appendEvent, nowOf } from \"./state.ts\";\nimport type { ItemStatus, Iteration, Methodology, Role, WorkItem, WorkflowState } from \"./types.ts\";\n\ntype NodeData = { id: string };\n\nexport function openIteration(state: WorkflowState): Iteration | undefined {\n return state.iterations.find((it) => it.endedAt === undefined);\n}\n\nexport function assignRole(\n state: WorkflowState,\n item: WorkItem,\n roleFor?: (item: WorkItem) => string | undefined,\n): Role {\n if (item.role) {\n const r = roleOf(state, item.role);\n if (!r)\n fail(\n \"unknown-role\",\n `item \"${item.id}\" is assigned to unknown role \"${item.role}\"`,\n \"editItem with an existing role id\",\n );\n return r;\n }\n const picked = roleFor ? roleFor(item) : undefined;\n if (picked !== undefined) {\n const r = roleOf(state, picked);\n if (!r)\n fail(\n \"unknown-role\",\n `the methodology picked unknown role \"${picked}\" for item \"${item.id}\"`,\n `registered roles: ${Object.keys(state.roles).join(\", \") || \"(none)\"}`,\n { items: [item.id] },\n );\n return r;\n }\n if (item.status === \"review\") {\n const author = authorOf(state, item);\n const reviewers = rolesWith(state, \"review\");\n const other = reviewers.find((r) => r.id !== author);\n const r = other ?? (reviewers.length === 1 ? reviewers[0] : undefined);\n if (!r)\n fail(\n \"missing-capability\",\n `no role has capability \"review\" for item \"${item.id}\"`,\n \"register a role with capability review\",\n { items: [item.id] },\n );\n return r;\n }\n const r = rolesWith(state, \"deliver\")[0];\n if (!r)\n fail(\n \"missing-capability\",\n `no role has capability \"deliver\" for item \"${item.id}\"`,\n \"register a role with capability deliver\",\n { items: [item.id] },\n );\n return r;\n}\n\nexport function resourceCapsFor(state: WorkflowState): Record<string, number> {\n const caps: Record<string, number> = {};\n for (const r of Object.values(state.roles)) {\n if (r.maxConcurrent !== undefined) caps[r.resourceClass ?? r.id] = r.maxConcurrent;\n }\n return caps;\n}\n\nexport function toExNodes(\n items: WorkItem[],\n state: WorkflowState,\n priorityOf?: (item: WorkItem) => number | undefined,\n roleFor?: (item: WorkItem) => string | undefined,\n): ExNode<NodeData>[] {\n const present = new Set(items.map((i) => i.id));\n return items.map((i) => {\n const role = assignRole(state, i, roleFor);\n const node: ExNode<NodeData> = {\n id: i.id,\n data: { id: i.id },\n dependsOn: i.dependsOn.filter((d) => present.has(d)),\n resourceClass: role.resourceClass ?? role.id,\n };\n const pr = priorityOf ? priorityOf(i) : i.priority;\n if (pr !== undefined) node.priority = pr;\n if (i.weight !== undefined) node.weight = i.weight;\n if (i.deadline !== undefined) node.deadline = Date.parse(i.deadline);\n return node;\n });\n}\n\nexport interface PlanOptions {\n max?: number;\n now?: string;\n fallbackTokensPerWeight?: number;\n}\nexport type PlanReason = \"no-candidates\" | \"budget-exhausted\" | \"wip-full\" | \"policy-blocked\";\n/** A ready item the planner did not pull, and why. */\nexport interface Skipped {\n id: string;\n reason: \"entry-policy\" | \"wip\" | \"resource-cap\" | \"budget\";\n detail: string;\n}\nexport interface PlanResult {\n state: WorkflowState;\n dispatched: WorkItem[];\n skipped: Skipped[];\n reason?: PlanReason;\n}\n\nexport function plan(\n state: WorkflowState,\n methodology: Methodology,\n opts: PlanOptions = {},\n): PlanResult {\n const at = nowOf(opts.now);\n // an item may enter the graph only if every dependency is done or is itself a candidate (so ex-flow orders it)\n const all = methodology.candidates(state);\n const candidates = all.filter((i) =>\n i.dependsOn.every((d) => state.items[d]?.status === \"done\" || all.some((c) => c.id === d)),\n );\n const readyAll = all.filter((i) => i.dependsOn.every((d) => state.items[d]?.status === \"done\"));\n if (candidates.length === 0)\n return { state, dispatched: [], skipped: [], reason: \"no-candidates\" };\n\n const po = methodology.plannerOptions(state);\n const options: ExFlowOptions<NodeData> = {\n schedulerMode: po.schedulerMode,\n resourceCaps: resourceCapsFor(state),\n };\n if (po.concurrencyCap !== undefined) options.concurrencyCap = po.concurrencyCap;\n if (po.fairnessPolicy !== undefined) options.fairnessPolicy = po.fairnessPolicy;\n if (po.maxDeferralRounds !== undefined) options.maxDeferralRounds = po.maxDeferralRounds;\n if (po.deadlineStrategy !== undefined) options.deadlineStrategy = po.deadlineStrategy;\n if (po.weightStrategy !== undefined) options.weightStrategy = po.weightStrategy;\n if (po.tieBreaker !== undefined) {\n const tb = po.tieBreaker;\n options.tieBreaker = (a, b) => tb(state.items[a.data.id]!, state.items[b.data.id]!);\n }\n\n let firstBatch: string[];\n let metrics: unknown;\n try {\n const flow = new ExFlow<NodeData>(options);\n for (const n of toExNodes(candidates, state, po.priorityOf, po.roleFor)) flow.addEntity(n);\n const details = flow.resolveExecutionDetails();\n firstBatch = (details.plan.batches[0] ?? []).map((r) => r.id);\n metrics = details.metrics;\n } catch (e) {\n if (e instanceof ExFlowRuntimeError) {\n fail(\n \"planner-error\",\n `ex-flow refused the graph: [${e.code}] ${e.message}`,\n \"fix the item graph (cycles, duplicate ids) with editItem; see diagnostics in the message\",\n { items: candidates.map((c) => c.id) },\n );\n }\n throw e;\n }\n\n // ready = first batch, but only items whose deps are really done (deps inside the batch are impossible by construction)\n const ready = firstBatch\n .map((id) => state.items[id]!)\n .filter((i) => i.dependsOn.every((d) => state.items[d]?.status === \"done\"));\n const inProgress = Object.values(state.items).filter((i) => i.status === \"in_progress\");\n const wipCounts = new Set<ItemStatus>(po.wipCounts ?? [\"in_progress\"]);\n const occupying = Object.values(state.items).filter((i) => wipCounts.has(i.status));\n const perClass: Record<string, number> = {};\n for (const i of inProgress) {\n const r = i.role ? roleOf(state, i.role) : undefined;\n const cls = r ? (r.resourceClass ?? r.id) : \"?\";\n perClass[cls] = (perClass[cls] ?? 0) + 1;\n }\n const caps = resourceCapsFor(state);\n const iteration = openIteration(state);\n let tokensLeft = iteration ? remaining(iteration.budget, iteration.spent).tokens : undefined;\n const limit = Math.min(opts.max ?? Infinity, po.concurrencyCap ?? Infinity);\n\n const dispatched: WorkItem[] = [];\n const skipped: Skipped[] = [];\n let reason: PlanReason | undefined;\n let next = state;\n for (const item of ready) {\n if (dispatched.length >= limit) {\n reason = \"wip-full\";\n break;\n }\n const pulledTo =\n typeof po.dispatchStage === \"function\" ? po.dispatchStage(item) : po.dispatchStage;\n const target = item.status === \"todo\" && pulledTo !== undefined ? pulledTo : item.stage;\n const stage = stageOf(state, target);\n // questions are answered, not delivered: like exit policies and gates, entry policies do not apply\n const violations =\n item.type === \"question\" ? [] : evaluatePolicies(state, item, stage.entryPolicy);\n if (violations.length > 0) {\n skipped.push({\n id: item.id,\n reason: \"entry-policy\",\n detail: violations.map((v) => v.message).join(\"; \"),\n });\n continue;\n }\n const limitHere = po.wipLimitOf ? po.wipLimitOf(stage, item) : stage.wipLimit;\n if (\n limitHere !== undefined &&\n occupying.filter((i) => i.stage === stage.id && i.id !== item.id).length +\n dispatched.filter((d) => d.stage === stage.id).length >=\n limitHere\n ) {\n reason = \"wip-full\";\n skipped.push({\n id: item.id,\n reason: \"wip\",\n detail: `stage \"${stage.id}\" is at its WIP limit of ${limitHere}`,\n });\n continue;\n }\n const role = assignRole(state, item, po.roleFor);\n const cls = role.resourceClass ?? role.id;\n if (caps[cls] !== undefined && (perClass[cls] ?? 0) >= caps[cls]!) {\n reason = \"wip-full\";\n skipped.push({\n id: item.id,\n reason: \"resource-cap\",\n detail: `resource class \"${cls}\" is at its cap of ${caps[cls]}`,\n });\n continue;\n }\n if (tokensLeft !== undefined) {\n const est = estimateTokens(state, item.weight, opts.fallbackTokensPerWeight);\n if (est > tokensLeft) {\n reason = \"budget-exhausted\";\n skipped.push({\n id: item.id,\n reason: \"budget\",\n detail: `needs about ${est} tokens, ${tokensLeft} left in the iteration`,\n });\n continue;\n }\n tokensLeft -= est;\n }\n perClass[cls] = (perClass[cls] ?? 0) + 1;\n next = moveItem(next, item.id, { stage: target, status: \"in_progress\" }, role.id, at);\n next = {\n ...next,\n items: { ...next.items, [item.id]: { ...next.items[item.id]!, role: role.id } },\n };\n dispatched.push(next.items[item.id]!);\n }\n if (reason === undefined && skipped.some((x) => x.reason === \"entry-policy\"))\n reason = \"policy-blocked\";\n if (reason === undefined && dispatched.length < readyAll.length) reason = \"wip-full\";\n if (dispatched.length === 0 && reason === undefined) reason = \"no-candidates\";\n next = appendEvent(\n next,\n \"planner.resolved\",\n \"planner\",\n { dispatched: dispatched.map((d) => d.id), reason: reason ?? null, skipped, metrics },\n at,\n );\n return reason\n ? { state: next, dispatched, skipped, reason }\n : { state: next, dispatched, skipped };\n}\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var chunk2IKIBB73_cjs=require('./chunk-2IKIBB73.cjs'),chunk23P7C25E_cjs=require('./chunk-23P7C25E.cjs'),chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs');function D(i,a){let t=[];for(let o of i.events)o.type==="item.completed"&&o.payload.id===a&&t.push({...o.payload,at:o.at});return t}function z(i,a){let t=D(i,a);return t[t.length-1]}function J(i,a,t){t.role||chunkS3BXVHO7_cjs.b("unknown-role",`item "${t.id}" has no role assigned`,"dispatch it with next() or set item.role",{items:[t.id]});let o=chunk23P7C25E_cjs.e(i,t.role);o||chunkS3BXVHO7_cjs.b("unknown-role",`role "${t.role}" does not exist`,`registered roles: ${Object.keys(i.roles).join(", ")}`);let u=[],d=[...o.do_not],s=[...t.dependsOn,...t.type==="bug"||t.type==="change-request"?t.affects??[]:[]];for(let n of s){let c=z(i,n);if(c){u.push({item:n,produced:c.produced,notes:c.notes});for(let m of c.do_not)d.includes(m)||d.push(m);}}let l=D(i,t.id).map(n=>({role:n.role,verdict:n.verdict,notes:n.notes,produced:n.produced,at:n.at})),e=new Set([t.id,...t.dependsOn]),g=Object.values(i.items).filter(n=>(n.type==="bug"||n.type==="change-request")&&n.id!==t.id&&n.status!=="done"&&n.status!=="dropped"&&(n.affects??[]).some(c=>e.has(c))).map(n=>({id:n.id,title:n.title,affects:n.affects??[]})),k=chunk2IKIBB73_cjs.f(i),f=chunk23P7C25E_cjs.p(i,t.stage).gate,r={item:t,role:o,modelTier:o.modelTier,invariants:[...a.invariants(i,t),...i.agreements],do_not:d,acceptance:t.acceptance,upstream:u,priorHandoffs:l,relatedBugs:g,budgetRemaining:k?chunk2IKIBB73_cjs.c(k.budget,k.spent):{}};return f&&(r.gateAhead=f),r}function oe(i,a,t={}){let o=chunk2IKIBB73_cjs.j(i,a,t),u=o.dispatched.map(d=>J(o.state,a,o.state.items[d.id]));return o.reason?{state:o.state,briefs:u,skipped:o.skipped,reason:o.reason}:{state:o.state,briefs:u,skipped:o.skipped}}var G=["done","needs-review","rework","blocked","escalate"],L=["policy","skill","memory","spec","review"],I=i=>typeof i=="object"&&i!==null&&!Array.isArray(i),v=i=>typeof i=="string";function X(i,a,t){let o=chunk23P7C25E_cjs.u(i,a.item);o.status!=="in_progress"&&chunkS3BXVHO7_cjs.b("invalid-transition",`item "${o.id}" is ${o.status}, not in_progress`,"only dispatched items can be completed; call next() first",{items:[o.id]}),Array.isArray(a.do_not)||chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff for "${o.id}" has no do_not array`,"set handoff.do_not to [] when there is nothing to forbid",{items:[o.id]}),(!Array.isArray(a.produced)||!Array.isArray(a.open_questions))&&chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff for "${o.id}" needs produced[] and open_questions[]`,"pass empty arrays when there is nothing",{items:[o.id]});let u=(e,g)=>chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff for "${o.id}": ${e}`,g,{items:[o.id]}),d=a.verdict??"done";G.includes(d)||u(`unknown verdict ${JSON.stringify(d)}`,`use one of: ${G.join(", ")}`),a.produced.every(e=>I(e)&&v(e.kind)&&v(e.ref))||u("produced[] entries need string kind and ref",'use { "kind": "code", "ref": "src/a.ts" }');let s=a.lessons??[];(!Array.isArray(s)||!s.every(e=>I(e)&&v(e.text)&&L.includes(e.scope)))&&u("lessons[] entries need a text and a scope",`scope is one of: ${L.join(", ")}`);let l=a.follow_ups??[];(!Array.isArray(l)||!l.every(e=>I(e)&&v(e.id)&&v(e.title)))&&u("follow_ups[] entries need a string id and title","describe each follow-up as a new item"),a.role!==o.role&&chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff role "${a.role}" differs from the dispatched role "${o.role}"`,`complete as "${o.role}" or re-dispatch`,{items:[o.id]}),(!t.model||t.model.trim()==="")&&chunkS3BXVHO7_cjs.b("accounting-invalid",`accounting for "${o.id}" has no model`,"record the model id that actually ran the work",{items:[o.id]});for(let e of ["tokensIn","tokensOut","durationMs"])(!Number.isFinite(t[e])||t[e]<0)&&chunkS3BXVHO7_cjs.b("accounting-invalid",`accounting.${e} must be a non-negative number`,`measure ${e} from the host's usage report`,{items:[o.id]});}function U(i){for(let a=i.transitions.length-1;a>=0;a--){let t=i.transitions[a];if(t.to.status==="in_progress")return t.from.stage}return i.stage}function K(i,a){return chunk23P7C25E_cjs.F(i,a)?.from.stage??U(a)}function fe(i,a,t,o,u){X(i,t,o);let d=chunk23P7C25E_cjs.a(u),s=t.item,l=t.role,e={...i,accounting:[...i.accounting,o]};for(let r of t.produced)e=chunk23P7C25E_cjs.y(e,s,{kind:r.kind,ref:r.ref,by:l},d);let g=chunk2IKIBB73_cjs.f(e);g&&(g.committed.includes(s)||chunk23P7C25E_cjs.u(e,s).iteration===g.id)&&(e={...e,iterations:e.iterations.map(r=>r.id===g.id?{...r,spent:chunk2IKIBB73_cjs.b(r.spent,o)}:r)});for(let r of t.lessons??[]){let n=`L${e.lessons.length+1}`;e={...e,lessons:[...e.lessons,{id:n,at:d,text:r.text,scope:r.scope,status:"raised",from:l,item:s}]},e=chunk23P7C25E_cjs.c(e,"lesson.raised",l,{id:n,from:l,item:s,scope:r.scope},d);}let k=[];for(let r of t.follow_ups??[]){let n=e.stages[0],{iteration:c,...m}=r;e=chunk23P7C25E_cjs.v(e,{...m,stage:n.id,parent:s,tags:[...r.tags??[],"follow-up"]},l,d),k.push(r.id);}let f=t.verdict??"done";if(f==="rework"){(!t.notes||t.notes.trim()==="")&&chunkS3BXVHO7_cjs.b("handoff-invalid",`rework on "${s}" needs notes`,"say what must change in handoff.notes",{items:[s]});let r=chunk23P7C25E_cjs.u(e,s);e=chunk23P7C25E_cjs.B(chunk23P7C25E_cjs.x(e,s,{stage:K(e,r),status:"todo"},l,d),s),e=chunk23P7C25E_cjs.c(e,"item.rework",l,{id:s,by:l,notes:t.notes},d);}else if((f==="done"||f==="needs-review")&&chunk23P7C25E_cjs.u(e,s).type==="question"){let r=e.stages[e.stages.length-1].id;e=chunk23P7C25E_cjs.x(e,s,{stage:r,status:"done"},l,d);}else if(f==="done"||f==="needs-review"){let r=chunk23P7C25E_cjs.u(e,s),n=chunk23P7C25E_cjs.p(e,r.stage);if(chunk23P7C25E_cjs.E(e,r,n.exitPolicy,`leave "${n.id}"`),n.gate){let c=chunk23P7C25E_cjs.H(e,r,n.gate,l);c.outcome==="fail"&&chunkS3BXVHO7_cjs.b("gate-unmet",`gate "${n.gate.id}" blocks "${s}": ${c.violations.map(m=>m.message).join("; ")}`,c.violations.map(m=>m.fix).join("; "),{items:[s],rule:c.violations[0].rule}),c.outcome==="human"?e=chunk23P7C25E_cjs.I(e,{kind:"gate",item:s,gate:n.gate.id,question:`Approve gate "${n.gate.id}" for "${r.title}" (${s})?`},d):e=chunk23P7C25E_cjs.c(chunk23P7C25E_cjs.C(e,s,l,f==="needs-review",d),"gate.passed",l,{item:s,gate:n.gate.id},d);}else e=chunk23P7C25E_cjs.C(e,s,l,f==="needs-review",d);}else if(f==="blocked")e=chunk23P7C25E_cjs.z(e,s,t.notes||"blocked by worker",l,l,d);else if(f==="escalate"){let r=chunk23P7C25E_cjs.i(e,"escalate")[0];r||chunkS3BXVHO7_cjs.b("missing-capability",`no role has capability "escalate" to receive the question from "${s}"`,"register a role with capability escalate",{items:[s]});let n=Object.keys(e.items).filter(h=>h.startsWith(`${s}-q`)).length+1,c=`${s}-q${n}`,m=chunk23P7C25E_cjs.u(e,s),O=U(m),W={id:c,type:"question",title:t.open_questions.join(" | ")||t.notes||`question from ${s}`,parent:s,role:r.id,priority:Number.MAX_SAFE_INTEGER,stage:O};m.iteration!==void 0&&(W.iteration=m.iteration),e=chunk23P7C25E_cjs.v(e,W,l,d),e=chunk23P7C25E_cjs.x(e,s,{stage:O,status:"todo"},l,d),e=chunk23P7C25E_cjs.s(e,s,h=>({...h,dependsOn:[...h.dependsOn,c]})),e=chunk23P7C25E_cjs.c(e,"item.escalated",l,{id:s,question:c,to:r.id},d);}return e=chunk23P7C25E_cjs.c(e,"item.completed",l,{id:s,role:l,verdict:f,produced:t.produced,notes:t.notes,do_not:t.do_not,open_questions:t.open_questions,followUps:k,tokens:o.tokensIn+o.tokensOut,durationMs:o.durationMs,model:o.model},d),a.afterComplete&&(e=a.afterComplete(e,s,d)),{state:e,warnings:[]}}exports.a=J;exports.b=oe;exports.c=fe;//# sourceMappingURL=chunk-NN3XJUHP.cjs.map
2
- //# sourceMappingURL=chunk-NN3XJUHP.cjs.map
1
+ 'use strict';var chunkCWBH7H52_cjs=require('./chunk-CWBH7H52.cjs'),chunkSJRRQZ3R_cjs=require('./chunk-SJRRQZ3R.cjs'),chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs');function D(i,a){let t=[];for(let o of i.events)o.type==="item.completed"&&o.payload.id===a&&t.push({...o.payload,at:o.at});return t}function z(i,a){let t=D(i,a);return t[t.length-1]}function J(i,a,t){t.role||chunkS3BXVHO7_cjs.b("unknown-role",`item "${t.id}" has no role assigned`,"dispatch it with next() or set item.role",{items:[t.id]});let o=chunkSJRRQZ3R_cjs.e(i,t.role);o||chunkS3BXVHO7_cjs.b("unknown-role",`role "${t.role}" does not exist`,`registered roles: ${Object.keys(i.roles).join(", ")}`);let u=[],d=[...o.do_not],s=[...t.dependsOn,...t.type==="bug"||t.type==="change-request"?t.affects??[]:[]];for(let n of s){let c=z(i,n);if(c){u.push({item:n,produced:c.produced,notes:c.notes});for(let m of c.do_not)d.includes(m)||d.push(m);}}let l=D(i,t.id).map(n=>({role:n.role,verdict:n.verdict,notes:n.notes,produced:n.produced,at:n.at})),e=new Set([t.id,...t.dependsOn]),g=Object.values(i.items).filter(n=>(n.type==="bug"||n.type==="change-request")&&n.id!==t.id&&n.status!=="done"&&n.status!=="dropped"&&(n.affects??[]).some(c=>e.has(c))).map(n=>({id:n.id,title:n.title,affects:n.affects??[]})),k=chunkCWBH7H52_cjs.f(i),f=chunkSJRRQZ3R_cjs.p(i,t.stage).gate,r={item:t,role:o,modelTier:o.modelTier,invariants:[...a.invariants(i,t),...i.agreements],do_not:d,acceptance:t.acceptance,upstream:u,priorHandoffs:l,relatedBugs:g,budgetRemaining:k?chunkCWBH7H52_cjs.c(k.budget,k.spent):{}};return f&&(r.gateAhead=f),r}function oe(i,a,t={}){let o=chunkCWBH7H52_cjs.j(i,a,t),u=o.dispatched.map(d=>J(o.state,a,o.state.items[d.id]));return o.reason?{state:o.state,briefs:u,skipped:o.skipped,reason:o.reason}:{state:o.state,briefs:u,skipped:o.skipped}}var G=["done","needs-review","rework","blocked","escalate"],L=["policy","skill","memory","spec","review"],I=i=>typeof i=="object"&&i!==null&&!Array.isArray(i),v=i=>typeof i=="string";function X(i,a,t){let o=chunkSJRRQZ3R_cjs.u(i,a.item);o.status!=="in_progress"&&chunkS3BXVHO7_cjs.b("invalid-transition",`item "${o.id}" is ${o.status}, not in_progress`,"only dispatched items can be completed; call next() first",{items:[o.id]}),Array.isArray(a.do_not)||chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff for "${o.id}" has no do_not array`,"set handoff.do_not to [] when there is nothing to forbid",{items:[o.id]}),(!Array.isArray(a.produced)||!Array.isArray(a.open_questions))&&chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff for "${o.id}" needs produced[] and open_questions[]`,"pass empty arrays when there is nothing",{items:[o.id]});let u=(e,g)=>chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff for "${o.id}": ${e}`,g,{items:[o.id]}),d=a.verdict??"done";G.includes(d)||u(`unknown verdict ${JSON.stringify(d)}`,`use one of: ${G.join(", ")}`),a.produced.every(e=>I(e)&&v(e.kind)&&v(e.ref))||u("produced[] entries need string kind and ref",'use { "kind": "code", "ref": "src/a.ts" }');let s=a.lessons??[];(!Array.isArray(s)||!s.every(e=>I(e)&&v(e.text)&&L.includes(e.scope)))&&u("lessons[] entries need a text and a scope",`scope is one of: ${L.join(", ")}`);let l=a.follow_ups??[];(!Array.isArray(l)||!l.every(e=>I(e)&&v(e.id)&&v(e.title)))&&u("follow_ups[] entries need a string id and title","describe each follow-up as a new item"),a.role!==o.role&&chunkS3BXVHO7_cjs.b("handoff-invalid",`handoff role "${a.role}" differs from the dispatched role "${o.role}"`,`complete as "${o.role}" or re-dispatch`,{items:[o.id]}),(!t.model||t.model.trim()==="")&&chunkS3BXVHO7_cjs.b("accounting-invalid",`accounting for "${o.id}" has no model`,"record the model id that actually ran the work",{items:[o.id]});for(let e of ["tokensIn","tokensOut","durationMs"])(!Number.isFinite(t[e])||t[e]<0)&&chunkS3BXVHO7_cjs.b("accounting-invalid",`accounting.${e} must be a non-negative number`,`measure ${e} from the host's usage report`,{items:[o.id]});}function U(i){for(let a=i.transitions.length-1;a>=0;a--){let t=i.transitions[a];if(t.to.status==="in_progress")return t.from.stage}return i.stage}function K(i,a){return chunkSJRRQZ3R_cjs.F(i,a)?.from.stage??U(a)}function fe(i,a,t,o,u){X(i,t,o);let d=chunkSJRRQZ3R_cjs.a(u),s=t.item,l=t.role,e={...i,accounting:[...i.accounting,o]};for(let r of t.produced)e=chunkSJRRQZ3R_cjs.y(e,s,{kind:r.kind,ref:r.ref,by:l},d);let g=chunkCWBH7H52_cjs.f(e);g&&(g.committed.includes(s)||chunkSJRRQZ3R_cjs.u(e,s).iteration===g.id)&&(e={...e,iterations:e.iterations.map(r=>r.id===g.id?{...r,spent:chunkCWBH7H52_cjs.b(r.spent,o)}:r)});for(let r of t.lessons??[]){let n=`L${e.lessons.length+1}`;e={...e,lessons:[...e.lessons,{id:n,at:d,text:r.text,scope:r.scope,status:"raised",from:l,item:s}]},e=chunkSJRRQZ3R_cjs.c(e,"lesson.raised",l,{id:n,from:l,item:s,scope:r.scope},d);}let k=[];for(let r of t.follow_ups??[]){let n=e.stages[0],{iteration:c,...m}=r;e=chunkSJRRQZ3R_cjs.v(e,{...m,stage:n.id,parent:s,tags:[...r.tags??[],"follow-up"]},l,d),k.push(r.id);}let f=t.verdict??"done";if(f==="rework"){(!t.notes||t.notes.trim()==="")&&chunkS3BXVHO7_cjs.b("handoff-invalid",`rework on "${s}" needs notes`,"say what must change in handoff.notes",{items:[s]});let r=chunkSJRRQZ3R_cjs.u(e,s);e=chunkSJRRQZ3R_cjs.B(chunkSJRRQZ3R_cjs.x(e,s,{stage:K(e,r),status:"todo"},l,d),s),e=chunkSJRRQZ3R_cjs.c(e,"item.rework",l,{id:s,by:l,notes:t.notes},d);}else if((f==="done"||f==="needs-review")&&chunkSJRRQZ3R_cjs.u(e,s).type==="question"){let r=e.stages[e.stages.length-1].id;e=chunkSJRRQZ3R_cjs.x(e,s,{stage:r,status:"done"},l,d);}else if(f==="done"||f==="needs-review"){let r=chunkSJRRQZ3R_cjs.u(e,s),n=chunkSJRRQZ3R_cjs.p(e,r.stage);if(chunkSJRRQZ3R_cjs.E(e,r,n.exitPolicy,`leave "${n.id}"`),n.gate){let c=chunkSJRRQZ3R_cjs.H(e,r,n.gate,l);c.outcome==="fail"&&chunkS3BXVHO7_cjs.b("gate-unmet",`gate "${n.gate.id}" blocks "${s}": ${c.violations.map(m=>m.message).join("; ")}`,c.violations.map(m=>m.fix).join("; "),{items:[s],rule:c.violations[0].rule}),c.outcome==="human"?e=chunkSJRRQZ3R_cjs.I(e,{kind:"gate",item:s,gate:n.gate.id,question:`Approve gate "${n.gate.id}" for "${r.title}" (${s})?`},d):e=chunkSJRRQZ3R_cjs.c(chunkSJRRQZ3R_cjs.C(e,s,l,f==="needs-review",d),"gate.passed",l,{item:s,gate:n.gate.id},d);}else e=chunkSJRRQZ3R_cjs.C(e,s,l,f==="needs-review",d);}else if(f==="blocked")e=chunkSJRRQZ3R_cjs.z(e,s,t.notes||"blocked by worker",l,l,d);else if(f==="escalate"){let r=chunkSJRRQZ3R_cjs.i(e,"escalate")[0];r||chunkS3BXVHO7_cjs.b("missing-capability",`no role has capability "escalate" to receive the question from "${s}"`,"register a role with capability escalate",{items:[s]});let n=Object.keys(e.items).filter(h=>h.startsWith(`${s}-q`)).length+1,c=`${s}-q${n}`,m=chunkSJRRQZ3R_cjs.u(e,s),O=U(m),W={id:c,type:"question",title:t.open_questions.join(" | ")||t.notes||`question from ${s}`,parent:s,role:r.id,priority:Number.MAX_SAFE_INTEGER,stage:O};m.iteration!==void 0&&(W.iteration=m.iteration),e=chunkSJRRQZ3R_cjs.v(e,W,l,d),e=chunkSJRRQZ3R_cjs.x(e,s,{stage:O,status:"todo"},l,d),e=chunkSJRRQZ3R_cjs.s(e,s,h=>({...h,dependsOn:[...h.dependsOn,c]})),e=chunkSJRRQZ3R_cjs.c(e,"item.escalated",l,{id:s,question:c,to:r.id},d);}return e=chunkSJRRQZ3R_cjs.c(e,"item.completed",l,{id:s,role:l,verdict:f,produced:t.produced,notes:t.notes,do_not:t.do_not,open_questions:t.open_questions,followUps:k,tokens:o.tokensIn+o.tokensOut,durationMs:o.durationMs,model:o.model},d),a.afterComplete&&(e=a.afterComplete(e,s,d)),{state:e,warnings:[]}}exports.a=J;exports.b=oe;exports.c=fe;//# sourceMappingURL=chunk-HHC5EZ54.cjs.map
2
+ //# sourceMappingURL=chunk-HHC5EZ54.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/brief.ts","../src/complete.ts"],"names":["completions","state","itemId","out","ev","lastCompletion","all","synthesizeBrief","methodology","item","fail","role","roleOf","upstream","doNot","sources","dep","p","d","priorHandoffs","touched","relatedBugs","b","a","it","openIteration","gate","stageOf","brief","remaining","next","opts","res","plan","briefs","VERDICTS","LESSON_SCOPES","isObj","x","str","validate","handoff","acc","getItem","bad","what","fix","verdict","lessons","l","followUps","f","k","pulledFromStage","i","reworkStage","lastDispatchBefore","complete","now","at","nowOf","id","s","addEvidence","addSpent","lid","appendEvent","n","first","_drop","rest","addItem","clearRole","moveItem","lastStageId","stage","assertPolicies","checkGate","v","raisePending","advanceItem","raiseBlocker","thinker","rolesWith","qid","parent","pulledFrom","q","patchItem"],"mappings":"uKAgBA,SAASA,EACPC,CAAAA,CACAC,CAAAA,CAC0C,CAC1C,IAAMC,CAAAA,CAAgD,EAAC,CACvD,IAAA,IAAWC,CAAAA,IAAMH,CAAAA,CAAM,OACjBG,CAAAA,CAAG,IAAA,GAAS,kBAAqBA,CAAAA,CAAG,OAAA,CAA6B,KAAOF,CAAAA,EAC1EC,CAAAA,CAAI,IAAA,CAAK,CAAE,GAAIC,CAAAA,CAAG,OAAA,CAA8B,GAAIA,CAAAA,CAAG,EAAG,CAAC,CAAA,CAE/D,OAAOD,CACT,CAEA,SAASE,EAAeJ,CAAAA,CAAsBC,CAAAA,CAA8C,CAC1F,IAAMI,CAAAA,CAAMN,EAAYC,CAAAA,CAAOC,CAAM,CAAA,CACrC,OAAOI,EAAIA,CAAAA,CAAI,MAAA,CAAS,CAAC,CAC3B,CAEO,SAASC,CAAAA,CACdN,CAAAA,CACAO,CAAAA,CACAC,CAAAA,CACO,CACFA,CAAAA,CAAK,IAAA,EACRC,oBACE,cAAA,CACA,CAAA,MAAA,EAASD,EAAK,EAAE,CAAA,sBAAA,CAAA,CAChB,0CAAA,CACA,CAAE,MAAO,CAACA,CAAAA,CAAK,EAAE,CAAE,CACrB,EACF,IAAME,CAAAA,CAAOC,oBAAOX,CAAAA,CAAOQ,CAAAA,CAAK,IAAI,CAAA,CAC/BE,CAAAA,EACHD,oBACE,cAAA,CACA,CAAA,MAAA,EAASD,EAAK,IAAI,CAAA,gBAAA,CAAA,CAClB,CAAA,kBAAA,EAAqB,MAAA,CAAO,KAAKR,CAAAA,CAAM,KAAK,EAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAC1D,CAAA,CACF,IAAMY,CAAAA,CAA8B,EAAC,CAC/BC,CAAAA,CAAQ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AChB,KAAA,CAAOA,CAAAA,CAAI,KACb,CAAA,CACAiB,CACF,EACInD,CAAAA,CAAY,aAAA,GAAesD,EAAItD,CAAAA,CAAY,aAAA,CAAcsD,EAAGD,CAAAA,CAAIF,CAAE,GAC/D,CAAE,KAAA,CAAOG,EAAG,QAAA,CAAU,EAAG,CAClC","file":"chunk-NN3XJUHP.cjs","sourcesContent":["import { remaining } from \"./budget.ts\";\nimport { fail } from \"./errors.ts\";\nimport { stageOf } from \"./items.ts\";\nimport { openIteration, plan, type PlanOptions, type PlanReason, type Skipped } from \"./planner.ts\";\nimport { roleOf } from \"./roles.ts\";\nimport type { Brief, Handoff, Methodology, Verdict, WorkItem, WorkflowState } from \"./types.ts\";\n\ninterface CompletedPayload {\n id: string;\n role: string;\n verdict: Verdict;\n produced: Handoff[\"produced\"];\n notes: string;\n do_not: string[];\n}\n\nfunction completions(\n state: WorkflowState,\n itemId: string,\n): Array<CompletedPayload & { at: string }> {\n const out: Array<CompletedPayload & { at: string }> = [];\n for (const ev of state.events) {\n if (ev.type === \"item.completed\" && (ev.payload as CompletedPayload).id === itemId)\n out.push({ ...(ev.payload as CompletedPayload), at: ev.at });\n }\n return out;\n}\n\nfunction lastCompletion(state: WorkflowState, itemId: string): CompletedPayload | undefined {\n const all = completions(state, itemId);\n return all[all.length - 1];\n}\n\nexport function synthesizeBrief(\n state: WorkflowState,\n methodology: Methodology,\n item: WorkItem,\n): Brief {\n if (!item.role)\n fail(\n \"unknown-role\",\n `item \"${item.id}\" has no role assigned`,\n \"dispatch it with next() or set item.role\",\n { items: [item.id] },\n );\n const role = roleOf(state, item.role);\n if (!role)\n fail(\n \"unknown-role\",\n `role \"${item.role}\" does not exist`,\n `registered roles: ${Object.keys(state.roles).join(\", \")}`,\n );\n const upstream: Brief[\"upstream\"] = [];\n const doNot = [...role.do_not];\n const sources = [\n ...item.dependsOn,\n ...(item.type === \"bug\" || item.type === \"change-request\" ? (item.affects ?? []) : []),\n ];\n for (const dep of sources) {\n const p = lastCompletion(state, dep);\n if (!p) continue;\n upstream.push({ item: dep, produced: p.produced, notes: p.notes });\n for (const d of p.do_not) if (!doNot.includes(d)) doNot.push(d);\n }\n const priorHandoffs: Brief[\"priorHandoffs\"] = completions(state, item.id).map((p) => ({\n role: p.role,\n verdict: p.verdict,\n notes: p.notes,\n produced: p.produced,\n at: p.at,\n }));\n const touched = new Set([item.id, ...item.dependsOn]);\n const relatedBugs: Brief[\"relatedBugs\"] = Object.values(state.items)\n .filter(\n (b) =>\n (b.type === \"bug\" || b.type === \"change-request\") &&\n b.id !== item.id &&\n b.status !== \"done\" &&\n b.status !== \"dropped\" &&\n (b.affects ?? []).some((a) => touched.has(a)),\n )\n .map((b) => ({ id: b.id, title: b.title, affects: b.affects ?? [] }));\n const it = openIteration(state);\n const gate = stageOf(state, item.stage).gate;\n const brief: Brief = {\n item,\n role,\n modelTier: role.modelTier,\n invariants: [...methodology.invariants(state, item), ...state.agreements],\n do_not: doNot,\n acceptance: item.acceptance,\n upstream,\n priorHandoffs,\n relatedBugs,\n budgetRemaining: it ? remaining(it.budget, it.spent) : {},\n };\n if (gate) brief.gateAhead = gate;\n return brief;\n}\n\nexport interface NextResult {\n state: WorkflowState;\n briefs: Brief[];\n skipped: Skipped[];\n reason?: PlanReason;\n}\n\nexport function next(\n state: WorkflowState,\n methodology: Methodology,\n opts: PlanOptions = {},\n): NextResult {\n const res = plan(state, methodology, opts);\n const briefs = res.dispatched.map((d) =>\n synthesizeBrief(res.state, methodology, res.state.items[d.id]!),\n );\n return res.reason\n ? { state: res.state, briefs, skipped: res.skipped, reason: res.reason }\n : { state: res.state, briefs, skipped: res.skipped };\n}\n","import { addSpent } from \"./budget.ts\";\nimport { fail } from \"./errors.ts\";\nimport { checkGate, lastDispatchBefore, raisePending } from \"./gates.ts\";\nimport {\n addEvidence,\n addItem,\n advanceItem,\n clearRole,\n getItem,\n moveItem,\n patchItem,\n raiseBlocker,\n stageOf,\n} from \"./items.ts\";\nimport { assertPolicies } from \"./policies.ts\";\nimport { openIteration } from \"./planner.ts\";\nimport { rolesWith } from \"./roles.ts\";\nimport { appendEvent, nowOf } from \"./state.ts\";\nimport type {\n Accounting,\n ApplyResult,\n Handoff,\n Methodology,\n NewItem,\n WorkItem,\n WorkflowState,\n} from \"./types.ts\";\n\nconst VERDICTS: readonly string[] = [\"done\", \"needs-review\", \"rework\", \"blocked\", \"escalate\"];\nconst LESSON_SCOPES: readonly string[] = [\"policy\", \"skill\", \"memory\", \"spec\", \"review\"];\n\nconst isObj = (x: unknown): x is Record<string, unknown> =>\n typeof x === \"object\" && x !== null && !Array.isArray(x);\nconst str = (x: unknown) => typeof x === \"string\";\n\nfunction validate(state: WorkflowState, handoff: Handoff, acc: Accounting): void {\n const item = getItem(state, handoff.item);\n if (item.status !== \"in_progress\")\n fail(\n \"invalid-transition\",\n `item \"${item.id}\" is ${item.status}, not in_progress`,\n \"only dispatched items can be completed; call next() first\",\n { items: [item.id] },\n );\n if (!Array.isArray(handoff.do_not))\n fail(\n \"handoff-invalid\",\n `handoff for \"${item.id}\" has no do_not array`,\n \"set handoff.do_not to [] when there is nothing to forbid\",\n { items: [item.id] },\n );\n if (!Array.isArray(handoff.produced) || !Array.isArray(handoff.open_questions))\n fail(\n \"handoff-invalid\",\n `handoff for \"${item.id}\" needs produced[] and open_questions[]`,\n \"pass empty arrays when there is nothing\",\n { items: [item.id] },\n );\n const bad = (what: string, fix: string) =>\n fail(\"handoff-invalid\", `handoff for \"${item.id}\": ${what}`, fix, { items: [item.id] });\n const verdict = handoff.verdict ?? \"done\";\n if (!VERDICTS.includes(verdict))\n bad(`unknown verdict ${JSON.stringify(verdict)}`, `use one of: ${VERDICTS.join(\", \")}`);\n if (!handoff.produced.every((p) => isObj(p) && str(p.kind) && str(p.ref)))\n bad(\"produced[] entries need string kind and ref\", 'use { \"kind\": \"code\", \"ref\": \"src/a.ts\" }');\n const lessons: unknown = handoff.lessons ?? [];\n if (\n !Array.isArray(lessons) ||\n !lessons.every((l) => isObj(l) && str(l.text) && LESSON_SCOPES.includes(l.scope as string))\n )\n bad(\n \"lessons[] entries need a text and a scope\",\n `scope is one of: ${LESSON_SCOPES.join(\", \")}`,\n );\n const followUps: unknown = handoff.follow_ups ?? [];\n if (!Array.isArray(followUps) || !followUps.every((f) => isObj(f) && str(f.id) && str(f.title)))\n bad(\"follow_ups[] entries need a string id and title\", \"describe each follow-up as a new item\");\n if (handoff.role !== item.role)\n fail(\n \"handoff-invalid\",\n `handoff role \"${handoff.role}\" differs from the dispatched role \"${item.role}\"`,\n `complete as \"${item.role}\" or re-dispatch`,\n { items: [item.id] },\n );\n if (!acc.model || acc.model.trim() === \"\")\n fail(\n \"accounting-invalid\",\n `accounting for \"${item.id}\" has no model`,\n \"record the model id that actually ran the work\",\n { items: [item.id] },\n );\n for (const k of [\"tokensIn\", \"tokensOut\", \"durationMs\"] as const) {\n if (!Number.isFinite(acc[k]) || acc[k] < 0)\n fail(\n \"accounting-invalid\",\n `accounting.${k} must be a non-negative number`,\n `measure ${k} from the host's usage report`,\n { items: [item.id] },\n );\n }\n}\n\n/** Stage the item was pulled from: the `from.stage` of its last transition into in_progress, else its current stage. */\nfunction pulledFromStage(item: WorkItem): string {\n for (let i = item.transitions.length - 1; i >= 0; i--) {\n const t = item.transitions[i]!;\n if (t.to.status === \"in_progress\") return t.from.stage;\n }\n return item.stage;\n}\n\n/** Stage a reworked item returns to: the from.stage of the last dispatch made from a stage strictly before the current one (so a reviewer's rework lands where the work was pulled from), else the plain pulled-from stage. */\nfunction reworkStage(state: WorkflowState, item: WorkItem): string {\n return lastDispatchBefore(state, item)?.from.stage ?? pulledFromStage(item);\n}\n\nexport function complete(\n state: WorkflowState,\n methodology: Methodology,\n handoff: Handoff,\n acc: Accounting,\n now?: string,\n): ApplyResult {\n validate(state, handoff, acc);\n const at = nowOf(now);\n const id = handoff.item;\n const role = handoff.role;\n let s: WorkflowState = { ...state, accounting: [...state.accounting, acc] };\n for (const p of handoff.produced)\n s = addEvidence(s, id, { kind: p.kind, ref: p.ref, by: role }, at);\n const it = openIteration(s);\n if (it && (it.committed.includes(id) || getItem(s, id).iteration === it.id)) {\n s = {\n ...s,\n iterations: s.iterations.map((x) =>\n x.id === it.id ? { ...x, spent: addSpent(x.spent, acc) } : x,\n ),\n };\n }\n\n for (const l of handoff.lessons ?? []) {\n const lid = `L${s.lessons.length + 1}`;\n s = {\n ...s,\n lessons: [\n ...s.lessons,\n { id: lid, at, text: l.text, scope: l.scope, status: \"raised\", from: role, item: id },\n ],\n };\n s = appendEvent(\n s,\n \"lesson.raised\",\n role,\n { id: lid, from: role, item: id, scope: l.scope },\n at,\n );\n }\n\n const followUps: string[] = [];\n for (const n of handoff.follow_ups ?? []) {\n const first = s.stages[0]!;\n const { iteration: _drop, ...rest } = n;\n s = addItem(\n s,\n { ...rest, stage: first.id, parent: id, tags: [...(n.tags ?? []), \"follow-up\"] },\n role,\n at,\n );\n followUps.push(n.id);\n }\n\n const verdict = handoff.verdict ?? \"done\";\n if (verdict === \"rework\") {\n if (!handoff.notes || handoff.notes.trim() === \"\")\n fail(\n \"handoff-invalid\",\n `rework on \"${id}\" needs notes`,\n \"say what must change in handoff.notes\",\n { items: [id] },\n );\n const item = getItem(s, id);\n s = clearRole(moveItem(s, id, { stage: reworkStage(s, item), status: \"todo\" }, role, at), id);\n s = appendEvent(s, \"item.rework\", role, { id, by: role, notes: handoff.notes }, at);\n } else if (\n (verdict === \"done\" || verdict === \"needs-review\") &&\n getItem(s, id).type === \"question\"\n ) {\n // a question is answered, not delivered: it skips exit policies and gates\n const lastStageId = s.stages[s.stages.length - 1]!.id;\n s = moveItem(s, id, { stage: lastStageId, status: \"done\" }, role, at);\n } else if (verdict === \"done\" || verdict === \"needs-review\") {\n const item = getItem(s, id);\n const stage = stageOf(s, item.stage);\n assertPolicies(s, item, stage.exitPolicy, `leave \"${stage.id}\"`);\n if (stage.gate) {\n const res = checkGate(s, item, stage.gate, role);\n if (res.outcome === \"fail\")\n fail(\n \"gate-unmet\",\n `gate \"${stage.gate.id}\" blocks \"${id}\": ${res.violations.map((v) => v.message).join(\"; \")}`,\n res.violations.map((v) => v.fix).join(\"; \"),\n { items: [id], rule: res.violations[0]!.rule },\n );\n if (res.outcome === \"human\") {\n s = raisePending(\n s,\n {\n kind: \"gate\",\n item: id,\n gate: stage.gate.id,\n question: `Approve gate \"${stage.gate.id}\" for \"${item.title}\" (${id})?`,\n },\n at,\n );\n } else {\n s = appendEvent(\n advanceItem(s, id, role, verdict === \"needs-review\", at),\n \"gate.passed\",\n role,\n { item: id, gate: stage.gate.id },\n at,\n );\n }\n } else {\n s = advanceItem(s, id, role, verdict === \"needs-review\", at);\n }\n } else if (verdict === \"blocked\") {\n s = raiseBlocker(s, id, handoff.notes || \"blocked by worker\", role, role, at);\n } else if (verdict === \"escalate\") {\n const thinker = rolesWith(s, \"escalate\")[0];\n if (!thinker)\n fail(\n \"missing-capability\",\n `no role has capability \"escalate\" to receive the question from \"${id}\"`,\n \"register a role with capability escalate\",\n { items: [id] },\n );\n const n = Object.keys(s.items).filter((k) => k.startsWith(`${id}-q`)).length + 1;\n const qid = `${id}-q${n}`;\n const parent = getItem(s, id);\n const pulledFrom = pulledFromStage(parent);\n const q: NewItem = {\n id: qid,\n type: \"question\",\n title: handoff.open_questions.join(\" | \") || handoff.notes || `question from ${id}`,\n parent: id,\n role: thinker.id,\n priority: Number.MAX_SAFE_INTEGER,\n stage: pulledFrom,\n };\n if (parent.iteration !== undefined) q.iteration = parent.iteration;\n s = addItem(s, q, role, at);\n s = moveItem(s, id, { stage: pulledFrom, status: \"todo\" }, role, at);\n s = patchItem(s, id, (x) => ({ ...x, dependsOn: [...x.dependsOn, qid] }));\n s = appendEvent(s, \"item.escalated\", role, { id, question: qid, to: thinker.id }, at);\n }\n\n s = appendEvent(\n s,\n \"item.completed\",\n role,\n {\n id,\n role,\n verdict,\n produced: handoff.produced,\n notes: handoff.notes,\n do_not: handoff.do_not,\n open_questions: handoff.open_questions,\n followUps,\n tokens: acc.tokensIn + acc.tokensOut,\n durationMs: acc.durationMs,\n model: acc.model,\n },\n at,\n );\n if (methodology.afterComplete) s = methodology.afterComplete(s, id, at);\n return { state: s, warnings: [] };\n}\n"]}
1
+ {"version":3,"sources":["../src/brief.ts","../src/complete.ts"],"names":["completions","state","itemId","out","ev","lastCompletion","all","synthesizeBrief","methodology","item","fail","role","roleOf","upstream","doNot","sources","dep","p","d","priorHandoffs","touched","relatedBugs","b","a","it","openIteration","gate","stageOf","brief","remaining","next","opts","res","plan","briefs","VERDICTS","LESSON_SCOPES","isObj","x","str","validate","handoff","acc","getItem","bad","what","fix","verdict","lessons","l","followUps","f","k","pulledFromStage","i","reworkStage","lastDispatchBefore","complete","now","at","nowOf","id","s","addEvidence","addSpent","lid","appendEvent","n","first","_drop","rest","addItem","clearRole","moveItem","lastStageId","stage","assertPolicies","checkGate","v","raisePending","advanceItem","raiseBlocker","thinker","rolesWith","qid","parent","pulledFrom","q","patchItem"],"mappings":"uKAgBA,SAASA,EACPC,CAAAA,CACAC,CAAAA,CAC0C,CAC1C,IAAMC,CAAAA,CAAgD,EAAC,CACvD,IAAA,IAAWC,CAAAA,IAAMH,CAAAA,CAAM,OACjBG,CAAAA,CAAG,IAAA,GAAS,kBAAqBA,CAAAA,CAAG,OAAA,CAA6B,KAAOF,CAAAA,EAC1EC,CAAAA,CAAI,IAAA,CAAK,CAAE,GAAIC,CAAAA,CAAG,OAAA,CAA8B,GAAIA,CAAAA,CAAG,EAAG,CAAC,CAAA,CAE/D,OAAOD,CACT,CAEA,SAASE,EAAeJ,CAAAA,CAAsBC,CAAAA,CAA8C,CAC1F,IAAMI,CAAAA,CAAMN,EAAYC,CAAAA,CAAOC,CAAM,CAAA,CACrC,OAAOI,EAAIA,CAAAA,CAAI,MAAA,CAAS,CAAC,CAC3B,CAEO,SAASC,CAAAA,CACdN,CAAAA,CACAO,CAAAA,CACAC,CAAAA,CACO,CACFA,CAAAA,CAAK,IAAA,EACRC,oBACE,cAAA,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AAAA,CAAK,EAAA,CAAIF,EAAQ,EAAG,CAAA,CAAGvB,CAAE,EACtF,CAEA,OAAAG,CAAAA,CAAII,mBAAAA,CACFJ,EACA,gBAAA,CACAnD,CAAAA,CACA,CACE,EAAA,CAAAkD,CAAAA,CACA,KAAAlD,CAAAA,CACA,OAAA,CAAAoC,CAAAA,CACA,QAAA,CAAUN,EAAQ,QAAA,CAClB,KAAA,CAAOA,EAAQ,KAAA,CACf,MAAA,CAAQA,EAAQ,MAAA,CAChB,cAAA,CAAgBA,EAAQ,cAAA,CACxB,SAAA,CAAAS,EACA,MAAA,CAAQR,CAAAA,CAAI,SAAWA,CAAAA,CAAI,SAAA,CAC3B,WAAYA,CAAAA,CAAI,UAAA,CAChB,KAAA,CAAOA,CAAAA,CAAI,KACb,CAAA,CACAiB,CACF,EACInD,CAAAA,CAAY,aAAA,GAAesD,EAAItD,CAAAA,CAAY,aAAA,CAAcsD,EAAGD,CAAAA,CAAIF,CAAE,GAC/D,CAAE,KAAA,CAAOG,EAAG,QAAA,CAAU,EAAG,CAClC","file":"chunk-HHC5EZ54.cjs","sourcesContent":["import { remaining } from \"./budget.ts\";\nimport { fail } from \"./errors.ts\";\nimport { stageOf } from \"./items.ts\";\nimport { openIteration, plan, type PlanOptions, type PlanReason, type Skipped } from \"./planner.ts\";\nimport { roleOf } from \"./roles.ts\";\nimport type { Brief, Handoff, Methodology, Verdict, WorkItem, WorkflowState } from \"./types.ts\";\n\ninterface CompletedPayload {\n id: string;\n role: string;\n verdict: Verdict;\n produced: Handoff[\"produced\"];\n notes: string;\n do_not: string[];\n}\n\nfunction completions(\n state: WorkflowState,\n itemId: string,\n): Array<CompletedPayload & { at: string }> {\n const out: Array<CompletedPayload & { at: string }> = [];\n for (const ev of state.events) {\n if (ev.type === \"item.completed\" && (ev.payload as CompletedPayload).id === itemId)\n out.push({ ...(ev.payload as CompletedPayload), at: ev.at });\n }\n return out;\n}\n\nfunction lastCompletion(state: WorkflowState, itemId: string): CompletedPayload | undefined {\n const all = completions(state, itemId);\n return all[all.length - 1];\n}\n\nexport function synthesizeBrief(\n state: WorkflowState,\n methodology: Methodology,\n item: WorkItem,\n): Brief {\n if (!item.role)\n fail(\n \"unknown-role\",\n `item \"${item.id}\" has no role assigned`,\n \"dispatch it with next() or set item.role\",\n { items: [item.id] },\n );\n const role = roleOf(state, item.role);\n if (!role)\n fail(\n \"unknown-role\",\n `role \"${item.role}\" does not exist`,\n `registered roles: ${Object.keys(state.roles).join(\", \")}`,\n );\n const upstream: Brief[\"upstream\"] = [];\n const doNot = [...role.do_not];\n const sources = [\n ...item.dependsOn,\n ...(item.type === \"bug\" || item.type === \"change-request\" ? (item.affects ?? []) : []),\n ];\n for (const dep of sources) {\n const p = lastCompletion(state, dep);\n if (!p) continue;\n upstream.push({ item: dep, produced: p.produced, notes: p.notes });\n for (const d of p.do_not) if (!doNot.includes(d)) doNot.push(d);\n }\n const priorHandoffs: Brief[\"priorHandoffs\"] = completions(state, item.id).map((p) => ({\n role: p.role,\n verdict: p.verdict,\n notes: p.notes,\n produced: p.produced,\n at: p.at,\n }));\n const touched = new Set([item.id, ...item.dependsOn]);\n const relatedBugs: Brief[\"relatedBugs\"] = Object.values(state.items)\n .filter(\n (b) =>\n (b.type === \"bug\" || b.type === \"change-request\") &&\n b.id !== item.id &&\n b.status !== \"done\" &&\n b.status !== \"dropped\" &&\n (b.affects ?? []).some((a) => touched.has(a)),\n )\n .map((b) => ({ id: b.id, title: b.title, affects: b.affects ?? [] }));\n const it = openIteration(state);\n const gate = stageOf(state, item.stage).gate;\n const brief: Brief = {\n item,\n role,\n modelTier: role.modelTier,\n invariants: [...methodology.invariants(state, item), ...state.agreements],\n do_not: doNot,\n acceptance: item.acceptance,\n upstream,\n priorHandoffs,\n relatedBugs,\n budgetRemaining: it ? remaining(it.budget, it.spent) : {},\n };\n if (gate) brief.gateAhead = gate;\n return brief;\n}\n\nexport interface NextResult {\n state: WorkflowState;\n briefs: Brief[];\n skipped: Skipped[];\n reason?: PlanReason;\n}\n\nexport function next(\n state: WorkflowState,\n methodology: Methodology,\n opts: PlanOptions = {},\n): NextResult {\n const res = plan(state, methodology, opts);\n const briefs = res.dispatched.map((d) =>\n synthesizeBrief(res.state, methodology, res.state.items[d.id]!),\n );\n return res.reason\n ? { state: res.state, briefs, skipped: res.skipped, reason: res.reason }\n : { state: res.state, briefs, skipped: res.skipped };\n}\n","import { addSpent } from \"./budget.ts\";\nimport { fail } from \"./errors.ts\";\nimport { checkGate, lastDispatchBefore, raisePending } from \"./gates.ts\";\nimport {\n addEvidence,\n addItem,\n advanceItem,\n clearRole,\n getItem,\n moveItem,\n patchItem,\n raiseBlocker,\n stageOf,\n} from \"./items.ts\";\nimport { assertPolicies } from \"./policies.ts\";\nimport { openIteration } from \"./planner.ts\";\nimport { rolesWith } from \"./roles.ts\";\nimport { appendEvent, nowOf } from \"./state.ts\";\nimport type {\n Accounting,\n ApplyResult,\n Handoff,\n Methodology,\n NewItem,\n WorkItem,\n WorkflowState,\n} from \"./types.ts\";\n\nconst VERDICTS: readonly string[] = [\"done\", \"needs-review\", \"rework\", \"blocked\", \"escalate\"];\nconst LESSON_SCOPES: readonly string[] = [\"policy\", \"skill\", \"memory\", \"spec\", \"review\"];\n\nconst isObj = (x: unknown): x is Record<string, unknown> =>\n typeof x === \"object\" && x !== null && !Array.isArray(x);\nconst str = (x: unknown) => typeof x === \"string\";\n\nfunction validate(state: WorkflowState, handoff: Handoff, acc: Accounting): void {\n const item = getItem(state, handoff.item);\n if (item.status !== \"in_progress\")\n fail(\n \"invalid-transition\",\n `item \"${item.id}\" is ${item.status}, not in_progress`,\n \"only dispatched items can be completed; call next() first\",\n { items: [item.id] },\n );\n if (!Array.isArray(handoff.do_not))\n fail(\n \"handoff-invalid\",\n `handoff for \"${item.id}\" has no do_not array`,\n \"set handoff.do_not to [] when there is nothing to forbid\",\n { items: [item.id] },\n );\n if (!Array.isArray(handoff.produced) || !Array.isArray(handoff.open_questions))\n fail(\n \"handoff-invalid\",\n `handoff for \"${item.id}\" needs produced[] and open_questions[]`,\n \"pass empty arrays when there is nothing\",\n { items: [item.id] },\n );\n const bad = (what: string, fix: string) =>\n fail(\"handoff-invalid\", `handoff for \"${item.id}\": ${what}`, fix, { items: [item.id] });\n const verdict = handoff.verdict ?? \"done\";\n if (!VERDICTS.includes(verdict))\n bad(`unknown verdict ${JSON.stringify(verdict)}`, `use one of: ${VERDICTS.join(\", \")}`);\n if (!handoff.produced.every((p) => isObj(p) && str(p.kind) && str(p.ref)))\n bad(\"produced[] entries need string kind and ref\", 'use { \"kind\": \"code\", \"ref\": \"src/a.ts\" }');\n const lessons: unknown = handoff.lessons ?? [];\n if (\n !Array.isArray(lessons) ||\n !lessons.every((l) => isObj(l) && str(l.text) && LESSON_SCOPES.includes(l.scope as string))\n )\n bad(\n \"lessons[] entries need a text and a scope\",\n `scope is one of: ${LESSON_SCOPES.join(\", \")}`,\n );\n const followUps: unknown = handoff.follow_ups ?? [];\n if (!Array.isArray(followUps) || !followUps.every((f) => isObj(f) && str(f.id) && str(f.title)))\n bad(\"follow_ups[] entries need a string id and title\", \"describe each follow-up as a new item\");\n if (handoff.role !== item.role)\n fail(\n \"handoff-invalid\",\n `handoff role \"${handoff.role}\" differs from the dispatched role \"${item.role}\"`,\n `complete as \"${item.role}\" or re-dispatch`,\n { items: [item.id] },\n );\n if (!acc.model || acc.model.trim() === \"\")\n fail(\n \"accounting-invalid\",\n `accounting for \"${item.id}\" has no model`,\n \"record the model id that actually ran the work\",\n { items: [item.id] },\n );\n for (const k of [\"tokensIn\", \"tokensOut\", \"durationMs\"] as const) {\n if (!Number.isFinite(acc[k]) || acc[k] < 0)\n fail(\n \"accounting-invalid\",\n `accounting.${k} must be a non-negative number`,\n `measure ${k} from the host's usage report`,\n { items: [item.id] },\n );\n }\n}\n\n/** Stage the item was pulled from: the `from.stage` of its last transition into in_progress, else its current stage. */\nfunction pulledFromStage(item: WorkItem): string {\n for (let i = item.transitions.length - 1; i >= 0; i--) {\n const t = item.transitions[i]!;\n if (t.to.status === \"in_progress\") return t.from.stage;\n }\n return item.stage;\n}\n\n/** Stage a reworked item returns to: the from.stage of the last dispatch made from a stage strictly before the current one (so a reviewer's rework lands where the work was pulled from), else the plain pulled-from stage. */\nfunction reworkStage(state: WorkflowState, item: WorkItem): string {\n return lastDispatchBefore(state, item)?.from.stage ?? pulledFromStage(item);\n}\n\nexport function complete(\n state: WorkflowState,\n methodology: Methodology,\n handoff: Handoff,\n acc: Accounting,\n now?: string,\n): ApplyResult {\n validate(state, handoff, acc);\n const at = nowOf(now);\n const id = handoff.item;\n const role = handoff.role;\n let s: WorkflowState = { ...state, accounting: [...state.accounting, acc] };\n for (const p of handoff.produced)\n s = addEvidence(s, id, { kind: p.kind, ref: p.ref, by: role }, at);\n const it = openIteration(s);\n if (it && (it.committed.includes(id) || getItem(s, id).iteration === it.id)) {\n s = {\n ...s,\n iterations: s.iterations.map((x) =>\n x.id === it.id ? { ...x, spent: addSpent(x.spent, acc) } : x,\n ),\n };\n }\n\n for (const l of handoff.lessons ?? []) {\n const lid = `L${s.lessons.length + 1}`;\n s = {\n ...s,\n lessons: [\n ...s.lessons,\n { id: lid, at, text: l.text, scope: l.scope, status: \"raised\", from: role, item: id },\n ],\n };\n s = appendEvent(\n s,\n \"lesson.raised\",\n role,\n { id: lid, from: role, item: id, scope: l.scope },\n at,\n );\n }\n\n const followUps: string[] = [];\n for (const n of handoff.follow_ups ?? []) {\n const first = s.stages[0]!;\n const { iteration: _drop, ...rest } = n;\n s = addItem(\n s,\n { ...rest, stage: first.id, parent: id, tags: [...(n.tags ?? []), \"follow-up\"] },\n role,\n at,\n );\n followUps.push(n.id);\n }\n\n const verdict = handoff.verdict ?? \"done\";\n if (verdict === \"rework\") {\n if (!handoff.notes || handoff.notes.trim() === \"\")\n fail(\n \"handoff-invalid\",\n `rework on \"${id}\" needs notes`,\n \"say what must change in handoff.notes\",\n { items: [id] },\n );\n const item = getItem(s, id);\n s = clearRole(moveItem(s, id, { stage: reworkStage(s, item), status: \"todo\" }, role, at), id);\n s = appendEvent(s, \"item.rework\", role, { id, by: role, notes: handoff.notes }, at);\n } else if (\n (verdict === \"done\" || verdict === \"needs-review\") &&\n getItem(s, id).type === \"question\"\n ) {\n // a question is answered, not delivered: it skips exit policies and gates\n const lastStageId = s.stages[s.stages.length - 1]!.id;\n s = moveItem(s, id, { stage: lastStageId, status: \"done\" }, role, at);\n } else if (verdict === \"done\" || verdict === \"needs-review\") {\n const item = getItem(s, id);\n const stage = stageOf(s, item.stage);\n assertPolicies(s, item, stage.exitPolicy, `leave \"${stage.id}\"`);\n if (stage.gate) {\n const res = checkGate(s, item, stage.gate, role);\n if (res.outcome === \"fail\")\n fail(\n \"gate-unmet\",\n `gate \"${stage.gate.id}\" blocks \"${id}\": ${res.violations.map((v) => v.message).join(\"; \")}`,\n res.violations.map((v) => v.fix).join(\"; \"),\n { items: [id], rule: res.violations[0]!.rule },\n );\n if (res.outcome === \"human\") {\n s = raisePending(\n s,\n {\n kind: \"gate\",\n item: id,\n gate: stage.gate.id,\n question: `Approve gate \"${stage.gate.id}\" for \"${item.title}\" (${id})?`,\n },\n at,\n );\n } else {\n s = appendEvent(\n advanceItem(s, id, role, verdict === \"needs-review\", at),\n \"gate.passed\",\n role,\n { item: id, gate: stage.gate.id },\n at,\n );\n }\n } else {\n s = advanceItem(s, id, role, verdict === \"needs-review\", at);\n }\n } else if (verdict === \"blocked\") {\n s = raiseBlocker(s, id, handoff.notes || \"blocked by worker\", role, role, at);\n } else if (verdict === \"escalate\") {\n const thinker = rolesWith(s, \"escalate\")[0];\n if (!thinker)\n fail(\n \"missing-capability\",\n `no role has capability \"escalate\" to receive the question from \"${id}\"`,\n \"register a role with capability escalate\",\n { items: [id] },\n );\n const n = Object.keys(s.items).filter((k) => k.startsWith(`${id}-q`)).length + 1;\n const qid = `${id}-q${n}`;\n const parent = getItem(s, id);\n const pulledFrom = pulledFromStage(parent);\n const q: NewItem = {\n id: qid,\n type: \"question\",\n title: handoff.open_questions.join(\" | \") || handoff.notes || `question from ${id}`,\n parent: id,\n role: thinker.id,\n priority: Number.MAX_SAFE_INTEGER,\n stage: pulledFrom,\n };\n if (parent.iteration !== undefined) q.iteration = parent.iteration;\n s = addItem(s, q, role, at);\n s = moveItem(s, id, { stage: pulledFrom, status: \"todo\" }, role, at);\n s = patchItem(s, id, (x) => ({ ...x, dependsOn: [...x.dependsOn, qid] }));\n s = appendEvent(s, \"item.escalated\", role, { id, question: qid, to: thinker.id }, at);\n }\n\n s = appendEvent(\n s,\n \"item.completed\",\n role,\n {\n id,\n role,\n verdict,\n produced: handoff.produced,\n notes: handoff.notes,\n do_not: handoff.do_not,\n open_questions: handoff.open_questions,\n followUps,\n tokens: acc.tokensIn + acc.tokensOut,\n durationMs: acc.durationMs,\n model: acc.model,\n },\n at,\n );\n if (methodology.afterComplete) s = methodology.afterComplete(s, id, at);\n return { state: s, warnings: [] };\n}\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var chunk2IKIBB73_cjs=require('./chunk-2IKIBB73.cjs'),chunk23P7C25E_cjs=require('./chunk-23P7C25E.cjs'),chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs'),exsorted=require('exsorted');var je=["requirements","design","implementation","verification","deployment","maintenance"],se={requirements:["srs"],design:["design-doc","interface-spec"],implementation:["code-baseline"],verification:["test-report","traceability-matrix"],deployment:["release-notes","deployment-record"],maintenance:["change-log"]},oe={requirements:"business-analyst",design:"architect",deployment:"release-manager"},ae=e=>`${e}-gate`,de="change-control",Ie=["order-backlog","define-acceptance","facilitate","deliver","review","verify","approve-gate","manage-flow","control-change","escalate"],Ee=e=>e.charAt(0).toUpperCase()+e.slice(1);function Te(){return je.map(e=>{let t={id:e,name:Ee(e),deliverables:[...se[e]??[]],gate:{id:ae(e),requires:[{capability:"approve-gate"}],evidence:[],onFail:{action:"block"}}},i=oe[e];return i!==void 0&&(t.deliverBy=i),t})}function k(e){return e.config}var j=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),X=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.trim()!=="");function Ke(e,t){if(e===void 0)return;j(e)||chunkS3BXVHO7_cjs.b("config-invalid",`${t}.budget must be an object`,'e.g. { "tokens": 400000 }');let i={};for(let s of ["tokens","turns","wallclockMs"]){let f=e[s];f!==void 0&&((typeof f!="number"||!Number.isFinite(f)||f<0)&&chunkS3BXVHO7_cjs.b("config-invalid",`${t}.budget.${s} must be a non-negative number`,"omit it for no limit"),i[s]=f);}return i}function De(e,t){return (!Array.isArray(e)||e.length===0)&&chunkS3BXVHO7_cjs.b("config-invalid",`${t} must be a non-empty array of "human" | { capability }`,'e.g. ["human", { "capability": "approve-gate" }]'),e.map(i=>i==="human"?"human":j(i)&&typeof i.capability=="string"&&Ie.includes(i.capability)?{capability:i.capability}:chunkS3BXVHO7_cjs.b("config-invalid",`${t} entry ${JSON.stringify(i)} is not "human" or a known capability`,`use "human" or { "capability": one of ${Ie.join(", ")} }`))}function Oe(e,t,i){let s=`waterfall config.phases[${t}]`;j(e)||chunkS3BXVHO7_cjs.b("config-invalid",`${s} must be an object`,'e.g. { "id": "design" }'),chunkS3BXVHO7_cjs.c(e.id,`${s}.id`);let f=e.id,d=e.deliverables??se[f]??[];X(d)||chunkS3BXVHO7_cjs.b("config-invalid",`${s}.deliverables must be a string[] of evidence kinds`,'e.g. ["srs"]');let a;if(e.gate===void 0)a={id:ae(f),requires:[{capability:"approve-gate"}],evidence:[],onFail:{action:"block"}};else {let c=e.gate;(!j(c)||typeof c.id!="string"||c.id.trim()==="")&&chunkS3BXVHO7_cjs.b("config-invalid",`${s}.gate must be a Gate with an id`,'e.g. { "id": "design-gate", "requires": [{ "capability": "approve-gate" }], "evidence": [] }');let l=c.evidence??[];X(l)||chunkS3BXVHO7_cjs.b("config-invalid",`${s}.gate.evidence must be a string[]`,"list evidence kinds or omit it"),a={id:c.id,requires:De(c.requires??[{capability:"approve-gate"}],`${s}.gate.requires`),evidence:[...l],onFail:{action:"block"}};}i(f)&&!a.requires.includes("human")&&(a.requires=["human",...a.requires]);let n={id:f,name:typeof e.name=="string"&&e.name.trim()!==""?e.name:Ee(f),deliverables:[...d],gate:a},r=Ke(e.budget,s);r!==void 0&&(n.budget=r);let o=e.deliverBy??oe[f];return o!==void 0&&((typeof o!="string"||o.trim()==="")&&chunkS3BXVHO7_cjs.b("config-invalid",`${s}.deliverBy must be a role id`,"name the role that delivers this phase or omit it"),n.deliverBy=o),n}function ce(e){let t=e??{};t.phases!==void 0&&!Array.isArray(t.phases)&&chunkS3BXVHO7_cjs.b("config-invalid","waterfall config.phases must be an array of phases","omit phases for the six classic phases");let i=t.humanGates??"all";i!=="all"&&!X(i)&&chunkS3BXVHO7_cjs.b("config-invalid",'waterfall config.humanGates must be "all" or a string[] of phase ids','omit it for "all"');let s=i==="all"?()=>true:l=>i.includes(l),f=t.phases===void 0?Te().map((l,u)=>Oe(l,u,s)):t.phases.map((l,u)=>Oe(l,u,s));f.length===0&&chunkS3BXVHO7_cjs.b("config-invalid","waterfall config.phases needs at least one phase",'e.g. [{ "id": "requirements" }]');let d=f.map(l=>l.id),a=d.find((l,u)=>d.indexOf(l)!==u);if(a!==void 0&&chunkS3BXVHO7_cjs.b("config-invalid",`duplicate phase id "${a}"`,"give every phase a unique id"),i!=="all")for(let l of i)d.includes(l)||chunkS3BXVHO7_cjs.b("config-invalid",`waterfall config.humanGates names unknown phase "${l}"`,`phases are: ${d.join(", ")}`);let n=t.changeControl??{};j(n)||chunkS3BXVHO7_cjs.b("config-invalid","waterfall config.changeControl must be an object",'e.g. { "requiresImpactAnalysis": true, "approvers": ["human"] }'),n.requiresImpactAnalysis!==void 0&&typeof n.requiresImpactAnalysis!="boolean"&&chunkS3BXVHO7_cjs.b("config-invalid","waterfall config.changeControl.requiresImpactAnalysis must be a boolean","omit it for true");let r={requiresImpactAnalysis:n.requiresImpactAnalysis===void 0?true:n.requiresImpactAnalysis,approvers:De(n.approvers??["human",{capability:"control-change"}],"waterfall config.changeControl.approvers")},o=t.traceability,c;if(o===void 0)c=d.includes("requirements")&&d.includes("design")&&d.includes("verification")?{from:"requirements",to:["design","verification"]}:{from:d[0],to:[]};else {(!j(o)||typeof o.from!="string"||!d.includes(o.from))&&chunkS3BXVHO7_cjs.b("config-invalid","waterfall config.traceability.from must be a phase id",`phases are: ${d.join(", ")}`);let l=o.to??[];X(l)||chunkS3BXVHO7_cjs.b("config-invalid","waterfall config.traceability.to must be a string[] of phase ids",`phases are: ${d.join(", ")}`);for(let u of l)d.includes(u)||chunkS3BXVHO7_cjs.b("config-invalid",`waterfall config.traceability.to names unknown phase "${u}"`,`phases are: ${d.join(", ")}`),d.indexOf(u)<=d.indexOf(o.from)&&chunkS3BXVHO7_cjs.b("config-invalid",`waterfall config.traceability.to phase "${u}" must come after "${o.from}"`,"trace forward only: from an earlier phase to later ones");c={from:o.from,to:[...l]};}return {phases:f,changeControl:r,traceability:c,humanGates:i==="all"?"all":[...i]}}var L="work",_="review",M="done";function b(e){return e.phases?e.phases:k(e).phases.map(t=>{let i={id:t.id,name:t.name,deliverables:[...t.deliverables],gate:t.gate,status:"pending"};return t.budget&&(i.budget=t.budget),i})}function S(e,t){return {...e,phases:t}}function I(e,t){let i=b(e).findIndex(s=>s.id===t);return i<0&&chunkS3BXVHO7_cjs.b("config-invalid",`unknown phase "${t}"`,`phases are: ${b(e).map(s=>s.id).join(" \u2192 ")}`),i}function E(e,t){return b(e)[I(e,t)]}function R(e,t){let i=new Set,s=t;for(;s&&!i.has(s.id);){if(s.phase!==void 0)return s.phase;i.add(s.id),s=s.parent!==void 0&&Object.hasOwn(e.items,s.parent)?e.items[s.parent]:void 0;}}function A(e,t){return Object.values(e.items).filter(i=>i.status!=="dropped"&&R(e,i)===t)}function O(e){return b(e).find(t=>t.status==="open")}function le(e){return b(e).find(t=>t.status!=="baselined")}function Ye(e,t){let i=R(e,t);return i!==void 0&&b(e).find(s=>s.id===i)?.status==="baselined"}function Be(e,t){let i=new Set((t.produced??[]).map(s=>s.kind));for(let s of A(e,t.id))for(let f of s.evidence)i.add(f.kind);return i}function G(e,t,i=[]){let s=Be(e,t);for(let d of i)s.add(d);let f=[];for(let d of [...t.deliverables,...t.gate.evidence])f.includes(d)||f.push(d);return f.filter(d=>!s.has(d))}function N(e){let t=b(e).map(s=>s.id),i=k(e).traceability.to.filter(s=>t.includes(s));if(i.length!==0)return i.reduce((s,f)=>t.indexOf(s)>=t.indexOf(f)?s:f)}function Le(e,t,i,s){let f=chunk2IKIBB73_cjs.f(e);return !f||!f.id.startsWith(`${t}#`)?e:{...e,iterations:e.iterations.map(d=>d.id===f.id?{...d,endedAt:s,outcome:i}:d)}}function ee(e,t,i,s){let f=E(e,t);f.status!=="open"&&chunkS3BXVHO7_cjs.b("invalid-transition",`phase "${t}" is ${f.status}, not open`,f.status==="baselined"?"it is already baselined; a change-request reopens it":"kickoff the phase first");let d=A(e,t),a={};for(let c of d)a[c.id]=c;let n=(e.baselines??[]).filter(c=>c.phase===t).length,r={phase:t,version:n+1,at:s,approvedBy:i,itemSnapshot:a},o=S(e,b(e).map(c=>c.id===t?{...c,status:"baselined"}:c));return o={...o,baseline:r,baselines:[...o.baselines??[],r]},o=Le(o,t,"completed",s),chunk23P7C25E_cjs.c(o,"phase.baselined",i[i.length-1]??"system",{phase:t,version:r.version,approvedBy:i,items:d.map(c=>c.id)},s)}function pe(e,t,i){let s=[];for(let n of t){let r=E(e,n);r.status==="pending"&&chunkS3BXVHO7_cjs.b("invalid-input",`phase "${n}" was never baselined; there is nothing to reopen`,"remove it from impactAnalysis.reopen"),r.status==="baselined"&&!s.includes(n)&&s.push(n);}let f=b(e).map(n=>s.includes(n.id)?{...n,status:"reopened"}:n),d=null,a=e;if(s.length){let n=Math.min(...s.map(o=>I(e,o))),r=f.find((o,c)=>o.status==="open"&&c>n);r&&(d=r.id,f=f.map(o=>o.id===r.id?{...o,status:"reopened"}:o),a=Le(a,r.id,"cancelled",i));}return {state:S(a,f),reopened:s,suspended:d}}function F(e,t,i,s,f){let d=chunk23P7C25E_cjs.u(e,t),a=d.impactAnalysis,n=pe(e,a?.reopen??[],f),r=chunk23P7C25E_cjs.x(n.state,t,{stage:M,status:"done"},i,f);for(let o of n.reopened)r=chunk23P7C25E_cjs.c(r,"phase.reopened",i,{phase:o,change:t},f);return n.suspended!==null&&(r=chunk23P7C25E_cjs.c(r,"phase.suspended",i,{phase:n.suspended,change:t},f)),chunk23P7C25E_cjs.c(r,"change.decided",i,{change:t,decision:"approve",by:i,note:s,reopened:n.reopened,suspended:n.suspended,weight:a?.weight??0,affects:d.affects??[]},f)}function V(e,t,i,s,f){let d=chunk23P7C25E_cjs.u(e,t),a=chunk23P7C25E_cjs.x(e,t,{status:"dropped"},i,f);return chunk23P7C25E_cjs.c(a,"change.decided",i,{change:t,decision:"reject",by:i,note:s,reopened:[],suspended:null,weight:0,affects:d.affects??[]},f)}var _e=["policy","skill","memory","spec","review"],Me=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Je(e){return Array.isArray(e)&&e.every(t=>Me(t)&&typeof t.text=="string"&&t.text.trim()!==""&&_e.includes(t.scope))}function Qe(e,t,i){let s=[...t.map(d=>d.id),...i],f=s.find((d,a)=>s.indexOf(d)!==a);f!==void 0&&chunkS3BXVHO7_cjs.b("invalid-input",`lesson "${f}" is referenced more than once`,"adopt or dismiss each lesson once");for(let d of s){let a=e.lessons.find(n=>n.id===d);a||chunkS3BXVHO7_cjs.b("invalid-input",`no lesson "${d}"`,`raised lessons: ${e.lessons.filter(n=>n.status==="raised").map(n=>n.id).join(", ")||"(none)"}`),a.status!=="raised"&&chunkS3BXVHO7_cjs.b("invalid-input",`lesson "${d}" is already ${a.status}`,"only raised lessons can be adopted or dismissed");}}function Ge(e){return (t,i)=>{chunk23P7C25E_cjs.o(t,i.by,"facilitate");let s=i.phase===void 0?void 0:H(t,i,"phaseRetrospective"),f=i.lessons??[];Je(f)||chunkS3BXVHO7_cjs.b("invalid-input","phaseRetrospective.lessons entries need a text and a scope",`scope is one of: ${_e.join(", ")}`);let d=i.adopt??[],a=i.dismiss??[];return (!Array.isArray(d)||!d.every(n=>Me(n)&&typeof n.id=="string")||!Array.isArray(a)||!a.every(n=>typeof n=="string"))&&chunkS3BXVHO7_cjs.b("invalid-input","phaseRetrospective.adopt must be [{ id, suggestedChange? }] and dismiss a string[]",'e.g. { "adopt": [{ "id": "L1" }], "dismiss": ["L2"] }'),Qe(t,d,a),chunk23P7C25E_cjs.M(t,e(),{type:"ceremony.phaseRetrospective",by:i.by,payload:i},n=>{let r=n,o=chunk23P7C25E_cjs.a(i.now),c=[],l=m=>{!m||m.kind!=="agreement"||(r.agreements.includes(m.text)||(r={...r,agreements:[...r.agreements,m.text]}),c.push(m.text));},u=[];for(let m of f){let g=`L${r.lessons.length+1}`,x={id:g,at:o,text:m.text,scope:m.scope,status:"adopted",from:i.by};m.suggestedChange&&(x.suggestedChange=m.suggestedChange),r={...r,lessons:[...r.lessons,x]},u.push(g),l(m.suggestedChange);}let p=[];for(let m of d)r={...r,lessons:r.lessons.map(g=>g.id===m.id?{...g,status:"adopted",...m.suggestedChange?{suggestedChange:m.suggestedChange}:{}}:g)},p.push(m.id),l(m.suggestedChange??r.lessons.find(g=>g.id===m.id)?.suggestedChange);for(let m of a)r={...r,lessons:r.lessons.map(g=>g.id===m?{...g,status:"dismissed"}:g)};return chunk23P7C25E_cjs.c(r,"phase.retrospective",i.by,{phase:s?.id??null,lessons:u,adopted:p,dismissed:a,agreements:c},o)})}}var Xe=(e,t)=>e.id<t.id?-1:e.id>t.id?1:0,Ne=(e,t)=>exsorted.timSort(A(e,t).filter(i=>i.type!=="question"),Xe),et=(e,t)=>(e.traces??[]).includes(t.id)||(t.traces??[]).includes(e.id);function T(e){let t=k(e).traceability,i=b(e).map(a=>a.id),s=t.to.filter(a=>i.includes(a)),f=Ne(e,t.from).map(a=>{let n={};for(let r of s)n[r]=Ne(e,r).filter(o=>et(a,o)).map(o=>o.id);return {item:a.id,links:n}}),d=f.map(a=>({item:a.item,phases:s.filter(n=>a.links[n].length===0)})).filter(a=>a.phases.length>0);return {from:t.from,to:s,rows:f,missing:d,coverage:{traced:f.length-d.length,total:f.length}}}function fe(e,t){return T(e).rows.filter(i=>(i.links[t]??[]).length===0).map(i=>i.item)}var tt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function H(e,t,i){let s=t.phase;return (typeof s!="string"||s.trim()==="")&&chunkS3BXVHO7_cjs.b("invalid-input",`${i} needs phase: string`,`pass one of: ${b(e).map(f=>f.id).join(", ")}`),E(e,s)}function Fe(e,t,i,s,f,d){let a=S(e,b(e).map(n=>n.id===t?{...n,produced:[...n.produced??[],{kind:i,ref:s,by:f,at:d}]}:n));return chunk23P7C25E_cjs.c(a,"phase.deliverable",f,{phase:t,kind:i,ref:s},d)}function ue(e){let t=(d,a,n,r)=>chunk23P7C25E_cjs.M(d,e(),{type:a,by:n.by,payload:n},o=>r(o,chunk23P7C25E_cjs.a(n.now)));return {kickoff:(d,a)=>{chunk23P7C25E_cjs.o(d,a.by,"facilitate");let n=H(d,a,"kickoff");return t(d,"ceremony.kickoff",a,(r,o)=>{let c=r.events.filter(p=>p.type==="phase.opened"&&p.payload.phase===n.id).length+1,l=A(r,n.id).filter(p=>p.status!=="done").map(p=>p.id);r=S(r,b(r).map(p=>p.id===n.id?{...p,status:"open"}:p));let u=n.budget??{};return r={...r,iterations:[...r.iterations,{id:`${n.id}#${c}`,goal:n.name,budget:u,spent:chunk2IKIBB73_cjs.a,startedAt:o,committed:l,carryover:[]}]},chunk23P7C25E_cjs.c(r,"phase.opened",a.by,{phase:n.id,version:c,items:l,budget:u},o)})},gateReview:(d,a)=>{let n=H(d,a,"gateReview");n.status!=="open"&&chunkS3BXVHO7_cjs.b("invalid-transition",`phase "${n.id}" is ${n.status}, not open`,n.status==="baselined"?"it is already baselined; a change-request reopens it":`kickoff "${n.id}" first`);let r=n.gate,o=chunk23P7C25E_cjs.j(d,r.id,"approve-gate");a.by!=="human"&&!o.includes(a.by)&&chunkS3BXVHO7_cjs.b("gate-unmet",`"${a.by}" may not review gate "${r.id}"`,`review as one of: human${o.map(p=>`, ${p}`).join("")}`,{rule:"gate"});let c=d.pending.find(p=>p.kind==="gate"&&p.item===void 0&&p.gate===r.id);c&&chunkS3BXVHO7_cjs.b("no-op",`gate "${r.id}" is already awaiting a decision (${c.id})`,`decide ${c.id} approve|reject`);let l=a.deliverables??[];(!Array.isArray(l)||!l.every(p=>tt(p)&&typeof p.kind=="string"&&p.kind.trim()!==""&&typeof p.ref=="string"))&&chunkS3BXVHO7_cjs.b("invalid-input","gateReview.deliverables must be [{ kind, ref }]",'e.g. { "deliverables": [{ "kind": "srs", "ref": "docs/srs.md" }] }');let u=l;return t(d,"ceremony.gateReview",a,(p,m)=>{for(let g of u)p=Fe(p,n.id,g.kind,g.ref,a.by,m);if(k(p).traceability.to.includes(n.id)){let g=T(p);p=chunk23P7C25E_cjs.c(p,"traceability.computed",a.by,{phase:n.id,from:g.from,to:g.to,coverage:g.coverage,missing:g.missing,rows:g.rows},m),n.id===N(p)&&g.missing.length===0&&(p=Fe(p,n.id,"traceability-matrix",`traceability.computed#${p.events[p.events.length-1].seq}`,a.by,m));}if(r.requires.includes("human")&&a.by!=="human"){p=chunk23P7C25E_cjs.I(p,{kind:"gate",gate:r.id,question:`Approve gate "${r.id}" and baseline phase "${n.name}"?`},m);let g=p.pending[p.pending.length-1].id;return chunk23P7C25E_cjs.c(p,"phase.gate-pending",a.by,{phase:n.id,gate:r.id,by:a.by,pending:g},m)}return ee(p,n.id,[a.by],m)})},changeControlBoard:(d,a)=>{chunk23P7C25E_cjs.o(d,a.by,"control-change");let n=a.change;(typeof n!="string"||n.trim()==="")&&chunkS3BXVHO7_cjs.b("invalid-input","changeControlBoard needs change: string (a change-request id)",'e.g. { "change": "CR-1", "decision": "approve", "note": "why" }');let r=chunk23P7C25E_cjs.u(d,n);if(r.type!=="change-request"&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${n}" is a ${r.type}, not a change-request`,"only change-request items go through the board",{items:[n]}),(r.status==="done"||r.status==="dropped")&&chunkS3BXVHO7_cjs.b("invalid-transition",`change "${n}" is already ${r.status==="done"?"approved":"rejected"}`,"raise a new change-request",{items:[n]}),r.status==="awaiting_human"){let p=d.pending.find(m=>m.item===n);chunkS3BXVHO7_cjs.b("no-op",`change "${n}" is awaiting the human decision${p?` (${p.id})`:""}`,`decide ${p?.id??"<pending id>"} approve|reject`,{items:[n]});}let o=a.decision;o!=="approve"&&o!=="reject"&&chunkS3BXVHO7_cjs.b("invalid-input",'changeControlBoard.decision must be "approve" or "reject"',"state the board's decision");let c=typeof a.note=="string"?a.note:"",l=k(d).changeControl.approvers;for(let p of l)p==="human"||a.by==="human"||chunk23P7C25E_cjs.n(d,a.by,p.capability)||chunkS3BXVHO7_cjs.b("gate-unmet",`"${a.by}" lacks capability "${p.capability}" required by change control`,`decide as one of: human${chunk23P7C25E_cjs.i(d,p.capability).map(m=>`, ${m.id}`).join("")}`,{rule:"change-control",items:[n]});let u=l.includes("human")&&a.by!=="human";return t(d,"ceremony.changeControlBoard",a,(p,m)=>{if(u){p=chunk23P7C25E_cjs.I(p,{kind:"decision",item:n,question:`Change "${n}" (${r.title}): the board (${a.by}) recommends ${o}${c?`: ${c}`:""}. Approve or reject the change?`},m);let g=p.pending[p.pending.length-1].id;return chunk23P7C25E_cjs.c(p,"change.recommended",a.by,{change:n,decision:o,note:c,pending:g},m)}return o==="approve"?F(p,n,a.by,c,m):V(p,n,a.by,c,m)})},phaseRetrospective:Ge(e)}}function ge(e,t,i,s,f,d){if(t.kind==="gate"&&t.item===void 0&&t.gate!==void 0){let a=b(e).find(o=>o.gate.id===t.gate);if(!a)return e;s!=="human"&&chunkS3BXVHO7_cjs.b("gate-unmet",`"${s}" may not decide phase gate "${t.gate}" (${t.id}); it awaits a human`,`decide ${t.id} as human`,{rule:"gate"});let n;for(let o=e.events.length-1;o>=0;o--){let c=e.events[o];if(c.type==="phase.gate-pending"&&c.payload.pending===t.id){n=c.by;break}}let r=n!==void 0&&n!==s?[n,s]:[s];return i==="approve"?ee(e,a.id,r,d):chunk23P7C25E_cjs.c(e,"phase.gate-failed",s,{phase:a.id,gate:t.gate,note:f},d)}if(t.kind==="decision"&&t.item!==void 0&&Object.hasOwn(e.items,t.item)){let a=e.items[t.item];return a.type!=="change-request"?e:(s!=="human"&&chunkS3BXVHO7_cjs.b("gate-unmet",`"${s}" may not decide change "${a.id}" (${t.id}); change control awaits a human`,`decide ${t.id} as human`,{rule:"change-control",items:[a.id]}),i==="approve"?F(e,a.id,s,f,d):V(e,a.id,s,f,d))}return e}function me(e){let t=k(e).phases.map($=>$.id),i=()=>Object.fromEntries(t.map($=>[$,0])),s=i(),f=i(),d=i(),a=i(),n=i(),r=new Map,o=new Map,c=new Map,l=0,u=0,p=0,m=0,g=0,x=0,we=0,ke=$=>{let w=o.get($),y=r.get($);return w!=="question"&&w!=="change-request"&&y!==void 0&&y in s};for(let $ of e.events){let w=$.payload??{};switch($.type){case "item.added":{let y=w,q=y.phase??(y.parent!==null?r.get(y.parent):void 0);r.set(y.id,q),o.set(y.id,y.type),c.set(y.id,"todo"),y.type==="change-request"&&(p+=1),ke(y.id)&&(s[q]+=1,y.type==="bug"&&(n[q]+=1));break}case "item.transition":{let y=w.id,q=w.to.status,Re=c.get(y);if(c.set(y,q),!ke(y))break;let ne=r.get(y);q==="done"&&Re!=="done"&&(f[ne]+=1),q==="dropped"&&(s[ne]-=1,Re==="done"&&(f[ne]-=1));break}case "item.completed":{let y=r.get(w.id);y!==void 0&&y in a&&(a[y]+=w.tokens??0);break}case "phase.opened":{let y=w.phase;y in d&&(d[y]=(w.budget??{}).tokens??0);break}case "traceability.computed":{let y=w.coverage;l=y.traced,u=y.total;break}case "change.decided":{w.decision==="approve"?(m+=1,x+=w.weight??0,we+=(w.reopened??[]).length):g+=1;break}}}let $e=i(),We=i();for(let $ of t){let w=s[$]??0;$e[$]=w===0?0:(f[$]??0)/w*100,We[$]=a[$]-d[$];}let Ae=m+g;return {phaseCompletion:$e,budgetPlanned:d,budgetSpent:a,scheduleVariance:We,requirementCoverage:u===0?0:l/u,requirementsTraced:l,requirementsTotal:u,defectsPerPhase:n,changeRequests:p,changesApproved:m,changesRejected:g,changeApprovalRate:Ae===0?0:m/Ae,reworkWeight:x,phasesReopened:we}}function he(e){let t=e.phases.map(i=>i.gate.id);return [{id:"project-manager",name:"Project Manager",modelTier:"large",capabilities:["facilitate","control-change","approve-gate","escalate"],canApprove:[...t,de],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 v=(e,t,i,s)=>s?{rule:e,severity:"error",item:s,message:t,fix:i}:{rule:e,severity:"error",message:t,fix:i},C=e=>e.payload??{},U=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),z=e=>{let t=C(e).phase;return typeof t=="string"?t:void 0},P=(e,t)=>b(e).find(i=>i.id===t),ye=e=>b(e).map(t=>t.id).join(", "),te=(e,t)=>typeof t=="string"&&Object.hasOwn(e.items,t)?e.items[t]:void 0;function Ve(e,t){if(t.phase!==void 0)return t.phase;let i=te(e,t.parent);return i?R(e,i):void 0}var He=e=>e.type!=="change-request"&&e.type!=="question",Ue=(e,t)=>`raise a change-request: addItem({ type: "change-request", affects: ["${e}"], impactAnalysis: { summary, reopen: ["${t}"], weight } }) and decide it in changeControlBoard`;function ze(e,t){let i=te(e,C(t).change);return i&&i.type==="change-request"?i:void 0}function be(){return [{id:"phase-sequential",severity:"error",check(n,r){let o=[];if(r.type==="ceremony.kickoff"){let c=z(r),l=c===void 0?void 0:P(n,c);if(!l)return [];l.status==="open"&&o.push(v("phase-sequential",`phase "${l.id}" is already open`,`gateReview "${l.id}" when its work is done`)),l.status==="baselined"&&o.push(v("phase-sequential",`phase "${l.id}" is baselined`,"only an approved change-request reopens a baselined phase"));let u=O(n);u&&u.id!==l.id&&o.push(v("phase-sequential",`phase "${u.id}" is still open`,`pass its gate (gateReview "${u.id}") before opening "${l.id}"`));}else if(r.type==="item.add"){let c=C(r).item;if(!U(c)||!He(c))return [];let l=Ve(n,c);l===void 0?o.push(v("phase-sequential",`item "${c.id}" belongs to no phase`,`set phase to one of: ${ye(n)}`,c.id)):P(n,l)||o.push(v("phase-sequential",`item "${c.id}" names unknown phase "${l}"`,`phases are: ${ye(n)}`,c.id));}else if(r.type==="item.edit"){let c=C(r).id,l=C(r).patch,u=te(n,c);if(!u||!U(l)||l.phase===void 0||l.phase===u.phase)return [];o.push(v("phase-sequential",`item "${u.id}" cannot move from phase "${u.phase??"(none)"}" to "${String(l.phase)}"`,`drop "${u.id}" and add a new item in phase "${String(l.phase)}"`,u.id));}return o}},{id:"gate-before-next-phase",severity:"error",check(n,r){if(r.type!=="ceremony.kickoff")return [];let o=z(r),c=b(n),l=o===void 0?-1:c.findIndex(p=>p.id===o);if(l<0)return [];let u=c.slice(0,l).filter(p=>p.status!=="baselined").map(p=>p.id);return u.length===0?[]:[v("gate-before-next-phase",`phase(s) ${u.join(", ")} before "${o}" are not baselined`,`kickoff and gateReview them in order, starting with "${u[0]}"`)]}},{id:"baseline-immutable",severity:"error",check(n,r){let o=c=>(n.baselines??[]).filter(l=>l.phase===c).length||1;if(r.type==="item.edit"){let c=te(n,C(r).id);if(!c)return [];let l=R(n,c);return l===void 0||P(n,l)?.status!=="baselined"?[]:[v("baseline-immutable",`item "${c.id}" is frozen: phase "${l}" is baselined (v${o(l)})`,Ue(c.id,l),c.id)]}if(r.type==="item.add"){let c=C(r).item;if(!U(c)||!He(c))return [];let l=Ve(n,c);return l===void 0||P(n,l)?.status!=="baselined"?[]:[v("baseline-immutable",`cannot add "${c.id}" to baselined phase "${l}" (v${o(l)})`,Ue(c.id,l),c.id)]}return []}},{id:"change-needs-impact-analysis",severity:"error",check(n,r){if(r.type!=="ceremony.changeControlBoard")return [];let o=ze(n,r);if(!o)return [];let c=k(n).changeControl,l=o.impactAnalysis,u=`editItem("${o.id}", { impactAnalysis: { summary: "what changes and why", reopen: ["<phase>"], weight: <points> } })`;if(l===void 0)return c.requiresImpactAnalysis?[v("change-needs-impact-analysis",`change "${o.id}" has no impact analysis`,u,o.id)]:[];let p=[];if((!U(l)||typeof l.summary!="string"||l.summary.trim()==="")&&p.push(v("change-needs-impact-analysis",`change "${o.id}" impactAnalysis.summary is empty`,u,o.id)),(!Array.isArray(l.reopen)||!l.reopen.every(g=>typeof g=="string"))&&p.push(v("change-needs-impact-analysis",`change "${o.id}" impactAnalysis.reopen must be a string[] of phase ids`,u,o.id)),(typeof l.weight!="number"||!Number.isFinite(l.weight)||l.weight<0)&&p.push(v("change-needs-impact-analysis",`change "${o.id}" impactAnalysis.weight must be a non-negative number`,u,o.id)),p.length)return p;let m=C(r).decision==="approve";for(let g of l.reopen){let x=P(n,g);x?m&&x.status==="pending"&&p.push(v("change-needs-impact-analysis",`phase "${g}" was never baselined; it cannot be reopened`,`remove "${g}" from impactAnalysis.reopen`,o.id)):p.push(v("change-needs-impact-analysis",`change "${o.id}" impactAnalysis.reopen names unknown phase "${g}"`,`phases are: ${ye(n)}`,o.id));}return p}},{id:"requirement-traced",severity:"error",check(n,r){if(r.type!=="ceremony.gateReview")return [];let o=z(r),c=k(n).traceability;return o===void 0||!c.to.includes(o)||!P(n,o)?[]:fe(n,o).map(l=>v("requirement-traced",`item "${l}" of phase "${c.from}" has no trace into "${o}"`,`editItem a "${o}" item with traces: ["${l}"] (or editItem("${l}", { traces: [...] }) while "${c.from}" is not baselined)`,l))}},{id:"deliverables-present",severity:"error",check(n,r){if(r.type!=="ceremony.gateReview")return [];let o=z(r),c=o===void 0?void 0:P(n,o);if(!c)return [];let l=[],u=A(n,c.id).filter(g=>g.status!=="done").map(g=>g.id);u.length&&l.push(v("deliverables-present",`${u.length} item(s) in phase "${c.id}" are not done: ${u.join(", ")}`,"finish them (next/complete) or drop them before the gate"));let p=C(r).deliverables,m=Array.isArray(p)?p.filter(g=>U(g)&&typeof g.kind=="string").map(g=>g.kind):[];c.id===N(n)&&m.push("traceability-matrix");for(let g of G(n,c,m))l.push(v("deliverables-present",`phase "${c.id}" has no deliverable "${g}"`,`pass deliverables: [{ "kind": "${g}", "ref": "<where it lives>" }] to gateReview, or attach evidence of kind "${g}" on an item of the phase`));return l}},{id:"approver-not-author",severity:"error",check(n,r){if(r.by==="human")return [];if(r.type==="ceremony.gateReview"){let o=z(r),c=o===void 0?void 0:P(n,o);if(!c)return [];let l=A(n,c.id).filter(p=>chunk23P7C25E_cjs.G(n,p)===r.by).map(p=>p.id);if(l.length===0)return [];let u=chunk23P7C25E_cjs.j(n,c.gate.id,"approve-gate",r.by);return [v("approver-not-author",`"${r.by}" authored ${l.join(", ")} in phase "${c.id}" and may not approve its gate`,`review the gate as one of: human${u.map(p=>`, ${p}`).join("")}`)]}if(r.type==="ceremony.changeControlBoard"){let o=ze(n,r);if(!o)return [];let c=n.events.find(u=>u.type==="item.added"&&u.payload.id===o.id);if(!c||c.by!==r.by)return [];let l=chunk23P7C25E_cjs.i(n,"control-change").map(u=>u.id).filter(u=>u!==r.by);return [v("approver-not-author",`"${r.by}" raised change "${o.id}" and may not decide it`,`decide as human${l.map(u=>`, ${u}`).join("")}`,o.id)]}return []}}]}function ve(e){return [{id:L,name:"Work",entryPolicy:[{kind:"dependencies-done"}],exitPolicy:[]},{id:_,name:"Review",entryPolicy:[],exitPolicy:[{kind:"no-open-blockers"}],review:true},{id:M,name:"Done",entryPolicy:[],exitPolicy:[]}]}var nt={backlog:"Requirements Baseline",item:"Work Package",stage:"Step",iteration:"Phase",increment:"Deliverable",ceremony:"Review",gate:"Phase Gate"};function it(e,t){let i=R(e,t);if(i!==void 0)return k(e).phases.find(s=>s.id===i)?.deliverBy}function rt(e){return {phases:b(e).map(i=>{let s=A(e,i.id),f=s.filter(a=>a.status==="done").length,d=G(e,i);return {id:i.id,name:i.name,status:i.status,items:s.length,done:f,missingDeliverables:d,readyForGate:i.status==="open"&&f===s.length&&d.length===0}}),current:le(e)?.id??null,open:O(e)?.id??null,pendingGates:e.pending.filter(i=>i.kind==="gate"&&i.item===void 0&&i.gate!==void 0).map(i=>({pending:i.id,gate:i.gate}))}}function st(){return {name:"waterfall",vocabulary:nt,validateConfig:ce,defaultStages:ve,defaultRoles:he,requiredCapabilities:["facilitate","control-change","approve-gate","deliver","verify"],exclusiveCapabilities:[],plannerOptions(e){return {schedulerMode:"level",roleFor:t=>t.status==="todo"&&t.type!=="question"?it(e,t):void 0}},candidates(e){let t=O(e);return t?Object.values(e.items).filter(i=>(i.status==="todo"||i.status==="review")&&(i.stage===L||i.stage===_)&&i.type!=="change-request"&&R(e,i)===t.id):[]},invariants(e,t){let i=k(e),s=b(e),f=R(e,t),d=f===void 0?void 0:s[I(e,f)],a=s.filter(r=>r.status==="baselined").map(r=>r.id),n=d?.gate.requires.includes("human");return [d?`Phase "${d.name}" (${I(e,d.id)+1}/${s.length}); deliverables: ${d.deliverables.join(", ")||"(none)"}; gate "${d.gate.id}"${n?" needs human approval":""}`:"This item belongs to no phase; it is dispatched only through its parent's phase",`Baselined phases are frozen: ${a.join(", ")||"(none yet)"}; to change their items, raise a change-request with an impact analysis`,i.traceability.to.length?`Traceability: every item of phase "${i.traceability.from}" must trace to an item in ${i.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:ue(st),rules:be(),metrics:e=>({...me(e)}),humanDefaults:{gates:"all"},report:e=>({...rt(e),coverage:T(e).coverage}),afterDecide:ge,afterComplete(e,t,i){let s=chunk2IKIBB73_cjs.f(e),f=O(e);if(!s||!f||s.committed.includes(t))return e;let d=e.items[t];if(!d||R(e,d)!==f.id)return e;let a=e.accounting[e.accounting.length-1];return !a||a.item!==t?e:{...e,iterations:e.iterations.map(n=>n.id===s.id?{...n,committed:[...n.committed,t],spent:chunk2IKIBB73_cjs.b(n.spent,a)}:n)}}}}exports.A=V;exports.B=T;exports.C=fe;exports.D=H;exports.E=ue;exports.F=ge;exports.G=me;exports.H=he;exports.I=be;exports.J=ve;exports.K=nt;exports.L=it;exports.M=rt;exports.N=st;exports.a=je;exports.b=se;exports.c=oe;exports.d=ae;exports.e=de;exports.f=Te;exports.g=k;exports.h=ce;exports.i=L;exports.j=_;exports.k=M;exports.l=b;exports.m=S;exports.n=I;exports.o=E;exports.p=R;exports.q=A;exports.r=O;exports.s=le;exports.t=Ye;exports.u=Be;exports.v=G;exports.w=N;exports.x=ee;exports.y=pe;exports.z=F;//# sourceMappingURL=chunk-TMKCALFT.cjs.map
2
- //# sourceMappingURL=chunk-TMKCALFT.cjs.map
1
+ 'use strict';var chunkCWBH7H52_cjs=require('./chunk-CWBH7H52.cjs'),chunkSJRRQZ3R_cjs=require('./chunk-SJRRQZ3R.cjs'),chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs'),exsorted=require('exsorted');var je=["requirements","design","implementation","verification","deployment","maintenance"],se={requirements:["srs"],design:["design-doc","interface-spec"],implementation:["code-baseline"],verification:["test-report","traceability-matrix"],deployment:["release-notes","deployment-record"],maintenance:["change-log"]},oe={requirements:"business-analyst",design:"architect",deployment:"release-manager"},ae=e=>`${e}-gate`,de="change-control",Ie=["order-backlog","define-acceptance","facilitate","deliver","review","verify","approve-gate","manage-flow","control-change","escalate"],Ee=e=>e.charAt(0).toUpperCase()+e.slice(1);function Te(){return je.map(e=>{let t={id:e,name:Ee(e),deliverables:[...se[e]??[]],gate:{id:ae(e),requires:[{capability:"approve-gate"}],evidence:[],onFail:{action:"block"}}},i=oe[e];return i!==void 0&&(t.deliverBy=i),t})}function k(e){return e.config}var j=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),X=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.trim()!=="");function Ke(e,t){if(e===void 0)return;j(e)||chunkS3BXVHO7_cjs.b("config-invalid",`${t}.budget must be an object`,'e.g. { "tokens": 400000 }');let i={};for(let s of ["tokens","turns","wallclockMs"]){let f=e[s];f!==void 0&&((typeof f!="number"||!Number.isFinite(f)||f<0)&&chunkS3BXVHO7_cjs.b("config-invalid",`${t}.budget.${s} must be a non-negative number`,"omit it for no limit"),i[s]=f);}return i}function De(e,t){return (!Array.isArray(e)||e.length===0)&&chunkS3BXVHO7_cjs.b("config-invalid",`${t} must be a non-empty array of "human" | { capability }`,'e.g. ["human", { "capability": "approve-gate" }]'),e.map(i=>i==="human"?"human":j(i)&&typeof i.capability=="string"&&Ie.includes(i.capability)?{capability:i.capability}:chunkS3BXVHO7_cjs.b("config-invalid",`${t} entry ${JSON.stringify(i)} is not "human" or a known capability`,`use "human" or { "capability": one of ${Ie.join(", ")} }`))}function Oe(e,t,i){let s=`waterfall config.phases[${t}]`;j(e)||chunkS3BXVHO7_cjs.b("config-invalid",`${s} must be an object`,'e.g. { "id": "design" }'),chunkS3BXVHO7_cjs.c(e.id,`${s}.id`);let f=e.id,d=e.deliverables??se[f]??[];X(d)||chunkS3BXVHO7_cjs.b("config-invalid",`${s}.deliverables must be a string[] of evidence kinds`,'e.g. ["srs"]');let a;if(e.gate===void 0)a={id:ae(f),requires:[{capability:"approve-gate"}],evidence:[],onFail:{action:"block"}};else {let c=e.gate;(!j(c)||typeof c.id!="string"||c.id.trim()==="")&&chunkS3BXVHO7_cjs.b("config-invalid",`${s}.gate must be a Gate with an id`,'e.g. { "id": "design-gate", "requires": [{ "capability": "approve-gate" }], "evidence": [] }');let l=c.evidence??[];X(l)||chunkS3BXVHO7_cjs.b("config-invalid",`${s}.gate.evidence must be a string[]`,"list evidence kinds or omit it"),a={id:c.id,requires:De(c.requires??[{capability:"approve-gate"}],`${s}.gate.requires`),evidence:[...l],onFail:{action:"block"}};}i(f)&&!a.requires.includes("human")&&(a.requires=["human",...a.requires]);let n={id:f,name:typeof e.name=="string"&&e.name.trim()!==""?e.name:Ee(f),deliverables:[...d],gate:a},r=Ke(e.budget,s);r!==void 0&&(n.budget=r);let o=e.deliverBy??oe[f];return o!==void 0&&((typeof o!="string"||o.trim()==="")&&chunkS3BXVHO7_cjs.b("config-invalid",`${s}.deliverBy must be a role id`,"name the role that delivers this phase or omit it"),n.deliverBy=o),n}function ce(e){let t=e??{};t.phases!==void 0&&!Array.isArray(t.phases)&&chunkS3BXVHO7_cjs.b("config-invalid","waterfall config.phases must be an array of phases","omit phases for the six classic phases");let i=t.humanGates??"all";i!=="all"&&!X(i)&&chunkS3BXVHO7_cjs.b("config-invalid",'waterfall config.humanGates must be "all" or a string[] of phase ids','omit it for "all"');let s=i==="all"?()=>true:l=>i.includes(l),f=t.phases===void 0?Te().map((l,u)=>Oe(l,u,s)):t.phases.map((l,u)=>Oe(l,u,s));f.length===0&&chunkS3BXVHO7_cjs.b("config-invalid","waterfall config.phases needs at least one phase",'e.g. [{ "id": "requirements" }]');let d=f.map(l=>l.id),a=d.find((l,u)=>d.indexOf(l)!==u);if(a!==void 0&&chunkS3BXVHO7_cjs.b("config-invalid",`duplicate phase id "${a}"`,"give every phase a unique id"),i!=="all")for(let l of i)d.includes(l)||chunkS3BXVHO7_cjs.b("config-invalid",`waterfall config.humanGates names unknown phase "${l}"`,`phases are: ${d.join(", ")}`);let n=t.changeControl??{};j(n)||chunkS3BXVHO7_cjs.b("config-invalid","waterfall config.changeControl must be an object",'e.g. { "requiresImpactAnalysis": true, "approvers": ["human"] }'),n.requiresImpactAnalysis!==void 0&&typeof n.requiresImpactAnalysis!="boolean"&&chunkS3BXVHO7_cjs.b("config-invalid","waterfall config.changeControl.requiresImpactAnalysis must be a boolean","omit it for true");let r={requiresImpactAnalysis:n.requiresImpactAnalysis===void 0?true:n.requiresImpactAnalysis,approvers:De(n.approvers??["human",{capability:"control-change"}],"waterfall config.changeControl.approvers")},o=t.traceability,c;if(o===void 0)c=d.includes("requirements")&&d.includes("design")&&d.includes("verification")?{from:"requirements",to:["design","verification"]}:{from:d[0],to:[]};else {(!j(o)||typeof o.from!="string"||!d.includes(o.from))&&chunkS3BXVHO7_cjs.b("config-invalid","waterfall config.traceability.from must be a phase id",`phases are: ${d.join(", ")}`);let l=o.to??[];X(l)||chunkS3BXVHO7_cjs.b("config-invalid","waterfall config.traceability.to must be a string[] of phase ids",`phases are: ${d.join(", ")}`);for(let u of l)d.includes(u)||chunkS3BXVHO7_cjs.b("config-invalid",`waterfall config.traceability.to names unknown phase "${u}"`,`phases are: ${d.join(", ")}`),d.indexOf(u)<=d.indexOf(o.from)&&chunkS3BXVHO7_cjs.b("config-invalid",`waterfall config.traceability.to phase "${u}" must come after "${o.from}"`,"trace forward only: from an earlier phase to later ones");c={from:o.from,to:[...l]};}return {phases:f,changeControl:r,traceability:c,humanGates:i==="all"?"all":[...i]}}var L="work",_="review",M="done";function b(e){return e.phases?e.phases:k(e).phases.map(t=>{let i={id:t.id,name:t.name,deliverables:[...t.deliverables],gate:t.gate,status:"pending"};return t.budget&&(i.budget=t.budget),i})}function S(e,t){return {...e,phases:t}}function I(e,t){let i=b(e).findIndex(s=>s.id===t);return i<0&&chunkS3BXVHO7_cjs.b("config-invalid",`unknown phase "${t}"`,`phases are: ${b(e).map(s=>s.id).join(" \u2192 ")}`),i}function E(e,t){return b(e)[I(e,t)]}function R(e,t){let i=new Set,s=t;for(;s&&!i.has(s.id);){if(s.phase!==void 0)return s.phase;i.add(s.id),s=s.parent!==void 0&&Object.hasOwn(e.items,s.parent)?e.items[s.parent]:void 0;}}function A(e,t){return Object.values(e.items).filter(i=>i.status!=="dropped"&&R(e,i)===t)}function O(e){return b(e).find(t=>t.status==="open")}function le(e){return b(e).find(t=>t.status!=="baselined")}function Ye(e,t){let i=R(e,t);return i!==void 0&&b(e).find(s=>s.id===i)?.status==="baselined"}function Be(e,t){let i=new Set((t.produced??[]).map(s=>s.kind));for(let s of A(e,t.id))for(let f of s.evidence)i.add(f.kind);return i}function G(e,t,i=[]){let s=Be(e,t);for(let d of i)s.add(d);let f=[];for(let d of [...t.deliverables,...t.gate.evidence])f.includes(d)||f.push(d);return f.filter(d=>!s.has(d))}function N(e){let t=b(e).map(s=>s.id),i=k(e).traceability.to.filter(s=>t.includes(s));if(i.length!==0)return i.reduce((s,f)=>t.indexOf(s)>=t.indexOf(f)?s:f)}function Le(e,t,i,s){let f=chunkCWBH7H52_cjs.f(e);return !f||!f.id.startsWith(`${t}#`)?e:{...e,iterations:e.iterations.map(d=>d.id===f.id?{...d,endedAt:s,outcome:i}:d)}}function ee(e,t,i,s){let f=E(e,t);f.status!=="open"&&chunkS3BXVHO7_cjs.b("invalid-transition",`phase "${t}" is ${f.status}, not open`,f.status==="baselined"?"it is already baselined; a change-request reopens it":"kickoff the phase first");let d=A(e,t),a={};for(let c of d)a[c.id]=c;let n=(e.baselines??[]).filter(c=>c.phase===t).length,r={phase:t,version:n+1,at:s,approvedBy:i,itemSnapshot:a},o=S(e,b(e).map(c=>c.id===t?{...c,status:"baselined"}:c));return o={...o,baseline:r,baselines:[...o.baselines??[],r]},o=Le(o,t,"completed",s),chunkSJRRQZ3R_cjs.c(o,"phase.baselined",i[i.length-1]??"system",{phase:t,version:r.version,approvedBy:i,items:d.map(c=>c.id)},s)}function pe(e,t,i){let s=[];for(let n of t){let r=E(e,n);r.status==="pending"&&chunkS3BXVHO7_cjs.b("invalid-input",`phase "${n}" was never baselined; there is nothing to reopen`,"remove it from impactAnalysis.reopen"),r.status==="baselined"&&!s.includes(n)&&s.push(n);}let f=b(e).map(n=>s.includes(n.id)?{...n,status:"reopened"}:n),d=null,a=e;if(s.length){let n=Math.min(...s.map(o=>I(e,o))),r=f.find((o,c)=>o.status==="open"&&c>n);r&&(d=r.id,f=f.map(o=>o.id===r.id?{...o,status:"reopened"}:o),a=Le(a,r.id,"cancelled",i));}return {state:S(a,f),reopened:s,suspended:d}}function F(e,t,i,s,f){let d=chunkSJRRQZ3R_cjs.u(e,t),a=d.impactAnalysis,n=pe(e,a?.reopen??[],f),r=chunkSJRRQZ3R_cjs.x(n.state,t,{stage:M,status:"done"},i,f);for(let o of n.reopened)r=chunkSJRRQZ3R_cjs.c(r,"phase.reopened",i,{phase:o,change:t},f);return n.suspended!==null&&(r=chunkSJRRQZ3R_cjs.c(r,"phase.suspended",i,{phase:n.suspended,change:t},f)),chunkSJRRQZ3R_cjs.c(r,"change.decided",i,{change:t,decision:"approve",by:i,note:s,reopened:n.reopened,suspended:n.suspended,weight:a?.weight??0,affects:d.affects??[]},f)}function V(e,t,i,s,f){let d=chunkSJRRQZ3R_cjs.u(e,t),a=chunkSJRRQZ3R_cjs.x(e,t,{status:"dropped"},i,f);return chunkSJRRQZ3R_cjs.c(a,"change.decided",i,{change:t,decision:"reject",by:i,note:s,reopened:[],suspended:null,weight:0,affects:d.affects??[]},f)}var _e=["policy","skill","memory","spec","review"],Me=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Je(e){return Array.isArray(e)&&e.every(t=>Me(t)&&typeof t.text=="string"&&t.text.trim()!==""&&_e.includes(t.scope))}function Qe(e,t,i){let s=[...t.map(d=>d.id),...i],f=s.find((d,a)=>s.indexOf(d)!==a);f!==void 0&&chunkS3BXVHO7_cjs.b("invalid-input",`lesson "${f}" is referenced more than once`,"adopt or dismiss each lesson once");for(let d of s){let a=e.lessons.find(n=>n.id===d);a||chunkS3BXVHO7_cjs.b("invalid-input",`no lesson "${d}"`,`raised lessons: ${e.lessons.filter(n=>n.status==="raised").map(n=>n.id).join(", ")||"(none)"}`),a.status!=="raised"&&chunkS3BXVHO7_cjs.b("invalid-input",`lesson "${d}" is already ${a.status}`,"only raised lessons can be adopted or dismissed");}}function Ge(e){return (t,i)=>{chunkSJRRQZ3R_cjs.o(t,i.by,"facilitate");let s=i.phase===void 0?void 0:H(t,i,"phaseRetrospective"),f=i.lessons??[];Je(f)||chunkS3BXVHO7_cjs.b("invalid-input","phaseRetrospective.lessons entries need a text and a scope",`scope is one of: ${_e.join(", ")}`);let d=i.adopt??[],a=i.dismiss??[];return (!Array.isArray(d)||!d.every(n=>Me(n)&&typeof n.id=="string")||!Array.isArray(a)||!a.every(n=>typeof n=="string"))&&chunkS3BXVHO7_cjs.b("invalid-input","phaseRetrospective.adopt must be [{ id, suggestedChange? }] and dismiss a string[]",'e.g. { "adopt": [{ "id": "L1" }], "dismiss": ["L2"] }'),Qe(t,d,a),chunkSJRRQZ3R_cjs.M(t,e(),{type:"ceremony.phaseRetrospective",by:i.by,payload:i},n=>{let r=n,o=chunkSJRRQZ3R_cjs.a(i.now),c=[],l=m=>{!m||m.kind!=="agreement"||(r.agreements.includes(m.text)||(r={...r,agreements:[...r.agreements,m.text]}),c.push(m.text));},u=[];for(let m of f){let g=`L${r.lessons.length+1}`,x={id:g,at:o,text:m.text,scope:m.scope,status:"adopted",from:i.by};m.suggestedChange&&(x.suggestedChange=m.suggestedChange),r={...r,lessons:[...r.lessons,x]},u.push(g),l(m.suggestedChange);}let p=[];for(let m of d)r={...r,lessons:r.lessons.map(g=>g.id===m.id?{...g,status:"adopted",...m.suggestedChange?{suggestedChange:m.suggestedChange}:{}}:g)},p.push(m.id),l(m.suggestedChange??r.lessons.find(g=>g.id===m.id)?.suggestedChange);for(let m of a)r={...r,lessons:r.lessons.map(g=>g.id===m?{...g,status:"dismissed"}:g)};return chunkSJRRQZ3R_cjs.c(r,"phase.retrospective",i.by,{phase:s?.id??null,lessons:u,adopted:p,dismissed:a,agreements:c},o)})}}var Xe=(e,t)=>e.id<t.id?-1:e.id>t.id?1:0,Ne=(e,t)=>exsorted.timSort(A(e,t).filter(i=>i.type!=="question"),Xe),et=(e,t)=>(e.traces??[]).includes(t.id)||(t.traces??[]).includes(e.id);function T(e){let t=k(e).traceability,i=b(e).map(a=>a.id),s=t.to.filter(a=>i.includes(a)),f=Ne(e,t.from).map(a=>{let n={};for(let r of s)n[r]=Ne(e,r).filter(o=>et(a,o)).map(o=>o.id);return {item:a.id,links:n}}),d=f.map(a=>({item:a.item,phases:s.filter(n=>a.links[n].length===0)})).filter(a=>a.phases.length>0);return {from:t.from,to:s,rows:f,missing:d,coverage:{traced:f.length-d.length,total:f.length}}}function fe(e,t){return T(e).rows.filter(i=>(i.links[t]??[]).length===0).map(i=>i.item)}var tt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function H(e,t,i){let s=t.phase;return (typeof s!="string"||s.trim()==="")&&chunkS3BXVHO7_cjs.b("invalid-input",`${i} needs phase: string`,`pass one of: ${b(e).map(f=>f.id).join(", ")}`),E(e,s)}function Fe(e,t,i,s,f,d){let a=S(e,b(e).map(n=>n.id===t?{...n,produced:[...n.produced??[],{kind:i,ref:s,by:f,at:d}]}:n));return chunkSJRRQZ3R_cjs.c(a,"phase.deliverable",f,{phase:t,kind:i,ref:s},d)}function ue(e){let t=(d,a,n,r)=>chunkSJRRQZ3R_cjs.M(d,e(),{type:a,by:n.by,payload:n},o=>r(o,chunkSJRRQZ3R_cjs.a(n.now)));return {kickoff:(d,a)=>{chunkSJRRQZ3R_cjs.o(d,a.by,"facilitate");let n=H(d,a,"kickoff");return t(d,"ceremony.kickoff",a,(r,o)=>{let c=r.events.filter(p=>p.type==="phase.opened"&&p.payload.phase===n.id).length+1,l=A(r,n.id).filter(p=>p.status!=="done").map(p=>p.id);r=S(r,b(r).map(p=>p.id===n.id?{...p,status:"open"}:p));let u=n.budget??{};return r={...r,iterations:[...r.iterations,{id:`${n.id}#${c}`,goal:n.name,budget:u,spent:chunkCWBH7H52_cjs.a,startedAt:o,committed:l,carryover:[]}]},chunkSJRRQZ3R_cjs.c(r,"phase.opened",a.by,{phase:n.id,version:c,items:l,budget:u},o)})},gateReview:(d,a)=>{let n=H(d,a,"gateReview");n.status!=="open"&&chunkS3BXVHO7_cjs.b("invalid-transition",`phase "${n.id}" is ${n.status}, not open`,n.status==="baselined"?"it is already baselined; a change-request reopens it":`kickoff "${n.id}" first`);let r=n.gate,o=chunkSJRRQZ3R_cjs.j(d,r.id,"approve-gate");a.by!=="human"&&!o.includes(a.by)&&chunkS3BXVHO7_cjs.b("gate-unmet",`"${a.by}" may not review gate "${r.id}"`,`review as one of: human${o.map(p=>`, ${p}`).join("")}`,{rule:"gate"});let c=d.pending.find(p=>p.kind==="gate"&&p.item===void 0&&p.gate===r.id);c&&chunkS3BXVHO7_cjs.b("no-op",`gate "${r.id}" is already awaiting a decision (${c.id})`,`decide ${c.id} approve|reject`);let l=a.deliverables??[];(!Array.isArray(l)||!l.every(p=>tt(p)&&typeof p.kind=="string"&&p.kind.trim()!==""&&typeof p.ref=="string"))&&chunkS3BXVHO7_cjs.b("invalid-input","gateReview.deliverables must be [{ kind, ref }]",'e.g. { "deliverables": [{ "kind": "srs", "ref": "docs/srs.md" }] }');let u=l;return t(d,"ceremony.gateReview",a,(p,m)=>{for(let g of u)p=Fe(p,n.id,g.kind,g.ref,a.by,m);if(k(p).traceability.to.includes(n.id)){let g=T(p);p=chunkSJRRQZ3R_cjs.c(p,"traceability.computed",a.by,{phase:n.id,from:g.from,to:g.to,coverage:g.coverage,missing:g.missing,rows:g.rows},m),n.id===N(p)&&g.missing.length===0&&(p=Fe(p,n.id,"traceability-matrix",`traceability.computed#${p.events[p.events.length-1].seq}`,a.by,m));}if(r.requires.includes("human")&&a.by!=="human"){p=chunkSJRRQZ3R_cjs.I(p,{kind:"gate",gate:r.id,question:`Approve gate "${r.id}" and baseline phase "${n.name}"?`},m);let g=p.pending[p.pending.length-1].id;return chunkSJRRQZ3R_cjs.c(p,"phase.gate-pending",a.by,{phase:n.id,gate:r.id,by:a.by,pending:g},m)}return ee(p,n.id,[a.by],m)})},changeControlBoard:(d,a)=>{chunkSJRRQZ3R_cjs.o(d,a.by,"control-change");let n=a.change;(typeof n!="string"||n.trim()==="")&&chunkS3BXVHO7_cjs.b("invalid-input","changeControlBoard needs change: string (a change-request id)",'e.g. { "change": "CR-1", "decision": "approve", "note": "why" }');let r=chunkSJRRQZ3R_cjs.u(d,n);if(r.type!=="change-request"&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${n}" is a ${r.type}, not a change-request`,"only change-request items go through the board",{items:[n]}),(r.status==="done"||r.status==="dropped")&&chunkS3BXVHO7_cjs.b("invalid-transition",`change "${n}" is already ${r.status==="done"?"approved":"rejected"}`,"raise a new change-request",{items:[n]}),r.status==="awaiting_human"){let p=d.pending.find(m=>m.item===n);chunkS3BXVHO7_cjs.b("no-op",`change "${n}" is awaiting the human decision${p?` (${p.id})`:""}`,`decide ${p?.id??"<pending id>"} approve|reject`,{items:[n]});}let o=a.decision;o!=="approve"&&o!=="reject"&&chunkS3BXVHO7_cjs.b("invalid-input",'changeControlBoard.decision must be "approve" or "reject"',"state the board's decision");let c=typeof a.note=="string"?a.note:"",l=k(d).changeControl.approvers;for(let p of l)p==="human"||a.by==="human"||chunkSJRRQZ3R_cjs.n(d,a.by,p.capability)||chunkS3BXVHO7_cjs.b("gate-unmet",`"${a.by}" lacks capability "${p.capability}" required by change control`,`decide as one of: human${chunkSJRRQZ3R_cjs.i(d,p.capability).map(m=>`, ${m.id}`).join("")}`,{rule:"change-control",items:[n]});let u=l.includes("human")&&a.by!=="human";return t(d,"ceremony.changeControlBoard",a,(p,m)=>{if(u){p=chunkSJRRQZ3R_cjs.I(p,{kind:"decision",item:n,question:`Change "${n}" (${r.title}): the board (${a.by}) recommends ${o}${c?`: ${c}`:""}. Approve or reject the change?`},m);let g=p.pending[p.pending.length-1].id;return chunkSJRRQZ3R_cjs.c(p,"change.recommended",a.by,{change:n,decision:o,note:c,pending:g},m)}return o==="approve"?F(p,n,a.by,c,m):V(p,n,a.by,c,m)})},phaseRetrospective:Ge(e)}}function ge(e,t,i,s,f,d){if(t.kind==="gate"&&t.item===void 0&&t.gate!==void 0){let a=b(e).find(o=>o.gate.id===t.gate);if(!a)return e;s!=="human"&&chunkS3BXVHO7_cjs.b("gate-unmet",`"${s}" may not decide phase gate "${t.gate}" (${t.id}); it awaits a human`,`decide ${t.id} as human`,{rule:"gate"});let n;for(let o=e.events.length-1;o>=0;o--){let c=e.events[o];if(c.type==="phase.gate-pending"&&c.payload.pending===t.id){n=c.by;break}}let r=n!==void 0&&n!==s?[n,s]:[s];return i==="approve"?ee(e,a.id,r,d):chunkSJRRQZ3R_cjs.c(e,"phase.gate-failed",s,{phase:a.id,gate:t.gate,note:f},d)}if(t.kind==="decision"&&t.item!==void 0&&Object.hasOwn(e.items,t.item)){let a=e.items[t.item];return a.type!=="change-request"?e:(s!=="human"&&chunkS3BXVHO7_cjs.b("gate-unmet",`"${s}" may not decide change "${a.id}" (${t.id}); change control awaits a human`,`decide ${t.id} as human`,{rule:"change-control",items:[a.id]}),i==="approve"?F(e,a.id,s,f,d):V(e,a.id,s,f,d))}return e}function me(e){let t=k(e).phases.map($=>$.id),i=()=>Object.fromEntries(t.map($=>[$,0])),s=i(),f=i(),d=i(),a=i(),n=i(),r=new Map,o=new Map,c=new Map,l=0,u=0,p=0,m=0,g=0,x=0,we=0,ke=$=>{let w=o.get($),y=r.get($);return w!=="question"&&w!=="change-request"&&y!==void 0&&y in s};for(let $ of e.events){let w=$.payload??{};switch($.type){case "item.added":{let y=w,q=y.phase??(y.parent!==null?r.get(y.parent):void 0);r.set(y.id,q),o.set(y.id,y.type),c.set(y.id,"todo"),y.type==="change-request"&&(p+=1),ke(y.id)&&(s[q]+=1,y.type==="bug"&&(n[q]+=1));break}case "item.transition":{let y=w.id,q=w.to.status,Re=c.get(y);if(c.set(y,q),!ke(y))break;let ne=r.get(y);q==="done"&&Re!=="done"&&(f[ne]+=1),q==="dropped"&&(s[ne]-=1,Re==="done"&&(f[ne]-=1));break}case "item.completed":{let y=r.get(w.id);y!==void 0&&y in a&&(a[y]+=w.tokens??0);break}case "phase.opened":{let y=w.phase;y in d&&(d[y]=(w.budget??{}).tokens??0);break}case "traceability.computed":{let y=w.coverage;l=y.traced,u=y.total;break}case "change.decided":{w.decision==="approve"?(m+=1,x+=w.weight??0,we+=(w.reopened??[]).length):g+=1;break}}}let $e=i(),We=i();for(let $ of t){let w=s[$]??0;$e[$]=w===0?0:(f[$]??0)/w*100,We[$]=a[$]-d[$];}let Ae=m+g;return {phaseCompletion:$e,budgetPlanned:d,budgetSpent:a,scheduleVariance:We,requirementCoverage:u===0?0:l/u,requirementsTraced:l,requirementsTotal:u,defectsPerPhase:n,changeRequests:p,changesApproved:m,changesRejected:g,changeApprovalRate:Ae===0?0:m/Ae,reworkWeight:x,phasesReopened:we}}function he(e){let t=e.phases.map(i=>i.gate.id);return [{id:"project-manager",name:"Project Manager",modelTier:"large",capabilities:["facilitate","control-change","approve-gate","escalate"],canApprove:[...t,de],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 v=(e,t,i,s)=>s?{rule:e,severity:"error",item:s,message:t,fix:i}:{rule:e,severity:"error",message:t,fix:i},C=e=>e.payload??{},U=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),z=e=>{let t=C(e).phase;return typeof t=="string"?t:void 0},P=(e,t)=>b(e).find(i=>i.id===t),ye=e=>b(e).map(t=>t.id).join(", "),te=(e,t)=>typeof t=="string"&&Object.hasOwn(e.items,t)?e.items[t]:void 0;function Ve(e,t){if(t.phase!==void 0)return t.phase;let i=te(e,t.parent);return i?R(e,i):void 0}var He=e=>e.type!=="change-request"&&e.type!=="question",Ue=(e,t)=>`raise a change-request: addItem({ type: "change-request", affects: ["${e}"], impactAnalysis: { summary, reopen: ["${t}"], weight } }) and decide it in changeControlBoard`;function ze(e,t){let i=te(e,C(t).change);return i&&i.type==="change-request"?i:void 0}function be(){return [{id:"phase-sequential",severity:"error",check(n,r){let o=[];if(r.type==="ceremony.kickoff"){let c=z(r),l=c===void 0?void 0:P(n,c);if(!l)return [];l.status==="open"&&o.push(v("phase-sequential",`phase "${l.id}" is already open`,`gateReview "${l.id}" when its work is done`)),l.status==="baselined"&&o.push(v("phase-sequential",`phase "${l.id}" is baselined`,"only an approved change-request reopens a baselined phase"));let u=O(n);u&&u.id!==l.id&&o.push(v("phase-sequential",`phase "${u.id}" is still open`,`pass its gate (gateReview "${u.id}") before opening "${l.id}"`));}else if(r.type==="item.add"){let c=C(r).item;if(!U(c)||!He(c))return [];let l=Ve(n,c);l===void 0?o.push(v("phase-sequential",`item "${c.id}" belongs to no phase`,`set phase to one of: ${ye(n)}`,c.id)):P(n,l)||o.push(v("phase-sequential",`item "${c.id}" names unknown phase "${l}"`,`phases are: ${ye(n)}`,c.id));}else if(r.type==="item.edit"){let c=C(r).id,l=C(r).patch,u=te(n,c);if(!u||!U(l)||l.phase===void 0||l.phase===u.phase)return [];o.push(v("phase-sequential",`item "${u.id}" cannot move from phase "${u.phase??"(none)"}" to "${String(l.phase)}"`,`drop "${u.id}" and add a new item in phase "${String(l.phase)}"`,u.id));}return o}},{id:"gate-before-next-phase",severity:"error",check(n,r){if(r.type!=="ceremony.kickoff")return [];let o=z(r),c=b(n),l=o===void 0?-1:c.findIndex(p=>p.id===o);if(l<0)return [];let u=c.slice(0,l).filter(p=>p.status!=="baselined").map(p=>p.id);return u.length===0?[]:[v("gate-before-next-phase",`phase(s) ${u.join(", ")} before "${o}" are not baselined`,`kickoff and gateReview them in order, starting with "${u[0]}"`)]}},{id:"baseline-immutable",severity:"error",check(n,r){let o=c=>(n.baselines??[]).filter(l=>l.phase===c).length||1;if(r.type==="item.edit"){let c=te(n,C(r).id);if(!c)return [];let l=R(n,c);return l===void 0||P(n,l)?.status!=="baselined"?[]:[v("baseline-immutable",`item "${c.id}" is frozen: phase "${l}" is baselined (v${o(l)})`,Ue(c.id,l),c.id)]}if(r.type==="item.add"){let c=C(r).item;if(!U(c)||!He(c))return [];let l=Ve(n,c);return l===void 0||P(n,l)?.status!=="baselined"?[]:[v("baseline-immutable",`cannot add "${c.id}" to baselined phase "${l}" (v${o(l)})`,Ue(c.id,l),c.id)]}return []}},{id:"change-needs-impact-analysis",severity:"error",check(n,r){if(r.type!=="ceremony.changeControlBoard")return [];let o=ze(n,r);if(!o)return [];let c=k(n).changeControl,l=o.impactAnalysis,u=`editItem("${o.id}", { impactAnalysis: { summary: "what changes and why", reopen: ["<phase>"], weight: <points> } })`;if(l===void 0)return c.requiresImpactAnalysis?[v("change-needs-impact-analysis",`change "${o.id}" has no impact analysis`,u,o.id)]:[];let p=[];if((!U(l)||typeof l.summary!="string"||l.summary.trim()==="")&&p.push(v("change-needs-impact-analysis",`change "${o.id}" impactAnalysis.summary is empty`,u,o.id)),(!Array.isArray(l.reopen)||!l.reopen.every(g=>typeof g=="string"))&&p.push(v("change-needs-impact-analysis",`change "${o.id}" impactAnalysis.reopen must be a string[] of phase ids`,u,o.id)),(typeof l.weight!="number"||!Number.isFinite(l.weight)||l.weight<0)&&p.push(v("change-needs-impact-analysis",`change "${o.id}" impactAnalysis.weight must be a non-negative number`,u,o.id)),p.length)return p;let m=C(r).decision==="approve";for(let g of l.reopen){let x=P(n,g);x?m&&x.status==="pending"&&p.push(v("change-needs-impact-analysis",`phase "${g}" was never baselined; it cannot be reopened`,`remove "${g}" from impactAnalysis.reopen`,o.id)):p.push(v("change-needs-impact-analysis",`change "${o.id}" impactAnalysis.reopen names unknown phase "${g}"`,`phases are: ${ye(n)}`,o.id));}return p}},{id:"requirement-traced",severity:"error",check(n,r){if(r.type!=="ceremony.gateReview")return [];let o=z(r),c=k(n).traceability;return o===void 0||!c.to.includes(o)||!P(n,o)?[]:fe(n,o).map(l=>v("requirement-traced",`item "${l}" of phase "${c.from}" has no trace into "${o}"`,`editItem a "${o}" item with traces: ["${l}"] (or editItem("${l}", { traces: [...] }) while "${c.from}" is not baselined)`,l))}},{id:"deliverables-present",severity:"error",check(n,r){if(r.type!=="ceremony.gateReview")return [];let o=z(r),c=o===void 0?void 0:P(n,o);if(!c)return [];let l=[],u=A(n,c.id).filter(g=>g.status!=="done").map(g=>g.id);u.length&&l.push(v("deliverables-present",`${u.length} item(s) in phase "${c.id}" are not done: ${u.join(", ")}`,"finish them (next/complete) or drop them before the gate"));let p=C(r).deliverables,m=Array.isArray(p)?p.filter(g=>U(g)&&typeof g.kind=="string").map(g=>g.kind):[];c.id===N(n)&&m.push("traceability-matrix");for(let g of G(n,c,m))l.push(v("deliverables-present",`phase "${c.id}" has no deliverable "${g}"`,`pass deliverables: [{ "kind": "${g}", "ref": "<where it lives>" }] to gateReview, or attach evidence of kind "${g}" on an item of the phase`));return l}},{id:"approver-not-author",severity:"error",check(n,r){if(r.by==="human")return [];if(r.type==="ceremony.gateReview"){let o=z(r),c=o===void 0?void 0:P(n,o);if(!c)return [];let l=A(n,c.id).filter(p=>chunkSJRRQZ3R_cjs.G(n,p)===r.by).map(p=>p.id);if(l.length===0)return [];let u=chunkSJRRQZ3R_cjs.j(n,c.gate.id,"approve-gate",r.by);return [v("approver-not-author",`"${r.by}" authored ${l.join(", ")} in phase "${c.id}" and may not approve its gate`,`review the gate as one of: human${u.map(p=>`, ${p}`).join("")}`)]}if(r.type==="ceremony.changeControlBoard"){let o=ze(n,r);if(!o)return [];let c=n.events.find(u=>u.type==="item.added"&&u.payload.id===o.id);if(!c||c.by!==r.by)return [];let l=chunkSJRRQZ3R_cjs.i(n,"control-change").map(u=>u.id).filter(u=>u!==r.by);return [v("approver-not-author",`"${r.by}" raised change "${o.id}" and may not decide it`,`decide as human${l.map(u=>`, ${u}`).join("")}`,o.id)]}return []}}]}function ve(e){return [{id:L,name:"Work",entryPolicy:[{kind:"dependencies-done"}],exitPolicy:[]},{id:_,name:"Review",entryPolicy:[],exitPolicy:[{kind:"no-open-blockers"}],review:true},{id:M,name:"Done",entryPolicy:[],exitPolicy:[]}]}var nt={backlog:"Requirements Baseline",item:"Work Package",stage:"Step",iteration:"Phase",increment:"Deliverable",ceremony:"Review",gate:"Phase Gate"};function it(e,t){let i=R(e,t);if(i!==void 0)return k(e).phases.find(s=>s.id===i)?.deliverBy}function rt(e){return {phases:b(e).map(i=>{let s=A(e,i.id),f=s.filter(a=>a.status==="done").length,d=G(e,i);return {id:i.id,name:i.name,status:i.status,items:s.length,done:f,missingDeliverables:d,readyForGate:i.status==="open"&&f===s.length&&d.length===0}}),current:le(e)?.id??null,open:O(e)?.id??null,pendingGates:e.pending.filter(i=>i.kind==="gate"&&i.item===void 0&&i.gate!==void 0).map(i=>({pending:i.id,gate:i.gate}))}}function st(){return {name:"waterfall",vocabulary:nt,validateConfig:ce,defaultStages:ve,defaultRoles:he,requiredCapabilities:["facilitate","control-change","approve-gate","deliver","verify"],exclusiveCapabilities:[],plannerOptions(e){return {schedulerMode:"level",roleFor:t=>t.status==="todo"&&t.type!=="question"?it(e,t):void 0}},candidates(e){let t=O(e);return t?Object.values(e.items).filter(i=>(i.status==="todo"||i.status==="review")&&(i.stage===L||i.stage===_)&&i.type!=="change-request"&&R(e,i)===t.id):[]},invariants(e,t){let i=k(e),s=b(e),f=R(e,t),d=f===void 0?void 0:s[I(e,f)],a=s.filter(r=>r.status==="baselined").map(r=>r.id),n=d?.gate.requires.includes("human");return [d?`Phase "${d.name}" (${I(e,d.id)+1}/${s.length}); deliverables: ${d.deliverables.join(", ")||"(none)"}; gate "${d.gate.id}"${n?" needs human approval":""}`:"This item belongs to no phase; it is dispatched only through its parent's phase",`Baselined phases are frozen: ${a.join(", ")||"(none yet)"}; to change their items, raise a change-request with an impact analysis`,i.traceability.to.length?`Traceability: every item of phase "${i.traceability.from}" must trace to an item in ${i.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:ue(st),rules:be(),metrics:e=>({...me(e)}),humanDefaults:{gates:"all"},report:e=>({...rt(e),coverage:T(e).coverage}),afterDecide:ge,afterComplete(e,t,i){let s=chunkCWBH7H52_cjs.f(e),f=O(e);if(!s||!f||s.committed.includes(t))return e;let d=e.items[t];if(!d||R(e,d)!==f.id)return e;let a=e.accounting[e.accounting.length-1];return !a||a.item!==t?e:{...e,iterations:e.iterations.map(n=>n.id===s.id?{...n,committed:[...n.committed,t],spent:chunkCWBH7H52_cjs.b(n.spent,a)}:n)}}}}exports.A=V;exports.B=T;exports.C=fe;exports.D=H;exports.E=ue;exports.F=ge;exports.G=me;exports.H=he;exports.I=be;exports.J=ve;exports.K=nt;exports.L=it;exports.M=rt;exports.N=st;exports.a=je;exports.b=se;exports.c=oe;exports.d=ae;exports.e=de;exports.f=Te;exports.g=k;exports.h=ce;exports.i=L;exports.j=_;exports.k=M;exports.l=b;exports.m=S;exports.n=I;exports.o=E;exports.p=R;exports.q=A;exports.r=O;exports.s=le;exports.t=Ye;exports.u=Be;exports.v=G;exports.w=N;exports.x=ee;exports.y=pe;exports.z=F;//# sourceMappingURL=chunk-KSKEFYY7.cjs.map
2
+ //# sourceMappingURL=chunk-KSKEFYY7.cjs.map