ex-workflow 1.0.1 → 1.1.1

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 (119) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +132 -21
  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-Cx63FX2K.d.ts → budget-Bd8KpGIr.d.ts} +1 -1
  8. package/dist/{budget-JyNKxP5N.d.cts → budget-CezCinPF.d.cts} +1 -1
  9. package/dist/chunk-6P3OKXSK.mjs +2 -0
  10. package/dist/chunk-6P3OKXSK.mjs.map +1 -0
  11. package/dist/{chunk-5PHK72VM.cjs → chunk-7FS6KWTG.cjs} +2 -2
  12. package/dist/{chunk-5PHK72VM.cjs.map → chunk-7FS6KWTG.cjs.map} +1 -1
  13. package/dist/chunk-7QQY4KJ2.mjs +2 -0
  14. package/dist/chunk-7QQY4KJ2.mjs.map +1 -0
  15. package/dist/chunk-AD4Z3JBL.cjs +2 -0
  16. package/dist/chunk-AD4Z3JBL.cjs.map +1 -0
  17. package/dist/chunk-ATCJ4IHP.mjs +2 -0
  18. package/dist/{chunk-Z2G7DGDF.mjs.map → chunk-ATCJ4IHP.mjs.map} +1 -1
  19. package/dist/chunk-C2IYMWE6.cjs +3 -0
  20. package/dist/chunk-C2IYMWE6.cjs.map +1 -0
  21. package/dist/chunk-EACZBAP3.cjs +2 -0
  22. package/dist/chunk-EACZBAP3.cjs.map +1 -0
  23. package/dist/chunk-EFCUM6DK.mjs +2 -0
  24. package/dist/chunk-EFCUM6DK.mjs.map +1 -0
  25. package/dist/chunk-EHBQBXWA.cjs +2 -0
  26. package/dist/{chunk-VXH2FAKV.cjs.map → chunk-EHBQBXWA.cjs.map} +1 -1
  27. package/dist/chunk-FTS75UIU.mjs +2 -0
  28. package/dist/{chunk-U3OXAO67.mjs.map → chunk-FTS75UIU.mjs.map} +1 -1
  29. package/dist/chunk-HCRVWMG4.cjs +2 -0
  30. package/dist/chunk-HCRVWMG4.cjs.map +1 -0
  31. package/dist/chunk-KLWZEXZU.mjs +3 -0
  32. package/dist/chunk-KLWZEXZU.mjs.map +1 -0
  33. package/dist/chunk-NDCQTRIV.mjs +2 -0
  34. package/dist/chunk-NDCQTRIV.mjs.map +1 -0
  35. package/dist/chunk-PMUGU5UJ.cjs +2 -0
  36. package/dist/chunk-PMUGU5UJ.cjs.map +1 -0
  37. package/dist/{chunk-7IG6EQI4.mjs → chunk-QZ6HD6DE.mjs} +3 -3
  38. package/dist/{chunk-7IG6EQI4.mjs.map → chunk-QZ6HD6DE.mjs.map} +1 -1
  39. package/dist/{chunk-HIHMBMB5.cjs → chunk-RL27372B.cjs} +2 -2
  40. package/dist/{chunk-HIHMBMB5.cjs.map → chunk-RL27372B.cjs.map} +1 -1
  41. package/dist/chunk-SP5MC7RR.mjs +2 -0
  42. package/dist/{chunk-QDMEM62U.mjs.map → chunk-SP5MC7RR.mjs.map} +1 -1
  43. package/dist/chunk-SVGTSPZF.cjs +2 -0
  44. package/dist/chunk-SVGTSPZF.cjs.map +1 -0
  45. package/dist/chunk-SYLO7FUL.mjs +2 -0
  46. package/dist/{chunk-3KFQPSRX.mjs.map → chunk-SYLO7FUL.mjs.map} +1 -1
  47. package/dist/chunk-T3V5UE34.mjs +2 -0
  48. package/dist/{chunk-UZQV73X7.mjs.map → chunk-T3V5UE34.mjs.map} +1 -1
  49. package/dist/{chunk-FKTCGQYB.cjs → chunk-TS66RAJR.cjs} +2 -2
  50. package/dist/{chunk-FKTCGQYB.cjs.map → chunk-TS66RAJR.cjs.map} +1 -1
  51. package/dist/{chunk-YRATJT7P.cjs → chunk-U23FUYPD.cjs} +4 -4
  52. package/dist/{chunk-YRATJT7P.cjs.map → chunk-U23FUYPD.cjs.map} +1 -1
  53. package/dist/chunk-U6GHFKKE.mjs +2 -0
  54. package/dist/chunk-U6GHFKKE.mjs.map +1 -0
  55. package/dist/{chunk-CYXVGHQM.cjs → chunk-YJQ5YJ7S.cjs} +2 -2
  56. package/dist/{chunk-CYXVGHQM.cjs.map → chunk-YJQ5YJ7S.cjs.map} +1 -1
  57. package/dist/cli/bin.cjs +1 -1
  58. package/dist/cli/bin.cjs.map +1 -1
  59. package/dist/cli/bin.mjs +1 -1
  60. package/dist/cli/bin.mjs.map +1 -1
  61. package/dist/cli/index.cjs +1 -1
  62. package/dist/cli/index.mjs +1 -1
  63. package/dist/experimentation/index.cjs +2 -0
  64. package/dist/experimentation/index.cjs.map +1 -0
  65. package/dist/experimentation/index.d.cts +28 -0
  66. package/dist/experimentation/index.d.ts +28 -0
  67. package/dist/experimentation/index.mjs +2 -0
  68. package/dist/experimentation/index.mjs.map +1 -0
  69. package/dist/index.cjs +1 -1
  70. package/dist/index.cjs.map +1 -1
  71. package/dist/index.d.cts +4 -4
  72. package/dist/index.d.ts +4 -4
  73. package/dist/index.mjs +1 -1
  74. package/dist/index.mjs.map +1 -1
  75. package/dist/investigation/index.cjs +2 -0
  76. package/dist/investigation/index.cjs.map +1 -0
  77. package/dist/investigation/index.d.cts +13 -0
  78. package/dist/investigation/index.d.ts +13 -0
  79. package/dist/investigation/index.mjs +2 -0
  80. package/dist/investigation/index.mjs.map +1 -0
  81. package/dist/kanban/index.cjs +1 -1
  82. package/dist/kanban/index.d.cts +1 -1
  83. package/dist/kanban/index.d.ts +1 -1
  84. package/dist/kanban/index.mjs +1 -1
  85. package/dist/schema/index.cjs +1 -1
  86. package/dist/schema/index.d.cts +3 -1
  87. package/dist/schema/index.d.ts +3 -1
  88. package/dist/schema/index.mjs +1 -1
  89. package/dist/scrum/index.cjs +1 -1
  90. package/dist/scrum/index.d.cts +3 -3
  91. package/dist/scrum/index.d.ts +3 -3
  92. package/dist/scrum/index.mjs +1 -1
  93. package/dist/types-BScHXlRx.d.cts +509 -0
  94. package/dist/types-BScHXlRx.d.ts +509 -0
  95. package/dist/types.d.cts +1 -388
  96. package/dist/types.d.ts +1 -388
  97. package/dist/waterfall/index.cjs +1 -1
  98. package/dist/waterfall/index.d.cts +1 -1
  99. package/dist/waterfall/index.d.ts +1 -1
  100. package/dist/waterfall/index.mjs +1 -1
  101. package/package.json +46 -21
  102. package/dist/chunk-3KFQPSRX.mjs +0 -2
  103. package/dist/chunk-5TXYMLBF.mjs +0 -3
  104. package/dist/chunk-5TXYMLBF.mjs.map +0 -1
  105. package/dist/chunk-MQWMQ4PD.mjs +0 -2
  106. package/dist/chunk-MQWMQ4PD.mjs.map +0 -1
  107. package/dist/chunk-QDMEM62U.mjs +0 -2
  108. package/dist/chunk-U3OXAO67.mjs +0 -2
  109. package/dist/chunk-UZQV73X7.mjs +0 -2
  110. package/dist/chunk-VXH2FAKV.cjs +0 -2
  111. package/dist/chunk-WOGK54HB.cjs +0 -3
  112. package/dist/chunk-WOGK54HB.cjs.map +0 -1
  113. package/dist/chunk-XMO2RCXB.cjs +0 -2
  114. package/dist/chunk-XMO2RCXB.cjs.map +0 -1
  115. package/dist/chunk-YBHHICTZ.mjs +0 -2
  116. package/dist/chunk-YBHHICTZ.mjs.map +0 -1
  117. package/dist/chunk-YJN4JEJU.cjs +0 -2
  118. package/dist/chunk-YJN4JEJU.cjs.map +0 -1
  119. package/dist/chunk-Z2G7DGDF.mjs +0 -2
@@ -1,6 +1,6 @@
1
- 'use strict';var chunkWOGK54HB_cjs=require('./chunk-WOGK54HB.cjs'),chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs'),promises=require('fs/promises'),crypto=require('crypto'),n=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var n__default=/*#__PURE__*/_interopDefault(n);var m=".workflow";function v(t){return n__default.default.join(t,m,"state.json")}async function y(t,e){let i=`${t}.tmp-${process.pid}-${crypto.randomBytes(4).toString("hex")}`;try{await promises.mkdir(n__default.default.dirname(t),{recursive:!0}),await promises.writeFile(i,e,"utf8"),await promises.rename(i,t);}catch(r){await promises.unlink(i).catch(()=>{}),chunkS3BXVHO7_cjs.b("invalid-input",`cannot write ${t}: ${r.message}`,"check the directory exists and is writable");}}async function T(t,e,i={}){let{retries:r=40,intervalMs:w=50,staleMs:u=6e4}=i,s=n__default.default.join(t,m,"state.lock");await promises.mkdir(n__default.default.dirname(s),{recursive:true});let d=false;for(let f=0;!d;f++)try{let a=await promises.open(s,"wx");await a.writeFile(`${process.pid} ${new Date().toISOString()}
1
+ 'use strict';var chunkC2IYMWE6_cjs=require('./chunk-C2IYMWE6.cjs'),chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs'),promises=require('fs/promises'),crypto=require('crypto'),n=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var n__default=/*#__PURE__*/_interopDefault(n);var m=".workflow";function v(t){return n__default.default.join(t,m,"state.json")}async function y(t,e){let i=`${t}.tmp-${process.pid}-${crypto.randomBytes(4).toString("hex")}`;try{await promises.mkdir(n__default.default.dirname(t),{recursive:!0}),await promises.writeFile(i,e,"utf8"),await promises.rename(i,t);}catch(r){await promises.unlink(i).catch(()=>{}),chunkS3BXVHO7_cjs.b("invalid-input",`cannot write ${t}: ${r.message}`,"check the directory exists and is writable");}}async function T(t,e,i={}){let{retries:r=40,intervalMs:w=50,staleMs:u=6e4}=i,s=n__default.default.join(t,m,"state.lock");await promises.mkdir(n__default.default.dirname(s),{recursive:true});let d=false;for(let f=0;!d;f++)try{let a=await promises.open(s,"wx");await a.writeFile(`${process.pid} ${new Date().toISOString()}
2
2
  `),await a.close(),d=!0;}catch(a){if(a.code!=="EEXIST")throw a;let o=await promises.stat(s).catch(()=>{});if(o&&Date.now()-o.mtimeMs>u){let l=await promises.stat(s).catch(()=>{});l&&l.ino===o.ino&&l.mtimeMs===o.mtimeMs&&await promises.unlink(s).catch(()=>{});continue}f>=r&&chunkS3BXVHO7_cjs.b("invalid-input","another exwf command holds .workflow/state.lock","retry, or delete the file if no exwf process is running"),await new Promise(l=>setTimeout(l,w));}try{return await e()}finally{await promises.unlink(s).catch(()=>{});}}async function B(t,e){let i=JSON.stringify(e,null,2)+`
3
- `;chunkWOGK54HB_cjs.b(chunkWOGK54HB_cjs.d,JSON.parse(i),v(t)),await y(v(t),i);}async function F(t){let e=v(t),i;try{i=await promises.readFile(e,"utf8");}catch{chunkS3BXVHO7_cjs.b("invalid-input",`no workflow state at ${e}`,"run `exwf init <scrum|kanban|waterfall> --config <file>` in this directory first");}let r;try{r=JSON.parse(i);}catch(f){chunkS3BXVHO7_cjs.b("invalid-input",`${e} is not valid JSON: ${f.message}`,"restore it from git or re-run exwf init");}(typeof r!="object"||r===null||Array.isArray(r))&&chunkS3BXVHO7_cjs.b("invalid-input",`${e} does not contain a workflow state object`,"restore it from git or re-run exwf init");let w=r;w.version!==1&&chunkS3BXVHO7_cjs.b("state-version",`${e} has schema version ${String(w.version)}; this ex-workflow reads version 1`,"upgrade ex-workflow, or run the migration this version documents in its changelog"),chunkWOGK54HB_cjs.b(chunkWOGK54HB_cjs.d,r,e);let u=n__default.default.join(t,m,"roles"),s=[];try{s=(await promises.readdir(u)).filter(f=>f.endsWith(".json"));}catch{}let d={...w.roles};for(let f of s){let a=n__default.default.join(u,f),o;try{o=JSON.parse(await promises.readFile(a,"utf8"));}catch(l){chunkS3BXVHO7_cjs.b("invalid-input",`role manifest ${a} is not valid JSON: ${l.message}`,"fix or delete that manifest");}chunkWOGK54HB_cjs.b(chunkWOGK54HB_cjs.e,o,`role manifest ${a}`),d[o.id]||(d[o.id]=o);}return {...w,roles:d}}function j(t,e){return n__default.default.resolve(e).startsWith(n__default.default.resolve(t,m)+n__default.default.sep)||chunkS3BXVHO7_cjs.b("invalid-input",`${e} resolves outside ${m}/`,"use a plain item id (letters, digits, - _ .)"),e}async function L(t,e){let i=j(t,n__default.default.join(t,m,"briefs",`${e.item.id}.json`));return await y(i,JSON.stringify(e,null,2)+`
3
+ `;chunkC2IYMWE6_cjs.b(chunkC2IYMWE6_cjs.d,JSON.parse(i),v(t)),await y(v(t),i);}async function F(t){let e=v(t),i;try{i=await promises.readFile(e,"utf8");}catch{chunkS3BXVHO7_cjs.b("invalid-input",`no workflow state at ${e}`,"run `exwf init <scrum|kanban|waterfall> --config <file>` in this directory first");}let r;try{r=JSON.parse(i);}catch(f){chunkS3BXVHO7_cjs.b("invalid-input",`${e} is not valid JSON: ${f.message}`,"restore it from git or re-run exwf init");}(typeof r!="object"||r===null||Array.isArray(r))&&chunkS3BXVHO7_cjs.b("invalid-input",`${e} does not contain a workflow state object`,"restore it from git or re-run exwf init");let w=r;w.version!==1&&chunkS3BXVHO7_cjs.b("state-version",`${e} has schema version ${String(w.version)}; this ex-workflow reads version 1`,"upgrade ex-workflow, or run the migration this version documents in its changelog"),chunkC2IYMWE6_cjs.b(chunkC2IYMWE6_cjs.d,r,e);let u=n__default.default.join(t,m,"roles"),s=[];try{s=(await promises.readdir(u)).filter(f=>f.endsWith(".json"));}catch{}let d={...w.roles};for(let f of s){let a=n__default.default.join(u,f),o;try{o=JSON.parse(await promises.readFile(a,"utf8"));}catch(l){chunkS3BXVHO7_cjs.b("invalid-input",`role manifest ${a} is not valid JSON: ${l.message}`,"fix or delete that manifest");}chunkC2IYMWE6_cjs.b(chunkC2IYMWE6_cjs.e,o,`role manifest ${a}`),d[o.id]||(d[o.id]=o);}return {...w,roles:d}}function j(t,e){return n__default.default.resolve(e).startsWith(n__default.default.resolve(t,m)+n__default.default.sep)||chunkS3BXVHO7_cjs.b("invalid-input",`${e} resolves outside ${m}/`,"use a plain item id (letters, digits, - _ .)"),e}async function L(t,e){let i=j(t,n__default.default.join(t,m,"briefs",`${e.item.id}.json`));return await y(i,JSON.stringify(e,null,2)+`
4
4
  `),i}async function A(t,e,i){let r=j(t,n__default.default.join(t,m,"handoffs",`${e.item}-${i}.json`));return await y(r,JSON.stringify(e,null,2)+`
5
- `),r}exports.a=m;exports.b=v;exports.c=T;exports.d=B;exports.e=F;exports.f=L;exports.g=A;//# sourceMappingURL=chunk-YRATJT7P.cjs.map
6
- //# sourceMappingURL=chunk-YRATJT7P.cjs.map
5
+ `),r}exports.a=m;exports.b=v;exports.c=T;exports.d=B;exports.e=F;exports.f=L;exports.g=A;//# sourceMappingURL=chunk-U23FUYPD.cjs.map
6
+ //# sourceMappingURL=chunk-U23FUYPD.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/adapters/file.ts"],"names":["WORKFLOW_DIR","statePath","root","path","writeAtomic","file","content","tmp","randomBytes","mkdir","writeFile","rename","e","unlink","fail","withStateLock","fn","opts","retries","intervalMs","staleMs","lock","held","attempt","fh","open","snap","stat","now","resolve","saveState","state","json","assertValid","workflowStateSchema","loadState","raw","readFile","parsed","rolesDir","manifests","readdir","roles","manifestPath","role","roleSchema","inWorkflowDir","saveBrief","brief","saveHandoff","handoff","seq"],"mappings":"gTAOO,IAAMA,EAAe,YAErB,SAASC,EAAUC,CAAAA,CAAsB,CAC9C,OAAOC,kBAAAA,CAAK,KAAKD,CAAAA,CAAMF,CAAAA,CAAc,YAAY,CACnD,CAEA,eAAeI,CAAAA,CAAYC,CAAAA,CAAcC,CAAAA,CAAgC,CACvE,IAAMC,CAAAA,CAAM,CAAA,EAAGF,CAAI,CAAA,KAAA,EAAQ,OAAA,CAAQ,GAAG,CAAA,CAAA,EAAIG,kBAAAA,CAAY,CAAC,CAAA,CAAE,SAAS,KAAK,CAAC,GACxE,GAAI,CACF,MAAMC,cAAAA,CAAMN,kBAAAA,CAAK,OAAA,CAAQE,CAAI,EAAG,CAAE,SAAA,CAAW,EAAK,CAAC,CAAA,CACnD,MAAMK,kBAAAA,CAAUH,CAAAA,CAAKD,EAAS,MAAM,CAAA,CACpC,MAAMK,eAAAA,CAAOJ,CAAAA,CAAKF,CAAI,EACxB,CAAA,MAASO,EAAG,CAEV,MAAMC,eAAAA,CAAON,CAAG,EAAE,KAAA,CAAM,IAAG,EAAY,CAAA,CACvCO,mBAAAA,CACE,gBACA,CAAA,aAAA,EAAgBT,CAAI,CAAA,EAAA,EAAMO,CA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ACAC,kBAAAA,CAAK,KAAKD,CAAAA,CAAMF,CAAAA,CAAc,UAAA,CAAY,CAAA,EAAGkD,CAAAA,CAAQ,IAAI,CAAA,CAAA,EAAIC,CAAG,OAAO,CACzE,CAAA,CACA,OAAA,MAAM/C,CAAAA,CAAYC,EAAM,IAAA,CAAK,SAAA,CAAU6C,CAAAA,CAAS,IAAA,CAAM,CAAC,CAAA,CAAI;AAAA,CAAI,EACxD7C,CACT","file":"chunk-YRATJT7P.cjs","sourcesContent":["import { mkdir, open, readFile, readdir, rename, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { randomBytes } from \"node:crypto\";\nimport path from \"node:path\";\nimport { fail } from \"../errors.ts\";\nimport { assertValid, roleSchema, workflowStateSchema } from \"../schema/index.ts\";\nimport type { Brief, Handoff, Role, WorkflowState } from \"../types.ts\";\n\nexport const WORKFLOW_DIR = \".workflow\";\n\nexport function statePath(root: string): string {\n return path.join(root, WORKFLOW_DIR, \"state.json\");\n}\n\nasync function writeAtomic(file: string, content: string): Promise<void> {\n const tmp = `${file}.tmp-${process.pid}-${randomBytes(4).toString(\"hex\")}`;\n try {\n await mkdir(path.dirname(file), { recursive: true });\n await writeFile(tmp, content, \"utf8\");\n await rename(tmp, file);\n } catch (e) {\n // best effort: remove the temp file if it was created; ignore failure\n await unlink(tmp).catch(() => undefined);\n fail(\n \"invalid-input\",\n `cannot write ${file}: ${(e as Error).message}`,\n \"check the directory exists and is writable\",\n );\n }\n}\n\nexport interface LockOptions {\n retries?: number;\n intervalMs?: number;\n staleMs?: number;\n}\n\n/** Run `fn` while holding `.workflow/state.lock`, so concurrent exwf commands cannot lose each other's updates. */\nexport async function withStateLock<T>(\n root: string,\n fn: () => Promise<T>,\n opts: LockOptions = {},\n): Promise<T> {\n const { retries = 40, intervalMs = 50, staleMs = 60_000 } = opts;\n const lock = path.join(root, WORKFLOW_DIR, \"state.lock\");\n await mkdir(path.dirname(lock), { recursive: true });\n let held = false;\n for (let attempt = 0; !held; attempt++) {\n try {\n const fh = await open(lock, \"wx\");\n await fh.writeFile(`${process.pid} ${new Date().toISOString()}\\n`);\n await fh.close();\n held = true;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== \"EEXIST\") throw e;\n const snap = await stat(lock).catch(() => undefined);\n if (snap && Date.now() - snap.mtimeMs > staleMs) {\n // re-stat just before unlink: if another recoverer already replaced the lock, leave it alone\n const now = await stat(lock).catch(() => undefined);\n if (now && now.ino === snap.ino && now.mtimeMs === snap.mtimeMs)\n await unlink(lock).catch(() => undefined);\n continue;\n }\n if (attempt >= retries)\n fail(\n \"invalid-input\",\n \"another exwf command holds .workflow/state.lock\",\n \"retry, or delete the file if no exwf process is running\",\n );\n await new Promise((resolve) => setTimeout(resolve, intervalMs));\n }\n }\n try {\n return await fn();\n } finally {\n await unlink(lock).catch(() => undefined);\n }\n}\n\nexport async function saveState(root: string, state: WorkflowState): Promise<void> {\n const json = JSON.stringify(state, null, 2) + \"\\n\";\n assertValid(workflowStateSchema, JSON.parse(json), statePath(root));\n await writeAtomic(statePath(root), json);\n}\n\nexport async function loadState(root: string): Promise<WorkflowState> {\n const file = statePath(root);\n let raw: string;\n try {\n raw = await readFile(file, \"utf8\");\n } catch {\n fail(\n \"invalid-input\",\n `no workflow state at ${file}`,\n \"run `exwf init <scrum|kanban|waterfall> --config <file>` in this directory first\",\n );\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (e) {\n fail(\n \"invalid-input\",\n `${file} is not valid JSON: ${(e as Error).message}`,\n \"restore it from git or re-run exwf init\",\n );\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n fail(\n \"invalid-input\",\n `${file} does not contain a workflow state object`,\n \"restore it from git or re-run exwf init\",\n );\n }\n const state = parsed as WorkflowState;\n if (state.version !== 1)\n fail(\n \"state-version\",\n `${file} has schema version ${String(state.version)}; this ex-workflow reads version 1`,\n \"upgrade ex-workflow, or run the migration this version documents in its changelog\",\n );\n assertValid(workflowStateSchema, parsed, file);\n const rolesDir = path.join(root, WORKFLOW_DIR, \"roles\");\n let manifests: string[] = [];\n try {\n manifests = (await readdir(rolesDir)).filter((f) => f.endsWith(\".json\"));\n } catch {\n /* no extra roles */\n }\n const roles = { ...state.roles };\n for (const f of manifests) {\n const manifestPath = path.join(rolesDir, f);\n let role: Role;\n try {\n role = JSON.parse(await readFile(manifestPath, \"utf8\")) as Role;\n } catch (e) {\n fail(\n \"invalid-input\",\n `role manifest ${manifestPath} is not valid JSON: ${(e as Error).message}`,\n \"fix or delete that manifest\",\n );\n }\n assertValid(roleSchema, role, `role manifest ${manifestPath}`);\n if (!roles[role.id]) roles[role.id] = role;\n }\n return { ...state, roles };\n}\n\nfunction inWorkflowDir(root: string, file: string): string {\n if (!path.resolve(file).startsWith(path.resolve(root, WORKFLOW_DIR) + path.sep))\n fail(\n \"invalid-input\",\n `${file} resolves outside ${WORKFLOW_DIR}/`,\n \"use a plain item id (letters, digits, - _ .)\",\n );\n return file;\n}\n\nexport async function saveBrief(root: string, brief: Brief): Promise<string> {\n const file = inWorkflowDir(\n root,\n path.join(root, WORKFLOW_DIR, \"briefs\", `${brief.item.id}.json`),\n );\n await writeAtomic(file, JSON.stringify(brief, null, 2) + \"\\n\");\n return file;\n}\n\nexport async function saveHandoff(root: string, handoff: Handoff, seq: number): Promise<string> {\n const file = inWorkflowDir(\n root,\n path.join(root, WORKFLOW_DIR, \"handoffs\", `${handoff.item}-${seq}.json`),\n );\n await writeAtomic(file, JSON.stringify(handoff, null, 2) + \"\\n\");\n return file;\n}\n"]}
1
+ {"version":3,"sources":["../src/adapters/file.ts"],"names":["WORKFLOW_DIR","statePath","root","path","writeAtomic","file","content","tmp","randomBytes","mkdir","writeFile","rename","e","unlink","fail","withStateLock","fn","opts","retries","intervalMs","staleMs","lock","held","attempt","fh","open","snap","stat","now","resolve","saveState","state","json","assertValid","workflowStateSchema","loadState","raw","readFile","parsed","rolesDir","manifests","readdir","roles","manifestPath","role","roleSchema","inWorkflowD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AI,CAAA,CAAE,UAAA,CAAWF,kBAAAA,CAAK,OAAA,CAAQD,CAAAA,CAAMF,CAAY,CAAA,CAAIG,kBAAAA,CAAK,GAAG,CAAA,EAC5EW,mBAAAA,CACE,eAAA,CACA,CAAA,EAAGT,CAAI,CAAA,kBAAA,EAAqBL,CAAY,CAAA,CAAA,CAAA,CACxC,8CACF,CAAA,CACKK,CACT,CAEA,eAAsB0C,CAAAA,CAAU7C,CAAAA,CAAc8C,CAAAA,CAA+B,CAC3E,IAAM3C,CAAAA,CAAOyC,CAAAA,CACX5C,CAAAA,CACAC,kBAAAA,CAAK,IAAA,CAAKD,EAAMF,CAAAA,CAAc,QAAA,CAAU,CAAA,EAAGgD,CAAAA,CAAM,IAAA,CAAK,EAAE,CAAA,KAAA,CAAO,CACjE,CAAA,CACA,OAAA,MAAM5C,CAAAA,CAAYC,CAAAA,CAAM,IAAA,CAAK,SAAA,CAAU2C,CAAAA,CAAO,IAAA,CAAM,CAAC,CAAA,CAAI;AAAA,CAAI,CAAA,CACtD3C,CACT,CAEA,eAAsB4C,EAAY/C,CAAAA,CAAcgD,CAAAA,CAAkBC,CAAAA,CAA8B,CAC9F,IAAM9C,CAAAA,CAAOyC,CAAAA,CACX5C,CAAAA,CACAC,kBAAAA,CAAK,KAAKD,CAAAA,CAAMF,CAAAA,CAAc,UAAA,CAAY,CAAA,EAAGkD,CAAAA,CAAQ,IAAI,CAAA,CAAA,EAAIC,CAAG,OAAO,CACzE,CAAA,CACA,OAAA,MAAM/C,CAAAA,CAAYC,EAAM,IAAA,CAAK,SAAA,CAAU6C,CAAAA,CAAS,IAAA,CAAM,CAAC,CAAA,CAAI;AAAA,CAAI,EACxD7C,CACT","file":"chunk-U23FUYPD.cjs","sourcesContent":["import { mkdir, open, readFile, readdir, rename, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { randomBytes } from \"node:crypto\";\nimport path from \"node:path\";\nimport { fail } from \"../errors.ts\";\nimport { assertValid, roleSchema, workflowStateSchema } from \"../schema/index.ts\";\nimport type { Brief, Handoff, Role, WorkflowState } from \"../types.ts\";\n\nexport const WORKFLOW_DIR = \".workflow\";\n\nexport function statePath(root: string): string {\n return path.join(root, WORKFLOW_DIR, \"state.json\");\n}\n\nasync function writeAtomic(file: string, content: string): Promise<void> {\n const tmp = `${file}.tmp-${process.pid}-${randomBytes(4).toString(\"hex\")}`;\n try {\n await mkdir(path.dirname(file), { recursive: true });\n await writeFile(tmp, content, \"utf8\");\n await rename(tmp, file);\n } catch (e) {\n // best effort: remove the temp file if it was created; ignore failure\n await unlink(tmp).catch(() => undefined);\n fail(\n \"invalid-input\",\n `cannot write ${file}: ${(e as Error).message}`,\n \"check the directory exists and is writable\",\n );\n }\n}\n\nexport interface LockOptions {\n retries?: number;\n intervalMs?: number;\n staleMs?: number;\n}\n\n/** Run `fn` while holding `.workflow/state.lock`, so concurrent exwf commands cannot lose each other's updates. */\nexport async function withStateLock<T>(\n root: string,\n fn: () => Promise<T>,\n opts: LockOptions = {},\n): Promise<T> {\n const { retries = 40, intervalMs = 50, staleMs = 60_000 } = opts;\n const lock = path.join(root, WORKFLOW_DIR, \"state.lock\");\n await mkdir(path.dirname(lock), { recursive: true });\n let held = false;\n for (let attempt = 0; !held; attempt++) {\n try {\n const fh = await open(lock, \"wx\");\n await fh.writeFile(`${process.pid} ${new Date().toISOString()}\\n`);\n await fh.close();\n held = true;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== \"EEXIST\") throw e;\n const snap = await stat(lock).catch(() => undefined);\n if (snap && Date.now() - snap.mtimeMs > staleMs) {\n // re-stat just before unlink: if another recoverer already replaced the lock, leave it alone\n const now = await stat(lock).catch(() => undefined);\n if (now && now.ino === snap.ino && now.mtimeMs === snap.mtimeMs)\n await unlink(lock).catch(() => undefined);\n continue;\n }\n if (attempt >= retries)\n fail(\n \"invalid-input\",\n \"another exwf command holds .workflow/state.lock\",\n \"retry, or delete the file if no exwf process is running\",\n );\n await new Promise((resolve) => setTimeout(resolve, intervalMs));\n }\n }\n try {\n return await fn();\n } finally {\n await unlink(lock).catch(() => undefined);\n }\n}\n\nexport async function saveState(root: string, state: WorkflowState): Promise<void> {\n const json = JSON.stringify(state, null, 2) + \"\\n\";\n assertValid(workflowStateSchema, JSON.parse(json), statePath(root));\n await writeAtomic(statePath(root), json);\n}\n\nexport async function loadState(root: string): Promise<WorkflowState> {\n const file = statePath(root);\n let raw: string;\n try {\n raw = await readFile(file, \"utf8\");\n } catch {\n fail(\n \"invalid-input\",\n `no workflow state at ${file}`,\n \"run `exwf init <scrum|kanban|waterfall> --config <file>` in this directory first\",\n );\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (e) {\n fail(\n \"invalid-input\",\n `${file} is not valid JSON: ${(e as Error).message}`,\n \"restore it from git or re-run exwf init\",\n );\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n fail(\n \"invalid-input\",\n `${file} does not contain a workflow state object`,\n \"restore it from git or re-run exwf init\",\n );\n }\n const state = parsed as WorkflowState;\n if (state.version !== 1)\n fail(\n \"state-version\",\n `${file} has schema version ${String(state.version)}; this ex-workflow reads version 1`,\n \"upgrade ex-workflow, or run the migration this version documents in its changelog\",\n );\n assertValid(workflowStateSchema, parsed, file);\n const rolesDir = path.join(root, WORKFLOW_DIR, \"roles\");\n let manifests: string[] = [];\n try {\n manifests = (await readdir(rolesDir)).filter((f) => f.endsWith(\".json\"));\n } catch {\n /* no extra roles */\n }\n const roles = { ...state.roles };\n for (const f of manifests) {\n const manifestPath = path.join(rolesDir, f);\n let role: Role;\n try {\n role = JSON.parse(await readFile(manifestPath, \"utf8\")) as Role;\n } catch (e) {\n fail(\n \"invalid-input\",\n `role manifest ${manifestPath} is not valid JSON: ${(e as Error).message}`,\n \"fix or delete that manifest\",\n );\n }\n assertValid(roleSchema, role, `role manifest ${manifestPath}`);\n if (!roles[role.id]) roles[role.id] = role;\n }\n return { ...state, roles };\n}\n\nfunction inWorkflowDir(root: string, file: string): string {\n if (!path.resolve(file).startsWith(path.resolve(root, WORKFLOW_DIR) + path.sep))\n fail(\n \"invalid-input\",\n `${file} resolves outside ${WORKFLOW_DIR}/`,\n \"use a plain item id (letters, digits, - _ .)\",\n );\n return file;\n}\n\nexport async function saveBrief(root: string, brief: Brief): Promise<string> {\n const file = inWorkflowDir(\n root,\n path.join(root, WORKFLOW_DIR, \"briefs\", `${brief.item.id}.json`),\n );\n await writeAtomic(file, JSON.stringify(brief, null, 2) + \"\\n\");\n return file;\n}\n\nexport async function saveHandoff(root: string, handoff: Handoff, seq: number): Promise<string> {\n const file = inWorkflowDir(\n root,\n path.join(root, WORKFLOW_DIR, \"handoffs\", `${handoff.item}-${seq}.json`),\n );\n await writeAtomic(file, JSON.stringify(handoff, null, 2) + \"\\n\");\n return file;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {W,c,a,e,O,u,y as y$1,x as x$1,R as R$1,E,s}from'./chunk-6P3OKXSK.mjs';import {b as b$1,c as c$1}from'./chunk-2FRRD6A3.mjs';var y=["tokens","turns","wallclockMs"];function w(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 x(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 ee(e,t){(!w(e)||!y.some(a=>e[a]!==void 0)||Object.keys(e).some(a=>!y.includes(a)))&&r(`${t} needs tokens, turns or wallclockMs limits`);let n={};for(let a of y){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{w(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:ee(e.candidateBudget??{turns:10},"candidateBudget"),totalBudget:ee(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 v(e){return (e.methodology!=="experimentation"||!e.experimentation)&&r("freeze an experimentation workflow first"),e.experimentation}function te(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 ne(e,t,n){return e.events.reduce((a,i)=>{if(i.type!=="item.completed"||!w(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(e.experimentation?.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 q(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 S(e,t){return q(t.spent,ne(e,t.item,t.author))}function D(e,t){if(!e.experimentation)return e;let n=C(e),a$1=["stopped","integrated"].includes(e.experimentation.status);return {...e,iterations:e.iterations.map(i=>i.id==="experiment"?{...i,budget:{...b(e.config).totalBudget},spent:n,...a$1?{endedAt:i.endedAt??a(t),outcome:i.outcome??(e.experimentation.status==="integrated"?"completed":"cancelled")}:{}}:i)}}function C(e,t=v(e)){let n=q(t.overhead,ne(e));return Object.values(t.candidates).reduce((a,i)=>{let o=S(e,i);return {tokens:a.tokens+o.tokens,turns:a.turns+o.turns,wallclockMs:a.wallclockMs+o.wallclockMs}},n)}function K(e){return Object.values(e.experimentation?.candidates??{}).filter(t=>t.status==="running"||e.items[t.item]?.status==="in_progress").length}function J(e){return Object.values(e.experimentation?.candidates??{}).reduce((t,n)=>{let a=e.items[n.item];return t+(a?.status==="in_progress"?O(e,a.weight,1):0)},0)}function ue(e){let t=b(e.config).totalBudget.tokens;if(t!==void 0)return Math.max(0,t-C(e).tokens-J(e))}function V(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 G(e,t){let n=b(e.config),a=S(e,t);return y.some(i=>n.candidateBudget[i]!==void 0&&a[i]>=n.candidateBudget[i])}function z(e){if(!e.experimentation)return false;let t=b(e.config),n=C(e);return y.some(a=>t.totalBudget[a]!==void 0&&n[a]>=t.totalBudget[a])}function A(e,t){let n=m(t.candidate,"candidate");return Object.hasOwn(e.candidates,n)||r(`unknown candidate ${n}`),e.candidates[n]}function P(e,t){return typeof e[t]!="boolean"&&r(`${t} must be boolean`),e[t]}function T(e){w(e.spent)||r("spent must contain nonnegative tokens, turns and wallclockMs");let t={};for(let n of y){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 M(e,t){return {...e,candidates:{...e.candidates,[t.id]:t}}}function H(e,t){let n=T(t);return {...e,overhead:{tokens:e.overhead.tokens+n.tokens,turns:e.overhead.turns+n.turns,wallclockMs:e.overhead.wallclockMs+n.wallclockMs}}}function N(e,t,n){return x$1(e,t.item,{stage:"done",status:"dropped"},n.by,n.now)}function B(e){e.status!=="running"&&r("experiment is not running");}function R(e){return ["validated","failed","timed-out","cancelled"].includes(e.status)}function F(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=>F(a,t)):Object.values(e).every(a=>a===void 0||F(a,t));return t.delete(e),n}function k(e,t,n){return (a$1,i)=>((!w(i)||!F(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"),te(a$1,i.by,t),W(a$1,ie(),{type:`ceremony.${e}`,by:i.by,payload:i},o=>c(D(n(o,i),i.now),`experimentation.${e}`,i.by,structuredClone(i),a(i.now))))}function ae(){return {freeze:k("frozen","facilitate",(e,t)=>{(e.methodology!=="experimentation"||e.experimentation)&&r("freeze may run only once in experimentation");let n=b(e.config),a$1=x(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){w(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");te(e,f,"deliver");let u$1=u(e,l);u$1.role&&u$1.role!==f&&r("candidate item role must match frozen author"),(s.has(l)||u$1.stage!=="candidate"||u$1.status!=="todo"||u$1.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 {...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:[]}],experimentation:{status:"running",baseSha:a$1,harness:i,candidates:o,released:[],overhead:{tokens:0,turns:0,wallclockMs:0}}}}),provision:k("provisioned","manage-flow",(e,t)=>{let n=v(e);B(n),z(e)&&r("total experiment budget exhausted");let a=A(n,t);a.status!=="pending"&&r("candidate already provisioned");let i=m(t.workspace,"workspace");return (x(t.baseSha,"baseSha")!==n.baseSha||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=M(n,{...a,workspace:i,status:"ready"}),{...e,experimentation:n}}),start:k("started","deliver",(e$1,t)=>{let n=v(e$1);B(n);let a=A(n,t);(a.status!=="ready"||a.author!==t.by)&&r("only the candidate author may start a ready candidate"),z(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"),V(e$1,a)||r("candidate author assignment or delivery capability changed");let s$1=C(e$1);i.totalBudget.turns!==void 0&&s$1.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=R$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=u(e$1,a.item),h=ue(e$1);h!==void 0&&O(e$1,u$1.weight,1)>h&&r("total experiment token budget reserved or insufficient"),u$1.status!=="todo"&&r("candidate item is already dispatched"),E(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"),G(e$1,a)&&r("candidate budget exhausted");let g=x$1(e$1,a.item,{stage:"building",status:"in_progress"},t.by,t.now);return g=s(g,a.item,p=>({...p,role:t.by})),{...g,experimentation:M(n,{...a,status:"running"})}}),submit:k("submitted","deliver",(e,t)=>{let n=v(e);B(n);let a=A(n,t),i=u(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=x(t.sha);(t.workspace!==a.workspace||t.harness!==n.harness||x(t.baseSha,"baseSha")!==n.baseSha)&&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=T(t),c=m(t.command,"command"),d=m(t.log,"log"),l=b(e.config),f=S(e,{...a,spent:s}),u$1=y.some(p=>l.candidateBudget[p]!==void 0&&f[p]>l.candidateBudget[p]),h={...a,status:u$1?"timed-out":"submitted",sha:o,score:t.score,spent:f,command:c,log:d};u$1&&(h.reason="candidate budget exceeded");let g={...e,experimentation:M(n,h)};return g=y$1(g,a.item,{kind:"candidate-sha",ref:o,by:t.by},t.now),g=y$1(g,a.item,{kind:"benchmark-result",ref:JSON.stringify({score:t.score,harness:n.harness,sha:o}),by:t.by},t.now),u$1?N(g,h,t):g}),terminate:k("terminated","manage-flow",(e,t)=>{let n=v(e);B(n);let a=A(n,t);R(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=T(t),s=m(t.log,"log");return N({...e,experimentation:M(n,{...a,status:t.status,reason:i,spent:q(S(e,a),S(e,{...a,spent:o})),terminalLog:s})},a,t)}),validate:k("validated","verify",(e,t)=>{let n=v(e);B(n);let a=A(n,t);a.status!=="submitted"&&r("validate an unvalidated submitted candidate"),t.by===a.author&&r("candidate author cannot independently validate"),!e.events.some(h=>h.type==="experimentation.started"&&w(h.payload)&&h.payload.candidate===a.id)&&u(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=x(t.sha),s=m(t.harness,"harness");(o!==a.sha||s!==n.harness)&&r("validation must match exact submitted SHA and frozen harness");let c=P(t,"passed"),d=P(t,"reproducible"),l=m(t.evidence,"evidence"),f={sha:o,harness:s,by:t.by,passed:c,reproducible:d,evidence:l},u$1={...e,experimentation:M(H(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=x$1(u$1,a.item,{stage:"done",status:c&&d?"done":"dropped"},t.by,t.now),u$1}),compare:k("compared","facilitate",(e,t)=>{let n=v(e);B(n);let a=Object.values(n.candidates);a.every(R)||r("comparison requires all candidates terminal and submissions independently validated");let i=b(e.config),o=C(e,n);if(y.some(d=>i.totalBudget[d]!==void 0&&o[d]>i.totalBudget[d]))return {...e,experimentation:{...n,status:"stopped",reason:"total budget exceeded"}};let s=a.filter(d=>{let l=S(e,d);return d.status==="validated"&&d.validation?.passed&&d.validation.reproducible&&d.validation.sha===d.sha&&d.validation.harness===n.harness&&!y.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 {...e,experimentation:c?{...n,status:"selected",selected:c.id}:{...n,status:"stopped",reason:"no eligible candidate"}}}),integrate:k("integration-recorded","control-change",(e,t)=>{let n=v(e);(!["selected","integrating"].includes(n.status)||!n.selected)&&r("compare and select before integration"),z(e)&&r("total budget exhausted before integration");let a=n.candidates[n.selected],i=x(t.selectedSha,"selectedSha");(i!==a.sha||a.validation?.sha!==i)&&r("integration must promote the exact selected and validated SHA");let o=x(t.targetSha,"targetSha"),s=x(t.integrationSha,"integrationSha");return n.integration?.sha===s&&n.integration.targetSha===o&&r("integration already recorded"),{...e,experimentation:{...H(n,t),status:"integrating",integration:{selectedSha:i,targetSha:o,sha:s,by:t.by}}}}),"validate-integration":k("integration-validated","verify",(e,t)=>{let n=v(e);(n.status!=="integrating"||!n.integration||!n.selected)&&r("record integration before fresh validation");let a=n.integration,i=n.candidates[n.selected];(t.by===a.by||t.by===i.author)&&r("integration validation must be independent of candidate author and integrator");let o=x(t.sha),s=x(t.targetSha,"targetSha"),c=m(t.harness,"harness");(o!==a.sha||s!==a.targetSha||c!==n.harness)&&r("fresh validation must match integration SHA, current target SHA and harness");let d=P(t,"passed"),l=m(t.evidence,"evidence"),f=H(n,t),u=b(e.config),h=C(e,f),g=y.some(p=>u.totalBudget[p]!==void 0&&h[p]>u.totalBudget[p]);return {...e,experimentation:{...f,status:d&&!g?"integrated":"stopped",...d&&!g?{}:{reason:g?"total budget exceeded":"integration validation failed"},integration:{...a,validation:{by:t.by,sha:o,harness:c,evidence:l,passed:d}}}}}),stop:k("stopped","manage-flow",(e,t)=>{let n=v(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,R(s)?s:{...s,status:"cancelled",reason:a}])),o=e;for(let s of Object.values(n.candidates))R(s)||(o=N(o,s,t));return {...o,experimentation:{...H(n,t),status:"stopped",reason:a,candidates:i}}}),cleanup:k("cleanup-recorded","manage-flow",(e,t)=>{let n=v(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"),{...e,experimentation:{...n,released:[...n.released,...t.workspaces]}}})}}function oe(e){let t=e.experimentation,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?{...C(e)}:{tokens:0,turns:0,wallclockMs:0},candidateTokens:Object.fromEntries(n.map(a=>[a.id,S(e,a).tokens]))}}function re(e){let t=e.experimentation;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 se(){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 de(){return [{id:"experimentation-lifecycle",severity:"error",check(e,t){let n=[],a=e.experimentation,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 ce(){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 ie(){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:ce,defaultRoles:se,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-K(e)),fallbackTokensPerWeight:1,reservedTokens:J(e),roleFor(n){return Object.values(e.experimentation?.candidates??{}).find(a=>a.item===n.id)?.author}}},candidates(e){let t=e.experimentation;if(!t||t.status!=="running")return [];let n=b(e.config);return z(e)||K(e)>=n.concurrencyCap?[]:Object.values(t.candidates).filter(a=>a.status==="ready"&&V(e,a)&&e.items[a.item]?.status==="todo"&&!G(e,a)).map(a=>e.items[a.item])},afterComplete(e,t,n){return D(e,n)},invariants(e,t){let n=e.experimentation,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:ae(),rules:de(),metrics:oe,report:re,humanDefaults:{gates:"none"},lockedConfigKeys:["objective","direction","tieBreak","concurrencyCap","maxCandidates","candidateBudget","totalBudget"]}}export{b as a,ae as b,oe as c,re as d,se as e,de as f,ce as g,ie as h};//# sourceMappingURL=chunk-U6GHFKKE.mjs.map
2
+ //# sourceMappingURL=chunk-U6GHFKKE.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/experimentation/config.ts","../src/experimentation/ceremonies.ts","../src/experimentation/metrics.ts","../src/experimentation/roles.ts","../src/experimentation/rules.ts","../src/experimentation/stages.ts","../src/experimentation/index.ts"],"names":["dimensions","object","value","invalid","message","fail","text","label","sha","s","budget","k","out","n","validateExperimentationConfig","raw","known","objective","direction","tieBreak","concurrencyCap","maxCandidates","key","error","experimentOf","authorize","by","capability","roleOf","completedUsage","item","author","sum","event","p","c","maximum","a","b","effectiveSpent","synchronizeBudget","now","usage","totalSpent","closed","it","nowOf","e","overhead","v","runningCount","reservedTokens","estimateTokens","unreservedTokens","limit","assignedAuthor","work","candidateExhausted","cfg","used","exhausted","candidate","i","id","bool","spent","put","charge","cost","closeItem","moveItem","active","done","jsonSafe","seen","valid","reduce","name","fn","applyAction","experimentation","current","appendEvent","experimentationCeremonies","baseSha","harness","candidates","items","assertId","getItem","workspace","x","running","role","cls","cap","resourceCapsFor","occupied","w","tokenCapacity","assertPolicies","st","next","patchItem","commit","command","log","measured","over","updated","addEvidence","reason","passed","reproducible","evidence","validation","_i","all","eligible","selected","selectedSha","targetSha","integrationSha","integration","charged","experimentationMetrics","experimentationReport","experimentationRoles","experimentationRules","state","action","errors","payload","experimentationStages","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aACF,CACF,CACF","file":"chunk-U6GHFKKE.mjs","sourcesContent":["import { fail } from \"../errors.ts\";\nimport type { Budget } from \"../types.ts\";\nexport interface ExperimentationConfig {\n objective: string;\n direction: \"minimize\" | \"maximize\";\n tieBreak: \"candidate-id\";\n concurrencyCap: number;\n maxCandidates: number;\n candidateBudget: Budget;\n totalBudget: Budget;\n}\nexport const dimensions = [\"tokens\", \"turns\", \"wallclockMs\"] as const;\nexport function object(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nexport function invalid(message: string): never {\n return fail(\"invalid-input\", message, \"supply valid experimentation ceremony input\");\n}\nexport function text(value: unknown, label: string): string {\n if (typeof value !== \"string\" || !value.trim()) invalid(`${label} must be a non-empty string`);\n return value;\n}\nexport function sha(value: unknown, label = \"sha\"): string {\n const s = text(value, label);\n if (!/^[a-f0-9]{40}$|^[a-f0-9]{64}$/.test(s))\n invalid(`${label} must be a full lowercase commit SHA`);\n return s;\n}\nfunction budget(value: unknown, label: string): Budget {\n if (\n !object(value) ||\n !dimensions.some((k) => value[k] !== undefined) ||\n Object.keys(value).some((k) => !dimensions.includes(k as (typeof dimensions)[number]))\n )\n invalid(`${label} needs tokens, turns or wallclockMs limits`);\n const out: Budget = {};\n for (const k of dimensions) {\n const n = value[k];\n if (n !== undefined) {\n if (typeof n !== \"number\" || !Number.isSafeInteger(n) || n <= 0)\n invalid(`${label}.${k} must be a positive safe integer`);\n out[k] = n;\n }\n }\n return out;\n}\nexport function validateExperimentationConfig(raw: unknown): ExperimentationConfig {\n try {\n if (!object(raw)) invalid(\"experimentation config must be an object\");\n const known = [\n \"objective\",\n \"direction\",\n \"tieBreak\",\n \"concurrencyCap\",\n \"maxCandidates\",\n \"candidateBudget\",\n \"totalBudget\",\n ];\n if (Object.keys(raw).some((k) => !known.includes(k)))\n invalid(\"unknown experimentation config key\");\n const objective = text(raw.objective, \"objective\");\n const direction = raw.direction ?? \"minimize\";\n if (direction !== \"minimize\" && direction !== \"maximize\")\n invalid(\"direction must be minimize or maximize\");\n const tieBreak = raw.tieBreak ?? \"candidate-id\";\n if (tieBreak !== \"candidate-id\") invalid(\"tieBreak must be candidate-id\");\n const concurrencyCap = raw.concurrencyCap ?? 2;\n const maxCandidates = raw.maxCandidates ?? 4;\n for (const [key, n] of Object.entries({ concurrencyCap, maxCandidates }))\n if (typeof n !== \"number\" || !Number.isSafeInteger(n) || n < 1)\n invalid(`${key} must be a positive safe integer`);\n if ((concurrencyCap as number) > (maxCandidates as number))\n invalid(\"concurrencyCap cannot exceed maxCandidates\");\n return {\n objective,\n direction,\n tieBreak,\n concurrencyCap: concurrencyCap as number,\n maxCandidates: maxCandidates as number,\n candidateBudget: budget(raw.candidateBudget ?? { turns: 10 }, \"candidateBudget\"),\n totalBudget: budget(raw.totalBudget ?? { turns: 40 }, \"totalBudget\"),\n };\n } catch (error) {\n fail(\n \"config-invalid\",\n error instanceof Error ? error.message : \"invalid experimentation config\",\n \"provide objective and positive finite limits\",\n );\n }\n}\n","import { assertId, fail } from \"../errors.ts\";\nimport { estimateTokens } from \"../budget.ts\";\nimport { resourceCapsFor } from \"../planner.ts\";\nimport { roleOf } from \"../roles.ts\";\nimport { addEvidence, getItem, moveItem, patchItem } from \"../items.ts\";\nimport { appendEvent, nowOf } from \"../state.ts\";\nimport { applyAction } from \"../methodology.ts\";\nimport { assertPolicies } from \"../policies.ts\";\nimport { experimentation } from \"./index.ts\";\nimport type { Capability, Ceremony, CeremonyInput, Spent, WorkflowState } from \"../types.ts\";\nimport { dimensions, invalid, object, sha, text, validateExperimentationConfig } from \"./config.ts\";\nimport type { ExperimentCandidate, ExperimentationState } from \"./state.ts\";\nexport function experimentOf(s: WorkflowState): ExperimentationState {\n if (s.methodology !== \"experimentation\" || !s.experimentation)\n invalid(\"freeze an experimentation workflow first\");\n return s.experimentation;\n}\nexport function authorize(s: WorkflowState, by: string, capability: Capability): void {\n if (!roleOf(s, by)?.capabilities.includes(capability))\n fail(\n \"missing-capability\",\n `${by} needs ${capability}`,\n \"use a role with the required capability\",\n );\n}\n/** Completion events bind cost to the actual dispatched item/actor; accounting labels are caller supplied. */\nfunction completedUsage(s: WorkflowState, item?: string, author?: string): Spent {\n return s.events.reduce(\n (sum, event) => {\n if (event.type !== \"item.completed\" || !object(event.payload)) return sum;\n const p = event.payload;\n if (\n typeof p.id !== \"string\" ||\n p.role !== event.by ||\n (item !== undefined && p.id !== item) ||\n (author !== undefined && p.role !== author)\n )\n return sum;\n if (\n typeof p.tokens !== \"number\" ||\n !Number.isFinite(p.tokens) ||\n p.tokens < 0 ||\n typeof p.durationMs !== \"number\" ||\n !Number.isFinite(p.durationMs) ||\n p.durationMs < 0\n )\n return sum;\n if (\n item === undefined &&\n Object.values(s.experimentation?.candidates ?? {}).some((c) => c.item === p.id)\n )\n return sum;\n return {\n tokens: sum.tokens + p.tokens,\n turns: sum.turns + 1,\n wallclockMs: sum.wallclockMs + p.durationMs,\n };\n },\n { tokens: 0, turns: 0, wallclockMs: 0 },\n );\n}\nfunction maximum(a: Spent, b: Spent): Spent {\n return {\n tokens: Math.max(a.tokens, b.tokens),\n turns: Math.max(a.turns, b.turns),\n wallclockMs: Math.max(a.wallclockMs, b.wallclockMs),\n };\n}\nexport function effectiveSpent(s: WorkflowState, c: ExperimentCandidate): Spent {\n return maximum(c.spent, completedUsage(s, c.item, c.author));\n}\nexport function synchronizeBudget(s: WorkflowState, now?: string): WorkflowState {\n if (!s.experimentation) return s;\n const usage = totalSpent(s);\n const closed = [\"stopped\", \"integrated\"].includes(s.experimentation.status);\n return {\n ...s,\n iterations: s.iterations.map((it) =>\n it.id === \"experiment\"\n ? {\n ...it,\n budget: { ...validateExperimentationConfig(s.config).totalBudget },\n spent: usage,\n ...(closed\n ? {\n endedAt: it.endedAt ?? nowOf(now),\n outcome:\n it.outcome ??\n (s.experimentation!.status === \"integrated\"\n ? (\"completed\" as const)\n : (\"cancelled\" as const)),\n }\n : {}),\n }\n : it,\n ),\n };\n}\nexport function totalSpent(s: WorkflowState, e = experimentOf(s)): Spent {\n const overhead = maximum(e.overhead, completedUsage(s));\n return Object.values(e.candidates).reduce((sum, c) => {\n const v = effectiveSpent(s, c);\n return {\n tokens: sum.tokens + v.tokens,\n turns: sum.turns + v.turns,\n wallclockMs: sum.wallclockMs + v.wallclockMs,\n };\n }, overhead);\n}\nexport function runningCount(s: WorkflowState): number {\n return Object.values(s.experimentation?.candidates ?? {}).filter(\n (c) => c.status === \"running\" || s.items[c.item]?.status === \"in_progress\",\n ).length;\n}\n/** Remaining token capacity after reserving estimates for currently dispatched work. */\nexport function reservedTokens(s: WorkflowState): number {\n return Object.values(s.experimentation?.candidates ?? {}).reduce((sum, c) => {\n const item = s.items[c.item];\n return sum + (item?.status === \"in_progress\" ? estimateTokens(s, item.weight, 1) : 0);\n }, 0);\n}\nexport function unreservedTokens(s: WorkflowState): number | undefined {\n const limit = validateExperimentationConfig(s.config).totalBudget.tokens;\n if (limit === undefined) return undefined;\n return Math.max(0, limit - totalSpent(s).tokens - reservedTokens(s));\n}\nexport function assignedAuthor(s: WorkflowState, c: ExperimentCandidate): boolean {\n const work = s.items[c.item];\n return (\n !!work &&\n (!work.role || work.role === c.author) &&\n !!roleOf(s, c.author)?.capabilities.includes(\"deliver\")\n );\n}\nexport function candidateExhausted(s: WorkflowState, c: ExperimentCandidate): boolean {\n const cfg = validateExperimentationConfig(s.config);\n const used = effectiveSpent(s, c);\n return dimensions.some(\n (k) => cfg.candidateBudget[k] !== undefined && used[k] >= cfg.candidateBudget[k]!,\n );\n}\nexport function exhausted(s: WorkflowState): boolean {\n if (!s.experimentation) return false;\n const cfg = validateExperimentationConfig(s.config);\n const usage = totalSpent(s);\n return dimensions.some(\n (k) => cfg.totalBudget[k] !== undefined && usage[k] >= cfg.totalBudget[k]!,\n );\n}\nfunction candidate(e: ExperimentationState, i: CeremonyInput): ExperimentCandidate {\n const id = text(i.candidate, \"candidate\");\n if (!Object.hasOwn(e.candidates, id)) invalid(`unknown candidate ${id}`);\n return e.candidates[id]!;\n}\nfunction bool(i: CeremonyInput, k: string): boolean {\n if (typeof i[k] !== \"boolean\") invalid(`${k} must be boolean`);\n return i[k] as boolean;\n}\nfunction spent(i: CeremonyInput): Spent {\n if (!object(i.spent)) invalid(\"spent must contain nonnegative tokens, turns and wallclockMs\");\n const out = {} as Spent;\n for (const k of dimensions) {\n const n = i.spent[k];\n if (typeof n !== \"number\" || !Number.isSafeInteger(n) || n < 0)\n invalid(`spent.${k} must be a nonnegative safe integer`);\n out[k] = n;\n }\n return out;\n}\nfunction put(e: ExperimentationState, c: ExperimentCandidate): ExperimentationState {\n return { ...e, candidates: { ...e.candidates, [c.id]: c } };\n}\nfunction charge(e: ExperimentationState, i: CeremonyInput): ExperimentationState {\n const cost = spent(i);\n return {\n ...e,\n overhead: {\n tokens: e.overhead.tokens + cost.tokens,\n turns: e.overhead.turns + cost.turns,\n wallclockMs: e.overhead.wallclockMs + cost.wallclockMs,\n },\n };\n}\nfunction closeItem(s: WorkflowState, c: ExperimentCandidate, i: CeremonyInput): WorkflowState {\n return moveItem(s, c.item, { stage: \"done\", status: \"dropped\" }, i.by, i.now);\n}\nfunction active(e: ExperimentationState): void {\n if (e.status !== \"running\") invalid(\"experiment is not running\");\n}\nfunction done(c: ExperimentCandidate): boolean {\n return [\"validated\", \"failed\", \"timed-out\", \"cancelled\"].includes(c.status);\n}\nfunction jsonSafe(value: unknown, seen = new Set<object>()): boolean {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n if (typeof value === \"number\") return Number.isFinite(value);\n if (typeof value !== \"object\" || seen.has(value)) return false;\n if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) return false;\n seen.add(value);\n // JSON.stringify drops an undefined property, so it is safe in an object but not in an array.\n const valid = Array.isArray(value)\n ? value.every((v) => jsonSafe(v, seen))\n : Object.values(value).every((v) => v === undefined || jsonSafe(v, seen));\n seen.delete(value);\n return valid;\n}\nfunction reduce(\n name: string,\n capability: Capability,\n fn: (s: WorkflowState, i: CeremonyInput) => WorkflowState,\n): Ceremony {\n return (s, i) => {\n if (!object(i) || !jsonSafe(i)) invalid(\"ceremony input must be JSON-safe\");\n text(i.by, \"by\");\n if (i.now !== undefined && (typeof i.now !== \"string\" || !Number.isFinite(Date.parse(i.now))))\n invalid(\"now must be a valid timestamp\");\n authorize(s, i.by, capability);\n return applyAction(\n s,\n experimentation(),\n { type: `ceremony.${name}`, by: i.by, payload: i },\n (current) =>\n appendEvent(\n synchronizeBudget(fn(current, i), i.now),\n `experimentation.${name}`,\n i.by,\n structuredClone(i),\n nowOf(i.now),\n ),\n );\n };\n}\nexport function experimentationCeremonies(): Record<string, Ceremony> {\n return {\n freeze: reduce(\"frozen\", \"facilitate\", (s, i) => {\n if (s.methodology !== \"experimentation\" || s.experimentation)\n invalid(\"freeze may run only once in experimentation\");\n const cfg = validateExperimentationConfig(s.config);\n const baseSha = sha(i.baseSha, \"baseSha\");\n const harness = text(i.harness, \"harness\");\n if (\n !Array.isArray(i.candidates) ||\n i.candidates.length < 1 ||\n i.candidates.length > cfg.maxCandidates\n )\n invalid(\"candidates must be a nonempty array within maxCandidates\");\n const candidates: Record<string, ExperimentCandidate> = {};\n const items = new Set<string>();\n for (const raw of i.candidates) {\n if (!object(raw)) invalid(\"candidate must be an object\");\n const id = text(raw.id, \"candidate.id\");\n assertId(id, \"candidate id\");\n if (Object.hasOwn(candidates, id)) invalid(\"candidate IDs must be unique safe identifiers\");\n const item = text(raw.item, \"candidate.item\");\n const author = text(raw.author, \"candidate.author\");\n authorize(s, author, \"deliver\");\n const work = getItem(s, item);\n if (work.role && work.role !== author)\n invalid(\"candidate item role must match frozen author\");\n if (\n items.has(item) ||\n work.stage !== \"candidate\" ||\n work.status !== \"todo\" ||\n work.acceptance.length === 0\n )\n invalid(\"candidate needs a distinct todo candidate item with acceptance criteria\");\n items.add(item);\n candidates[id] = {\n id,\n item,\n author,\n status: \"pending\",\n spent: { tokens: 0, turns: 0, wallclockMs: 0 },\n };\n }\n return {\n ...s,\n iterations: [\n ...s.iterations,\n {\n id: \"experiment\",\n goal: cfg.objective,\n budget: { ...cfg.totalBudget },\n spent: { tokens: 0, turns: 0, wallclockMs: 0 },\n startedAt: nowOf(i.now),\n committed: [...items],\n carryover: [],\n },\n ],\n experimentation: {\n status: \"running\",\n baseSha,\n harness,\n candidates,\n released: [],\n overhead: { tokens: 0, turns: 0, wallclockMs: 0 },\n },\n };\n }),\n provision: reduce(\"provisioned\", \"manage-flow\", (s, i) => {\n let e = experimentOf(s);\n active(e);\n if (exhausted(s)) invalid(\"total experiment budget exhausted\");\n const c = candidate(e, i);\n if (c.status !== \"pending\") invalid(\"candidate already provisioned\");\n const workspace = text(i.workspace, \"workspace\");\n if (sha(i.baseSha, \"baseSha\") !== e.baseSha || i.isolated !== true)\n invalid(\"provision must attest isolated workspace at the exact frozen base SHA\");\n if (Object.values(e.candidates).some((x) => x.workspace === workspace))\n invalid(\"candidate workspaces must be distinct\");\n e = put(e, { ...c, workspace, status: \"ready\" });\n return { ...s, experimentation: e };\n }),\n start: reduce(\"started\", \"deliver\", (s, i) => {\n const e = experimentOf(s);\n active(e);\n const c = candidate(e, i);\n if (c.status !== \"ready\" || c.author !== i.by)\n invalid(\"only the candidate author may start a ready candidate\");\n if (exhausted(s)) invalid(\"total experiment budget exhausted\");\n const cfg = validateExperimentationConfig(s.config);\n const running = Object.values(e.candidates).filter(\n (x) => x.status === \"running\" || s.items[x.item]?.status === \"in_progress\",\n ).length;\n if (running >= cfg.concurrencyCap) invalid(\"candidate concurrency cap reached\");\n if (!assignedAuthor(s, c))\n invalid(\"candidate author assignment or delivery capability changed\");\n const usage = totalSpent(s);\n if (cfg.totalBudget.turns !== undefined && usage.turns + running >= cfg.totalBudget.turns)\n invalid(\"total experiment budget reserved by running candidates\");\n const role = roleOf(s, c.author)!;\n const cls = role.resourceClass ?? role.id;\n const cap = resourceCapsFor(s)[cls];\n const occupied = Object.values(s.items).filter(\n (w) =>\n w.status === \"in_progress\" &&\n w.role &&\n (roleOf(s, w.role)?.resourceClass ?? w.role) === cls,\n ).length;\n if (cap !== undefined && occupied >= cap) invalid(\"role resource capacity reached\");\n const work = getItem(s, c.item);\n const tokenCapacity = unreservedTokens(s);\n if (tokenCapacity !== undefined && estimateTokens(s, work.weight, 1) > tokenCapacity)\n invalid(\"total experiment token budget reserved or insufficient\");\n if (work.status !== \"todo\") invalid(\"candidate item is already dispatched\");\n assertPolicies(\n s,\n work,\n [\n { kind: \"dependencies-done\" },\n { kind: \"no-open-blockers\" },\n { kind: \"acceptance-written\" },\n ...s.stages.find((st) => st.id === \"building\")!.entryPolicy,\n ],\n \"start candidate execution\",\n );\n if (candidateExhausted(s, c)) invalid(\"candidate budget exhausted\");\n let next = moveItem(s, c.item, { stage: \"building\", status: \"in_progress\" }, i.by, i.now);\n next = patchItem(next, c.item, (w) => ({ ...w, role: i.by }));\n return { ...next, experimentation: put(e, { ...c, status: \"running\" }) };\n }),\n submit: reduce(\"submitted\", \"deliver\", (s, i) => {\n const e = experimentOf(s);\n active(e);\n const c = candidate(e, i);\n const work = getItem(s, c.item);\n if (\n (c.status !== \"running\" && !(c.status === \"ready\" && work.status === \"in_progress\")) ||\n c.author !== i.by ||\n work.role !== i.by\n )\n invalid(\"only the running candidate author may submit once\");\n const commit = sha(i.sha);\n if (\n i.workspace !== c.workspace ||\n i.harness !== e.harness ||\n sha(i.baseSha, \"baseSha\") !== e.baseSha\n )\n invalid(\"submission provenance must match frozen base SHA, harness and owned workspace\");\n if (typeof i.score !== \"number\" || !Number.isFinite(i.score)) invalid(\"score must be finite\");\n const usage = spent(i);\n const command = text(i.command, \"command\");\n const log = text(i.log, \"log\");\n const cfg = validateExperimentationConfig(s.config);\n const measured = effectiveSpent(s, { ...c, spent: usage });\n const over = dimensions.some(\n (k) => cfg.candidateBudget[k] !== undefined && measured[k] > cfg.candidateBudget[k]!,\n );\n const updated: ExperimentCandidate = {\n ...c,\n status: over ? \"timed-out\" : \"submitted\",\n sha: commit,\n score: i.score,\n spent: measured,\n command,\n log,\n };\n if (over) updated.reason = \"candidate budget exceeded\";\n let next: WorkflowState = { ...s, experimentation: put(e, updated) };\n next = addEvidence(next, c.item, { kind: \"candidate-sha\", ref: commit, by: i.by }, i.now);\n next = addEvidence(\n next,\n c.item,\n {\n kind: \"benchmark-result\",\n ref: JSON.stringify({ score: i.score, harness: e.harness, sha: commit }),\n by: i.by,\n },\n i.now,\n );\n return over ? closeItem(next, updated, i) : next;\n }),\n terminate: reduce(\"terminated\", \"manage-flow\", (s, i) => {\n const e = experimentOf(s);\n active(e);\n const c = candidate(e, i);\n if (done(c)) invalid(\"candidate is already terminal\");\n if (![\"failed\", \"timed-out\", \"cancelled\"].includes(i.status as string))\n invalid(\"status must be failed, timed-out or cancelled\");\n const reason = text(i.reason, \"reason\");\n const usage = spent(i);\n const log = text(i.log, \"log\");\n return closeItem(\n {\n ...s,\n experimentation: put(e, {\n ...c,\n status: i.status as ExperimentCandidate[\"status\"],\n reason,\n spent: maximum(effectiveSpent(s, c), effectiveSpent(s, { ...c, spent: usage })),\n terminalLog: log,\n }),\n },\n c,\n i,\n );\n }),\n validate: reduce(\"validated\", \"verify\", (s, i) => {\n const e = experimentOf(s);\n active(e);\n const c = candidate(e, i);\n if (c.status !== \"submitted\") invalid(\"validate an unvalidated submitted candidate\");\n if (i.by === c.author) invalid(\"candidate author cannot independently validate\");\n // A candidate the planner dispatched is completed by its builder (handoff and accounting)\n // before validation; one the host started by ceremony has no completion to wait for.\n const started = s.events.some(\n (event) =>\n event.type === \"experimentation.started\" &&\n object(event.payload) &&\n event.payload.candidate === c.id,\n );\n if (!started && getItem(s, c.item).status === \"in_progress\")\n fail(\n \"invalid-input\",\n `candidate \"${c.id}\" item \"${c.item}\" is still in progress under the planner`,\n `complete item \"${c.item}\" with the builder's handoff (candidate-sha ${c.sha}) and accounting before validating`,\n { items: [c.item] },\n );\n const commit = sha(i.sha);\n const harness = text(i.harness, \"harness\");\n if (commit !== c.sha || harness !== e.harness)\n invalid(\"validation must match exact submitted SHA and frozen harness\");\n const passed = bool(i, \"passed\");\n const reproducible = bool(i, \"reproducible\");\n const evidence = text(i.evidence, \"evidence\");\n const validation = { sha: commit, harness, by: i.by, passed, reproducible, evidence };\n let next: WorkflowState = {\n ...s,\n experimentation: put(charge(e, i), {\n ...c,\n status: passed && reproducible ? \"validated\" : \"failed\",\n validation,\n }),\n };\n next = addEvidence(next, c.item, { kind: \"validation\", ref: evidence, by: i.by }, i.now);\n next = moveItem(\n next,\n c.item,\n { stage: \"done\", status: passed && reproducible ? \"done\" : \"dropped\" },\n i.by,\n i.now,\n );\n return next;\n }),\n compare: reduce(\"compared\", \"facilitate\", (s, _i) => {\n const e = experimentOf(s);\n active(e);\n const all = Object.values(e.candidates);\n if (!all.every(done))\n invalid(\n \"comparison requires all candidates terminal and submissions independently validated\",\n );\n const cfg = validateExperimentationConfig(s.config);\n const usage = totalSpent(s, e);\n if (\n dimensions.some((k) => cfg.totalBudget[k] !== undefined && usage[k] > cfg.totalBudget[k]!)\n )\n return {\n ...s,\n experimentation: { ...e, status: \"stopped\", reason: \"total budget exceeded\" },\n };\n const eligible = all.filter((c) => {\n const used = effectiveSpent(s, c);\n return (\n c.status === \"validated\" &&\n c.validation?.passed &&\n c.validation.reproducible &&\n c.validation.sha === c.sha &&\n c.validation.harness === e.harness &&\n !dimensions.some(\n (k) => cfg.candidateBudget[k] !== undefined && used[k] > cfg.candidateBudget[k]!,\n )\n );\n });\n eligible.sort((a, b) => {\n const delta = (a.score! - b.score!) * (cfg.direction === \"minimize\" ? 1 : -1);\n return delta || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);\n });\n const selected = eligible[0];\n return {\n ...s,\n experimentation: selected\n ? { ...e, status: \"selected\", selected: selected.id }\n : { ...e, status: \"stopped\", reason: \"no eligible candidate\" },\n };\n }),\n integrate: reduce(\"integration-recorded\", \"control-change\", (s, i) => {\n const e = experimentOf(s);\n if (![\"selected\", \"integrating\"].includes(e.status) || !e.selected)\n invalid(\"compare and select before integration\");\n if (exhausted(s)) invalid(\"total budget exhausted before integration\");\n const c = e.candidates[e.selected]!;\n const selectedSha = sha(i.selectedSha, \"selectedSha\");\n if (selectedSha !== c.sha || c.validation?.sha !== selectedSha)\n invalid(\"integration must promote the exact selected and validated SHA\");\n const targetSha = sha(i.targetSha, \"targetSha\");\n const integrationSha = sha(i.integrationSha, \"integrationSha\");\n if (e.integration?.sha === integrationSha && e.integration.targetSha === targetSha)\n invalid(\"integration already recorded\");\n return {\n ...s,\n experimentation: {\n ...charge(e, i),\n status: \"integrating\",\n integration: { selectedSha, targetSha, sha: integrationSha, by: i.by },\n },\n };\n }),\n \"validate-integration\": reduce(\"integration-validated\", \"verify\", (s, i) => {\n const e = experimentOf(s);\n if (e.status !== \"integrating\" || !e.integration || !e.selected)\n invalid(\"record integration before fresh validation\");\n const integration = e.integration;\n const c = e.candidates[e.selected]!;\n if (i.by === integration.by || i.by === c.author)\n invalid(\"integration validation must be independent of candidate author and integrator\");\n const commit = sha(i.sha);\n const targetSha = sha(i.targetSha, \"targetSha\");\n const harness = text(i.harness, \"harness\");\n if (\n commit !== integration.sha ||\n targetSha !== integration.targetSha ||\n harness !== e.harness\n )\n invalid(\"fresh validation must match integration SHA, current target SHA and harness\");\n const passed = bool(i, \"passed\");\n const evidence = text(i.evidence, \"evidence\");\n const charged = charge(e, i);\n const cfg = validateExperimentationConfig(s.config);\n const usage = totalSpent(s, charged);\n const over = dimensions.some(\n (k) => cfg.totalBudget[k] !== undefined && usage[k] > cfg.totalBudget[k]!,\n );\n return {\n ...s,\n experimentation: {\n ...charged,\n status: passed && !over ? \"integrated\" : \"stopped\",\n ...(passed && !over\n ? {}\n : { reason: over ? \"total budget exceeded\" : \"integration validation failed\" }),\n integration: {\n ...integration,\n validation: { by: i.by, sha: commit, harness, evidence, passed },\n },\n },\n };\n }),\n stop: reduce(\"stopped\", \"manage-flow\", (s, i) => {\n const e = experimentOf(s);\n if (e.status === \"stopped\" || e.status === \"integrated\") invalid(\"experiment already closed\");\n const reason = text(i.reason, \"reason\");\n if (\n Object.values(e.candidates).some(\n (c) =>\n c.status === \"running\" ||\n c.status === \"submitted\" ||\n s.items[c.item]?.status === \"in_progress\",\n )\n )\n invalid(\"terminate active attempts with final usage and log before stopping\");\n const candidates = Object.fromEntries(\n Object.values(e.candidates).map((c) => [\n c.id,\n done(c) ? c : { ...c, status: \"cancelled\" as const, reason },\n ]),\n );\n let next = s;\n for (const c of Object.values(e.candidates)) if (!done(c)) next = closeItem(next, c, i);\n return {\n ...next,\n experimentation: { ...charge(e, i), status: \"stopped\", reason, candidates },\n };\n }),\n cleanup: reduce(\"cleanup-recorded\", \"manage-flow\", (s, i) => {\n const e = experimentOf(s);\n if (e.status !== \"stopped\" && e.status !== \"integrated\")\n invalid(\"cleanup requires a closed experiment\");\n if (\n !Array.isArray(i.workspaces) ||\n i.workspaces.length === 0 ||\n i.workspaces.some(\n (w) =>\n typeof w !== \"string\" ||\n !Object.values(e.candidates).some((c) => c.workspace === w) ||\n e.released.includes(w),\n ) ||\n new Set(i.workspaces).size !== i.workspaces.length\n )\n invalid(\"workspaces must list distinct owned unreleased identities\");\n return {\n ...s,\n experimentation: { ...e, released: [...e.released, ...(i.workspaces as string[])] },\n };\n }),\n };\n}\n","import type { WorkflowState } from \"../types.ts\";\nimport { effectiveSpent, totalSpent } from \"./ceremonies.ts\";\nexport function experimentationMetrics(\n s: WorkflowState,\n): Record<string, number | Record<string, number>> {\n const e = s.experimentation;\n const all = Object.values(e?.candidates ?? {});\n return {\n candidates: all.length,\n validated: all.filter((c) => c.status === \"validated\").length,\n failed: all.filter((c) => c.status === \"failed\").length,\n timedOut: all.filter((c) => c.status === \"timed-out\").length,\n cancelled: all.filter((c) => c.status === \"cancelled\").length,\n integrated: e?.status === \"integrated\" ? 1 : 0,\n spent: e ? { ...totalSpent(s) } : { tokens: 0, turns: 0, wallclockMs: 0 },\n candidateTokens: Object.fromEntries(all.map((c) => [c.id, effectiveSpent(s, c).tokens])),\n };\n}\nexport function experimentationReport(s: WorkflowState): Record<string, unknown> {\n const e = s.experimentation;\n return {\n status: e?.status ?? \"unfrozen\",\n baseSha: e?.baseSha ?? null,\n harness: e?.harness ?? null,\n selected: e?.selected ?? null,\n reason: e?.reason ?? null,\n integration: e?.integration ? structuredClone(e.integration) : null,\n candidates: structuredClone(e?.candidates ?? {}),\n cleanup: Object.values(e?.candidates ?? {}).flatMap((c) =>\n c.workspace && !e?.released.includes(c.workspace) ? [c.workspace] : [],\n ),\n hostResponsibilities: [\n \"provision isolated workspaces at baseSha\",\n \"execute candidates and the frozen harness\",\n \"integrate selected SHA at the current target\",\n \"execute fresh integration validation\",\n \"release owned workspace identities and record cleanup\",\n ],\n };\n}\n","import type { Role } from \"../types.ts\";\nexport function experimentationRoles(): Role[] {\n return [\n {\n id: \"coordinator\",\n name: \"Experiment coordinator\",\n modelTier: \"large\",\n capabilities: [\"facilitate\", \"order-backlog\", \"manage-flow\"],\n canApprove: [],\n inputs: [\"objective\", \"budgets\"],\n outputs: [\"comparison\"],\n do_not: [\"Change the frozen baseline or harness\"],\n },\n {\n id: \"builder\",\n name: \"Candidate builder\",\n modelTier: \"large\",\n capabilities: [\"deliver\"],\n canApprove: [],\n inputs: [\"frozen harness\", \"isolated workspace\"],\n outputs: [\"candidate-sha\", \"benchmark-result\"],\n do_not: [\"Validate your own candidate\", \"Change another candidate workspace\"],\n },\n {\n id: \"validator\",\n name: \"Independent validator\",\n modelTier: \"large\",\n capabilities: [\"verify\", \"review\", \"approve-gate\"],\n canApprove: [\"experiment-validation\"],\n inputs: [\"exact candidate SHA\", \"frozen harness\"],\n outputs: [\"validation\"],\n do_not: [\"Approve your own work\"],\n },\n {\n id: \"integrator\",\n name: \"Selected candidate integrator\",\n modelTier: \"large\",\n capabilities: [\"deliver\", \"control-change\"],\n canApprove: [],\n inputs: [\"selected SHA\", \"current target SHA\"],\n outputs: [\"integration SHA\"],\n do_not: [\"Declare integration validated\"],\n },\n ];\n}\n","import type { Rule } from \"../types.ts\";\nexport function experimentationRules(): Rule[] {\n return [\n {\n id: \"experimentation-lifecycle\",\n severity: \"error\",\n check(state, action) {\n const errors: string[] = [];\n const e = state.experimentation;\n const payload = action.payload as\n | {\n item?: string;\n handoff?: { verdict?: string; produced?: { kind: string; ref: string }[] };\n }\n | undefined;\n if (action.type === \"item.complete\") {\n if (![\"done\", \"needs-review\"].includes(payload?.handoff?.verdict ?? \"done\"))\n errors.push(\n \"unsupported completion verdict: terminate this attempt with final usage and log, then freeze a new experiment for retries\",\n );\n const c =\n e && Object.values(e.candidates).find((candidate) => candidate.item === payload?.item);\n if (!c || ![\"submitted\", \"validated\"].includes(c.status))\n errors.push(\"submit the candidate SHA and benchmark before completing work\");\n if (\n c?.status === \"submitted\" &&\n !payload?.handoff?.produced?.some((p) => p.kind === \"candidate-sha\" && p.ref === c.sha)\n )\n errors.push(\"handoff must retain the exact submitted candidate SHA\");\n }\n return errors.map((message) => ({\n rule: \"experimentation-lifecycle\",\n severity: \"error\" as const,\n message,\n fix: \"follow the frozen experimentation lifecycle\",\n }));\n },\n },\n ];\n}\n","import type { Stage } from \"../types.ts\";\nexport function experimentationStages(): Stage[] {\n return [\n {\n id: \"candidate\",\n name: \"Frozen candidate\",\n entryPolicy: [],\n exitPolicy: [\n { kind: \"acceptance-written\" },\n { kind: \"no-open-blockers\" },\n { kind: \"dependencies-done\" },\n ],\n },\n {\n id: \"building\",\n name: \"Isolated candidate execution\",\n entryPolicy: [\n { kind: \"acceptance-written\" },\n { kind: \"no-open-blockers\" },\n { kind: \"dependencies-done\" },\n ],\n exitPolicy: [\n { kind: \"evidence\", evidenceKind: \"candidate-sha\" },\n { kind: \"evidence\", evidenceKind: \"benchmark-result\" },\n ],\n },\n {\n id: \"validation\",\n name: \"Independent exact-SHA validation\",\n review: true,\n entryPolicy: [],\n exitPolicy: [{ kind: \"evidence\", evidenceKind: \"validation\" }],\n gate: {\n id: \"experiment-validation\",\n requires: [{ capability: \"verify\" }],\n evidence: [\"validation\"],\n onFail: { action: \"block\" },\n },\n },\n {\n id: \"done\",\n name: \"Candidate work complete\",\n entryPolicy: [],\n exitPolicy: [],\n deliveryPoint: true,\n },\n ];\n}\n","import type { Methodology } from \"../types.ts\";\nimport {\n experimentationCeremonies,\n candidateExhausted,\n exhausted,\n runningCount,\n assignedAuthor,\n synchronizeBudget,\n reservedTokens,\n} from \"./ceremonies.ts\";\nimport { validateExperimentationConfig, type ExperimentationConfig } from \"./config.ts\";\nimport { experimentationMetrics, experimentationReport } from \"./metrics.ts\";\nimport { experimentationRoles } from \"./roles.ts\";\nimport { experimentationRules } from \"./rules.ts\";\nimport { experimentationStages } from \"./stages.ts\";\nexport {\n validateExperimentationConfig,\n experimentationCeremonies,\n experimentationMetrics,\n experimentationReport,\n experimentationRoles,\n experimentationRules,\n experimentationStages,\n};\nexport type { ExperimentationConfig } from \"./config.ts\";\nexport type { ExperimentationState, ExperimentCandidate } from \"./state.ts\";\nexport function experimentation(): Methodology<ExperimentationConfig> {\n return {\n name: \"experimentation\",\n vocabulary: {\n backlog: \"Candidate pool\",\n item: \"Candidate work item\",\n stage: \"Experiment stage\",\n iteration: \"Experiment run\",\n increment: \"Validated integration\",\n ceremony: \"Experiment control\",\n gate: \"Independent validation\",\n },\n validateConfig: validateExperimentationConfig,\n defaultStages: experimentationStages,\n defaultRoles: experimentationRoles,\n requiredCapabilities: [\"facilitate\", \"manage-flow\", \"deliver\", \"verify\", \"control-change\"],\n exclusiveCapabilities: [],\n plannerOptions(s) {\n const cfg = validateExperimentationConfig(s.config);\n return {\n schedulerMode: \"throughput\",\n dispatchStage: \"building\",\n concurrencyCap: Math.max(1, cfg.concurrencyCap - runningCount(s)),\n fallbackTokensPerWeight: 1,\n reservedTokens: reservedTokens(s),\n roleFor(item) {\n return Object.values(s.experimentation?.candidates ?? {}).find(\n (candidate) => candidate.item === item.id,\n )?.author;\n },\n };\n },\n candidates(s) {\n const e = s.experimentation;\n if (!e || e.status !== \"running\") return [];\n const cfg = validateExperimentationConfig(s.config);\n if (exhausted(s) || runningCount(s) >= cfg.concurrencyCap) return [];\n return Object.values(e.candidates)\n .filter(\n (c) =>\n c.status === \"ready\" &&\n assignedAuthor(s, c) &&\n s.items[c.item]?.status === \"todo\" &&\n !candidateExhausted(s, c),\n )\n .map((c) => s.items[c.item]!);\n },\n afterComplete(s, _item, now) {\n return synchronizeBudget(s, now);\n },\n invariants(s, item) {\n const e = s.experimentation;\n const c = Object.values(e?.candidates ?? {}).find((candidate) => candidate.item === item.id);\n return [\n `Frozen base SHA: ${e?.baseSha ?? \"unfrozen\"}; harness: ${e?.harness ?? \"unfrozen\"}`,\n `Candidate: ${c?.id ?? \"unregistered\"}; isolated workspace: ${c?.workspace ?? \"not provisioned\"}`,\n `Objective and budget: ${JSON.stringify(s.config)}`,\n \"Submit an exact commit SHA and harness benchmark before completion; independent validation is mandatory.\",\n \"Host owns process execution, Git integration and workspace cleanup.\",\n ];\n },\n ceremonies: experimentationCeremonies(),\n rules: experimentationRules(),\n metrics: experimentationMetrics,\n report: experimentationReport,\n humanDefaults: { gates: \"none\" },\n lockedConfigKeys: [\n \"objective\",\n \"direction\",\n \"tieBreak\",\n \"concurrencyCap\",\n \"maxCandidates\",\n \"candidateBudget\",\n \"totalBudget\",\n ],\n };\n}\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkVXH2FAKV_cjs=require('./chunk-VXH2FAKV.cjs'),chunkXMO2RCXB_cjs=require('./chunk-XMO2RCXB.cjs'),chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs'),exsorted=require('exsorted');var P=new Set(["in_progress","blocked","awaiting_human"]),E=new Set(["todo","in_progress","blocked","review","awaiting_human"]);function se(e){let t=e.stages[0];return t||chunkS3BXVHO7_cjs.b("config-invalid","kanban board has no columns","init with at least options, a commitment column and a delivery column"),t}function K(e){let t=e.stages.find(a=>a.commitmentPoint);return t||chunkS3BXVHO7_cjs.b("config-invalid","no column is the commitment point","set commitmentPoint: true on exactly one column"),t}function ee(e){let t=e.stages.find(a=>a.deliveryPoint);return t||chunkS3BXVHO7_cjs.b("config-invalid","no column is the delivery point","set deliveryPoint: true on the last column"),t}function X(e,t){return chunkXMO2RCXB_cjs.p(e,t),e.stages.findIndex(a=>a.id===t)}function D(e,t){let a=X(e,t.stage);return a>=X(e,K(e).id)&&a<X(e,ee(e).id)}function U(e){return Object.values(e.items).filter(t=>t.classOfService==="expedite"&&P.has(t.status)&&D(e,t)).map(t=>t.id)}function _(e){for(let t=e.transitions.length-1;t>=0;t--){let a=e.transitions[t];if(a.to.stage===e.stage&&a.from.stage!==e.stage)return a.at}}var Y=["replenishment","delivery-planning","service-delivery-review","operations-review","risk-review","strategy-review"],I=["expedite","fixed-date","standard","intangible"],te=864e5;function h(e){return e.config}var Pe=[{id:"options",name:"Options",policies:[{kind:"acceptance-written"}]},{id:"ready",name:"Ready",wipLimit:4,commitmentPoint:true,policies:[{kind:"dependencies-done"}]},{id:"dev",name:"Development",wipLimit:3,policies:[{kind:"evidence",evidenceKind:"test-output"}]},{id:"review",name:"Review",wipLimit:2,review:true,policies:[{kind:"no-open-blockers"}]},{id:"done",name:"Done",deliveryPoint:true,policies:[]}],B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function q(e,t,a,s=1){if(e!==void 0)return (typeof e!="number"||!Number.isFinite(e)||e<s)&&chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.${t} must be a number >= ${s} (got ${JSON.stringify(e)})`,a),e}var Me=["acceptance-written","estimate-present","no-open-blockers","dependencies-done"],ae=e=>typeof e=="string"&&e.trim()!=="";function ce(e,t){Array.isArray(e)||chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.${t} must be an array of Policy objects`,'e.g. [{ "kind": "evidence", "evidenceKind": "test-output" }]');let a=[];return e.forEach((s,m)=>{let f=`kanban config.${t}[${m}]`;B(s)&&(s.kind==="evidence"?ae(s.evidenceKind):s.kind==="custom"?ae(s.id)&&ae(s.description):typeof s.kind=="string"&&Me.includes(s.kind))||chunkS3BXVHO7_cjs.b("config-invalid",`${f} must be a Policy`,`use a Policy such as { "kind": "evidence", "evidenceKind": "test-output" }, { "kind": "custom", "id": "x", "description": "..." } or one of: ${Me.join(", ")}`),a.push(s);}),a}function Ne(e,t){B(e)||chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.columns[${t}] must be an object`,'e.g. { "id": "dev", "policies": [] }'),chunkS3BXVHO7_cjs.c(e.id,`kanban config.columns[${t}].id`);let a=e.id;Array.isArray(e.policies)||chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.columns[${t}] ("${a}") needs policies: Policy[]`,'every column states its policies explicitly, e.g. [{ "kind": "acceptance-written" }]');let s={id:a,name:typeof e.name=="string"&&e.name.trim()!==""?e.name:a,policies:ce(e.policies,`columns[${t}].policies`)},m=q(e.wipLimit,`columns[${t}].wipLimit`,"omit wipLimit for no limit");m!==void 0&&(s.wipLimit=m);for(let f of ["commitmentPoint","deliveryPoint","review"])e[f]!==void 0&&(typeof e[f]!="boolean"&&chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.columns[${t}].${f} must be a boolean`,`set ${f}: true or omit it`),e[f]&&(s[f]=true));return s}function H(e){let t=e??{};t.columns!==void 0&&!Array.isArray(t.columns)&&chunkS3BXVHO7_cjs.b("config-invalid","kanban config.columns must be an array of columns","omit columns for the default board (options, ready, dev, review, done)");let a=t.columns===void 0?Pe.map(o=>({...o})):t.columns.map(Ne),s=new Set;for(let o of a)s.has(o.id)&&chunkS3BXVHO7_cjs.b("config-invalid",`duplicate column id "${o.id}"`,"give every column a unique id"),s.add(o.id);let m={},f=t.classesOfService??{};B(f)||chunkS3BXVHO7_cjs.b("config-invalid","kanban config.classesOfService must be an object keyed by class",'e.g. { "expedite": { "wipBypass": 1 } }');for(let[o,c]of Object.entries(f)){I.includes(o)||chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.classesOfService.${o} is not a class of service`,`use one of: ${I.join(", ")}`),B(c)||chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.classesOfService.${o} must be an object`,'e.g. { "wipBypass": 1, "sle": { "percentile": 85, "targetMs": 604800000 } }');let d={},p=q(c.wipBypass,`classesOfService.${o}.wipBypass`,"omit it for the default 1",0);if(p!==void 0&&(d.wipBypass=p),c.sle!==void 0){let g=c.sle;(!B(g)||typeof g.percentile!="number"||g.percentile<0||g.percentile>100)&&chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.classesOfService.${o}.sle.percentile must be 0..100`,'e.g. { "percentile": 85, "targetMs": 604800000 }');let k=q(g.targetMs,`classesOfService.${o}.sle.targetMs`,"state the service level target in milliseconds");k===void 0&&chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.classesOfService.${o}.sle.targetMs is required`,"state the service level target in milliseconds"),d.sle={percentile:g.percentile,targetMs:k};}m[o]=d;}let y=t.fairness??{};(!B(y)||y.aging!==void 0&&typeof y.aging!="boolean")&&chunkS3BXVHO7_cjs.b("config-invalid","kanban config.fairness must be { aging: boolean, maxDeferralRounds?: number }","omit it for aging on");let l=q(y.maxDeferralRounds,"fairness.maxDeferralRounds","omit it for 5 rounds"),i={aging:y.aging===void 0?true:y.aging,maxDeferralRounds:l??5},r={},n=t.cadences??{};B(n)||chunkS3BXVHO7_cjs.b("config-invalid","kanban config.cadences must be an object keyed by cadence",'e.g. { "replenishment": { "everyTurns": 10 } }');for(let[o,c]of Object.entries(n)){Y.includes(o)||chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.cadences.${o} is not a cadence`,`use one of: ${Y.join(", ")}`),B(c)||chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.cadences.${o} must be an object`,'e.g. { "everyTurns": 10 }');let d=q(c.everyTurns,`cadences.${o}.everyTurns`,"omit it when the cadence is run by hand");r[o]=d===void 0?{}:{everyTurns:d};}return {columns:a,classesOfService:m,fairness:i,cadences:r,throughputWindowMs:q(t.throughputWindowMs,"throughputWindowMs","omit it for one week")??7*te,maxExpedite:q(t.maxExpedite,"maxExpedite","omit it for 1")??1}}function ne(e,t){return e.events.find(s=>s.type==="item.added"&&s.payload.id===t)?.at??e.events[0].at}function ie(e,t,a){return Date.parse(a)-Date.parse(_(t)??ne(e,t.id))}function qe(e,t){return e.stages.map(a=>{let s=Object.values(e.items).filter(l=>l.stage===a.id&&l.status!=="dropped"),m=exsorted.timSort(s.map(l=>({id:l.id,title:l.title,type:l.type,status:l.status,classOfService:l.classOfService??"standard",role:l.role??null,ageMs:ie(e,l,t),blocked:l.blockers.some(i=>!i.clearedAt),deadline:l.deadline??null})),(l,i)=>i.ageMs-l.ageMs||(l.id<i.id?-1:1)),f=m.filter(l=>P.has(l.status)).length,y=m.filter(l=>l.status==="todo"||l.status==="review").length;return {id:a.id,name:a.name,wipLimit:a.wipLimit??null,active:f,queued:y,overLimit:a.wipLimit!==void 0&&f>a.wipLimit,commitmentPoint:a.commitmentPoint===true,deliveryPoint:a.deliveryPoint===true,cards:m}})}var Ee=e=>`cadence.${e}`;function le(e){let t=h(e);return Y.map(a=>{let s=0,m=null;for(let l of e.events)l.type===Ee(a)&&(s=l.seq,m=l.at);let f=e.events.filter(l=>l.type==="item.completed"&&l.seq>s).length,y=t.cadences[a]?.everyTurns??null;return {cadence:a,everyTurns:y,lastAt:m,turnsSince:f,due:y!==null&&f>=y}})}var De=(e,t)=>Date.parse(t)-Date.parse(e),Ie=e=>e.transition??null;function re(e,t,a){let s=new Map,m=[],f=e[0]?.at??"1970-01-01T00:00:00.000Z",y=(i,r,n)=>{r===t&&i.committedAt===void 0&&(i.committedAt=n),r===a&&i.deliveredAt===void 0&&(i.deliveredAt=n);},l=(i,r,n)=>{i.since.status==="in_progress"&&(i.activeMs+=De(i.since.at,n)),i.since.status==="blocked"&&(i.blockedMs+=De(i.since.at,n)),i.since={status:r.status,at:n},r.stage!==i.stage&&(i.stays[i.stays.length-1].leftAt=n,i.stays.push({stage:r.stage,enteredAt:n}),y(i,r.stage,n)),i.stage=r.stage,i.status=r.status;};for(let i of e){f=i.at;let r=i.payload??{};switch(i.type){case "item.added":{let n=r.id,o=r.stage,c={id:n,type:typeof r.type=="string"?r.type:"task",stage:o,status:"todo",stays:[{stage:o,enteredAt:i.at}],classOfService:"standard",activeMs:0,blockedMs:0,since:{status:"todo",at:i.at}};y(c,o,i.at),s.set(n,c);break}case "item.transition":{let n=s.get(r.id);if(!n)break;l(n,r.to,i.at);break}case "cadence.replenishment":{let n=r.items??[];for(let o of n){let c=s.get(o.id);c&&(c.classOfService=o.classOfService,o.deadline?c.deadline=o.deadline:delete c.deadline);}break}case "blocker.raised":{m.push({item:r.id,blocker:r.blocker,raisedAt:i.at});let n=s.get(r.id),o=Ie(r);n&&o&&l(n,o.to,i.at);break}case "blocker.cleared":{let n=m.find(d=>d.item===r.id&&d.blocker===r.blocker&&d.clearedAt===void 0);n&&(n.clearedAt=i.at);let o=s.get(r.id),c=Ie(r);o&&c&&l(o,c.to,i.at);break}}}return {items:s,blockers:m,lastAt:f}}function V(e,t){if(e.length===0)return 0;let a=exsorted.timSort([...e],(m,f)=>m-f),s=Math.min(a.length,Math.max(1,Math.ceil(t/100*a.length)));return a[s-1]}var G=(e,t)=>Date.parse(t)-Date.parse(e),We=(e,t)=>t===0?0:e/t;function je(e){let t=e.stages.find(s=>s.commitmentPoint)?.id??"",a=e.stages.find(s=>s.deliveryPoint)?.id??"";return {commitment:t,delivery:a,ci:e.stages.findIndex(s=>s.id===t),di:e.stages.findIndex(s=>s.id===a)}}function Le(e){let t={};for(let a of e.items.values())for(let s of a.stays)s.leftAt!==void 0&&(t[s.stage]??=[]).push(G(s.enteredAt,s.leftAt));return t}function me(e){let t=je(e);return Le(re(e.events,t.commitment,t.delivery))}function Z(e){let t=h(e),a=je(e),s=re(e.events,a.commitment,a.delivery),m=[...s.items.values()],f=e.stages.map(u=>u.id),y=new Map(f.map((u,v)=>[u,v])),l=exsorted.timSort(m.filter(u=>u.type!=="question"&&u.committedAt!==void 0&&u.deliveredAt!==void 0),(u,v)=>Date.parse(u.deliveredAt)-Date.parse(v.deliveredAt)),i=l.map(u=>G(u.committedAt,u.deliveredAt)),r={};for(let[u,v]of Object.entries(Le(s)))r[u]=v.reduce((w,x)=>w+x,0)/v.length;let n=m.filter(u=>u.type!=="question"&&u.committedAt!==void 0).map(u=>Date.parse(u.committedAt)),o=[];if(n.length>0){let u=n.reduce((w,x)=>x<w?x:w,n[0]),v=Math.floor((Date.parse(s.lastAt)-u)/t.throughputWindowMs)+1;o=Array.from({length:v},()=>0);for(let w of l){let x=Math.floor((Date.parse(w.deliveredAt)-u)/t.throughputWindowMs);x>=0&&x<v&&(o[x]+=1);}}let c=Object.fromEntries(f.map(u=>[u,0])),d={};for(let u of m){if(!E.has(u.status))continue;Object.hasOwn(c,u.stage)&&(c[u.stage]+=1);let v=y.get(u.stage);v!==void 0&&v>=a.ci&&v<a.di&&(d[u.id]=G(u.stays[u.stays.length-1].enteredAt,s.lastAt));}let p=new Map;for(let u of m)for(let v of u.stays){let w=p.get(v.stage)??new Map;w.has(u.id)||w.set(u.id,v.enteredAt),p.set(v.stage,w);}let g=exsorted.timSort([...new Set(e.events.map(u=>u.at.slice(0,10)))],(u,v)=>u<v?-1:u>v?1:0),k={};for(let u of g)for(let v of f)k[`${u}:${v}`]=[...p.get(v)?.values()??[]].filter(w=>w.slice(0,10)<=u).length;let M={};for(let[u,v]of Object.entries(t.classesOfService)){if(!v?.sle)continue;let w=l.filter(x=>x.classOfService===u);w.length!==0&&(M[u]=w.filter(x=>G(x.committedAt,x.deliveredAt)<=v.sle.targetMs).length/w.length);}let C=s.blockers.reduce((u,v)=>u+G(v.raisedAt,v.clearedAt??s.lastAt),0);return {leadTimeMs:i,leadTimeP50:V(i,50),leadTimeP85:V(i,85),cycleTimeMsByColumn:r,throughput:o,wipByColumn:c,flowEfficiency:We(l.reduce((u,v)=>u+v.activeMs,0),i.reduce((u,v)=>u+v,0)),agingWipMs:d,cumulativeFlow:k,sleCompliance:M,blockerTimeMs:C,meanBlockerTimeMs:We(C,s.blockers.length)}}function fe(e,t){let a=Date.parse(t),s=me(e),m=[],f=[],y=Object.fromEntries(e.stages.map(i=>[i.id,0])),l=Object.fromEntries(e.stages.map(i=>[i.id,0]));for(let i of Object.values(e.items)){for(let r of i.blockers)r.clearedAt||m.push({item:i.id,blocker:r.id,owner:r.owner,reason:r.reason,ageMs:a-Date.parse(r.raisedAt)});if(P.has(i.status)?l[i.stage]=(l[i.stage]??0)+1:(i.status==="todo"||i.status==="review")&&(y[i.stage]=(y[i.stage]??0)+1),E.has(i.status)&&D(e,i)){let r=s[i.stage]??[],n=r.length?V(r,85):null,o=ie(e,i,t);f.push({item:i.id,column:i.stage,status:i.status,ageMs:o,p85Ms:n,overP85:n!==null&&o>n});}}return {blockers:m,agingWip:exsorted.timSort(f,(i,r)=>r.ageMs-i.ageMs||(i.item<r.item?-1:1)),queued:y,active:l}}function Fe(e,t){let a=K(e).id;return e.items[t].transitions.find(f=>f.to.stage===a&&f.from.stage!==a)?.at??ne(e,t)}function ue(e,t,a){let s=Date.parse(t),m=h(e),f=Z(e).leadTimeMs,y=m.classesOfService["fixed-date"]?.sle?.percentile??85,l=f.length?V(f,y):null,i=[],r=[];for(let n of Object.values(e.items)){for(let p of n.blockers){let g=p.clearedAt?0:s-Date.parse(p.raisedAt);!p.clearedAt&&g>a&&r.push({item:n.id,blocker:p.id,owner:p.owner,ageMs:g});}if(n.classOfService!=="fixed-date"||!n.deadline||!E.has(n.status)||!D(e,n))continue;let o=s-Date.parse(Fe(e,n.id)),c=l===null?null:Math.max(0,l-o),d=Date.parse(n.deadline)-s;i.push({item:n.id,deadline:n.deadline,timeLeftMs:d,projectedRemainingMs:c,atRisk:d<0||c!==null&&c>d});}return {fixedDate:i,staleBlockers:r,expediteActive:U(e)}}var F=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function pe(e,t,a){let s=t.items;(!Array.isArray(s)||s.length===0||!s.every(f=>typeof f=="string"))&&chunkS3BXVHO7_cjs.b("invalid-input",`${a} needs items: string[]`,'pass ["A", "B"]');let m=s.find((f,y)=>s.indexOf(f)!==y);m!==void 0&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${m}" appears twice in items[]`,"list each item once",{items:[m]});for(let f of s)chunkXMO2RCXB_cjs.u(e,f);return s}function Je(e){return F(e)&&typeof e.percentile=="number"&&e.percentile>=0&&e.percentile<=100&&typeof e.targetMs=="number"&&Number.isFinite(e.targetMs)&&e.targetMs>0}function Ke(e,t){let{wipLimit:a,...s}=e;return t===null?s:{...s,wipLimit:t}}function ge(e){let t=(i,r,n,o)=>chunkXMO2RCXB_cjs.Y(i,e(),{type:r,by:n.by,payload:n},c=>o(c,chunkXMO2RCXB_cjs.a(n.now)));return {replenishment:(i,r)=>{chunkXMO2RCXB_cjs.o(i,r.by,"order-backlog","manage-flow");let n=pe(i,r,"replenishment"),o=K(i),c=se(i);for(let d of n)chunkXMO2RCXB_cjs.G(i,chunkXMO2RCXB_cjs.u(i,d),c.exitPolicy,`leave "${c.id}"`);return t(i,"ceremony.replenishment",r,(d,p)=>{for(let g of n)d=chunkXMO2RCXB_cjs.x(d,g,{stage:o.id,status:"todo"},r.by,p);return chunkXMO2RCXB_cjs.c(d,"cadence.replenishment",r.by,{column:o.id,items:n.map(g=>{let k=chunkXMO2RCXB_cjs.u(d,g);return {id:g,classOfService:k.classOfService??"standard",deadline:k.deadline??null}})},p)})},"delivery-planning":(i,r)=>{chunkXMO2RCXB_cjs.o(i,r.by,"facilitate","manage-flow");let n=pe(i,r,"delivery-planning"),o=ee(i),c=i.stages[i.stages.findIndex(d=>d.id===o.id)-1];for(let d of n){let p=chunkXMO2RCXB_cjs.u(i,d);p.stage!==c.id&&p.stage!==o.id&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${d}" is in "${p.stage}", not ready for delivery`,`only cards in "${c.id}" or "${o.id}" can be planned for delivery`,{items:[d]});}return t(i,"ceremony.delivery-planning",r,(d,p)=>chunkXMO2RCXB_cjs.c(d,"cadence.delivery-planning",r.by,{items:n,window:typeof r.window=="string"?r.window:null,delivered:n.filter(g=>chunkXMO2RCXB_cjs.u(d,g).status==="done")},p))},"service-delivery-review":(i,r)=>{chunkXMO2RCXB_cjs.o(i,r.by,"manage-flow");let n=r.wip??{},o=r.policies??{},c=r.sle??{};(!F(n)||!F(o)||!F(c))&&chunkS3BXVHO7_cjs.b("invalid-input","service-delivery-review takes wip, policies and sle objects keyed by column or class",'e.g. { "wip": { "dev": 2 }, "policies": { "dev": [{ "kind": "no-open-blockers" }] }, "sle": { "standard": { "percentile": 85, "targetMs": 604800000 } } }');for(let[g,k]of Object.entries(n))chunkXMO2RCXB_cjs.p(i,g),k!==null&&(typeof k!="number"||!Number.isFinite(k)||k<1)&&chunkS3BXVHO7_cjs.b("invalid-input",`wip.${g} must be a positive number or null`,"null removes the limit");let d={};for(let[g,k]of Object.entries(o))chunkXMO2RCXB_cjs.p(i,g),d[g]=ce(k,`policies.${g}`);for(let[g,k]of Object.entries(c))I.includes(g)||chunkS3BXVHO7_cjs.b("invalid-input",`sle.${g} is not a class of service`,`use one of: ${I.join(", ")}`),k!==null&&!Je(k)&&chunkS3BXVHO7_cjs.b("invalid-input",`sle.${g} must be { percentile: 0..100, targetMs: > 0 } or null`,"null removes the service level");let p=chunkVXH2FAKV_cjs.a(i,r,"service-delivery-review");return t(i,"ceremony.service-delivery-review",r,(g,k)=>{let M=h(g),C=g.stages,u=M.columns,v={...M.classesOfService},w=[],x=[],we=[];for(let[S,O]of Object.entries(n)){let W=C.find(R=>R.id===S).wipLimit??null;W!==O&&(w.push({column:S,before:W,after:O}),C=C.map(R=>R.id===S?Ke(R,O):R),u=u.map(R=>R.id===S?Ke(R,O):R));}for(let[S,O]of Object.entries(d)){let W=C.find($=>$.id===S).exitPolicy;if(JSON.stringify(W)===JSON.stringify(O))continue;x.push({column:S,before:W,after:O});let R=C.findIndex($=>$.id===S),Q=C[R].commitmentPoint?C[R+1]?.id:void 0;C=C.map($=>$.id===S?{...$,exitPolicy:O}:$.id===Q?{...$,entryPolicy:O}:$),u=u.map($=>$.id===S?{...$,policies:O}:$);}for(let[S,O]of Object.entries(c)){let W=v[S]?.sle??null;if(JSON.stringify(W)===JSON.stringify(O))continue;we.push({classOfService:S,before:W,after:O});let{sle:R,...Q}=v[S]??{};v={...v,[S]:O===null?Q:{...Q,sle:O}};}g={...g,stages:C,config:{...M,columns:u,classesOfService:v}};let T=chunkVXH2FAKV_cjs.b(g,p,r.by,k);return chunkXMO2RCXB_cjs.c(T.state,"cadence.service-delivery-review",r.by,{wip:w,policies:x,sle:we,lessons:T.created,adopted:T.adopted.slice(T.created.length),dismissed:T.dismissed,agreements:T.agreements,retired:T.retired},k)})},"operations-review":(i,r)=>{chunkXMO2RCXB_cjs.o(i,r.by,"facilitate","manage-flow");let n=r.assign??[];(!Array.isArray(n)||!n.every(o=>F(o)&&typeof o.item=="string"&&typeof o.blocker=="string"))&&chunkS3BXVHO7_cjs.b("invalid-input","operations-review.assign must be [{ item, blocker, owner }]",'e.g. { "assign": [{ "item": "A", "blocker": "A-b1", "owner": "service-delivery-manager" }] }');for(let o of n){let c=chunkXMO2RCXB_cjs.u(i,o.item);c.blockers.some(d=>d.id===o.blocker&&!d.clearedAt)||chunkS3BXVHO7_cjs.b("invalid-input",`item "${o.item}" has no open blocker "${o.blocker}"`,`open blockers: ${c.blockers.filter(d=>!d.clearedAt).map(d=>d.id).join(", ")||"(none)"}`,{items:[o.item]});}return t(i,"ceremony.operations-review",r,(o,c)=>{for(let d of n){let p=chunkXMO2RCXB_cjs.u(o,d.item).blockers.find(g=>g.id===d.blocker).owner;o=chunkXMO2RCXB_cjs.s(o,d.item,g=>({...g,blockers:g.blockers.map(k=>k.id===d.blocker?{...k,owner:d.owner}:k)})),o=chunkXMO2RCXB_cjs.c(o,"blocker.reassigned",r.by,{id:d.item,blocker:d.blocker,from:p,to:d.owner},c);}return chunkXMO2RCXB_cjs.c(o,"cadence.operations-review",r.by,fe(o,c),c)})},"risk-review":(i,r)=>{chunkXMO2RCXB_cjs.o(i,r.by,"facilitate","manage-flow");let n=r.staleAfterMs??7*te;return (typeof n!="number"||!Number.isFinite(n)||n<0)&&chunkS3BXVHO7_cjs.b("invalid-input","risk-review.staleAfterMs must be a non-negative number of milliseconds","omit it for one week"),t(i,"ceremony.risk-review",r,(o,c)=>chunkXMO2RCXB_cjs.c(o,"cadence.risk-review",r.by,ue(o,c,n),c))},"strategy-review":(i,r)=>{chunkXMO2RCXB_cjs.o(i,r.by,"manage-flow");let n=h(i),o=r.classesOfService??{};F(o)||chunkS3BXVHO7_cjs.b("invalid-input","strategy-review.classesOfService must be an object keyed by class",'e.g. { "expedite": { "wipBypass": 2 }, "intangible": null }');let c={...n.classesOfService};for(let[p,g]of Object.entries(o))I.includes(p)||chunkS3BXVHO7_cjs.b("invalid-input",`classesOfService.${p} is not a class of service`,`use one of: ${I.join(", ")}`),g===null?delete c[p]:c[p]=g;let d=H({...n,classesOfService:c,maxExpedite:r.maxExpedite??n.maxExpedite});return t(i,"ceremony.strategy-review",r,(p,g)=>{let k=Object.fromEntries(I.map(M=>[M,0]));for(let M of Object.values(p.items))E.has(M.status)&&D(p,M)&&(k[M.classOfService??"standard"]+=1);return p={...p,config:{...h(p),classesOfService:d.classesOfService,maxExpedite:d.maxExpedite}},chunkXMO2RCXB_cjs.c(p,"cadence.strategy-review",r.by,{mix:k,before:{classesOfService:n.classesOfService,maxExpedite:n.maxExpedite},after:{classesOfService:d.classesOfService,maxExpedite:d.maxExpedite}},g)})}}}function ye(){return [{id:"service-request-manager",name:"Service Request Manager",modelTier:"large",capabilities:["order-backlog","define-acceptance","manage-flow","escalate"],canApprove:[],inputs:["stakeholder-requests","options"],outputs:["ordered-options","acceptance-criteria","classes-of-service"],do_not:["do not implement items yourself","do not push work past the commitment point outside replenishment"]},{id:"service-delivery-manager",name:"Service Delivery Manager",modelTier:"large",capabilities:["facilitate","manage-flow","escalate"],canApprove:[],inputs:["board","flow-metrics","blockers"],outputs:["cadence-records","wip-and-policy-changes","lessons"],do_not:["do not reorder the options","do not assign work; the planner pulls"]},{id:"worker",name:"Worker",modelTier:"small",capabilities:["deliver","review","verify"],canApprove:[],inputs:["brief"],outputs:["code","test-output"],do_not:["do not change acceptance criteria","do not pull more work while your card is open"]}]}var A=(e,t,a,s,m)=>m?{rule:e,severity:t,item:m,message:a,fix:s}:{rule:e,severity:t,message:a,fix:s},z=e=>e.payload??{},oe=e=>{let t=z(e).items;return Array.isArray(t)?t:[]},Ue=(e,t)=>Object.values(e.items).filter(a=>a.stage===t&&P.has(a.status)).length;function ve(){return [{id:"policy-explicit",severity:"error",check(l,i){let r=l.stages.find(n=>n.deliveryPoint)?.id;if(i.type==="init")return l.stages.filter(n=>n.id!==r&&n.exitPolicy.length===0).map(n=>A("policy-explicit","error",`column "${n.id}" has no explicit policy`,`give column "${n.id}" at least one policy, e.g. { "kind": "acceptance-written" }`));if(i.type==="ceremony.service-delivery-review"){let n=z(i).policies??{};return Object.entries(n).filter(([o,c])=>o!==r&&Array.isArray(c)&&c.length===0).map(([o])=>A("policy-explicit","error",`column "${o}" would be left without a policy`,"keep at least one policy per column; Kanban policies are explicit"))}return []}},{id:"commitment-point-once",severity:"error",check(l,i){if(i.type!=="init")return [];let r=[],n=l.stages.filter(c=>c.commitmentPoint),o=l.stages.filter(c=>c.deliveryPoint);if(n.length!==1&&r.push(A("commitment-point-once","error",`${n.length} columns are marked commitmentPoint (${n.map(c=>c.id).join(", ")||"none"})`,"mark exactly one column commitmentPoint: true")),o.length!==1&&r.push(A("commitment-point-once","error",`${o.length} columns are marked deliveryPoint (${o.map(c=>c.id).join(", ")||"none"})`,"mark exactly one column deliveryPoint: true")),n.length===1&&o.length===1){let c=l.stages.indexOf(n[0]),d=l.stages.indexOf(o[0]);d!==l.stages.length-1&&r.push(A("commitment-point-once","error",`delivery column "${o[0].id}" is not the last column`,"move the delivery column to the end; finished cards leave the board there")),c===0?r.push(A("commitment-point-once","error",`commitment column "${n[0].id}" is the first column`,"keep an Options column before the commitment point; replenishment pulls from it")):c>=d&&r.push(A("commitment-point-once","error",`commitment column "${n[0].id}" comes after the delivery column`,"order columns options \u2192 commitment \u2192 \u2026 \u2192 delivery"));}return r}},{id:"wip-respected",severity:"error",check(l,i){if(i.type==="ceremony.replenishment"){let r=l.stages.find(p=>p.commitmentPoint);if(!r||r.wipLimit===void 0)return [];let n=oe(i),o=Object.values(l.items).filter(p=>p.stage===r.id&&E.has(p.status)).length,c=n.some(p=>l.items[p]?.classOfService==="expedite")?h(l).classesOfService.expedite?.wipBypass??1:0,d=r.wipLimit+c;return o+n.length<=d?[]:[A("wip-respected","error",`column "${r.id}" holds ${o} card(s); pulling ${n.length} more exceeds its WIP limit of ${r.wipLimit}${c?` (+${c} expedite bypass)`:""}`,`pull at most ${Math.max(0,d-o)} card(s) now, or raise the limit in a service-delivery-review`)]}if(i.type==="ceremony.service-delivery-review"){let r=z(i).wip??{},n=[];for(let[o,c]of Object.entries(r)){if(typeof c!="number")continue;let d=Ue(l,o);d>c&&n.push(A("wip-respected","warning",`column "${o}" has ${d} active card(s), above the new limit of ${c}`,"nothing new is pulled into it until it drains; finish or move cards"));}return n}return []}},{id:"pull-not-push",severity:"error",check(l,i){if(i.type!=="ceremony.replenishment")return [];let r=l.stages[0],n=l.stages.find(d=>d.commitmentPoint);if(!r||!n)return [];let o=[],c=z(i).column;c!==void 0&&c!==n.id&&o.push(A("pull-not-push","error",`replenishment may only pull into the commitment column "${n.id}", not "${String(c)}"`,"drop column or set it to the commitment column; later columns are pulled by the planner"));for(let d of oe(i)){let p=l.items[d];p&&(p.stage!==r.id||p.status!=="todo")&&o.push(A("pull-not-push","error",`item "${d}" is ${p.status} in "${p.stage}", not an option`,`only todo cards in "${r.id}" can be pulled; cards already on the board flow by pull`,d));}return o}},{id:"blocker-has-owner",severity:"error",check(l,i){if(!i.type.startsWith("ceremony."))return [];let r=[];if(i.type==="ceremony.operations-review"){let n=z(i).assign??[];for(let o of n)(typeof o.owner!="string"||o.owner.trim()==="")&&r.push(A("blocker-has-owner","error",`blocker "${o.blocker}" on "${o.item}" would have no owner`,"name the role or person who clears it",o.item));}for(let n of Object.values(l.items))for(let o of n.blockers)!o.clearedAt&&o.owner.trim()===""&&r.push(A("blocker-has-owner","warning",`blocker "${o.id}" on "${n.id}" has no owner`,`assign one in operations-review: { "assign": [{ "item": "${n.id}", "blocker": "${o.id}", "owner": "<who>" }] }`,n.id));return r}},{id:"one-expedite",severity:"error",check(l,i){if(i.type!=="ceremony.replenishment")return [];let r=oe(i).filter(c=>l.items[c]?.classOfService==="expedite");if(r.length===0)return [];let n=Object.values(l.items).filter(c=>c.classOfService==="expedite"&&E.has(c.status)&&D(l,c)).map(c=>c.id),o=h(l).maxExpedite;return n.length+r.length<=o?[]:[A("one-expedite","error",`${n.length} expedite card(s) already on the board (${n.join(", ")||"none"}); pulling ${r.join(", ")} exceeds maxExpedite ${o}`,"deliver the current expedite first, reclassify the new card, or raise maxExpedite in a strategy-review")]}},{id:"fixed-date-needs-deadline",severity:"error",check(l,i){return i.type!=="ceremony.replenishment"?[]:oe(i).filter(r=>{let n=l.items[r];return n?.classOfService==="fixed-date"&&!(n.deadline&&Number.isFinite(Date.parse(n.deadline)))}).map(r=>A("fixed-date-needs-deadline","error",`fixed-date item "${r}" has no deadline`,`editItem("${r}", { deadline: "<ISO date>" }) before pulling it`,r))}}]}function be(e){let t=e.columns.map(m=>{let f={id:m.id,name:m.name,entryPolicy:[],exitPolicy:m.policies};return m.wipLimit!==void 0&&(f.wipLimit=m.wipLimit),m.commitmentPoint&&(f.commitmentPoint=true),m.deliveryPoint&&(f.deliveryPoint=true),m.review&&(f.review=true),f}),a=t.findIndex(m=>m.commitmentPoint),s=a>=0?t[a+1]:void 0;return s&&(s.entryPolicy=t[a].exitPolicy),t}var He={backlog:"Options",item:"Work Item",stage:"Column",iteration:"Cadence",increment:"Delivery",ceremony:"Cadence",gate:"Policy"},Ge={expedite:0,"fixed-date":1,standard:2,intangible:3},Be=e=>Ge[e.classOfService??"standard"]??2,ke=1e15,Ze=4e9,ze=(e,t,a)=>Math.min(a,Math.max(t,e));function Qe(e,t){let a=e.classOfService??"standard";if(e.type==="question")return 5*ke;if(a==="fixed-date"&&e.deadline!==void 0){let l=Date.parse(e.deadline);if(Number.isFinite(l))return 3*ke+1e10-Math.floor(l/1e3)}let s=t.aging?Math.floor(t.deferrals/t.maxDeferralRounds):0,m=ze(e.priority??0,-1e9,1e9)+s*Ze,f=t.aging&&t.deferrals>=t.maxDeferralRounds;return (a==="expedite"?4:a==="fixed-date"?3:a==="intangible"&&!f?1:2)*ke+m}function Te(e,t){let a=Be(e)-Be(t);if(a!==0)return a;let s=_(e),m=_(t),f=s===void 0?0:Date.parse(s),y=m===void 0?0:Date.parse(m);return f!==y?f-y:e.id<t.id?-1:e.id>t.id?1:0}function Xe(e){return e.map(t=>t.kind==="evidence"?`evidence ${t.evidenceKind}`:t.kind==="custom"?`${t.id}: ${t.description}`:t.kind).join(", ")||"(none)"}function et(){return {name:"kanban",vocabulary:He,validateConfig:H,defaultStages:be,defaultRoles:ye,requiredCapabilities:["manage-flow","deliver"],exclusiveCapabilities:[],plannerOptions(e){let t=h(e),a=K(e),s=e.stages[e.stages.findIndex(n=>n.id===a.id)+1],m=t.classesOfService.expedite?.wipBypass??1,f=[],y=[0],l=new Map;for(let n of e.events)f.push(Date.parse(n.at)),y.push(y[y.length-1]+(n.type==="planner.resolved"?1:0)),n.type==="item.added"&&l.set(n.payload.id,n.at);let i=n=>{let o=0,c=f.length;for(;o<c;){let d=o+c>>1;f[d]<=n?o=d+1:c=d;}return y[f.length]-y[o]},r={schedulerMode:"throughput",fairnessPolicy:t.fairness.aging?"aging":"none",deadlineStrategy:"earliest-first",dispatchStage:n=>n.stage===a.id&&s?s.id:void 0,priorityOf:n=>{let o=Date.parse(_(n)??l.get(n.id)??"");return Qe(n,{deferrals:i(Number.isFinite(o)?o:0),aging:t.fairness.aging,maxDeferralRounds:t.fairness.maxDeferralRounds})},tieBreaker:Te,wipCounts:[...P],wipLimitOf:(n,o)=>n.wipLimit===void 0?void 0:o.classOfService==="expedite"?n.wipLimit+m:n.wipLimit};return r.maxDeferralRounds=t.fairness.maxDeferralRounds,r},candidates(e){let t=Math.max(0,h(e).maxExpedite-U(e).length),a=Object.values(e.items).filter(m=>(m.status==="todo"||m.status==="review")&&D(e,m)),s=exsorted.timSort(a.filter(m=>m.classOfService==="expedite"),Te).slice(0,t);return a.filter(m=>m.classOfService!=="expedite"||s.includes(m))},invariants(e,t){let a=h(e),s=e.stages.find(l=>l.id===t.stage),m=t.classOfService??"standard",f=a.classesOfService[m]?.sle,y=Object.values(e.items).filter(l=>l.stage===s.id&&P.has(l.status)).length;return [`Column "${s.name}" exit policies: ${Xe(s.exitPolicy)}`,`Class of service: ${m}${t.deadline?`; deadline ${t.deadline}`:""}${f?`; service level p${f.percentile} <= ${f.targetMs} ms`:""}`,`WIP limit of "${s.name}": ${s.wipLimit??"none"} (active now: ${y}); finish this card before pulling another`,`Do not change the scope of "${t.id}" or its acceptance criteria; raise open_questions instead`]},ceremonies:ge(et),rules:ve(),metrics:e=>({...Z(e)}),humanDefaults:{gates:"none"},lockedConfigKeys:["columns","classesOfService"],report:e=>({cadencesDue:le(e)})}}exports.A=pe;exports.B=ge;exports.C=ye;exports.D=ve;exports.E=be;exports.F=He;exports.G=Qe;exports.H=Te;exports.I=et;exports.a=P;exports.b=E;exports.c=se;exports.d=K;exports.e=ee;exports.f=X;exports.g=D;exports.h=U;exports.i=_;exports.j=Y;exports.k=I;exports.l=te;exports.m=h;exports.n=Pe;exports.o=H;exports.p=ne;exports.q=ie;exports.r=qe;exports.s=Ee;exports.t=le;exports.u=re;exports.v=V;exports.w=me;exports.x=Z;exports.y=fe;exports.z=ue;//# sourceMappingURL=chunk-CYXVGHQM.cjs.map
2
- //# sourceMappingURL=chunk-CYXVGHQM.cjs.map
1
+ 'use strict';var chunkEHBQBXWA_cjs=require('./chunk-EHBQBXWA.cjs'),chunkEACZBAP3_cjs=require('./chunk-EACZBAP3.cjs'),chunkS3BXVHO7_cjs=require('./chunk-S3BXVHO7.cjs'),exsorted=require('exsorted');var P=new Set(["in_progress","blocked","awaiting_human"]),E=new Set(["todo","in_progress","blocked","review","awaiting_human"]);function se(e){let t=e.stages[0];return t||chunkS3BXVHO7_cjs.b("config-invalid","kanban board has no columns","init with at least options, a commitment column and a delivery column"),t}function K(e){let t=e.stages.find(a=>a.commitmentPoint);return t||chunkS3BXVHO7_cjs.b("config-invalid","no column is the commitment point","set commitmentPoint: true on exactly one column"),t}function ee(e){let t=e.stages.find(a=>a.deliveryPoint);return t||chunkS3BXVHO7_cjs.b("config-invalid","no column is the delivery point","set deliveryPoint: true on the last column"),t}function X(e,t){return chunkEACZBAP3_cjs.p(e,t),e.stages.findIndex(a=>a.id===t)}function D(e,t){let a=X(e,t.stage);return a>=X(e,K(e).id)&&a<X(e,ee(e).id)}function U(e){return Object.values(e.items).filter(t=>t.classOfService==="expedite"&&P.has(t.status)&&D(e,t)).map(t=>t.id)}function _(e){for(let t=e.transitions.length-1;t>=0;t--){let a=e.transitions[t];if(a.to.stage===e.stage&&a.from.stage!==e.stage)return a.at}}var Y=["replenishment","delivery-planning","service-delivery-review","operations-review","risk-review","strategy-review"],I=["expedite","fixed-date","standard","intangible"],te=864e5;function h(e){return e.config}var Pe=[{id:"options",name:"Options",policies:[{kind:"acceptance-written"}]},{id:"ready",name:"Ready",wipLimit:4,commitmentPoint:true,policies:[{kind:"dependencies-done"}]},{id:"dev",name:"Development",wipLimit:3,policies:[{kind:"evidence",evidenceKind:"test-output"}]},{id:"review",name:"Review",wipLimit:2,review:true,policies:[{kind:"no-open-blockers"}]},{id:"done",name:"Done",deliveryPoint:true,policies:[]}],B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function q(e,t,a,s=1){if(e!==void 0)return (typeof e!="number"||!Number.isFinite(e)||e<s)&&chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.${t} must be a number >= ${s} (got ${JSON.stringify(e)})`,a),e}var Me=["acceptance-written","estimate-present","no-open-blockers","dependencies-done"],ae=e=>typeof e=="string"&&e.trim()!=="";function ce(e,t){Array.isArray(e)||chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.${t} must be an array of Policy objects`,'e.g. [{ "kind": "evidence", "evidenceKind": "test-output" }]');let a=[];return e.forEach((s,m)=>{let f=`kanban config.${t}[${m}]`;B(s)&&(s.kind==="evidence"?ae(s.evidenceKind):s.kind==="custom"?ae(s.id)&&ae(s.description):typeof s.kind=="string"&&Me.includes(s.kind))||chunkS3BXVHO7_cjs.b("config-invalid",`${f} must be a Policy`,`use a Policy such as { "kind": "evidence", "evidenceKind": "test-output" }, { "kind": "custom", "id": "x", "description": "..." } or one of: ${Me.join(", ")}`),a.push(s);}),a}function Ne(e,t){B(e)||chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.columns[${t}] must be an object`,'e.g. { "id": "dev", "policies": [] }'),chunkS3BXVHO7_cjs.c(e.id,`kanban config.columns[${t}].id`);let a=e.id;Array.isArray(e.policies)||chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.columns[${t}] ("${a}") needs policies: Policy[]`,'every column states its policies explicitly, e.g. [{ "kind": "acceptance-written" }]');let s={id:a,name:typeof e.name=="string"&&e.name.trim()!==""?e.name:a,policies:ce(e.policies,`columns[${t}].policies`)},m=q(e.wipLimit,`columns[${t}].wipLimit`,"omit wipLimit for no limit");m!==void 0&&(s.wipLimit=m);for(let f of ["commitmentPoint","deliveryPoint","review"])e[f]!==void 0&&(typeof e[f]!="boolean"&&chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.columns[${t}].${f} must be a boolean`,`set ${f}: true or omit it`),e[f]&&(s[f]=true));return s}function H(e){let t=e??{};t.columns!==void 0&&!Array.isArray(t.columns)&&chunkS3BXVHO7_cjs.b("config-invalid","kanban config.columns must be an array of columns","omit columns for the default board (options, ready, dev, review, done)");let a=t.columns===void 0?Pe.map(o=>({...o})):t.columns.map(Ne),s=new Set;for(let o of a)s.has(o.id)&&chunkS3BXVHO7_cjs.b("config-invalid",`duplicate column id "${o.id}"`,"give every column a unique id"),s.add(o.id);let m={},f=t.classesOfService??{};B(f)||chunkS3BXVHO7_cjs.b("config-invalid","kanban config.classesOfService must be an object keyed by class",'e.g. { "expedite": { "wipBypass": 1 } }');for(let[o,c]of Object.entries(f)){I.includes(o)||chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.classesOfService.${o} is not a class of service`,`use one of: ${I.join(", ")}`),B(c)||chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.classesOfService.${o} must be an object`,'e.g. { "wipBypass": 1, "sle": { "percentile": 85, "targetMs": 604800000 } }');let d={},p=q(c.wipBypass,`classesOfService.${o}.wipBypass`,"omit it for the default 1",0);if(p!==void 0&&(d.wipBypass=p),c.sle!==void 0){let g=c.sle;(!B(g)||typeof g.percentile!="number"||g.percentile<0||g.percentile>100)&&chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.classesOfService.${o}.sle.percentile must be 0..100`,'e.g. { "percentile": 85, "targetMs": 604800000 }');let k=q(g.targetMs,`classesOfService.${o}.sle.targetMs`,"state the service level target in milliseconds");k===void 0&&chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.classesOfService.${o}.sle.targetMs is required`,"state the service level target in milliseconds"),d.sle={percentile:g.percentile,targetMs:k};}m[o]=d;}let y=t.fairness??{};(!B(y)||y.aging!==void 0&&typeof y.aging!="boolean")&&chunkS3BXVHO7_cjs.b("config-invalid","kanban config.fairness must be { aging: boolean, maxDeferralRounds?: number }","omit it for aging on");let l=q(y.maxDeferralRounds,"fairness.maxDeferralRounds","omit it for 5 rounds"),i={aging:y.aging===void 0?true:y.aging,maxDeferralRounds:l??5},r={},n=t.cadences??{};B(n)||chunkS3BXVHO7_cjs.b("config-invalid","kanban config.cadences must be an object keyed by cadence",'e.g. { "replenishment": { "everyTurns": 10 } }');for(let[o,c]of Object.entries(n)){Y.includes(o)||chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.cadences.${o} is not a cadence`,`use one of: ${Y.join(", ")}`),B(c)||chunkS3BXVHO7_cjs.b("config-invalid",`kanban config.cadences.${o} must be an object`,'e.g. { "everyTurns": 10 }');let d=q(c.everyTurns,`cadences.${o}.everyTurns`,"omit it when the cadence is run by hand");r[o]=d===void 0?{}:{everyTurns:d};}return {columns:a,classesOfService:m,fairness:i,cadences:r,throughputWindowMs:q(t.throughputWindowMs,"throughputWindowMs","omit it for one week")??7*te,maxExpedite:q(t.maxExpedite,"maxExpedite","omit it for 1")??1}}function ne(e,t){return e.events.find(s=>s.type==="item.added"&&s.payload.id===t)?.at??e.events[0].at}function ie(e,t,a){return Date.parse(a)-Date.parse(_(t)??ne(e,t.id))}function qe(e,t){return e.stages.map(a=>{let s=Object.values(e.items).filter(l=>l.stage===a.id&&l.status!=="dropped"),m=exsorted.timSort(s.map(l=>({id:l.id,title:l.title,type:l.type,status:l.status,classOfService:l.classOfService??"standard",role:l.role??null,ageMs:ie(e,l,t),blocked:l.blockers.some(i=>!i.clearedAt),deadline:l.deadline??null})),(l,i)=>i.ageMs-l.ageMs||(l.id<i.id?-1:1)),f=m.filter(l=>P.has(l.status)).length,y=m.filter(l=>l.status==="todo"||l.status==="review").length;return {id:a.id,name:a.name,wipLimit:a.wipLimit??null,active:f,queued:y,overLimit:a.wipLimit!==void 0&&f>a.wipLimit,commitmentPoint:a.commitmentPoint===true,deliveryPoint:a.deliveryPoint===true,cards:m}})}var Ee=e=>`cadence.${e}`;function le(e){let t=h(e);return Y.map(a=>{let s=0,m=null;for(let l of e.events)l.type===Ee(a)&&(s=l.seq,m=l.at);let f=e.events.filter(l=>l.type==="item.completed"&&l.seq>s).length,y=t.cadences[a]?.everyTurns??null;return {cadence:a,everyTurns:y,lastAt:m,turnsSince:f,due:y!==null&&f>=y}})}var De=(e,t)=>Date.parse(t)-Date.parse(e),Ie=e=>e.transition??null;function re(e,t,a){let s=new Map,m=[],f=e[0]?.at??"1970-01-01T00:00:00.000Z",y=(i,r,n)=>{r===t&&i.committedAt===void 0&&(i.committedAt=n),r===a&&i.deliveredAt===void 0&&(i.deliveredAt=n);},l=(i,r,n)=>{i.since.status==="in_progress"&&(i.activeMs+=De(i.since.at,n)),i.since.status==="blocked"&&(i.blockedMs+=De(i.since.at,n)),i.since={status:r.status,at:n},r.stage!==i.stage&&(i.stays[i.stays.length-1].leftAt=n,i.stays.push({stage:r.stage,enteredAt:n}),y(i,r.stage,n)),i.stage=r.stage,i.status=r.status;};for(let i of e){f=i.at;let r=i.payload??{};switch(i.type){case "item.added":{let n=r.id,o=r.stage,c={id:n,type:typeof r.type=="string"?r.type:"task",stage:o,status:"todo",stays:[{stage:o,enteredAt:i.at}],classOfService:"standard",activeMs:0,blockedMs:0,since:{status:"todo",at:i.at}};y(c,o,i.at),s.set(n,c);break}case "item.transition":{let n=s.get(r.id);if(!n)break;l(n,r.to,i.at);break}case "cadence.replenishment":{let n=r.items??[];for(let o of n){let c=s.get(o.id);c&&(c.classOfService=o.classOfService,o.deadline?c.deadline=o.deadline:delete c.deadline);}break}case "blocker.raised":{m.push({item:r.id,blocker:r.blocker,raisedAt:i.at});let n=s.get(r.id),o=Ie(r);n&&o&&l(n,o.to,i.at);break}case "blocker.cleared":{let n=m.find(d=>d.item===r.id&&d.blocker===r.blocker&&d.clearedAt===void 0);n&&(n.clearedAt=i.at);let o=s.get(r.id),c=Ie(r);o&&c&&l(o,c.to,i.at);break}}}return {items:s,blockers:m,lastAt:f}}function V(e,t){if(e.length===0)return 0;let a=exsorted.timSort([...e],(m,f)=>m-f),s=Math.min(a.length,Math.max(1,Math.ceil(t/100*a.length)));return a[s-1]}var G=(e,t)=>Date.parse(t)-Date.parse(e),We=(e,t)=>t===0?0:e/t;function je(e){let t=e.stages.find(s=>s.commitmentPoint)?.id??"",a=e.stages.find(s=>s.deliveryPoint)?.id??"";return {commitment:t,delivery:a,ci:e.stages.findIndex(s=>s.id===t),di:e.stages.findIndex(s=>s.id===a)}}function Le(e){let t={};for(let a of e.items.values())for(let s of a.stays)s.leftAt!==void 0&&(t[s.stage]??=[]).push(G(s.enteredAt,s.leftAt));return t}function me(e){let t=je(e);return Le(re(e.events,t.commitment,t.delivery))}function Z(e){let t=h(e),a=je(e),s=re(e.events,a.commitment,a.delivery),m=[...s.items.values()],f=e.stages.map(u=>u.id),y=new Map(f.map((u,v)=>[u,v])),l=exsorted.timSort(m.filter(u=>u.type!=="question"&&u.committedAt!==void 0&&u.deliveredAt!==void 0),(u,v)=>Date.parse(u.deliveredAt)-Date.parse(v.deliveredAt)),i=l.map(u=>G(u.committedAt,u.deliveredAt)),r={};for(let[u,v]of Object.entries(Le(s)))r[u]=v.reduce((w,x)=>w+x,0)/v.length;let n=m.filter(u=>u.type!=="question"&&u.committedAt!==void 0).map(u=>Date.parse(u.committedAt)),o=[];if(n.length>0){let u=n.reduce((w,x)=>x<w?x:w,n[0]),v=Math.floor((Date.parse(s.lastAt)-u)/t.throughputWindowMs)+1;o=Array.from({length:v},()=>0);for(let w of l){let x=Math.floor((Date.parse(w.deliveredAt)-u)/t.throughputWindowMs);x>=0&&x<v&&(o[x]+=1);}}let c=Object.fromEntries(f.map(u=>[u,0])),d={};for(let u of m){if(!E.has(u.status))continue;Object.hasOwn(c,u.stage)&&(c[u.stage]+=1);let v=y.get(u.stage);v!==void 0&&v>=a.ci&&v<a.di&&(d[u.id]=G(u.stays[u.stays.length-1].enteredAt,s.lastAt));}let p=new Map;for(let u of m)for(let v of u.stays){let w=p.get(v.stage)??new Map;w.has(u.id)||w.set(u.id,v.enteredAt),p.set(v.stage,w);}let g=exsorted.timSort([...new Set(e.events.map(u=>u.at.slice(0,10)))],(u,v)=>u<v?-1:u>v?1:0),k={};for(let u of g)for(let v of f)k[`${u}:${v}`]=[...p.get(v)?.values()??[]].filter(w=>w.slice(0,10)<=u).length;let M={};for(let[u,v]of Object.entries(t.classesOfService)){if(!v?.sle)continue;let w=l.filter(x=>x.classOfService===u);w.length!==0&&(M[u]=w.filter(x=>G(x.committedAt,x.deliveredAt)<=v.sle.targetMs).length/w.length);}let C=s.blockers.reduce((u,v)=>u+G(v.raisedAt,v.clearedAt??s.lastAt),0);return {leadTimeMs:i,leadTimeP50:V(i,50),leadTimeP85:V(i,85),cycleTimeMsByColumn:r,throughput:o,wipByColumn:c,flowEfficiency:We(l.reduce((u,v)=>u+v.activeMs,0),i.reduce((u,v)=>u+v,0)),agingWipMs:d,cumulativeFlow:k,sleCompliance:M,blockerTimeMs:C,meanBlockerTimeMs:We(C,s.blockers.length)}}function fe(e,t){let a=Date.parse(t),s=me(e),m=[],f=[],y=Object.fromEntries(e.stages.map(i=>[i.id,0])),l=Object.fromEntries(e.stages.map(i=>[i.id,0]));for(let i of Object.values(e.items)){for(let r of i.blockers)r.clearedAt||m.push({item:i.id,blocker:r.id,owner:r.owner,reason:r.reason,ageMs:a-Date.parse(r.raisedAt)});if(P.has(i.status)?l[i.stage]=(l[i.stage]??0)+1:(i.status==="todo"||i.status==="review")&&(y[i.stage]=(y[i.stage]??0)+1),E.has(i.status)&&D(e,i)){let r=s[i.stage]??[],n=r.length?V(r,85):null,o=ie(e,i,t);f.push({item:i.id,column:i.stage,status:i.status,ageMs:o,p85Ms:n,overP85:n!==null&&o>n});}}return {blockers:m,agingWip:exsorted.timSort(f,(i,r)=>r.ageMs-i.ageMs||(i.item<r.item?-1:1)),queued:y,active:l}}function Fe(e,t){let a=K(e).id;return e.items[t].transitions.find(f=>f.to.stage===a&&f.from.stage!==a)?.at??ne(e,t)}function ue(e,t,a){let s=Date.parse(t),m=h(e),f=Z(e).leadTimeMs,y=m.classesOfService["fixed-date"]?.sle?.percentile??85,l=f.length?V(f,y):null,i=[],r=[];for(let n of Object.values(e.items)){for(let p of n.blockers){let g=p.clearedAt?0:s-Date.parse(p.raisedAt);!p.clearedAt&&g>a&&r.push({item:n.id,blocker:p.id,owner:p.owner,ageMs:g});}if(n.classOfService!=="fixed-date"||!n.deadline||!E.has(n.status)||!D(e,n))continue;let o=s-Date.parse(Fe(e,n.id)),c=l===null?null:Math.max(0,l-o),d=Date.parse(n.deadline)-s;i.push({item:n.id,deadline:n.deadline,timeLeftMs:d,projectedRemainingMs:c,atRisk:d<0||c!==null&&c>d});}return {fixedDate:i,staleBlockers:r,expediteActive:U(e)}}var F=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function pe(e,t,a){let s=t.items;(!Array.isArray(s)||s.length===0||!s.every(f=>typeof f=="string"))&&chunkS3BXVHO7_cjs.b("invalid-input",`${a} needs items: string[]`,'pass ["A", "B"]');let m=s.find((f,y)=>s.indexOf(f)!==y);m!==void 0&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${m}" appears twice in items[]`,"list each item once",{items:[m]});for(let f of s)chunkEACZBAP3_cjs.u(e,f);return s}function Je(e){return F(e)&&typeof e.percentile=="number"&&e.percentile>=0&&e.percentile<=100&&typeof e.targetMs=="number"&&Number.isFinite(e.targetMs)&&e.targetMs>0}function Ke(e,t){let{wipLimit:a,...s}=e;return t===null?s:{...s,wipLimit:t}}function ge(e){let t=(i,r,n,o)=>chunkEACZBAP3_cjs.W(i,e(),{type:r,by:n.by,payload:n},c=>o(c,chunkEACZBAP3_cjs.a(n.now)));return {replenishment:(i,r)=>{chunkEACZBAP3_cjs.o(i,r.by,"order-backlog","manage-flow");let n=pe(i,r,"replenishment"),o=K(i),c=se(i);for(let d of n)chunkEACZBAP3_cjs.E(i,chunkEACZBAP3_cjs.u(i,d),c.exitPolicy,`leave "${c.id}"`);return t(i,"ceremony.replenishment",r,(d,p)=>{for(let g of n)d=chunkEACZBAP3_cjs.x(d,g,{stage:o.id,status:"todo"},r.by,p);return chunkEACZBAP3_cjs.c(d,"cadence.replenishment",r.by,{column:o.id,items:n.map(g=>{let k=chunkEACZBAP3_cjs.u(d,g);return {id:g,classOfService:k.classOfService??"standard",deadline:k.deadline??null}})},p)})},"delivery-planning":(i,r)=>{chunkEACZBAP3_cjs.o(i,r.by,"facilitate","manage-flow");let n=pe(i,r,"delivery-planning"),o=ee(i),c=i.stages[i.stages.findIndex(d=>d.id===o.id)-1];for(let d of n){let p=chunkEACZBAP3_cjs.u(i,d);p.stage!==c.id&&p.stage!==o.id&&chunkS3BXVHO7_cjs.b("invalid-input",`item "${d}" is in "${p.stage}", not ready for delivery`,`only cards in "${c.id}" or "${o.id}" can be planned for delivery`,{items:[d]});}return t(i,"ceremony.delivery-planning",r,(d,p)=>chunkEACZBAP3_cjs.c(d,"cadence.delivery-planning",r.by,{items:n,window:typeof r.window=="string"?r.window:null,delivered:n.filter(g=>chunkEACZBAP3_cjs.u(d,g).status==="done")},p))},"service-delivery-review":(i,r)=>{chunkEACZBAP3_cjs.o(i,r.by,"manage-flow");let n=r.wip??{},o=r.policies??{},c=r.sle??{};(!F(n)||!F(o)||!F(c))&&chunkS3BXVHO7_cjs.b("invalid-input","service-delivery-review takes wip, policies and sle objects keyed by column or class",'e.g. { "wip": { "dev": 2 }, "policies": { "dev": [{ "kind": "no-open-blockers" }] }, "sle": { "standard": { "percentile": 85, "targetMs": 604800000 } } }');for(let[g,k]of Object.entries(n))chunkEACZBAP3_cjs.p(i,g),k!==null&&(typeof k!="number"||!Number.isFinite(k)||k<1)&&chunkS3BXVHO7_cjs.b("invalid-input",`wip.${g} must be a positive number or null`,"null removes the limit");let d={};for(let[g,k]of Object.entries(o))chunkEACZBAP3_cjs.p(i,g),d[g]=ce(k,`policies.${g}`);for(let[g,k]of Object.entries(c))I.includes(g)||chunkS3BXVHO7_cjs.b("invalid-input",`sle.${g} is not a class of service`,`use one of: ${I.join(", ")}`),k!==null&&!Je(k)&&chunkS3BXVHO7_cjs.b("invalid-input",`sle.${g} must be { percentile: 0..100, targetMs: > 0 } or null`,"null removes the service level");let p=chunkEHBQBXWA_cjs.a(i,r,"service-delivery-review");return t(i,"ceremony.service-delivery-review",r,(g,k)=>{let M=h(g),C=g.stages,u=M.columns,v={...M.classesOfService},w=[],x=[],we=[];for(let[S,O]of Object.entries(n)){let W=C.find(R=>R.id===S).wipLimit??null;W!==O&&(w.push({column:S,before:W,after:O}),C=C.map(R=>R.id===S?Ke(R,O):R),u=u.map(R=>R.id===S?Ke(R,O):R));}for(let[S,O]of Object.entries(d)){let W=C.find($=>$.id===S).exitPolicy;if(JSON.stringify(W)===JSON.stringify(O))continue;x.push({column:S,before:W,after:O});let R=C.findIndex($=>$.id===S),Q=C[R].commitmentPoint?C[R+1]?.id:void 0;C=C.map($=>$.id===S?{...$,exitPolicy:O}:$.id===Q?{...$,entryPolicy:O}:$),u=u.map($=>$.id===S?{...$,policies:O}:$);}for(let[S,O]of Object.entries(c)){let W=v[S]?.sle??null;if(JSON.stringify(W)===JSON.stringify(O))continue;we.push({classOfService:S,before:W,after:O});let{sle:R,...Q}=v[S]??{};v={...v,[S]:O===null?Q:{...Q,sle:O}};}g={...g,stages:C,config:{...M,columns:u,classesOfService:v}};let T=chunkEHBQBXWA_cjs.b(g,p,r.by,k);return chunkEACZBAP3_cjs.c(T.state,"cadence.service-delivery-review",r.by,{wip:w,policies:x,sle:we,lessons:T.created,adopted:T.adopted.slice(T.created.length),dismissed:T.dismissed,agreements:T.agreements,retired:T.retired},k)})},"operations-review":(i,r)=>{chunkEACZBAP3_cjs.o(i,r.by,"facilitate","manage-flow");let n=r.assign??[];(!Array.isArray(n)||!n.every(o=>F(o)&&typeof o.item=="string"&&typeof o.blocker=="string"))&&chunkS3BXVHO7_cjs.b("invalid-input","operations-review.assign must be [{ item, blocker, owner }]",'e.g. { "assign": [{ "item": "A", "blocker": "A-b1", "owner": "service-delivery-manager" }] }');for(let o of n){let c=chunkEACZBAP3_cjs.u(i,o.item);c.blockers.some(d=>d.id===o.blocker&&!d.clearedAt)||chunkS3BXVHO7_cjs.b("invalid-input",`item "${o.item}" has no open blocker "${o.blocker}"`,`open blockers: ${c.blockers.filter(d=>!d.clearedAt).map(d=>d.id).join(", ")||"(none)"}`,{items:[o.item]});}return t(i,"ceremony.operations-review",r,(o,c)=>{for(let d of n){let p=chunkEACZBAP3_cjs.u(o,d.item).blockers.find(g=>g.id===d.blocker).owner;o=chunkEACZBAP3_cjs.s(o,d.item,g=>({...g,blockers:g.blockers.map(k=>k.id===d.blocker?{...k,owner:d.owner}:k)})),o=chunkEACZBAP3_cjs.c(o,"blocker.reassigned",r.by,{id:d.item,blocker:d.blocker,from:p,to:d.owner},c);}return chunkEACZBAP3_cjs.c(o,"cadence.operations-review",r.by,fe(o,c),c)})},"risk-review":(i,r)=>{chunkEACZBAP3_cjs.o(i,r.by,"facilitate","manage-flow");let n=r.staleAfterMs??7*te;return (typeof n!="number"||!Number.isFinite(n)||n<0)&&chunkS3BXVHO7_cjs.b("invalid-input","risk-review.staleAfterMs must be a non-negative number of milliseconds","omit it for one week"),t(i,"ceremony.risk-review",r,(o,c)=>chunkEACZBAP3_cjs.c(o,"cadence.risk-review",r.by,ue(o,c,n),c))},"strategy-review":(i,r)=>{chunkEACZBAP3_cjs.o(i,r.by,"manage-flow");let n=h(i),o=r.classesOfService??{};F(o)||chunkS3BXVHO7_cjs.b("invalid-input","strategy-review.classesOfService must be an object keyed by class",'e.g. { "expedite": { "wipBypass": 2 }, "intangible": null }');let c={...n.classesOfService};for(let[p,g]of Object.entries(o))I.includes(p)||chunkS3BXVHO7_cjs.b("invalid-input",`classesOfService.${p} is not a class of service`,`use one of: ${I.join(", ")}`),g===null?delete c[p]:c[p]=g;let d=H({...n,classesOfService:c,maxExpedite:r.maxExpedite??n.maxExpedite});return t(i,"ceremony.strategy-review",r,(p,g)=>{let k=Object.fromEntries(I.map(M=>[M,0]));for(let M of Object.values(p.items))E.has(M.status)&&D(p,M)&&(k[M.classOfService??"standard"]+=1);return p={...p,config:{...h(p),classesOfService:d.classesOfService,maxExpedite:d.maxExpedite}},chunkEACZBAP3_cjs.c(p,"cadence.strategy-review",r.by,{mix:k,before:{classesOfService:n.classesOfService,maxExpedite:n.maxExpedite},after:{classesOfService:d.classesOfService,maxExpedite:d.maxExpedite}},g)})}}}function ye(){return [{id:"service-request-manager",name:"Service Request Manager",modelTier:"large",capabilities:["order-backlog","define-acceptance","manage-flow","escalate"],canApprove:[],inputs:["stakeholder-requests","options"],outputs:["ordered-options","acceptance-criteria","classes-of-service"],do_not:["do not implement items yourself","do not push work past the commitment point outside replenishment"]},{id:"service-delivery-manager",name:"Service Delivery Manager",modelTier:"large",capabilities:["facilitate","manage-flow","escalate"],canApprove:[],inputs:["board","flow-metrics","blockers"],outputs:["cadence-records","wip-and-policy-changes","lessons"],do_not:["do not reorder the options","do not assign work; the planner pulls"]},{id:"worker",name:"Worker",modelTier:"small",capabilities:["deliver","review","verify"],canApprove:[],inputs:["brief"],outputs:["code","test-output"],do_not:["do not change acceptance criteria","do not pull more work while your card is open"]}]}var A=(e,t,a,s,m)=>m?{rule:e,severity:t,item:m,message:a,fix:s}:{rule:e,severity:t,message:a,fix:s},z=e=>e.payload??{},oe=e=>{let t=z(e).items;return Array.isArray(t)?t:[]},Ue=(e,t)=>Object.values(e.items).filter(a=>a.stage===t&&P.has(a.status)).length;function ve(){return [{id:"policy-explicit",severity:"error",check(l,i){let r=l.stages.find(n=>n.deliveryPoint)?.id;if(i.type==="init")return l.stages.filter(n=>n.id!==r&&n.exitPolicy.length===0).map(n=>A("policy-explicit","error",`column "${n.id}" has no explicit policy`,`give column "${n.id}" at least one policy, e.g. { "kind": "acceptance-written" }`));if(i.type==="ceremony.service-delivery-review"){let n=z(i).policies??{};return Object.entries(n).filter(([o,c])=>o!==r&&Array.isArray(c)&&c.length===0).map(([o])=>A("policy-explicit","error",`column "${o}" would be left without a policy`,"keep at least one policy per column; Kanban policies are explicit"))}return []}},{id:"commitment-point-once",severity:"error",check(l,i){if(i.type!=="init")return [];let r=[],n=l.stages.filter(c=>c.commitmentPoint),o=l.stages.filter(c=>c.deliveryPoint);if(n.length!==1&&r.push(A("commitment-point-once","error",`${n.length} columns are marked commitmentPoint (${n.map(c=>c.id).join(", ")||"none"})`,"mark exactly one column commitmentPoint: true")),o.length!==1&&r.push(A("commitment-point-once","error",`${o.length} columns are marked deliveryPoint (${o.map(c=>c.id).join(", ")||"none"})`,"mark exactly one column deliveryPoint: true")),n.length===1&&o.length===1){let c=l.stages.indexOf(n[0]),d=l.stages.indexOf(o[0]);d!==l.stages.length-1&&r.push(A("commitment-point-once","error",`delivery column "${o[0].id}" is not the last column`,"move the delivery column to the end; finished cards leave the board there")),c===0?r.push(A("commitment-point-once","error",`commitment column "${n[0].id}" is the first column`,"keep an Options column before the commitment point; replenishment pulls from it")):c>=d&&r.push(A("commitment-point-once","error",`commitment column "${n[0].id}" comes after the delivery column`,"order columns options \u2192 commitment \u2192 \u2026 \u2192 delivery"));}return r}},{id:"wip-respected",severity:"error",check(l,i){if(i.type==="ceremony.replenishment"){let r=l.stages.find(p=>p.commitmentPoint);if(!r||r.wipLimit===void 0)return [];let n=oe(i),o=Object.values(l.items).filter(p=>p.stage===r.id&&E.has(p.status)).length,c=n.some(p=>l.items[p]?.classOfService==="expedite")?h(l).classesOfService.expedite?.wipBypass??1:0,d=r.wipLimit+c;return o+n.length<=d?[]:[A("wip-respected","error",`column "${r.id}" holds ${o} card(s); pulling ${n.length} more exceeds its WIP limit of ${r.wipLimit}${c?` (+${c} expedite bypass)`:""}`,`pull at most ${Math.max(0,d-o)} card(s) now, or raise the limit in a service-delivery-review`)]}if(i.type==="ceremony.service-delivery-review"){let r=z(i).wip??{},n=[];for(let[o,c]of Object.entries(r)){if(typeof c!="number")continue;let d=Ue(l,o);d>c&&n.push(A("wip-respected","warning",`column "${o}" has ${d} active card(s), above the new limit of ${c}`,"nothing new is pulled into it until it drains; finish or move cards"));}return n}return []}},{id:"pull-not-push",severity:"error",check(l,i){if(i.type!=="ceremony.replenishment")return [];let r=l.stages[0],n=l.stages.find(d=>d.commitmentPoint);if(!r||!n)return [];let o=[],c=z(i).column;c!==void 0&&c!==n.id&&o.push(A("pull-not-push","error",`replenishment may only pull into the commitment column "${n.id}", not "${String(c)}"`,"drop column or set it to the commitment column; later columns are pulled by the planner"));for(let d of oe(i)){let p=l.items[d];p&&(p.stage!==r.id||p.status!=="todo")&&o.push(A("pull-not-push","error",`item "${d}" is ${p.status} in "${p.stage}", not an option`,`only todo cards in "${r.id}" can be pulled; cards already on the board flow by pull`,d));}return o}},{id:"blocker-has-owner",severity:"error",check(l,i){if(!i.type.startsWith("ceremony."))return [];let r=[];if(i.type==="ceremony.operations-review"){let n=z(i).assign??[];for(let o of n)(typeof o.owner!="string"||o.owner.trim()==="")&&r.push(A("blocker-has-owner","error",`blocker "${o.blocker}" on "${o.item}" would have no owner`,"name the role or person who clears it",o.item));}for(let n of Object.values(l.items))for(let o of n.blockers)!o.clearedAt&&o.owner.trim()===""&&r.push(A("blocker-has-owner","warning",`blocker "${o.id}" on "${n.id}" has no owner`,`assign one in operations-review: { "assign": [{ "item": "${n.id}", "blocker": "${o.id}", "owner": "<who>" }] }`,n.id));return r}},{id:"one-expedite",severity:"error",check(l,i){if(i.type!=="ceremony.replenishment")return [];let r=oe(i).filter(c=>l.items[c]?.classOfService==="expedite");if(r.length===0)return [];let n=Object.values(l.items).filter(c=>c.classOfService==="expedite"&&E.has(c.status)&&D(l,c)).map(c=>c.id),o=h(l).maxExpedite;return n.length+r.length<=o?[]:[A("one-expedite","error",`${n.length} expedite card(s) already on the board (${n.join(", ")||"none"}); pulling ${r.join(", ")} exceeds maxExpedite ${o}`,"deliver the current expedite first, reclassify the new card, or raise maxExpedite in a strategy-review")]}},{id:"fixed-date-needs-deadline",severity:"error",check(l,i){return i.type!=="ceremony.replenishment"?[]:oe(i).filter(r=>{let n=l.items[r];return n?.classOfService==="fixed-date"&&!(n.deadline&&Number.isFinite(Date.parse(n.deadline)))}).map(r=>A("fixed-date-needs-deadline","error",`fixed-date item "${r}" has no deadline`,`editItem("${r}", { deadline: "<ISO date>" }) before pulling it`,r))}}]}function be(e){let t=e.columns.map(m=>{let f={id:m.id,name:m.name,entryPolicy:[],exitPolicy:m.policies};return m.wipLimit!==void 0&&(f.wipLimit=m.wipLimit),m.commitmentPoint&&(f.commitmentPoint=true),m.deliveryPoint&&(f.deliveryPoint=true),m.review&&(f.review=true),f}),a=t.findIndex(m=>m.commitmentPoint),s=a>=0?t[a+1]:void 0;return s&&(s.entryPolicy=t[a].exitPolicy),t}var He={backlog:"Options",item:"Work Item",stage:"Column",iteration:"Cadence",increment:"Delivery",ceremony:"Cadence",gate:"Policy"},Ge={expedite:0,"fixed-date":1,standard:2,intangible:3},Be=e=>Ge[e.classOfService??"standard"]??2,ke=1e15,Ze=4e9,ze=(e,t,a)=>Math.min(a,Math.max(t,e));function Qe(e,t){let a=e.classOfService??"standard";if(e.type==="question")return 5*ke;if(a==="fixed-date"&&e.deadline!==void 0){let l=Date.parse(e.deadline);if(Number.isFinite(l))return 3*ke+1e10-Math.floor(l/1e3)}let s=t.aging?Math.floor(t.deferrals/t.maxDeferralRounds):0,m=ze(e.priority??0,-1e9,1e9)+s*Ze,f=t.aging&&t.deferrals>=t.maxDeferralRounds;return (a==="expedite"?4:a==="fixed-date"?3:a==="intangible"&&!f?1:2)*ke+m}function Te(e,t){let a=Be(e)-Be(t);if(a!==0)return a;let s=_(e),m=_(t),f=s===void 0?0:Date.parse(s),y=m===void 0?0:Date.parse(m);return f!==y?f-y:e.id<t.id?-1:e.id>t.id?1:0}function Xe(e){return e.map(t=>t.kind==="evidence"?`evidence ${t.evidenceKind}`:t.kind==="custom"?`${t.id}: ${t.description}`:t.kind).join(", ")||"(none)"}function et(){return {name:"kanban",vocabulary:He,validateConfig:H,defaultStages:be,defaultRoles:ye,requiredCapabilities:["manage-flow","deliver"],exclusiveCapabilities:[],plannerOptions(e){let t=h(e),a=K(e),s=e.stages[e.stages.findIndex(n=>n.id===a.id)+1],m=t.classesOfService.expedite?.wipBypass??1,f=[],y=[0],l=new Map;for(let n of e.events)f.push(Date.parse(n.at)),y.push(y[y.length-1]+(n.type==="planner.resolved"?1:0)),n.type==="item.added"&&l.set(n.payload.id,n.at);let i=n=>{let o=0,c=f.length;for(;o<c;){let d=o+c>>1;f[d]<=n?o=d+1:c=d;}return y[f.length]-y[o]},r={schedulerMode:"throughput",fairnessPolicy:t.fairness.aging?"aging":"none",deadlineStrategy:"earliest-first",dispatchStage:n=>n.stage===a.id&&s?s.id:void 0,priorityOf:n=>{let o=Date.parse(_(n)??l.get(n.id)??"");return Qe(n,{deferrals:i(Number.isFinite(o)?o:0),aging:t.fairness.aging,maxDeferralRounds:t.fairness.maxDeferralRounds})},tieBreaker:Te,wipCounts:[...P],wipLimitOf:(n,o)=>n.wipLimit===void 0?void 0:o.classOfService==="expedite"?n.wipLimit+m:n.wipLimit};return r.maxDeferralRounds=t.fairness.maxDeferralRounds,r},candidates(e){let t=Math.max(0,h(e).maxExpedite-U(e).length),a=Object.values(e.items).filter(m=>(m.status==="todo"||m.status==="review")&&D(e,m)),s=exsorted.timSort(a.filter(m=>m.classOfService==="expedite"),Te).slice(0,t);return a.filter(m=>m.classOfService!=="expedite"||s.includes(m))},invariants(e,t){let a=h(e),s=e.stages.find(l=>l.id===t.stage),m=t.classOfService??"standard",f=a.classesOfService[m]?.sle,y=Object.values(e.items).filter(l=>l.stage===s.id&&P.has(l.status)).length;return [`Column "${s.name}" exit policies: ${Xe(s.exitPolicy)}`,`Class of service: ${m}${t.deadline?`; deadline ${t.deadline}`:""}${f?`; service level p${f.percentile} <= ${f.targetMs} ms`:""}`,`WIP limit of "${s.name}": ${s.wipLimit??"none"} (active now: ${y}); finish this card before pulling another`,`Do not change the scope of "${t.id}" or its acceptance criteria; raise open_questions instead`]},ceremonies:ge(et),rules:ve(),metrics:e=>({...Z(e)}),humanDefaults:{gates:"none"},lockedConfigKeys:["columns","classesOfService"],report:e=>({cadencesDue:le(e)})}}exports.A=pe;exports.B=ge;exports.C=ye;exports.D=ve;exports.E=be;exports.F=He;exports.G=Qe;exports.H=Te;exports.I=et;exports.a=P;exports.b=E;exports.c=se;exports.d=K;exports.e=ee;exports.f=X;exports.g=D;exports.h=U;exports.i=_;exports.j=Y;exports.k=I;exports.l=te;exports.m=h;exports.n=Pe;exports.o=H;exports.p=ne;exports.q=ie;exports.r=qe;exports.s=Ee;exports.t=le;exports.u=re;exports.v=V;exports.w=me;exports.x=Z;exports.y=fe;exports.z=ue;//# sourceMappingURL=chunk-YJQ5YJ7S.cjs.map
2
+ //# sourceMappingURL=chunk-YJQ5YJ7S.cjs.map