ex-workflow 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +145 -13
  3. package/dist/adapters/index.cjs +1 -1
  4. package/dist/adapters/index.d.cts +1 -1
  5. package/dist/adapters/index.d.ts +1 -1
  6. package/dist/adapters/index.mjs +1 -1
  7. package/dist/{budget-Gckmqj74.d.ts → budget-BuQ9GWsg.d.ts} +1 -1
  8. package/dist/{budget-Bm839Qw0.d.cts → budget-DDqQQIgp.d.cts} +1 -1
  9. package/dist/{chunk-VXOZIP77.cjs → chunk-2FBA7RBS.cjs} +2 -2
  10. package/dist/{chunk-VXOZIP77.cjs.map → chunk-2FBA7RBS.cjs.map} +1 -1
  11. package/dist/chunk-3S7F5QXK.mjs +2 -0
  12. package/dist/{chunk-BYPFTO7P.mjs.map → chunk-3S7F5QXK.mjs.map} +1 -1
  13. package/dist/{chunk-K4VSMIJZ.cjs → chunk-3ZUBCA7Q.cjs} +2 -2
  14. package/dist/{chunk-K4VSMIJZ.cjs.map → chunk-3ZUBCA7Q.cjs.map} +1 -1
  15. package/dist/chunk-4F5HZLKD.cjs +2 -0
  16. package/dist/{chunk-SFYUJQYW.cjs.map → chunk-4F5HZLKD.cjs.map} +1 -1
  17. package/dist/{chunk-4HG6A3SF.mjs → chunk-5DCOXGRW.mjs} +2 -2
  18. package/dist/{chunk-4HG6A3SF.mjs.map → chunk-5DCOXGRW.mjs.map} +1 -1
  19. package/dist/chunk-5GXB6GMX.mjs +2 -0
  20. package/dist/chunk-5GXB6GMX.mjs.map +1 -0
  21. package/dist/chunk-5ZGNEY2I.mjs +2 -0
  22. package/dist/{chunk-32NVJV5C.mjs.map → chunk-5ZGNEY2I.mjs.map} +1 -1
  23. package/dist/chunk-6PFJYRM7.cjs +2 -0
  24. package/dist/chunk-6PFJYRM7.cjs.map +1 -0
  25. package/dist/{chunk-W2P27645.cjs → chunk-BANKVCYY.cjs} +2 -2
  26. package/dist/{chunk-W2P27645.cjs.map → chunk-BANKVCYY.cjs.map} +1 -1
  27. package/dist/chunk-BD665RYK.mjs +2 -0
  28. package/dist/chunk-BD665RYK.mjs.map +1 -0
  29. package/dist/chunk-COPYGMHE.mjs +2 -0
  30. package/dist/chunk-COPYGMHE.mjs.map +1 -0
  31. package/dist/{chunk-3O5MPAJT.cjs → chunk-CVGEIXW6.cjs} +2 -2
  32. package/dist/{chunk-3O5MPAJT.cjs.map → chunk-CVGEIXW6.cjs.map} +1 -1
  33. package/dist/chunk-CX2E7ZTQ.mjs +2 -0
  34. package/dist/{chunk-JNLWI4JM.mjs.map → chunk-CX2E7ZTQ.mjs.map} +1 -1
  35. package/dist/chunk-DVFTTBCT.cjs +3 -0
  36. package/dist/chunk-DVFTTBCT.cjs.map +1 -0
  37. package/dist/{chunk-U3RU5LOF.cjs → chunk-EQXYFHHD.cjs} +2 -2
  38. package/dist/{chunk-U3RU5LOF.cjs.map → chunk-EQXYFHHD.cjs.map} +1 -1
  39. package/dist/{chunk-OVR5CK3R.cjs → chunk-H26KXQ3I.cjs} +2 -2
  40. package/dist/{chunk-OVR5CK3R.cjs.map → chunk-H26KXQ3I.cjs.map} +1 -1
  41. package/dist/chunk-ILDXZWEL.mjs +2 -0
  42. package/dist/{chunk-OZAYOPLB.mjs.map → chunk-ILDXZWEL.mjs.map} +1 -1
  43. package/dist/{chunk-RXY434DX.cjs → chunk-KA6DVHO5.cjs} +4 -4
  44. package/dist/{chunk-RXY434DX.cjs.map → chunk-KA6DVHO5.cjs.map} +1 -1
  45. package/dist/chunk-KLOSFZFK.cjs +2 -0
  46. package/dist/chunk-KLOSFZFK.cjs.map +1 -0
  47. package/dist/{chunk-WPVL27G4.mjs → chunk-LG23WXAP.mjs} +2 -2
  48. package/dist/{chunk-WPVL27G4.mjs.map → chunk-LG23WXAP.mjs.map} +1 -1
  49. package/dist/chunk-MU26QW32.cjs +2 -0
  50. package/dist/chunk-MU26QW32.cjs.map +1 -0
  51. package/dist/chunk-OEHVWRJG.mjs +2 -0
  52. package/dist/{chunk-7EF47R2J.mjs.map → chunk-OEHVWRJG.mjs.map} +1 -1
  53. package/dist/{chunk-3GKYL6VB.mjs → chunk-ONVAUZOD.mjs} +3 -3
  54. package/dist/{chunk-3GKYL6VB.mjs.map → chunk-ONVAUZOD.mjs.map} +1 -1
  55. package/dist/{chunk-LIATP6LY.mjs → chunk-PFHVB2WT.mjs} +2 -2
  56. package/dist/{chunk-LIATP6LY.mjs.map → chunk-PFHVB2WT.mjs.map} +1 -1
  57. package/dist/chunk-QJMOCISZ.mjs +3 -0
  58. package/dist/chunk-QJMOCISZ.mjs.map +1 -0
  59. package/dist/chunk-RGHM3JJM.cjs +2 -0
  60. package/dist/chunk-RGHM3JJM.cjs.map +1 -0
  61. package/dist/chunk-UMG3WOD7.cjs +2 -0
  62. package/dist/{chunk-QAENYYU6.cjs.map → chunk-UMG3WOD7.cjs.map} +1 -1
  63. package/dist/{chunk-6D6FL3XK.mjs → chunk-UT7QV6CE.mjs} +2 -2
  64. package/dist/{chunk-6D6FL3XK.mjs.map → chunk-UT7QV6CE.mjs.map} +1 -1
  65. package/dist/chunk-WU5JELOM.mjs +2 -0
  66. package/dist/chunk-WU5JELOM.mjs.map +1 -0
  67. package/dist/{chunk-IIEKK2S3.cjs → chunk-YGCNLXPJ.cjs} +2 -2
  68. package/dist/{chunk-IIEKK2S3.cjs.map → chunk-YGCNLXPJ.cjs.map} +1 -1
  69. package/dist/cli/bin.cjs +1 -1
  70. package/dist/cli/bin.cjs.map +1 -1
  71. package/dist/cli/bin.mjs +1 -1
  72. package/dist/cli/bin.mjs.map +1 -1
  73. package/dist/cli/index.cjs +1 -1
  74. package/dist/cli/index.mjs +1 -1
  75. package/dist/experimentation/index.cjs +1 -1
  76. package/dist/experimentation/index.d.cts +2 -2
  77. package/dist/experimentation/index.d.ts +2 -2
  78. package/dist/experimentation/index.mjs +1 -1
  79. package/dist/index.cjs +1 -1
  80. package/dist/index.cjs.map +1 -1
  81. package/dist/index.d.cts +8 -6
  82. package/dist/index.d.ts +8 -6
  83. package/dist/index.mjs +1 -1
  84. package/dist/index.mjs.map +1 -1
  85. package/dist/investigation/index.cjs +1 -1
  86. package/dist/investigation/index.d.cts +2 -2
  87. package/dist/investigation/index.d.ts +2 -2
  88. package/dist/investigation/index.mjs +1 -1
  89. package/dist/kanban/index.cjs +1 -1
  90. package/dist/kanban/index.d.cts +1 -1
  91. package/dist/kanban/index.d.ts +1 -1
  92. package/dist/kanban/index.mjs +1 -1
  93. package/dist/policies/index.cjs +2 -0
  94. package/dist/policies/index.cjs.map +1 -0
  95. package/dist/policies/index.d.cts +199 -0
  96. package/dist/policies/index.d.ts +199 -0
  97. package/dist/policies/index.mjs +2 -0
  98. package/dist/policies/index.mjs.map +1 -0
  99. package/dist/registry/index.cjs +1 -1
  100. package/dist/registry/index.d.cts +1 -1
  101. package/dist/registry/index.d.ts +1 -1
  102. package/dist/registry/index.mjs +1 -1
  103. package/dist/schema/index.cjs +1 -1
  104. package/dist/schema/index.mjs +1 -1
  105. package/dist/scrum/index.cjs +1 -1
  106. package/dist/scrum/index.d.cts +3 -3
  107. package/dist/scrum/index.d.ts +3 -3
  108. package/dist/scrum/index.mjs +1 -1
  109. package/dist/{types-DjePDfms.d.cts → types-DLOtndDY.d.cts} +61 -1
  110. package/dist/{types-DjePDfms.d.ts → types-DLOtndDY.d.ts} +61 -1
  111. package/dist/types.d.cts +1 -1
  112. package/dist/types.d.ts +1 -1
  113. package/dist/waterfall/index.cjs +1 -1
  114. package/dist/waterfall/index.d.cts +1 -1
  115. package/dist/waterfall/index.d.ts +1 -1
  116. package/dist/waterfall/index.mjs +1 -1
  117. package/package.json +14 -1
  118. package/dist/chunk-32NVJV5C.mjs +0 -2
  119. package/dist/chunk-43GLYYA2.cjs +0 -3
  120. package/dist/chunk-43GLYYA2.cjs.map +0 -1
  121. package/dist/chunk-7EF47R2J.mjs +0 -2
  122. package/dist/chunk-BD76VFI4.mjs +0 -3
  123. package/dist/chunk-BD76VFI4.mjs.map +0 -1
  124. package/dist/chunk-BHAEPYRJ.cjs +0 -2
  125. package/dist/chunk-BHAEPYRJ.cjs.map +0 -1
  126. package/dist/chunk-BYPFTO7P.mjs +0 -2
  127. package/dist/chunk-FDZB73PH.mjs +0 -2
  128. package/dist/chunk-FDZB73PH.mjs.map +0 -1
  129. package/dist/chunk-JNLWI4JM.mjs +0 -2
  130. package/dist/chunk-LCN4UNYK.cjs +0 -2
  131. package/dist/chunk-LCN4UNYK.cjs.map +0 -1
  132. package/dist/chunk-MB465DI4.mjs +0 -2
  133. package/dist/chunk-MB465DI4.mjs.map +0 -1
  134. package/dist/chunk-OZAYOPLB.mjs +0 -2
  135. package/dist/chunk-QAENYYU6.cjs +0 -2
  136. package/dist/chunk-SFYUJQYW.cjs +0 -2
  137. package/dist/chunk-UUWDQVIJ.mjs +0 -2
  138. package/dist/chunk-UUWDQVIJ.mjs.map +0 -1
  139. package/dist/chunk-Z43GUETW.cjs +0 -2
  140. package/dist/chunk-Z43GUETW.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/roles/registry.ts","../src/core/brief.ts","../src/core/complete.ts","../src/core/accounting.ts"],"names":["OPEN","registerRole","state","role","by","now","assertId","roleOf","fail","next","appendEvent","retireRole","roleId","open","i","roles","completions","itemId","out","ev","lastCompletion","all","synthesizeBrief","methodology","item","upstream","doNot","sources","dep","p","d","priorHandoffs","touched","relatedBugs","b","a","it","openIteration","gate","stageOf","brief","remaining","openQuestions","last","opts","res","plan","briefs","VERDICTS","LESSON_SCOPES","isObj","x","str","validate","handoff","acc","getItem","bad","what","fix","verdict","lessons","l","followUps","f","k","pulledFromStage","t","reworkStage","lastDispatchBefore","complete","result","ruled","applyAction","completeBody","at","nowOf","id","s","addEvidence","addSpent","lid","first","_drop","rest","addItem","warnings","clearRole","moveItem","lastStageId","stage","assertPolicies","checkGate","v","raisePending","advanceItem","raiseBlocker","thinker","rolesWith","n","qid","parent","pulledFrom","q","patchItem","NUMERIC","pick","correctAccounting","patch","line","indexes","idx","before","flag","after","delta","owner"],"mappings":"qHAKA,IAAMA,EAAAA,CAA4B,IAAI,GAAA,CAAI,CAAC,aAAA,CAAe,QAAA,CAAU,SAAS,CAAC,CAAA,CAcvE,SAASC,EAAAA,CACdC,CAAAA,CACAC,EACAC,CAAAA,CACAC,CAAAA,CACkB,CAClBC,mBAAAA,CAASH,CAAAA,CAAK,EAAA,CAAI,SAAS,CAAA,CACvBI,oBAAOL,CAAAA,CAAOC,CAAAA,CAAK,EAAE,CAAA,EACvBK,mBAAAA,CACE,gBAAA,CACA,CAAA,MAAA,EAASL,CAAAA,CAAK,EAAE,CAAA,gBAAA,CAAA,CAChB,CAAA,kCAAA,EAAqCA,CAAAA,CAAK,EAAE,CAAA,QAAA,CAC9C,CAAA,CACF,IAAMM,CAAAA,CAAO,CAAE,GAAGP,CAAAA,CAAO,KAAA,CAAO,CAAE,GAAGA,CAAAA,CAAM,KAAA,CAAO,CAACC,EAAK,EAAE,EAAGA,CAAK,CAAE,CAAA,CACpE,OAAOO,mBAAAA,CACLD,CAAAA,CACA,kBACAL,CAAAA,CACA,CAAE,IAAA,CAAMD,CAAAA,CAAK,EAAA,CAAI,YAAA,CAAcA,CAAAA,CAAK,YAAa,EACjDE,CACF,CACF,CAcO,SAASM,EAAAA,CACdT,CAAAA,CACAU,CAAAA,CACAR,CAAAA,CACAC,EACkB,CACbE,mBAAAA,CAAOL,CAAAA,CAAOU,CAAM,CAAA,EACvBJ,mBAAAA,CACE,cAAA,CACA,CAAA,MAAA,EAASI,CAAM,CAAA,gBAAA,CAAA,CACf,CAAA,kBAAA,EAAqB,MAAA,CAAO,IAAA,CAAKV,CAAAA,CAAM,KAAK,CAAA,CAAE,IAAA,CAAK,IAAI,CAAA,EAAK,QAAQ,CAAA,CACtE,CAAA,CACF,IAAMW,CAAAA,CAAO,MAAA,CAAO,MA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AAA,EAAa4E,CAAAA,CAAO,OAAA,EAAW5E,CAAAA,CAAG,OAAA,CAAA,GAElDgF,EAAQhF,CAAAA,CAAAA,CAEZ,IAAI0C,CAAAA,CAAsB,CACxB,GAAG5E,CAAAA,CACH,UAAA,CAAYA,CAAAA,CAAM,WAAW,GAAA,CAAI,CAACiD,CAAAA,CAAGrC,CAAAA,GAAOA,CAAAA,GAAMiG,CAAAA,CAAMG,CAAAA,CAAQ/D,CAAE,CACpE,CAAA,CACA,OAAIiE,CAAAA,GACFtC,CAAAA,CAAI,CACF,GAAGA,CAAAA,CACH,UAAA,CAAYA,EAAE,UAAA,CAAW,GAAA,CAAK1C,CAAAA,EAC5BA,CAAAA,CAAG,EAAA,GAAOgF,CAAAA,CAAM,EAAA,CACZ,CACE,GAAGhF,CAAAA,CACH,KAAA,CAAO,CACL,GAAGA,CAAAA,CAAG,KAAA,CACN,MAAA,CAAQ,IAAA,CAAK,IAAI,CAAA,CAAGA,CAAAA,CAAG,KAAA,CAAM,MAAA,CAAS+E,CAAAA,CAAM,MAAM,CAAA,CAClD,WAAA,CAAa,KAAK,GAAA,CAAI,CAAA,CAAG/E,CAAAA,CAAG,KAAA,CAAM,WAAA,CAAc+E,CAAAA,CAAM,UAAU,CAClE,CACF,CAAA,CACA/E,CACN,CACF,CAAA,CAAA,CACK1B,mBAAAA,CACLoE,CAAAA,CACA,sBAAA,CACA1E,CAAAA,CACA,CACE,IAAA,CAAMa,CAAAA,CACN,IAAA,CAAMkF,CAAAA,CACN,SAAA,CAAWiB,CAAAA,EAAO,EAAA,EAAM,IAAA,CACxB,OAAQlF,CAAAA,CACR,KAAA,CAAOC,CAAAA,CACP,KAAA,CAAAgF,CACF,CAAA,CACAvC,mBAAAA,CAAMvE,CAAG,CACX,CACF","file":"chunk-LCN4UNYK.cjs","sourcesContent":["import { assertId, fail } from \"../errors.ts\";\nimport { appendEvent } from \"../state.ts\";\nimport type { Role, WorkflowState } from \"../types.ts\";\nimport { roleOf } from \"./lookup.ts\";\n\nconst OPEN: ReadonlySet<string> = new Set([\"in_progress\", \"review\", \"blocked\"]);\n\nexport function registerRole<N extends string>(\n state: WorkflowState<N>,\n role: Role,\n by: string,\n now?: string,\n): WorkflowState<N>;\nexport function registerRole(\n state: WorkflowState,\n role: Role,\n by: string,\n now?: string,\n): WorkflowState;\nexport function registerRole<N extends string>(\n state: WorkflowState<N>,\n role: Role,\n by: string,\n now?: string,\n): WorkflowState<N> {\n assertId(role.id, \"role id\");\n if (roleOf(state, role.id))\n fail(\n \"duplicate-role\",\n `role \"${role.id}\" already exists`,\n `use a different id or retireRole(\"${role.id}\") first`,\n );\n const next = { ...state, roles: { ...state.roles, [role.id]: role } };\n return appendEvent(\n next,\n \"role.registered\",\n by,\n { role: role.id, capabilities: role.capabilities },\n now,\n );\n}\n\nexport function retireRole<N extends string>(\n state: WorkflowState<N>,\n roleId: string,\n by: string,\n now?: string,\n): WorkflowState<N>;\nexport function retireRole(\n state: WorkflowState,\n roleId: string,\n by: string,\n now?: string,\n): WorkflowState;\nexport function retireRole<N extends string>(\n state: WorkflowState<N>,\n roleId: string,\n by: string,\n now?: string,\n): WorkflowState<N> {\n if (!roleOf(state, roleId))\n fail(\n \"unknown-role\",\n `role \"${roleId}\" does not exist`,\n `registered roles: ${Object.keys(state.roles).join(\", \") || \"(none)\"}`,\n );\n const open = Object.values(state.items)\n .filter((i) => i.role === roleId && OPEN.has(i.status))\n .map((i) => i.id);\n if (open.length)\n fail(\n \"role-has-open-items\",\n `role \"${roleId}\" still holds ${open.length} open item(s)`,\n `complete or reassign ${open.join(\", \")} before retiring the role`,\n { items: open },\n );\n const roles = { ...state.roles };\n delete roles[roleId];\n return appendEvent({ ...state, roles }, \"role.retired\", by, { role: roleId }, now);\n}\n","import { remaining } from \"./budget.ts\";\nimport { fail } from \"./errors.ts\";\nimport { stageOf } from \"./items/stage.ts\";\nimport { openIteration, plan, type PlanOptions, type PlanReason, type Skipped } from \"./planner.ts\";\nimport { roleOf } from \"./roles/lookup.ts\";\nimport type {\n Brief,\n Handoff,\n Methodology,\n MethodologyName,\n Verdict,\n WorkItem,\n WorkflowState,\n} 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 open_questions?: string[];\n}\n\nfunction completions(\n state: WorkflowState<string>,\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(\n state: WorkflowState<string>,\n itemId: string,\n): CompletedPayload | undefined {\n const all = completions(state, itemId);\n return all[all.length - 1];\n}\n\nexport function synthesizeBrief<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\n item: WorkItem,\n): Brief;\nexport function synthesizeBrief(\n state: WorkflowState,\n methodology: Methodology,\n item: WorkItem,\n): Brief;\nexport function synthesizeBrief<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\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 if (item.type === \"question\" && item.parent) {\n const p = lastCompletion(state, item.parent);\n if (p) {\n brief.parent = {\n item: item.parent,\n role: p.role,\n notes: p.notes,\n produced: p.produced,\n open_questions: p.open_questions ?? [],\n do_not: p.do_not,\n };\n for (const d of p.do_not) if (!doNot.includes(d)) doNot.push(d);\n }\n }\n return brief;\n}\n\n/** Open questions of finished items: the last completion per item, verdict done/needs-review, with open_questions left unanswered. */\nexport function openQuestions(\n state: WorkflowState<string>,\n): Array<{ item: string; role: string; questions: string[]; at: string }>;\nexport function openQuestions(\n state: WorkflowState,\n): Array<{ item: string; role: string; questions: string[]; at: string }>;\nexport function openQuestions(\n state: WorkflowState<string>,\n): Array<{ item: string; role: string; questions: string[]; at: string }> {\n const last = new Map<string, CompletedPayload & { at: string }>();\n for (const ev of state.events) {\n if (ev.type !== \"item.completed\") continue;\n const p = ev.payload as CompletedPayload;\n last.delete(p.id);\n last.set(p.id, { ...p, at: ev.at });\n }\n return [...last.values()]\n .filter(\n (p) =>\n (p.verdict === \"done\" || p.verdict === \"needs-review\") &&\n (p.open_questions ?? []).length > 0,\n )\n .map((p) => ({ item: p.id, role: p.role, questions: p.open_questions ?? [], at: p.at }));\n}\n\nexport interface NextResult<N extends string = MethodologyName> {\n state: WorkflowState<N>;\n briefs: Brief[];\n skipped: Skipped[];\n reason?: PlanReason;\n}\n\nexport function next<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\n opts?: PlanOptions,\n): NextResult<N>;\nexport function next(\n state: WorkflowState,\n methodology: Methodology,\n opts?: PlanOptions,\n): NextResult;\nexport function next<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\n opts: PlanOptions = {},\n): NextResult<N> {\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 { addEvidence } from \"./items/evidence.ts\";\nimport { addItem, getItem, patchItem } from \"./items/record.ts\";\nimport { advanceItem, clearRole, moveItem } from \"./items/move.ts\";\nimport { raiseBlocker } from \"./items/blockers.ts\";\nimport { stageOf } from \"./items/stage.ts\";\nimport { applyAction } from \"./methodology.ts\";\nimport { assertPolicies } from \"./policies.ts\";\nimport { openIteration } from \"./planner.ts\";\nimport { rolesWith } from \"./roles/lookup.ts\";\nimport { appendEvent, nowOf } from \"./state.ts\";\nimport type {\n Accounting,\n ApplyResult,\n Handoff,\n Methodology,\n NewItem,\n Violation,\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<string>, 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 if (acc.tokensIn + acc.tokensOut === 0 && acc.estimate !== true)\n fail(\n \"accounting-invalid\",\n `accounting for \"${item.id}\" records 0 tokens`,\n \"pass the host's usage figures, or set estimate: true (CLI --estimate) to record a placeholder and correct it later with correctAccounting / exwf account\",\n { items: [item.id] },\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<string>, item: WorkItem): string {\n return lastDispatchBefore(state, item)?.from.stage ?? pulledFromStage(item);\n}\n\nexport function complete<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\n handoff: Handoff,\n acc: Accounting,\n now?: string,\n): ApplyResult<N>;\nexport function complete(\n state: WorkflowState,\n methodology: Methodology,\n handoff: Handoff,\n acc: Accounting,\n now?: string,\n): ApplyResult;\nexport function complete<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\n handoff: Handoff,\n acc: Accounting,\n now?: string,\n): ApplyResult<N> {\n validate(state, handoff, acc);\n // the methodology's rules see the completion (applyAction validates, appends nothing, then reduces)\n let result: ApplyResult<N> | undefined;\n const ruled = applyAction(\n state,\n methodology,\n { type: \"item.complete\", by: handoff.role, payload: { item: handoff.item, handoff } },\n () => {\n result = completeBody(state, methodology, handoff, acc, now);\n return result.state;\n },\n );\n return { state: ruled.state, warnings: [...ruled.warnings, ...result!.warnings] };\n}\n\nfunction completeBody<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\n handoff: Handoff,\n acc: Accounting,\n now?: string,\n): ApplyResult<N> {\n const at = nowOf(now);\n const id = handoff.item;\n const role = handoff.role;\n let s: WorkflowState<N> = { ...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 const warnings: Violation[] = [];\n if ((verdict === \"done\" || verdict === \"needs-review\") && handoff.open_questions.length > 0)\n warnings.push({\n rule: \"open-questions-ignored\",\n severity: \"warning\",\n item: id,\n message: `\"${id}\" finished with ${handoff.open_questions.length} open question(s) nobody will see: ${handoff.open_questions.join(\" | \")}`,\n fix: 'use verdict \"escalate\" to route them to a role with capability escalate, or answer them in the next brief',\n });\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","import { fail } from \"./errors.ts\";\nimport { getItem } from \"./items/record.ts\";\nimport { appendEvent, nowOf } from \"./state.ts\";\nimport type { Accounting, Iteration, WorkflowState } from \"./types.ts\";\n\nexport interface AccountingPatch {\n tokensIn?: number;\n tokensOut?: number;\n durationMs?: number;\n model?: string;\n}\n\nconst NUMERIC = [\n [\"tokensIn\", \"tokens-in\"],\n [\"tokensOut\", \"tokens-out\"],\n [\"durationMs\", \"duration-ms\"],\n] as const;\n\nconst pick = (a: Accounting) => ({\n tokensIn: a.tokensIn,\n tokensOut: a.tokensOut,\n durationMs: a.durationMs,\n model: a.model,\n});\n\n/**\n * Rewrite one accounting line of an item (`line` is 1-based among the item's lines, default the last).\n * The owning iteration's spent follows the delta, open or closed; the event records before/after.\n */\nexport function correctAccounting<N extends string>(\n state: WorkflowState<N>,\n itemId: string,\n patch: AccountingPatch,\n by: string,\n now?: string,\n line?: number,\n): WorkflowState<N>;\nexport function correctAccounting(\n state: WorkflowState,\n itemId: string,\n patch: AccountingPatch,\n by: string,\n now?: string,\n line?: number,\n): WorkflowState;\nexport function correctAccounting<N extends string>(\n state: WorkflowState<N>,\n itemId: string,\n patch: AccountingPatch,\n by: string,\n now?: string,\n line?: number,\n): WorkflowState<N> {\n getItem(state, itemId);\n const indexes: number[] = [];\n state.accounting.forEach((a, i) => {\n if (a.item === itemId) indexes.push(i);\n });\n if (indexes.length === 0)\n fail(\n \"invalid-input\",\n `item \"${itemId}\" has no accounting line to correct`,\n `complete \"${itemId}\" first (exwf complete), then exwf account`,\n { items: [itemId] },\n );\n const n = line ?? indexes.length;\n if (!Number.isInteger(n) || n < 1 || n > indexes.length)\n fail(\n \"invalid-input\",\n `item \"${itemId}\" has ${indexes.length} accounting line(s), not line ${String(line)}`,\n `pass --line 1..${indexes.length}`,\n { items: [itemId] },\n );\n const idx = indexes[n - 1]!;\n const before = state.accounting[idx]!;\n for (const [k, flag] of NUMERIC) {\n const v = patch[k];\n if (v !== undefined && (!Number.isFinite(v) || v < 0))\n fail(\n \"accounting-invalid\",\n `${k} must be a non-negative number`,\n `pass --${flag} <n> with a measured figure`,\n { items: [itemId] },\n );\n }\n if (patch.model !== undefined && patch.model.trim() === \"\")\n fail(\n \"accounting-invalid\",\n \"model must not be empty\",\n \"pass --model with the model id that ran the work\",\n { items: [itemId] },\n );\n const { estimate: _drop, ...rest } = before;\n const after: Accounting = {\n ...rest,\n tokensIn: patch.tokensIn ?? before.tokensIn,\n tokensOut: patch.tokensOut ?? before.tokensOut,\n durationMs: patch.durationMs ?? before.durationMs,\n model: patch.model ?? before.model,\n };\n if (after.tokensIn + after.tokensOut === 0)\n fail(\n \"accounting-invalid\",\n `the correction leaves \"${itemId}\" at 0 tokens`,\n \"pass the host's usage figures with --tokens-in / --tokens-out\",\n { items: [itemId] },\n );\n const b = pick(before);\n const a = pick(after);\n const unchanged =\n b.tokensIn === a.tokensIn &&\n b.tokensOut === a.tokensOut &&\n b.durationMs === a.durationMs &&\n b.model === a.model;\n // replacing a placeholder with the same figures still settles it, so it is not a no-op\n if (unchanged && before.estimate !== true)\n fail(\n \"no-op\",\n `accounting for \"${itemId}\" line ${n} already has these figures`,\n \"pass at least one different value to exwf account\",\n { items: [itemId] },\n );\n const delta = {\n tokens: a.tokensIn + a.tokensOut - (b.tokensIn + b.tokensOut),\n durationMs: a.durationMs - b.durationMs,\n };\n const item = state.items[itemId]!;\n let owner: Iteration | undefined;\n for (const it of state.iterations) {\n // the last iteration that was open when the line was recorded and carried the item\n if (\n (it.committed.includes(itemId) || item.iteration === it.id) &&\n it.startedAt <= before.endedAt &&\n (it.endedAt === undefined || before.endedAt <= it.endedAt)\n )\n owner = it;\n }\n let s: WorkflowState<N> = {\n ...state,\n accounting: state.accounting.map((x, i) => (i === idx ? after : x)),\n };\n if (owner)\n s = {\n ...s,\n iterations: s.iterations.map((it) =>\n it.id === owner.id\n ? {\n ...it,\n spent: {\n ...it.spent,\n tokens: Math.max(0, it.spent.tokens + delta.tokens),\n wallclockMs: Math.max(0, it.spent.wallclockMs + delta.durationMs),\n },\n }\n : it,\n ),\n };\n return appendEvent(\n s,\n \"accounting.corrected\",\n by,\n {\n item: itemId,\n line: n,\n iteration: owner?.id ?? null,\n before: b,\n after: a,\n delta,\n },\n nowOf(now),\n );\n}\n"]}
@@ -1,2 +0,0 @@
1
- import {e,c as c$1,N,n,K as K$1,R,U,a,y,r,J as J$1,s,v,u,C,F,G,w,z,g,q,D}from'./chunk-UUWDQVIJ.mjs';import {c,b}from'./chunk-YS6CXERQ.mjs';var te=new Set(["in_progress","review","blocked"]);function ce(s,o,e$1,i){c(o.id,"role id"),e(s,o.id)&&b("duplicate-role",`role "${o.id}" already exists`,`use a different id or retireRole("${o.id}") first`);let u={...s,roles:{...s.roles,[o.id]:o}};return c$1(u,"role.registered",e$1,{role:o.id,capabilities:o.capabilities},i)}function ue(s,o,e$1,i){e(s,o)||b("unknown-role",`role "${o}" does not exist`,`registered roles: ${Object.keys(s.roles).join(", ")||"(none)"}`);let u=Object.values(s.items).filter(r=>r.role===o&&te.has(r.status)).map(r=>r.id);u.length&&b("role-has-open-items",`role "${o}" still holds ${u.length} open item(s)`,`complete or reassign ${u.join(", ")} before retiring the role`,{items:u});let a={...s.roles};return delete a[o],c$1({...s,roles:a},"role.retired",e$1,{role:o},i)}function X(s,o){let e=[];for(let i of s.events)i.type==="item.completed"&&i.payload.id===o&&e.push({...i.payload,at:i.at});return e}function J(s,o){let e=X(s,o);return e[e.length-1]}function oe(s,o,e$1){e$1.role||b("unknown-role",`item "${e$1.id}" has no role assigned`,"dispatch it with next() or set item.role",{items:[e$1.id]});let i=e(s,e$1.role);i||b("unknown-role",`role "${e$1.role}" does not exist`,`registered roles: ${Object.keys(s.roles).join(", ")}`);let u=[],a=[...i.do_not],r=[...e$1.dependsOn,...e$1.type==="bug"||e$1.type==="change-request"?e$1.affects??[]:[]];for(let n of r){let l=J(s,n);if(l){u.push({item:n,produced:l.produced,notes:l.notes});for(let m of l.do_not)a.includes(m)||a.push(m);}}let d=X(s,e$1.id).map(n=>({role:n.role,verdict:n.verdict,notes:n.notes,produced:n.produced,at:n.at})),t=new Set([e$1.id,...e$1.dependsOn]),f=Object.values(s.items).filter(n=>(n.type==="bug"||n.type==="change-request")&&n.id!==e$1.id&&n.status!=="done"&&n.status!=="dropped"&&(n.affects??[]).some(l=>t.has(l))).map(n=>({id:n.id,title:n.title,affects:n.affects??[]})),v=N(s),g=n(s,e$1.stage).gate,w={item:e$1,role:i,modelTier:i.modelTier,invariants:[...o.invariants(s,e$1),...s.agreements],do_not:a,acceptance:e$1.acceptance,upstream:u,priorHandoffs:d,relatedBugs:f,budgetRemaining:v?K$1(v.budget,v.spent):{}};if(g&&(w.gateAhead=g),e$1.type==="question"&&e$1.parent){let n=J(s,e$1.parent);if(n){w.parent={item:e$1.parent,role:n.role,notes:n.notes,produced:n.produced,open_questions:n.open_questions??[],do_not:n.do_not};for(let l of n.do_not)a.includes(l)||a.push(l);}}return w}function ye(s){let o=new Map;for(let e of s.events){if(e.type!=="item.completed")continue;let i=e.payload;o.delete(i.id),o.set(i.id,{...i,at:e.at});}return [...o.values()].filter(e=>(e.verdict==="done"||e.verdict==="needs-review")&&(e.open_questions??[]).length>0).map(e=>({item:e.id,role:e.role,questions:e.open_questions??[],at:e.at}))}function he(s,o,e={}){let i=R(s,o,e),u=i.dispatched.map(a=>oe(i.state,o,i.state.items[a.id]));return i.reason?{state:i.state,briefs:u,skipped:i.skipped,reason:i.reason}:{state:i.state,briefs:u,skipped:i.skipped}}var K=["done","needs-review","rework","blocked","escalate"],Y=["policy","skill","memory","spec","review"],P=s=>typeof s=="object"&&s!==null&&!Array.isArray(s),$=s=>typeof s=="string";function ne(s,o,e){let i=r(s,o.item);i.status!=="in_progress"&&b("invalid-transition",`item "${i.id}" is ${i.status}, not in_progress`,"only dispatched items can be completed; call next() first",{items:[i.id]}),Array.isArray(o.do_not)||b("handoff-invalid",`handoff for "${i.id}" has no do_not array`,"set handoff.do_not to [] when there is nothing to forbid",{items:[i.id]}),(!Array.isArray(o.produced)||!Array.isArray(o.open_questions))&&b("handoff-invalid",`handoff for "${i.id}" needs produced[] and open_questions[]`,"pass empty arrays when there is nothing",{items:[i.id]});let u=(t,f)=>b("handoff-invalid",`handoff for "${i.id}": ${t}`,f,{items:[i.id]}),a=o.verdict??"done";K.includes(a)||u(`unknown verdict ${JSON.stringify(a)}`,`use one of: ${K.join(", ")}`),o.produced.every(t=>P(t)&&$(t.kind)&&$(t.ref))||u("produced[] entries need string kind and ref",'use { "kind": "code", "ref": "src/a.ts" }');let r$1=o.lessons??[];(!Array.isArray(r$1)||!r$1.every(t=>P(t)&&$(t.text)&&Y.includes(t.scope)))&&u("lessons[] entries need a text and a scope",`scope is one of: ${Y.join(", ")}`);let d=o.follow_ups??[];(!Array.isArray(d)||!d.every(t=>P(t)&&$(t.id)&&$(t.title)))&&u("follow_ups[] entries need a string id and title","describe each follow-up as a new item"),o.role!==i.role&&b("handoff-invalid",`handoff role "${o.role}" differs from the dispatched role "${i.role}"`,`complete as "${i.role}" or re-dispatch`,{items:[i.id]}),(!e.model||e.model.trim()==="")&&b("accounting-invalid",`accounting for "${i.id}" has no model`,"record the model id that actually ran the work",{items:[i.id]});for(let t of ["tokensIn","tokensOut","durationMs"])(!Number.isFinite(e[t])||e[t]<0)&&b("accounting-invalid",`accounting.${t} must be a non-negative number`,`measure ${t} from the host's usage report`,{items:[i.id]});e.tokensIn+e.tokensOut===0&&e.estimate!==true&&b("accounting-invalid",`accounting for "${i.id}" records 0 tokens`,"pass the host's usage figures, or set estimate: true (CLI --estimate) to record a placeholder and correct it later with correctAccounting / exwf account",{items:[i.id]});}function Z(s){for(let o=s.transitions.length-1;o>=0;o--){let e=s.transitions[o];if(e.to.status==="in_progress")return e.from.stage}return s.stage}function se(s,o){return D(s,o)?.from.stage??Z(o)}function Pe(s,o,e,i,u){ne(s,e,i);let a,r=U(s,o,{type:"item.complete",by:e.role,payload:{item:e.item,handoff:e}},()=>(a=ie(s,o,e,i,u),a.state));return {state:r.state,warnings:[...r.warnings,...a.warnings]}}function ie(s$1,o,e,i,u$1){let a$1=a(u$1),r$1=e.item,d=e.role,t={...s$1,accounting:[...s$1.accounting,i]};for(let n of e.produced)t=y(t,r$1,{kind:n.kind,ref:n.ref,by:d},a$1);let f=N(t);f&&(f.committed.includes(r$1)||r(t,r$1).iteration===f.id)&&(t={...t,iterations:t.iterations.map(n=>n.id===f.id?{...n,spent:J$1(n.spent,i)}:n)});for(let n of e.lessons??[]){let l=`L${t.lessons.length+1}`;t={...t,lessons:[...t.lessons,{id:l,at:a$1,text:n.text,scope:n.scope,status:"raised",from:d,item:r$1}]},t=c$1(t,"lesson.raised",d,{id:l,from:d,item:r$1,scope:n.scope},a$1);}let v$1=[];for(let n of e.follow_ups??[]){let l=t.stages[0],{iteration:m,...k}=n;t=s(t,{...k,stage:l.id,parent:r$1,tags:[...n.tags??[],"follow-up"]},d,a$1),v$1.push(n.id);}let g$1=e.verdict??"done",w$1=[];if((g$1==="done"||g$1==="needs-review")&&e.open_questions.length>0&&w$1.push({rule:"open-questions-ignored",severity:"warning",item:r$1,message:`"${r$1}" finished with ${e.open_questions.length} open question(s) nobody will see: ${e.open_questions.join(" | ")}`,fix:'use verdict "escalate" to route them to a role with capability escalate, or answer them in the next brief'}),g$1==="rework"){(!e.notes||e.notes.trim()==="")&&b("handoff-invalid",`rework on "${r$1}" needs notes`,"say what must change in handoff.notes",{items:[r$1]});let n=r(t,r$1);t=v(u(t,r$1,{stage:se(t,n),status:"todo"},d,a$1),r$1),t=c$1(t,"item.rework",d,{id:r$1,by:d,notes:e.notes},a$1);}else if((g$1==="done"||g$1==="needs-review")&&r(t,r$1).type==="question"){let n=t.stages[t.stages.length-1].id;t=u(t,r$1,{stage:n,status:"done"},d,a$1);}else if(g$1==="done"||g$1==="needs-review"){let n$1=r(t,r$1),l=n(t,n$1.stage);if(C(t,n$1,l.exitPolicy,`leave "${l.id}"`),l.gate){let m=F(t,n$1,l.gate,d);m.outcome==="fail"&&b("gate-unmet",`gate "${l.gate.id}" blocks "${r$1}": ${m.violations.map(k=>k.message).join("; ")}`,m.violations.map(k=>k.fix).join("; "),{items:[r$1],rule:m.violations[0].rule}),m.outcome==="human"?t=G(t,{kind:"gate",item:r$1,gate:l.gate.id,question:`Approve gate "${l.gate.id}" for "${n$1.title}" (${r$1})?`},a$1):t=c$1(w(t,r$1,d,g$1==="needs-review",a$1),"gate.passed",d,{item:r$1,gate:l.gate.id},a$1);}else t=w(t,r$1,d,g$1==="needs-review",a$1);}else if(g$1==="blocked")t=z(t,r$1,e.notes||"blocked by worker",d,d,a$1);else if(g$1==="escalate"){let n=g(t,"escalate")[0];n||b("missing-capability",`no role has capability "escalate" to receive the question from "${r$1}"`,"register a role with capability escalate",{items:[r$1]});let l=Object.keys(t.items).filter(h=>h.startsWith(`${r$1}-q`)).length+1,m=`${r$1}-q${l}`,k=r(t,r$1),W=Z(k),x={id:m,type:"question",title:e.open_questions.join(" | ")||e.notes||`question from ${r$1}`,parent:r$1,role:n.id,priority:Number.MAX_SAFE_INTEGER,stage:W};k.iteration!==void 0&&(x.iteration=k.iteration),t=s(t,x,d,a$1),t=u(t,r$1,{stage:W,status:"todo"},d,a$1),t=q(t,r$1,h=>({...h,dependsOn:[...h.dependsOn,m]})),t=c$1(t,"item.escalated",d,{id:r$1,question:m,to:n.id},a$1);}return t=c$1(t,"item.completed",d,{id:r$1,role:d,verdict:g$1,produced:e.produced,notes:e.notes,do_not:e.do_not,open_questions:e.open_questions,followUps:v$1,tokens:i.tokensIn+i.tokensOut,durationMs:i.durationMs,model:i.model},a$1),o.afterComplete&&(t=o.afterComplete(t,r$1,a$1)),{state:t,warnings:w$1}}var re=[["tokensIn","tokens-in"],["tokensOut","tokens-out"],["durationMs","duration-ms"]],ee=s=>({tokensIn:s.tokensIn,tokensOut:s.tokensOut,durationMs:s.durationMs,model:s.model});function He(s,o,e,i,u,a$1){r(s,o);let r$1=[];s.accounting.forEach((p,S)=>{p.item===o&&r$1.push(S);}),r$1.length===0&&b("invalid-input",`item "${o}" has no accounting line to correct`,`complete "${o}" first (exwf complete), then exwf account`,{items:[o]});let d=a$1??r$1.length;(!Number.isInteger(d)||d<1||d>r$1.length)&&b("invalid-input",`item "${o}" has ${r$1.length} accounting line(s), not line ${String(a$1)}`,`pass --line 1..${r$1.length}`,{items:[o]});let t=r$1[d-1],f=s.accounting[t];for(let[p,S]of re){let q=e[p];q!==void 0&&(!Number.isFinite(q)||q<0)&&b("accounting-invalid",`${p} must be a non-negative number`,`pass --${S} <n> with a measured figure`,{items:[o]});}e.model!==void 0&&e.model.trim()===""&&b("accounting-invalid","model must not be empty","pass --model with the model id that ran the work",{items:[o]});let{estimate:v,...g}=f,w={...g,tokensIn:e.tokensIn??f.tokensIn,tokensOut:e.tokensOut??f.tokensOut,durationMs:e.durationMs??f.durationMs,model:e.model??f.model};w.tokensIn+w.tokensOut===0&&b("accounting-invalid",`the correction leaves "${o}" at 0 tokens`,"pass the host's usage figures with --tokens-in / --tokens-out",{items:[o]});let n=ee(f),l=ee(w);n.tokensIn===l.tokensIn&&n.tokensOut===l.tokensOut&&n.durationMs===l.durationMs&&n.model===l.model&&f.estimate!==true&&b("no-op",`accounting for "${o}" line ${d} already has these figures`,"pass at least one different value to exwf account",{items:[o]});let k={tokens:l.tokensIn+l.tokensOut-(n.tokensIn+n.tokensOut),durationMs:l.durationMs-n.durationMs},W=s.items[o],x;for(let p of s.iterations)(p.committed.includes(o)||W.iteration===p.id)&&p.startedAt<=f.endedAt&&(p.endedAt===void 0||f.endedAt<=p.endedAt)&&(x=p);let h={...s,accounting:s.accounting.map((p,S)=>S===t?w:p)};return x&&(h={...h,iterations:h.iterations.map(p=>p.id===x.id?{...p,spent:{...p.spent,tokens:Math.max(0,p.spent.tokens+k.tokens),wallclockMs:Math.max(0,p.spent.wallclockMs+k.durationMs)}}:p)}),c$1(h,"accounting.corrected",i,{item:o,line:d,iteration:x?.id??null,before:n,after:l,delta:k},a(u))}export{ce as a,ue as b,oe as c,ye as d,he as e,Pe as f,He as g};//# sourceMappingURL=chunk-MB465DI4.mjs.map
2
- //# sourceMappingURL=chunk-MB465DI4.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/roles/registry.ts","../src/core/brief.ts","../src/core/complete.ts","../src/core/accounting.ts"],"names":["OPEN","registerRole","state","role","by","now","assertId","roleOf","fail","next","appendEvent","retireRole","roleId","open","i","roles","completions","itemId","out","ev","lastCompletion","all","synthesizeBrief","methodology","item","upstream","doNot","sources","dep","p","d","priorHandoffs","touched","relatedBugs","b","a","it","openIteration","gate","stageOf","brief","remaining","openQuestions","last","opts","res","plan","briefs","VERDICTS","LESSON_SCOPES","isObj","x","str","validate","handoff","acc","getItem","bad","what","fix","verdict","lessons","l","followUps","f","k","pulledFromStage","t","reworkStage","lastDispatchBefore","complete","result","ruled","applyAction","completeBody","at","nowOf","id","s","addEvidence","addSpent","lid","first","_drop","rest","addItem","warnings","clearRole","moveItem","lastStageId","stage","assertPolicies","checkGate","v","raisePending","advanceItem","raiseBlocker","thinker","rolesWith","n","qid","parent","pulledFrom","q","patchItem","NUMERIC","pick","correctAccounting","patch","line","indexes","idx","before","flag","after","delta","owner"],"mappings":"2IAKA,IAAMA,EAAAA,CAA4B,IAAI,GAAA,CAAI,CAAC,aAAA,CAAe,QAAA,CAAU,SAAS,CAAC,CAAA,CAcvE,SAASC,EAAAA,CACdC,CAAAA,CACAC,EACAC,GAAAA,CACAC,CAAAA,CACkB,CAClBC,CAAAA,CAASH,CAAAA,CAAK,EAAA,CAAI,SAAS,CAAA,CACvBI,EAAOL,CAAAA,CAAOC,CAAAA,CAAK,EAAE,CAAA,EACvBK,CAAAA,CACE,gBAAA,CACA,CAAA,MAAA,EAASL,CAAAA,CAAK,EAAE,CAAA,gBAAA,CAAA,CAChB,CAAA,kCAAA,EAAqCA,CAAAA,CAAK,EAAE,CAAA,QAAA,CAC9C,CAAA,CACF,IAAMM,CAAAA,CAAO,CAAE,GAAGP,CAAAA,CAAO,KAAA,CAAO,CAAE,GAAGA,CAAAA,CAAM,KAAA,CAAO,CAACC,EAAK,EAAE,EAAGA,CAAK,CAAE,CAAA,CACpE,OAAOO,GAAAA,CACLD,CAAAA,CACA,kBACAL,GAAAA,CACA,CAAE,IAAA,CAAMD,CAAAA,CAAK,EAAA,CAAI,YAAA,CAAcA,CAAAA,CAAK,YAAa,EACjDE,CACF,CACF,CAcO,SAASM,EAAAA,CACdT,CAAAA,CACAU,CAAAA,CACAR,GAAAA,CACAC,EACkB,CACbE,CAAAA,CAAOL,CAAAA,CAAOU,CAAM,CAAA,EACvBJ,CAAAA,CACE,cAAA,CACA,CAAA,MAAA,EAASI,CAAM,CAAA,gBAAA,CAAA,CACf,CAAA,kBAAA,EAAqB,MAAA,CAA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vent } from \"../state.ts\";\nimport type { Role, WorkflowState } from \"../types.ts\";\nimport { roleOf } from \"./lookup.ts\";\n\nconst OPEN: ReadonlySet<string> = new Set([\"in_progress\", \"review\", \"blocked\"]);\n\nexport function registerRole<N extends string>(\n state: WorkflowState<N>,\n role: Role,\n by: string,\n now?: string,\n): WorkflowState<N>;\nexport function registerRole(\n state: WorkflowState,\n role: Role,\n by: string,\n now?: string,\n): WorkflowState;\nexport function registerRole<N extends string>(\n state: WorkflowState<N>,\n role: Role,\n by: string,\n now?: string,\n): WorkflowState<N> {\n assertId(role.id, \"role id\");\n if (roleOf(state, role.id))\n fail(\n \"duplicate-role\",\n `role \"${role.id}\" already exists`,\n `use a different id or retireRole(\"${role.id}\") first`,\n );\n const next = { ...state, roles: { ...state.roles, [role.id]: role } };\n return appendEvent(\n next,\n \"role.registered\",\n by,\n { role: role.id, capabilities: role.capabilities },\n now,\n );\n}\n\nexport function retireRole<N extends string>(\n state: WorkflowState<N>,\n roleId: string,\n by: string,\n now?: string,\n): WorkflowState<N>;\nexport function retireRole(\n state: WorkflowState,\n roleId: string,\n by: string,\n now?: string,\n): WorkflowState;\nexport function retireRole<N extends string>(\n state: WorkflowState<N>,\n roleId: string,\n by: string,\n now?: string,\n): WorkflowState<N> {\n if (!roleOf(state, roleId))\n fail(\n \"unknown-role\",\n `role \"${roleId}\" does not exist`,\n `registered roles: ${Object.keys(state.roles).join(\", \") || \"(none)\"}`,\n );\n const open = Object.values(state.items)\n .filter((i) => i.role === roleId && OPEN.has(i.status))\n .map((i) => i.id);\n if (open.length)\n fail(\n \"role-has-open-items\",\n `role \"${roleId}\" still holds ${open.length} open item(s)`,\n `complete or reassign ${open.join(\", \")} before retiring the role`,\n { items: open },\n );\n const roles = { ...state.roles };\n delete roles[roleId];\n return appendEvent({ ...state, roles }, \"role.retired\", by, { role: roleId }, now);\n}\n","import { remaining } from \"./budget.ts\";\nimport { fail } from \"./errors.ts\";\nimport { stageOf } from \"./items/stage.ts\";\nimport { openIteration, plan, type PlanOptions, type PlanReason, type Skipped } from \"./planner.ts\";\nimport { roleOf } from \"./roles/lookup.ts\";\nimport type {\n Brief,\n Handoff,\n Methodology,\n MethodologyName,\n Verdict,\n WorkItem,\n WorkflowState,\n} 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 open_questions?: string[];\n}\n\nfunction completions(\n state: WorkflowState<string>,\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(\n state: WorkflowState<string>,\n itemId: string,\n): CompletedPayload | undefined {\n const all = completions(state, itemId);\n return all[all.length - 1];\n}\n\nexport function synthesizeBrief<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\n item: WorkItem,\n): Brief;\nexport function synthesizeBrief(\n state: WorkflowState,\n methodology: Methodology,\n item: WorkItem,\n): Brief;\nexport function synthesizeBrief<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\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 if (item.type === \"question\" && item.parent) {\n const p = lastCompletion(state, item.parent);\n if (p) {\n brief.parent = {\n item: item.parent,\n role: p.role,\n notes: p.notes,\n produced: p.produced,\n open_questions: p.open_questions ?? [],\n do_not: p.do_not,\n };\n for (const d of p.do_not) if (!doNot.includes(d)) doNot.push(d);\n }\n }\n return brief;\n}\n\n/** Open questions of finished items: the last completion per item, verdict done/needs-review, with open_questions left unanswered. */\nexport function openQuestions(\n state: WorkflowState<string>,\n): Array<{ item: string; role: string; questions: string[]; at: string }>;\nexport function openQuestions(\n state: WorkflowState,\n): Array<{ item: string; role: string; questions: string[]; at: string }>;\nexport function openQuestions(\n state: WorkflowState<string>,\n): Array<{ item: string; role: string; questions: string[]; at: string }> {\n const last = new Map<string, CompletedPayload & { at: string }>();\n for (const ev of state.events) {\n if (ev.type !== \"item.completed\") continue;\n const p = ev.payload as CompletedPayload;\n last.delete(p.id);\n last.set(p.id, { ...p, at: ev.at });\n }\n return [...last.values()]\n .filter(\n (p) =>\n (p.verdict === \"done\" || p.verdict === \"needs-review\") &&\n (p.open_questions ?? []).length > 0,\n )\n .map((p) => ({ item: p.id, role: p.role, questions: p.open_questions ?? [], at: p.at }));\n}\n\nexport interface NextResult<N extends string = MethodologyName> {\n state: WorkflowState<N>;\n briefs: Brief[];\n skipped: Skipped[];\n reason?: PlanReason;\n}\n\nexport function next<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\n opts?: PlanOptions,\n): NextResult<N>;\nexport function next(\n state: WorkflowState,\n methodology: Methodology,\n opts?: PlanOptions,\n): NextResult;\nexport function next<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\n opts: PlanOptions = {},\n): NextResult<N> {\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 { addEvidence } from \"./items/evidence.ts\";\nimport { addItem, getItem, patchItem } from \"./items/record.ts\";\nimport { advanceItem, clearRole, moveItem } from \"./items/move.ts\";\nimport { raiseBlocker } from \"./items/blockers.ts\";\nimport { stageOf } from \"./items/stage.ts\";\nimport { applyAction } from \"./methodology.ts\";\nimport { assertPolicies } from \"./policies.ts\";\nimport { openIteration } from \"./planner.ts\";\nimport { rolesWith } from \"./roles/lookup.ts\";\nimport { appendEvent, nowOf } from \"./state.ts\";\nimport type {\n Accounting,\n ApplyResult,\n Handoff,\n Methodology,\n NewItem,\n Violation,\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<string>, 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 if (acc.tokensIn + acc.tokensOut === 0 && acc.estimate !== true)\n fail(\n \"accounting-invalid\",\n `accounting for \"${item.id}\" records 0 tokens`,\n \"pass the host's usage figures, or set estimate: true (CLI --estimate) to record a placeholder and correct it later with correctAccounting / exwf account\",\n { items: [item.id] },\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<string>, item: WorkItem): string {\n return lastDispatchBefore(state, item)?.from.stage ?? pulledFromStage(item);\n}\n\nexport function complete<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\n handoff: Handoff,\n acc: Accounting,\n now?: string,\n): ApplyResult<N>;\nexport function complete(\n state: WorkflowState,\n methodology: Methodology,\n handoff: Handoff,\n acc: Accounting,\n now?: string,\n): ApplyResult;\nexport function complete<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\n handoff: Handoff,\n acc: Accounting,\n now?: string,\n): ApplyResult<N> {\n validate(state, handoff, acc);\n // the methodology's rules see the completion (applyAction validates, appends nothing, then reduces)\n let result: ApplyResult<N> | undefined;\n const ruled = applyAction(\n state,\n methodology,\n { type: \"item.complete\", by: handoff.role, payload: { item: handoff.item, handoff } },\n () => {\n result = completeBody(state, methodology, handoff, acc, now);\n return result.state;\n },\n );\n return { state: ruled.state, warnings: [...ruled.warnings, ...result!.warnings] };\n}\n\nfunction completeBody<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\n handoff: Handoff,\n acc: Accounting,\n now?: string,\n): ApplyResult<N> {\n const at = nowOf(now);\n const id = handoff.item;\n const role = handoff.role;\n let s: WorkflowState<N> = { ...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 const warnings: Violation[] = [];\n if ((verdict === \"done\" || verdict === \"needs-review\") && handoff.open_questions.length > 0)\n warnings.push({\n rule: \"open-questions-ignored\",\n severity: \"warning\",\n item: id,\n message: `\"${id}\" finished with ${handoff.open_questions.length} open question(s) nobody will see: ${handoff.open_questions.join(\" | \")}`,\n fix: 'use verdict \"escalate\" to route them to a role with capability escalate, or answer them in the next brief',\n });\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","import { fail } from \"./errors.ts\";\nimport { getItem } from \"./items/record.ts\";\nimport { appendEvent, nowOf } from \"./state.ts\";\nimport type { Accounting, Iteration, WorkflowState } from \"./types.ts\";\n\nexport interface AccountingPatch {\n tokensIn?: number;\n tokensOut?: number;\n durationMs?: number;\n model?: string;\n}\n\nconst NUMERIC = [\n [\"tokensIn\", \"tokens-in\"],\n [\"tokensOut\", \"tokens-out\"],\n [\"durationMs\", \"duration-ms\"],\n] as const;\n\nconst pick = (a: Accounting) => ({\n tokensIn: a.tokensIn,\n tokensOut: a.tokensOut,\n durationMs: a.durationMs,\n model: a.model,\n});\n\n/**\n * Rewrite one accounting line of an item (`line` is 1-based among the item's lines, default the last).\n * The owning iteration's spent follows the delta, open or closed; the event records before/after.\n */\nexport function correctAccounting<N extends string>(\n state: WorkflowState<N>,\n itemId: string,\n patch: AccountingPatch,\n by: string,\n now?: string,\n line?: number,\n): WorkflowState<N>;\nexport function correctAccounting(\n state: WorkflowState,\n itemId: string,\n patch: AccountingPatch,\n by: string,\n now?: string,\n line?: number,\n): WorkflowState;\nexport function correctAccounting<N extends string>(\n state: WorkflowState<N>,\n itemId: string,\n patch: AccountingPatch,\n by: string,\n now?: string,\n line?: number,\n): WorkflowState<N> {\n getItem(state, itemId);\n const indexes: number[] = [];\n state.accounting.forEach((a, i) => {\n if (a.item === itemId) indexes.push(i);\n });\n if (indexes.length === 0)\n fail(\n \"invalid-input\",\n `item \"${itemId}\" has no accounting line to correct`,\n `complete \"${itemId}\" first (exwf complete), then exwf account`,\n { items: [itemId] },\n );\n const n = line ?? indexes.length;\n if (!Number.isInteger(n) || n < 1 || n > indexes.length)\n fail(\n \"invalid-input\",\n `item \"${itemId}\" has ${indexes.length} accounting line(s), not line ${String(line)}`,\n `pass --line 1..${indexes.length}`,\n { items: [itemId] },\n );\n const idx = indexes[n - 1]!;\n const before = state.accounting[idx]!;\n for (const [k, flag] of NUMERIC) {\n const v = patch[k];\n if (v !== undefined && (!Number.isFinite(v) || v < 0))\n fail(\n \"accounting-invalid\",\n `${k} must be a non-negative number`,\n `pass --${flag} <n> with a measured figure`,\n { items: [itemId] },\n );\n }\n if (patch.model !== undefined && patch.model.trim() === \"\")\n fail(\n \"accounting-invalid\",\n \"model must not be empty\",\n \"pass --model with the model id that ran the work\",\n { items: [itemId] },\n );\n const { estimate: _drop, ...rest } = before;\n const after: Accounting = {\n ...rest,\n tokensIn: patch.tokensIn ?? before.tokensIn,\n tokensOut: patch.tokensOut ?? before.tokensOut,\n durationMs: patch.durationMs ?? before.durationMs,\n model: patch.model ?? before.model,\n };\n if (after.tokensIn + after.tokensOut === 0)\n fail(\n \"accounting-invalid\",\n `the correction leaves \"${itemId}\" at 0 tokens`,\n \"pass the host's usage figures with --tokens-in / --tokens-out\",\n { items: [itemId] },\n );\n const b = pick(before);\n const a = pick(after);\n const unchanged =\n b.tokensIn === a.tokensIn &&\n b.tokensOut === a.tokensOut &&\n b.durationMs === a.durationMs &&\n b.model === a.model;\n // replacing a placeholder with the same figures still settles it, so it is not a no-op\n if (unchanged && before.estimate !== true)\n fail(\n \"no-op\",\n `accounting for \"${itemId}\" line ${n} already has these figures`,\n \"pass at least one different value to exwf account\",\n { items: [itemId] },\n );\n const delta = {\n tokens: a.tokensIn + a.tokensOut - (b.tokensIn + b.tokensOut),\n durationMs: a.durationMs - b.durationMs,\n };\n const item = state.items[itemId]!;\n let owner: Iteration | undefined;\n for (const it of state.iterations) {\n // the last iteration that was open when the line was recorded and carried the item\n if (\n (it.committed.includes(itemId) || item.iteration === it.id) &&\n it.startedAt <= before.endedAt &&\n (it.endedAt === undefined || before.endedAt <= it.endedAt)\n )\n owner = it;\n }\n let s: WorkflowState<N> = {\n ...state,\n accounting: state.accounting.map((x, i) => (i === idx ? after : x)),\n };\n if (owner)\n s = {\n ...s,\n iterations: s.iterations.map((it) =>\n it.id === owner.id\n ? {\n ...it,\n spent: {\n ...it.spent,\n tokens: Math.max(0, it.spent.tokens + delta.tokens),\n wallclockMs: Math.max(0, it.spent.wallclockMs + delta.durationMs),\n },\n }\n : it,\n ),\n };\n return appendEvent(\n s,\n \"accounting.corrected\",\n by,\n {\n item: itemId,\n line: n,\n iteration: owner?.id ?? null,\n before: b,\n after: a,\n delta,\n },\n nowOf(now),\n );\n}\n"]}
@@ -1,2 +0,0 @@
1
- import {a as a$2,b as b$2}from'./chunk-FDZB73PH.mjs';import {a as a$1,b as b$3}from'./chunk-TQR3VFZU.mjs';import {U as U$1,c,a,e,M,r as r$1,y as y$1,u,P as P$1,C as C$1,q as q$1}from'./chunk-UUWDQVIJ.mjs';import {b as b$1,c as c$1}from'./chunk-YS6CXERQ.mjs';var g=e=>a$1(e,"experimentation"),y=(e,t)=>b$3(e,"experimentation",t);var k=["tokens","turns","wallclockMs"];function C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function r(e){return b$1("invalid-input",e,"supply valid experimentation ceremony input")}function m(e,t){return (typeof e!="string"||!e.trim())&&r(`${t} must be a non-empty string`),e}function v(e,t="sha"){let n=m(e,t);return /^[a-f0-9]{40}$|^[a-f0-9]{64}$/.test(n)||r(`${t} must be a full lowercase commit SHA`),n}function re(e,t){(!C(e)||!k.some(a=>e[a]!==void 0)||Object.keys(e).some(a=>!k.includes(a)))&&r(`${t} needs tokens, turns or wallclockMs limits`);let n={};for(let a of k){let i=e[a];i!==void 0&&((typeof i!="number"||!Number.isSafeInteger(i)||i<=0)&&r(`${t}.${a} must be a positive safe integer`),n[a]=i);}return n}function b(e){try{C(e)||r("experimentation config must be an object");let t=["objective","direction","tieBreak","concurrencyCap","maxCandidates","candidateBudget","totalBudget"];Object.keys(e).some(c=>!t.includes(c))&&r("unknown experimentation config key");let n=m(e.objective,"objective"),a=e.direction??"minimize";a!=="minimize"&&a!=="maximize"&&r("direction must be minimize or maximize");let i=e.tieBreak??"candidate-id";i!=="candidate-id"&&r("tieBreak must be candidate-id");let o=e.concurrencyCap??2,s=e.maxCandidates??4;for(let[c,d]of Object.entries({concurrencyCap:o,maxCandidates:s}))(typeof d!="number"||!Number.isSafeInteger(d)||d<1)&&r(`${c} must be a positive safe integer`);return o>s&&r("concurrencyCap cannot exceed maxCandidates"),{objective:n,direction:a,tieBreak:i,concurrencyCap:o,maxCandidates:s,candidateBudget:re(e.candidateBudget??{turns:10},"candidateBudget"),totalBudget:re(e.totalBudget??{turns:40},"totalBudget")}}catch(t){b$1("config-invalid",t instanceof Error?t.message:"invalid experimentation config","provide objective and positive finite limits");}}function S(e){let t=g(e);return (e.methodology!=="experimentation"||!t)&&r("freeze an experimentation workflow first"),t}function de(e$1,t,n){e(e$1,t)?.capabilities.includes(n)||b$1("missing-capability",`${t} needs ${n}`,"use a role with the required capability");}function ce(e,t,n){return e.events.reduce((a,i)=>{if(i.type!=="item.completed"||!C(i.payload))return a;let o=i.payload;return typeof o.id!="string"||o.role!==i.by||t!==void 0&&o.id!==t||n!==void 0&&o.role!==n||typeof o.tokens!="number"||!Number.isFinite(o.tokens)||o.tokens<0||typeof o.durationMs!="number"||!Number.isFinite(o.durationMs)||o.durationMs<0||t===void 0&&Object.values(g(e)?.candidates??{}).some(s=>s.item===o.id)?a:{tokens:a.tokens+o.tokens,turns:a.turns+1,wallclockMs:a.wallclockMs+o.durationMs}},{tokens:0,turns:0,wallclockMs:0})}function V(e,t){return {tokens:Math.max(e.tokens,t.tokens),turns:Math.max(e.turns,t.turns),wallclockMs:Math.max(e.wallclockMs,t.wallclockMs)}}function E(e,t){return V(t.spent,ce(e,t.item,t.author))}function G(e,t){let n=g(e);if(!n)return e;let a$1=j(e),i=["stopped","integrated"].includes(n.status);return {...e,iterations:e.iterations.map(o=>o.id==="experiment"?{...o,budget:{...b(e.config).totalBudget},spent:a$1,...i?{endedAt:o.endedAt??a(t),outcome:o.outcome??(n.status==="integrated"?"completed":"cancelled")}:{}}:o)}}function j(e,t=S(e)){let n=V(t.overhead,ce(e));return Object.values(t.candidates).reduce((a,i)=>{let o=E(e,i);return {tokens:a.tokens+o.tokens,turns:a.turns+o.turns,wallclockMs:a.wallclockMs+o.wallclockMs}},n)}function L(e){return Object.values(g(e)?.candidates??{}).filter(t=>t.status==="running"||e.items[t.item]?.status==="in_progress").length}function U(e){return Object.values(g(e)?.candidates??{}).reduce((t,n)=>{let a=e.items[n.item];return t+(a?.status==="in_progress"?M(e,a.weight,1):0)},0)}function be(e){let t=b(e.config).totalBudget.tokens;if(t!==void 0)return Math.max(0,t-j(e).tokens-U(e))}function Q(e$1,t){let n=e$1.items[t.item];return !!n&&(!n.role||n.role===t.author)&&!!e(e$1,t.author)?.capabilities.includes("deliver")}function X(e,t){let n=b(e.config),a=E(e,t);return k.some(i=>n.candidateBudget[i]!==void 0&&a[i]>=n.candidateBudget[i])}function I(e){if(!g(e))return false;let t=b(e.config),n=j(e);return k.some(a=>t.totalBudget[a]!==void 0&&n[a]>=t.totalBudget[a])}function W(e,t){let n=m(t.candidate,"candidate");return Object.hasOwn(e.candidates,n)||r(`unknown candidate ${n}`),e.candidates[n]}function se(e){let t=e.selected;return (t===void 0||!Object.hasOwn(e.candidates,t))&&b$1("invalid-input",`the experiment's selected candidate ${JSON.stringify(t)} is not one of its candidates`,"restore .workflow/state.json from git, or run compare again"),e.candidates[t]}function q(e,t){return typeof e[t]!="boolean"&&r(`${t} must be boolean`),e[t]}function J(e){C(e.spent)||r("spent must contain nonnegative tokens, turns and wallclockMs");let t={};for(let n of k){let a=e.spent[n];(typeof a!="number"||!Number.isSafeInteger(a)||a<0)&&r(`spent.${n} must be a nonnegative safe integer`),t[n]=a;}return t}function $(e,t){return {...e,candidates:{...e.candidates,[t.id]:t}}}function P(e,t){let n=J(t);return {...e,overhead:{tokens:e.overhead.tokens+n.tokens,turns:e.overhead.turns+n.turns,wallclockMs:e.overhead.wallclockMs+n.wallclockMs}}}function D(e,t,n){return u(e,t.item,{stage:"done",status:"dropped"},n.by,n.now)}function A(e){e.status!=="running"&&r("experiment is not running");}function N(e){return ["validated","failed","timed-out","cancelled"].includes(e.status)}function K(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="boolean")return true;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e)||!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype)return false;t.add(e);let n=Array.isArray(e)?e.every(a=>K(a,t)):Object.values(e).every(a=>a===void 0||K(a,t));return t.delete(e),n}function w(e,t,n){return (a$1,i)=>((!C(i)||!K(i))&&r("ceremony input must be JSON-safe"),m(i.by,"by"),i.now!==void 0&&(typeof i.now!="string"||!Number.isFinite(Date.parse(i.now)))&&r("now must be a valid timestamp"),de(a$1,i.by,t),U$1(a$1,le(),{type:`ceremony.${e}`,by:i.by,payload:i},o=>c(G(n(o,i),i.now),`experimentation.${e}`,i.by,structuredClone(i),a(i.now))))}function ue(){return {freeze:w("frozen","facilitate",(e,t)=>{(e.methodology!=="experimentation"||g(e))&&r("freeze may run only once in experimentation");let n=b(e.config),a$1=v(t.baseSha,"baseSha"),i=m(t.harness,"harness");(!Array.isArray(t.candidates)||t.candidates.length<1||t.candidates.length>n.maxCandidates)&&r("candidates must be a nonempty array within maxCandidates");let o={},s=new Set;for(let c of t.candidates){C(c)||r("candidate must be an object");let d=m(c.id,"candidate.id");c$1(d,"candidate id"),Object.hasOwn(o,d)&&r("candidate IDs must be unique safe identifiers");let l=m(c.item,"candidate.item"),f=m(c.author,"candidate.author");de(e,f,"deliver");let u=r$1(e,l);u.role&&u.role!==f&&r("candidate item role must match frozen author"),(s.has(l)||u.stage!=="candidate"||u.status!=="todo"||u.acceptance.length===0)&&r("candidate needs a distinct todo candidate item with acceptance criteria"),s.add(l),o[d]={id:d,item:l,author:f,status:"pending",spent:{tokens:0,turns:0,wallclockMs:0}};}return y({...e,iterations:[...e.iterations,{id:"experiment",goal:n.objective,budget:{...n.totalBudget},spent:{tokens:0,turns:0,wallclockMs:0},startedAt:a(t.now),committed:[...s],carryover:[]}]},{status:"running",baseSha:a$1,harness:i,candidates:o,released:[],overhead:{tokens:0,turns:0,wallclockMs:0}})}),provision:w("provisioned","manage-flow",(e,t)=>{let n=S(e);A(n),I(e)&&r("total experiment budget exhausted");let a=W(n,t);a.status!=="pending"&&r("candidate already provisioned");let i=m(t.workspace,"workspace");return (b$2({baseSha:n.baseSha},{baseSha:v(t.baseSha,"baseSha")}).length||t.isolated!==true)&&r("provision must attest isolated workspace at the exact frozen base SHA"),Object.values(n.candidates).some(o=>o.workspace===i)&&r("candidate workspaces must be distinct"),n=$(n,{...a,workspace:i,status:"ready"}),y(e,n)}),start:w("started","deliver",(e$1,t)=>{let n=S(e$1);A(n);let a=W(n,t);(a.status!=="ready"||a.author!==t.by)&&r("only the candidate author may start a ready candidate"),I(e$1)&&r("total experiment budget exhausted");let i=b(e$1.config),o=Object.values(n.candidates).filter(p=>p.status==="running"||e$1.items[p.item]?.status==="in_progress").length;o>=i.concurrencyCap&&r("candidate concurrency cap reached"),Q(e$1,a)||r("candidate author assignment or delivery capability changed");let s=j(e$1);i.totalBudget.turns!==void 0&&s.turns+o>=i.totalBudget.turns&&r("total experiment budget reserved by running candidates");let c=e(e$1,a.author),d=c.resourceClass??c.id,l=P$1(e$1)[d],f=Object.values(e$1.items).filter(p=>p.status==="in_progress"&&p.role&&(e(e$1,p.role)?.resourceClass??p.role)===d).length;l!==void 0&&f>=l&&r("role resource capacity reached");let u$1=r$1(e$1,a.item),x=be(e$1);x!==void 0&&M(e$1,u$1.weight,1)>x&&r("total experiment token budget reserved or insufficient"),u$1.status!=="todo"&&r("candidate item is already dispatched"),C$1(e$1,u$1,[{kind:"dependencies-done"},{kind:"no-open-blockers"},{kind:"acceptance-written"},...e$1.stages.find(p=>p.id==="building").entryPolicy],"start candidate execution"),X(e$1,a)&&r("candidate budget exhausted");let h=u(e$1,a.item,{stage:"building",status:"in_progress"},t.by,t.now);return h=q$1(h,a.item,p=>({...p,role:t.by})),y(h,$(n,{...a,status:"running"}))}),submit:w("submitted","deliver",(e,t)=>{let n=S(e);A(n);let a=W(n,t),i=r$1(e,a.item);(a.status!=="running"&&!(a.status==="ready"&&i.status==="in_progress")||a.author!==t.by||i.role!==t.by)&&r("only the running candidate author may submit once");let o=v(t.sha);(b$2({workspace:a.workspace,harness:n.harness},t).length||b$2({baseSha:n.baseSha},{baseSha:v(t.baseSha,"baseSha")}).length)&&r("submission provenance must match frozen base SHA, harness and owned workspace"),(typeof t.score!="number"||!Number.isFinite(t.score))&&r("score must be finite");let s=J(t),c=m(t.command,"command"),d=m(t.log,"log"),l=b(e.config),f=E(e,{...a,spent:s}),u=k.some(p=>l.candidateBudget[p]!==void 0&&f[p]>l.candidateBudget[p]),x={...a,status:u?"timed-out":"submitted",sha:o,score:t.score,spent:f,command:c,log:d};u&&(x.reason="candidate budget exceeded");let h=y(e,$(n,x));return h=y$1(h,a.item,{kind:"candidate-sha",ref:o,by:t.by},t.now),h=y$1(h,a.item,{kind:"benchmark-result",ref:JSON.stringify({score:t.score,harness:n.harness,sha:o}),by:t.by},t.now),u?D(h,x,t):h}),terminate:w("terminated","manage-flow",(e,t)=>{let n=S(e);A(n);let a=W(n,t);N(a)&&r("candidate is already terminal"),["failed","timed-out","cancelled"].includes(t.status)||r("status must be failed, timed-out or cancelled");let i=m(t.reason,"reason"),o=J(t),s=m(t.log,"log");return D(y({...e},$(n,{...a,status:t.status,reason:i,spent:V(E(e,a),E(e,{...a,spent:o})),terminalLog:s})),a,t)}),validate:w("validated","verify",(e,t)=>{let n=S(e);A(n);let a=W(n,t);a.status!=="submitted"&&r("validate an unvalidated submitted candidate"),a$2(t.by,[a.author]).length&&r("candidate author cannot independently validate"),!e.events.some(x=>x.type==="experimentation.started"&&C(x.payload)&&x.payload.candidate===a.id)&&r$1(e,a.item).status==="in_progress"&&b$1("invalid-input",`candidate "${a.id}" item "${a.item}" is still in progress under the planner`,`complete item "${a.item}" with the builder's handoff (candidate-sha ${a.sha}) and accounting before validating`,{items:[a.item]});let o=v(t.sha),s=m(t.harness,"harness");b$2({sha:a.sha,harness:n.harness},{sha:o,harness:s}).length&&r("validation must match exact submitted SHA and frozen harness");let c=q(t,"passed"),d=q(t,"reproducible"),l=m(t.evidence,"evidence"),f={sha:o,harness:s,by:t.by,passed:c,reproducible:d,evidence:l},u$1=y({...e},$(P(n,t),{...a,status:c&&d?"validated":"failed",validation:f}));return u$1=y$1(u$1,a.item,{kind:"validation",ref:l,by:t.by},t.now),u$1=u(u$1,a.item,{stage:"done",status:c&&d?"done":"dropped"},t.by,t.now),u$1}),compare:w("compared","facilitate",(e,t)=>{let n=S(e);A(n);let a=Object.values(n.candidates);a.every(N)||r("comparison requires all candidates terminal and submissions independently validated");let i=b(e.config),o=j(e,n);if(k.some(d=>i.totalBudget[d]!==void 0&&o[d]>i.totalBudget[d]))return y(e,{...n,status:"stopped",reason:"total budget exceeded"});let s=a.filter(d=>{let l=E(e,d);return d.status==="validated"&&d.validation?.passed&&d.validation.reproducible&&!b$2({sha:d.sha,harness:n.harness},d.validation).length&&!k.some(f=>i.candidateBudget[f]!==void 0&&l[f]>i.candidateBudget[f])});s.sort((d,l)=>(d.score-l.score)*(i.direction==="minimize"?1:-1)||(d.id<l.id?-1:d.id>l.id?1:0));let c=s[0];return y({...e},c?{...n,status:"selected",selected:c.id}:{...n,status:"stopped",reason:"no eligible candidate"})}),integrate:w("integration-recorded","control-change",(e,t)=>{let n=S(e);(!["selected","integrating"].includes(n.status)||!n.selected)&&r("compare and select before integration"),I(e)&&r("total budget exhausted before integration");let a=se(n),i=v(t.selectedSha,"selectedSha");(i!==a.sha||a.validation?.sha!==i)&&r("integration must promote the exact selected and validated SHA");let o=v(t.targetSha,"targetSha"),s=v(t.integrationSha,"integrationSha");return n.integration?.sha===s&&n.integration.targetSha===o&&r("integration already recorded"),y(e,{...P(n,t),status:"integrating",integration:{selectedSha:i,targetSha:o,sha:s,by:t.by}})}),"validate-integration":w("integration-validated","verify",(e,t)=>{let n=S(e);(n.status!=="integrating"||!n.integration||!n.selected)&&r("record integration before fresh validation");let a=n.integration,i=se(n);a$2(t.by,[a.by,i.author]).length&&r("integration validation must be independent of candidate author and integrator");let o=v(t.sha),s=v(t.targetSha,"targetSha"),c=m(t.harness,"harness");b$2({sha:a.sha,targetSha:a.targetSha,harness:n.harness},{sha:o,targetSha:s,harness:c}).length&&r("fresh validation must match integration SHA, current target SHA and harness");let d=q(t,"passed"),l=m(t.evidence,"evidence"),f=P(n,t),u=b(e.config),x=j(e,f),h=k.some(p=>u.totalBudget[p]!==void 0&&x[p]>u.totalBudget[p]);return y(e,{...f,status:d&&!h?"integrated":"stopped",...d&&!h?{}:{reason:h?"total budget exceeded":"integration validation failed"},integration:{...a,validation:{by:t.by,sha:o,harness:c,evidence:l,passed:d}}})}),stop:w("stopped","manage-flow",(e,t)=>{let n=S(e);(n.status==="stopped"||n.status==="integrated")&&r("experiment already closed");let a=m(t.reason,"reason");Object.values(n.candidates).some(s=>s.status==="running"||s.status==="submitted"||e.items[s.item]?.status==="in_progress")&&r("terminate active attempts with final usage and log before stopping");let i=Object.fromEntries(Object.values(n.candidates).map(s=>[s.id,N(s)?s:{...s,status:"cancelled",reason:a}])),o=e;for(let s of Object.values(n.candidates))N(s)||(o=D(o,s,t));return y(o,{...P(n,t),status:"stopped",reason:a,candidates:i})}),cleanup:w("cleanup-recorded","manage-flow",(e,t)=>{let n=S(e);return n.status!=="stopped"&&n.status!=="integrated"&&r("cleanup requires a closed experiment"),(!Array.isArray(t.workspaces)||t.workspaces.length===0||t.workspaces.some(a=>typeof a!="string"||!Object.values(n.candidates).some(i=>i.workspace===a)||n.released.includes(a))||new Set(t.workspaces).size!==t.workspaces.length)&&r("workspaces must list distinct owned unreleased identities"),y(e,{...n,released:[...n.released,...t.workspaces]})})}}function pe(e){let t=g(e),n=Object.values(t?.candidates??{});return {candidates:n.length,validated:n.filter(a=>a.status==="validated").length,failed:n.filter(a=>a.status==="failed").length,timedOut:n.filter(a=>a.status==="timed-out").length,cancelled:n.filter(a=>a.status==="cancelled").length,integrated:t?.status==="integrated"?1:0,spent:t?{...j(e)}:{tokens:0,turns:0,wallclockMs:0},candidateTokens:Object.fromEntries(n.map(a=>[a.id,E(e,a).tokens]))}}function me(e){let t=g(e);return {status:t?.status??"unfrozen",baseSha:t?.baseSha??null,harness:t?.harness??null,selected:t?.selected??null,reason:t?.reason??null,integration:t?.integration?structuredClone(t.integration):null,candidates:structuredClone(t?.candidates??{}),cleanup:Object.values(t?.candidates??{}).flatMap(n=>n.workspace&&!t?.released.includes(n.workspace)?[n.workspace]:[]),hostResponsibilities:["provision isolated workspaces at baseSha","execute candidates and the frozen harness","integrate selected SHA at the current target","execute fresh integration validation","release owned workspace identities and record cleanup"]}}function fe(){return [{id:"coordinator",name:"Experiment coordinator",modelTier:"large",capabilities:["facilitate","order-backlog","manage-flow"],canApprove:[],inputs:["objective","budgets"],outputs:["comparison"],do_not:["Change the frozen baseline or harness"]},{id:"builder",name:"Candidate builder",modelTier:"large",capabilities:["deliver"],canApprove:[],inputs:["frozen harness","isolated workspace"],outputs:["candidate-sha","benchmark-result"],do_not:["Validate your own candidate","Change another candidate workspace"]},{id:"validator",name:"Independent validator",modelTier:"large",capabilities:["verify","review","approve-gate"],canApprove:["experiment-validation"],inputs:["exact candidate SHA","frozen harness"],outputs:["validation"],do_not:["Approve your own work"]},{id:"integrator",name:"Selected candidate integrator",modelTier:"large",capabilities:["deliver","control-change"],canApprove:[],inputs:["selected SHA","current target SHA"],outputs:["integration SHA"],do_not:["Declare integration validated"]}]}function ge(){return [{id:"experimentation-lifecycle",severity:"error",check(e,t){let n=[],a=g(e),i=t.payload;if(t.type==="item.complete"){["done","needs-review"].includes(i?.handoff?.verdict??"done")||n.push("unsupported completion verdict: terminate this attempt with final usage and log, then freeze a new experiment for retries");let o=a&&Object.values(a.candidates).find(s=>s.item===i?.item);(!o||!["submitted","validated"].includes(o.status))&&n.push("submit the candidate SHA and benchmark before completing work"),o?.status==="submitted"&&!i?.handoff?.produced?.some(s=>s.kind==="candidate-sha"&&s.ref===o.sha)&&n.push("handoff must retain the exact submitted candidate SHA");}return n.map(o=>({rule:"experimentation-lifecycle",severity:"error",message:o,fix:"follow the frozen experimentation lifecycle"}))}}]}function he(){return [{id:"candidate",name:"Frozen candidate",entryPolicy:[],exitPolicy:[{kind:"acceptance-written"},{kind:"no-open-blockers"},{kind:"dependencies-done"}]},{id:"building",name:"Isolated candidate execution",entryPolicy:[{kind:"acceptance-written"},{kind:"no-open-blockers"},{kind:"dependencies-done"}],exitPolicy:[{kind:"evidence",evidenceKind:"candidate-sha"},{kind:"evidence",evidenceKind:"benchmark-result"}]},{id:"validation",name:"Independent exact-SHA validation",review:true,entryPolicy:[],exitPolicy:[{kind:"evidence",evidenceKind:"validation"}],gate:{id:"experiment-validation",requires:[{capability:"verify"}],evidence:["validation"],onFail:{action:"block"}}},{id:"done",name:"Candidate work complete",entryPolicy:[],exitPolicy:[],deliveryPoint:true}]}function le(){return {name:"experimentation",vocabulary:{backlog:"Candidate pool",item:"Candidate work item",stage:"Experiment stage",iteration:"Experiment run",increment:"Validated integration",ceremony:"Experiment control",gate:"Independent validation"},validateConfig:b,defaultStages:he,defaultRoles:fe,requiredCapabilities:["facilitate","manage-flow","deliver","verify","control-change"],exclusiveCapabilities:[],plannerOptions(e){let t=b(e.config);return {schedulerMode:"throughput",dispatchStage:"building",concurrencyCap:Math.max(1,t.concurrencyCap-L(e)),fallbackTokensPerWeight:1,reservedTokens:U(e),roleFor(n){return Object.values(g(e)?.candidates??{}).find(a=>a.item===n.id)?.author}}},candidates(e){let t=g(e);if(!t||t.status!=="running")return [];let n=b(e.config);return I(e)||L(e)>=n.concurrencyCap?[]:Object.values(t.candidates).filter(a=>a.status==="ready"&&Q(e,a)&&e.items[a.item]?.status==="todo"&&!X(e,a)).map(a=>e.items[a.item])},afterComplete(e,t,n){return G(e,n)},invariants(e,t){let n=g(e),a=Object.values(n?.candidates??{}).find(i=>i.item===t.id);return [`Frozen base SHA: ${n?.baseSha??"unfrozen"}; harness: ${n?.harness??"unfrozen"}`,`Candidate: ${a?.id??"unregistered"}; isolated workspace: ${a?.workspace??"not provisioned"}`,`Objective and budget: ${JSON.stringify(e.config)}`,"Submit an exact commit SHA and harness benchmark before completion; independent validation is mandatory.","Host owns process execution, Git integration and workspace cleanup."]},ceremonies:ue(),rules:ge(),metrics:pe,report:me,humanDefaults:{gates:"none"},lockedConfigKeys:["objective","direction","tieBreak","concurrencyCap","maxCandidates","candidateBudget","totalBudget"]}}export{b as a,ue as b,pe as c,me as d,fe as e,ge as f,he as g,le as h};//# sourceMappingURL=chunk-OZAYOPLB.mjs.map
2
- //# sourceMappingURL=chunk-OZAYOPLB.mjs.map
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkBHAEPYRJ_cjs=require('./chunk-BHAEPYRJ.cjs'),chunkBBI7AKJK_cjs=require('./chunk-BBI7AKJK.cjs'),chunkZ43GUETW_cjs=require('./chunk-Z43GUETW.cjs'),chunkOSHBJIYD_cjs=require('./chunk-OSHBJIYD.cjs');var m=e=>chunkBBI7AKJK_cjs.a(e,"investigation"),_=(e,i)=>chunkBBI7AKJK_cjs.b(e,"investigation",i);function v(e,i){return [...new Set([...e.events.filter(d=>d.type==="item.completed"&&d.payload.id===i).map(d=>d.by),...(e.items[i]?.transitions??[]).filter(d=>d.to.status==="in_progress").map(d=>d.by)])]}function N(e,i){let d;for(let p=e.events.length-1;p>=0;p--){let s=e.events[p];if(s.type==="item.completed"&&s.payload.id===i){d=s.payload;break}}return d&&["done","needs-review"].includes(d.verdict)?d.produced.filter(p=>p.kind==="experiment-output").map(p=>p.ref):[]}function I(e){return chunkOSHBJIYD_cjs.b("invalid-input",`the investigation state is inconsistent: ${e}`,"restore .workflow/state.json from git, or start a new investigation")}function O(e){return e.rounds.at(-1)??I(`phase ${e.phase} has no round`)}function S(e){return e.iterations.find(i=>i.id==="investigation")??I('there is no "investigation" iteration')}function R(e){let i=e;return (!i||typeof i!="object"||Array.isArray(i)||typeof i.question!="string"||!i.question.trim()||!Number.isSafeInteger(i.maxRounds)||i.maxRounds<1||!i.budget||typeof i.budget!="object"||Array.isArray(i.budget)||!Object.keys(i.budget).length||Object.entries(i.budget).some(([d,p])=>!["tokens","turns","wallclockMs"].includes(d)||typeof p!="number"||!Number.isFinite(p)||p<=0))&&chunkOSHBJIYD_cjs.b("config-invalid","investigation requires question, positive maxRounds and a finite positive budget","provide bounded investigation config"),{question:i.question,maxRounds:i.maxRounds,budget:{...i.budget}}}function H(e,i,d,p){let s=m(e);return chunkOSHBJIYD_cjs.b("invalid-input",`${i} (phase ${s?.phase??"intake"}): ${d}`,p,{items:s?[s.item,...s.rounds.at(-1)?[s.rounds.at(-1).item]:[]]:[]})}var F=(e,i)=>!!e&&!!i&&!chunkBHAEPYRJ_cjs.b(e,i,["id","claim","falsifiedBy"]).length,y=e=>typeof e=="string"&&e.trim().length>0,B=e=>Array.isArray(e)&&e.length>0&&e.every(y)&&new Set(e).size===e.length,D=(e,i)=>e&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).find(d=>!i.includes(d)):void 0,E=(e,i)=>Array.isArray(e)?e.map(d=>D(d,i)).find(Boolean):void 0;function Q(e,i,d){chunkZ43GUETW_cjs.e(e,i)?.capabilities.includes(d)||chunkOSHBJIYD_cjs.b("missing-capability",`${i} needs ${d}`,"use a registered role with the required capability");}function b(e,i,d,p){return chunkZ43GUETW_cjs.c(_(e,i),`investigation.${p}`,d.by,{...i},chunkZ43GUETW_cjs.a(d.now))}function C(e,i,d,p,s){let n=chunkZ43GUETW_cjs.a(d.now),t=b(e,{...i,phase:"closed",outcome:p,...s?{stopReason:s}:{}},d,p);t={...t,iterations:t.iterations.map(a=>a.id==="investigation"?{...a,endedAt:n,outcome:p==="stopped"?"cancelled":"completed"}:a)};for(let a of Object.values(t.items).filter(r=>r.id===i.item||i.rounds.some(u=>u.item===r.id)))a.status!=="done"&&a.status!=="dropped"&&(t=chunkZ43GUETW_cjs.u(t,a.id,{status:p==="resolved"&&a.id===i.item?"done":"dropped"},d.by,n));return t}function U(e){let i,d=()=>i??=e(),p=(s,n,t,a)=>(r,u)=>{Q(r,u.by,n);let o=m(r);return (!o||o.phase==="closed")&&H(r,s,"no active investigation","start a new investigation with intake {item}"),t&&o.phase!==t&&!(s==="hypotheses"&&o.phase==="preregister")&&H(r,s,`expected ${t}, got ${o.phase}`,`finish phase ${o.phase} before calling ${s}; ${s} requires phase ${t}`),chunkZ43GUETW_cjs.U(r,d(),{type:`ceremony.${s}`,by:u.by,payload:u},()=>a(r,o,u,(l,g)=>H(r,s,l,g)))};return {intake(s,n){Q(s,n.by,"facilitate");let t=(r,u)=>H(s,"intake",r,u);s.methodology!=="investigation"&&t(`workflow methodology is ${s.methodology}, not investigation`,"init a workflow with the investigation methodology before intake"),m(s)&&t("investigation already started","use the existing investigation or initialize a new workflow"),y(n.item)||t("item is required","set intake.item to a unique investigation item ID");let a=R(s.config);return chunkZ43GUETW_cjs.U(s,d(),{type:"ceremony.intake",by:n.by,payload:n},()=>{let r=chunkZ43GUETW_cjs.s(s,{id:n.item,title:a.question,acceptance:["Independent evidence-based conclusion"],stage:"intake"},n.by,n.now);return r={...r,iterations:[...r.iterations,{id:"investigation",goal:a.question,budget:{...a.budget},spent:{tokens:0,turns:0,wallclockMs:0},startedAt:chunkZ43GUETW_cjs.a(n.now),committed:[],carryover:[]}]},b(r,{item:n.item,phase:"hypotheses",hypotheses:[],rounds:[],contributors:[n.by]},n,"intake")})},hypotheses:p("hypotheses","define-acceptance","hypotheses",(s,n,t,a)=>{let r=t.hypotheses,u=E(r,["id","claim","falsifiedBy"]);return u&&a(`unknown key "${u}" in a hypotheses entry`,"use only id, claim and falsifiedBy in each hypotheses entry"),(!Array.isArray(r)||!r.length||r.some(o=>!o||!y(o.id)||!y(o.claim)||!y(o.falsifiedBy))||new Set(r.map(o=>o.id)).size!==r.length||r.length<2&&!y(t.singleHypothesisRationale))&&a("provide competing falsifiable hypotheses or single-testable rationale","set hypotheses to unique {id, claim, falsifiedBy} entries; supply singleHypothesisRationale when there is only one"),b(s,{...n,hypotheses:r.map(o=>({id:o.id,claim:o.claim,falsifiedBy:o.falsifiedBy})),...y(t.singleHypothesisRationale)?{singleHypothesisRationale:t.singleHypothesisRationale}:{},contributors:[...new Set([...n.contributors,t.by])],phase:"preregister"},t,"hypotheses")}),preregister:p("preregister","define-acceptance","preregister",(s,n,t,a)=>{let r=R(s.config),u=s.iterations.find(c=>c.id==="investigation");(n.rounds.length>=r.maxRounds||!u||chunkZ43GUETW_cjs.L(r.budget,u.spent))&&a(`round limit or budget exhausted (${n.rounds.length} of ${r.maxRounds} rounds used)`,"call stop {reason} to close this investigation, or start a new one with a larger maxRounds or budget");let o=t.experiment,l=D(o,["id","procedureRef","predictions","replayOf"])??E(o?.predictions,["hypothesis","prediction"]);if(l&&a(`unknown key "${l}" in experiment`,"use only id, procedureRef, predictions [{hypothesis, prediction}] and replayOf in experiment"),(!o||!y(o.id)||!y(o.procedureRef)||n.rounds.some(c=>c.experiment.id===o.id)||!Array.isArray(o.predictions)||o.predictions.length!==n.hypotheses.length||n.hypotheses.some(c=>o.predictions.filter(f=>f?.hypothesis===c.id&&y(f.prediction)).length!==1)||new Set(o.predictions.map(c=>c.prediction)).size!==o.predictions.length)&&a("preregister unique experiment with differing predictions for every hypothesis","set experiment.id to a new ID, experiment.procedureRef, and one distinct experiment.predictions entry per hypothesis"),o.replayOf){let c=n.rounds.find(f=>f.experiment.id===o.replayOf&&f.result?.valid);(!c||chunkBHAEPYRJ_cjs.b(c.experiment,o,["procedureRef"]).length||c.hypotheses.length!==n.hypotheses.length||n.hypotheses.some(f=>!F(f,c.hypotheses.find(q=>q.id===f.id)))||o.predictions.some(f=>!c.experiment.predictions.some(q=>!chunkBHAEPYRJ_cjs.b(q,f,["hypothesis","prediction"]).length)))&&a("replay must repeat the procedure, predictions and hypotheses of a prior valid experiment","set experiment.replayOf to a valid prior experiment with identical procedureRef, predictions and hypothesis definitions");}let g=`${n.item}-run-${n.rounds.length+1}`,w=chunkZ43GUETW_cjs.s(s,{id:g,title:`Experiment ${o.id}`,stage:"execute",acceptance:[o.procedureRef],iteration:"investigation"},t.by,t.now);return w={...w,iterations:w.iterations.map(c=>c.id==="investigation"?{...c,committed:[...c.committed,g]}:c)},b(w,{...n,phase:"observe",rounds:[...n.rounds,{experiment:{id:o.id,procedureRef:o.procedureRef,predictions:o.predictions.map(c=>({hypothesis:c.hypothesis,prediction:c.prediction})),...o.replayOf?{replayOf:o.replayOf}:{}},hypotheses:n.hypotheses.map(c=>({...c})),item:g,by:t.by}],contributors:[...new Set([...n.contributors,t.by])]},t,"preregister")}),observe:p("observe","verify","observe",(s,n,t,a)=>{let r=O(n),u=t.result,o=D(u,["id","valid","summary","provenanceRefs"]);return o&&a(`unknown key "${o}" in result`,"use only id, valid, summary and provenanceRefs in result"),(t.experiment!==r.experiment.id||!u||!y(u.id)||typeof u.valid!="boolean"||!y(u.summary)||!B(u.provenanceRefs)||n.rounds.some(l=>l.result?.id===u.id))&&a("observation needs current experiment, unique result and provenance","set experiment to the active experiment ID and result to {id, valid, summary, provenanceRefs} with a new result.id"),s.items[r.item]?.status!=="done"&&a("complete experiment execution before recording observations","dispatch and complete the active experiment item before calling observe"),N(s,r.item).some(l=>u.provenanceRefs.includes(l))||a("observation must link fresh experiment-output evidence from the latest completion",`include an experiment-output ref produced by the latest successful completion of item "${r.item}" in result.provenanceRefs`),b(s,{...n,phase:"update-belief",rounds:n.rounds.map(l=>l===r?{...l,result:{id:u.id,valid:u.valid,summary:u.summary,provenanceRefs:[...u.provenanceRefs]}}:l),contributors:[...new Set([...n.contributors,t.by,...v(s,r.item)])]},t,"observe")}),"update-belief":p("update-belief","define-acceptance","update-belief",(s,n,t,a)=>{let r=O(n),u=t.assessments,o=E(u,["hypothesis","assessment","reason"]);o&&a(`unknown key "${o}" in an assessments entry`,"use only hypothesis, assessment and reason in each assessments entry"),(t.result!==r.result?.id||!Array.isArray(u)||u.length!==n.hypotheses.length||n.hypotheses.some(c=>u.filter(f=>f?.hypothesis===c.id&&["supported","refuted","uncertain"].includes(f.assessment)&&y(f.reason)).length!==1)||!["round","conclusion"].includes(t.next))&&a("belief update must assess every hypothesis against current result","set result to the latest result ID, assessments to one {hypothesis, assessment, reason} per hypothesis, and next to round or conclusion"),!(r.result??I(`round ${r.experiment.id} has no result`)).valid&&u.some(c=>c.assessment!=="uncertain")&&a("invalid experiments cannot support beliefs","set every assessment to uncertain for an invalid experiment result");let g=b(s,{...n,phase:t.next==="round"?"preregister":"conclusion",rounds:n.rounds.map(c=>c===r?{...c,update:{result:t.result,assessments:u.map(f=>({hypothesis:f.hypothesis,assessment:f.assessment,reason:f.reason}))}}:c),contributors:[...new Set([...n.contributors,t.by])]},t,"belief-updated"),w=S(g);return t.next==="round"&&(n.rounds.length>=R(s.config).maxRounds||chunkZ43GUETW_cjs.L(w.budget,w.spent))&&(g=C(g,m(g),t,"stopped","budget or round limit exhausted")),g}),conclude:p("conclude","define-acceptance","conclusion",(s,n,t,a)=>{let r=t;return (!["resolved","inconclusive"].includes(r.outcome)||!y(r.summary)||!B(r.evidenceRefs)||r.evidenceRefs.some(u=>!n.rounds.some(o=>o.result?.provenanceRefs.includes(u))))&&a("conclusion needs observed evidence references","set outcome, summary and evidenceRefs to references preserved in recorded observations"),r.outcome==="resolved"&&(!y(r.supportedHypothesis)||!n.rounds.slice(-1).some(u=>u.result?.valid&&u.update?.assessments.some(o=>o.hypothesis===r.supportedHypothesis&&o.assessment==="supported")))&&a("resolved conclusion needs a supported hypothesis","set supportedHypothesis to a hypothesis supported by the latest valid round, or choose outcome inconclusive"),b(s,{...n,phase:"review",conclusion:{outcome:r.outcome,summary:r.summary,evidenceRefs:[...r.evidenceRefs],...r.supportedHypothesis?{supportedHypothesis:r.supportedHypothesis}:{},by:t.by},contributors:[...new Set([...n.contributors,t.by])]},t,"conclusion")}),"review-conclusion":p("review-conclusion","review","review",(s,n,t,a)=>{let r=n.conclusion??I("phase review has no conclusion");if(chunkBHAEPYRJ_cjs.a(t.by,n.contributors).length&&a("conclusion reviewer must be independent of investigation contributors","use a review-capable role that did not contribute to or execute this investigation"),(typeof t.approve!="boolean"||!y(t.reason))&&a("review needs approval and reason","set approve to a boolean and reason to a nonempty review explanation"),!t.approve){let o=t.next??"conclusion";o!=="round"&&o!=="conclusion"&&a("review rejection next must be round or conclusion","set next to round for more evidence or conclusion for a revised conclusion");let l=b(s,{...n,phase:o==="round"?"preregister":"conclusion",reviewHistory:[...n.reviewHistory??[],{by:t.by,reason:t.reason,approve:false,next:o,replayRefs:[]}]},t,"review-rejected"),g=S(s);return o==="round"&&(n.rounds.length>=R(s.config).maxRounds||chunkZ43GUETW_cjs.L(g.budget,g.spent))?C(l,m(l),t,"stopped","budget or round limit exhausted after review requested another round"):l}let u=Array.isArray(t.replayRefs)?t.replayRefs:[];return r.outcome==="resolved"&&(!B(u)||!n.rounds.some(o=>o.experiment.replayOf&&!chunkBHAEPYRJ_cjs.a(v(s,o.item),v(s,(n.rounds.find(l=>l.experiment.id===o.experiment.replayOf)??I(`round ${o.experiment.id} replays the unknown experiment ${o.experiment.replayOf}`)).item)).length&&F(o.hypotheses.find(l=>l.id===r.supportedHypothesis),O(n).hypotheses.find(l=>l.id===r.supportedHypothesis))&&o.result?.valid&&u.includes(o.result.id)&&o.update?.assessments.some(l=>l.hypothesis===r.supportedHypothesis&&l.assessment==="supported")))&&a("resolved conclusion requires valid replay result and supporting belief update","set replayRefs to a valid independent replay result supporting the latest supported hypothesis definition, or reject with next round"),C(s,{...n,review:{by:t.by,reason:t.reason,replayRefs:u},reviewHistory:[...n.reviewHistory??[],{by:t.by,reason:t.reason,approve:true,replayRefs:u}]},t,r.outcome)}),stop:p("stop","facilitate",void 0,(s,n,t,a)=>(y(t.reason)||a("stop needs reason","set reason to a nonempty explanation for stopping this investigation"),C(s,n,t,"stopped",t.reason)))}}function V(){return [{id:"independent-replay",severity:"error",check(e,i){if(i.type!=="item.complete")return [];let d=m(e)?.rounds.find(s=>s.item===i.payload?.item),p=m(e)?.rounds.find(s=>s.experiment.id===d?.experiment.replayOf);return p&&chunkBHAEPYRJ_cjs.a(i.by,v(e,p.item)).length?[{rule:"independent-replay",item:d.item,severity:"error",message:"Replay executor also executed the original experiment",fix:"assign a different deliver-capable role"}]:[]}},{id:"investigation-execution-only",severity:"error",check(e,i){if(i.type!=="item.complete")return [];let d=i.payload,p=m(e);return p?.phase==="observe"&&p.rounds.at(-1)?.item===d.item?[]:[{rule:"investigation-execution-only",item:d.item,severity:"error",message:"Only the active preregistered experiment can complete",fix:`complete only the active experiment item in phase observe; current phase is ${p?.phase??"intake"}`}]}}]}function G(){return [{id:"replay-worker",name:"Independent replay worker",modelTier:"small",capabilities:["deliver","verify"],canApprove:[],inputs:["preregistered-experiment"],outputs:["experiment-output"],do_not:["Do not change the replay procedure"]},{id:"investigator",name:"Investigator",modelTier:"large",capabilities:["facilitate","define-acceptance","deliver","verify"],canApprove:[],inputs:["question","prior-results"],outputs:["hypotheses","preregistered-experiment","belief-update"],do_not:["Do not revise predictions after execution","Do not approve your own conclusions"]},{id:"conclusion-reviewer",name:"Independent conclusion reviewer",modelTier:"large",capabilities:["review"],canApprove:["investigation-conclusion"],inputs:["evidence","replay","conclusion"],outputs:["conclusion-review"],do_not:["Do not approve unsupported conclusions"]}]}function J(){return [{id:"intake",name:"Intake",entryPolicy:[],exitPolicy:[{kind:"acceptance-written"}]},{id:"execute",name:"Execute preregistered experiment",entryPolicy:[{kind:"acceptance-written"},{kind:"no-open-blockers"}],exitPolicy:[{kind:"evidence",evidenceKind:"experiment-output"}]},{id:"observed",name:"Execution recorded",entryPolicy:[],exitPolicy:[]}]}function L(){return {name:"investigation",validateConfig:R,lockedConfigKeys:["question","maxRounds","budget"],vocabulary:{backlog:"Questions",item:"Investigation artifact",stage:"Investigation phase",iteration:"Investigation budget",increment:"Conclusion",ceremony:"Investigation ceremony",gate:"Independent conclusion review"},defaultStages:J,defaultRoles:G,requiredCapabilities:["facilitate","define-acceptance","deliver","verify","review"],exclusiveCapabilities:[],humanDefaults:{gates:"none"},ceremonies:U(L),plannerOptions:e=>({schedulerMode:"level",concurrencyCap:1,roleFor:i=>{let d=m(e)?.rounds.find(a=>a.item===i.id),p=m(e)?.rounds.find(a=>a.experiment.id===d?.experiment.replayOf),s=p?v(e,p.item):[],n=Object.values(e.roles),t=(p?void 0:n.find(a=>a.capabilities.includes("deliver")&&a.capabilities.includes("define-acceptance")))??n.find(a=>a.capabilities.includes("deliver")&&!chunkBHAEPYRJ_cjs.a(a.id,s).length);return t||chunkOSHBJIYD_cjs.b("missing-capability",`No eligible executor for experiment item "${i.id}"`,p?`register an independent deliver-capable role that did not execute "${p.item}"`:"register a role with deliver capability",{items:[i.id]}),t.id},estimateMode:"per-call",fallbackTokensPerWeight:1}),candidates:e=>{let i=m(e),d=i?.rounds.at(-1)?.item;return i?.phase==="observe"&&!chunkZ43GUETW_cjs.L(e.config.budget,S(e).spent)?Object.values(e.items).filter(p=>p.id===d&&p.stage==="execute"&&p.status==="todo"):[]},afterComplete:(e,i,d)=>{let p=m(e),s=e.iterations.find(n=>n.id==="investigation");return p?.phase!=="observe"||p.rounds.at(-1)?.item!==i||e.items[i]?.status==="done"||!s||!chunkZ43GUETW_cjs.L(s.budget,s.spent)?e:C(e,p,{by:"investigation",now:d},"stopped",`budget exhausted before experiment item "${i}" completed; start a new investigation with sufficient budget`)},invariants:e=>[`Question: ${e.config.question}`,"Execute only the preregistered procedure; retain raw observation provenance; report invalid runs."],rules:V(),metrics:e=>({rounds:m(e)?.rounds.length??0,validRuns:m(e)?.rounds.filter(i=>i.result?.valid).length??0,invalidRuns:m(e)?.rounds.filter(i=>i.result&&!i.result.valid).length??0}),report:e=>({phase:m(e)?.phase??"intake",outcome:m(e)?.outcome??null,rounds:m(e)?.rounds.length??0,conclusion:m(e)?.conclusion??null,stopReason:m(e)?.stopReason??null})}}exports.a=R;exports.b=L;//# sourceMappingURL=chunk-QAENYYU6.cjs.map
2
- //# sourceMappingURL=chunk-QAENYYU6.cjs.map
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkBHAEPYRJ_cjs=require('./chunk-BHAEPYRJ.cjs'),chunkBBI7AKJK_cjs=require('./chunk-BBI7AKJK.cjs'),chunkZ43GUETW_cjs=require('./chunk-Z43GUETW.cjs'),chunkOSHBJIYD_cjs=require('./chunk-OSHBJIYD.cjs');var g=e=>chunkBBI7AKJK_cjs.a(e,"experimentation"),y=(e,t)=>chunkBBI7AKJK_cjs.b(e,"experimentation",t);var k=["tokens","turns","wallclockMs"];function C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function r(e){return chunkOSHBJIYD_cjs.b("invalid-input",e,"supply valid experimentation ceremony input")}function m(e,t){return (typeof e!="string"||!e.trim())&&r(`${t} must be a non-empty string`),e}function v(e,t="sha"){let n=m(e,t);return /^[a-f0-9]{40}$|^[a-f0-9]{64}$/.test(n)||r(`${t} must be a full lowercase commit SHA`),n}function re(e,t){(!C(e)||!k.some(a=>e[a]!==void 0)||Object.keys(e).some(a=>!k.includes(a)))&&r(`${t} needs tokens, turns or wallclockMs limits`);let n={};for(let a of k){let i=e[a];i!==void 0&&((typeof i!="number"||!Number.isSafeInteger(i)||i<=0)&&r(`${t}.${a} must be a positive safe integer`),n[a]=i);}return n}function b(e){try{C(e)||r("experimentation config must be an object");let t=["objective","direction","tieBreak","concurrencyCap","maxCandidates","candidateBudget","totalBudget"];Object.keys(e).some(c=>!t.includes(c))&&r("unknown experimentation config key");let n=m(e.objective,"objective"),a=e.direction??"minimize";a!=="minimize"&&a!=="maximize"&&r("direction must be minimize or maximize");let i=e.tieBreak??"candidate-id";i!=="candidate-id"&&r("tieBreak must be candidate-id");let o=e.concurrencyCap??2,s=e.maxCandidates??4;for(let[c,d]of Object.entries({concurrencyCap:o,maxCandidates:s}))(typeof d!="number"||!Number.isSafeInteger(d)||d<1)&&r(`${c} must be a positive safe integer`);return o>s&&r("concurrencyCap cannot exceed maxCandidates"),{objective:n,direction:a,tieBreak:i,concurrencyCap:o,maxCandidates:s,candidateBudget:re(e.candidateBudget??{turns:10},"candidateBudget"),totalBudget:re(e.totalBudget??{turns:40},"totalBudget")}}catch(t){chunkOSHBJIYD_cjs.b("config-invalid",t instanceof Error?t.message:"invalid experimentation config","provide objective and positive finite limits");}}function S(e){let t=g(e);return (e.methodology!=="experimentation"||!t)&&r("freeze an experimentation workflow first"),t}function de(e,t,n){chunkZ43GUETW_cjs.e(e,t)?.capabilities.includes(n)||chunkOSHBJIYD_cjs.b("missing-capability",`${t} needs ${n}`,"use a role with the required capability");}function ce(e,t,n){return e.events.reduce((a,i)=>{if(i.type!=="item.completed"||!C(i.payload))return a;let o=i.payload;return typeof o.id!="string"||o.role!==i.by||t!==void 0&&o.id!==t||n!==void 0&&o.role!==n||typeof o.tokens!="number"||!Number.isFinite(o.tokens)||o.tokens<0||typeof o.durationMs!="number"||!Number.isFinite(o.durationMs)||o.durationMs<0||t===void 0&&Object.values(g(e)?.candidates??{}).some(s=>s.item===o.id)?a:{tokens:a.tokens+o.tokens,turns:a.turns+1,wallclockMs:a.wallclockMs+o.durationMs}},{tokens:0,turns:0,wallclockMs:0})}function V(e,t){return {tokens:Math.max(e.tokens,t.tokens),turns:Math.max(e.turns,t.turns),wallclockMs:Math.max(e.wallclockMs,t.wallclockMs)}}function E(e,t){return V(t.spent,ce(e,t.item,t.author))}function G(e,t){let n=g(e);if(!n)return e;let a=j(e),i=["stopped","integrated"].includes(n.status);return {...e,iterations:e.iterations.map(o=>o.id==="experiment"?{...o,budget:{...b(e.config).totalBudget},spent:a,...i?{endedAt:o.endedAt??chunkZ43GUETW_cjs.a(t),outcome:o.outcome??(n.status==="integrated"?"completed":"cancelled")}:{}}:o)}}function j(e,t=S(e)){let n=V(t.overhead,ce(e));return Object.values(t.candidates).reduce((a,i)=>{let o=E(e,i);return {tokens:a.tokens+o.tokens,turns:a.turns+o.turns,wallclockMs:a.wallclockMs+o.wallclockMs}},n)}function L(e){return Object.values(g(e)?.candidates??{}).filter(t=>t.status==="running"||e.items[t.item]?.status==="in_progress").length}function U(e){return Object.values(g(e)?.candidates??{}).reduce((t,n)=>{let a=e.items[n.item];return t+(a?.status==="in_progress"?chunkZ43GUETW_cjs.M(e,a.weight,1):0)},0)}function be(e){let t=b(e.config).totalBudget.tokens;if(t!==void 0)return Math.max(0,t-j(e).tokens-U(e))}function Q(e,t){let n=e.items[t.item];return !!n&&(!n.role||n.role===t.author)&&!!chunkZ43GUETW_cjs.e(e,t.author)?.capabilities.includes("deliver")}function X(e,t){let n=b(e.config),a=E(e,t);return k.some(i=>n.candidateBudget[i]!==void 0&&a[i]>=n.candidateBudget[i])}function I(e){if(!g(e))return false;let t=b(e.config),n=j(e);return k.some(a=>t.totalBudget[a]!==void 0&&n[a]>=t.totalBudget[a])}function W(e,t){let n=m(t.candidate,"candidate");return Object.hasOwn(e.candidates,n)||r(`unknown candidate ${n}`),e.candidates[n]}function se(e){let t=e.selected;return (t===void 0||!Object.hasOwn(e.candidates,t))&&chunkOSHBJIYD_cjs.b("invalid-input",`the experiment's selected candidate ${JSON.stringify(t)} is not one of its candidates`,"restore .workflow/state.json from git, or run compare again"),e.candidates[t]}function q(e,t){return typeof e[t]!="boolean"&&r(`${t} must be boolean`),e[t]}function J(e){C(e.spent)||r("spent must contain nonnegative tokens, turns and wallclockMs");let t={};for(let n of k){let a=e.spent[n];(typeof a!="number"||!Number.isSafeInteger(a)||a<0)&&r(`spent.${n} must be a nonnegative safe integer`),t[n]=a;}return t}function $(e,t){return {...e,candidates:{...e.candidates,[t.id]:t}}}function P(e,t){let n=J(t);return {...e,overhead:{tokens:e.overhead.tokens+n.tokens,turns:e.overhead.turns+n.turns,wallclockMs:e.overhead.wallclockMs+n.wallclockMs}}}function D(e,t,n){return chunkZ43GUETW_cjs.u(e,t.item,{stage:"done",status:"dropped"},n.by,n.now)}function A(e){e.status!=="running"&&r("experiment is not running");}function N(e){return ["validated","failed","timed-out","cancelled"].includes(e.status)}function K(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="boolean")return true;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e)||!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype)return false;t.add(e);let n=Array.isArray(e)?e.every(a=>K(a,t)):Object.values(e).every(a=>a===void 0||K(a,t));return t.delete(e),n}function w(e,t,n){return (a,i)=>((!C(i)||!K(i))&&r("ceremony input must be JSON-safe"),m(i.by,"by"),i.now!==void 0&&(typeof i.now!="string"||!Number.isFinite(Date.parse(i.now)))&&r("now must be a valid timestamp"),de(a,i.by,t),chunkZ43GUETW_cjs.U(a,le(),{type:`ceremony.${e}`,by:i.by,payload:i},o=>chunkZ43GUETW_cjs.c(G(n(o,i),i.now),`experimentation.${e}`,i.by,structuredClone(i),chunkZ43GUETW_cjs.a(i.now))))}function ue(){return {freeze:w("frozen","facilitate",(e,t)=>{(e.methodology!=="experimentation"||g(e))&&r("freeze may run only once in experimentation");let n=b(e.config),a=v(t.baseSha,"baseSha"),i=m(t.harness,"harness");(!Array.isArray(t.candidates)||t.candidates.length<1||t.candidates.length>n.maxCandidates)&&r("candidates must be a nonempty array within maxCandidates");let o={},s=new Set;for(let c of t.candidates){C(c)||r("candidate must be an object");let d=m(c.id,"candidate.id");chunkOSHBJIYD_cjs.c(d,"candidate id"),Object.hasOwn(o,d)&&r("candidate IDs must be unique safe identifiers");let l=m(c.item,"candidate.item"),f=m(c.author,"candidate.author");de(e,f,"deliver");let u=chunkZ43GUETW_cjs.r(e,l);u.role&&u.role!==f&&r("candidate item role must match frozen author"),(s.has(l)||u.stage!=="candidate"||u.status!=="todo"||u.acceptance.length===0)&&r("candidate needs a distinct todo candidate item with acceptance criteria"),s.add(l),o[d]={id:d,item:l,author:f,status:"pending",spent:{tokens:0,turns:0,wallclockMs:0}};}return y({...e,iterations:[...e.iterations,{id:"experiment",goal:n.objective,budget:{...n.totalBudget},spent:{tokens:0,turns:0,wallclockMs:0},startedAt:chunkZ43GUETW_cjs.a(t.now),committed:[...s],carryover:[]}]},{status:"running",baseSha:a,harness:i,candidates:o,released:[],overhead:{tokens:0,turns:0,wallclockMs:0}})}),provision:w("provisioned","manage-flow",(e,t)=>{let n=S(e);A(n),I(e)&&r("total experiment budget exhausted");let a=W(n,t);a.status!=="pending"&&r("candidate already provisioned");let i=m(t.workspace,"workspace");return (chunkBHAEPYRJ_cjs.b({baseSha:n.baseSha},{baseSha:v(t.baseSha,"baseSha")}).length||t.isolated!==true)&&r("provision must attest isolated workspace at the exact frozen base SHA"),Object.values(n.candidates).some(o=>o.workspace===i)&&r("candidate workspaces must be distinct"),n=$(n,{...a,workspace:i,status:"ready"}),y(e,n)}),start:w("started","deliver",(e,t)=>{let n=S(e);A(n);let a=W(n,t);(a.status!=="ready"||a.author!==t.by)&&r("only the candidate author may start a ready candidate"),I(e)&&r("total experiment budget exhausted");let i=b(e.config),o=Object.values(n.candidates).filter(p=>p.status==="running"||e.items[p.item]?.status==="in_progress").length;o>=i.concurrencyCap&&r("candidate concurrency cap reached"),Q(e,a)||r("candidate author assignment or delivery capability changed");let s=j(e);i.totalBudget.turns!==void 0&&s.turns+o>=i.totalBudget.turns&&r("total experiment budget reserved by running candidates");let c=chunkZ43GUETW_cjs.e(e,a.author),d=c.resourceClass??c.id,l=chunkZ43GUETW_cjs.P(e)[d],f=Object.values(e.items).filter(p=>p.status==="in_progress"&&p.role&&(chunkZ43GUETW_cjs.e(e,p.role)?.resourceClass??p.role)===d).length;l!==void 0&&f>=l&&r("role resource capacity reached");let u=chunkZ43GUETW_cjs.r(e,a.item),x=be(e);x!==void 0&&chunkZ43GUETW_cjs.M(e,u.weight,1)>x&&r("total experiment token budget reserved or insufficient"),u.status!=="todo"&&r("candidate item is already dispatched"),chunkZ43GUETW_cjs.C(e,u,[{kind:"dependencies-done"},{kind:"no-open-blockers"},{kind:"acceptance-written"},...e.stages.find(p=>p.id==="building").entryPolicy],"start candidate execution"),X(e,a)&&r("candidate budget exhausted");let h=chunkZ43GUETW_cjs.u(e,a.item,{stage:"building",status:"in_progress"},t.by,t.now);return h=chunkZ43GUETW_cjs.q(h,a.item,p=>({...p,role:t.by})),y(h,$(n,{...a,status:"running"}))}),submit:w("submitted","deliver",(e,t)=>{let n=S(e);A(n);let a=W(n,t),i=chunkZ43GUETW_cjs.r(e,a.item);(a.status!=="running"&&!(a.status==="ready"&&i.status==="in_progress")||a.author!==t.by||i.role!==t.by)&&r("only the running candidate author may submit once");let o=v(t.sha);(chunkBHAEPYRJ_cjs.b({workspace:a.workspace,harness:n.harness},t).length||chunkBHAEPYRJ_cjs.b({baseSha:n.baseSha},{baseSha:v(t.baseSha,"baseSha")}).length)&&r("submission provenance must match frozen base SHA, harness and owned workspace"),(typeof t.score!="number"||!Number.isFinite(t.score))&&r("score must be finite");let s=J(t),c=m(t.command,"command"),d=m(t.log,"log"),l=b(e.config),f=E(e,{...a,spent:s}),u=k.some(p=>l.candidateBudget[p]!==void 0&&f[p]>l.candidateBudget[p]),x={...a,status:u?"timed-out":"submitted",sha:o,score:t.score,spent:f,command:c,log:d};u&&(x.reason="candidate budget exceeded");let h=y(e,$(n,x));return h=chunkZ43GUETW_cjs.y(h,a.item,{kind:"candidate-sha",ref:o,by:t.by},t.now),h=chunkZ43GUETW_cjs.y(h,a.item,{kind:"benchmark-result",ref:JSON.stringify({score:t.score,harness:n.harness,sha:o}),by:t.by},t.now),u?D(h,x,t):h}),terminate:w("terminated","manage-flow",(e,t)=>{let n=S(e);A(n);let a=W(n,t);N(a)&&r("candidate is already terminal"),["failed","timed-out","cancelled"].includes(t.status)||r("status must be failed, timed-out or cancelled");let i=m(t.reason,"reason"),o=J(t),s=m(t.log,"log");return D(y({...e},$(n,{...a,status:t.status,reason:i,spent:V(E(e,a),E(e,{...a,spent:o})),terminalLog:s})),a,t)}),validate:w("validated","verify",(e,t)=>{let n=S(e);A(n);let a=W(n,t);a.status!=="submitted"&&r("validate an unvalidated submitted candidate"),chunkBHAEPYRJ_cjs.a(t.by,[a.author]).length&&r("candidate author cannot independently validate"),!e.events.some(x=>x.type==="experimentation.started"&&C(x.payload)&&x.payload.candidate===a.id)&&chunkZ43GUETW_cjs.r(e,a.item).status==="in_progress"&&chunkOSHBJIYD_cjs.b("invalid-input",`candidate "${a.id}" item "${a.item}" is still in progress under the planner`,`complete item "${a.item}" with the builder's handoff (candidate-sha ${a.sha}) and accounting before validating`,{items:[a.item]});let o=v(t.sha),s=m(t.harness,"harness");chunkBHAEPYRJ_cjs.b({sha:a.sha,harness:n.harness},{sha:o,harness:s}).length&&r("validation must match exact submitted SHA and frozen harness");let c=q(t,"passed"),d=q(t,"reproducible"),l=m(t.evidence,"evidence"),f={sha:o,harness:s,by:t.by,passed:c,reproducible:d,evidence:l},u=y({...e},$(P(n,t),{...a,status:c&&d?"validated":"failed",validation:f}));return u=chunkZ43GUETW_cjs.y(u,a.item,{kind:"validation",ref:l,by:t.by},t.now),u=chunkZ43GUETW_cjs.u(u,a.item,{stage:"done",status:c&&d?"done":"dropped"},t.by,t.now),u}),compare:w("compared","facilitate",(e,t)=>{let n=S(e);A(n);let a=Object.values(n.candidates);a.every(N)||r("comparison requires all candidates terminal and submissions independently validated");let i=b(e.config),o=j(e,n);if(k.some(d=>i.totalBudget[d]!==void 0&&o[d]>i.totalBudget[d]))return y(e,{...n,status:"stopped",reason:"total budget exceeded"});let s=a.filter(d=>{let l=E(e,d);return d.status==="validated"&&d.validation?.passed&&d.validation.reproducible&&!chunkBHAEPYRJ_cjs.b({sha:d.sha,harness:n.harness},d.validation).length&&!k.some(f=>i.candidateBudget[f]!==void 0&&l[f]>i.candidateBudget[f])});s.sort((d,l)=>(d.score-l.score)*(i.direction==="minimize"?1:-1)||(d.id<l.id?-1:d.id>l.id?1:0));let c=s[0];return y({...e},c?{...n,status:"selected",selected:c.id}:{...n,status:"stopped",reason:"no eligible candidate"})}),integrate:w("integration-recorded","control-change",(e,t)=>{let n=S(e);(!["selected","integrating"].includes(n.status)||!n.selected)&&r("compare and select before integration"),I(e)&&r("total budget exhausted before integration");let a=se(n),i=v(t.selectedSha,"selectedSha");(i!==a.sha||a.validation?.sha!==i)&&r("integration must promote the exact selected and validated SHA");let o=v(t.targetSha,"targetSha"),s=v(t.integrationSha,"integrationSha");return n.integration?.sha===s&&n.integration.targetSha===o&&r("integration already recorded"),y(e,{...P(n,t),status:"integrating",integration:{selectedSha:i,targetSha:o,sha:s,by:t.by}})}),"validate-integration":w("integration-validated","verify",(e,t)=>{let n=S(e);(n.status!=="integrating"||!n.integration||!n.selected)&&r("record integration before fresh validation");let a=n.integration,i=se(n);chunkBHAEPYRJ_cjs.a(t.by,[a.by,i.author]).length&&r("integration validation must be independent of candidate author and integrator");let o=v(t.sha),s=v(t.targetSha,"targetSha"),c=m(t.harness,"harness");chunkBHAEPYRJ_cjs.b({sha:a.sha,targetSha:a.targetSha,harness:n.harness},{sha:o,targetSha:s,harness:c}).length&&r("fresh validation must match integration SHA, current target SHA and harness");let d=q(t,"passed"),l=m(t.evidence,"evidence"),f=P(n,t),u=b(e.config),x=j(e,f),h=k.some(p=>u.totalBudget[p]!==void 0&&x[p]>u.totalBudget[p]);return y(e,{...f,status:d&&!h?"integrated":"stopped",...d&&!h?{}:{reason:h?"total budget exceeded":"integration validation failed"},integration:{...a,validation:{by:t.by,sha:o,harness:c,evidence:l,passed:d}}})}),stop:w("stopped","manage-flow",(e,t)=>{let n=S(e);(n.status==="stopped"||n.status==="integrated")&&r("experiment already closed");let a=m(t.reason,"reason");Object.values(n.candidates).some(s=>s.status==="running"||s.status==="submitted"||e.items[s.item]?.status==="in_progress")&&r("terminate active attempts with final usage and log before stopping");let i=Object.fromEntries(Object.values(n.candidates).map(s=>[s.id,N(s)?s:{...s,status:"cancelled",reason:a}])),o=e;for(let s of Object.values(n.candidates))N(s)||(o=D(o,s,t));return y(o,{...P(n,t),status:"stopped",reason:a,candidates:i})}),cleanup:w("cleanup-recorded","manage-flow",(e,t)=>{let n=S(e);return n.status!=="stopped"&&n.status!=="integrated"&&r("cleanup requires a closed experiment"),(!Array.isArray(t.workspaces)||t.workspaces.length===0||t.workspaces.some(a=>typeof a!="string"||!Object.values(n.candidates).some(i=>i.workspace===a)||n.released.includes(a))||new Set(t.workspaces).size!==t.workspaces.length)&&r("workspaces must list distinct owned unreleased identities"),y(e,{...n,released:[...n.released,...t.workspaces]})})}}function pe(e){let t=g(e),n=Object.values(t?.candidates??{});return {candidates:n.length,validated:n.filter(a=>a.status==="validated").length,failed:n.filter(a=>a.status==="failed").length,timedOut:n.filter(a=>a.status==="timed-out").length,cancelled:n.filter(a=>a.status==="cancelled").length,integrated:t?.status==="integrated"?1:0,spent:t?{...j(e)}:{tokens:0,turns:0,wallclockMs:0},candidateTokens:Object.fromEntries(n.map(a=>[a.id,E(e,a).tokens]))}}function me(e){let t=g(e);return {status:t?.status??"unfrozen",baseSha:t?.baseSha??null,harness:t?.harness??null,selected:t?.selected??null,reason:t?.reason??null,integration:t?.integration?structuredClone(t.integration):null,candidates:structuredClone(t?.candidates??{}),cleanup:Object.values(t?.candidates??{}).flatMap(n=>n.workspace&&!t?.released.includes(n.workspace)?[n.workspace]:[]),hostResponsibilities:["provision isolated workspaces at baseSha","execute candidates and the frozen harness","integrate selected SHA at the current target","execute fresh integration validation","release owned workspace identities and record cleanup"]}}function fe(){return [{id:"coordinator",name:"Experiment coordinator",modelTier:"large",capabilities:["facilitate","order-backlog","manage-flow"],canApprove:[],inputs:["objective","budgets"],outputs:["comparison"],do_not:["Change the frozen baseline or harness"]},{id:"builder",name:"Candidate builder",modelTier:"large",capabilities:["deliver"],canApprove:[],inputs:["frozen harness","isolated workspace"],outputs:["candidate-sha","benchmark-result"],do_not:["Validate your own candidate","Change another candidate workspace"]},{id:"validator",name:"Independent validator",modelTier:"large",capabilities:["verify","review","approve-gate"],canApprove:["experiment-validation"],inputs:["exact candidate SHA","frozen harness"],outputs:["validation"],do_not:["Approve your own work"]},{id:"integrator",name:"Selected candidate integrator",modelTier:"large",capabilities:["deliver","control-change"],canApprove:[],inputs:["selected SHA","current target SHA"],outputs:["integration SHA"],do_not:["Declare integration validated"]}]}function ge(){return [{id:"experimentation-lifecycle",severity:"error",check(e,t){let n=[],a=g(e),i=t.payload;if(t.type==="item.complete"){["done","needs-review"].includes(i?.handoff?.verdict??"done")||n.push("unsupported completion verdict: terminate this attempt with final usage and log, then freeze a new experiment for retries");let o=a&&Object.values(a.candidates).find(s=>s.item===i?.item);(!o||!["submitted","validated"].includes(o.status))&&n.push("submit the candidate SHA and benchmark before completing work"),o?.status==="submitted"&&!i?.handoff?.produced?.some(s=>s.kind==="candidate-sha"&&s.ref===o.sha)&&n.push("handoff must retain the exact submitted candidate SHA");}return n.map(o=>({rule:"experimentation-lifecycle",severity:"error",message:o,fix:"follow the frozen experimentation lifecycle"}))}}]}function he(){return [{id:"candidate",name:"Frozen candidate",entryPolicy:[],exitPolicy:[{kind:"acceptance-written"},{kind:"no-open-blockers"},{kind:"dependencies-done"}]},{id:"building",name:"Isolated candidate execution",entryPolicy:[{kind:"acceptance-written"},{kind:"no-open-blockers"},{kind:"dependencies-done"}],exitPolicy:[{kind:"evidence",evidenceKind:"candidate-sha"},{kind:"evidence",evidenceKind:"benchmark-result"}]},{id:"validation",name:"Independent exact-SHA validation",review:true,entryPolicy:[],exitPolicy:[{kind:"evidence",evidenceKind:"validation"}],gate:{id:"experiment-validation",requires:[{capability:"verify"}],evidence:["validation"],onFail:{action:"block"}}},{id:"done",name:"Candidate work complete",entryPolicy:[],exitPolicy:[],deliveryPoint:true}]}function le(){return {name:"experimentation",vocabulary:{backlog:"Candidate pool",item:"Candidate work item",stage:"Experiment stage",iteration:"Experiment run",increment:"Validated integration",ceremony:"Experiment control",gate:"Independent validation"},validateConfig:b,defaultStages:he,defaultRoles:fe,requiredCapabilities:["facilitate","manage-flow","deliver","verify","control-change"],exclusiveCapabilities:[],plannerOptions(e){let t=b(e.config);return {schedulerMode:"throughput",dispatchStage:"building",concurrencyCap:Math.max(1,t.concurrencyCap-L(e)),fallbackTokensPerWeight:1,reservedTokens:U(e),roleFor(n){return Object.values(g(e)?.candidates??{}).find(a=>a.item===n.id)?.author}}},candidates(e){let t=g(e);if(!t||t.status!=="running")return [];let n=b(e.config);return I(e)||L(e)>=n.concurrencyCap?[]:Object.values(t.candidates).filter(a=>a.status==="ready"&&Q(e,a)&&e.items[a.item]?.status==="todo"&&!X(e,a)).map(a=>e.items[a.item])},afterComplete(e,t,n){return G(e,n)},invariants(e,t){let n=g(e),a=Object.values(n?.candidates??{}).find(i=>i.item===t.id);return [`Frozen base SHA: ${n?.baseSha??"unfrozen"}; harness: ${n?.harness??"unfrozen"}`,`Candidate: ${a?.id??"unregistered"}; isolated workspace: ${a?.workspace??"not provisioned"}`,`Objective and budget: ${JSON.stringify(e.config)}`,"Submit an exact commit SHA and harness benchmark before completion; independent validation is mandatory.","Host owns process execution, Git integration and workspace cleanup."]},ceremonies:ue(),rules:ge(),metrics:pe,report:me,humanDefaults:{gates:"none"},lockedConfigKeys:["objective","direction","tieBreak","concurrencyCap","maxCandidates","candidateBudget","totalBudget"]}}exports.a=b;exports.b=ue;exports.c=pe;exports.d=me;exports.e=fe;exports.f=ge;exports.g=he;exports.h=le;//# sourceMappingURL=chunk-SFYUJQYW.cjs.map
2
- //# sourceMappingURL=chunk-SFYUJQYW.cjs.map
@@ -1,2 +0,0 @@
1
- import {b as b$1,c}from'./chunk-YS6CXERQ.mjs';import {ExFlow,ExFlowRuntimeError}from'ex-flow';function h(e){return e??new Date().toISOString()}function Y(e){let t=new Set;for(let i of e.stages)t.has(i.id)&&b$1("config-invalid",`duplicate stage id "${i.id}"`,"give every stage a unique id"),t.add(i.id);let o={};for(let i of e.roles)c(i.id,"role id"),Object.hasOwn(o,i.id)&&b$1("duplicate-role",`duplicate role id "${i.id}"`,"give every role a unique id"),o[i.id]=i;let n=h(e.now);return {version:1,methodology:e.methodology,config:e.config,items:{},stages:e.stages,roles:o,iterations:[],events:[{seq:1,at:n,type:"state.created",by:"system",payload:{methodology:e.methodology}}],accounting:[],pending:[],lessons:[],agreements:[]}}function w(e,t,o,n,i){let s={seq:(e.events[e.events.length-1]?.seq??0)+1,at:h(i),type:t,by:o,payload:n};return {...e,events:[...e.events,s]}}function $e(e,t){for(let o=e.events.length-1;o>=0;o--){let n=e.events[o];if(t===void 0||n.type===t)return n}}function V(e,t){return Object.hasOwn(e.roles,t)?e.roles[t]:void 0}function G(e,t){return e.capabilities.includes(t)}function q(e,t){return Object.values(e.roles).filter(o=>G(o,t))}function B(e,t,o,n){return Object.values(e.roles).filter(i=>i.id!==n&&i.canApprove.includes(t)&&(o===void 0||i.capabilities.includes(o))).map(i=>i.id)}function Re(e,t){return q(e,"approve-gate").filter(o=>o.canApprove.includes(t))}function ee(e,t,o){for(let n of t)q(e,n).length===0&&b$1("missing-capability",`no registered role has capability "${n}"`,`register a role whose capabilities include "${n}" (registerRole) before init`);for(let n of o){let i=q(e,n);i.length>1&&b$1("exclusive-capability",`capability "${n}" must belong to exactly one role but is held by ${i.map(r=>r.id).join(", ")}`,`remove "${n}" from all but one role`);}}function te(e,t){return t.length===0?[]:Object.values(e.roles).filter(o=>t.every(n=>G(o,n)))}function he(e,t,...o){if(t==="human")return true;let n=V(e,t);return !!n&&o.some(i=>G(n,i))}function Ee(e,t,...o){if(!he(e,t,...o)){let n=Object.values(e.roles).filter(i=>o.some(r=>G(i,r))).map(i=>i.id);b$1("missing-capability",`"${t}" lacks capability ${o.map(i=>`"${i}"`).join(" or ")}`,`run this as one of: human${n.map(i=>`, ${i}`).join("")}`);}}function M(e,t){let o=e.stages.find(n=>n.id===t);return o||b$1("unknown-stage",`stage "${t}" does not exist`,`stages are: ${e.stages.map(n=>n.id).join(" \u2192 ")}`),o}function oe(e,t){let o=e.stages.findIndex(n=>n.id===t);return o<0&&M(e,t),e.stages[o+1]}function ne(e,t){return e.stages[e.stages.length-1]?.id===t}function R(e,t){return {...e,items:{...e.items,[t.id]:t}}}function ie(e,t,o){return R(e,o(b(e,t)))}function b(e,t){let o=Object.hasOwn(e.items,t)?e.items[t]:void 0;return o||b$1("unknown-item",`item "${t}" does not exist`,`add it with addItem first; known items: ${Object.keys(e.items).join(", ")||"(none)"}`,{items:[t]}),o}function _(e,t,o){let n=t.filter(i=>!Object.hasOwn(e.items,i));n.length&&b$1("unknown-item",`${o} refers to unknown item(s) ${n.join(", ")}`,"add those items first or remove the reference",{items:n});}function De(e,t,o,n){c(t.id,"item id"),Object.hasOwn(e.items,t.id)&&b$1("duplicate-item",`item "${t.id}" already exists`,"use editItem to change it, or pick a new id",{items:[t.id]});let i=e.stages[0];i||b$1("config-invalid","state has no stages","create the state with at least one stage");let r=t.stage??i.id;M(e,r),_(e,t.dependsOn??[],`item "${t.id}".dependsOn`),t.affects&&_(e,t.affects,`item "${t.id}".affects`),t.parent!==void 0&&_(e,[t.parent],`item "${t.id}".parent`),t.role!==void 0&&!Object.hasOwn(e.roles,t.role)&&b$1("unknown-role",`role "${t.role}" does not exist`,`registered roles: ${Object.keys(e.roles).join(", ")}`);let{stage:s,...a}=t,l={type:"task",acceptance:[],dependsOn:[],...a,id:t.id,title:t.title,stage:r,status:"todo",evidence:[],blockers:[],transitions:[]},f=R(e,l);return w(f,"item.added",o,{id:l.id,type:l.type,stage:l.stage,weight:l.weight??null,priority:l.priority??null,phase:l.phase??null,parent:l.parent??null},n)}function Ve(e,t,o,n,i){let r=b(e,t);o.dependsOn&&_(e,o.dependsOn,`item "${t}".dependsOn`),o.affects&&_(e,o.affects,`item "${t}".affects`),o.parent!==void 0&&_(e,[o.parent],`item "${t}".parent`),o.role!==void 0&&!Object.hasOwn(e.roles,o.role)&&b$1("unknown-role",`role "${o.role}" does not exist`,`registered roles: ${Object.keys(e.roles).join(", ")}`);let s=Object.keys(o).filter(f=>JSON.stringify(o[f])!==JSON.stringify(r[f]));s.length===0&&b$1("no-op",`editItem("${t}") changes nothing`,"pass at least one field with a different value",{items:[t]});let a={...r};for(let f of s)a[f]=o[f];let l=R(e,a);return w(l,"item.edited",n,{id:t,changed:s},i)}function P(e,t,o,n,i){let r=b(e,t),s=o.stage??r.stage;M(e,s),(r.status==="done"||r.status==="dropped")&&b$1("invalid-transition",`item "${t}" is ${r.status} and cannot move`,"create a new item (or a change-request) instead of reopening a finished one",{items:[t]}),s===r.stage&&o.status===r.status&&b$1("no-op",`item "${t}" is already ${r.status} in "${s}"`,"choose a different stage or status",{items:[t]});let a=h(i),l={...r,stage:s,status:o.status,transitions:[...r.transitions,{from:{stage:r.stage,status:r.status},to:{stage:s,status:o.status},at:a,by:n}]},f=R(e,l);return w(f,"item.transition",n,{id:t,from:{stage:r.stage,status:r.status},to:{stage:s,status:o.status}},a)}function Q(e,t){return ye(e,t,["role"])}function re(e,t,o,n,i){let r=b(e,t),s=oe(e,r.stage);if(!s)return P(e,t,{status:"done"},o,i);if(ne(e,s.id))return P(e,t,{stage:s.id,status:"done"},o,i);let a=n||s.review===true?"review":"todo";return Q(P(e,t,{stage:s.id,status:a},o,i),t)}function ye(e,t,o){return ie(e,t,n=>{let i={...n};for(let r of o)delete i[r];return i})}function K(e,t){let o=0,n=false;for(let i=e.events.length-1;i>=0;i--){let r=e.events[i];if(r.payload?.id===t.id){if(r.type==="item.rework"){n=true;break}r.type==="item.evidence"&&o++;}}return n?t.evidence.slice(Math.max(0,t.evidence.length-o)):t.evidence}function Qe(e,t,o,n){let i=b(e,t),r=h(n),s={...i,evidence:[...i.evidence,{...o,at:r}]},a=R(e,s);return w(a,"item.evidence",o.by,{id:t,kind:o.kind,ref:o.ref},r)}function ae(e,t,o,n,i,r){let s=b(e,t),a=h(r),l=`${t}-b${s.blockers.length+1}`,f=s.status==="blocked"?null:{from:{stage:s.stage,status:s.status},to:{stage:s.stage,status:"blocked"},at:a,by:i},g={...s,status:"blocked",blockers:[...s.blockers,{id:l,reason:o,owner:n,raisedAt:a}],transitions:f?[...s.transitions,f]:s.transitions},p=R(e,g);return w(p,"blocker.raised",i,{id:t,blocker:l,reason:o,owner:n,transition:f&&{from:f.from,to:f.to}},a)}function se(e,t){for(let o=e.transitions.length-1;o>=0;o--){let n=e.transitions[o];if(n.to.status===t)return n}}function ot(e,t,o,n,i,r){let s=b(e,t),a=s.blockers.findIndex(W=>W.id===o&&!W.clearedAt);a<0&&b$1("invalid-input",`item "${t}" has no open blocker "${o}"`,`open blockers: ${s.blockers.filter(W=>!W.clearedAt).map(W=>W.id).join(", ")||"(none)"}`,{items:[t]});let l=h(i),f=s.blockers.map((W,F)=>F===a?{...W,clearedAt:l}:W),g=f.some(W=>!W.clearedAt),p=se(s,"blocked")?.from.status??"todo",u=s.stage,m=p,x=false;p==="in_progress"?(m="todo",u=se(s,"in_progress")?.from.stage??s.stage):p==="awaiting_human"&&(m=M(e,s.stage).review?"review":"todo",x=true);let{role:I,...C}=s,S=g?null:{from:{stage:s.stage,status:"blocked"},to:{stage:u,status:m},at:l,by:n},E={...x&&!g?C:s,blockers:f,stage:g?s.stage:u,status:g?"blocked":m,transitions:S?[...s.transitions,S]:s.transitions},T=R(e,E);return w(T,"blocker.cleared",n,{id:t,blocker:o,transition:S&&{from:S.from,to:S.to},note:r??null},l)}function U(e,t,o){let n=[],i=K(e,t),r=(s,a,l)=>n.push({rule:s,severity:"error",item:t.id,message:a,fix:l});for(let s of o)switch(s.kind){case "evidence":i.some(a=>a.kind===s.evidenceKind)||r("policy:evidence",`item "${t.id}" has no evidence of kind "${s.evidenceKind}"`,`attach evidence { kind: "${s.evidenceKind}" } via addEvidence or in the handoff.produced`);break;case "acceptance-written":t.acceptance.length===0&&r("policy:acceptance-written",`item "${t.id}" has no acceptance criteria`,"editItem with a non-empty acceptance[] (needs define-acceptance)");break;case "estimate-present":t.weight===void 0&&r("policy:estimate-present",`item "${t.id}" has no weight`,"editItem with a weight (story points)");break;case "no-open-blockers":{let a=t.blockers.filter(l=>!l.clearedAt);a.length&&r("policy:no-open-blockers",`item "${t.id}" has ${a.length} open blocker(s)`,`clearBlocker ${a.map(l=>l.id).join(", ")}`);break}case "dependencies-done":{let a=t.dependsOn.filter(l=>e.items[l]?.status!=="done");a.length&&r("policy:dependencies-done",`item "${t.id}" depends on unfinished ${a.join(", ")}`,`finish ${a.join(", ")} first`);break}case "custom":i.some(a=>a.kind===`policy:${s.id}`)||r(`policy:custom:${s.id}`,`item "${t.id}" has not satisfied "${s.description}"`,`attach evidence { kind: "policy:${s.id}" } when it is satisfied`);break}return n}function st(e,t,o,n){let i=U(e,t,o);i.length&&b$1("policy-unmet",`item "${t.id}" cannot ${n}: ${i.length} polic${i.length===1?"y":"ies"} unmet`,i.map(r=>r.fix).join("; "),{items:[t.id]});}function xe(e,t){let o=new Map(e.stages.map((i,r)=>[i.id,r])),n=o.get(t.stage);if(n!==void 0)for(let i=t.transitions.length-1;i>=0;i--){let r=t.transitions[i],s=o.get(r.from.stage);if(r.to.status==="in_progress"&&s!==void 0&&s<n)return r}}function H(e,t){let o=xe(e,t);if(o)return o.by;for(let n=t.transitions.length-1;n>=0;n--){let i=t.transitions[n];if(i.to.status==="in_progress")return i.by}}function Se(e,t,o,n){let i=[],r=K(e,t);for(let a of o.evidence)r.some(l=>l.kind===a)||i.push({rule:"gate:evidence",severity:"error",item:t.id,message:`gate "${o.id}" needs evidence "${a}" on item "${t.id}"`,fix:`attach evidence { kind: "${a}" } before approving`});if(i.length)return {outcome:"fail",violations:i};let s=false;for(let a of o.requires){if(a==="human"){n!=="human"&&(s=true);continue}if(!B(e,o.id,a.capability).includes(n)){i.push({rule:"gate:capability",severity:"error",item:t.id,message:`"${n}" may not approve gate "${o.id}" (needs capability "${a.capability}" and canApprove "${o.id}")`,fix:`approve as one of: ${B(e,o.id,a.capability).join(", ")||"(no role qualifies; register one)"}`});continue}let f=H(e,t);if(f!==void 0&&f===n){let g=B(e,o.id,a.capability,n);i.push({rule:"conflict-of-interest",severity:"error",item:t.id,message:`role "${n}" did the work on "${t.id}" and may not approve it`,fix:`approve as a different role: ${g.join(", ")||"(register another approver)"}`});}}return i.length?{outcome:"fail",violations:i}:s?{outcome:"human"}:{outcome:"pass"}}function mt(e,t,o){let n=h(o),i=`p${e.events.filter(a=>a.type==="pending.raised").length+1}`,r={...t,id:i,raisedAt:n},s={...e,pending:[...e.pending,r]};return t.item&&b(s,t.item).status!=="awaiting_human"&&(s=P(s,t.item,{status:"awaiting_human"},"system",n)),w(s,"pending.raised","system",{id:i,kind:t.kind,item:t.item??null,gate:t.gate??null},n)}function kt(e,t,o,n,i,r,s){o!=="approve"&&o!=="reject"&&b$1("invalid-input",`decision must be "approve" or "reject" (got ${JSON.stringify(o)})`,"pass approve or reject");let a=e.pending.find(u=>u.id===t);a||b$1("unknown-pending",`no pending decision "${t}"`,`open decisions: ${e.pending.map(u=>u.id).join(", ")||"(none)"}`);let l=a.kind==="gate"&&a.item?b(e,a.item):void 0,f=l&&(e.stages.find(u=>a.gate!==void 0&&u.gate?.id===a.gate)?.gate??e.stages.find(u=>u.id===l.stage)?.gate);l&&f&&n!=="human"&&(f.requires.includes("human")?void 0:Se(e,l,f,n))?.outcome!=="pass"&&b$1("gate-unmet",`"${n}" may not decide gate "${f.id}" on "${l.id}"`,`decide as one of: human${f.requires.flatMap(m=>m==="human"?[]:B(e,f.id,m.capability)).map(m=>`, ${m}`).join("")}`,{items:[l.id],rule:"gate"});let g=h(r),p={...e,pending:e.pending.filter(u=>u.id!==t)};if(p=w(p,"pending.decided",n,{id:t,decision:o,note:i,item:a.item??null,gate:a.gate??null},g),l){let u=l.id,m=a.gate??f?.id??null;if(o==="approve"){let x=false;for(let I=e.events.length-1;I>=0;I--){let C=e.events[I];if(!(C.type!=="item.completed"||C.payload.id!==u)){x=C.payload.verdict==="needs-review";break}}p=re(p,u,n,x,g),p=w(p,"gate.passed",n,{item:u,gate:m},g);}else {let x=f?.onFail??{action:"block"};x.action==="return-to"?p=Q(P(p,u,{stage:x.stage,status:"todo"},n,g),u):p=ae(p,u,`gate "${m??"?"}" rejected: ${i||"no reason given"}`,n,n,g),p=w(p,"gate.failed",n,{item:u,gate:m,note:i},g);}}return s?.afterDecide&&(p=s.afterDecide(p,a,o,n,i,g)),p}var ht=Object.freeze({tokens:0,turns:0,wallclockMs:0});function yt(e,t){return {tokens:e.tokens+t.tokensIn+t.tokensOut,turns:e.turns+1,wallclockMs:e.wallclockMs+t.durationMs}}function le(e,t){let o={};return e.tokens!==void 0&&(o.tokens=Math.max(0,e.tokens-t.tokens)),e.turns!==void 0&&(o.turns=Math.max(0,e.turns-t.turns)),e.wallclockMs!==void 0&&(o.wallclockMs=Math.max(0,e.wallclockMs-t.wallclockMs)),o}function xt(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 de(e,t,o=2e4,n="per-weight"){let i=t??1,r=[];for(let l of e.accounting){if(l.estimate===true)continue;let f=l.tokensIn+l.tokensOut;if(n==="per-call"){r.push(f);continue}let g=e.items[l.item]?.weight;g===void 0||g<=0||r.push(f/g);}if(r.length===0)return n==="per-call"?o:o*i;r.sort((l,f)=>l-f);let s=Math.floor(r.length/2),a=r.length%2?r[s]:(r[s-1]+r[s])/2;return Math.round(n==="per-call"?a:a*i)}function z(e){return e.iterations.find(t=>t.endedAt===void 0)}function ce(e,t,o){if(t.role){let r=V(e,t.role);return r||b$1("unknown-role",`item "${t.id}" is assigned to unknown role "${t.role}"`,"editItem with an existing role id"),r}let n=o?o(t):void 0;if(n!==void 0){let r=V(e,n);return r||b$1("unknown-role",`the methodology picked unknown role "${n}" for item "${t.id}"`,`registered roles: ${Object.keys(e.roles).join(", ")||"(none)"}`,{items:[t.id]}),r}if(t.status==="review"){let r=H(e,t),s=q(e,"review"),l=s.find(f=>f.id!==r)??(s.length===1?s[0]:void 0);return l||b$1("missing-capability",`no role has capability "review" for item "${t.id}"`,"register a role with capability review",{items:[t.id]}),l}let i=q(e,"deliver")[0];return i||b$1("missing-capability",`no role has capability "deliver" for item "${t.id}"`,"register a role with capability deliver",{items:[t.id]}),i}function fe(e){let t={};for(let o of Object.values(e.roles))o.maxConcurrent!==void 0&&(t[o.resourceClass??o.id]=o.maxConcurrent);return t}function be(e,t,o,n){let i=new Set(e.map(r=>r.id));return e.map(r=>{let s=ce(t,r,n),a={id:r.id,data:{id:r.id},dependsOn:r.dependsOn.filter(f=>i.has(f)),resourceClass:s.resourceClass??s.id},l=o?o(r):r.priority;return l!==void 0&&(a.priority=l),r.weight!==void 0&&(a.weight=r.weight),r.deadline!==void 0&&(a.deadline=Date.parse(r.deadline)),a})}function jt(e,t,o={}){let n=h(o.now),i=t.candidates(e),r=i.filter(d=>d.dependsOn.every(k=>e.items[k]?.status==="done"||i.some(v=>v.id===k))),s=i.filter(d=>d.dependsOn.every(k=>e.items[k]?.status==="done"));if(r.length===0)return {state:e,dispatched:[],skipped:[],reason:z(e)?.closing?"budget-exhausted":"no-candidates"};let a=t.plannerOptions(e),l={schedulerMode:a.schedulerMode,resourceCaps:fe(e)};if(a.concurrencyCap!==void 0&&(l.concurrencyCap=a.concurrencyCap),a.fairnessPolicy!==void 0&&(l.fairnessPolicy=a.fairnessPolicy),a.maxDeferralRounds!==void 0&&(l.maxDeferralRounds=a.maxDeferralRounds),a.deadlineStrategy!==void 0&&(l.deadlineStrategy=a.deadlineStrategy),a.weightStrategy!==void 0&&(l.weightStrategy=a.weightStrategy),a.tieBreaker!==void 0){let d=a.tieBreaker;l.tieBreaker=(k,v)=>d(e.items[k.data.id],e.items[v.data.id]);}let f,g;try{let d=new ExFlow(l);for(let v of be(r,e,a.priorityOf,a.roleFor))d.addEntity(v);let k=d.resolveExecutionDetails();f=(k.plan.batches[0]??[]).map(v=>v.id),g=k.metrics;}catch(d){throw d instanceof ExFlowRuntimeError&&b$1("planner-error",`ex-flow refused the graph: [${d.code}] ${d.message}`,"fix the item graph (cycles, duplicate ids) with editItem; see diagnostics in the message",{items:r.map(k=>k.id)}),d}let p=f.map(d=>e.items[d]).filter(d=>d.dependsOn.every(k=>e.items[k]?.status==="done")),u=Object.values(e.items).filter(d=>d.status==="in_progress"),m=new Set(a.wipCounts??["in_progress"]),x=Object.values(e.items).filter(d=>m.has(d.status)),I={};for(let d of u){let k=d.role?V(e,d.role):void 0,v=k?k.resourceClass??k.id:"?";I[v]=(I[v]??0)+1;}let C=fe(e),S=z(e),E=S?le(S.budget,S.spent):{},T=E.tokens===void 0?void 0:Math.max(0,E.tokens-(a.reservedTokens??0)),W=S?Object.values(e.items).filter(d=>(d.iteration===S.id||S.committed.includes(d.id))&&d.status==="in_progress").length:0,F=E.turns===void 0?void 0:E.turns-W,pe=E.wallclockMs!==void 0&&E.wallclockMs<=0,me=a.estimateMode??"per-weight",ke=o.fallbackTokensPerWeight??a.fallbackTokensPerWeight,we=Math.min(o.max??1/0,a.concurrencyCap??1/0),j=[],$=[],y,N=e;for(let d of p){if(j.length>=we){y="wip-full";break}let k=typeof a.dispatchStage=="function"?a.dispatchStage(d):a.dispatchStage,v=d.status==="todo"&&k!==void 0?k:d.stage,D=M(e,v),X=d.type==="question"?[]:U(e,d,D.entryPolicy);if(X.length>0){$.push({id:d.id,reason:"entry-policy",detail:X.map(O=>O.message).join("; ")});continue}let Z=a.wipLimitOf?a.wipLimitOf(D,d):D.wipLimit;if(Z!==void 0&&x.filter(O=>O.stage===D.id&&O.id!==d.id).length+j.filter(O=>O.stage===D.id).length>=Z){y="wip-full",$.push({id:d.id,reason:"wip",detail:`stage "${D.id}" is at its WIP limit of ${Z}`});continue}let L=ce(e,d,a.roleFor),A=L.resourceClass??L.id;if(C[A]!==void 0&&(I[A]??0)>=C[A]){y="wip-full",$.push({id:d.id,reason:"resource-cap",detail:`resource class "${A}" is at its cap of ${C[A]}`});continue}if(F!==void 0&&F<=0){y="budget-exhausted",$.push({id:d.id,reason:"budget",detail:`turns budget spent: ${S.spent.turns} used + ${W+j.length} in flight of ${S.budget.turns}`});continue}if(pe){y="budget-exhausted",$.push({id:d.id,reason:"budget",detail:"wall-clock budget spent"});continue}if(T!==void 0){let O=de(e,d.weight,ke,me);if(O>T){y="budget-exhausted",$.push({id:d.id,reason:"budget",detail:`needs about ${O} tokens, ${T} left in the iteration`});continue}T-=O;}I[A]=(I[A]??0)+1,F!==void 0&&(F-=1),N=P(N,d.id,{stage:v,status:"in_progress"},L.id,n),N={...N,items:{...N.items,[d.id]:{...N.items[d.id],role:L.id}}},j.push(N.items[d.id]);}return y===void 0&&$.some(d=>d.reason==="entry-policy")&&(y="policy-blocked"),y===void 0&&j.length<s.length&&(y="wip-full"),j.length===0&&y===void 0&&(y="no-candidates"),N=w(N,"planner.resolved","planner",{dispatched:j.map(d=>d.id),reason:y??null,skipped:$,metrics:g},n),y?{state:N,dispatched:j,skipped:$,reason:y}:{state:N,dispatched:j,skipped:$}}function ue(e){return [{id:"separation-lost",severity:"warning",check(n,i){return i.type!=="init"&&i.type!=="role.register"?[]:te(n,e.requiredCapabilities).map(r=>({rule:"separation-lost",severity:"warning",message:`role "${r.id}" holds every required capability (${e.requiredCapabilities.join(", ")}); no separation of duties`,fix:"fine for a solo operator; otherwise split capabilities across roles"}))}},{id:"conflict-of-interest",severity:"error",check(n,i){if(i.type!=="complete")return [];let r=i.payload?.handoff;if(!r)return [];let s=r.verdict??"done";if(s!=="done"&&s!=="needs-review")return [];let a=n.items[r.item];if(!a)return [];let l=n.stages.find(g=>g.id===a.stage)?.gate;if(!l||!l.requires.some(g=>g!=="human"))return [];if(H(n,a)!==r.role)return [];let f=B(n,l.id,void 0,r.role);return [{rule:"conflict-of-interest",severity:"error",item:a.id,message:`role "${r.role}" authored "${a.id}" and may not pass gate "${l.id}" on it`,fix:`hand the gate to another approver: ${f.join(", ")||"(register one)"}`}]}}]}function Ne(e,t,o){let n=[];for(let i of [...ue(t),...t.rules])n.push(...i.check(e,o));return n}function ge(e,t,o,n){let i=Ne(e,t,o),r=i.filter(s=>s.severity==="error");return r.length&&b$1("rule-violation",`${o.type} violates ${r.map(s=>s.rule).join(", ")}: ${r.map(s=>s.message).join("; ")}`,r.map(s=>s.fix).join("; "),{rule:r[0].rule,items:r.map(s=>s.item).filter(s=>!!s)}),{state:n(e),warnings:i.filter(s=>s.severity==="warning")}}function _t(e){let t=e.methodology,o=t.validateConfig(e.config),n=e.stages??t.defaultStages(o),i=e.roles??t.defaultRoles(o),r=e.now!==void 0?{methodology:t.name,config:o,stages:n,roles:i,now:e.now}:{methodology:t.name,config:o,stages:n,roles:i},s=Y(r);return ee(s,t.requiredCapabilities,t.exclusiveCapabilities),ge(s,t,{type:"init",by:e.by??"system"},a=>a)}function Gt(e,t,o,n,i){(typeof o!="object"||o===null||Array.isArray(o)||Object.keys(o).length===0)&&b$1("invalid-input","config patch must be a non-empty object",'pass e.g. { "sprintBudget": { "tokens": 1500000 } } to exwf config set');let r=z(e);r&&b$1("invalid-input",`config cannot change while ${r.id} is open`,"close it first (exwf ceremony review or cancel; a waterfall phase closes at its gate), then run exwf config set");let s=(t.lockedConfigKeys??[]).filter(u=>Object.hasOwn(o,u));s.length&&b$1("invalid-input",`config key(s) ${s.join(", ")} cannot change after init`,t.name==="kanban"?"use the service-delivery-review cadence for columns and classes of service":"start a new workflow with exwf init to change them");let a=e.config??{},l=t.validateConfig({...a,...o}),f=Object.keys(o).filter(u=>!Object.hasOwn(l,u));f.length&&b$1("invalid-input",`unknown config key(s) ${f.join(", ")}`,`known keys: ${Object.keys(l).join(", ")}`);let g=Object.keys(o).filter(u=>JSON.stringify(a[u])!==JSON.stringify(l[u]));g.length===0&&b$1("no-op","config patch changes nothing","pass at least one key with a different value to exwf config set");let p=u=>Object.fromEntries(g.map(m=>[m,u[m]]));return ge(e,t,{type:"config.change",by:n,payload:{patch:o}},u=>{let m=h(i),x=w({...u,config:l},"config.changed",n,{changed:g,before:p(a),after:p(l)},m);return t.afterConfigChange&&(x=t.afterConfigChange(x,m)),x})}export{ot as A,U as B,st as C,xe as D,H as E,Se as F,mt as G,kt as H,ht as I,yt as J,le as K,xt as L,de as M,z as N,ce as O,fe as P,be as Q,jt as R,ue as S,Ne as T,ge as U,_t as V,Gt as W,h as a,Y as b,w as c,$e as d,V as e,G as f,q as g,B as h,Re as i,ee as j,te as k,he as l,Ee as m,M as n,oe as o,ne as p,ie as q,b as r,De as s,Ve as t,P as u,Q as v,re as w,ye as x,Qe as y,ae as z};//# sourceMappingURL=chunk-UUWDQVIJ.mjs.map
2
- //# sourceMappingURL=chunk-UUWDQVIJ.mjs.map