@a-company/paradigm 7.1.0 → 7.2.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 (131) hide show
  1. package/dist/{accept-orchestration-WMGFGYDK.js → accept-orchestration-XW44LF5Y.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/captain-CAXGHC2V.js +2 -0
  9. package/dist/captain-CWCLFOXV.js +2 -0
  10. package/dist/{chunk-QDP4G53M.js → chunk-27EK3OQZ.js} +4 -4
  11. package/dist/chunk-2KK4JQ55.js +17 -0
  12. package/dist/chunk-3I3TITBA.js +25 -0
  13. package/dist/chunk-3YM5ABNX.js +2 -0
  14. package/dist/{chunk-RDWWSQGH.js → chunk-6HYRS3PH.js} +14 -14
  15. package/dist/{chunk-S3UVQ5RV.js → chunk-6VZSOQ7Y.js} +1 -1
  16. package/dist/chunk-727PXENG.js +2 -0
  17. package/dist/chunk-A5EEY6NO.js +3 -0
  18. package/dist/{chunk-DLMDHS2X.js → chunk-ASBK55FU.js} +1 -1
  19. package/dist/{chunk-4GC35IFF.js → chunk-D6BSCELB.js} +1 -1
  20. package/dist/{chunk-G6DK3ND3.js → chunk-DH7QVZDI.js} +9 -0
  21. package/dist/chunk-FG3M6VVO.js +30 -0
  22. package/dist/chunk-FNYYQNJY.js +2 -0
  23. package/dist/chunk-K6TLYNRQ.js +7 -0
  24. package/dist/chunk-K7KT6FL3.js +25 -0
  25. package/dist/chunk-M7JHVVDW.js +6 -0
  26. package/dist/chunk-NFN5UUJB.js +2 -0
  27. package/dist/{chunk-EG22HDXI.js → chunk-NRP2KJ6I.js} +12 -12
  28. package/dist/{chunk-VPNJL4LS.js → chunk-QPQBXRXX.js} +1 -1
  29. package/dist/chunk-RZRFYGND.js +504 -0
  30. package/dist/chunk-UNSI6DVD.js +93 -0
  31. package/dist/{chunk-W4BW7GXA.js → chunk-USYV5QYU.js} +1 -1
  32. package/dist/chunk-VOPJ47QY.js +2 -0
  33. package/dist/{chunk-KP5VOYAH.js → chunk-W3VWORQZ.js} +1 -1
  34. package/dist/chunk-WMTES556.js +2 -0
  35. package/dist/chunk-XBK244QR.js +6 -0
  36. package/dist/{chunk-YQK3XU63.js → chunk-XSKIXXFW.js} +12 -12
  37. package/dist/{chunk-MBSY57RN.js → chunk-Y76OIMDO.js} +1 -1
  38. package/dist/chunk-YYRP7FLC.js +2 -0
  39. package/dist/{compliance-4P3EE5OA.js → compliance-3M6COUCO.js} +3 -3
  40. package/dist/{constellation-RHZAEFV7.js → constellation-TIKNCZWR.js} +1 -1
  41. package/dist/{cost-24UZSS2P.js → cost-VTHZQKO4.js} +2 -2
  42. package/dist/{diff-VBVIUNL5.js → diff-Z2YSIRC4.js} +1 -1
  43. package/dist/{dist-TNE4GFT7.js → dist-PW5YPGFF.js} +1 -1
  44. package/dist/{docs-NTP6UENF.js → docs-OWJ7EPD7.js} +1 -1
  45. package/dist/github-4X4MYINS.js +4 -0
  46. package/dist/{habits-BX2IRSUI.js → habits-UA7YT3CG.js} +3 -3
  47. package/dist/{hooks-AXBWYJ5V.js → hooks-XXJ7CSGJ.js} +1 -1
  48. package/dist/index.js +9 -9
  49. package/dist/{init-F4MSKZIW.js → init-QPMLEQWQ.js} +1 -1
  50. package/dist/{integrity-7TKX3DZ4.js → integrity-FRGF5BFS.js} +1 -1
  51. package/dist/lint-Y4P3MHBV.js +26 -0
  52. package/dist/list-5XRLWD7K.js +12 -0
  53. package/dist/mcp.js +1 -1
  54. package/dist/{migrate-5M4KUQ2L.js → migrate-LIVXILOO.js} +1 -1
  55. package/dist/nomination-engine-EFXDEPZN.js +2 -0
  56. package/dist/{orchestrate-MLUGQOEJ.js → orchestrate-C5NM5MFN.js} +1 -1
  57. package/dist/orchestration-EVWQWTOV.js +2 -0
  58. package/dist/orchestration-UP3KFUJT.js +2 -0
  59. package/dist/{platform-server-Y6TLEXR2.js → platform-server-FXF3XFHM.js} +1 -1
  60. package/dist/{probe-27ARJKRO.js → probe-G3TKOJYW.js} +1 -1
  61. package/dist/quiz-QKIKAVL7.js +10 -0
  62. package/dist/registry-NEW4OJ44.js +2 -0
  63. package/dist/reindex-QZYOD5K4.js +2 -0
  64. package/dist/{reindex-ZLDQBFUR.js → reindex-W67B2LQP.js} +1 -1
  65. package/dist/remember-KZYAY77S.js +14 -0
  66. package/dist/{review-BRO2UP4M.js → review-WHRNLW2W.js} +1 -1
  67. package/dist/{ripple-KCVDS3WE.js → ripple-B6U7263T.js} +1 -1
  68. package/dist/{serve-2PKJP65E.js → serve-6RNZYK2I.js} +2 -2
  69. package/dist/{serve-XZ6GBUS3.js → serve-ZT2Z54NK.js} +1 -1
  70. package/dist/{setup-5V2AGLQ6.js → setup-L5OP24US.js} +3 -3
  71. package/dist/{shift-PM4GI736.js → shift-UDKXCIW7.js} +3 -3
  72. package/dist/{show-N5LGB5B2.js → show-VXNGIJE4.js} +3 -3
  73. package/dist/{snapshot-YMX5QRBM.js → snapshot-MT5L6XE4.js} +1 -1
  74. package/dist/{spawn-PHA2SVQ3.js → spawn-I6XG57S2.js} +1 -1
  75. package/dist/status-45KIG32R.js +6 -0
  76. package/dist/{status-3GJXI4IK.js → status-4QGKLOP6.js} +4 -4
  77. package/dist/{summary-RPU2BS3Q.js → summary-6QNVQZJV.js} +1 -1
  78. package/dist/symphony-KQJ6HIXB.js +53 -0
  79. package/dist/symphony-VDNDFK7H.js +2 -0
  80. package/dist/symphony-relay-ASMKPDEE.js +3 -0
  81. package/dist/task-KFND4HLF.js +3 -0
  82. package/dist/task-loader-HBZ3KRH2.js +2 -0
  83. package/dist/task-loader-IO4UVFUD.js +2 -0
  84. package/dist/task-settlement-NF7PFSNE.js +3 -0
  85. package/dist/task-settlement-TATNPY6L.js +3 -0
  86. package/dist/team-6WNNLBAO.js +2 -0
  87. package/dist/thread-2A7QKU72.js +41 -0
  88. package/dist/tools-GDWT74O6.js +2 -0
  89. package/dist/tools-SDWAFQMQ.js +142 -0
  90. package/dist/validate-OZTX3FYX.js +13 -0
  91. package/dist/validate-RIMSY3RP.js +9 -0
  92. package/dist/{workspace-6POCBPDY.js → workspace-4D4TQ637.js} +1 -1
  93. package/package.json +1 -1
  94. package/dist/add-V6XR7DU5.js +0 -12
  95. package/dist/agent-loader-Z753DQWH.js +0 -2
  96. package/dist/ambient-QB7V4TBR.js +0 -6
  97. package/dist/captain-3COP6YTD.js +0 -2
  98. package/dist/chunk-4CGPLLWQ.js +0 -30
  99. package/dist/chunk-7SWEOPWF.js +0 -2
  100. package/dist/chunk-CHSU6LTR.js +0 -2
  101. package/dist/chunk-EKNLG73M.js +0 -6
  102. package/dist/chunk-H55W26AR.js +0 -3
  103. package/dist/chunk-HE2NA5QF.js +0 -8
  104. package/dist/chunk-JIXHEBGK.js +0 -7
  105. package/dist/chunk-MBPLJKE5.js +0 -3
  106. package/dist/chunk-OIYJUU6T.js +0 -25
  107. package/dist/chunk-QO7YPQXC.js +0 -2
  108. package/dist/chunk-XPPFILCM.js +0 -2
  109. package/dist/chunk-YCDOA5IQ.js +0 -18
  110. package/dist/lint-IGKE6UPS.js +0 -26
  111. package/dist/list-NC3QGT75.js +0 -12
  112. package/dist/lore-loader-HAZ5FRLP.js +0 -2
  113. package/dist/nomination-engine-ORHH4L2W.js +0 -2
  114. package/dist/orchestration-O2OVPTIZ.js +0 -2
  115. package/dist/quiz-TNV6APBM.js +0 -10
  116. package/dist/remember-MJRNTXYS.js +0 -14
  117. package/dist/session-work-log-FF7CKMWP.js +0 -2
  118. package/dist/status-ENAI35NL.js +0 -6
  119. package/dist/symphony-CFAYJGLF.js +0 -2
  120. package/dist/symphony-L56O5ZG3.js +0 -53
  121. package/dist/symphony-relay-Y2UR3YNR.js +0 -3
  122. package/dist/task-loader-H7HQAYGL.js +0 -2
  123. package/dist/task-loader-YZME4RKE.js +0 -2
  124. package/dist/task-settlement-HINBVZBE.js +0 -3
  125. package/dist/task-settlement-XC6E6JNT.js +0 -3
  126. package/dist/team-25LK6CWM.js +0 -2
  127. package/dist/thread-HFXK65D4.js +0 -41
  128. package/dist/tools-GAU5WOEI.js +0 -2
  129. package/dist/validate-IQG7DBFC.js +0 -9
  130. package/dist/validate-LSCDOLBO.js +0 -13
  131. package/dist/work-log-loader-CRVTOMVB.js +0 -2
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import {z}from'zod';import*as l from'fs';import*as u from'path';import*as p from'js-yaml';var bt={warn(){}},kt=bt;function A(){return kt}var k="pack.yaml";var Pt="paradigm.universityPack";var V=/^[a-z0-9][a-z0-9-]{0,63}$/,B=["track","index","chronological","featured"],H=64,It=z.object({id:z.string().regex(V,"invalid section id"),name:z.string().min(1).max(120),order:z.number().int().min(0).max(9999),style:z.enum(B,{errorMap:()=>({message:`section.style must be one of ${B.join("|")}`})}),description:z.string().max(1e3).optional(),default:z.boolean({invalid_type_error:"section.default must be a boolean"}).optional()}).strict(),X=z.array(It).max(H,`sections must contain \u2264${H} entries`);z.object({sections:X.optional()}).passthrough();z.object({section:z.string().regex(V).optional(),order:z.number().int().min(0).max(9999).optional()}).passthrough();var Z="@a-company/university",tt=".paradigm/university",et=".paradigm/cache/packs.json",S=class extends Error{constructor(t,e){super(`pack-load failed (${t}: ${e})`),this.errorClass=t,this.detail=e,this.name="PackLoadError";}},Ct=["id","name","version","schema_version","tenant_kind"],wt=new Set(["first-party","project","external"]),J={id:"main",name:"Curriculum",order:1,style:"track",default:true};function nt(t){if(t==null)return [{...J}];if(Array.isArray(t)&&t.length===0)return [{...J}];let e=X.safeParse(t);if(!e.success){let i=e.error.issues[0],a=i?`${i.path.join(".")||"sections"}: ${i.message}`:"sections failed schema validation";throw new S("manifest-invalid",a)}let n=e.data.map(i=>({...i})),r=new Set;for(let i of n){if(r.has(i.id))throw new S("manifest-invalid",`duplicate section id "${i.id}"`);r.add(i.id);}n.length===1&&!n[0].default&&(n[0]={...n[0],default:true});let s=n.filter(i=>i.default===true);if(s.length>1)throw new S("manifest-invalid",`at most one section may set default: true (found ${s.length})`);return n.sort((i,a)=>i.order-a.order||i.id.localeCompare(a.id)),n}function xt(t){if(t&&typeof t=="object"&&"name"in t&&typeof t.name=="string"){let e=t.name;return e==="YAMLException"?"yaml syntax error":e}return "parse error"}function E(t){let e=u.join(t,k);if(!l.existsSync(e))throw new S("missing-manifest",`no ${k} at pack root`);let n;try{n=l.readFileSync(e,"utf-8");}catch{throw new S("manifest-unparseable","file read error")}let r;try{r=p.load(n);}catch(i){throw new S("manifest-unparseable",xt(i))}let s=r;if(!s||typeof s!="object")throw new S("manifest-invalid","manifest is not an object");for(let i of Ct){let a=s[i];if(a==null||a==="")throw new S("missing-required-field",`required field ${String(i)} is missing or empty`)}if(!wt.has(String(s.tenant_kind)))throw new S("missing-required-field","tenant_kind must be one of first-party|project|external");return s.sections=nt(s.sections),s}function Vt(t){let e=u.join(t,k);if(!l.existsSync(e))return null;try{let n=p.load(l.readFileSync(e,"utf8"));return n&&typeof n.id=="string"&&n.id.length>0?n.id:null}catch{return null}}function _t(t){let e=Et(t);if(e)return e;let n=[],r=u.join(t,"node_modules",Z);if(l.existsSync(u.join(r,k)))try{let i=E(r);n.push({manifest:i,rootDir:r,source:"first-party"});}catch(i){A().warn("first-party pack manifest invalid",{errorClass:i instanceof S?i.errorClass:"other"});}for(let i of jt(t))try{let a=E(i);n.push({manifest:a,rootDir:i,source:"npm"});}catch(a){A().warn("npm pack manifest invalid",{errorClass:a instanceof S?a.errorClass:"other"});}let s=u.join(t,tt);if(l.existsSync(s)&&l.statSync(s).isDirectory()){let i=u.join(s,k),a;if(l.existsSync(i))try{a=E(s),n.push({manifest:a,rootDir:s,source:"local"});}catch(d){A().warn("local pack manifest invalid",{errorClass:d instanceof S?d.errorClass:"other"});}let o=a?.id??"project";for(let d of At(s))try{let f=E(d);n.push({manifest:f,rootDir:d,source:"local",parentPackId:o});}catch(f){A().warn("discipline sub-pack manifest invalid",{errorClass:f instanceof S?f.errorClass:"other"});}}return Tt(t,n),n}function jt(t){let e=u.join(t,"package.json");if(!l.existsSync(e))return [];let n;try{n=JSON.parse(l.readFileSync(e,"utf8"));}catch{return []}let r=new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.devDependencies||{}),...Object.keys(n.peerDependencies||{})]);if(r.size===0)return [];let s=u.join(t,"node_modules");if(!l.existsSync(s))return [];let i=[];for(let a of r){if(a===Z)continue;let o=u.join(s,a,"package.json");if(!l.existsSync(o))continue;let d;try{d=JSON.parse(l.readFileSync(o,"utf8"));}catch{continue}let f=d.paradigm?.universityPack;if(typeof f!="string"||f.length===0)continue;let c=u.resolve(u.dirname(o),f);l.existsSync(u.join(c,k))&&i.push(c);}return i}function At(t){let e=[],n;try{n=l.readdirSync(t,{withFileTypes:!0});}catch{return e}for(let r of n){if(!r.isDirectory()||r.name.startsWith("."))continue;let s=u.join(t,r.name);l.existsSync(u.join(s,k))&&e.push(s);}return e}function st(t){try{return l.statSync(u.join(t,"node_modules")).mtime.getTime()}catch{return}}function rt(t){try{return l.statSync(u.join(t,tt)).mtime.getTime()}catch{return}}function Et(t){let e=u.join(t,et);if(!l.existsSync(e))return null;let n;try{n=JSON.parse(l.readFileSync(e,"utf8"));}catch{return null}if(n.version!==1||!Array.isArray(n.packs))return null;let r=st(t),s=rt(t);return n.node_modules_mtime_ms!==r||n.local_university_mtime_ms!==s?null:n.packs.map(i=>({manifest:i.manifest,rootDir:i.rootDir,source:i.source,...i.parentPackId?{parentPackId:i.parentPackId}:{}}))}function Tt(t,e){let n=u.join(t,et);try{l.mkdirSync(u.dirname(n),{recursive:!0});let r={version:1,node_modules_mtime_ms:st(t),local_university_mtime_ms:rt(t),packs:e.map(s=>({manifest:s.manifest,rootDir:s.rootDir,source:s.source,...s.parentPackId?{parentPackId:s.parentPackId}:{}}))};l.writeFileSync(n,JSON.stringify(r,null,2),"utf8");}catch{}}var P=".paradigm/university",w="content",L="notes",T="policies",F="quizzes",N="paths",W="diplomas",U="index.yaml",it="config.yaml";function ot(t){return typeof t=="string"?{packRoot:t,stampPackId:true,resolveDefaultPack:true}:{packRoot:t?.packRoot,stampPackId:t?.stampPackId??true,resolveDefaultPack:t?.resolveDefaultPack??true}}function at(t,e,n){return e||(n?ct(t):u.join(t,P))}function ct(t){let e=u.join(t,P);if(l.existsSync(e))return e;try{let r=_t(t).find(s=>s.manifest.tenant_kind==="first-party");if(r)return r.rootDir}catch{}return e}function $(t){if(!l.existsSync(t))return null;let e=u.join(t,k);if(l.existsSync(e))try{return E(t)}catch(r){A().warn("pack manifest invalid, using implicit manifest",{errorClass:r instanceof S?r.errorClass:"other"});}let n=u.basename(t)||"project";return {id:n,name:n,version:"0.0.0",schema_version:"1",tenant_kind:"project",description:"Implicit project pack (pack.yaml not present \u2014 v5 layout)",origin_hint:"authored",sections:nt(void 0)}}function Ft(t,e,n){return e?{...t,...t.pack_id?{}:{pack_id:e.id},...t.discipline||!n?{}:{discipline:n}}:t}var R={name:"Project University",tagline:"Learn the codebase",institution:"Paradigm"},G={primary:"#6366f1",secondary:"#8b5cf6",accent:"#f59e0b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",textMuted:"#94a3b8",success:"#22c55e",error:"#ef4444",font:"Inter, system-ui, sans-serif"},q={branding:R,theme:G,content:{categories:[],defaultDifficulty:"beginner",requireApproval:false},diplomas:{includeGlobalPLSAT:true,customCertStyle:null}};function Y(t){let e=u.join(t,P,it);if(!l.existsSync(e))return {...q};try{let n=l.readFileSync(e,"utf8"),r=p.load(n);return r?{branding:{...R,...r.branding||{}},theme:{...G,...r.theme||{}},content:{categories:r.content?.categories||[],defaultDifficulty:r.content?.defaultDifficulty||"beginner",requireApproval:r.content?.requireApproval??!1,defaultCategory:r.content?.defaultCategory},diplomas:{includeGlobalPLSAT:r.diplomas?.includeGlobalPLSAT??!0,customCertStyle:r.diplomas?.customCertStyle??null}}:{...q}}catch{return {...q}}}function Nt(t){let e=u.join(t,it);if(!l.existsSync(e))return null;try{let n=l.readFileSync(e,"utf8"),r=p.load(n);return r?{branding:{...R,...r.branding||{}},theme:{...G,...r.theme||{}},content:{categories:r.content?.categories||[],defaultDifficulty:r.content?.defaultDifficulty||"beginner",requireApproval:r.content?.requireApproval??!1,defaultCategory:r.content?.defaultCategory},diplomas:{includeGlobalPLSAT:r.diplomas?.includeGlobalPLSAT??!0,customCertStyle:r.diplomas?.customCertStyle??null}}:null}catch{return null}}function $t(t){let e=u.join(t,k);if(!l.existsSync(e))return false;try{let n=l.readFileSync(e,"utf8"),r=p.load(n);return !r||!Array.isArray(r.sections)?!1:r.sections.some(s=>s&&typeof s.id=="string"&&s.id.length>0)}catch{return false}}function M(t){let e=u.join(t,P,U);if(!l.existsSync(e))return null;try{let n=l.readFileSync(e,"utf8");return p.load(n)}catch{return null}}function ft(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:p.load(e[1]),body:e[2].trim()}}catch{return null}}function Dt(t,e){return `---
3
+ ${p.dump(t,{lineWidth:-1,noRefs:true,sortKeys:false})}---
4
+
5
+ ${e}
6
+ `}function Xt(t,e,n){let r=Q(t,e,".md",n);if(!r)return null;try{let s=l.readFileSync(r,"utf8"),i=ft(s);if(!i)return null;let a=i.frontmatter;return {frontmatter:Gt(a),body:i.body}}catch{return null}}function Zt(t,e,n,r){let{packRoot:s,stampPackId:i,resolveDefaultPack:a}=ot(r),o=e.type==="policy"?T:L,d=at(t,s,a),f=u.join(d,w,o);l.mkdirSync(f,{recursive:true});let c=i?$(d):null,b=Ft(e,c),_=u.join(f,`${b.id}.md`),x=Dt(b,n);return l.writeFileSync(_,x,"utf8"),_}function Ot(t,e,n){let r=Q(t,e,".yaml",n);if(!r)return null;try{let s=l.readFileSync(r,"utf8"),i=p.load(s);return !i||!i.id?null:Yt(i)}catch{return null}}function te(t,e,n){let{packRoot:r,stampPackId:s,resolveDefaultPack:i}=ot(n),a=at(t,r,i),o=u.join(a,w,F);l.mkdirSync(o,{recursive:true});let d=s?$(a):null,f={...e,...e.pack_id||!d?{}:{pack_id:d.id}},c=u.join(o,`${f.id}.yaml`);return l.writeFileSync(c,p.dump(f,{lineWidth:-1,noRefs:true}),"utf8"),c}function lt(t,e,n){let r=Q(t,e,".yaml",n);if(!r)return null;try{let s=l.readFileSync(r,"utf8"),i=p.load(s);return !i||!i.id?null:i}catch{return null}}function ee(t,e,n){let r=n??ct(t),s=u.join(r,w,N);l.mkdirSync(s,{recursive:true});let i=u.join(s,`${e.id}.yaml`);return l.writeFileSync(i,p.dump(e,{lineWidth:-1,noRefs:true}),"utf8"),i}function dt(t,e,n){let r=n??u.join(t,P),s=u.join(r,W);if(!l.existsSync(s))return [];let i=[];try{let a=l.readdirSync(s).filter(o=>o.endsWith(".yaml"));for(let o of a)try{let d=l.readFileSync(u.join(s,o),"utf8"),f=p.load(d);if(!f||!f.id||e?.student&&f.student!==e.student||e?.type&&f.type!==e.type)continue;i.push(f);}catch{}}catch{}return i.sort((a,o)=>o.earnedAt.localeCompare(a.earnedAt))}function ne(t,e,n){let r=n??u.join(t,P),s=u.join(r,W);l.mkdirSync(s,{recursive:true});let i=$(r),a={...e,...e.pack_id||!i?{}:{pack_id:i.id}},o=u.join(s,`${a.id}.yaml`);return l.writeFileSync(o,p.dump(a,{lineWidth:-1,noRefs:true}),"utf8"),o}function se(t,e,n){return Lt(t,e,n).entries}function Lt(t,e,n){let r=n?K(n):M(t);if(!r)return {entries:[],total:0,returned:0};let s=[...r.entries];if(e.type&&(s=s.filter(d=>d.type===e.type)),e.tag&&(s=s.filter(d=>d.tags.some(f=>f.startsWith(e.tag)))),e.difficulty&&(s=s.filter(d=>d.difficulty===e.difficulty)),e.symbol&&(s=s.filter(d=>d.symbols.some(f=>f===e.symbol))),e.author&&(s=s.filter(d=>d.author===e.author)),e.query){let d=e.query.toLowerCase();s=s.filter(f=>f.title.toLowerCase().includes(d)||f.id.toLowerCase().includes(d)||f.tags.some(c=>c.toLowerCase().includes(d)));}if(e.category&&(s=s.filter(d=>d.category===e.category)),e.section&&(s=s.filter(d=>d.section===e.section)),e.track){let d=Y(t),f=new Map;for(let c of d.content.categories)f.set(c.id,c.track||"core");s=s.filter(c=>(c.category&&f.get(c.category)||"core")===e.track);}let i=s.length,a=e.limit||20,o=s.slice(0,a);return {entries:o,total:i,returned:o.length}}var ut=[w,"src/content"],yt=[L,T,F,N];function Mt(t){if(!l.existsSync(t))return false;for(let e of yt){let n=u.join(t,e);if(l.existsSync(n))try{if(l.readdirSync(n).some(r=>r.endsWith(".md")||r.endsWith(".yaml")))return !0}catch{}}return false}function qt(t){let e=ht(t);return e?u.join(t,e):null}function ht(t){let e=null;for(let n of ut){let r=u.join(t,n);if(l.existsSync(r)&&(e===null&&(e=n),Mt(r)))return n}return e}function re(t){for(let e of ut){let n=u.join(t,e);if(!l.existsSync(n))continue;let r=0;for(let s of yt){let i=u.join(n,s);if(l.existsSync(i))try{r+=l.readdirSync(i).filter(a=>a.endsWith(".md")||a.endsWith(".yaml")).length;}catch{}}if(r>0)return r}return 0}function mt(t,e){let n=[];for(let i of [L,T]){let a=u.join(t,i);if(l.existsSync(a))try{for(let o of l.readdirSync(a).filter(d=>d.endsWith(".md")))try{let d=l.readFileSync(u.join(a,o),"utf8"),f=ft(d);if(!f)continue;let c=f.frontmatter;n.push({id:c.id||o.replace(".md",""),title:c.title||o,type:c.type||(i===T?"policy":"note"),author:c.author||"unknown",created:c.created||"",updated:c.updated||"",tags:Array.isArray(c.tags)?c.tags:[],symbols:Array.isArray(c.symbols)?c.symbols:[],difficulty:c.difficulty||"beginner",file:`${e}/${i}/${o}`,...c.category?{category:c.category}:{},...typeof c.section=="string"&&c.section?{section:c.section}:{},...typeof c.order=="number"&&Number.isFinite(c.order)?{order:c.order}:{}});}catch{}}catch{}}let r=u.join(t,F);if(l.existsSync(r))try{for(let i of l.readdirSync(r).filter(a=>a.endsWith(".yaml")))try{let a=l.readFileSync(u.join(r,i),"utf8"),o=p.load(a);if(!o||!o.id)continue;n.push({id:o.id,title:o.title||i,type:"quiz",author:o.author||"unknown",created:o.created||"",updated:o.updated||"",tags:o.tags||[],symbols:o.symbols||[],difficulty:o.difficulty||"beginner",file:`${e}/${F}/${i}`,...o.category?{category:o.category}:{},...typeof o.section=="string"&&o.section?{section:o.section}:{},...typeof o.order=="number"&&Number.isFinite(o.order)?{order:o.order}:{}});}catch{}}catch{}let s=u.join(t,N);if(l.existsSync(s))try{for(let i of l.readdirSync(s).filter(a=>a.endsWith(".yaml")))try{let a=l.readFileSync(u.join(s,i),"utf8"),o=p.load(a);if(!o||!o.id)continue;n.push({id:o.id,title:o.title||i,type:"path",author:o.author||"unknown",created:o.created||"",updated:o.updated||"",tags:o.tags||[],symbols:[],file:`${e}/${N}/${i}`,...o.category?{category:o.category}:{},...typeof o.section=="string"&&o.section?{section:o.section}:{},...typeof o.order=="number"&&Number.isFinite(o.order)?{order:o.order}:{}});}catch{}}catch{}return n}function zt(t){let e=u.join(t,P),n=u.join(e,w),r=mt(n,w),s=0,i=u.join(e,W);if(l.existsSync(i))try{s=l.readdirSync(i).filter(d=>d.endsWith(".yaml")).length;}catch{}let a={version:"1.0",generatedAt:new Date().toISOString(),totalContent:r.length,entries:r,diplomaCount:s};l.mkdirSync(e,{recursive:true});let o=u.join(e,U);return l.writeFileSync(o,p.dump(a,{lineWidth:-1,noRefs:true}),"utf8"),a}function K(t,e){let n=u.join(t,U);if(l.existsSync(n))try{let a=l.readFileSync(n,"utf8"),o=p.load(a);if(o)return o}catch{}let r=ht(t);if(!r)return {version:"1.0",generatedAt:new Date().toISOString(),totalContent:0,entries:[],diplomaCount:0};let s=u.join(t,r),i=mt(s,r);return {version:"1.0",generatedAt:new Date().toISOString(),totalContent:i.length,entries:i,diplomaCount:0}}function ie(t,e,n){let r=n?K(n):M(t)||zt(t),s=[],i=r.entries;e?.id&&(i=i.filter(c=>c.id===e.id));let a=null;e?.deep&&(a=pt(t));let o=new Set(r.entries.map(c=>c.id));for(let c of i){if(c.title||s.push({contentId:c.id,severity:"error",check:"missing-title",message:"Content is missing a title",fix:"Add a title field to the content frontmatter"}),c.type==="quiz"&&Wt(t,c.id,s,n),c.type==="path"&&Ut(t,c.id,o,s,n),a&&c.symbols.length>0){Y(t).content.categories.find(h=>h.id===c.category)?.validationStrictness==="relaxed";for(let h of c.symbols)a.has(h)||s.push({contentId:c.id,severity:"warning",check:"broken-symbol-ref",message:`Symbol "${h}" not found in scan-index`,fix:`Remove or update the symbol reference in ${c.id}`});}e?.deep&&c.symbols.length>0&&c.updated&&Qt(t,c,s);}Rt(t,r,s,n);let d=dt(t);for(let c of d)if(c.total>0&&c.percentage!==Math.round(c.score/c.total*1e4)/100){let b=Math.round(c.score/c.total*1e4)/100;Math.abs(c.percentage-b)>.1&&s.push({contentId:c.id,severity:"warning",check:"diploma-score-mismatch",message:`Diploma percentage ${c.percentage} doesn't match score ${c.score}/${c.total} (expected ${b})`});}let f=Kt(t,r);return {status:s.some(c=>c.severity==="error")?"errors":s.length>0?"warnings":"healthy",totalContent:r.totalContent,checked:i.length,issues:s,symbolCoverage:f}}function Wt(t,e,n,r){let s=Ot(t,e,r);if(!s){n.push({contentId:e,severity:"error",check:"unreadable-quiz",message:"Quiz file could not be parsed"});return}(!s.passThreshold||s.passThreshold<0||s.passThreshold>1)&&n.push({contentId:e,severity:"warning",check:"invalid-pass-threshold",message:`passThreshold should be between 0 and 1, got ${s.passThreshold}`,fix:"Set passThreshold to a value between 0.0 and 1.0"});for(let i of s.questions){if(!i.choices||typeof i.choices!="object"){n.push({contentId:e,severity:"error",check:"invalid-quiz-choices",message:`Question ${i.id} has no choices defined`});continue}(!i.correct||!(i.correct in i.choices))&&n.push({contentId:e,severity:"error",check:"invalid-quiz-answer",message:`Question ${i.id}: correct answer "${i.correct}" not found in choices [${Object.keys(i.choices).join(", ")}]`,fix:`Set correct to one of: ${Object.keys(i.choices).join(", ")}`});}}function Ut(t,e,n,r,s){let i=lt(t,e,s);if(!i){r.push({contentId:e,severity:"error",check:"unreadable-path",message:"Learning path file could not be parsed"});return}for(let a of i.steps)a.content.startsWith("plsat:")||n.has(a.content)||r.push({contentId:e,severity:"error",check:"broken-path-step",message:`Learning path step references "${a.content}" which doesn't exist`,fix:`Create content with id "${a.content}" or remove this step`});}function Rt(t,e,n,r){let s=r??u.join(t,P),i=$(s);if(!i||!i.sections||i.sections.length===0)return;let a=new Set(i.sections.map(f=>f.id)),o=i.sections.find(f=>f.default===true);for(let f of e.entries)f.section&&!a.has(f.section)&&n.push({contentId:f.id,severity:"warning",check:"dangling-section-ref",message:`Entry references section "${f.section}" which is not declared in pack.yaml`,fix:`Add a section with id "${f.section}" to pack.yaml, or remove the section field`});let d=new Map;for(let f of i.sections)d.set(f.id,0);for(let f of e.entries)f.section&&a.has(f.section)?d.set(f.section,(d.get(f.section)||0)+1):!f.section&&o&&d.set(o.id,(d.get(o.id)||0)+1);for(let f of i.sections)(d.get(f.id)||0)===0&&n.push({contentId:f.id,severity:"warning",check:"empty-section",message:`Section "${f.id}" has zero entries`,fix:`Add at least one entry with section: "${f.id}", or remove the section from pack.yaml`});}function oe(t,e){let n=M(t);if(!n)return [];let r=[];for(let s of n.entries)if(s.symbols.includes(e)){let i=gt(t,s,e);r.push({id:s.id,title:s.title,type:s.type,stale:i});}return r}function ae(t,e,n){let r=n?K(n):M(t);if(!r)return {paths:[],suggestedContent:[],extracurricular:[],diplomaCount:0,totalContent:0};let s=n&&Nt(n)||Y(t),i=new Set;for(let h of s.content.categories)h.excludeFromOnboarding&&i.add(h.id);let a=r.entries.filter(h=>!h.category||!i.has(h.category)),o=r.entries.filter(h=>h.category&&i.has(h.category)),d=a.filter(h=>h.type==="path"),f=e?dt(t,{student:e},n):[],c=new Set(f.map(h=>h.source)),b=d.map(h=>{let I=lt(t,h.id,n);return {id:h.id,title:h.title,steps:I?.steps.length||0,completed:c.has(h.id)}}),_=a.filter(h=>h.type!=="path"&&(h.difficulty==="beginner"||h.tags.includes("onboarding"))).slice(0,10),x={paths:b,suggestedContent:_,extracurricular:o,diplomaCount:f.length,totalContent:r.totalContent};if(n&&$t(n)){let I=($(n)?.sections??[]).slice().sort((D,C)=>D.order-C.order||D.id.localeCompare(C.id));if(I.length>0){let D=I.find(g=>g.default===true)??I[0],C=new Map;for(let g of I)C.set(g.id,[]);for(let g of r.entries){let j=g.section&&C.has(g.section)?g.section:D.id,O=C.get(j);O&&O.push(g);}let St=(g,j)=>{let O=typeof g.order=="number"?g.order:Number.POSITIVE_INFINITY,vt=typeof j.order=="number"?j.order:Number.POSITIVE_INFINITY;return O-vt||g.id.localeCompare(j.id)};x.sections=I.map(g=>({id:g.id,name:g.name,entries:(C.get(g.id)??[]).sort(St)}));}}return x}function Q(t,e,n,r){let s=r??u.join(t,P),i=qt(s)??u.join(s,w);for(let a of [L,T,F,N]){let o=u.join(i,a,`${e}${n}`);if(l.existsSync(o))return o}return null}function Gt(t){return {id:t.id||"",title:t.title||"",type:t.type||"note",author:t.author||"unknown",created:t.created||"",updated:t.updated||"",tags:Array.isArray(t.tags)?t.tags:[],symbols:Array.isArray(t.symbols)?t.symbols:[],difficulty:t.difficulty||"beginner",estimatedMinutes:t.estimatedMinutes,prerequisites:Array.isArray(t.prerequisites)?t.prerequisites:[],...t.category?{category:t.category}:{},...t.origin?{origin:t.origin}:{},...t.source?{source:t.source}:{},...t.pack_id?{pack_id:t.pack_id}:{},...t.discipline?{discipline:t.discipline}:{},...t.section?{section:t.section}:{},...typeof t.order=="number"?{order:t.order}:{}}}function Yt(t){return {...t,tags:t.tags||[],symbols:t.symbols||[],difficulty:t.difficulty||"beginner",passThreshold:t.passThreshold??.7,questions:t.questions||[]}}function pt(t){let e=new Set,n=u.join(t,".paradigm","scan-index.json");if(!l.existsSync(n))return e;try{let r=l.readFileSync(n,"utf8"),s=JSON.parse(r);if(s.symbols&&Array.isArray(s.symbols))for(let i of s.symbols)i.symbol&&e.add(i.symbol);}catch{}return e}function Kt(t,e){let n=pt(t),r=new Set;for(let i of e.entries)for(let a of i.symbols)n.has(a)&&r.add(a);let s=n.size;return {totalSymbols:s,coveredByContent:r.size,percentage:s>0?Math.round(r.size/s*100):0}}function gt(t,e,n){if(!e.updated)return false;let r=new Date(e.updated).getTime();if(isNaN(r))return false;let s=u.join(t,".paradigm","scan-index.json");if(!l.existsSync(s))return false;try{let i=l.readFileSync(s,"utf8"),a=JSON.parse(i);if(a.symbols&&Array.isArray(a.symbols)){for(let o of a.symbols)if(o.symbol===n&&o.filePath){let d=u.join(t,o.filePath);if(l.existsSync(d)&&l.statSync(d).mtime.getTime()>r)return !0}}}catch{}return false}function Qt(t,e,n){for(let r of e.symbols)if(gt(t,e,r)){n.push({contentId:e.id,severity:"warning",check:"stale-content",message:`Content may be stale: symbol "${r}" was updated after content was last modified`,fix:`Review and update ${e.id} to reflect changes to ${r}`});break}}export{k as a,Pt as b,Vt as c,ct as d,$ as e,Y as f,M as g,Xt as h,Zt as i,Ot as j,te as k,lt as l,ee as m,dt as n,ne as o,se as p,Lt as q,qt as r,re as s,zt as t,K as u,ie as v,oe as w,ae as x};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {b,a}from'./chunk-EK4ZRIFJ.js';b();var n=new Map,t=new Map;function y(r,e){n.set(r,e),t.delete(r),a.component("#sync-provider").info("Provider registered",{id:r});}function v(r){let e=t.get(r);if(e)return e;let o=n.get(r);if(!o)return;let i=o();return t.set(r,i),i}function p(){n.clear(),t.clear();}export{y as a,v as b,p as c};
@@ -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-ASBK55FU.js';import {e}from'./chunk-YXLGVOZO.js';import {a}from'./chunk-FYDRENK7.js';import {f,g,h}from'./chunk-3YM5ABNX.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,t,e,s){let n=new Map,i;try{i=await f(h,{blurb:e,priority:"medium",tags:["orchestration","epic"],claimant:{kind:"archetype",ref:"orchestrator"},external_ref:{provider:"orchestration",ref:t}});try{await g(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 f(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:{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,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 g(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$1,t,e){if(!t)return false;try{return e==="success"?await h(h$1,t):await g(h$1,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};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a,O,j as j$2,M as M$1,B}from'./chunk-KP5VOYAH.js';import {a as a$1,b as b$3,c as c$1}from'./chunk-M4UMM6DC.js';import {r,i,a as a$2,f}from'./chunk-TMDPDIWA.js';import {j as j$1,b as b$2,a as a$4}from'./chunk-GRZQIKST.js';import {b as b$1,a as a$3}from'./chunk-EK4ZRIFJ.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as S from'fs';import*as T from'path';import*as j from'crypto';import {execSync}from'child_process';import*as C from'js-yaml';import*as Y from'os';import ht from'sql.js';var ve={};c(ve,{contentSearch:()=>gt,detectFileRename:()=>Ae,generateFingerprint:()=>xe,levenshteinDistance:()=>Ie,levenshteinSimilarity:()=>se,searchSiblingFiles:()=>Ce,slidingWindowSearch:()=>V});function xe(e){let t=e.split(`
2
+ import {a,O,j as j$2,M as M$1,B}from'./chunk-W3VWORQZ.js';import {a as a$1,b as b$3,c as c$1}from'./chunk-M4UMM6DC.js';import {r,i,a as a$2,f}from'./chunk-TMDPDIWA.js';import {j as j$1,b as b$2,a as a$4}from'./chunk-GRZQIKST.js';import {b as b$1,a as a$3}from'./chunk-EK4ZRIFJ.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as S from'fs';import*as T from'path';import*as j from'crypto';import {execSync}from'child_process';import*as C from'js-yaml';import*as Y from'os';import ht from'sql.js';var ve={};c(ve,{contentSearch:()=>gt,detectFileRename:()=>Ae,generateFingerprint:()=>xe,levenshteinDistance:()=>Ie,levenshteinSimilarity:()=>se,searchSiblingFiles:()=>Ce,slidingWindowSearch:()=>V});function xe(e){let t=e.split(`
3
3
  `).filter(n=>n.trim()!=="");return {firstLine:q(t[0]||""),lastLine:q(t[t.length-1]||""),lineCount:t.length,structuralHash:Le(t)}}function Le(e){let t=e.map(n=>n.trim()).filter(n=>Re.test(n)).map(n=>{let s=n.match(Re);return s?s[1].trim():""}).join("|");return j.createHash("sha256").update(t).digest("hex").slice(0,16)}function q(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function Ie(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;e.length>t.length&&([e,t]=[t,e]);let n=e.length,s=t.length;if(n>5e3||s>5e3)return Math.abs(n-s);let r=new Array(n+1),i=new Array(n+1);for(let a=0;a<=n;a++)r[a]=a;for(let a=1;a<=s;a++){i[0]=a;for(let c=1;c<=n;c++){let o=e[c-1]===t[a-1]?0:1;i[c]=Math.min(r[c]+1,i[c-1]+1,r[c-1]+o);}[r,i]=[i,r];}return r[n]}function se(e,t){if(e.length===0&&t.length===0)return 1;let n=Math.max(e.length,t.length);return 1-Ie(e,t)/n}function V(e,t,n,s=3){let{lineCount:r}=t,i=Math.max(1,Math.floor(r*.8)),a=Math.ceil(r*1.2),c=[],o=ne(n);for(let l of [r,i,a])if(!(l>e.length))for(let d=0;d<=e.length-l;d++){let p=e.slice(d,d+l),y=ft(p,t,o);if(y>=.5){let m=p.join(`
4
4
  `);c.push({windowStart:d+1,windowEnd:d+l,similarity:se(ne(m),o),score:y});}}let u=new Map;for(let l of c){let d=u.get(l.windowStart);(!d||l.score>d.score)&&u.set(l.windowStart,l);}return Array.from(u.values()).sort((l,d)=>d.score-l.score).slice(0,s)}function ft(e,t,n){let s=e.filter(p=>p.trim()!=="");if(s.length===0)return 0;let r=0,i=q(s[0]),a=q(s[s.length-1]),c=0;i===t.firstLine&&(c+=.5),a===t.lastLine&&(c+=.5),r+=c*lt,Le(s)===t.structuralHash&&(r+=ut);let u=s.join(`
5
5
  `),l=se(ne(u),n);l>=.8&&(r+=(l-.8)/.2*dt);let d=s.length/t.lineCount;if(d>=.8&&d<=1.2){let p=1-Math.abs(1-d)/.2;r+=p*pt;}return r}function ne(e){return e.split(`