@a-company/paradigm 7.1.0 → 7.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/dist/{accept-orchestration-WMGFGYDK.js → accept-orchestration-JA3A3TSU.js} +1 -1
  2. package/dist/add-CBDU23S2.js +12 -0
  3. package/dist/{aggregate-KZICPVT3.js → aggregate-H7SB2UYT.js} +1 -1
  4. package/dist/{ambient-HAXPDIWK.js → ambient-TFLZFV5Y.js} +1 -1
  5. package/dist/ambient-VCTUHHIG.js +2 -0
  6. package/dist/arch-loader-YVOS3QRY.js +2 -0
  7. package/dist/{beacon-52EWNZPK.js → beacon-WVN264OT.js} +1 -1
  8. package/dist/calibrate-SH6PRZFD.js +2 -0
  9. package/dist/calibration-aggregate-5IVXSBDP.js +2 -0
  10. package/dist/calibration-aggregate-DUEE3LL2.js +4 -0
  11. package/dist/captain-ILBN2IKJ.js +2 -0
  12. package/dist/captain-J4FZ5PRU.js +2 -0
  13. package/dist/{chunk-QDP4G53M.js → chunk-27EK3OQZ.js} +4 -4
  14. package/dist/{chunk-KP5VOYAH.js → chunk-3F4QP2Z5.js} +1 -1
  15. package/dist/{chunk-VPNJL4LS.js → chunk-5VR7FKS5.js} +1 -1
  16. package/dist/{chunk-S3UVQ5RV.js → chunk-6VZSOQ7Y.js} +1 -1
  17. package/dist/chunk-7BZPDOOQ.js +25 -0
  18. package/dist/{chunk-YQK3XU63.js → chunk-7HUPVOAY.js} +12 -12
  19. package/dist/chunk-A5EEY6NO.js +3 -0
  20. package/dist/{chunk-4GC35IFF.js → chunk-D6BSCELB.js} +1 -1
  21. package/dist/{chunk-G6DK3ND3.js → chunk-DH7QVZDI.js} +9 -0
  22. package/dist/chunk-FG3M6VVO.js +30 -0
  23. package/dist/chunk-FNYYQNJY.js +2 -0
  24. package/dist/{chunk-RDWWSQGH.js → chunk-IBKCMLOW.js} +14 -14
  25. package/dist/chunk-K6TLYNRQ.js +7 -0
  26. package/dist/{chunk-W4BW7GXA.js → chunk-KA6QEI3C.js} +1 -1
  27. package/dist/chunk-L3AOKDMU.js +93 -0
  28. package/dist/chunk-M7JHVVDW.js +6 -0
  29. package/dist/chunk-MBKTVQS2.js +2 -0
  30. package/dist/chunk-NFN5UUJB.js +2 -0
  31. package/dist/chunk-O4ADSTSY.js +504 -0
  32. package/dist/chunk-RPGSQQTS.js +2 -0
  33. package/dist/chunk-RQHZUPLO.js +4 -0
  34. package/dist/chunk-SD3KVW5Q.js +2 -0
  35. package/dist/chunk-VKVVIN6J.js +25 -0
  36. package/dist/chunk-VOPJ47QY.js +2 -0
  37. package/dist/chunk-VR2LLUYE.js +17 -0
  38. package/dist/chunk-WMTES556.js +2 -0
  39. package/dist/chunk-XBK244QR.js +6 -0
  40. package/dist/{chunk-MBSY57RN.js → chunk-Y76OIMDO.js} +1 -1
  41. package/dist/{chunk-EG22HDXI.js → chunk-YNFF7XHV.js} +12 -12
  42. package/dist/chunk-YYRP7FLC.js +2 -0
  43. package/dist/{compliance-4P3EE5OA.js → compliance-3M6COUCO.js} +3 -3
  44. package/dist/{constellation-RHZAEFV7.js → constellation-TIKNCZWR.js} +1 -1
  45. package/dist/{cost-24UZSS2P.js → cost-VTHZQKO4.js} +2 -2
  46. package/dist/{diff-VBVIUNL5.js → diff-NZSJW3V3.js} +1 -1
  47. package/dist/dist-6TDAY6TQ-HMSTBL57.js +39 -0
  48. package/dist/{dist-TNE4GFT7.js → dist-PW5YPGFF.js} +1 -1
  49. package/dist/{docs-NTP6UENF.js → docs-DWU3T2BV.js} +1 -1
  50. package/dist/github-GI3HX3N5.js +4 -0
  51. package/dist/{habits-BX2IRSUI.js → habits-UA7YT3CG.js} +3 -3
  52. package/dist/{hooks-AXBWYJ5V.js → hooks-XXJ7CSGJ.js} +1 -1
  53. package/dist/index.js +9 -9
  54. package/dist/{init-F4MSKZIW.js → init-QPMLEQWQ.js} +1 -1
  55. package/dist/{integrity-7TKX3DZ4.js → integrity-FRGF5BFS.js} +1 -1
  56. package/dist/lint-Y4P3MHBV.js +26 -0
  57. package/dist/list-5XRLWD7K.js +12 -0
  58. package/dist/mcp.js +1 -1
  59. package/dist/{migrate-5M4KUQ2L.js → migrate-LIVXILOO.js} +1 -1
  60. package/dist/nomination-engine-EFXDEPZN.js +2 -0
  61. package/dist/{orchestrate-MLUGQOEJ.js → orchestrate-C7SI4J7C.js} +1 -1
  62. package/dist/orchestration-4MJKBSGM.js +2 -0
  63. package/dist/orchestration-S2ESNKSA.js +2 -0
  64. package/dist/platform-server-IOWHNS7Q.js +25 -0
  65. package/dist/{probe-27ARJKRO.js → probe-G3TKOJYW.js} +1 -1
  66. package/dist/quiz-QKIKAVL7.js +10 -0
  67. package/dist/registry-NEW4OJ44.js +2 -0
  68. package/dist/{reindex-ZLDQBFUR.js → reindex-G2JLIGOQ.js} +1 -1
  69. package/dist/reindex-JR3PXYQE.js +2 -0
  70. package/dist/remember-KZYAY77S.js +14 -0
  71. package/dist/{review-BRO2UP4M.js → review-WHRNLW2W.js} +1 -1
  72. package/dist/{ripple-KCVDS3WE.js → ripple-B6U7263T.js} +1 -1
  73. package/dist/{sentinel-EFPEX246.js → sentinel-RIEQWALQ.js} +1 -1
  74. package/dist/{sentinel-bridge-UR2MKARY.js → sentinel-bridge-D4LFDFCH.js} +1 -1
  75. package/dist/{serve-2PKJP65E.js → serve-6RNZYK2I.js} +2 -2
  76. package/dist/serve-PWAFVYYC.js +9 -0
  77. package/dist/{server-4D77LCST.js → server-K7G3IHR3.js} +1 -1
  78. package/dist/{setup-5V2AGLQ6.js → setup-L5OP24US.js} +3 -3
  79. package/dist/{shift-PM4GI736.js → shift-HGXZ5THV.js} +3 -3
  80. package/dist/{show-N5LGB5B2.js → show-VXNGIJE4.js} +3 -3
  81. package/dist/{snapshot-YMX5QRBM.js → snapshot-MT5L6XE4.js} +1 -1
  82. package/dist/status-45KIG32R.js +6 -0
  83. package/dist/{status-3GJXI4IK.js → status-4QGKLOP6.js} +4 -4
  84. package/dist/{summary-RPU2BS3Q.js → summary-6QNVQZJV.js} +1 -1
  85. package/dist/symphony-KQJ6HIXB.js +53 -0
  86. package/dist/symphony-VDNDFK7H.js +2 -0
  87. package/dist/symphony-relay-ASMKPDEE.js +3 -0
  88. package/dist/sync-layer-C2PF273N.js +2 -0
  89. package/dist/task-PRLQ4VPK.js +3 -0
  90. package/dist/task-loader-EIXPKHA3.js +2 -0
  91. package/dist/task-loader-LFEE6OU7.js +2 -0
  92. package/dist/task-settlement-A2T6EACG.js +3 -0
  93. package/dist/task-settlement-ZXOY4YGX.js +3 -0
  94. package/dist/team-KP4HMUB5.js +2 -0
  95. package/dist/thread-2A7QKU72.js +41 -0
  96. package/dist/tools-NOMEIBS7.js +2 -0
  97. package/dist/tools-YW3Q27UI.js +142 -0
  98. package/dist/validate-OZTX3FYX.js +13 -0
  99. package/dist/validate-RIMSY3RP.js +9 -0
  100. package/dist/{workspace-6POCBPDY.js → workspace-4D4TQ637.js} +1 -1
  101. package/package.json +2 -6
  102. package/platform-ui/dist/assets/{AmbientSection-CwatqcBD.js → AmbientSection-xoxr3DQg.js} +1 -1
  103. package/platform-ui/dist/assets/{DocsSection-BZ2SFJBZ.js → DocsSection-Us2qksna.js} +1 -1
  104. package/platform-ui/dist/assets/{GitSection-MNNYU1tO.js → GitSection-DIHZyadf.js} +1 -1
  105. package/platform-ui/dist/assets/{GraphSection-COYjb4Pt.js → GraphSection-9TO0L1IO.js} +1 -1
  106. package/platform-ui/dist/assets/{LoreSection-B0hUbfsJ.js → LoreSection-DVDit8Aw.js} +1 -1
  107. package/platform-ui/dist/assets/{SentinelSection-BCxW1DCp.js → SentinelSection-a5_VNYcx.js} +1 -1
  108. package/platform-ui/dist/assets/{SymphonySection-BsucZRqy.js → SymphonySection-cRHEoJ9t.js} +1 -1
  109. package/platform-ui/dist/assets/TasksSection-44_gDO3L.css +1 -0
  110. package/platform-ui/dist/assets/TasksSection-h8x3qRIj.js +1 -0
  111. package/platform-ui/dist/assets/{TeamSection-C0QNTudW.js → TeamSection-mFoDyNic.js} +1 -1
  112. package/platform-ui/dist/assets/{UniversitySection-DN1-g9pw.js → UniversitySection-D99YRjmC.js} +1 -1
  113. package/platform-ui/dist/assets/{index-DwUT8pju.js → index-D_wB2S_2.js} +11 -11
  114. package/platform-ui/dist/index.html +1 -1
  115. package/dist/add-V6XR7DU5.js +0 -12
  116. package/dist/agent-loader-Z753DQWH.js +0 -2
  117. package/dist/ambient-QB7V4TBR.js +0 -6
  118. package/dist/calibrate-PHVP7RPH.js +0 -4
  119. package/dist/captain-3COP6YTD.js +0 -2
  120. package/dist/chunk-4CGPLLWQ.js +0 -30
  121. package/dist/chunk-7SWEOPWF.js +0 -2
  122. package/dist/chunk-CHSU6LTR.js +0 -2
  123. package/dist/chunk-EKNLG73M.js +0 -6
  124. package/dist/chunk-H55W26AR.js +0 -3
  125. package/dist/chunk-HE2NA5QF.js +0 -8
  126. package/dist/chunk-JIXHEBGK.js +0 -7
  127. package/dist/chunk-MBPLJKE5.js +0 -3
  128. package/dist/chunk-OIYJUU6T.js +0 -25
  129. package/dist/chunk-QO7YPQXC.js +0 -2
  130. package/dist/chunk-XMAV5AG6.js +0 -2
  131. package/dist/chunk-XPPFILCM.js +0 -2
  132. package/dist/chunk-YCDOA5IQ.js +0 -18
  133. package/dist/dist-GQ42YS5N-4HIJZVBB.js +0 -39
  134. package/dist/lint-IGKE6UPS.js +0 -26
  135. package/dist/list-NC3QGT75.js +0 -12
  136. package/dist/lore-loader-HAZ5FRLP.js +0 -2
  137. package/dist/lore-server-FC2GMDLT.js +0 -14
  138. package/dist/nomination-engine-ORHH4L2W.js +0 -2
  139. package/dist/orchestration-O2OVPTIZ.js +0 -2
  140. package/dist/platform-server-Y6TLEXR2.js +0 -25
  141. package/dist/quiz-TNV6APBM.js +0 -10
  142. package/dist/remember-MJRNTXYS.js +0 -14
  143. package/dist/serve-L52ZUTU6.js +0 -10
  144. package/dist/serve-XZ6GBUS3.js +0 -8
  145. package/dist/session-work-log-FF7CKMWP.js +0 -2
  146. package/dist/status-ENAI35NL.js +0 -6
  147. package/dist/symphony-CFAYJGLF.js +0 -2
  148. package/dist/symphony-L56O5ZG3.js +0 -53
  149. package/dist/symphony-relay-Y2UR3YNR.js +0 -3
  150. package/dist/task-loader-H7HQAYGL.js +0 -2
  151. package/dist/task-loader-YZME4RKE.js +0 -2
  152. package/dist/task-settlement-HINBVZBE.js +0 -3
  153. package/dist/task-settlement-XC6E6JNT.js +0 -3
  154. package/dist/team-25LK6CWM.js +0 -2
  155. package/dist/thread-HFXK65D4.js +0 -41
  156. package/dist/tools-GAU5WOEI.js +0 -2
  157. package/dist/validate-IQG7DBFC.js +0 -9
  158. package/dist/validate-LSCDOLBO.js +0 -13
  159. package/dist/work-log-loader-CRVTOMVB.js +0 -2
  160. package/graph-ui/dist/assets/index-BlgXTl53.css +0 -1
  161. package/graph-ui/dist/assets/index-Bq5nXK8p.js +0 -63
  162. package/graph-ui/dist/index.html +0 -13
  163. package/lore-ui/dist/assets/index-C3EixkjW.css +0 -1
  164. package/lore-ui/dist/assets/index-DKhNxgtW.js +0 -56
  165. package/lore-ui/dist/index.html +0 -13
  166. package/platform-ui/dist/assets/CanvasSection-dFAthehN.js +0 -9
  167. package/platform-ui/dist/assets/CanvasSection-flMXU19z.css +0 -1
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import {b,a as a$1}from'./chunk-DLMDHS2X.js';import {a}from'./chunk-FYDRENK7.js';import {a as a$2}from'./chunk-TYWB5IQJ.js';import {e}from'./chunk-YXLGVOZO.js';import {e as e$1,f,g}from'./chunk-XPPFILCM.js';import {a as a$4}from'./chunk-MBPLJKE5.js';import {b as b$1}from'./chunk-EKZDFEJW.js';import {a as a$3,b as b$2}from'./chunk-LPBCQM5Y.js';import {o,t,x}from'./chunk-4GC35IFF.js';import'minimatch';import*as S from'fs';import*as C from'path';import*as W from'js-yaml';import {spawn}from'child_process';var Pe=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","tradeoff","pros and cons","decision"],Ae=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs","changelog","architecture doc"],Ce=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","doesn't work","doesn't","cant","can't","regression","patch"],Ie=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify","modularize","decouple","split","merge"],De=["auth","authentication","authorization","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","api key","role","access","gate","portal","sensitive","private","security","vulnerability","xss","sql injection","csrf"],$e=/[@#$%^!?&~][a-zA-Z0-9_-]+/g,fe={analysis:{agents:["architect"],models:{architect:"opus"},costMultiplier:{min:.3,max:.5}},documentation:{agents:["architect"],models:{architect:"sonnet"},costMultiplier:{min:.25,max:.45}},bugfix:{agents:["security","builder"],models:{security:"opus",builder:"haiku"},costMultiplier:{min:.5,max:.8}},refactor:{agents:["architect","builder"],models:{architect:"opus",builder:"haiku"},costMultiplier:{min:.6,max:.85}},feature:{agents:["architect","security","builder","tester"],models:{architect:"opus",security:"opus",builder:"haiku",tester:"haiku"},costMultiplier:{min:.8,max:1.2}}};function Me(h){let t=h.match($e)||[];return [...new Set(t)]}function U(h,t){let e=h.toLowerCase();return t.filter(s=>e.includes(s.toLowerCase()))}function Fe(h,t,e,s){let n=0;e.length>=5?n+=2:e.length>=2&&(n+=1);let i=h.split(/\s+/).length;i>=100?n+=2:i>=50&&(n+=1);let r=new Set(e.map(l=>l[0]));return r.size>=4?n+=2:r.size>=2&&(n+=1),e.some(l=>l.startsWith("^"))&&(n+=1),e.some(l=>l.startsWith("$"))&&(n+=1),t==="feature"&&(n+=1),t==="refactor"&&(n+=1),n>=5?"high":n>=2?"medium":"low"}function Be(h,t,e){if(U(h,De).length>0||t.some(n=>n.startsWith("^")))return true;return false}function K(h,t){let e=Me(h),s=U(h,Pe),n=U(h,Ae),i=U(h,Ce),r=U(h,Ie),l,o;s.length>0&&i.length===0&&r.length===0?(l="analysis",o=s):n.length>0&&i.length===0?(l="documentation",o=n):i.length>0?(l="bugfix",o=i):r.length>0?(l="refactor",o=r):(l="feature",o=[]);let a=fe[l],d=Be(h,e),c=[...a.agents];d&&!c.includes("security")&&(c=["security",...c]);let f=Fe(h,l,e),p={...a.costMultiplier};return f==="high"?(p.min*=1.2,p.max*=1.3):f==="low"&&(p.min*=.8,p.max*=.9),d&&!a.agents.includes("security")&&(p.min+=.15,p.max+=.2),{type:l,complexity:f,recommendedAgents:c,securityRequired:d,costMultiplier:p,matchedKeywords:o,symbols:e}}function H(h,t){let e=fe[t.type];return h==="security"&&t.securityRequired?"opus":e.models[h]||"sonnet"}var _e=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,Ee=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi],Le=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"];function me(h,t$1,e$1){let s=h.toLowerCase(),n=h.match(_e)||[],i=[...new Set(n)],r=i.map(g=>{let y=t(e$1,g),w=y.length>0?y[0]:null;return {symbol:g,exists:!!w,type:w?.type,description:w?.description}}),l=r.filter(g=>g.exists).map(g=>{let y=x(e$1,g.symbol),w=new Set;for(let F of y){let v=x(e$1,F.symbol);for(let P of v)P.symbol!==g.symbol&&!y.find(ee=>ee.symbol===P.symbol)&&w.add(P.symbol);}let R=y.length+w.size,I="low";return R>10?I="high":R>3&&(I="medium"),{symbol:g.symbol,directDependents:y.length,indirectDependents:w.size,impact:I}}),o=a$3(t$1),a=o.status==="ok"?o.data:null,d={exists:o.status!=="missing",gateCount:a?b$2(a).length:0,gates:a?b$2(a).map(g=>`^${g}`):[],routeCount:a?.routes?Object.keys(a.routes).length:0},c=Le.some(g=>s.includes(g)),f=e(t$1),p=f?a$2(h,f.agents).map(g=>({name:g.name,confidence:g.confidence,reason:g.reason})):[],u=[];return r.some(g=>g.exists)&&u.push("ripple-analysis"),c&&u.push("portal-compliance"),i.some(g=>g.startsWith("^"))&&u.push("gate-validation"),i.some(g=>g.startsWith("!"))&&u.push("signal-registration"),u.push("purpose-coverage"),{affectedSymbols:r,rippleAnalysis:l,portalStatus:d,taskAddsRoutes:c,suggestedAgents:p,requiredChecks:u}}function ye(h,t$1,e,s){let n=[],i=a$3(e),r=i.status==="ok"?i.data:null,l=r?b$2(r):[],o=r?.routes?Object.keys(r.routes):[];for(let p of h){let u=C.isAbsolute(p)?p:C.join(e,p);if(!S.existsSync(u))continue;let g;try{g=S.readFileSync(u,"utf-8");}catch{continue}for(let y of Ee){y.lastIndex=0;let w;for(;(w=y.exec(g))!==null;){let R=w[2]||w[0];R&&R.startsWith("/")&&(!o.some(F=>F.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===R)&&r?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${R}" found in ${C.relative(e,u)} but not declared in portal.yaml`,file:C.relative(e,u),suggestion:"Add this route to portal.yaml with appropriate ^gates. Run paradigm_gates_for_route to get suggestions."}):!r&&R.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${R}" found but no portal.yaml exists`,file:C.relative(e,u),suggestion:"Create portal.yaml to declare gates for API routes. Run: paradigm portal init"}));}}}for(let p of t$1)t(s,p).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${p}" was touched but is not registered in any .purpose file`,suggestion:`Add "${p}" to the nearest .purpose file. Use paradigm_purpose_add_component or paradigm_purpose_add_signal.`});for(let p of t$1)if(p.startsWith("^")){let u=p.slice(1);l.includes(u)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${p}" is referenced but not declared in portal.yaml`,suggestion:`Add ${p} to portal.yaml with description and check expression.`});}h.length>=5&&t$1.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${h.length} files, ${t$1.length} symbols) \u2014 consider recording architectural decisions`,suggestion:"Use paradigm_wisdom_record to capture any decisions or antipatterns discovered during this task."});let a=n.filter(p=>p.severity==="error").length,d=n.filter(p=>p.severity==="warning").length,c=4,f="pass";return a>0?f="violations":d>0&&(f="warnings"),{status:f,violations:n,summary:{totalChecks:c,passed:c-(a>0?1:0)-(d>0?1:0),warnings:d,errors:a},blocksCompletion:a>0}}var je=".paradigm/events/iteration-revisions.jsonl";function be(h,t){try{let e=C.join(h,je),s=C.dirname(e);S.existsSync(s)||S.mkdirSync(s,{recursive:!0});let n={timestamp:new Date().toISOString(),type:"iteration-revision",...t};S.appendFileSync(e,JSON.stringify(n)+`
3
- `,"utf8");}catch{}}function we(h,t){let e=Math.random().toString(36).substring(2,8);return `itrev-${h}-r${t}-${Date.now()}-${e}`}async function le(h,t,e,s){let n=new Map,i;try{i=await e$1(h,{blurb:e,priority:"medium",tags:["orchestration","epic"],claimant:{kind:"archetype",ref:"orchestrator"},external_ref:{kind:"orchestration",ref:t}});try{await f(h,i,{status:"in-progress"});}catch(l){a$4.flow("$cli-task-bridge").warn("Epic promote to in-progress failed",{orchestrationId:t,epicTaskId:i,error:l instanceof Error?l.message:String(l)});}let r=[...s].sort((l,o)=>l.stage-o.stage);for(let l of r)try{let o=(l.dependsOn||[]).map(d=>n.get(d)).filter(d=>typeof d=="string"),a=await e$1(h,{blurb:l.subtask,priority:"medium",tags:["orchestration"],claimant:{kind:"archetype",ref:l.agent},parentTaskId:i,stage:l.stage,...o.length>0?{dependsOn:o}:{},external_ref:{kind:"orchestration",ref:t}});n.set(l.agent,a);}catch(o){a$4.flow("$cli-task-bridge").warn("Stage task emission failed",{orchestrationId:t,agent:l.agent,stage:l.stage,error:o instanceof Error?o.message:String(o)});}a$4.flow("$cli-task-bridge").info("Emitted CLI orchestration task DAG",{orchestrationId:t,epicTaskId:i,stageTasks:n.size});}catch(r){a$4.flow("$cli-task-bridge").warn("CLI task DAG emission failed; orchestration continues",{orchestrationId:t,error:r instanceof Error?r.message:String(r)});}return {epicTaskId:i,stageTaskIds:n}}async function ce(h,t){if(!t)return false;try{return await f(h,t,{status:"in-progress"})}catch(e){return a$4.flow("$cli-task-bridge").warn("Stage progress update failed (non-fatal)",{taskId:t,error:e instanceof Error?e.message:String(e)}),false}}async function G(h,t,e){if(!t)return false;try{return e==="success"?await g(h,t):await f(h,t,{status:"shelved",shelved:new Date().toISOString()})}catch(s){return a$4.flow("$cli-task-bridge").warn("Stage complete update failed (non-fatal)",{taskId:t,outcome:e,error:s instanceof Error?s.message:String(s)}),false}}var qe=".paradigm/events/estimate-actuals.jsonl";function ue(h,t){try{let e=C.join(h,qe),s=C.dirname(e);S.existsSync(s)||S.mkdirSync(s,{recursive:!0});let n={archetype:t.archetype,taskType:t.taskType,actualTokens:t.actualTokens,...t.parentTaskId?{parentTaskId:t.parentTaskId}:{},ts:t.ts||new Date().toISOString()};return S.appendFileSync(e,JSON.stringify(n)+`
4
- `,"utf8"),!0}catch(e){return a$4.component("#calibration").warn("estimate-actual capture failed (non-fatal)",{archetype:t.archetype,taskType:t.taskType,error:e instanceof Error?e.message:String(e)}),false}}var ke={architect:"opus",security:"opus",reviewer:"sonnet",builder:"haiku",tester:"haiku"},Ue=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","role","access control","vulnerability","injection","xss","csrf"];function We(h,t){let e=h.toLowerCase(),s=Ue.some(r=>e.includes(r.toLowerCase())),n=h.includes("^"),i=false;return s||n||i}var ze=["rename","refactor","migrate","restructure","move","reorganize"];function Ve(h){let t=h.toLowerCase();return ze.some(e=>t.includes(e))}var Q=class{spawner;auditLogger;rootDir;constructor(t){this.rootDir=t,this.spawner=new b(t),this.auditLogger=new a(t);}async initialize(){await this.spawner.initialize();}async orchestrate(t,e={}){let s=e.mode||"faceted",n=Date.now(),i=this.generateOrchestrationId(),r={success:false,mode:s,orchestrationId:i,task:t,agentsSpawned:0,totalTokens:{input:0,output:0,total:0},totalCost:0,duration_ms:0,agentResults:[]};try{let l;if(e.pmGovernance?.enabled)try{let{aggregateFromDirectory:a}=await import('./dist-TNE4GFT7.js'),d=await a(this.rootDir),c=o(d);l=me(t,this.rootDir,c);}catch{}if(s==="solo"){let a=await this.runSoloMode(t,e,i);r.agentsSpawned=1,r.agentResults=[a],r.success=a.success,a.relay&&(r.totalTokens=a.relay.metrics.tokens_used,r.totalCost=b$1(r.totalTokens,e.orchestratorModel||"opus"));}else {let a=await this.runFacetedMode(t,e,i);r.agentsSpawned=a.results.length,r.agentResults=a.results,r.totalTokens=a.totalTokens,r.totalCost=a.totalCost,r.success=a.success,r.parallelBuilderStats=a.parallelBuilderStats,r.iterationOutcome=a.iterationOutcome;}if(e.pmGovernance?.enabled&&l)try{let{aggregateFromDirectory:a}=await import('./dist-TNE4GFT7.js'),d=await a(this.rootDir),c=o(d),f=[],p=[];for(let g of r.agentResults)g.relay?.outputs?.artifacts&&f.push(...g.relay.outputs.artifacts.map(y=>y.path));for(let g of l.affectedSymbols)p.push(g.symbol);let u=ye(f,p,this.rootDir,c);r.complianceReport={preflight:l,postflight:u},e.pmGovernance.blockOnViolations&&u.blocksCompletion&&(r.success=!1);}catch{r.complianceReport={preflight:l};}r.duration_ms=Date.now()-n;let o$1=this.auditLogger.startOrchestration(i,t,s);return o$1.completed=new Date().toISOString(),o$1.status=r.success?"success":"failed",o$1.totals={duration_ms:r.duration_ms,tokens:r.totalTokens.total,cost_usd:r.totalCost,agents_spawned:r.agentsSpawned,files_created:0,files_modified:0},this.auditLogger.saveOrchestration(o$1),r.log=o$1,r}catch(l){return r.error=l instanceof Error?l.message:String(l),r.duration_ms=Date.now()-n,r}}async compare(t,e={}){let s=await this.orchestrate(t,{...e,mode:"solo"}),n=await this.orchestrate(t,{...e,mode:"faceted"}),i=s.totalTokens.total-n.totalTokens.total,r=s.totalCost-n.totalCost,l=s.duration_ms-n.duration_ms,o="tie";return n.success&&!s.success?o="faceted":s.success&&!n.success?o="solo":n.totalCost<s.totalCost*.8?o="faceted":s.totalCost<n.totalCost*.8&&(o="solo"),{solo:s,faceted:n,comparison:{winner:o,tokensSaved:i,costDiff:r,timeDiff:l,soloSucceeded:s.success,facetedSucceeded:n.success}}}async runSoloMode(t,e$1,s){let i=e(this.rootDir)?.team.default_agent||"architect",r=e$1.orchestratorModel||"opus",l;s&&(l=await le(this.rootDir,s,t,[{agent:i,stage:0,subtask:t,dependsOn:[]}]));let o=l?.stageTaskIds.get(i),a={model:r,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.budget,onMessage:e$1.onMessage?c=>e$1.onMessage("solo",c):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart("solo",t,r),await ce(this.rootDir,o);let d=await this.spawner.spawn(i,t,a);return e$1.onAgentComplete&&e$1.onAgentComplete("solo",d,r),d.relay&&ue(this.rootDir,{archetype:i,taskType:K(t).type,actualTokens:d.relay.metrics.tokens_used,parentTaskId:l?.epicTaskId}),await G(this.rootDir,o,d.success?"success":"failure"),d}async runFacetedMode(t,e$1,s){let n=e(this.rootDir);if(!n)return {success:false,results:[],totalTokens:{input:0,output:0,total:0},totalCost:0};let i=K(t).type,r="";if(Ve(t)){let k=a$1(t);if(k.length>0){let b=[];b.push(`## Auto-Ripple Analysis
2
+ import {a as a$2}from'./chunk-TYWB5IQJ.js';import {b as b$1,a as a$1}from'./chunk-DLMDHS2X.js';import {a}from'./chunk-FYDRENK7.js';import {e}from'./chunk-YXLGVOZO.js';import {h,i,j}from'./chunk-MBKTVQS2.js';import {b,a as a$4}from'./chunk-EK4ZRIFJ.js';import {b as b$2}from'./chunk-EKZDFEJW.js';import {a as a$3,b as b$3}from'./chunk-LPBCQM5Y.js';import {o,t,x}from'./chunk-D6BSCELB.js';import'minimatch';import*as S from'fs';import*as C from'path';import*as W from'js-yaml';import {spawn}from'child_process';var Ae=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","tradeoff","pros and cons","decision"],Ce=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs","changelog","architecture doc"],Ie=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","doesn't work","doesn't","cant","can't","regression","patch"],De=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify","modularize","decouple","split","merge"],$e=["auth","authentication","authorization","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","api key","role","access","gate","portal","sensitive","private","security","vulnerability","xss","sql injection","csrf"],Me=/[@#$%^!?&~][a-zA-Z0-9_-]+/g,me={analysis:{agents:["architect"],models:{architect:"opus"},costMultiplier:{min:.3,max:.5}},documentation:{agents:["architect"],models:{architect:"sonnet"},costMultiplier:{min:.25,max:.45}},bugfix:{agents:["security","builder"],models:{security:"opus",builder:"haiku"},costMultiplier:{min:.5,max:.8}},refactor:{agents:["architect","builder"],models:{architect:"opus",builder:"haiku"},costMultiplier:{min:.6,max:.85}},feature:{agents:["architect","security","builder","tester"],models:{architect:"opus",security:"opus",builder:"haiku",tester:"haiku"},costMultiplier:{min:.8,max:1.2}}};function Fe(h){let t=h.match(Me)||[];return [...new Set(t)]}function U(h,t){let e=h.toLowerCase();return t.filter(s=>e.includes(s.toLowerCase()))}function Be(h,t,e,s){let n=0;e.length>=5?n+=2:e.length>=2&&(n+=1);let i=h.split(/\s+/).length;i>=100?n+=2:i>=50&&(n+=1);let r=new Set(e.map(l=>l[0]));return r.size>=4?n+=2:r.size>=2&&(n+=1),e.some(l=>l.startsWith("^"))&&(n+=1),e.some(l=>l.startsWith("$"))&&(n+=1),t==="feature"&&(n+=1),t==="refactor"&&(n+=1),n>=5?"high":n>=2?"medium":"low"}function _e(h,t,e){if(U(h,$e).length>0||t.some(n=>n.startsWith("^")))return true;return false}function K(h,t){let e=Fe(h),s=U(h,Ae),n=U(h,Ce),i=U(h,Ie),r=U(h,De),l,o;s.length>0&&i.length===0&&r.length===0?(l="analysis",o=s):n.length>0&&i.length===0?(l="documentation",o=n):i.length>0?(l="bugfix",o=i):r.length>0?(l="refactor",o=r):(l="feature",o=[]);let a=me[l],d=_e(h,e),c=[...a.agents];d&&!c.includes("security")&&(c=["security",...c]);let f=Be(h,l,e),p={...a.costMultiplier};return f==="high"?(p.min*=1.2,p.max*=1.3):f==="low"&&(p.min*=.8,p.max*=.9),d&&!a.agents.includes("security")&&(p.min+=.15,p.max+=.2),{type:l,complexity:f,recommendedAgents:c,securityRequired:d,costMultiplier:p,matchedKeywords:o,symbols:e}}function H(h,t){let e=me[t.type];return h==="security"&&t.securityRequired?"opus":e.models[h]||"sonnet"}var Ee=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,Le=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi],je=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"];function ye(h,t$1,e$1){let s=h.toLowerCase(),n=h.match(Ee)||[],i=[...new Set(n)],r=i.map(g=>{let y=t(e$1,g),w=y.length>0?y[0]:null;return {symbol:g,exists:!!w,type:w?.type,description:w?.description}}),l=r.filter(g=>g.exists).map(g=>{let y=x(e$1,g.symbol),w=new Set;for(let F of y){let v=x(e$1,F.symbol);for(let P of v)P.symbol!==g.symbol&&!y.find(ee=>ee.symbol===P.symbol)&&w.add(P.symbol);}let R=y.length+w.size,I="low";return R>10?I="high":R>3&&(I="medium"),{symbol:g.symbol,directDependents:y.length,indirectDependents:w.size,impact:I}}),o=a$3(t$1),a=o.status==="ok"?o.data:null,d={exists:o.status!=="missing",gateCount:a?b$3(a).length:0,gates:a?b$3(a).map(g=>`^${g}`):[],routeCount:a?.routes?Object.keys(a.routes).length:0},c=je.some(g=>s.includes(g)),f=e(t$1),p=f?a$2(h,f.agents).map(g=>({name:g.name,confidence:g.confidence,reason:g.reason})):[],u=[];return r.some(g=>g.exists)&&u.push("ripple-analysis"),c&&u.push("portal-compliance"),i.some(g=>g.startsWith("^"))&&u.push("gate-validation"),i.some(g=>g.startsWith("!"))&&u.push("signal-registration"),u.push("purpose-coverage"),{affectedSymbols:r,rippleAnalysis:l,portalStatus:d,taskAddsRoutes:c,suggestedAgents:p,requiredChecks:u}}function be(h,t$1,e,s){let n=[],i=a$3(e),r=i.status==="ok"?i.data:null,l=r?b$3(r):[],o=r?.routes?Object.keys(r.routes):[];for(let p of h){let u=C.isAbsolute(p)?p:C.join(e,p);if(!S.existsSync(u))continue;let g;try{g=S.readFileSync(u,"utf-8");}catch{continue}for(let y of Le){y.lastIndex=0;let w;for(;(w=y.exec(g))!==null;){let R=w[2]||w[0];R&&R.startsWith("/")&&(!o.some(F=>F.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===R)&&r?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${R}" found in ${C.relative(e,u)} but not declared in portal.yaml`,file:C.relative(e,u),suggestion:"Add this route to portal.yaml with appropriate ^gates. Run paradigm_gates_for_route to get suggestions."}):!r&&R.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${R}" found but no portal.yaml exists`,file:C.relative(e,u),suggestion:"Create portal.yaml to declare gates for API routes. Run: paradigm portal init"}));}}}for(let p of t$1)t(s,p).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${p}" was touched but is not registered in any .purpose file`,suggestion:`Add "${p}" to the nearest .purpose file. Use paradigm_purpose_add_component or paradigm_purpose_add_signal.`});for(let p of t$1)if(p.startsWith("^")){let u=p.slice(1);l.includes(u)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${p}" is referenced but not declared in portal.yaml`,suggestion:`Add ${p} to portal.yaml with description and check expression.`});}h.length>=5&&t$1.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${h.length} files, ${t$1.length} symbols) \u2014 consider recording architectural decisions`,suggestion:"Use paradigm_wisdom_record to capture any decisions or antipatterns discovered during this task."});let a=n.filter(p=>p.severity==="error").length,d=n.filter(p=>p.severity==="warning").length,c=4,f="pass";return a>0?f="violations":d>0&&(f="warnings"),{status:f,violations:n,summary:{totalChecks:c,passed:c-(a>0?1:0)-(d>0?1:0),warnings:d,errors:a},blocksCompletion:a>0}}var qe=".paradigm/events/iteration-revisions.jsonl";function we(h,t){try{let e=C.join(h,qe),s=C.dirname(e);S.existsSync(s)||S.mkdirSync(s,{recursive:!0});let n={timestamp:new Date().toISOString(),type:"iteration-revision",...t};S.appendFileSync(e,JSON.stringify(n)+`
3
+ `,"utf8");}catch{}}function ke(h,t){let e=Math.random().toString(36).substring(2,8);return `itrev-${h}-r${t}-${Date.now()}-${e}`}b();async function le(h$1,t,e,s){let n=new Map,i$1;try{i$1=await h(h$1,{blurb:e,priority:"medium",tags:["orchestration","epic"],claimant:{kind:"archetype",ref:"orchestrator"},external_ref:{provider:"orchestration",ref:t}});try{await i(h$1,i$1,{status:"in-progress"});}catch(l){a$4.flow("$cli-task-bridge").warn("Epic promote to in-progress failed",{orchestrationId:t,epicTaskId:i$1,error:l instanceof Error?l.message:String(l)});}let r=[...s].sort((l,o)=>l.stage-o.stage);for(let l of r)try{let o=(l.dependsOn||[]).map(d=>n.get(d)).filter(d=>typeof d=="string"),a=await h(h$1,{blurb:l.subtask,priority:"medium",tags:["orchestration"],claimant:{kind:"archetype",ref:l.agent},parentTaskId:i$1,stage:l.stage,...o.length>0?{dependsOn:o}:{},external_ref:{provider:"orchestration",ref:t}});n.set(l.agent,a);}catch(o){a$4.flow("$cli-task-bridge").warn("Stage task emission failed",{orchestrationId:t,agent:l.agent,stage:l.stage,error:o instanceof Error?o.message:String(o)});}a$4.flow("$cli-task-bridge").info("Emitted CLI orchestration task DAG",{orchestrationId:t,epicTaskId:i$1,stageTasks:n.size});}catch(r){a$4.flow("$cli-task-bridge").warn("CLI task DAG emission failed; orchestration continues",{orchestrationId:t,error:r instanceof Error?r.message:String(r)});}return {epicTaskId:i$1,stageTaskIds:n}}async function ce(h,t){if(!t)return false;try{return await i(h,t,{status:"in-progress"})}catch(e){return a$4.flow("$cli-task-bridge").warn("Stage progress update failed (non-fatal)",{taskId:t,error:e instanceof Error?e.message:String(e)}),false}}async function G(h,t,e){if(!t)return false;try{return e==="success"?await j(h,t):await i(h,t,{status:"shelved",shelved:new Date().toISOString()})}catch(s){return a$4.flow("$cli-task-bridge").warn("Stage complete update failed (non-fatal)",{taskId:t,outcome:e,error:s instanceof Error?s.message:String(s)}),false}}b();var Ne=".paradigm/events/estimate-actuals.jsonl";function ue(h,t){try{let e=C.join(h,Ne),s=C.dirname(e);S.existsSync(s)||S.mkdirSync(s,{recursive:!0});let n={archetype:t.archetype,taskType:t.taskType,actualTokens:t.actualTokens,...t.parentTaskId?{parentTaskId:t.parentTaskId}:{},ts:t.ts||new Date().toISOString()};return S.appendFileSync(e,JSON.stringify(n)+`
4
+ `,"utf8"),!0}catch(e){return a$4.component("#calibration").warn("estimate-actual capture failed (non-fatal)",{archetype:t.archetype,taskType:t.taskType,error:e instanceof Error?e.message:String(e)}),false}}var Se={architect:"opus",security:"opus",reviewer:"sonnet",builder:"haiku",tester:"haiku"},Ge=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","role","access control","vulnerability","injection","xss","csrf"];function ze(h,t){let e=h.toLowerCase(),s=Ge.some(r=>e.includes(r.toLowerCase())),n=h.includes("^"),i=false;return s||n||i}var Ve=["rename","refactor","migrate","restructure","move","reorganize"];function Ye(h){let t=h.toLowerCase();return Ve.some(e=>t.includes(e))}var Q=class{spawner;auditLogger;rootDir;constructor(t){this.rootDir=t,this.spawner=new b$1(t),this.auditLogger=new a(t);}async initialize(){await this.spawner.initialize();}async orchestrate(t,e={}){let s=e.mode||"faceted",n=Date.now(),i=this.generateOrchestrationId(),r={success:false,mode:s,orchestrationId:i,task:t,agentsSpawned:0,totalTokens:{input:0,output:0,total:0},totalCost:0,duration_ms:0,agentResults:[]};try{let l;if(e.pmGovernance?.enabled)try{let{aggregateFromDirectory:a}=await import('./dist-PW5YPGFF.js'),d=await a(this.rootDir),c=o(d);l=ye(t,this.rootDir,c);}catch{}if(s==="solo"){let a=await this.runSoloMode(t,e,i);r.agentsSpawned=1,r.agentResults=[a],r.success=a.success,a.relay&&(r.totalTokens=a.relay.metrics.tokens_used,r.totalCost=b$2(r.totalTokens,e.orchestratorModel||"opus"));}else {let a=await this.runFacetedMode(t,e,i);r.agentsSpawned=a.results.length,r.agentResults=a.results,r.totalTokens=a.totalTokens,r.totalCost=a.totalCost,r.success=a.success,r.parallelBuilderStats=a.parallelBuilderStats,r.iterationOutcome=a.iterationOutcome;}if(e.pmGovernance?.enabled&&l)try{let{aggregateFromDirectory:a}=await import('./dist-PW5YPGFF.js'),d=await a(this.rootDir),c=o(d),f=[],p=[];for(let g of r.agentResults)g.relay?.outputs?.artifacts&&f.push(...g.relay.outputs.artifacts.map(y=>y.path));for(let g of l.affectedSymbols)p.push(g.symbol);let u=be(f,p,this.rootDir,c);r.complianceReport={preflight:l,postflight:u},e.pmGovernance.blockOnViolations&&u.blocksCompletion&&(r.success=!1);}catch{r.complianceReport={preflight:l};}r.duration_ms=Date.now()-n;let o$1=this.auditLogger.startOrchestration(i,t,s);return o$1.completed=new Date().toISOString(),o$1.status=r.success?"success":"failed",o$1.totals={duration_ms:r.duration_ms,tokens:r.totalTokens.total,cost_usd:r.totalCost,agents_spawned:r.agentsSpawned,files_created:0,files_modified:0},this.auditLogger.saveOrchestration(o$1),r.log=o$1,r}catch(l){return r.error=l instanceof Error?l.message:String(l),r.duration_ms=Date.now()-n,r}}async compare(t,e={}){let s=await this.orchestrate(t,{...e,mode:"solo"}),n=await this.orchestrate(t,{...e,mode:"faceted"}),i=s.totalTokens.total-n.totalTokens.total,r=s.totalCost-n.totalCost,l=s.duration_ms-n.duration_ms,o="tie";return n.success&&!s.success?o="faceted":s.success&&!n.success?o="solo":n.totalCost<s.totalCost*.8?o="faceted":s.totalCost<n.totalCost*.8&&(o="solo"),{solo:s,faceted:n,comparison:{winner:o,tokensSaved:i,costDiff:r,timeDiff:l,soloSucceeded:s.success,facetedSucceeded:n.success}}}async runSoloMode(t,e$1,s){let i=e(this.rootDir)?.team.default_agent||"architect",r=e$1.orchestratorModel||"opus",l;s&&(l=await le(this.rootDir,s,t,[{agent:i,stage:0,subtask:t,dependsOn:[]}]));let o=l?.stageTaskIds.get(i),a={model:r,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.budget,onMessage:e$1.onMessage?c=>e$1.onMessage("solo",c):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart("solo",t,r),await ce(this.rootDir,o);let d=await this.spawner.spawn(i,t,a);return e$1.onAgentComplete&&e$1.onAgentComplete("solo",d,r),d.relay&&ue(this.rootDir,{archetype:i,taskType:K(t).type,actualTokens:d.relay.metrics.tokens_used,parentTaskId:l?.epicTaskId}),await G(this.rootDir,o,d.success?"success":"failure"),d}async runFacetedMode(t,e$1,s){let n=e(this.rootDir);if(!n)return {success:false,results:[],totalTokens:{input:0,output:0,total:0},totalCost:0};let i=K(t).type,r="";if(Ye(t)){let k=a$1(t);if(k.length>0){let b=[];b.push(`## Auto-Ripple Analysis
5
5
  `),b.push("The following symbols are affected by this refactoring:"),b.push("");for(let T of k.slice(0,5))b.push(`- **${T}**: Check dependencies before renaming/moving`);b.push(""),b.push("**Recommendation:** Run `paradigm_ripple` for each symbol before making changes."),r=b.join(`
6
- `);}}let l=this.planAgentSequence(t,n.agents),o=this.groupByStage(l),a;if(s){let k=l.map(b=>({agent:b.agent,stage:b.stage,subtask:b.subtask,dependsOn:b.dependsOn}));a=await le(this.rootDir,s,t,k);}let d=new Set,c=[],f={input:0,output:0,total:0},p=0,u=new Map,g=true,y=n.orchestration?.iteration,w=y?.enabled===true,R=l.find(k=>k.agent==="builder")?.subtask,I=l.some(k=>k.agent==="reviewer"),F=l.some(k=>k.agent==="tester"),v=w&&!!R&&I,P,ee=Array.from(o.keys()).sort((k,b)=>k-b);for(let k of ee){let b=o.get(k)||[];if(b.length===0)continue;if(e$1.checkpoints?.beforeAgentSpawn&&e$1.onCheckpoint){let m=b.map(D=>D.agent).join(", ");if(!await e$1.onCheckpoint(`Stage ${k}: Spawn ${m}${b.length>1?" (parallel)":""}`)){g=false;break}}let T=b.map(async m=>{let O=e$1.agentBudgets?.[m.agent]?.maxTokens?"haiku":m.model||ke[m.agent]||"sonnet",D="";if(m.dependsOn.length>0){let _=m.dependsOn.map(te=>u.get(te)).filter(Boolean);_.length>0&&(D=_.join(`
6
+ `);}}let l=this.planAgentSequence(t,n.agents),o=this.groupByStage(l),a;if(s){let k=l.map(b=>({agent:b.agent,stage:b.stage,subtask:b.subtask,dependsOn:b.dependsOn}));a=await le(this.rootDir,s,t,k);}let d=new Set,c=[],f={input:0,output:0,total:0},p=0,u=new Map,g=true,y=n.orchestration?.iteration,w=y?.enabled===true,R=l.find(k=>k.agent==="builder")?.subtask,I=l.some(k=>k.agent==="reviewer"),F=l.some(k=>k.agent==="tester"),v=w&&!!R&&I,P,ee=Array.from(o.keys()).sort((k,b)=>k-b);for(let k of ee){let b=o.get(k)||[];if(b.length===0)continue;if(e$1.checkpoints?.beforeAgentSpawn&&e$1.onCheckpoint){let m=b.map(D=>D.agent).join(", ");if(!await e$1.onCheckpoint(`Stage ${k}: Spawn ${m}${b.length>1?" (parallel)":""}`)){g=false;break}}let T=b.map(async m=>{let O=e$1.agentBudgets?.[m.agent]?.maxTokens?"haiku":m.model||Se[m.agent]||"sonnet",D="";if(m.dependsOn.length>0){let _=m.dependsOn.map(te=>u.get(te)).filter(Boolean);_.length>0&&(D=_.join(`
7
7
 
8
8
  ---
9
9
 
@@ -16,18 +16,18 @@ import {b,a as a$1}from'./chunk-DLMDHS2X.js';import {a}from'./chunk-FYDRENK7.js'
16
16
  ## Context from previous agents:
17
17
  ${q}`:m.subtask;v&&m.agent==="reviewer"&&(B=`${B}
18
18
 
19
- ${Se}`);let $={model:O,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.agentBudgets?.[m.agent]||e$1.budget,onMessage:e$1.onMessage?_=>e$1.onMessage(m.agent,_):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart(m.agent,m.subtask,O),await ce(this.rootDir,a?.stageTaskIds.get(m.agent));let x=await this.spawner.spawn(m.agent,B,$);return e$1.onAgentComplete&&e$1.onAgentComplete(m.agent,x,O),await G(this.rootDir,a?.stageTaskIds.get(m.agent),x.success?"success":"failure"),d.add(m.agent),{step:m,result:x,model:O}}),Re=await Promise.all(T);for(let{step:m,result:O,model:D}of Re){if(c.push(O),O.relay){f.input+=O.relay.metrics.tokens_used.input,f.output+=O.relay.metrics.tokens_used.output,f.total+=O.relay.metrics.tokens_used.total,p+=b$1(O.relay.metrics.tokens_used,D),ue(this.rootDir,{archetype:m.agent,taskType:i,actualTokens:O.relay.metrics.tokens_used,parentTaskId:a?.epicTaskId});let q=O.relay.handoff?.context||`${m.agent} completed: ${O.relay.outputs.decisions.join(", ")||"task done"}`;if(u.set(m.agent,q),m.agent==="architect"&&O.relay){let B=this.extractFilePlanFromRelay(O);if(B&&B.length>0){let $=this.planBuilderStages(B);if($.hasFilePlan&&$.totalBuilders>1){let x=await this.runParallelBuilders($,u.get("architect")||"",e$1);c.push(...x.results),f.input+=x.totalTokens.input,f.output+=x.totalTokens.output,f.total+=x.totalTokens.total,p+=x.totalCost,x.success||(g=false),P={usedFilePlan:true,totalSubPhases:$.stages.length,totalParallelBuilders:$.totalBuilders,filesCreated:$.totalFiles};for(let[_,te]of o){let Te=te.filter(xe=>xe.agent!=="builder");o.set(_,Te);}await G(this.rootDir,a?.stageTaskIds.get("builder"),x.success?"success":"failure"),d.add("builder");}}}}!O.success&&m.required&&(g=false);}if(!g||e$1.checkpoints?.afterAgentComplete&&e$1.onCheckpoint&&!await e$1.onCheckpoint(`Stage ${k} completed. Continue to next stage?`))break}let de;if(v&&g){let k=[...c].reverse().find(T=>T.relay?.agent==="reviewer"),b=k?this.parseIterationVerdict(k):null;if(b?.verdict==="changes-requested"){let T=await this.runReviewIteration({builderSubtask:R,firstReview:b,hasTester:F,maxRoundsConfig:y?.defaultMaxRounds??3,options:e$1});c.push(...T.extraResults),f.input+=T.extraTokens.input,f.output+=T.extraTokens.output,f.total+=T.extraTokens.total,p+=T.extraCost,de=T.iterationOutcome;}else k&&!b&&e$1.onMessage&&e$1.onMessage("orchestrator",{type:"text",content:"[iteration] reviewer produced no parseable iteration-verdict \u2014 re-review loop not triggered.",timestamp:new Date().toISOString()});}if(a)for(let[k,b]of a.stageTaskIds)d.has(k)||await G(this.rootDir,b,"failure");return {success:g,results:c,totalTokens:f,totalCost:p,parallelBuilderStats:P,iterationOutcome:de}}async runReviewIteration(t){let{builderSubtask:e,firstReview:s,hasTester:n,maxRoundsConfig:i,options:r}=t,l=i%2===0?i:i+1,o=[e];s.openThreads.length&&o.push("","## Reviewer asked you to resolve:",...s.openThreads.map(u=>`- ${u}`)),s.whatChanged.length&&o.push("","## Reviewer notes:",...s.whatChanged.map(u=>`- ${u}`));let a=u=>r.agentBudgets?.[u]?.maxTokens?"haiku":ke[u]||"sonnet",d=u=>r.agentBudgets?.[u]||r.budget,c=await this.runIterationLoop(o.join(`
20
- `),{maxRounds:l,mode:"ping-pong",iterateAgent:"builder",reviewAgent:"reviewer",workingDirectory:r.workingDirectory||this.rootDir,mcpServerPath:r.mcpServerPath,resolveModel:a,resolveBudget:d,onRound:r.onAgentComplete?u=>r.onAgentComplete(u.agent,u.spawnResult,a(u.agent)):void 0}),f=c.rounds.map(u=>u.spawnResult),p=0;for(let u of c.rounds)u.spawnResult.relay&&(p+=b$1(u.spawnResult.relay.metrics.tokens_used,a(u.agent)));if(n&&c.converged){let u=await this.spawner.spawn("tester",`Re-test after re-review convergence:
21
- ${e}`,{model:"haiku",workingDirectory:r.workingDirectory||this.rootDir,mcpServerPath:r.mcpServerPath});f.push(u),u.relay&&(p+=b$1(u.relay.metrics.tokens_used,"haiku"),c.totalTokens.input+=u.relay.metrics.tokens_used.input,c.totalTokens.output+=u.relay.metrics.tokens_used.output,c.totalTokens.total+=u.relay.metrics.tokens_used.total);}return {extraResults:f,extraTokens:c.totalTokens,extraCost:p,iterationOutcome:{converged:c.converged,roundsRun:c.rounds.length,openThreads:c.unresolved?.openThreads??[]}}}extractFilePlanFromRelay(t){if(!t.relay)return;let e=t.relay.handoff?.context||"";if(e.includes("filePlan:"))return this.parseFilePlanFromText(e)}parseFilePlanFromText(t){let e=[],s=t.match(/filePlan:\s*\n([\s\S]*?)(?=\n[a-z_]+:|$)/);if(!s)return;let i=s[1].split(`
22
- `),r=null,l=false,o={};for(let a of i){let d=a.trim();if(!(!d||d.startsWith("#"))){if(d.startsWith("- group:")){r&&(o.path&&(r.files.push({path:o.path,description:o.description||""}),o={}),e.push(r)),r={group:d.split(":")[1].trim(),subPhase:0,files:[]},l=false;continue}if(r){if(d.startsWith("subPhase:")){r.subPhase=parseInt(d.split(":")[1].trim(),10)||0;continue}if(d==="files:"){l=true;continue}if(l){if(d.startsWith("- path:")){o.path&&r.files.push({path:o.path,description:o.description||""}),o={path:d.split(":").slice(1).join(":").trim().replace(/^["']|["']$/g,"")};continue}if(d.startsWith("description:")){o.description=d.split(":").slice(1).join(":").trim().replace(/^["']|["']$/g,"");continue}}}}}return o.path&&r&&r.files.push({path:o.path,description:o.description||""}),r&&e.push(r),e.length>0?e:void 0}planAgentSequence(t,e){let s=a$1(t),n=t.toLowerCase(),i=K(t),r=[],l=We(t);if(i.type==="analysis")return e.architect&&r.push({agent:"architect",subtask:`Analyze and recommend: ${t}`,required:true,stage:0,dependsOn:[],model:"opus"}),r;if(i.type==="documentation")return e.architect&&r.push({agent:"architect",subtask:`Document: ${t}`,required:true,stage:0,dependsOn:[],model:"sonnet"}),r;let o=n.includes("design")||n.includes("architect")||n.includes("plan")||n.includes("spec"),a=l||n.includes("auth")||n.includes("security")||n.includes("gate")||s.some(g=>g.startsWith("^"));if(o&&e.architect&&r.push({agent:"architect",subtask:`Design and specify: ${t}`,required:true,stage:0,dependsOn:[],model:"opus"}),a&&e.security&&r.push({agent:"security",subtask:`Review security aspects of: ${t}`,required:l,stage:0,dependsOn:[],model:"opus"}),(n.includes("build")||n.includes("implement")||n.includes("create")||n.includes("add")||n.includes("fix"))&&e.builder){let g=o&&e.architect?["architect"]:[];r.push({agent:"builder",subtask:`Implement: ${t}`,required:true,stage:g.length>0?1:0,dependsOn:g,model:"haiku"});}let c=n.includes("review")||n.includes("check"),f=n.includes("test")||n.includes("verify")||n.includes("validate"),p=r.some(g=>g.agent==="builder"),u=p?2:o?1:0;if(c&&e.reviewer&&r.push({agent:"reviewer",subtask:`Review: ${t}`,required:false,stage:u,dependsOn:p?["builder"]:[],model:"sonnet"}),f&&e.tester&&r.push({agent:"tester",subtask:`Test and validate: ${t}`,required:false,stage:u,dependsOn:p?["builder"]:[],model:"haiku"}),r.length===0){let g=i.recommendedAgents;if(g.includes("architect")&&e.architect&&r.push({agent:"architect",subtask:`Design: ${t}`,required:true,stage:0,dependsOn:[],model:H("architect",i)}),(g.includes("security")||l)&&e.security&&r.push({agent:"security",subtask:`Security review: ${t}`,required:l,stage:0,dependsOn:[],model:"opus"}),g.includes("builder")&&e.builder){let y=r.length>0;r.push({agent:"builder",subtask:`Implement: ${t}`,required:true,stage:y?1:0,dependsOn:r.filter(w=>w.stage===0).map(w=>w.agent),model:H("builder",i)});}if(g.includes("tester")&&e.tester){let y=r.find(w=>w.agent==="builder")?.stage??0;r.push({agent:"tester",subtask:`Test: ${t}`,required:false,stage:y+1,dependsOn:e.builder?["builder"]:[],model:H("tester",i)});}}try{let g=a$2(t,e),y=new Set(r.map(v=>v.agent)),w=new Set(["documentor"]),I=(r.length>0?Math.max(...r.map(v=>v.stage)):-1)+1,F=r.map(v=>v.agent);for(let v of g){if(y.has(v.name)||w.has(v.name)||!e[v.name]||v.confidence==="low")continue;let P=e[v.name];r.push({agent:v.name,subtask:`Contribute (${P?.focus??"specialist"}): ${t}`,required:!1,stage:I,dependsOn:F,model:P?.defaultModel??"sonnet"}),y.add(v.name);}}catch{}return r.sort((g,y)=>g.stage-y.stage)}groupByStage(t){let e=new Map;for(let s of t){let n=e.get(s.stage)||[];n.push({agent:s.agent,subtask:s.subtask,required:s.required,dependsOn:s.dependsOn}),e.set(s.stage,n);}return e}generateOrchestrationId(){let t=new Date().toISOString().slice(0,10),e=Math.random().toString(36).substring(2,8);return `orch-${t}-${e}`}planBuilderStages(t){if(!t||t.length===0)return {hasFilePlan:false,stages:[{subPhase:0,builders:[{agent:"builder",group:"all",files:[],availableFiles:[]}]}],totalFiles:0,totalBuilders:1};let e=new Map;for(let o of t){let a=e.get(o.subPhase)||[];a.push(o),e.set(o.subPhase,a);}let s=[],n=[...e.keys()].sort((o,a)=>o-a),i=[],r=0,l=0;for(let o of n){let a=e.get(o),d=[];for(let c=0;c<a.length;c++){let f=a[c];l+=f.files.length,r++,d.push({agent:`builder-${o}-${c}`,group:f.group,files:f.files,availableFiles:[...i]});}s.push({subPhase:o,builders:d});for(let c of a)for(let f of c.files)i.push(f.path);}return {hasFilePlan:true,stages:s,totalFiles:l,totalBuilders:r}}buildParallelBuilderPrompt(t,e,s,n){let i=[];i.push(`You are a BUILDER agent responsible for implementing the **${n}** group.`),i.push(""),i.push("## Your Assignment"),i.push(""),i.push("### Files to Create:");for(let r of t)i.push(`- \`${r.path}\`: ${r.description}`);if(i.push(""),e.length>0){i.push("### Available Files (already created):"),i.push("These files exist and you can import from them:");for(let r of e)i.push(`- \`${r}\``);i.push("");}return s&&(i.push("### Context from Architect:"),i.push(s),i.push("")),i.push("### Instructions:"),i.push("1. Create ONLY the files assigned to you"),i.push("2. You can import from available files (already created)"),i.push("3. Follow existing patterns in the codebase"),i.push("4. Use the Paradigm logger (not console.log)"),i.push("5. End with the standard Agent Relay block"),i.join(`
23
- `)}async runParallelBuilders(t,e,s){let n=[],i={input:0,output:0,total:0},r=0,l=true;for(let o of t.stages){if(s.checkpoints?.beforeAgentSpawn&&s.onCheckpoint){let c=o.builders.map(p=>p.group).join(", ");if(!await s.onCheckpoint(`Builder Sub-phase ${o.subPhase}: ${c}${o.builders.length>1?" (parallel)":""}`)){l=false;break}}let a=o.builders.map(async c=>{let f=this.buildParallelBuilderPrompt(c.files,c.availableFiles,e,c.group),p={model:"haiku",workingDirectory:s.workingDirectory||this.rootDir,mcpServerPath:s.mcpServerPath,budget:s.budget,onMessage:s.onMessage?g=>s.onMessage(c.agent,g):void 0,onCheckpoint:s.onCheckpoint};s.onAgentStart&&s.onAgentStart(c.agent,`Implement ${c.group}`,"haiku");let u=await this.spawner.spawn("builder",f,p);return s.onAgentComplete&&s.onAgentComplete(c.agent,u,"haiku"),{builder:c,result:u}}),d=await Promise.all(a);for(let{result:c}of d)n.push(c),c.relay&&(i.input+=c.relay.metrics.tokens_used.input,i.output+=c.relay.metrics.tokens_used.output,i.total+=c.relay.metrics.tokens_used.total,r+=b$1(c.relay.metrics.tokens_used,"haiku")),c.success||(l=false);if(!l||s.checkpoints?.afterAgentComplete&&s.onCheckpoint&&!await s.onCheckpoint(`Sub-phase ${o.subPhase} complete. Continue to next sub-phase?`))break}return {success:l,results:n,totalTokens:i,totalCost:r}}async runIterationLoop(t,e,s){if(!Number.isInteger(e.maxRounds)||e.maxRounds<1)throw new Error(`runIterationLoop: maxRounds must be an integer >= 1 (got ${e.maxRounds})`);if(e.mode==="ping-pong"&&!e.reviewAgent)throw new Error("runIterationLoop: ping-pong mode requires reviewAgent");let n=s??(a=>be(this.rootDir,{id:we(a.agent,a.round),agent:a.agent,corrections:a.corrections,symbols:a.symbols,round:a.round})),i=[],r={input:0,output:0,total:0},l=null,o=null;for(let a=1;a<=e.maxRounds;a++){let d=this.iterationAgentForRound(e,a),c=this.buildIterationTask(t,l,a),f={workingDirectory:e.workingDirectory||this.rootDir,mcpServerPath:e.mcpServerPath,model:e.resolveModel?.(d),budget:e.resolveBudget?.(d)},p=await this.spawner.spawn(d,c,f);p.relay&&(r.input+=p.relay.metrics.tokens_used.input,r.output+=p.relay.metrics.tokens_used.output,r.total+=p.relay.metrics.tokens_used.total);let u=this.parseIterationVerdict(p);u&&(o=u);let g=false;if(this.beliefRevised(u,l)){let w=u.corrections.length>0?u.corrections:this.reopenedClaims(u,l);n({agent:d,corrections:w,symbols:p.relay?.outputs.symbols??[],round:a}),g=true;}let y={round:a,agent:d,spawnResult:p,delta:u,promoted:g};if(i.push(y),e.onRound?.(y),!p.success)return this.unresolvedResult(i,o,r,"spawn-failed",a);if(u===null)return this.unresolvedResult(i,o,r,"unparseable-verdict",a);if(this.isConverged(u,e,d))return {converged:true,rounds:i,finalDelta:u,totalTokens:r};l=u;}return this.unresolvedResult(i,o,r,"max-rounds",e.maxRounds)}unresolvedResult(t,e,s,n,i){return {converged:false,rounds:t,finalDelta:e,totalTokens:s,unresolved:{reason:n,roundsRun:i,openThreads:e?.openThreads??[]}}}iterationAgentForRound(t,e){return t.mode==="single-role"||e%2===1?t.iterateAgent:t.reviewAgent}isConverged(t,e,s){return t.verdict!=="approved"?false:e.mode==="single-role"?t.openThreads.length===0:s===e.reviewAgent}reopenedClaims(t,e){return e?t.whatChanged.filter(s=>e.alreadyVerified.includes(s)):[]}beliefRevised(t,e){return t?t.corrections.length>0?true:this.reopenedClaims(t,e).length>0:false}buildIterationTask(t,e,s){let n=[t];return e&&(n.push("",`## Iteration delta (entering round ${s})`),n.push(`- Verdict so far: ${e.verdict}`),e.whatChanged.length&&n.push("- Changed last round:",...e.whatChanged.map(i=>` - ${i}`)),e.alreadyVerified.length&&n.push("- Already verified (do NOT re-litigate):",...e.alreadyVerified.map(i=>` - ${i}`)),e.openThreads.length&&n.push("- Open threads to resolve:",...e.openThreads.map(i=>` - ${i}`))),n.push("",Se),n.join(`
19
+ ${ve}`);let $={model:O,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.agentBudgets?.[m.agent]||e$1.budget,onMessage:e$1.onMessage?_=>e$1.onMessage(m.agent,_):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart(m.agent,m.subtask,O),await ce(this.rootDir,a?.stageTaskIds.get(m.agent));let x=await this.spawner.spawn(m.agent,B,$);return e$1.onAgentComplete&&e$1.onAgentComplete(m.agent,x,O),await G(this.rootDir,a?.stageTaskIds.get(m.agent),x.success?"success":"failure"),d.add(m.agent),{step:m,result:x,model:O}}),Te=await Promise.all(T);for(let{step:m,result:O,model:D}of Te){if(c.push(O),O.relay){f.input+=O.relay.metrics.tokens_used.input,f.output+=O.relay.metrics.tokens_used.output,f.total+=O.relay.metrics.tokens_used.total,p+=b$2(O.relay.metrics.tokens_used,D),ue(this.rootDir,{archetype:m.agent,taskType:i,actualTokens:O.relay.metrics.tokens_used,parentTaskId:a?.epicTaskId});let q=O.relay.handoff?.context||`${m.agent} completed: ${O.relay.outputs.decisions.join(", ")||"task done"}`;if(u.set(m.agent,q),m.agent==="architect"&&O.relay){let B=this.extractFilePlanFromRelay(O);if(B&&B.length>0){let $=this.planBuilderStages(B);if($.hasFilePlan&&$.totalBuilders>1){let x=await this.runParallelBuilders($,u.get("architect")||"",e$1);c.push(...x.results),f.input+=x.totalTokens.input,f.output+=x.totalTokens.output,f.total+=x.totalTokens.total,p+=x.totalCost,x.success||(g=false),P={usedFilePlan:true,totalSubPhases:$.stages.length,totalParallelBuilders:$.totalBuilders,filesCreated:$.totalFiles};for(let[_,te]of o){let xe=te.filter(Pe=>Pe.agent!=="builder");o.set(_,xe);}await G(this.rootDir,a?.stageTaskIds.get("builder"),x.success?"success":"failure"),d.add("builder");}}}}!O.success&&m.required&&(g=false);}if(!g||e$1.checkpoints?.afterAgentComplete&&e$1.onCheckpoint&&!await e$1.onCheckpoint(`Stage ${k} completed. Continue to next stage?`))break}let de;if(v&&g){let k=[...c].reverse().find(T=>T.relay?.agent==="reviewer"),b=k?this.parseIterationVerdict(k):null;if(b?.verdict==="changes-requested"){let T=await this.runReviewIteration({builderSubtask:R,firstReview:b,hasTester:F,maxRoundsConfig:y?.defaultMaxRounds??3,options:e$1});c.push(...T.extraResults),f.input+=T.extraTokens.input,f.output+=T.extraTokens.output,f.total+=T.extraTokens.total,p+=T.extraCost,de=T.iterationOutcome;}else k&&!b&&e$1.onMessage&&e$1.onMessage("orchestrator",{type:"text",content:"[iteration] reviewer produced no parseable iteration-verdict \u2014 re-review loop not triggered.",timestamp:new Date().toISOString()});}if(a)for(let[k,b]of a.stageTaskIds)d.has(k)||await G(this.rootDir,b,"failure");return {success:g,results:c,totalTokens:f,totalCost:p,parallelBuilderStats:P,iterationOutcome:de}}async runReviewIteration(t){let{builderSubtask:e,firstReview:s,hasTester:n,maxRoundsConfig:i,options:r}=t,l=i%2===0?i:i+1,o=[e];s.openThreads.length&&o.push("","## Reviewer asked you to resolve:",...s.openThreads.map(u=>`- ${u}`)),s.whatChanged.length&&o.push("","## Reviewer notes:",...s.whatChanged.map(u=>`- ${u}`));let a=u=>r.agentBudgets?.[u]?.maxTokens?"haiku":Se[u]||"sonnet",d=u=>r.agentBudgets?.[u]||r.budget,c=await this.runIterationLoop(o.join(`
20
+ `),{maxRounds:l,mode:"ping-pong",iterateAgent:"builder",reviewAgent:"reviewer",workingDirectory:r.workingDirectory||this.rootDir,mcpServerPath:r.mcpServerPath,resolveModel:a,resolveBudget:d,onRound:r.onAgentComplete?u=>r.onAgentComplete(u.agent,u.spawnResult,a(u.agent)):void 0}),f=c.rounds.map(u=>u.spawnResult),p=0;for(let u of c.rounds)u.spawnResult.relay&&(p+=b$2(u.spawnResult.relay.metrics.tokens_used,a(u.agent)));if(n&&c.converged){let u=await this.spawner.spawn("tester",`Re-test after re-review convergence:
21
+ ${e}`,{model:"haiku",workingDirectory:r.workingDirectory||this.rootDir,mcpServerPath:r.mcpServerPath});f.push(u),u.relay&&(p+=b$2(u.relay.metrics.tokens_used,"haiku"),c.totalTokens.input+=u.relay.metrics.tokens_used.input,c.totalTokens.output+=u.relay.metrics.tokens_used.output,c.totalTokens.total+=u.relay.metrics.tokens_used.total);}return {extraResults:f,extraTokens:c.totalTokens,extraCost:p,iterationOutcome:{converged:c.converged,roundsRun:c.rounds.length,openThreads:c.unresolved?.openThreads??[]}}}extractFilePlanFromRelay(t){if(!t.relay)return;let e=t.relay.handoff?.context||"";if(e.includes("filePlan:"))return this.parseFilePlanFromText(e)}parseFilePlanFromText(t){let e=[],s=t.match(/filePlan:\s*\n([\s\S]*?)(?=\n[a-z_]+:|$)/);if(!s)return;let i=s[1].split(`
22
+ `),r=null,l=false,o={};for(let a of i){let d=a.trim();if(!(!d||d.startsWith("#"))){if(d.startsWith("- group:")){r&&(o.path&&(r.files.push({path:o.path,description:o.description||""}),o={}),e.push(r)),r={group:d.split(":")[1].trim(),subPhase:0,files:[]},l=false;continue}if(r){if(d.startsWith("subPhase:")){r.subPhase=parseInt(d.split(":")[1].trim(),10)||0;continue}if(d==="files:"){l=true;continue}if(l){if(d.startsWith("- path:")){o.path&&r.files.push({path:o.path,description:o.description||""}),o={path:d.split(":").slice(1).join(":").trim().replace(/^["']|["']$/g,"")};continue}if(d.startsWith("description:")){o.description=d.split(":").slice(1).join(":").trim().replace(/^["']|["']$/g,"");continue}}}}}return o.path&&r&&r.files.push({path:o.path,description:o.description||""}),r&&e.push(r),e.length>0?e:void 0}planAgentSequence(t,e){let s=a$1(t),n=t.toLowerCase(),i=K(t),r=[],l=ze(t);if(i.type==="analysis")return e.architect&&r.push({agent:"architect",subtask:`Analyze and recommend: ${t}`,required:true,stage:0,dependsOn:[],model:"opus"}),r;if(i.type==="documentation")return e.architect&&r.push({agent:"architect",subtask:`Document: ${t}`,required:true,stage:0,dependsOn:[],model:"sonnet"}),r;let o=n.includes("design")||n.includes("architect")||n.includes("plan")||n.includes("spec"),a=l||n.includes("auth")||n.includes("security")||n.includes("gate")||s.some(g=>g.startsWith("^"));if(o&&e.architect&&r.push({agent:"architect",subtask:`Design and specify: ${t}`,required:true,stage:0,dependsOn:[],model:"opus"}),a&&e.security&&r.push({agent:"security",subtask:`Review security aspects of: ${t}`,required:l,stage:0,dependsOn:[],model:"opus"}),(n.includes("build")||n.includes("implement")||n.includes("create")||n.includes("add")||n.includes("fix"))&&e.builder){let g=o&&e.architect?["architect"]:[];r.push({agent:"builder",subtask:`Implement: ${t}`,required:true,stage:g.length>0?1:0,dependsOn:g,model:"haiku"});}let c=n.includes("review")||n.includes("check"),f=n.includes("test")||n.includes("verify")||n.includes("validate"),p=r.some(g=>g.agent==="builder"),u=p?2:o?1:0;if(c&&e.reviewer&&r.push({agent:"reviewer",subtask:`Review: ${t}`,required:false,stage:u,dependsOn:p?["builder"]:[],model:"sonnet"}),f&&e.tester&&r.push({agent:"tester",subtask:`Test and validate: ${t}`,required:false,stage:u,dependsOn:p?["builder"]:[],model:"haiku"}),r.length===0){let g=i.recommendedAgents;if(g.includes("architect")&&e.architect&&r.push({agent:"architect",subtask:`Design: ${t}`,required:true,stage:0,dependsOn:[],model:H("architect",i)}),(g.includes("security")||l)&&e.security&&r.push({agent:"security",subtask:`Security review: ${t}`,required:l,stage:0,dependsOn:[],model:"opus"}),g.includes("builder")&&e.builder){let y=r.length>0;r.push({agent:"builder",subtask:`Implement: ${t}`,required:true,stage:y?1:0,dependsOn:r.filter(w=>w.stage===0).map(w=>w.agent),model:H("builder",i)});}if(g.includes("tester")&&e.tester){let y=r.find(w=>w.agent==="builder")?.stage??0;r.push({agent:"tester",subtask:`Test: ${t}`,required:false,stage:y+1,dependsOn:e.builder?["builder"]:[],model:H("tester",i)});}}try{let g=a$2(t,e),y=new Set(r.map(v=>v.agent)),w=new Set(["documentor"]),I=(r.length>0?Math.max(...r.map(v=>v.stage)):-1)+1,F=r.map(v=>v.agent);for(let v of g){if(y.has(v.name)||w.has(v.name)||!e[v.name]||v.confidence==="low")continue;let P=e[v.name];r.push({agent:v.name,subtask:`Contribute (${P?.focus??"specialist"}): ${t}`,required:!1,stage:I,dependsOn:F,model:P?.defaultModel??"sonnet"}),y.add(v.name);}}catch{}return r.sort((g,y)=>g.stage-y.stage)}groupByStage(t){let e=new Map;for(let s of t){let n=e.get(s.stage)||[];n.push({agent:s.agent,subtask:s.subtask,required:s.required,dependsOn:s.dependsOn}),e.set(s.stage,n);}return e}generateOrchestrationId(){let t=new Date().toISOString().slice(0,10),e=Math.random().toString(36).substring(2,8);return `orch-${t}-${e}`}planBuilderStages(t){if(!t||t.length===0)return {hasFilePlan:false,stages:[{subPhase:0,builders:[{agent:"builder",group:"all",files:[],availableFiles:[]}]}],totalFiles:0,totalBuilders:1};let e=new Map;for(let o of t){let a=e.get(o.subPhase)||[];a.push(o),e.set(o.subPhase,a);}let s=[],n=[...e.keys()].sort((o,a)=>o-a),i=[],r=0,l=0;for(let o of n){let a=e.get(o),d=[];for(let c=0;c<a.length;c++){let f=a[c];l+=f.files.length,r++,d.push({agent:`builder-${o}-${c}`,group:f.group,files:f.files,availableFiles:[...i]});}s.push({subPhase:o,builders:d});for(let c of a)for(let f of c.files)i.push(f.path);}return {hasFilePlan:true,stages:s,totalFiles:l,totalBuilders:r}}buildParallelBuilderPrompt(t,e,s,n){let i=[];i.push(`You are a BUILDER agent responsible for implementing the **${n}** group.`),i.push(""),i.push("## Your Assignment"),i.push(""),i.push("### Files to Create:");for(let r of t)i.push(`- \`${r.path}\`: ${r.description}`);if(i.push(""),e.length>0){i.push("### Available Files (already created):"),i.push("These files exist and you can import from them:");for(let r of e)i.push(`- \`${r}\``);i.push("");}return s&&(i.push("### Context from Architect:"),i.push(s),i.push("")),i.push("### Instructions:"),i.push("1. Create ONLY the files assigned to you"),i.push("2. You can import from available files (already created)"),i.push("3. Follow existing patterns in the codebase"),i.push("4. Use the Paradigm logger (not console.log)"),i.push("5. End with the standard Agent Relay block"),i.join(`
23
+ `)}async runParallelBuilders(t,e,s){let n=[],i={input:0,output:0,total:0},r=0,l=true;for(let o of t.stages){if(s.checkpoints?.beforeAgentSpawn&&s.onCheckpoint){let c=o.builders.map(p=>p.group).join(", ");if(!await s.onCheckpoint(`Builder Sub-phase ${o.subPhase}: ${c}${o.builders.length>1?" (parallel)":""}`)){l=false;break}}let a=o.builders.map(async c=>{let f=this.buildParallelBuilderPrompt(c.files,c.availableFiles,e,c.group),p={model:"haiku",workingDirectory:s.workingDirectory||this.rootDir,mcpServerPath:s.mcpServerPath,budget:s.budget,onMessage:s.onMessage?g=>s.onMessage(c.agent,g):void 0,onCheckpoint:s.onCheckpoint};s.onAgentStart&&s.onAgentStart(c.agent,`Implement ${c.group}`,"haiku");let u=await this.spawner.spawn("builder",f,p);return s.onAgentComplete&&s.onAgentComplete(c.agent,u,"haiku"),{builder:c,result:u}}),d=await Promise.all(a);for(let{result:c}of d)n.push(c),c.relay&&(i.input+=c.relay.metrics.tokens_used.input,i.output+=c.relay.metrics.tokens_used.output,i.total+=c.relay.metrics.tokens_used.total,r+=b$2(c.relay.metrics.tokens_used,"haiku")),c.success||(l=false);if(!l||s.checkpoints?.afterAgentComplete&&s.onCheckpoint&&!await s.onCheckpoint(`Sub-phase ${o.subPhase} complete. Continue to next sub-phase?`))break}return {success:l,results:n,totalTokens:i,totalCost:r}}async runIterationLoop(t,e,s){if(!Number.isInteger(e.maxRounds)||e.maxRounds<1)throw new Error(`runIterationLoop: maxRounds must be an integer >= 1 (got ${e.maxRounds})`);if(e.mode==="ping-pong"&&!e.reviewAgent)throw new Error("runIterationLoop: ping-pong mode requires reviewAgent");let n=s??(a=>we(this.rootDir,{id:ke(a.agent,a.round),agent:a.agent,corrections:a.corrections,symbols:a.symbols,round:a.round})),i=[],r={input:0,output:0,total:0},l=null,o=null;for(let a=1;a<=e.maxRounds;a++){let d=this.iterationAgentForRound(e,a),c=this.buildIterationTask(t,l,a),f={workingDirectory:e.workingDirectory||this.rootDir,mcpServerPath:e.mcpServerPath,model:e.resolveModel?.(d),budget:e.resolveBudget?.(d)},p=await this.spawner.spawn(d,c,f);p.relay&&(r.input+=p.relay.metrics.tokens_used.input,r.output+=p.relay.metrics.tokens_used.output,r.total+=p.relay.metrics.tokens_used.total);let u=this.parseIterationVerdict(p);u&&(o=u);let g=false;if(this.beliefRevised(u,l)){let w=u.corrections.length>0?u.corrections:this.reopenedClaims(u,l);n({agent:d,corrections:w,symbols:p.relay?.outputs.symbols??[],round:a}),g=true;}let y={round:a,agent:d,spawnResult:p,delta:u,promoted:g};if(i.push(y),e.onRound?.(y),!p.success)return this.unresolvedResult(i,o,r,"spawn-failed",a);if(u===null)return this.unresolvedResult(i,o,r,"unparseable-verdict",a);if(this.isConverged(u,e,d))return {converged:true,rounds:i,finalDelta:u,totalTokens:r};l=u;}return this.unresolvedResult(i,o,r,"max-rounds",e.maxRounds)}unresolvedResult(t,e,s,n,i){return {converged:false,rounds:t,finalDelta:e,totalTokens:s,unresolved:{reason:n,roundsRun:i,openThreads:e?.openThreads??[]}}}iterationAgentForRound(t,e){return t.mode==="single-role"||e%2===1?t.iterateAgent:t.reviewAgent}isConverged(t,e,s){return t.verdict!=="approved"?false:e.mode==="single-role"?t.openThreads.length===0:s===e.reviewAgent}reopenedClaims(t,e){return e?t.whatChanged.filter(s=>e.alreadyVerified.includes(s)):[]}beliefRevised(t,e){return t?t.corrections.length>0?true:this.reopenedClaims(t,e).length>0:false}buildIterationTask(t,e,s){let n=[t];return e&&(n.push("",`## Iteration delta (entering round ${s})`),n.push(`- Verdict so far: ${e.verdict}`),e.whatChanged.length&&n.push("- Changed last round:",...e.whatChanged.map(i=>` - ${i}`)),e.alreadyVerified.length&&n.push("- Already verified (do NOT re-litigate):",...e.alreadyVerified.map(i=>` - ${i}`)),e.openThreads.length&&n.push("- Open threads to resolve:",...e.openThreads.map(i=>` - ${i}`))),n.push("",ve),n.join(`
24
24
  `)}parseIterationVerdict(t){if(!t.relay)return null;let e=[];t.relay.handoff?.context&&e.push(t.relay.handoff.context),t.relay.outputs?.decisions?.length&&e.push(t.relay.outputs.decisions.join(`
25
- `)),t.relay.rawResponse&&e.push(t.relay.rawResponse);for(let s of e){let n=Ye(s);if(n)return n}return null}},Se=["## Required: end with an iteration-verdict block","After your work, append a fenced block tagged `iteration-verdict` with JSON:","```iteration-verdict","{",' "verdict": "approved" | "changes-requested",',' "whatChanged": ["progress made this round"],',' "alreadyVerified": ["settled claims; do not revisit"],',' "openThreads": ["unresolved items for the next round"],',' "corrections": ["only genuine belief revisions: was X, now Y"]',"}","```",'Use "approved" only when no open threads remain. Leave "corrections" empty if nothing you previously believed changed.'].join(`
26
- `);function Ye(h){let t=[...h.matchAll(/```iteration-verdict\s*\n([\s\S]*?)```/g)];if(t.length===0)return null;for(let e=t.length-1;e>=0;e--)try{let s=JSON.parse(t[e][1].trim());if(s.verdict!=="approved"&&s.verdict!=="changes-requested")continue;return {verdict:s.verdict,whatChanged:Array.isArray(s.whatChanged)?s.whatChanged:[],alreadyVerified:Array.isArray(s.alreadyVerified)?s.alreadyVerified:[],openThreads:Array.isArray(s.openThreads)?s.openThreads:[],corrections:Array.isArray(s.corrections)?s.corrections:[]}}catch{continue}return null}var Oe=class{rootDir;orchestrationsDir;constructor(t){this.rootDir=t,this.orchestrationsDir=C.join(t,".paradigm","orchestrations"),this.ensureOrchestrationDir();}async startBackground(t,e={}){let s=this.generateId(),n=C.join(this.orchestrationsDir,`${s}.output`),i=C.join(this.orchestrationsDir,`${s}.log`),r={id:s,task:t,status:"pending",mode:e.mode||"faceted",created:new Date().toISOString(),outputFile:n,logFile:i,artifacts:[]};return this.saveOrchestration(r),this.spawnOrchestration(s,t,e),r}getOrchestration(t){let e=C.join(this.orchestrationsDir,`${t}.yaml`);if(!S.existsSync(e))return null;try{let s=S.readFileSync(e,"utf-8");return W.load(s)}catch{return null}}listOrchestrations(t={}){let e=S.readdirSync(this.orchestrationsDir).filter(n=>n.endsWith(".yaml")&&!n.includes("output")&&!n.includes("log")).sort().reverse(),s=[];for(let n of e){if(t.limit&&s.length>=t.limit)break;let i=C.join(this.orchestrationsDir,n);try{let r=S.readFileSync(i,"utf-8"),l=W.load(r);if(t.status&&!(Array.isArray(t.status)?t.status:[t.status]).includes(l.status))continue;s.push(l);}catch{}}return s}getRunning(){return this.listOrchestrations({status:"running"})}getOutput(t,e={}){let s=this.getOrchestration(t);if(!s||!S.existsSync(s.outputFile))return "";let n=S.readFileSync(s.outputFile,"utf-8");return e.lines?n.split(`
25
+ `)),t.relay.rawResponse&&e.push(t.relay.rawResponse);for(let s of e){let n=Ke(s);if(n)return n}return null}},ve=["## Required: end with an iteration-verdict block","After your work, append a fenced block tagged `iteration-verdict` with JSON:","```iteration-verdict","{",' "verdict": "approved" | "changes-requested",',' "whatChanged": ["progress made this round"],',' "alreadyVerified": ["settled claims; do not revisit"],',' "openThreads": ["unresolved items for the next round"],',' "corrections": ["only genuine belief revisions: was X, now Y"]',"}","```",'Use "approved" only when no open threads remain. Leave "corrections" empty if nothing you previously believed changed.'].join(`
26
+ `);function Ke(h){let t=[...h.matchAll(/```iteration-verdict\s*\n([\s\S]*?)```/g)];if(t.length===0)return null;for(let e=t.length-1;e>=0;e--)try{let s=JSON.parse(t[e][1].trim());if(s.verdict!=="approved"&&s.verdict!=="changes-requested")continue;return {verdict:s.verdict,whatChanged:Array.isArray(s.whatChanged)?s.whatChanged:[],alreadyVerified:Array.isArray(s.alreadyVerified)?s.alreadyVerified:[],openThreads:Array.isArray(s.openThreads)?s.openThreads:[],corrections:Array.isArray(s.corrections)?s.corrections:[]}}catch{continue}return null}var Re=class{rootDir;orchestrationsDir;constructor(t){this.rootDir=t,this.orchestrationsDir=C.join(t,".paradigm","orchestrations"),this.ensureOrchestrationDir();}async startBackground(t,e={}){let s=this.generateId(),n=C.join(this.orchestrationsDir,`${s}.output`),i=C.join(this.orchestrationsDir,`${s}.log`),r={id:s,task:t,status:"pending",mode:e.mode||"faceted",created:new Date().toISOString(),outputFile:n,logFile:i,artifacts:[]};return this.saveOrchestration(r),this.spawnOrchestration(s,t,e),r}getOrchestration(t){let e=C.join(this.orchestrationsDir,`${t}.yaml`);if(!S.existsSync(e))return null;try{let s=S.readFileSync(e,"utf-8");return W.load(s)}catch{return null}}listOrchestrations(t={}){let e=S.readdirSync(this.orchestrationsDir).filter(n=>n.endsWith(".yaml")&&!n.includes("output")&&!n.includes("log")).sort().reverse(),s=[];for(let n of e){if(t.limit&&s.length>=t.limit)break;let i=C.join(this.orchestrationsDir,n);try{let r=S.readFileSync(i,"utf-8"),l=W.load(r);if(t.status&&!(Array.isArray(t.status)?t.status:[t.status]).includes(l.status))continue;s.push(l);}catch{}}return s}getRunning(){return this.listOrchestrations({status:"running"})}getOutput(t,e={}){let s=this.getOrchestration(t);if(!s||!S.existsSync(s.outputFile))return "";let n=S.readFileSync(s.outputFile,"utf-8");return e.lines?n.split(`
27
27
  `).slice(-e.lines).join(`
28
28
  `):n}async accept(t,e={}){let s=this.getOrchestration(t);if(!s)return false;if(s.status!=="completed")throw new Error(`Cannot accept orchestration in '${s.status}' status`);return s.status="accepted",this.saveOrchestration(s),true}async reject(t,e={}){let s=this.getOrchestration(t);if(!s)return false;if(s.status!=="completed")throw new Error(`Cannot reject orchestration in '${s.status}' status`);if(s.status="rejected",s.error=e.reason,this.saveOrchestration(s),e.cleanup&&s.artifacts.length>0){for(let n of s.artifacts)if(n.action==="created"){let i=C.join(this.rootDir,n.path);S.existsSync(i)&&S.unlinkSync(i);}}return true}async getDiff(t){let e=this.getOrchestration(t);if(!e)return "";if(e.artifacts.length===0)return "No file changes in this orchestration.";let s=[];s.push(`Orchestration: ${t}`),s.push(`Task: ${e.task}`),s.push(`Status: ${e.status}`),s.push(""),s.push("Files:");for(let n of e.artifacts){let i=n.action==="created"?"+":n.action==="modified"?"~":"-";s.push(` ${i} ${n.path}`);}return s.join(`
29
29
  `)}markComplete(t,e){let s=this.getOrchestration(t);if(s){s.status=e.success?"completed":"failed",s.completed=new Date().toISOString(),s.result=e,s.parallelBuilderStats=e.parallelBuilderStats;for(let n of e.agentResults)if(n.relay?.outputs.artifacts)for(let i of n.relay.outputs.artifacts)s.artifacts.push(i);this.saveOrchestration(s);}}async notify(t,e=["bell"]){let s=this.getOrchestration(t);if(s)for(let n of e)switch(n){case "bell":process.stdout.write("\x07");break;case "desktop":try{process.platform==="darwin"?spawn("osascript",["-e",`display notification "Orchestration ${s.status}: ${s.task.slice(0,50)}" with title "Paradigm"`]):spawn("notify-send",["Paradigm",`Orchestration ${s.status}: ${s.task.slice(0,50)}`]);}catch{}break;case "file":let i=C.join(this.orchestrationsDir,`${t}.status`);S.writeFileSync(i,JSON.stringify({id:t,status:s.status,completed:s.completed,task:s.task}));break;}}ensureOrchestrationDir(){S.existsSync(this.orchestrationsDir)||S.mkdirSync(this.orchestrationsDir,{recursive:true});}generateId(){let t=new Date().toISOString().slice(0,10),e=Date.now().toString(36),s=Math.random().toString(36).substring(2,6);return `orch-${t}-${e}-${s}`}saveOrchestration(t){let e=C.join(this.orchestrationsDir,`${t.id}.yaml`);S.writeFileSync(e,W.dump(t));}spawnOrchestration(t,e,s){let n=this.getOrchestration(t);n&&(n.status="running",n.started=new Date().toISOString(),this.saveOrchestration(n)),(async()=>{try{let i=new Q(this.rootDir);await i.initialize();let r=S.createWriteStream(n.outputFile,{flags:"a"}),l=await i.orchestrate(e,{...s,onMessage:(o,a)=>{a.type==="text"&&r.write(`[${o}] ${a.content}
30
30
  `),s.onMessage?.(o,a);},onAgentStart:(o,a,d)=>{r.write(`
31
31
  \u25B6 ${o}: ${a}
32
32
  `),s.onAgentStart?.(o,a,d);},onAgentComplete:(o,a,d)=>{let c=a.success?"\u2713":"\u2717";r.write(`${c} ${o} completed
33
- `),s.onAgentComplete?.(o,a,d);}});r.end(),this.markComplete(t,l),s.notify&&await this.notify(t,s.notifyMethods||["bell"]);}catch(i){let r=this.getOrchestration(t);r&&(r.status="failed",r.error=i instanceof Error?i.message:String(i),r.completed=new Date().toISOString(),this.saveOrchestration(r));}})();}};export{Q as a,Oe as b};
33
+ `),s.onAgentComplete?.(o,a,d);}});r.end(),this.markComplete(t,l),s.notify&&await this.notify(t,s.notifyMethods||["bell"]);}catch(i){let r=this.getOrchestration(t);r&&(r.status="failed",r.error=i instanceof Error?i.message:String(i),r.completed=new Date().toISOString(),this.saveOrchestration(r));}})();}};export{Q as a,Re as b};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {s,r as r$1,u,i,k,c as c$1}from'./chunk-M7JHVVDW.js';import*as c from'fs';import*as r from'path';import*as x from'js-yaml';var f=".paradigm/university",j="pack.yaml";function B(n){let e=l(n);if(!e||!Array.isArray(e.sections))return [];let a=[];for(let t of e.sections)t&&typeof t.id=="string"&&t.id.length>0&&a.push({id:t.id,name:typeof t.name=="string"?t.name:void 0});return a}function l(n){let e=r.join(n,j);if(!c.existsSync(e))return null;try{let a=c.readFileSync(e,"utf8");return x.load(a)??null}catch{return null}}function b(n){let e=[],a=r.join(n,"node_modules","@a-company","university"),t=l(a);t&&t.id&&t.tenant_kind&&e.push({id:t.id,name:t.name,tenantKind:t.tenant_kind,packRoot:a,disciplines:t.disciplines,entryCount:s(a)});let i=r.join(n,f);if(c.existsSync(i)){let s$1=l(i),o=s$1?.id??r.basename(n),P=s$1?.tenant_kind??"project";e.push({id:o,name:s$1?.name,tenantKind:P,packRoot:i,disciplines:s$1?.disciplines,entryCount:s(i)});try{let R=c.readdirSync(i,{withFileTypes:!0});for(let u of R){if(!u.isDirectory()||u.name.startsWith("."))continue;let m=r.join(i,u.name),d=l(m);!d||!d.id||e.push({id:d.id,name:d.name,tenantKind:d.tenant_kind??"project",packRoot:m,disciplines:d.disciplines,entryCount:s(m)});}}catch{}}return e}function D(n,e){let a=b(n),t;if(e.pack){let i=a.find(s=>s.id===e.pack);if(i)t={packId:i.id,packRoot:i.packRoot,tenantKind:i.tenantKind,hasManifest:true};else {let s=r.join(n,f);t={packId:e.pack,packRoot:s,hasManifest:false};}}else if(e.project){let i=a.find(o=>o.tenantKind==="project"&&!o.disciplines),s=r.join(n,f);i?t={packId:i.id,packRoot:i.packRoot,tenantKind:i.tenantKind,hasManifest:true}:t={packId:r.basename(n),packRoot:s,hasManifest:false};}else {let i=a.find(s=>s.tenantKind==="project");if(i)t={packId:i.id,packRoot:i.packRoot,tenantKind:i.tenantKind,hasManifest:true};else {let s=a.find(o=>o.tenantKind==="first-party");if(s)t={packId:s.id,packRoot:s.packRoot,tenantKind:s.tenantKind,hasManifest:true};else {let o=r.join(n,f);t={packId:r.basename(n),packRoot:o,hasManifest:false};}}}if(e.discipline){let i=r.join(t.packRoot,e.discipline),s=l(i);s&&s.id?(t.subPackRoot=i,t.subPackId=s.id):c.existsSync(i)&&(t.subPackRoot=i,t.subPackId=`${t.packId}-${e.discipline}`);}return t}function w(n){return !!(n.pack||n.project||n.discipline)}function N(n){let e=r$1(n);return e&&s(n)>0?e:null}function F(n){return u(n,n)}function E(n,e,a,t){let i$1=I(e,t);return i(n,i$1,a,{packRoot:t,stampPackId:false,resolveDefaultPack:false})}function T(n,e,a){let t=I(e,a);return k(n,t,{packRoot:a,stampPackId:false,resolveDefaultPack:false})}function I(n,e){if(!e)return n;let a=c$1(e);return a&&!n.pack_id?{...n,pack_id:a}:n}export{B as a,b,D as c,w as d,N as e,F as f,E as g,T as h};
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import {a,e,d}from'./chunk-QO7YPQXC.js';import'./chunk-5TAVYPOV.js';import*as u from'fs';import*as m from'path';import {execSync}from'child_process';import n from'chalk';import*as w from'js-yaml';function $(s){return s.match(/(?:^|\s)((?:\/|\.\/|[a-zA-Z0-9_-]+\/)[^\s,;:'"]+\.[a-zA-Z]{1,10})\b/)?.[1]}async function R(s,a$1){try{let r=a(s),d$1=[];try{d$1=execSync("git diff --name-only HEAD",{cwd:s,encoding:"utf8",timeout:5e3}).trim().split(`
3
- `).filter(Boolean);}catch{}let l;try{l=execSync("git status --porcelain",{cwd:s,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let c=m.join(s,"portal.yaml"),f=!1;if(u.existsSync(c))try{let t=u.readFileSync(c,"utf8"),e=w.load(t);f=e?.routes!=null&&Object.keys(e.routes).length>0;}catch{}let i=e({toolsCalled:[],filesModified:d$1,symbolsTouched:[],loreRecorded:!1,hasPortalRoutes:f,taskAddsRoutes:!1,gitClean:l}),o=d(r,a$1,i),g=0;if(o.evaluations.length>0)try{let t=m.join(s,".paradigm","sentinel");if(u.existsSync(t)){let{SentinelStorage:e}=await import('./dist-VGFSP3XM.js'),p=new e(t);for(let b of o.evaluations)p.recordPracticeEvent({habitId:b.habit.id,habitCategory:b.habit.category,result:b.result,engineer:"agent",sessionId:`cli-${Date.now().toString(36)}`,symbolsTouched:[],filesModified:d$1,notes:b.reason}),g++;}}catch{}let h=m.join(s,".paradigm",".habits-blocking");try{if(a$1==="on-stop"&&o.blocksCompletion){let t=o.evaluations.filter(e=>e.result==="skipped"&&e.habit.severity==="block").map(e=>`${e.habit.name}: ${e.reason}`);u.writeFileSync(h,t.join(`
4
- `),"utf8");}else a$1==="on-stop"&&u.existsSync(h)&&u.unlinkSync(h);}catch{}return {trigger:a$1,evaluation:{total:o.summary.total,followed:o.summary.followed,skipped:o.summary.skipped,partial:o.summary.partial,blockingViolations:o.summary.blockingViolations,blocksCompletion:o.blocksCompletion},habits:o.evaluations.map(t=>({id:t.habit.id,name:t.habit.name,category:t.habit.category,severity:t.habit.severity,result:t.result,reason:t.reason,evidence:t.evidence})),recorded:g}}catch{return null}}async function P(s,a){let r=m.join(s,".paradigm","aspect-graph.db");if(!u.existsSync(r))return {driftedCount:0,healedCount:0,cleanCount:0,missingCount:0,details:[]};try{let{driftCheckCommand:d}=await import('./drift-ILZE5BFJ.js'),l="",c=console.log;console.log=f=>{l=f;};try{await d({json:!0,autoHeal:a});}finally{console.log=c;}return l?JSON.parse(l):null}catch{return null}}async function B(s){if(!u.existsSync(m.join(s,"portal.yaml")))return null;try{let{checkPortalCompliance:a}=await import('./portal-compliance-JONQ4SOP.js'),r=await a(s);return {status:r.status,declaredButUnusedCount:r.declaredButUnused.length,usedButUndeclaredCount:r.usedButUndeclared.length,properlyDeclaredCount:r.properlyDeclared.length,declaredButUnused:r.declaredButUnused,usedButUndeclared:r.usedButUndeclared,properlyDeclared:r.properlyDeclared,portalError:r.portalError,...r.nearMatches&&r.nearMatches.length>0?{suggestions:r.nearMatches.map(d=>({gate:d.gate,didYouMean:d.didYouMean,distance:d.distance}))}:{}}}catch{return null}}async function j(s){try{let{runPostflightLearning:a}=await import('./ambient-QB7V4TBR.js');return await a(s)}catch{return null}}async function A(s){let a=process.cwd(),r=s.trigger||"on-stop",d=s.autoHeal!==false,l=[],c=[],f=await R(a,r),i=await P(a,d),o=await B(a);if(f?.evaluation.blocksCompletion){let t=f.habits.filter(e=>e.result==="skipped"&&e.severity==="block");for(let e of t){let p=`Blocking habit not satisfied: ${e.name} \u2014 ${e.reason}`;l.push(p),c.push({message:p,source:"habits",file:$(e.reason),severity:"blocking"});}}if(i&&i.driftedCount>0){let t=`${i.driftedCount} aspect anchor(s) have drifted (content genuinely changed). Run paradigm_aspect_check to review.`;l.push(t);for(let e of i.details.filter(p=>p.status==="drifted"))c.push({message:`Aspect ~${e.aspectId} drifted at lines ${e.startLine}-${e.endLine}`,source:"drift",file:e.path,severity:"advisory"});c.filter(e=>e.source==="drift").length===0&&c.push({message:t,source:"drift",severity:"advisory"});}if(o&&o.portalError?.kind==="unparseable"){let e=`portal.yaml unparseable: ${o.portalError.errorClass} \u2014 run 'paradigm doctor' for details`;l.push(e),c.push({message:e,source:"portal",file:"portal.yaml",severity:"blocking"});}else if(o&&o.usedButUndeclaredCount>0){let t=o.usedButUndeclared.filter(e=>e!=="__portal_unparseable__");if(t.length>0){let e=`${t.length} gate(s) used in code but not declared in portal.yaml: ${t.join(", ")}`;l.push(e);for(let p of t)c.push({message:`Gate ^${p} used in code but not declared in portal.yaml`,source:"portal",file:"portal.yaml",severity:"blocking"});}}let g=null;s.learn&&(g=await j(a));let h={habits:f,drift:i,portal:o,violations:l,structuredViolations:c,postflight:s.learn?g:void 0};if(s.json)console.log(JSON.stringify(h));else {if(console.log(n.magenta(`
2
+ import {a}from'./chunk-FNYYQNJY.js';import {n as n$1,m as m$1}from'./chunk-WMTES556.js';import'./chunk-5TAVYPOV.js';import*as u from'fs';import*as m from'path';import {execSync}from'child_process';import n from'chalk';import*as w from'js-yaml';function $(s){return s.match(/(?:^|\s)((?:\/|\.\/|[a-zA-Z0-9_-]+\/)[^\s,;:'"]+\.[a-zA-Z]{1,10})\b/)?.[1]}async function R(s,a$1){try{let r=a(s),d=[];try{d=execSync("git diff --name-only HEAD",{cwd:s,encoding:"utf8",timeout:5e3}).trim().split(`
3
+ `).filter(Boolean);}catch{}let l;try{l=execSync("git status --porcelain",{cwd:s,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let c=m.join(s,"portal.yaml"),f=!1;if(u.existsSync(c))try{let t=u.readFileSync(c,"utf8"),e=w.load(t);f=e?.routes!=null&&Object.keys(e.routes).length>0;}catch{}let i=n$1({toolsCalled:[],filesModified:d,symbolsTouched:[],loreRecorded:!1,hasPortalRoutes:f,taskAddsRoutes:!1,gitClean:l}),o=m$1(r,a$1,i),g=0;if(o.evaluations.length>0)try{let t=m.join(s,".paradigm","sentinel");if(u.existsSync(t)){let{SentinelStorage:e}=await import('./dist-VGFSP3XM.js'),p=new e(t);for(let b of o.evaluations)p.recordPracticeEvent({habitId:b.habit.id,habitCategory:b.habit.category,result:b.result,engineer:"agent",sessionId:`cli-${Date.now().toString(36)}`,symbolsTouched:[],filesModified:d,notes:b.reason}),g++;}}catch{}let h=m.join(s,".paradigm",".habits-blocking");try{if(a$1==="on-stop"&&o.blocksCompletion){let t=o.evaluations.filter(e=>e.result==="skipped"&&e.habit.severity==="block").map(e=>`${e.habit.name}: ${e.reason}`);u.writeFileSync(h,t.join(`
4
+ `),"utf8");}else a$1==="on-stop"&&u.existsSync(h)&&u.unlinkSync(h);}catch{}return {trigger:a$1,evaluation:{total:o.summary.total,followed:o.summary.followed,skipped:o.summary.skipped,partial:o.summary.partial,blockingViolations:o.summary.blockingViolations,blocksCompletion:o.blocksCompletion},habits:o.evaluations.map(t=>({id:t.habit.id,name:t.habit.name,category:t.habit.category,severity:t.habit.severity,result:t.result,reason:t.reason,evidence:t.evidence})),recorded:g}}catch{return null}}async function P(s,a){let r=m.join(s,".paradigm","aspect-graph.db");if(!u.existsSync(r))return {driftedCount:0,healedCount:0,cleanCount:0,missingCount:0,details:[]};try{let{driftCheckCommand:d}=await import('./drift-ILZE5BFJ.js'),l="",c=console.log;console.log=f=>{l=f;};try{await d({json:!0,autoHeal:a});}finally{console.log=c;}return l?JSON.parse(l):null}catch{return null}}async function B(s){if(!u.existsSync(m.join(s,"portal.yaml")))return null;try{let{checkPortalCompliance:a}=await import('./portal-compliance-JONQ4SOP.js'),r=await a(s);return {status:r.status,declaredButUnusedCount:r.declaredButUnused.length,usedButUndeclaredCount:r.usedButUndeclared.length,properlyDeclaredCount:r.properlyDeclared.length,declaredButUnused:r.declaredButUnused,usedButUndeclared:r.usedButUndeclared,properlyDeclared:r.properlyDeclared,portalError:r.portalError,...r.nearMatches&&r.nearMatches.length>0?{suggestions:r.nearMatches.map(d=>({gate:d.gate,didYouMean:d.didYouMean,distance:d.distance}))}:{}}}catch{return null}}async function j(s){try{let{runPostflightLearning:a}=await import('./ambient-VCTUHHIG.js');return await a(s)}catch{return null}}async function A(s){let a=process.cwd(),r=s.trigger||"on-stop",d=s.autoHeal!==false,l=[],c=[],f=await R(a,r),i=await P(a,d),o=await B(a);if(f?.evaluation.blocksCompletion){let t=f.habits.filter(e=>e.result==="skipped"&&e.severity==="block");for(let e of t){let p=`Blocking habit not satisfied: ${e.name} \u2014 ${e.reason}`;l.push(p),c.push({message:p,source:"habits",file:$(e.reason),severity:"blocking"});}}if(i&&i.driftedCount>0){let t=`${i.driftedCount} aspect anchor(s) have drifted (content genuinely changed). Run paradigm_aspect_check to review.`;l.push(t);for(let e of i.details.filter(p=>p.status==="drifted"))c.push({message:`Aspect ~${e.aspectId} drifted at lines ${e.startLine}-${e.endLine}`,source:"drift",file:e.path,severity:"advisory"});c.filter(e=>e.source==="drift").length===0&&c.push({message:t,source:"drift",severity:"advisory"});}if(o&&o.portalError?.kind==="unparseable"){let e=`portal.yaml unparseable: ${o.portalError.errorClass} \u2014 run 'paradigm doctor' for details`;l.push(e),c.push({message:e,source:"portal",file:"portal.yaml",severity:"blocking"});}else if(o&&o.usedButUndeclaredCount>0){let t=o.usedButUndeclared.filter(e=>e!=="__portal_unparseable__");if(t.length>0){let e=`${t.length} gate(s) used in code but not declared in portal.yaml: ${t.join(", ")}`;l.push(e);for(let p of t)c.push({message:`Gate ^${p} used in code but not declared in portal.yaml`,source:"portal",file:"portal.yaml",severity:"blocking"});}}let g=null;s.learn&&(g=await j(a));let h={habits:f,drift:i,portal:o,violations:l,structuredViolations:c,postflight:s.learn?g:void 0};if(s.json)console.log(JSON.stringify(h));else {if(console.log(n.magenta(`
5
5
  Paradigm Compliance Check
6
6
  `)),f){let{evaluation:t}=f,e=t.blocksCompletion?n.red:n.green;console.log(n.white(" Habits:")),console.log(` ${e(`${t.followed} followed, ${t.skipped} skipped, ${t.partial} partial`)}`),t.blockingViolations>0&&console.log(n.red(` ${t.blockingViolations} blocking violation(s)`)),console.log();}if(i&&(console.log(n.white(" Drift:")),i.healedCount>0&&console.log(n.green(` Auto-healed: ${i.healedCount} shifted anchor(s)`)),i.cleanCount>0&&console.log(n.green(` Clean: ${i.cleanCount} anchor(s)`)),i.driftedCount>0&&console.log(n.red(` Drifted: ${i.driftedCount} anchor(s)`)),i.missingCount>0&&console.log(n.yellow(` Missing: ${i.missingCount} anchor file(s)`)),console.log()),o){console.log(n.white(" Portal:"));let t=o.status==="compliant"?n.green:o.status==="warnings"?n.yellow:n.red;console.log(` Status: ${t(o.status)}`),o.usedButUndeclaredCount>0&&console.log(n.red(` ${o.usedButUndeclaredCount} undeclared gate(s)`)),console.log();}if(g){if(console.log(n.white(" Postflight Learning:")),g.journalsWritten>0){console.log(n.green(` Journals written: ${g.journalsWritten}`));for(let[t,e]of Object.entries(g.journalsByAgent))e>0&&console.log(n.gray(` ${t}: ${e} entries`));}else console.log(n.gray(" No verdicts to learn from"));g.promoted>0&&console.log(n.green(` Promoted to notebooks: ${g.promoted}`)),console.log();}if(l.length>0){console.log(n.red(` ${l.length} violation(s):`));for(let t of l)console.log(n.red(` - ${t}`));}else console.log(n.green(" All checks passed."));console.log();}l.length>0&&(process.exitCode=1);}export{A as complianceCheckCommand};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {m as m$1,o,C,B,r}from'./chunk-4GC35IFF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import {a}from'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';import*as u from'fs';import*as m from'path';import e from'chalk';import F from'ora';function I(t){let o={gates:[],signals:[],components:[],flows:[],aspects:[]};for(let r of t){if(!r||r.length<2)continue;switch(r[0]){case "^":o.gates.push(r);break;case "!":o.signals.push(r);break;case "#":o.components.push(r);break;case "$":o.flows.push(r);break;case "~":o.aspects.push(r);break}}return o}function T(t,o){let r$1={},g={},l=B(t),a=C(t);for(let s of a){let n=I(s.references),i={type:s.type,path:s.filePath,references:s.references,referencedBy:s.referencedBy};s.description&&(i.description=s.description),s.tags&&s.tags.length>0&&(i.tags=s.tags),n.gates.length>0&&(i.gates=n.gates),n.signals.length>0&&(i.signals=n.signals),n.components.length>0&&(i.components=n.components),n.flows.length>0&&(i.flows=n.flows),n.aspects.length>0&&(i.aspects=n.aspects),r$1[s.symbol]=i;}let y=r(t,"flow");for(let s of y){let n=s.data,i=n?.sequence||n?.gates||s.references;g[s.symbol]={description:s.description,sequence:i};}return {version:"1.0",generated:new Date().toISOString(),project:o,stats:{components:l.component,flows:l.flow,gates:l.gate,signals:l.signal,aspects:l.aspect,total:Object.values(l).reduce((s,n)=>s+n,0)},stars:r$1,orbits:g}}async function z(t,o$1={}){let r=process.cwd(),g=t?m.resolve(r,t):r,l=m.basename(g),a$1=o$1.format||"json";o$1.quiet||console.log(e.blue(`
2
+ import {m as m$1,o,C,B,r}from'./chunk-D6BSCELB.js';import'./chunk-K6TLYNRQ.js';import'./chunk-ZJQY5PPP.js';import {a}from'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';import*as u from'fs';import*as m from'path';import e from'chalk';import F from'ora';function I(t){let o={gates:[],signals:[],components:[],flows:[],aspects:[]};for(let r of t){if(!r||r.length<2)continue;switch(r[0]){case "^":o.gates.push(r);break;case "!":o.signals.push(r);break;case "#":o.components.push(r);break;case "$":o.flows.push(r);break;case "~":o.aspects.push(r);break}}return o}function T(t,o){let r$1={},g={},l=B(t),a=C(t);for(let s of a){let n=I(s.references),i={type:s.type,path:s.filePath,references:s.references,referencedBy:s.referencedBy};s.description&&(i.description=s.description),s.tags&&s.tags.length>0&&(i.tags=s.tags),n.gates.length>0&&(i.gates=n.gates),n.signals.length>0&&(i.signals=n.signals),n.components.length>0&&(i.components=n.components),n.flows.length>0&&(i.flows=n.flows),n.aspects.length>0&&(i.aspects=n.aspects),r$1[s.symbol]=i;}let y=r(t,"flow");for(let s of y){let n=s.data,i=n?.sequence||n?.gates||s.references;g[s.symbol]={description:s.description,sequence:i};}return {version:"1.0",generated:new Date().toISOString(),project:o,stats:{components:l.component,flows:l.flow,gates:l.gate,signals:l.signal,aspects:l.aspect,total:Object.values(l).reduce((s,n)=>s+n,0)},stars:r$1,orbits:g}}async function z(t,o$1={}){let r=process.cwd(),g=t?m.resolve(r,t):r,l=m.basename(g),a$1=o$1.format||"json";o$1.quiet||console.log(e.blue(`
3
3
  \u2728 Building Constellation...
4
4
  `));let y=F("Aggregating symbols...").start(),s=a.command("constellation").start("Building constellation",{project:l});try{let n=await m$1(g),i=o(n);a.operation("aggregate").debug("Symbols aggregated",{count:C(i).length}),y.text="Building constellation...";let p=T(i,l),$=m.join(g,".paradigm");u.existsSync($)||u.mkdirSync($,{recursive:!0});let h=o$1.output||m.join($,`constellation.${a$1}`),S;if(a$1==="yaml"?S=d(p):S=JSON.stringify(p,null,2),u.writeFileSync(h,S,"utf8"),a.component("constellation-file").success("Constellation written",{path:h,format:a$1}),y.succeed("Constellation built"),s.success("Constellation built",{path:h,stars:Object.keys(p.stars).length}),!o$1.quiet){console.log(e.white(`
5
5
  Constellation Stats`)),console.log(e.gray("\u2500".repeat(40)));let f=p.stats,q=[{symbol:"#",name:"Components",count:f.components,color:e.green},{symbol:"$",name:"Flows",count:f.flows,color:e.yellow},{symbol:"^",name:"Gates",count:f.gates,color:e.red},{symbol:"!",name:"Signals",count:f.signals,color:e.cyan},{symbol:"~",name:"Aspects",count:f.aspects,color:e.magenta}];for(let{symbol:c,name:R,count:O,color:E}of q)O>0&&console.log(` ${E(c)} ${R.padEnd(12)} ${e.cyan(O.toString())}`);console.log(e.gray("\u2500".repeat(40))),console.log(` Total stars: ${e.cyan(f.total.toString())}`),console.log(` Total orbits: ${e.cyan(Object.keys(p.orbits).length.toString())}`),console.log(e.gray(`
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import {e}from'./chunk-JIXHEBGK.js';import {e as e$1}from'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as v from'fs';import*as l from'path';import o from'chalk';import D from'ora';function Q(t){let a=t.length;return Math.ceil(a/3.5)}function f(t,a){try{let s=v.readFileSync(t,"utf8"),m=Buffer.byteLength(s,"utf8"),C=Q(s),r=l.relative(a,t);return {path:t,relativePath:r,tokens:C,bytes:m}}catch{return null}}function i(t){return t<1e3?t.toString():`${(t/1e3).toFixed(1)}k`}async function L(t,a){let s=t?l.resolve(t):process.cwd(),m=D();a.json||console.log(o.blue(`
2
+ import {f as f$1}from'./chunk-K6TLYNRQ.js';import {e}from'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as v from'fs';import*as l from'path';import o from'chalk';import D from'ora';function Q(t){let a=t.length;return Math.ceil(a/3.5)}function f(t,a){try{let s=v.readFileSync(t,"utf8"),m=Buffer.byteLength(s,"utf8"),C=Q(s),r=l.relative(a,t);return {path:t,relativePath:r,tokens:C,bytes:m}}catch{return null}}function i(t){return t<1e3?t.toString():`${(t/1e3).toFixed(1)}k`}async function L(t,a){let s=t?l.resolve(t):process.cwd(),m=D();a.json||console.log(o.blue(`
3
3
  \u{1F4B0} Paradigm Cost Analysis
4
- `)),m.start("Analyzing context files...");let C=await e(s),r=[];for(let e of C){let n=f(e,s);n&&r.push(n);}let A=await e$1(s),y=[];for(let e of A){let n=f(e,s);n&&y.push(n);}let R=l.join(s,".paradigm","scan-index.json"),h=f(R,s),I=l.join(s,".cursorrules"),q=l.join(s,".cursor","rules","paradigm.mdc"),g=f(I,s);g||(g=f(q,s)),m.stop();let x=r.reduce((e,n)=>e+n.tokens,0),F=y.reduce((e,n)=>e+n.tokens,0),b=h?.tokens||0,P=g?.tokens||0,w=x+F+b,u=w+P,T=150,k=T*7,c=u>0?Math.round((1-k/u)*100):0,d=[],M=r.filter(e=>e.tokens>500);M.length>0&&d.push(`${M.length} .purpose file(s) exceed 500 tokens. Consider splitting large features.`);let N=l.join(s,".cursor","mcp.json"),$=v.existsSync(N);$||d.push("MCP not configured. Run `paradigm mcp setup` to enable dynamic context (80%+ savings)."),h||d.push("No scan-index.json found. Run `paradigm index` for visual discovery support."),r.length<3&&d.push("Few .purpose files found. Add more context for better AI understanding.");let O={static:{purposeFiles:r,portalFiles:y,scanIndex:h,cursorrules:g,total:u},dynamic:{avgQueryTokens:T,typicalConversation:k},savings:{percentage:Math.max(0,c),description:c>0?`${c}% fewer tokens with MCP vs static context`:"MCP provides on-demand context loading"},recommendations:d};if(a.json){console.log(JSON.stringify(O,null,2));return}if(console.log(o.white("Context Token Analysis")),console.log(o.gray("\u2500".repeat(50))),console.log(o.cyan(`
4
+ `)),m.start("Analyzing context files...");let C=await f$1(s),r=[];for(let e of C){let n=f(e,s);n&&r.push(n);}let A=await e(s),y=[];for(let e of A){let n=f(e,s);n&&y.push(n);}let R=l.join(s,".paradigm","scan-index.json"),h=f(R,s),I=l.join(s,".cursorrules"),q=l.join(s,".cursor","rules","paradigm.mdc"),g=f(I,s);g||(g=f(q,s)),m.stop();let x=r.reduce((e,n)=>e+n.tokens,0),F=y.reduce((e,n)=>e+n.tokens,0),b=h?.tokens||0,P=g?.tokens||0,w=x+F+b,u=w+P,T=150,k=T*7,c=u>0?Math.round((1-k/u)*100):0,d=[],M=r.filter(e=>e.tokens>500);M.length>0&&d.push(`${M.length} .purpose file(s) exceed 500 tokens. Consider splitting large features.`);let N=l.join(s,".cursor","mcp.json"),$=v.existsSync(N);$||d.push("MCP not configured. Run `paradigm mcp setup` to enable dynamic context (80%+ savings)."),h||d.push("No scan-index.json found. Run `paradigm index` for visual discovery support."),r.length<3&&d.push("Few .purpose files found. Add more context for better AI understanding.");let O={static:{purposeFiles:r,portalFiles:y,scanIndex:h,cursorrules:g,total:u},dynamic:{avgQueryTokens:T,typicalConversation:k},savings:{percentage:Math.max(0,c),description:c>0?`${c}% fewer tokens with MCP vs static context`:"MCP provides on-demand context loading"},recommendations:d};if(a.json){console.log(JSON.stringify(O,null,2));return}if(console.log(o.white("Context Token Analysis")),console.log(o.gray("\u2500".repeat(50))),console.log(o.cyan(`
5
5
  Static Context (loaded every conversation):`)),console.log(` .purpose files (${r.length}):`.padEnd(35)+o.yellow(i(x)+" tokens")),console.log(` portal.yaml (${y.length}):`.padEnd(35)+o.yellow(i(F)+" tokens")),h&&console.log(" scan-index.json:".padEnd(35)+o.yellow(i(b)+" tokens")),g&&console.log(" .cursorrules:".padEnd(35)+o.yellow(i(P)+" tokens")),console.log(o.gray("\u2500".repeat(50))),console.log(" Static Total:".padEnd(35)+o.yellow.bold(i(u)+" tokens")),console.log(o.cyan(`
6
6
  Dynamic Context (MCP on-demand):`)),console.log(" Avg query response:".padEnd(35)+o.green(i(T)+" tokens")),console.log(" Typical conversation (~7 queries):".padEnd(35)+o.green(i(k)+" tokens")),console.log(o.cyan(`
7
7
  Potential Savings:`)),c>0){let e=c>70?o.green:c>40?o.yellow:o.white;console.log(" MCP vs Static:".padEnd(35)+e.bold(`${c}% reduction`));let n=u/1e3*.01,p=k/1e3*.01,j=n-p;j>.001&&console.log(" Est. savings per conversation:".padEnd(35)+o.green(`~$${j.toFixed(4)}`));}if(a.detailed&&r.length>0){console.log(o.cyan(`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-EG22HDXI.js';import'./chunk-DLMDHS2X.js';import'./chunk-FYDRENK7.js';import'./chunk-ECLUYHAR.js';import'./chunk-TYWB5IQJ.js';import'./chunk-YXLGVOZO.js';import'./chunk-XPPFILCM.js';import'./chunk-MBPLJKE5.js';import'./chunk-EKZDFEJW.js';import'./chunk-LPBCQM5Y.js';import'./chunk-4GC35IFF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as i from'fs';import*as a from'path';import o from'chalk';async function D(l,f,t){let d=f?a.resolve(f):process.cwd();if(!l){t.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(o.red(`
2
+ import {b}from'./chunk-YNFF7XHV.js';import'./chunk-TYWB5IQJ.js';import'./chunk-DLMDHS2X.js';import'./chunk-FYDRENK7.js';import'./chunk-ECLUYHAR.js';import'./chunk-YXLGVOZO.js';import'./chunk-MBKTVQS2.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-EKZDFEJW.js';import'./chunk-LPBCQM5Y.js';import'./chunk-D6BSCELB.js';import'./chunk-K6TLYNRQ.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as i from'fs';import*as a from'path';import o from'chalk';async function D(l,f,t){let d=f?a.resolve(f):process.cwd();if(!l){t.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(o.red(`
3
3
  Orchestration ID required.`)),console.log(o.gray(`Usage: paradigm team diff <orchestration-id>
4
4
  `)));return}let e=new b(d).getOrchestration(l);if(!e){t.json?console.log(JSON.stringify({error:"Orchestration not found",id:l})):console.log(o.red(`
5
5
  Orchestration not found: ${l}