@a-company/paradigm 7.0.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 (145) hide show
  1. package/dist/{accept-orchestration-YO2V2WYA.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-OW5M5LVN.js +2 -0
  5. package/dist/{ambient-OX7YJ4PJ.js → ambient-TFLZFV5Y.js} +1 -1
  6. package/dist/ambient-VCTUHHIG.js +2 -0
  7. package/dist/arch-loader-YVOS3QRY.js +2 -0
  8. package/dist/{beacon-52EWNZPK.js → beacon-WVN264OT.js} +1 -1
  9. package/dist/calibrate-PHVP7RPH.js +4 -0
  10. package/dist/captain-CAXGHC2V.js +2 -0
  11. package/dist/captain-CWCLFOXV.js +2 -0
  12. package/dist/{chunk-QDP4G53M.js → chunk-27EK3OQZ.js} +4 -4
  13. package/dist/chunk-2KK4JQ55.js +17 -0
  14. package/dist/chunk-3I3TITBA.js +25 -0
  15. package/dist/chunk-3YM5ABNX.js +2 -0
  16. package/dist/{chunk-47YPID6H.js → chunk-6HYRS3PH.js} +21 -21
  17. package/dist/{chunk-S3UVQ5RV.js → chunk-6VZSOQ7Y.js} +1 -1
  18. package/dist/chunk-727PXENG.js +2 -0
  19. package/dist/chunk-A5EEY6NO.js +3 -0
  20. package/dist/{chunk-DLMDHS2X.js → chunk-ASBK55FU.js} +1 -1
  21. package/dist/{chunk-4GC35IFF.js → chunk-D6BSCELB.js} +1 -1
  22. package/dist/{chunk-G6DK3ND3.js → chunk-DH7QVZDI.js} +9 -0
  23. package/dist/chunk-ECO3LHCE.js +2 -0
  24. package/dist/chunk-FG3M6VVO.js +30 -0
  25. package/dist/chunk-FNYYQNJY.js +2 -0
  26. package/dist/{chunk-ROU3F2HZ.js → chunk-HSY75GRR.js} +3 -3
  27. package/dist/chunk-K6TLYNRQ.js +7 -0
  28. package/dist/chunk-K7KT6FL3.js +25 -0
  29. package/dist/chunk-KAUGQMXU.js +4 -0
  30. package/dist/chunk-M7JHVVDW.js +6 -0
  31. package/dist/chunk-NFN5UUJB.js +2 -0
  32. package/dist/chunk-NRP2KJ6I.js +33 -0
  33. package/dist/{chunk-WROJSWAO.js → chunk-QPQBXRXX.js} +1 -1
  34. package/dist/chunk-RVXQNS6K.js +30 -0
  35. package/dist/chunk-RZRFYGND.js +504 -0
  36. package/dist/chunk-UNSI6DVD.js +93 -0
  37. package/dist/{chunk-JCGCPAHF.js → chunk-USYV5QYU.js} +1 -1
  38. package/dist/chunk-VOPJ47QY.js +2 -0
  39. package/dist/{chunk-QBIQ2FYB.js → chunk-W3VWORQZ.js} +1 -1
  40. package/dist/chunk-WMTES556.js +2 -0
  41. package/dist/chunk-XBK244QR.js +6 -0
  42. package/dist/chunk-XSKIXXFW.js +504 -0
  43. package/dist/{chunk-MBSY57RN.js → chunk-Y76OIMDO.js} +1 -1
  44. package/dist/chunk-YYRP7FLC.js +2 -0
  45. package/dist/{compliance-MLG4W6S4.js → compliance-3M6COUCO.js} +3 -3
  46. package/dist/{constellation-RHZAEFV7.js → constellation-TIKNCZWR.js} +1 -1
  47. package/dist/{cost-24UZSS2P.js → cost-VTHZQKO4.js} +2 -2
  48. package/dist/{diff-MC6AXLKX.js → diff-Z2YSIRC4.js} +1 -1
  49. package/dist/{dist-TNE4GFT7.js → dist-PW5YPGFF.js} +1 -1
  50. package/dist/{docs-3YFNNZRV.js → docs-OWJ7EPD7.js} +1 -1
  51. package/dist/github-4X4MYINS.js +4 -0
  52. package/dist/{habits-BX2IRSUI.js → habits-UA7YT3CG.js} +3 -3
  53. package/dist/{hooks-AXBWYJ5V.js → hooks-XXJ7CSGJ.js} +1 -1
  54. package/dist/index.js +9 -9
  55. package/dist/{init-F4MSKZIW.js → init-QPMLEQWQ.js} +1 -1
  56. package/dist/{integrity-7TKX3DZ4.js → integrity-FRGF5BFS.js} +1 -1
  57. package/dist/journal-loader-CNNA4EAU.js +2 -0
  58. package/dist/lint-Y4P3MHBV.js +26 -0
  59. package/dist/list-5XRLWD7K.js +12 -0
  60. package/dist/mcp.js +1 -1
  61. package/dist/{migrate-5M4KUQ2L.js → migrate-LIVXILOO.js} +1 -1
  62. package/dist/{nomination-engine-AQHU2KBU.js → nomination-engine-EFXDEPZN.js} +1 -1
  63. package/dist/nomination-engine-YRHZZZUN.js +2 -0
  64. package/dist/notebook-loader-TZVIMNDJ.js +2 -0
  65. package/dist/{orchestrate-GMYEBA5T.js → orchestrate-C5NM5MFN.js} +1 -1
  66. package/dist/orchestration-EVWQWTOV.js +2 -0
  67. package/dist/orchestration-UP3KFUJT.js +2 -0
  68. package/dist/{platform-server-WIBVYHIV.js → platform-server-FXF3XFHM.js} +1 -1
  69. package/dist/{probe-27ARJKRO.js → probe-G3TKOJYW.js} +1 -1
  70. package/dist/quiz-QKIKAVL7.js +10 -0
  71. package/dist/registry-NEW4OJ44.js +2 -0
  72. package/dist/reindex-QZYOD5K4.js +2 -0
  73. package/dist/{reindex-XTRF23F7.js → reindex-W67B2LQP.js} +1 -1
  74. package/dist/remember-KZYAY77S.js +14 -0
  75. package/dist/{review-BRO2UP4M.js → review-WHRNLW2W.js} +1 -1
  76. package/dist/{ripple-KCVDS3WE.js → ripple-B6U7263T.js} +1 -1
  77. package/dist/{serve-2PKJP65E.js → serve-6RNZYK2I.js} +2 -2
  78. package/dist/{serve-SMGWGJLM.js → serve-ZT2Z54NK.js} +1 -1
  79. package/dist/{setup-5V2AGLQ6.js → setup-L5OP24US.js} +3 -3
  80. package/dist/{shift-JBCEDCGA.js → shift-UDKXCIW7.js} +3 -3
  81. package/dist/{show-N5LGB5B2.js → show-VXNGIJE4.js} +3 -3
  82. package/dist/{snapshot-YMX5QRBM.js → snapshot-MT5L6XE4.js} +1 -1
  83. package/dist/{spawn-PHA2SVQ3.js → spawn-I6XG57S2.js} +1 -1
  84. package/dist/status-45KIG32R.js +6 -0
  85. package/dist/{status-3GJXI4IK.js → status-4QGKLOP6.js} +4 -4
  86. package/dist/{summary-RPU2BS3Q.js → summary-6QNVQZJV.js} +1 -1
  87. package/dist/symphony-KQJ6HIXB.js +53 -0
  88. package/dist/symphony-VDNDFK7H.js +2 -0
  89. package/dist/symphony-relay-ASMKPDEE.js +3 -0
  90. package/dist/task-KFND4HLF.js +3 -0
  91. package/dist/task-loader-HBZ3KRH2.js +2 -0
  92. package/dist/task-loader-IO4UVFUD.js +2 -0
  93. package/dist/task-settlement-NF7PFSNE.js +3 -0
  94. package/dist/task-settlement-TATNPY6L.js +3 -0
  95. package/dist/team-6WNNLBAO.js +2 -0
  96. package/dist/thread-2A7QKU72.js +41 -0
  97. package/dist/tools-GDWT74O6.js +2 -0
  98. package/dist/tools-SDWAFQMQ.js +142 -0
  99. package/dist/university-ui/assets/{index-B8hm_MdR.js → index-AbTjHBCf.js} +2 -2
  100. package/dist/university-ui/assets/{index-B8hm_MdR.js.map → index-AbTjHBCf.js.map} +1 -1
  101. package/dist/university-ui/index.html +1 -1
  102. package/dist/validate-OZTX3FYX.js +13 -0
  103. package/dist/validate-RIMSY3RP.js +9 -0
  104. package/dist/{workspace-6POCBPDY.js → workspace-4D4TQ637.js} +1 -1
  105. package/package.json +1 -1
  106. package/dist/add-V6XR7DU5.js +0 -12
  107. package/dist/agent-loader-VGBPL3TH.js +0 -2
  108. package/dist/ambient-7HBJHJL2.js +0 -2
  109. package/dist/ambient-SST5CLEC.js +0 -35
  110. package/dist/captain-YUP3KVCA.js +0 -2
  111. package/dist/chunk-3MZ4J2LF.js +0 -2
  112. package/dist/chunk-6AKNXD22.js +0 -32
  113. package/dist/chunk-7SWEOPWF.js +0 -2
  114. package/dist/chunk-CVPKQ3JH.js +0 -8
  115. package/dist/chunk-EKNLG73M.js +0 -6
  116. package/dist/chunk-FRQRREJ6.js +0 -29
  117. package/dist/chunk-GD4F2HC6.js +0 -3
  118. package/dist/chunk-JIXHEBGK.js +0 -7
  119. package/dist/chunk-K54L6CFR.js +0 -25
  120. package/dist/chunk-MBPLJKE5.js +0 -3
  121. package/dist/chunk-QEQCPVF5.js +0 -4
  122. package/dist/chunk-QGZRM6ZB.js +0 -2
  123. package/dist/chunk-QO7YPQXC.js +0 -2
  124. package/dist/chunk-S4J337EQ.js +0 -504
  125. package/dist/chunk-V6MIKLMY.js +0 -18
  126. package/dist/journal-loader-GLH7XFTK.js +0 -2
  127. package/dist/lint-IGKE6UPS.js +0 -26
  128. package/dist/list-NC3QGT75.js +0 -12
  129. package/dist/lore-loader-D2ISOASW.js +0 -2
  130. package/dist/notebook-loader-6DYFMNJ2.js +0 -2
  131. package/dist/orchestration-G5MAY6IA.js +0 -2
  132. package/dist/quiz-TNV6APBM.js +0 -10
  133. package/dist/remember-MJRNTXYS.js +0 -14
  134. package/dist/session-work-log-QXPAXY5K.js +0 -2
  135. package/dist/status-ENAI35NL.js +0 -6
  136. package/dist/symphony-7INZR43F.js +0 -53
  137. package/dist/symphony-G6IENE4K.js +0 -2
  138. package/dist/symphony-relay-2RHG25Z4.js +0 -3
  139. package/dist/task-loader-IGQQ6ZFL.js +0 -2
  140. package/dist/task-settlement-NW4XMJGJ.js +0 -3
  141. package/dist/team-J2YXPEGX.js +0 -2
  142. package/dist/thread-HFXK65D4.js +0 -41
  143. package/dist/tools-HNJ7D5IO.js +0 -2
  144. package/dist/validate-IQG7DBFC.js +0 -9
  145. package/dist/validate-LSCDOLBO.js +0 -13
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import {a,O,l as l$1,D,G,L,F,K,J,I,N}from'./chunk-W3VWORQZ.js';import {a as a$2,d as d$1}from'./chunk-Q527BPUF.js';import {a as a$4}from'./chunk-VOPJ47QY.js';import {b as b$2}from'./chunk-RGSFU2YW.js';import {m,q as q$1,k,n,o,l,i,j as j$1,g}from'./chunk-TMDPDIWA.js';import {f}from'./chunk-KLBH26PA.js';import {j,a as a$3,i as i$1,b as b$1,h as h$1,g as g$2,c,d as d$2}from'./chunk-GRZQIKST.js';import {d,g as g$1,e,h,j as j$2,f as f$1}from'./chunk-ACJWUOMA.js';import {b,a as a$1}from'./chunk-EK4ZRIFJ.js';import*as R from'fs';import*as A from'path';import*as q from'js-yaml';import {execSync}from'child_process';import*as $t from'os';b();b();var Lt=".paradigm/navigator.yaml";async function st(n){let e=A.join(n,Lt);if(!R.existsSync(e))return {config:null,configPath:null};try{let o=R.readFileSync(e,"utf8");return {config:q.load(o),configPath:e}}catch(o){return a$1.component("#navigator-loader").error("Error parsing navigator.yaml",{error:o}),{config:null,configPath:e}}}function rt(n,e,o){switch(e.intent){case "find":return Ht(n,e.target||"");case "explore":return Bt(n,e.target||"");case "context":return Mt(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Ht(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let r=n.symbols[e];if(r)t.paths.push(r),t.symbols.push(e),t.explanation=`Found symbol ${e} at ${r}`;else {let s=Object.entries(n.symbols).filter(([i])=>i.includes(e.slice(1))).slice(0,5);s.length>0?(t.paths=s.map(([,i])=>i),t.symbols=s.map(([i])=>i),t.explanation=`Found ${s.length} symbols matching "${e}"`):t.explanation=`Symbol ${e} not found in navigator`;}}else {let r=Object.entries(n.symbols).filter(([s])=>s.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(r.length>0)t.paths=r.map(([,s])=>s),t.symbols=r.map(([s])=>s),t.explanation=`Found ${r.length} symbols matching "${e}"`;else {let s=Jt(n,e);s?(t.paths=s.paths,t.explanation=`Found ${e} in structure: ${s.paths.join(", ")}`):t.explanation=`No matches found for "${e}"`;}}return t.suggested_order=we(t.paths,n),t}function Bt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase();for(let[s,i]of Object.entries(n.structure))if(i&&(s.toLowerCase().includes(r)||r.includes(s.toLowerCase()))){t.paths.push(...i.paths);let a=Object.entries(n.symbols).filter(([c])=>c.startsWith(i.symbol)).slice(0,10);t.symbols.push(...a.map(([c])=>c));}for(let[s,i]of Object.entries(n.key_files))s.toLowerCase().includes(r)&&t.paths.push(...i);if(t.paths.length===0){let s=Object.entries(n.symbols).filter(([i,a])=>i.toLowerCase().includes(r)||a.toLowerCase().includes(r)).slice(0,10);t.paths=[...new Set(s.map(([,i])=>i))],t.symbols=s.map(([i])=>i);}return t.explanation=`Exploration paths for "${e}": ${t.paths.length} locations, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Mt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase(),s=Gt(r);for(let[i,a]of Object.entries(n.structure))a&&s.some(c=>i.toLowerCase().includes(c))&&t.paths.push(...a.paths);for(let[i,a]of Object.entries(n.symbols)){let c=i.slice(1).toLowerCase();s.some(l=>c.includes(l)||l.includes(c))&&(t.paths.push(a),t.symbols.push(i));}return t.paths.push(...n.key_files.config),t.paths=[...new Set(t.paths)],t.symbols=[...new Set(t.symbols)],r.includes("test")?t.skip=n.skip_patterns.always:t.skip=[...n.skip_patterns.always,...n.skip_patterns.unless_testing],!r.includes("doc")&&!r.includes("readme")&&t.skip.push(...n.skip_patterns.unless_docs),t.explanation=`Context for "${e}": ${t.paths.length} relevant files, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Jt(n,e){let o=e.toLowerCase();for(let[t,r]of Object.entries(n.structure))if(r&&(t.toLowerCase().includes(o)||o.includes(t.toLowerCase())))return r;return null}function Gt(n){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return n.split(/\s+/).map(o=>o.replace(/[^a-z0-9]/g,"")).filter(o=>o.length>2&&!e.has(o))}function we(n,e){let o={};for(let t of n){let r=0;e.key_files.config.some(s=>t.includes(s))&&(r+=100),e.key_files.entry.some(s=>t.includes(s))&&(r+=80),e.key_files.types.some(s=>t.includes(s))&&(r+=60),r-=t.split("/").length*2,o[t]=r;}return [...n].sort((t,r)=>(o[r]||0)-(o[t]||0))}b();function qt(n){let e=A.resolve(n),o=R.readFileSync(e,"utf8"),t=q.load(o);if(!t||typeof t!="object")throw new Error(`Invalid workspace file: ${n}`);let r={version:String(t.version||"1.0"),name:String(t.name||"unnamed-workspace"),members:[]};if(Array.isArray(t.members)){for(let s of t.members)if(typeof s=="object"&&s!==null){let i=s;r.members.push({name:String(i.name||""),path:String(i.path||""),role:i.role,exports:Array.isArray(i.exports)?i.exports.map(String):void 0});}}return r}function at(n,e){let o=A.resolve(n),t=A.resolve(o,e);if(!R.existsSync(t))return a$1.component("#workspace-loader").warn("Workspace file not found",{workspacePath:t}),null;let r;try{r=qt(t);}catch(c){return a$1.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let s=A.dirname(t),i="";for(let c of r.members){let l=A.resolve(s,c.path);if(it(l)===it(o)){i=c.name;break}}if(!i)return a$1.component("#workspace-loader").warn("Current directory is not a member of workspace",{workspace:r.name}),null;let a=new Map;for(let c of r.members){if(c.name===i)continue;let l=A.resolve(s,c.path),d=A.join(l,".paradigm","scan-index.json");if(!R.existsSync(d)){a$1.component("#workspace-loader").warn("No scan-index.json for workspace member",{member:c.name,scanIndexPath:d});continue}try{let p=JSON.parse(R.readFileSync(d,"utf8")),u=Vt(p);c.exports&&c.exports.length>0&&(u=Ut(u,c.exports));let y=null,x=A.join(l,"portal.yaml");if(R.existsSync(x))try{let m=R.readFileSync(x,"utf8"),C=q.load(m);C&&(y=C);}catch{}a.set(c.name,{index:u,gateConfig:y});}catch(p){a$1.component("#workspace-loader").warn("Could not load index for workspace member",{member:c.name,error:p.message});}}return {config:r,workspacePath:t,currentMember:i,siblingIndices:a}}function Ut(n,e){let t=q$1(n).filter(r=>{let s=r.symbol;return e.some(i=>zt(i,s))});return Kt(t)}function zt(n,e){let o=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${o}$`,"i").test(e)}function xe(n,e){let o=[];for(let[t,r]of n.siblingIndices){let s=m(r.index,e);for(let i of s)o.push({project:t,symbol:`${t}/${i.symbol}`,type:i.type,description:i.description,filePath:i.filePath});}return o}function ct(n,e){let o=[],t=e.includes("/")?e.split("/").pop():e;for(let[r,s]of n.siblingIndices){let i=[],a=q$1(s.index);for(let c of a){let l=c.references||[],d=c.description||"",p=l.some(y=>y===t||y===e||y.endsWith(`/${t}`)),u=d.includes(t);(p||u)&&i.push({symbol:c.symbol,type:c.type,description:c.description});}i.length>0&&o.push({project:r,references:i});}return o}function it(n){return A.resolve(n).replace(/\/+$/,"")}function Vt(n){let e={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"},o=[];for(let[t,r]of Object.entries(e)){let s=n[t];if(!(!s||typeof s!="object"))for(let[i,a]of Object.entries(s)){let c={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"}[r]||"#";o.push({id:i,symbol:a.symbol||`${c}${i}`,type:r,source:"purpose",filePath:a.path||"",data:{},references:a.related||[],referencedBy:[],description:a.description,tags:a.visualTags||[]});}}return j$1({symbols:o,purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}function Kt(n){return j$1({symbols:n.map(e=>({id:e.id||e.symbol.replace(/^[#$^!~]/,""),symbol:e.symbol,type:e.type,source:"purpose",filePath:e.filePath||"",data:e.data||{},references:e.references||[],referencedBy:e.referencedBy||[],description:e.description,tags:e.tags})),purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}var Qt={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function to(){return [Qt]}async function pt(n,e,o){if(n!=="paradigm_navigate")return {handled:false,text:""};let t={intent:e.intent||"find",target:e.target,task:e.task},r=await st(o.rootDir);if(r.config||(r={config:Yt(o),configPath:null}),false);if(t.intent==="context"&&!t.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((t.intent==="find"||t.intent==="explore")&&!t.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${t.intent} intent`,example:t.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let s=`navigate:${t.intent}:${t.target||""}:${t.task||""}`,i=await a.getOrCompute(s,()=>{let c=rt(r.config,t,o.rootDir),l={intent:t.intent,...t.target&&{target:t.target},...t.task&&{task:t.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(r.config?.auto_generated&&(l.auto_generated=true,l.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(l.note="No paths found.",l.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(l.tip=l.tip||"Many paths returned. Start with suggested_order for efficient exploration."),o.workspace){if(t.intent==="find"&&t.target&&c.paths.length===0){let d=xe(o.workspace,t.target);d.length>0&&(l.workspaceResults=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(t.intent==="context"&&t.task){let d=xe(o.workspace,t.task);d.length>0&&(l.workspaceContext=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})));}}return JSON.stringify(l,null,2)}),a$1=i;if(e.response_format==="concise")try{let c=JSON.parse(i);delete c.skip,delete c.tip,delete c.note,delete c.recovery,delete c.workspaceResults,delete c.workspaceContext,delete c.auto_generated,a$1=JSON.stringify(c,null,2);}catch{}try{let c=A.join(o.rootDir,".paradigm",".nav-called");R.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a$1}}function Yt(n){let e={},o={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},t=q$1(n.index),r=new Set;for(let a of t)if(a.filePath){e[a.symbol]=a.filePath,r.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":o.features.paths.includes(c)||o.features.paths.push(c);break;case "component":o.components.paths.includes(c)||o.components.paths.push(c);break;case "gate":o.gates.paths.includes(c)||o.gates.paths.push(c);break;case "flow":o.flows.paths.includes(c)||o.flows.paths.push(c);break}}let s=[],i=[];for(let a of n.aggregation.purposeFiles)s.push(a.filePath);return s.push(".paradigm/config.yaml"),n.gateConfig&&s.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:o,key_files:{config:s.slice(0,10),entry:i,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}function mt(n,e,o={}){let{maxResults:t=20}=o,r=[],s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=[`rg -n --no-heading "${s}" "${n}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${s}" "${n}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of i)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return r;let c=a.trim().split(`
3
+ `);for(let l of c.slice(0,t)){let d=l.match(/^(.+?):(\d+):(.*)$/);if(d){let[,p,u,y]=d,x=A.relative(n,p),m="unknown";x.includes(".purpose")||x.includes("portal.yaml")?m="purpose":y.includes("//")||y.includes("#")||y.includes("*")?m="comment":m="code",r.push({filePath:x,line:parseInt(u,10),content:y.trim().slice(0,200),context:m});}}return r}b();var Zt=30*1e3,ut=new Map;async function gt(n){let e=A.resolve(n),o=ut.get(e);if(o&&Date.now()-o.loadedAt<Zt)return o.index;let t=await en(e);return t&&ut.set(e,{index:t,loadedAt:Date.now()}),t}async function en(n){let e=A.join(n,".paradigm","flow-index.json");if(!R.existsSync(e))return null;try{let o=R.readFileSync(e,"utf8");return JSON.parse(o)}catch(o){return a$1.component("#flow-loader").error("Error parsing flow-index.json",{error:o}),null}}function tn(n,e){let o=n.symbolToFlows[e]||[],t=[];for(let r of o){let s=n.flows[r];if(!s)continue;let i=s.steps.map((a,c)=>({step:a,index:c})).filter(({step:a})=>a.symbol===e);for(let{step:a,index:c}of i){let l=s.steps.slice(c+1).map(d=>d.id);t.push({flowId:s.id,definedIn:s.definedIn,description:s.description,trigger:s.trigger,stepAffected:{id:a.id,action:a.action,position:c+1},downstreamSteps:l,validation:s.validation});}}return t}function yt(n,e){let o=tn(n,e),t=new Set;for(let i of o)i.validation?.command&&t.add(i.validation.command);let r="low",s=o.reduce((i,a)=>i+a.downstreamSteps.length,0);return o.length>3||s>10?r="high":(o.length>1||s>3)&&(r="medium"),{symbol:e,totalFlows:o.length,impactLevel:r,affectedFlows:o,validationCommands:Array.from(t),suggestion:o.length>0?`Changes to ${e} may affect ${o.length} flow(s). ${t.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function go(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["dependencies","impact","blast radius","what would break","dependents","affects"]}]}async function le(n$1,e,o$1){if(n$1!=="paradigm_ripple")return {handled:false,text:""};let{symbol:t,depth:r=3,includeWorkspace:s=false,response_format:i}=e,a=k(o$1.index,t);if(!a){let h=nn(o$1.rootDir,t);return O(h.length,n$1),{handled:true,text:h}}let c=Math.min(Math.max(r||3,1),5),l$2=n(o$1.index,t),d=new Set([t]),p=new Map;function u(h,P){if(P>=c)return;let v=[];for(let w of h){if(d.has(w))continue;d.add(w);let j=n(o$1.index,w);for(let T of j)d.has(T.symbol)||v.push(T.symbol);}v.length>0&&(p.set(P+1,v),u(v,P+1));}u(l$2.map(h=>h.symbol),1);let y=new Set;for(let[,h]of p)for(let P of h)P!==t&&!l$2.find(v=>v.symbol===P)&&y.add(P);let x=o(o$1.index,t),m=l$2.length+y.size,C="low";m>10?C="high":m>3&&(C="medium");let N=await gt(o$1.rootDir),F=null;if(N){let h=yt(N,t);h.totalFlows>0&&(h.impactLevel==="high"&&C==="low"?C="medium":h.impactLevel==="high"&&(C="high"),F={totalFlows:h.totalFlows,affectedFlows:h.affectedFlows.map(P=>({flowId:P.flowId,impactLevel:P.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${P.stepAffected.position}, affects ${P.downstreamSteps.length} downstream steps`})),validationSuggestion:h.validationCommands.length>0?`Run: ${h.validationCommands[0]}`:void 0});}let $=new Set([t,...l$2.map(h=>h.symbol),...y]),I=[];try{let h=l(o$1.index,"gate");for(let P of h)$.has(P.symbol)&&I.push({gate:P.symbol,description:P.description});for(let P of l$2)P.type==="gate"&&!I.find(v=>v.gate===P.symbol)&&I.push({gate:P.symbol,description:P.description});}catch{}let _={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:C,analysis:{directlyAffected:l$2.map(h=>({symbol:h.symbol,type:h.type,description:h.description})),indirectlyAffected:Array.from(y),indirectByLevel:Object.fromEntries(p),dependsOn:x.map(h=>({symbol:h.symbol,type:h.type}))},summary:{directCount:l$2.length,indirectCount:y.size,totalAffected:m,dependsOnCount:x.length,levelsAnalyzed:c},recommendation:on(C)};F&&(_.affectedFlows=F),I.length>0&&(_.affectedGates=I),_.suggestedReviewScope=sn(C,l$2.length,y.size,I.length,F?.totalFlows??0);try{let h=await l$1(o$1.rootDir,t);h.length>0&&(_.personas_affected=h,h.length>2&&C==="low"&&(_.impact="medium"));}catch{}try{let h=D(o$1.rootDir,t);h.length>0&&(_.university_content_affected=h.map(P=>({id:P.id,title:P.title,type:P.type,stale:P.stale})));}catch{}if(s&&o$1.workspace){let h=ct(o$1.workspace,t);if(h.length>0){_.workspaceImpact={siblings:h.map(v=>({project:v.project,references:v.references.map(w=>({symbol:w.symbol,type:w.type,description:w.description}))}))};let P=h.reduce((v,w)=>v+w.references.length,0);P>0&&C==="low"&&(_.impact="medium"),P>5&&(_.impact="high");}}let O$1=i==="concise"?{symbol:_.symbol,impact:_.impact,summary:_.summary}:_,E=JSON.stringify(O$1,null,2);return O(E.length,n$1),{handled:true,text:E}}function nn(n,e){let o=mt(n,e,{maxResults:20});if(o.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let t=[...new Set(o.map(i=>i.filePath))],r={};for(let i of o)r[i.context]=(r[i.context]||0)+1;let s="low";return t.length>10||o.length>20?s="high":(t.length>3||o.length>5)&&(s="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:s,analysis:{filesAffected:t.slice(0,10),totalFilesAffected:t.length,totalReferences:o.length,contextBreakdown:r,sampleReferences:o.slice(0,5).map(i=>({file:i.filePath,line:i.line,preview:i.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function on(n){switch(n){case "high":return "High impact change - review all affected symbols carefully before modifying";case "medium":return "Moderate impact - check direct dependencies for breaking changes";case "low":return "Low impact - safe to modify with standard review"}}function sn(n,e,o,t,r){let s=[];return e>0&&s.push(`Review ${e} direct dependent(s) for breaking changes`),o>0&&s.push(`Scan ${o} indirect dependent(s) for cascading effects`),t>0&&s.push(`Verify ${t} affected gate(s) still enforce correct auth/access`),r>0&&s.push(`Validate ${r} affected flow(s) end-to-end`),n==="high"?s.push("Consider running full test suite before merging"):n==="medium"&&s.push("Run targeted tests for affected components"),s.length===0&&s.push("No downstream dependents detected - safe to proceed"),s}b();b();var rn=30*1e3,ve=new Map,bt=".paradigm/wisdom";async function wt(n){let e=A.resolve(n),o=ve.get(e);if(o&&Date.now()-o.loadedAt<rn)return o.context;let t=await an(e);return ve.set(e,{context:t,loadedAt:Date.now()}),t}async function an(n){let e$1=A.join(n,bt),o=R.existsSync(e$1),[t,r,s,i]=o?await Promise.all([cn(e$1),ln(e$1),dn(e$1),pn(e$1)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e(),l=f$1();}catch{}let d$1=new Set(r.map(m=>m.id)),p=r.map(m=>({...m,scope:"project"}));for(let m of a)d$1.has(m.id)||p.push({...m,scope:"global"});let u=new Set(i.map(m=>m.id)),y=i.map(m=>({...m,scope:"project"}));for(let m of c)u.has(m.id)||y.push({...m,scope:"global"});let x=t;if(l&&!t)x=l;else if(l&&t){let m={...t.by_symbol};if(l.by_symbol)for(let[C,N]of Object.entries(l.by_symbol))m[C]||(m[C]=N);x={...t,by_symbol:m,global:{...l.global,...t.global}};}return {preferences:x,antipatterns:p,decisions:y,expertise:s}}function V(n){let e=A.resolve(n);ve.delete(e);}async function cn(n){let e=A.join(n,"preferences.yaml");if(!R.existsSync(e))return null;try{let o=R.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#wisdom-loader").error("Error parsing preferences.yaml",{error:o}),null}}async function ln(n){let e=A.join(n,"antipatterns.yaml");if(!R.existsSync(e))return [];try{let o=R.readFileSync(e,"utf8");return q.load(o).antipatterns||[]}catch(o){return a$1.component("#wisdom-loader").error("Error parsing antipatterns.yaml",{error:o}),[]}}async function dn(n){let e=A.join(n,"expertise.yaml");if(!R.existsSync(e))return null;try{let o=R.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#wisdom-loader").error("Error parsing expertise.yaml",{error:o}),null}}var ht=new Set;async function pn(n){let e=A.join(n,"decisions");if(!R.existsSync(e))return [];let o=[];try{let t=R.readdirSync(e);t.some(s=>s.endsWith(".yaml")||s.endsWith(".yml"))&&!ht.has(e)&&(ht.add(e),a$1.component("#wisdom-loader").warn("wisdom-decisions found; run `paradigm migrate decisions` in v6.0. In v5.39.0 wisdom-decisions are still read but will be migrated to TD-streams in v6.0."));for(let s of t){if(!s.endsWith(".yaml")&&!s.endsWith(".yml"))continue;let i=A.join(e,s);try{let a=R.readFileSync(i,"utf8"),c=q.load(a);o.push(c);}catch(a){a$1.component("#wisdom-loader").error(`Error parsing ${s}`,{error:a});}}}catch(t){a$1.component("#wisdom-loader").error("Error reading decisions directory",{error:t});}return o.sort((t,r)=>t.id.localeCompare(r.id)),o}function St(n,e){return e.map(o=>fn(n,o))}function fn(n,e){let o=n.preferences?.by_symbol?.[e]||null,t=n.antipatterns.filter(i=>i.symbols.some(a=>a===e||de(e,a))),r=n.decisions.filter(i=>i.symbols.some(a=>a===e||de(e,a))),s=n.expertise?.experts.filter(i=>i.symbols?.some(a=>a===e||de(e,a)))||[];return {symbol:e,preferences:o,antipatterns:t,decisions:r,experts:s}}function xt(n,e){return n.expertise?n.expertise.experts.filter(o=>!!(e.symbol&&o.symbols&&o.symbols.some(t=>t===e.symbol||de(e.symbol,t))||e.area&&o.areas&&o.areas.some(t=>t.toLowerCase().includes(e.area.toLowerCase())))):[]}function de(n,e){if(e.endsWith("*")){let o=e.slice(0,-1);return n.startsWith(o)}return n===e}async function vt(n,e){let o=A.join(n,bt),t=A.join(o,"antipatterns.yaml");R.existsSync(o)||R.mkdirSync(o,{recursive:true});let r={version:"1.0",antipatterns:[]};if(R.existsSync(t))try{let s=R.readFileSync(t,"utf8"),i=q.load(s);i&&typeof i=="object"&&(r={version:i.version||"1.0",antipatterns:Array.isArray(i.antipatterns)?i.antipatterns:[]});}catch{}r.antipatterns.push({...e,added:new Date().toISOString()}),R.writeFileSync(t,q.dump(r,{lineWidth:-1})),V(n);}b();var kt=".paradigm/history";async function _t(n){let e=A.join(n,kt);if(!R.existsSync(e))return {index:null,validation:null};let[o,t]=await Promise.all([mn(e),un(e)]);return {index:o,validation:t}}async function mn(n){let e=A.join(n,"index.yaml");if(!R.existsSync(e))return null;try{let o=R.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#history-loader").error("Error parsing index.yaml",{error:o.message}),null}}async function un(n){let e=A.join(n,"validation.yaml");if(!R.existsSync(e))return null;try{let o=R.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#history-loader").error("Error parsing validation.yaml",{error:o.message}),null}}function xo(n,e){return e.map(o=>gn(n,o))}function gn(n,e){let o=n.index?.by_symbol?.[e]||null,t=[];if(n.index?.co_changes){for(let s of n.index.co_changes)if(s.symbols.includes(e))for(let i of s.symbols)i!==e&&!t.includes(i)&&t.push(i);}let r=n.validation?.by_symbol?.[e]||null;return {symbol:e,summary:o,recent:o?.recent||[],co_changes:t,validation:r}}function vo(n,e){let o=[],t=[];if(!n.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let i of e){let a=n.index.by_symbol?.[i];a&&(a.fragility==="high"||a.fragility==="critical")&&o.push({symbol:i,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=n.index.fragile_symbols?.find(l=>l.symbol===i);c&&!o.find(l=>l.symbol===i)&&o.push(c);}for(let i of e){let a=n.index.co_changes?.filter(c=>c.symbols.includes(i));if(a?.length)for(let c of a){let l=c.symbols.filter(d=>d!==i&&!e.includes(d));l.length>0&&c.correlation>.7&&t.push(`${i} often changes with ${l.join(", ")} (${Math.round(c.correlation*100)}% correlation)`);}}let r=o.filter(i=>i.fragility==="critical").length===0,s=[];return o.length>0&&(s.push("Consider adding extra test coverage before modifying fragile symbols"),s.push("Review recent rollbacks and failures for these symbols")),t.length>0&&s.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:o,warnings:t,safe_to_modify:r,recommendations:s}}async function yn(n,e){let o=A.join(n,kt),t=A.join(o,"log.jsonl");R.existsSync(o)||R.mkdirSync(o,{recursive:true});let r=hn(t),s=new Date().toISOString(),i={id:r,ts:s,...e},a=JSON.stringify(i)+`
4
+ `;return R.appendFileSync(t,a),r}async function ko(n,e,o,t){return yn(n,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:o,tests:t})}function hn(n){let e=1;return R.existsSync(n)&&(e=R.readFileSync(n,"utf8").split(`
5
+ `).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}async function Ao(n){let e=A.resolve(n),o=await i(e),t=j$1(o),r=null,s=A.join(e,"portal.yaml");if(R.existsSync(s))try{r=await g(s);}catch(d){let p=d?.name??"Error";a$1.component("#index-loader").warn("Could not parse portal.yaml",{errorClass:p});}let i$1=A.basename(e),a=A.join(e,".premise");if(R.existsSync(a))try{let p=R.readFileSync(a,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);p&&(i$1=p[1].trim());}catch{}let c=null,l=A.join(e,".paradigm","config.yaml");if(R.existsSync(l))try{let d=R.readFileSync(l,"utf8"),p=q.load(d);p&&typeof p=="object"&&(p.version||a$1.component("#index-loader").warn('config.yaml missing "version" field'),p.project||a$1.component("#index-loader").warn('config.yaml missing "project" field')),p&&typeof p.workspace=="string"&&(c=at(e,p.workspace));}catch(d){a$1.component("#index-loader").warn("Failed to load workspace config",{error:d.message});}return {rootDir:e,index:t,aggregation:o,gateConfig:r,projectName:i$1,wisdom:null,history:null,workspace:c,_loadedAt:Date.now()}}async function fe(n){return n.wisdom||(n.wisdom=await wt(n.rootDir)),n.wisdom}async function Oo(n){return n.history||(n.history=await _t(n.rootDir)),n.history}j();b();var Pt=false;function Jo(){return [{name:"paradigm_wisdom_context",description:"Get team wisdom (preferences, antipatterns, decisions) for symbols before implementing. Call this before making changes to understand team patterns. Returns preferences, antipatterns, and decisions relevant to the specified symbols. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get wisdom for (e.g., ["@checkout", "#payment-form"])'},include_global:{type:"boolean",description:"Include global preferences (default: true)"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_wisdom_record",description:"Record a new team learning: antipattern (what not to do) or decision (architectural choice). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to record"},id:{type:"string",description:'Unique ID (for antipattern: e.g., "api-001", for decision: e.g., "001")'},symbols:{type:"array",items:{type:"string"},description:"Related symbols"},description:{type:"string",description:"What not to do (antipattern) or the decision made (decision)"},reason:{type:"string",description:"Why this is an antipattern / context for decision"},alternative:{type:"string",description:"What to do instead (for antipatterns)"},title:{type:"string",description:"Decision title (for decisions)"},status:{type:"string",enum:["proposed","accepted","deprecated","superseded"],description:"Decision status (for decisions)"},rationale:{type:"object",properties:{factors:{type:"array",items:{type:"string"}},conclusion:{type:"string"}},description:"Decision rationale (for decisions)"},consequences:{type:"object",properties:{positive:{type:"array",items:{type:"string"}},negative:{type:"array",items:{type:"string"}},mitigations:{type:"array",items:{type:"string"}}},description:"Expected consequences (for decisions)"},scope:{type:"string",enum:["project","global"],description:'Where to store: "project" (default) writes to .paradigm/wisdom/, "global" writes to ~/.paradigm/wisdom/'}},required:["type","id","symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]}},{name:"paradigm_wisdom_expert",description:"Find human experts who know about specific symbols or areas. Returns names and contact info for relevant experts. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to find experts for (e.g., "@checkout")'},area:{type:"string",description:'General area to find experts for (e.g., "payments", "auth")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Dt(n,e$1,o){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:r=true}=e$1,s=await fe(o),i=St(s,t),a={symbols:t,wisdom:i.map(d=>({symbol:d.symbol,preferences:d.preferences,antipatterns:d.antipatterns.map(p=>({id:p.id,description:p.description,reason:p.reason,alternative:p.alternative,scope:p.scope||"project"})),decisions:d.decisions.map(p=>({id:p.id,title:p.title,status:p.status,decision:p.decision,scope:p.scope||"project"})),experts:d.experts.map(p=>p.name)}))};r&&s.preferences?.global&&(a.global_preferences=s.preferences.global);let c=i.reduce((d,p)=>d+p.antipatterns.length,0),l=i.reduce((d,p)=>d+p.decisions.length,0);a.summary={symbols_with_preferences:i.filter(d=>d.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:i.some(d=>d.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let d={},p=[];for(let u of t){let y=await a$3(o.rootDir,{symbol:u,hasAssessment:!0,limit:100});if(y.length===0)continue;let x={correct:0,partial:0,incorrect:0},m=0,C=0;for(let F of y){let $=F.assessment.verdict;x[$]++,F.confidence!=null&&(m+=F.confidence,C++);}d[u]={total:y.length,...x,avgConfidence:C>0?Math.round(m/C*1e3)/1e3:null};let N=(x.correct+x.partial*.5)/y.length;N<.6&&y.length>=3&&p.push(`Low historical accuracy for ${u}: ${Math.round(N*100)}% across ${y.length} entries. Proceed with extra caution.`);}Object.keys(d).length>0&&(a.calibration=d),p.length>0&&(a.calibration_warnings=p);}catch{}return {handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_wisdom_record":{let{type:t,id:r,symbols:s,description:i,reason:a,alternative:c,title:l,status:d,rationale:p,consequences:u,scope:y="project"}=e$1;if(t==="antipattern"){if(!i||!a||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let x={id:r,symbols:s,description:i,reason:a,alternative:c};return y==="global"?g$1(x):await vt(o.rootDir,x),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,scope:y,message:`Antipattern recorded to ${y} scope`})}}if(t==="decision"){if(!l||!i||!p||!u)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};if(Pt||(Pt=true,a$1.component("#wisdom").warn('paradigm_wisdom_record({type:"decision"}) is deprecated. Use paradigm_decision_record instead.',{deprecation:"v6.0",canonical_tool:"paradigm_decision_record"})),y==="global"){let C={id:r,title:l,status:d||"proposed",date:new Date().toISOString().split("T")[0],symbols:s,context:a||"",decision:i,rationale:p,consequences:u};return h(C),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,scope:"global",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record for project-scoped decisions.',message:"Decision recorded to global scope"})}}let x=a$2(o.rootDir,{title:l,decision:i,rationale:{factors:p.factors,conclusion:p.conclusion},participants:[{id:"wisdom-record",role:"agent",stance:"proposed"}],symbols_affected:s,status:d==="accepted"?"active":d==="proposed"?"proposed":"active",context:a||void 0,consequences:u,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),m=d$1(o.rootDir,x.id);return V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:x.id,legacy_id:r,scope:"project",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record going forward.',message:`Decision recorded (routed to decisions stream as ${x.id})`,...m?{companion_lore_id:m}:{}})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_promote":{let{type:t,id:r}=e$1,s=await fe(o),i=A.basename(o.rootDir);if(t==="antipattern"){let a=s.antipatterns.find(l=>l.id===r);return a?d().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Antipattern "${r}" already exists in global scope`})}:(g$1({...a,learned_from:`promoted from ${i}`}),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,promoted_from:i,message:`Antipattern "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${r}" not found in project`})}}if(t==="decision"){let a=s.decisions.find(l=>l.id===r);return a?e().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Decision "${r}" already exists in global scope`})}:(h(a),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,promoted_from:i,message:`Decision "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${r}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_expert":{let{symbol:t,area:r}=e$1;if(!t&&!r)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let s=await fe(o),i=xt(s,{symbol:t,area:r});return {handled:true,text:JSON.stringify({query:{symbol:t,area:r},count:i.length,experts:i.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:i.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function Uo(){return [{name:"paradigm_protocol_search",description:"Search for protocols matching a task description. Call BEFORE exploring the codebase \u2014 if a matching protocol exists, follow its steps instead of discovering the pattern from scratch. Returns top matches with steps, exemplar, and freshness info. ~200 tokens.",inputSchema:{type:"object",properties:{task:{type:"string",description:'Task description to search for (e.g., "add a new page", "add API route")'},limit:{type:"number",description:"Maximum results (default: 3)"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_get",description:"Get a specific protocol by ID with full details and freshness check. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID (e.g., "P-add-view")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_record",description:"Record a new protocol after completing repeatable work. Captures the steps you followed so future agents can skip exploration. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Protocol name (e.g., "Add a new view")'},description:{type:"string",description:"What this protocol accomplishes"},trigger:{type:"array",items:{type:"string"},description:'Phrases that should match this protocol (e.g., ["add view", "new page"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g., ["ui", "frontend"])'},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols involved (e.g., ["#logs-view"])'},exemplar:{type:"string",description:'Canonical file to study for this pattern (e.g., "ui/src/views/LogsView.tsx")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"],description:"Step action type"},target:{type:"string",description:"File path (supports {Name}/{name} placeholders)"},template_from:{type:"string",description:"File to use as template (for create actions)"},reference:{type:"string",description:"Where in the file to make changes (for modify actions)"},command:{type:"string",description:"Command to execute (for run actions)"},notes:{type:"string",description:"Additional guidance for this step"}},required:["action"]},description:"Ordered steps to follow"},recorded_from:{type:"string",description:'Lore entry ID this protocol was learned from (e.g., "L-2026-03-01-001")'}},required:["name","description","trigger","tags","steps"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_update",description:"Update an existing protocol. Use refresh:true after successfully following a protocol to bump last_verified. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID to update (e.g., "P-add-view")'},refresh:{type:"boolean",description:"Set true to bump last_verified to now (use after successfully following the protocol)"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},trigger:{type:"array",items:{type:"string"},description:"Updated trigger phrases"},tags:{type:"array",items:{type:"string"},description:"Updated tags"},symbols:{type:"array",items:{type:"string"},description:"Updated symbols"},exemplar:{type:"string",description:"Updated exemplar path"},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"]},target:{type:"string"},template_from:{type:"string"},reference:{type:"string"},command:{type:"string"},notes:{type:"string"}},required:["action"]},description:"Updated steps"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_validate",description:"Validate protocol references \u2014 check that referenced files exist, exemplars haven't drifted. Validates all protocols if no ID given. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Protocol ID to validate (omit to validate all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Rt(n,e,o){switch(n){case "paradigm_protocol_search":{let t=e.task,r=e.limit||3,s=await I(o.rootDir,t,r);return s.length===0?{handled:true,text:JSON.stringify({count:0,task:t,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:s.length,task:t,matches:s.map(i=>({id:i.protocol.id,name:i.protocol.name,description:i.protocol.description,score:i.score,status:i.protocol.status,exemplar:i.protocol.exemplar,last_verified:i.protocol.last_verified,steps:i.protocol.steps.map(bn)}))},null,2)}}case "paradigm_protocol_get":{let t=e.id,r=await G(o.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let s=L(o.rootDir,r);return {handled:true,text:JSON.stringify({...r,freshness:{status:s.status,issues:s.issues}},null,2)}}case "paradigm_protocol_record":{let t=e.steps||[],r=await J(o.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:t,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:r,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let t=e.id,r=e.refresh,s={};e.name!==void 0&&(s.name=e.name),e.description!==void 0&&(s.description=e.description),e.trigger!==void 0&&(s.trigger=e.trigger),e.tags!==void 0&&(s.tags=e.tags),e.symbols!==void 0&&(s.symbols=e.symbols),e.exemplar!==void 0&&(s.exemplar=e.exemplar),e.steps!==void 0&&(s.steps=e.steps);let i=await K(o.rootDir,t,s,r===true);return {handled:true,text:JSON.stringify({success:i,id:t,refreshed:r===true,message:i?r?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${t}`})}}case "paradigm_protocol_validate":{let t=e.id;if(t){let a=await G(o.rootDir,t);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let c=L(o.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let s=(await F(o.rootDir)).map(a=>{let c=L(o.rootDir,a);return {id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified}}),i={total:s.length,current:s.filter(a=>a.status==="current").length,stale:s.filter(a=>a.status==="stale").length,broken:s.filter(a=>a.status==="broken").length};return {handled:true,text:JSON.stringify({protocols:s,health:i},null,2)}}default:return {handled:false,text:""}}}function bn(n){let e={action:n.action};return n.target&&(e.target=n.target),n.template_from&&(e.template_from=n.template_from),n.reference&&(e.reference=n.reference),n.command&&(e.command=n.command),n.notes&&(e.notes=n.notes),e}j();var ee=null,ke=false;async function _e(n){if(ee)ke||(await ee.ensureReady(),ke=true);else {let e=A.join(n,".paradigm","sentinel","sentinel.db");ee=new f(e),await ee.ensureReady(),ke=true;}return ee}async function wn(n,e){return (await _e(n)).recordPracticeEvent(e)}async function Ko(n,e){return (await _e(n)).getPracticeEvents(e)}async function Ce(n,e){return (await _e(n)).getComplianceRate(e)}async function It(n,e){let o=["discovery","verification","testing","documentation","collaboration","security"],t=[];for(let r of o){let s=await Ce(n,{...e,habitCategory:r});s.total>0&&t.push({category:r,...s});}return t}async function Qo(n,e,o){let t=[];for(let r of e){let s=await wn(n,{habitId:r.habitId,habitCategory:r.habitCategory,result:r.result,engineer:o.engineer,sessionId:o.sessionId,loreEntryId:o.loreEntryId,taskDescription:o.taskDescription,symbolsTouched:o.symbolsTouched,filesModified:o.filesModified,notes:r.notes});t.push(s);}return t}b();function At(n){return {handled:true,text:JSON.stringify({error:n},null,2)}}var me={code:"lore_type_decision_removed",message:"lore type 'decision' was removed in v6.0. Use paradigm_decision_record instead. The decision will be stored in .paradigm/decisions/ and a companion lore insight entry (type:'insight' with references.decision_id) will be written automatically so the timeline stays complete. For narrative-only references, use paradigm_lore_record({type:'insight', references:{decision_id}}).",successor_tool:"paradigm_decision_record",doc:"docs/private/plans/v6.0-decisions-locked.md",removed_in:"6.0.0"};function Ot(){let n=process.env.PARADIGM_AUTHOR;if(n)return Pe(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Pe(e)}catch{}try{let e=$t.userInfo().username;if(e)return Pe(e)}catch{}return "unknown"}function Pe(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function is(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, milestone, retro, insight, etc.). Call after completing significant work. Returns the created entry ID and file path. For decisions, use paradigm_decision_record (a companion lore insight is auto-written). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function je(n,e,o){switch(n){case "paradigm_lore_search":{let t={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},r=await a$3(o.rootDir,t);return {handled:true,text:JSON.stringify({count:r.length,filter:Object.fromEntries(Object.entries(t).filter(([,s])=>s!==void 0)),entries:r.map(Nt)},null,2)}}case "paradigm_lore_record":{let{type:t,title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:u,duration_minutes:y,decisions:x,errors_encountered:m,learnings:C,verification:N$1,tags:F,meta:$,body:I,linked_lore:_,linked_tasks:O,linked_commits:E,confidence:h}=e;if(t==="decision")return a$1.component("#lore").warn("rejected paradigm_lore_record({type:'decision'}) \u2014 removed in v6.0",{removed_in:me.removed_in,successor_tool:me.successor_tool}),At(me);let P;try{let S=new Date(Date.now()-2592e6).toISOString(),b=await Ce(o.rootDir,{dateFrom:S});if(b.total>0){let f=(await It(o.rootDir,{dateFrom:S})).filter(k=>k.rate<60).map(k=>k.category);P={rate:b.rate,followed:b.followed,skipped:b.skipped,partial:b.partial,weakAreas:f.length>0?f:void 0};}}catch{}let v={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:y,author:Ot(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:u,decisions:x,errors_encountered:m,learnings:C,verification:N$1,tags:F,meta:$||void 0,habit_compliance:P,body:I,linked_lore:_,linked_tasks:O,linked_commits:E,confidence:h!=null&&h>=0&&h<=1?h:void 0},w=await d$2(o.rootDir,v);j$2().setLastLoreEntryId(w);try{let S=process.env.PARADIGM_AGENT_ID;if(S&&i&&i.length>0){let{updateExpertiseFromLore:b}=await import('./agent-loader-W3RQJVW7.js');b(o.rootDir,S,{symbols_touched:i,confidence:h!=null&&h>=0&&h<=1?h:void 0});}}catch{}let j=null;try{c&&c.length>=2&&(j=N(o.rootDir,c,l||[]));}catch{}let T;if(e.stream){let S=e.stream,b=S==="auto"?xn(e):S;try{if(b==="work-log"){let{recordWorkLog:g}=await import('./work-log-loader-DL5GZ2BQ.js');g(o.rootDir,{agent:v.agent?.model||"unknown",summary:v.summary,outcome:v.verification?.status==="pass"?"pass":v.verification?.status==="fail"?"fail":"partial",files_modified:v.files_modified,symbols_touched:v.symbols_touched,commit:v.commit,linked_lore:v.id||w}),T="work-log";}else if(b==="journal"&&v.learnings?.length){let{recordJournalEntry:g}=await import('./journal-loader-CNNA4EAU.js');for(let f of v.learnings)g(v.agent?.model||"unknown",{trigger:"self_reflection",insight:f,project:o.projectName||"unknown",transferable:!1,linked_work_log:v.id||w});T="journal";}else if(b==="decision"&&v.decisions?.length){let{recordDecision:g}=await import('./decision-loader-HELL2AMX.js');for(let f of v.decisions)g(o.rootDir,{title:f.decision.slice(0,100),decision:f.decision,rationale:f.rationale,participants:[{id:`agent/${v.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:v.symbols_touched,status:"active",linked_lore:v.id||w});T="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:w,type:t,title:r,message:"Lore entry recorded successfully",...T?{stream:T}:{},...j?{protocol_suggestion:j}:{}})}}case "paradigm_lore_timeline":{let t=e.limit||10,r=await c(o.rootDir),s=await a$3(o.rootDir,{limit:t}),i={};for(let l of s)for(let d of l.symbols_touched)i[d]=(i[d]||0)+1;let a=Object.entries(i).sort(([,l],[,d])=>d-l).slice(0,10).map(([l,d])=>({symbol:l,count:d})),c$1={};for(let l of s){let d=l.author;c$1[d]||(c$1[d]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c$1[d].count++,l.agent&&(c$1[d].hasAgent=true),l.timestamp>c$1[d].lastActive&&(c$1[d].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:r||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:s.map(Nt),hotSymbols:a,authors:Object.entries(c$1).map(([l,d])=>({id:l,hasAgent:d.hasAgent,entries:d.count,lastActive:d.lastActive}))},null,2)}}case "paradigm_lore_get":{let t=e.id,r=await b$1(o.rootDir,t);return r?{handled:true,text:JSON.stringify(r,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})}}case "paradigm_lore_update":{let t=e.id,{id:r,...s}=e,i={};for(let[c,l]of Object.entries(s))l!==void 0&&(i[c]=l);let a=await g$2(o.rootDir,t,i);return {handled:true,text:JSON.stringify({success:a,id:t,message:a?"Lore entry updated":`Lore entry not found: ${t}`})}}case "paradigm_lore_assess":{let t=e.id,r=e.verdict,s=e.notes,i=await b$1(o.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})};let a={verdict:r,assessed_by:Ot(),assessed_at:new Date().toISOString(),notes:s},c=await h$1(o.rootDir,t,a);try{let u=process.env.PARADIGM_AGENT_ID;if(u&&c&&i.symbols_touched?.length){let{updateExpertiseFromAssessment:y}=await import('./agent-loader-W3RQJVW7.js');y(o.rootDir,u,{symbols_touched:i.symbols_touched,verdict:r});}}catch{}let l=r==="correct"?1:r==="partial"?.5:0,d=i.confidence!=null?l-i.confidence:null,p=d!=null?d>.1?"Under-confident (actual outcome better than predicted)":d<-0.1?"Over-confident (actual outcome worse than predicted)":"Well-calibrated":"No confidence recorded \u2014 delta not computed";return {handled:true,text:JSON.stringify({success:c,id:t,verdict:r,confidence:i.confidence??null,delta:d,deltaDescription:p,message:c?`Assessment recorded: ${r}${d!=null?` (delta: ${d>0?"+":""}${d.toFixed(2)})`:""}`:`Failed to assess: ${t}`})}}case "paradigm_lore_calibration":{let t={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},r=await a$3(o.rootDir,t),s=r.filter(I=>I.confidence!=null),i=r.length,a=s.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,p=0;for(let I of r){let _=I.assessment.verdict;c[_]++;let O=_==="correct"?1:_==="partial"?.5:0;l+=O,I.confidence!=null&&(d+=I.confidence,p+=Math.abs(O-I.confidence));}let u=i>0?l/i:0,y=a>0?d/a:null,x=a>0?l/i-d/a:null,m=a>0?1-p/a:null,C=e.groupBy,N;if(C&&i>0){let I=new Map;for(let _ of r){let O=[];C==="symbol"?O=_.symbols_touched||[]:C==="tag"?O=_.tags||[]:C==="type"&&(O=[_.type||"agent-session"]);for(let E of O)I.has(E)||I.set(E,[]),I.get(E).push(_);}N=Array.from(I.entries()).map(([_,O])=>{let E=O.filter(j=>j.confidence!=null),h={correct:0,partial:0,incorrect:0},P=0,v=0,w=0;for(let j of O){let T=j.assessment.verdict;h[T]++;let S=T==="correct"?1:T==="partial"?.5:0;P+=S,j.confidence!=null&&(v+=j.confidence,w+=Math.abs(S-j.confidence));}return {key:_,total:O.length,accuracyRate:P/O.length,avgConfidence:E.length>0?v/E.length:null,calibrationScore:E.length>0?1-w/E.length:null,verdictBreakdown:h}}).sort((_,O)=>O.total-_.total);}let F=[],$=i<5?`Low sample size (N=${i}). Stats may not be representative.`:i<15?`Moderate sample (N=${i}). Trends are directional, not conclusive.`:null;return $&&F.push($),m!=null&&(m>=.9?F.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):m>=.7?F.push("Good calibration \u2014 some room for improvement in confidence estimates."):m>=.5?F.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):F.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),x!=null&&(x>.15?F.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):x<-0.15&&F.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>i*.3&&i>=5&&F.push(`High error rate: ${c.incorrect}/${i} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:i,totalWithConfidence:a,accuracyRate:Math.round(u*1e3)/1e3,avgConfidence:y!=null?Math.round(y*1e3)/1e3:null,avgDelta:x!=null?Math.round(x*1e3)/1e3:null,calibrationScore:m!=null?Math.round(m*1e3)/1e3:null,verdictBreakdown:c,...N?{groups:N}:{},insights:F},null,2)}}case "paradigm_lore_delete":{let t=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let s=await i$1(o.rootDir,t);return {handled:true,text:JSON.stringify({success:s,id:t,message:s?"Lore entry deleted":`Lore entry not found: ${t}`})}}default:return {handled:false,text:""}}}function xn(n){return n.task_ref||n.files_modified||n.commit?"work-log":n.learnings||n.confidence!==void 0?"journal":n.decisions?.some(o=>o.rationale)?"decision":"work-log"}function Nt(n){return {id:n.id,type:n.type,title:n.title,summary:n.summary,author:n.author,agent:n.agent,timestamp:n.timestamp,duration_minutes:n.duration_minutes,symbols_touched:n.symbols_touched,verification:n.verification?.status,review:n.review?{completeness:n.review.completeness,quality:n.review.quality}:null,confidence:n.confidence??null,assessment:n.assessment?n.assessment.verdict:null,assessment_delta:n.assessment_delta??null,tags:n.tags}}function Ss(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_captain_board",description:"Cid's owned run-DAG board (#captain-board). action='read' (default, read-only) assembles the live orchestration DAG \u2014 each run's epic + ordered stage-children with status/claimant/dependsOn, plus ripple-ranked unclaimed open tasks and a summary. action='claim' writes a task's claimant (status stays open; human/peer claims override an archetype proposal). action='advance' records a blocked_on reason without changing status (orchestration owns in-progress/done). ~300 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["read","claim","advance"],description:"Board action. Default 'read'."},taskId:{type:"string",description:"Target task id (required for claim/advance)."},claimant:{type:"object",description:"For claim: the new owner { kind: 'archetype'|'human'|'peer', ref }.",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},blockedOn:{type:"string",description:"For advance: the blocking reason recorded on the task."}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function xs(n,e,o){return n==="paradigm_captain_brief"?vn(e,o):n==="paradigm_captain_debrief"?kn(e,o):n==="paradigm_captain_board"?jn(e,o):{handled:false,text:""}}async function vn(n,e){let o=n.taskDescription,t=n.symbols||[],r=n.depth||"standard",s=A.join(e.rootDir,".paradigm"),i=A.join(s,".cid-session"),a=A.join(s,".cid-briefed");try{R.existsSync(a)&&R.unlinkSync(a);let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r};R.mkdirSync(s,{recursive:!0}),R.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let c=Tn(o),l=[],d=new Set;for(let S of t)if(!d.has(S)){d.add(S);let b=Tt(S);l.push({id:S,type:b,description:"Provided as anchor symbol"});}let p=[];try{for(let S of c.slice(0,3)){let g=m(e.index,S).slice(0,5);for(let f of g)if(!d.has(f.symbol)){d.add(f.symbol);let k=Ln(f.type);l.push({id:f.symbol,type:k,description:f.description||"",file:f.file}),p.push(f.symbol);}}}catch{}let u={directories:[],files:[]};try{let S=await pt("paradigm_navigate",{intent:"context",task:o,response_format:"concise"},e);if(S.handled){let b=JSON.parse(S.text);if(b.files)for(let g of b.files){let f=typeof g=="string"?g:g.path||g.file||"";f&&u.files.push(f);}if(b.directories)for(let g of b.directories){let f=typeof g=="string"?g:g.path||g.directory||"";f&&u.directories.push(f);}if(b.symbols)for(let g of b.symbols){let f=typeof g=="string"?g:g.id;f&&!d.has(f)&&(d.add(f),l.push({id:f,type:Tt(f),description:typeof g=="object"&&g.description||""}));}}}catch{}let y=new Set(u.directories);for(let S of u.files){let b=A.dirname(S);b&&b!=="."&&y.add(b);}let x=l.slice(0,r==="deep"?5:3),m$1={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(r!=="quick"&&x.length>0)for(let S of x)try{let b=await le("paradigm_ripple",{symbol:S.id,depth:2,response_format:"concise"},e);if(b.handled){let g=JSON.parse(b.text);if(g.analysis){for(let f of g.analysis.directlyAffected||[]){let k=f.symbol||f;k&&!m$1.affectedSymbols.includes(k)&&m$1.affectedSymbols.push(k);}for(let f of g.analysis.indirectlyAffected||[])f&&!m$1.affectedSymbols.includes(f)&&m$1.affectedSymbols.push(f);}if(g.affectedFlows?.affectedFlows)for(let f of g.affectedFlows.affectedFlows){let k=f.flowId||f;k&&!m$1.affectedFlows.includes(k)&&m$1.affectedFlows.push(k);}if(g.affectedGates)for(let f of g.affectedGates){let k=f.gate||f;k&&!m$1.affectedGates.includes(k)&&m$1.affectedGates.push(k);}g.impact==="high"&&(m$1.fragileSymbols.includes(S.id)||m$1.fragileSymbols.push(S.id));}}catch{}let C=[],N=Wn(o);if(N.length>0)try{let{handleGatesForRoute:S}=await import('./tools-GDWT74O6.js').catch(()=>({handleGatesForRoute:null})),b=A.join(e.rootDir,"portal.yaml");if(R.existsSync(b)){let g=R.readFileSync(b,"utf8");for(let f of N){let k=g.includes(f);C.push({route:f,gate:"^authenticated",declared:k});}}else for(let g of N)C.push({route:g,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let F=[];if(r!=="quick"&&l.length>0)try{let S=l.slice(0,5).map(g=>g.id),b=await Dt("paradigm_wisdom_context",{symbols:S,include_global:!0},e);if(b.handled){let g=JSON.parse(b.text);if(g.antipatterns)for(let f of g.antipatterns.slice(0,3)){let k=f.pattern||f.description||f.text||String(f);k&&!F.includes(k)&&F.push(k);}if(g.wisdom?.antipatterns)for(let f of g.wisdom.antipatterns.slice(0,3)){let k=f.pattern||f.description||String(f);k&&!F.includes(k)&&F.push(k);}}}catch{}let $={matched:false};try{let S=await Rt("paradigm_protocol_search",{task:o,limit:1},e);if(S.handled){let b=JSON.parse(S.text),g=b.matches||b.protocols||b.results||[];if(g.length>0){let f=g[0];$={matched:!0,id:f.id,name:f.name||f.title,steps:(f.steps||[]).slice(0,5).map(k=>typeof k=="string"?k:k.description||String(k))};}}}catch{}let I=[];if(r!=="quick")try{let S=l[0]?.id,b={limit:r==="deep"?5:3};S&&(b.symbol=S);let g=await je("paradigm_lore_search",b,e);if(g.handled){let k=JSON.parse(g.text).entries||[];for(let M of k.slice(0,3))I.push({id:M.id,summary:(M.summary||M.title||"").slice(0,100),relevance:S?`Related to ${S}`:"Recent project history"});}}catch{}let _=Array.from(y),O$1=0;for(let S of _){let b=A.join(e.rootDir,S,".purpose");if(R.existsSync(b))try{R.readFileSync(b,"utf8").trim().length>50&&O$1++;}catch{}}let E=_.length>0?O$1/_.length:.5,h=Hn(E),P=Bn(E,h,_.length),v=m$1.affectedSymbols.length+u.files.length,w=v>20?"large":v>8?"medium":v>2?"small":"tiny",j={territory:{directories:_.slice(0,10),files:u.files.slice(0,10),estimatedScope:w},symbols:l.slice(0,10),blastRadius:m$1,gates:C,protocol:$,warnings:F,coverage:{score:E,label:h,note:P},loreRefs:I,archMap:b$2(e.rootDir),renderedBrief:""};j.renderedBrief=Mn(j);try{let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r,coverageScore:E};R.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let T=JSON.stringify(j,null,2);return O(T.length,"paradigm_captain_brief"),{handled:true,text:T}}async function kn(n,e){let o=n.orchestrationId,t=n.sessionSummary,r=n.touchedFiles||[],s=n.newSymbols||[],i=n.notes,a=A.join(e.rootDir,".paradigm"),c=A.join(a,".cid-briefed"),l=A.join(a,".pending-review"),d=new Set;for(let w of r){let j=A.dirname(w);j&&j!=="."&&d.add(j);}let p=0,u=d.size;for(let w of d){let j=A.join(e.rootDir,w,".purpose");if(R.existsSync(j))try{R.readFileSync(j,"utf8").trim().length>50&&p++;}catch{}}let y=u>0?p/u:1,x=[],m=[];for(let w of d){let j=A.join(e.rootDir,w,".purpose"),T=A.join(e.rootDir,w),S=false;if(R.existsSync(j))try{S=R.readFileSync(j,"utf8").trim().length>50;}catch{}if(S){if(r.some(g=>A.dirname(g)===w&&s.length>0)){m.push(w);try{let g=JSON.stringify({path:w,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${o}: ${s.join(", ")}`,timestamp:new Date().toISOString()});R.appendFileSync(l,g+`
6
+ `,"utf8");}catch{}}}else try{if(!R.existsSync(T))continue;let b=A.basename(w),g=Jn(b,w,r);R.writeFileSync(j,g,"utf8"),x.push(w),m.push(w);try{let f=JSON.stringify({path:w,reason:"captain-debrief",priority:"high",context:`Touched during orchestration ${o}. Files: ${r.filter(k=>A.dirname(k)===w).join(", ")}`,timestamp:new Date().toISOString()});R.appendFileSync(l,f+`
7
+ `,"utf8");}catch{}}catch{}}let C=0;for(let w of d){let j=A.join(e.rootDir,w,".purpose");if(R.existsSync(j))try{R.readFileSync(j,"utf8").trim().length>50&&C++;}catch{}}let N=u>0?C/u:1,F="";try{let w=await je("paradigm_lore_record",{type:"agent-session",title:`Cid Debrief: ${t.slice(0,80)}`,summary:t,symbols_touched:s,files_modified:r,tags:["arc:cid-debrief",`orch:${o}`],meta:{orchestrationId:o,coverageScore:{before:y,after:N},coverageAdded:x,...i?{notes:i}:{}}},e);if(w.handled){let j=JSON.parse(w.text);F=j.id||j.entry?.id||"";}}catch{}let $={ranThisSession:false,selfHealed:false,blockProposed:false};if($.ranThisSession=Pn(a),!$.ranThisSession)try{let{runPostflightLearning:w}=await import('./ambient-OW5M5LVN.js');await w(e.rootDir,{claimant:"navigation"}),$.selfHealed=!0,a$1.flow("$captain-board").info("Cid self-healed postflight (no prior liveness record)",{orchestrationId:o});}catch(w){$.selfHealError=w instanceof Error?w.message:String(w),a$1.flow("$captain-board").warn("Cid postflight self-heal threw \u2014 proposing advise block",{orchestrationId:o,error:$.selfHealError});try{let{handleProposeBlockTool:j}=await import('./propose-block-ZEMEWJQF.js');await j("paradigm_propose_block",{claimant:"navigation",severity:"advise",reason:`Postflight learning did not run and Cid's self-heal failed: ${$.selfHealError}`,unblock_hint:"Run `paradigm_ambient_learn_postflight` manually, or inspect .paradigm/events/settlement-liveness.jsonl for the severed stage."},e),$.blockProposed=!0;}catch{}}let I=false;try{let w={timestamp:new Date().toISOString(),sessionId:o,touchedFiles:r,coverageScore:N};R.mkdirSync(a,{recursive:!0}),R.writeFileSync(c,JSON.stringify(w,null,2),"utf8"),I=!0;}catch{}let _={taskDescription:t,orchestrationId:o,agentContributions:[],coverageDelta:{before:y,after:N},newSymbols:s,touchedFiles:r,notes:i||""};try{let w=A.join(a,"events","session-log.jsonl");if(R.existsSync(w)){let S=R.readFileSync(w,"utf8").split(`
8
+ `).filter(g=>g.trim().length>0).slice(-50),b=new Map;for(let g of S)try{let f=JSON.parse(g),k=f.agentId||f.agent||f.role||"";if(!k)continue;b.has(k)||b.set(k,{contributions:[],symbolsTouched:new Set,patternsObserved:[]});let M=b.get(k),De=f.action||f.event||f.message||"";if(De&&M.contributions.push(String(De).slice(0,120)),Array.isArray(f.symbols))for(let te of f.symbols)M.symbolsTouched.add(String(te));let Re=f.symbol||"";if(Re&&M.symbolsTouched.add(Re),Array.isArray(f.patterns))for(let te of f.patterns)M.patternsObserved.includes(String(te))||M.patternsObserved.push(String(te));}catch{}for(let[g,f]of b.entries())_.agentContributions.push({agentId:g,contribution:f.contributions.slice(-3).join(" | "),symbolsTouched:Array.from(f.symbolsTouched).slice(0,10),patternsObserved:f.patternsObserved.slice(0,5)});}}catch{}let O$1=_.agentContributions.length;_.agentContributions.length===0&&_.agentContributions.push({agentId:"session",contribution:t.slice(0,200),symbolsTouched:s.slice(0,10),patternsObserved:[]}),O$1>0&&a$4(e.rootDir,{verdicts:O$1,source:"debrief"});let E={coverageAdded:x,delegatedToDocumentor:m,loreEntryId:F,coverageScore:{before:y,after:N,delta:N-y},stopHookCleared:I,postflight:$,sessionInsights:_},h=["","\u2501\u2501\u2501 LEARNING HANDOFF (\u2192 Loid) \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501","","Cid has prepared session insights for Loid's learning pass.","Call paradigm_ambient_learn_postflight with the sessionInsights","from this debrief to complete the session.","","sessionInsights available in: debrief.sessionInsights"].join(`
9
+ `),v=JSON.stringify(E,null,2)+`
10
+ `+h;return O(v.length,"paradigm_captain_debrief"),{handled:true,text:v}}var _n=A.join("events","settlement-liveness.jsonl"),Cn=360*60*1e3;function Pn(n){let e=A.join(n,_n);if(!R.existsSync(e))return false;try{let t=R.readFileSync(e,"utf8").split(`
11
+ `).filter(s=>s.trim().length>0),r=Date.now()-Cn;for(let s of t.slice(-50))try{let i=JSON.parse(s),a=i.ts?new Date(i.ts).getTime():NaN;if(Number.isNaN(a)||a<r)continue;if(i.stages?.runPostflightLearning==="ok")return !0}catch{}}catch{return false}return false}async function jn(n,e){let o=n.action||"read";if(o==="claim")return $n(n,e);if(o==="advance")return En(n,e);let t=await On(e.rootDir,{},e),r=JSON.stringify(t,null,2);return O(r.length,"paradigm_captain_board"),{handled:true,text:r}}function Dn(n,e){return n.settledAt?n.crashed_at||e.some(t=>t.crashed_at)?"crashed":"settled":e.length===0?"pending":e.some(t=>t.status==="in-progress")||n.status==="in-progress"?"in-progress":"pending"}function Rn(n){return [...n].sort((e,o)=>{let t=e.stage??0,r=o.stage??0;if(t!==r)return t-r;let s=e.dependsOn?.length??0,i=o.dependsOn?.length??0;return s!==i?s-i:e.id.localeCompare(o.id)})}async function Fn(n,e){let o=Wt(n).slice(0,3),t=[];for(let r of o)try{let s=await le("paradigm_ripple",{symbol:r,depth:1,response_format:"concise"},e);s.handled&&JSON.parse(s.text).impact==="high"&&!t.includes(r)&&t.push(r);}catch{}return t}var In=/[#$^!~][a-z][a-z0-9-]*/gi;function Wt(n){let e=new Set;for(let t of n.tags||[])/^[#$^!~]/.test(t)&&e.add(t);let o=n.blurb?.match(In)||[];for(let t of o)e.add(t);return Array.from(e)}async function An(n,e){let o=Wt(n).slice(0,3),t=0,r=[];for(let s of o)try{let i=await le("paradigm_ripple",{symbol:s,depth:2,response_format:"concise"},e);if(i.handled){let a=JSON.parse(i.text),c=a.analysis?.directlyAffected?.length??0,l=a.analysis?.indirectlyAffected?.length??0;t+=c*2+l,a.impact==="high"&&!r.includes(s)&&r.push(s);}}catch{}return {score:t,fragile:r}}var Et={high:0,medium:1,low:2};async function On(n,e={},o){let t=o,{loadTasks:r}=await import('./task-loader-IO4UVFUD.js'),s=[];try{s=await r(n,{status:"all",limit:9999});}catch(u){a$1.flow("$captain-board").warn("Board task load failed",{error:u instanceof Error?u.message:String(u)});}let i=s.filter(u=>u.external_ref?.provider==="orchestration"&&!u.parentTaskId&&!u.settledAt),a=[];for(let u of i){let y=Rn(s.filter(m=>m.parentTaskId===u.id)),x=[];for(let m of y){let C=t?await Fn(m,t):[];x.push({taskId:m.id,blurb:m.blurb,stage:m.stage,status:m.status,claimant:m.claimant,dependsOn:m.dependsOn||[],fragileSymbols:C});}a.push({epicTaskId:u.id,blurb:u.blurb,runStatus:Dn(u,y),settledAt:u.settledAt,nodes:x});}let c=s.filter(u=>u.status==="open"&&!u.claimant),l=[];for(let u of c){let{score:y,fragile:x}=t?await An(u,t):{score:0,fragile:[]},m;e.proposeClaimants&&(m=await Nn(u,n)),l.push({taskId:u.id,blurb:u.blurb,priority:u.priority,tags:u.tags||[],rippleScore:y,fragileSymbols:x,proposedClaimant:m});}l.sort((u,y)=>{if(y.rippleScore!==u.rippleScore)return y.rippleScore-u.rippleScore;let x=(Et[u.priority]??1)-(Et[y.priority]??1);return x!==0?x:y.taskId.localeCompare(u.taskId)});let d=s.filter(u=>u.status==="in-progress").length,p=s.filter(u=>u.status==="open").length;return {runs:a,unclaimed:l,summary:{runs:a.length,open:p,inFlight:d,unclaimed:l.length}}}async function Nn(n,e){try{let{suggestAgentsForTask:o,loadAgentsManifest:t}=await import('./orchestration-UP3KFUJT.js'),r=t(e);if(!r?.agents)return;let s=[n.blurb,...n.tags||[]].join(" "),i=o(s,r.agents);return i.length===0?void 0:{kind:"archetype",ref:i[0].name}}catch{return}}async function $n(n,e){let o=n.taskId,t=n.claimant;if(!o||!t?.kind||!t?.ref)return {handled:true,text:JSON.stringify({ok:false,error:"claim requires taskId and claimant {kind, ref}"})};let{loadTask:r,updateTask:s}=await import('./task-loader-IO4UVFUD.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a=i.claimant;if(a&&a.kind!=="archetype"&&t.kind==="archetype")return a$1.flow("$captain-board").info("Claim rejected: archetype cannot override human/peer claim",{taskId:o,existing:a.kind,proposed:t.kind}),{handled:true,text:JSON.stringify({ok:false,error:`task ${o} is claimed by ${a.kind}:${a.ref}; archetype proposal cannot override`,claimant:a})};let c=await s(e.rootDir,o,{claimant:t});return a$1.flow("$captain-board").info("Captain claim written",{taskId:o,claimant:t,ok:c}),{handled:true,text:JSON.stringify({ok:c,taskId:o,claimant:t,status:"open"})}}async function En(n,e){let o=n.taskId,t=n.blockedOn;if(!o||!t)return {handled:true,text:JSON.stringify({ok:false,error:"advance requires taskId and blockedOn (v7.0 has no 'blocked' status \u2014 advance records a reason only)"})};let{loadTask:r,updateTask:s}=await import('./task-loader-IO4UVFUD.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a=await s(e.rootDir,o,{blocked_on:t});return a$1.flow("$captain-board").info("Captain advance: blocked_on recorded (status unchanged)",{taskId:o,blockedOn:t,status:i.status,ok:a}),{handled:true,text:JSON.stringify({ok:a,taskId:o,blocked_on:t,status:i.status})}}function Tn(n){let e=new Set(["the","a","an","to","of","in","and","or","for","with","that","this","is","it","be","as","at","by","from","add","create","update","fix","implement","make","build","change","modify","new","old","get","set","use","using"]),o=n.match(/[#$^!~@&%?][a-z][a-z0-9-]*/g)||[],t=n.replace(/[#$^!~@&%?]/g," ").split(/[\s\-_\/.,;:'"()\[\]{}!?]+/).map(s=>s.toLowerCase()).filter(s=>s.length>2&&!e.has(s));return [...new Set([...o,...t])].slice(0,6)}function Wn(n){let e=[],o=/(?:GET|POST|PUT|PATCH|DELETE)\s+(\/[a-z0-9\-\/:_{}]+)/gi,t;for(;(t=o.exec(n))!==null;)e.push(t[1]);let r=/\/api\/[a-z0-9\-\/:_{}]+/g;for(;(t=r.exec(n))!==null;)e.includes(t[0])||e.push(t[0]);return e}function Tt(n){return n.startsWith("#")?"component":n.startsWith("$")?"flow":n.startsWith("^")?"gate":n.startsWith("!")?"signal":n.startsWith("~")?"aspect":"component"}function Ln(n){switch(n){case "component":return "component";case "flow":return "flow";case "gate":return "gate";case "signal":return "signal";case "aspect":return "aspect";default:return "component"}}function Hn(n){return n>=.85?"comprehensive":n>=.6?"reliable":n>=.3?"partial":"sparse"}function Bn(n,e,o){let t=Math.round(n*100);switch(e){case "sparse":return `${t}% of ${o} director(ies) covered. Brief may be significantly incomplete. Builder should explore directly.`;case "partial":return `${t}% of ${o} director(ies) covered. Brief covers key symbols. Some areas uncharted.`;case "reliable":return `${t}% of ${o} director(ies) covered. Brief is reliable for this task.`;case "comprehensive":return `${t}% of ${o} director(ies) covered. Area is fully mapped.`}}function Mn(n){let e=[],o="\u2501".repeat(52);e.push(`${o}`),e.push("");let t=n.territory.directories.slice(0,3).join(", ")||"(none detected)";e.push(`Territory: ${t}`);let r=n.symbols.slice(0,5).map(d=>d.id).join(", ")||"(none found)";e.push(`Symbols: ${r}`);let s=n.blastRadius.affectedFiles.length+n.territory.files.length,i=n.blastRadius.affectedFlows.length,a=n.blastRadius.affectedGates.length,c=n.blastRadius.fragileSymbols.length>0?` \xB7 \u26A0 ${n.blastRadius.fragileSymbols.slice(0,2).join(", ")} (fragile)`:"";if(e.push(`Blast Radius: ${s} files \xB7 ${i} flows \xB7 ${a} gates${c}`),n.gates.length>0){let d=n.gates.slice(0,2).map(p=>`${p.route} \u2192 ${p.gate} (${p.declared?"declared \u2713":"UNDECLARED \u2717"})`);e.push(`Gates: ${d.join("; ")}`);}if(n.protocol.matched){let d=n.protocol.steps?.length?` (${n.protocol.steps.length} steps)`:"";e.push(`Protocol: ${n.protocol.name||n.protocol.id}${d} \u2014 matched`);}else e.push("Protocol: (none matched)");n.warnings.length>0&&e.push(`Warnings: "${n.warnings[0].slice(0,80)}"`);let l=Math.round(n.coverage.score*100);return e.push(`Coverage: ${l}% \u2014 brief is ${n.coverage.label}`),e.push(""),e.push(`${o}`),e.join(`
12
+ `)}function Jn(n,e,o){let r=o.filter(s=>A.dirname(s)===e).slice(0,3).map(s=>`# - ${A.basename(s)}`).join(`
13
+ `);return `# Auto-generated .purpose stub \u2014 created by Cid (captain debrief)
14
+ # Delegate to Scribe (Documentor) for rich documentation
15
+ name: ${n}
16
+ description: "TODO: describe what this directory/module does"
17
+ context:
18
+ - "Stub created by Cid during coverage audit \u2014 update with real context"
19
+ ${r?`# Key files touched:
20
+ ${r}`:""}
21
+ components:
22
+ ${n}:
23
+ description: "TODO: describe this component"
24
+ tags: []
25
+ `}export{is as A,je as B,Ss as C,xs as D,On as E,Nn as F,fn as a,xt as b,xo as c,gn as d,vo as e,yn as f,ko as g,xe as h,Ao as i,fe as j,Oo as k,to as l,pt as m,mt as n,gt as o,yt as p,go as q,le as r,Jo as s,Dt as t,Uo as u,Rt as v,Ko as w,Ce as x,It as y,Qo as z};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import {b as b$1}from'./chunk-5TAVYPOV.js';import*as i from'fs';import*as l from'path';import*as N from'os';import*as u from'js-yaml';function g(o){if(!o)return "";let t=o.trim();return t=t.replace(/^symbol:/i,""),t=t.replace(/^[#$^!~@&%?]/,""),t.trim().toLowerCase()}function E(o,t,n){let s=new Map,c=l.join(y,o);w(c,s);let e=l.join(t,h,o);w(e,s);let r=Array.from(s.values());if(n?.concepts&&n.concepts.length>0){let p=new Set(n.concepts.map(g));r=r.filter(a=>a.concepts.some(f=>p.has(g(f))));}if(n?.tags&&n.tags.length>0){let p=new Set(n.tags.map(a=>a.toLowerCase()));r=r.filter(a=>a.tags.some(f=>p.has(f.toLowerCase())));}return r.sort((p,a)=>a.appliedCount-p.appliedCount)}function w(o,t){if(i.existsSync(o))try{let n=i.readdirSync(o).filter(s=>s.startsWith(O)&&s.endsWith(S));for(let s of n)try{let c=i.readFileSync(l.join(o,s),"utf-8"),e=u.load(c);e?.id&&t.set(e.id,e);}catch{}}catch{}}function _(o,t,n){let s=Array.from(new Set((t||[]).map(g).filter(Boolean)));if(s.length===0)return {value:b,found:false};let c=E(o,n,{concepts:s});return c.length===0?{value:b,found:false}:{value:Math.max(...c.map(r=>typeof r.confidence=="number"?r.confidence:b)),found:true}}function $(o,t,n){let s=E(o,n),c=t.toLowerCase();return s.filter(e=>e.context.toLowerCase().includes(c)||e.snippet.toLowerCase().includes(c)||e.concepts.some(r=>r.toLowerCase().includes(c))||e.tags.some(r=>r.toLowerCase().includes(c)))}function L(o){let t=[o.context,o.snippet,...o.concepts,...o.tags].join(" ").toLowerCase();return ["paradigm","mcp_","mcp tool",".paradigm/","lore entry","lore record","aspect","^gate","portal.yaml",".purpose","sentinel","symphony","ambient nomination","paradigm_"," pan ","agent notebook","concept anchor","symbol system","work log","knowledge stream","nevr.land","neverland"].some(s=>t.includes(s))?"platform-specific":/[#$^!~][a-z][a-z0-9-]{2,}/.test(t)||/\/[a-z0-9_-]{2,}\/[a-z0-9_-]/.test(t)?"project-specific":"generalizable"}function v(o,t,n,s){let c=new Date().toISOString(),e=(t.concepts[0]||t.context.split(" ").slice(0,4).join(" ")||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),p=`nb-${o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}-${e}`,a=t.scope??L({context:t.context,snippet:t.snippet,concepts:t.concepts,tags:t.tags}),f=Array.from(new Set((t.concepts||[]).map(g).filter(Boolean))),m={...t,concepts:f,id:p,scope:a,publishable:t.publishable??true,confidence:t.confidence??.5,appliedCount:0,created:c,updated:c},d=n==="global"?l.join(y,o):l.join(s||process.cwd(),h,o);i.existsSync(d)||i.mkdirSync(d,{recursive:true});let x=`${p}${S}`,k=l.join(d,x),C=u.dump(m,{lineWidth:120,noRefs:true,sortKeys:false});return i.writeFileSync(k,C,"utf-8"),{entry:m,filePath:k}}async function z(o,t,n,s="global"){let{loadLoreEntry:c}=await import('./lore-loader-PXFKMKAN.js'),e=await c(n,t);if(!e)return null;let r=[];if(e.symbols_touched)for(let f of e.symbols_touched){let m=f.replace(/^[#$^!~]/,"").toLowerCase();r.push(m);}let p=e.summary||"";e.body&&(p+=`
3
+
4
+ `+e.body);let a={source:"lore",loreEntryId:t,originProject:l.basename(n),createdBy:o};return v(o,{context:e.title||`Promoted from ${t}`,snippet:p,provenance:a,confidence:e.confidence??.7,concepts:r,tags:e.tags||[]},s,n)}function T(o,t,n){let s=l.join(n,h,o),c=l.join(y,o);for(let e of [s,c]){let r=l.join(e,`${t}${S}`);if(i.existsSync(r))try{let p=i.readFileSync(r,"utf-8"),a=u.load(p);if(a)return a.appliedCount=(a.appliedCount||0)+1,a.updated=new Date().toISOString(),i.writeFileSync(r,u.dump(a,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var y,h,O,S,b,P=b$1(()=>{y=l.join(N.homedir(),".paradigm","notebooks"),h=".paradigm/notebooks",O="nb-",S=".yaml";b=.5;});export{g as a,E as b,b as c,_ as d,$ as e,L as f,v as g,z as h,T as i,P as j};
@@ -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};
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env node
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
+ `),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||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
+
8
+ ---
9
+
10
+ `));}let q=D;m.agent==="architect"&&r&&(q=r+(D?`
11
+
12
+ ---
13
+
14
+ `+D:""));let B=q?`${m.subtask}
15
+
16
+ ## Context from previous agents:
17
+ ${q}`:m.subtask;v&&m.agent==="reviewer"&&(B=`${B}
18
+
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
+ `)}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=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
+ `).slice(-e.lines).join(`
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
+ `)}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
+ `),s.onMessage?.(o,a);},onAgentStart:(o,a,d)=>{r.write(`
31
+ \u25B6 ${o}: ${a}
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,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-QBIQ2FYB.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(`
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ import {c,b as b$2}from'./chunk-3KVVC4WV.js';import {j,a as a$1,d,g as g$1}from'./chunk-KAUGQMXU.js';import {z,i,c as c$1,f as f$1,j as j$1}from'./chunk-KAFQA7HV.js';import {b as b$1,a as a$2}from'./chunk-EK4ZRIFJ.js';import {f,b as b$3}from'./chunk-ECO3LHCE.js';import {b,a}from'./chunk-5TAVYPOV.js';import*as l from'fs';import*as g from'path';import*as nt from'js-yaml';import*as T from'os';function Q(e){return g.join(e,K,ut)}function gt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${e}-${t}`}function E(e,t){let n={id:gt(),timestamp:new Date().toISOString(),...t};_.push(n),_.length>k&&(_=_.slice(-k));try{let o=g.join(e,K);l.mkdirSync(o,{recursive:!0});let r=Q(e);l.appendFileSync(r,JSON.stringify(n)+`
3
+ `,"utf8"),pt(r);}catch{}return n}function pt(e){try{if(l.statSync(e).size>512*1024){let o=l.readFileSync(e,"utf8").trim().split(`
4
+ `);if(o.length>k){let r=o.slice(-k);l.writeFileSync(e,r.join(`
5
+ `)+`
6
+ `,"utf8");}}}catch{}}function Lt(e,t){let n=ht(e);return t?.type&&(n=n.filter(o=>o.type===t.type)),t?.source&&(n=n.filter(o=>o.source===t.source)),t?.symbol&&(n=n.filter(o=>o.symbols?.includes(t.symbol))),t?.agent&&(n=n.filter(o=>o.agent===t.agent)),t?.since&&(n=n.filter(o=>o.timestamp>=t.since)),n.sort((o,r)=>r.timestamp.localeCompare(o.timestamp)),t?.limit&&(n=n.slice(0,t.limit)),n}function ht(e){let t=Q(e);if(!l.existsSync(t))return [..._];try{return l.readFileSync(t,"utf8").trim().split(`
7
+ `).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return [..._]}}function Z(e,t,n){let o=0,r=0,i=0,s=0;if(n.symbols?.length&&e.symbols?.length)for(let c of n.symbols)for(let a of e.symbols)X(c,a)&&(o=Math.max(o,1));if(n.paths?.length&&e.path){for(let c of n.paths)if(X(c,e.path)){r=1;break}}if(n.concepts?.length){let c=[e.context||"",...e.keywords||[],e.type||""].join(" ").toLowerCase(),a=0;for(let u of n.concepts)u&&c.includes(u.toLowerCase())&&a++;n.concepts.length>0&&(i=a/n.concepts.length);}if(n.signals?.length){for(let c of n.signals)if(c.type===e.type){s=1;break}}let f=[o,r,i,s].sort((c,a)=>a-c),d=f[0]*.5+f[1]*.2+f[2]*.15+f[3]*.15,m=n.threshold??.6;return {agentId:t,score:d,breakdown:{symbolMatch:o,pathMatch:r,conceptMatch:i,signalMatch:s},shouldNominate:d>=m,quietReason:d<m?"below-threshold":void 0}}function X(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var K,ut,k,_,tt=b(()=>{K=".paradigm/events",ut="stream.jsonl",k=1e3,_=[];});function C(e){let t=g.join(e,yt);if(!l.existsSync(t))return {...b$2};try{let n=l.readFileSync(t,"utf8"),o=nt.load(n);return bt(b$2,o)}catch{return {...b$2}}}function bt(e,t){let n={...e};if(t.version&&(n.version=t.version),t.default_ring&&(n.default_ring=t.default_ring),t.observation&&(n.observation={allow:t.observation.allow||e.observation?.allow,deny:[...e.observation?.deny||[],...t.observation.deny||[]].filter((o,r,i)=>i.indexOf(o)===r)}),t.streams){n.streams={...e.streams};for(let o of ["work_log","learning_journal","team_decisions"])t.streams[o]&&(n.streams[o]={...e.streams?.[o],...t.streams[o],deny_content:[...e.streams?.[o]?.deny_content||[],...t.streams[o]?.deny_content||[]].filter((r,i,s)=>s.indexOf(r)===i)});}return t.upstream&&(n.upstream={...e.upstream,...t.upstream}),t.network&&(n.network={...e.network,...t.network}),t.agent_overrides&&(n.agent_overrides={...e.agent_overrides,...t.agent_overrides}),t.deployment&&(n.deployment={...e.deployment,...t.deployment}),n}function M(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(r=>R(r,t))||e.observation?.deny?.some(o=>R(o,t))?false:e.observation?.allow?.length?e.observation.allow.some(o=>R(o,t)):true}function Gt(e,t,n){let o=t.streams?.[n];if(!o)return {filtered:e,redacted:[]};let r=[],i=e;if(o.redaction)for(let s of o.redaction)try{let f=new RegExp(s.pattern,"gi"),d=i.match(f);d&&(r.push(...d),i=i.replace(f,s.replacement||"[REDACTED]"));}catch{}return {filtered:i,redacted:r}}function R(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var yt,ot=b(()=>{c();yt=".paradigm/data-policy.yaml";});function kt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function jt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${e}-${t}`}function st(e,t){let n=i(e),o=C(e),r=[];for(let m of n){if(!m.attention||!c$1(m.id,e)||t.path&&!M(o,t.path,m.id))continue;let c=Z(t,m.id,m.attention);c.shouldNominate&&r.push({profile:m,score:c});}if(r.length===0)return {nominations:[],debates:[]};let i$1=A(e,{since:new Date(Date.now()-3e4).toISOString()}),s=r.filter(({profile:m})=>!i$1.find(a=>a.agent===m.id&&a.brief===rt(m,t,{...r.find(u=>u.profile.id===m.id).score})));if(s.length===0)return {nominations:[],debates:[]};let f=s.map(({profile:m,score:c})=>{let a=Tt(t,c),u=Pt(m,t);return {id:kt(),agent:m.id,relevance:c.score,urgency:a,type:u,brief:rt(m,t,c),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});Dt(e,f);let d=At(e,f);return d.length>0&&Ft(e,d),{nominations:f,debates:d}}function Tt(e,t){return e.severity==="critical"?"critical":e.severity==="error"||e.type==="compliance-violation"||e.type==="error-encountered"?"high":e.type==="gate-added"||e.type==="route-created"||t.score>=.9?"medium":"low"}function Pt(e,t){let n=e.collaboration?.stance;return t.type==="compliance-violation"||t.type==="error-encountered"?"warning":t.type==="gate-added"||t.type==="route-created"?"observation":n==="advisory"||n==="lead"?"suggestion":"observation"}function rt(e,t,n){let o=e.role||e.id;switch(t.type){case "gate-checked":return `${o}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${o}: ${t.path||"File"} modified \u2014 review for ${e.id==="security"?"security implications":e.id==="tester"?"test coverage":e.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${o}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${o}: New route ${t.symbols?.join(", ")||""} \u2014 ${e.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${o}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${e.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${o}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${o}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${o}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let r=n.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:n.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${o}: ${r}`}}}function At(e,t){if(t.length<2)return [];let n=[],o=new Map;for(let r of t)for(let i of r.triggered_by){let s=o.get(i)||[];s.push(r),o.set(i,s);}for(let[r,i]of o){if(i.length<2||new Set(i.map(m=>m.agent)).size<2)continue;let f=new Set(i.map(m=>m.type)),d=f.size>1&&f.has("warning")&&f.has("suggestion");n.push({id:jt(),topic:`Multiple agents responded to event ${r}`,nominations:i.map(m=>m.id),type:d?"conflicting":"complementary",overlap_events:[r]});}return n}function I(e){return g.join(e,S,St)}function L(e){return g.join(e,S,_t)}function Dt(e,t){try{let n=g.join(e,S);l.mkdirSync(n,{recursive:!0});let o=I(e),r=t.map(s=>JSON.stringify(s)).join(`
8
+ `)+`
9
+ `;l.appendFileSync(o,r,"utf8"),J(o,it);let{nominationTtlDays:i}=P(e);at(o,i*24*60*60*1e3);}catch{}}function Ft(e,t){try{let n=g.join(e,S);l.mkdirSync(n,{recursive:!0});let o=L(e),r=t.map(s=>JSON.stringify(s)).join(`
10
+ `)+`
11
+ `;l.appendFileSync(o,r,"utf8"),J(o,Et);let{debateTtlDays:i}=P(e);at(o,i*24*60*60*1e3);}catch{}}function $t(e,t){try{let n=g.join(e,S);l.mkdirSync(n,{recursive:!0});let o=g.join(n,wt);l.appendFileSync(o,JSON.stringify(t)+`
12
+ `,"utf8"),J(o,it);}catch(n){a$2.component("#promotion-decisions").warn("failed to record promotion decision",{agent:t.agent,error:n instanceof Error?n.message:String(n)});}}function J(e,t){try{let o=l.readFileSync(e,"utf8").trim().split(`
13
+ `).filter(r=>r.trim());if(o.length>t){let r=o.slice(-t);l.writeFileSync(e,r.join(`
14
+ `)+`
15
+ `,"utf8");}}catch{}}function P(e){let t={nominationTtlDays:Nt,debateTtlDays:vt};try{let n=g.join(e,".paradigm","config.yaml");if(!l.existsSync(n))return t;let o=a("js-yaml"),r=l.readFileSync(n,"utf8"),s=o.load(r)?.ambient;return s?{nominationTtlDays:typeof s["nomination-ttl-days"]=="number"?s["nomination-ttl-days"]:t.nominationTtlDays,debateTtlDays:typeof s["debate-ttl-days"]=="number"?s["debate-ttl-days"]:t.debateTtlDays}:t}catch{return t}}function at(e,t){try{if(!l.existsSync(e))return;let o=l.readFileSync(e,"utf8").trim().split(`
16
+ `).filter(s=>s.trim());if(o.length<=xt)return;let r=Date.now()-t,i=o.filter(s=>{try{let f=JSON.parse(s);return (f.timestamp?new Date(f.timestamp).getTime():Date.now())>=r}catch{return !0}});i.length<o.length&&l.writeFileSync(e,i.join(`
17
+ `)+`
18
+ `,"utf8");}catch{}}function A(e,t){let n=I(e);if(!l.existsSync(n))return [];try{let r=l.readFileSync(n,"utf8").trim().split(`
19
+ `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null);return t?.agent&&(r=r.filter(i=>i.agent===t.agent)),t?.urgency&&(r=r.filter(i=>i.urgency===t.urgency)),t?.surfaced!==void 0&&(r=r.filter(i=>i.surfaced===t.surfaced)),t?.pending_only&&(r=r.filter(i=>!i.engaged)),t?.since&&(r=r.filter(i=>i.timestamp>=t.since)),r.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),t?.limit&&(r=r.slice(0,t.limit)),r}catch{return []}}function Kt(e){let t=L(e);if(!l.existsSync(t))return [];try{return l.readFileSync(t,"utf8").trim().split(`
20
+ `).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return []}}function Qt(e,t,n,o){let r=I(e);if(!l.existsSync(r))return false;try{let s=l.readFileSync(r,"utf8").trim().split(`
21
+ `),f=!1,d=s.map(m=>{try{let c=JSON.parse(m);return c.id===t?(c.engaged=!0,c.response=n,o&&(c.reason=o),f=!0,JSON.stringify(c)):m}catch{return m}});if(f&&(l.writeFileSync(r,d.join(`
22
+ `)+`
23
+ `,"utf8"),n==="accepted"||n==="dismissed")){let m=JSON.parse(s.find(a=>{try{return JSON.parse(a).id===t}catch{return !1}}));i(e).find(a=>a.id===m.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&E(e,{type:"work-completed",source:"agent-action",agent:m.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return f}catch{return false}}function Zt(e,t,n,o){let r=L(e);if(!l.existsSync(r))return false;try{let s=l.readFileSync(r,"utf8").trim().split(`
24
+ `),f=!1,d=s.map(m=>{try{let c=JSON.parse(m);if(c.id===t){c.resolution={chosen:n,reason:o,resolved_by:"human",resolved_at:new Date().toISOString()},f=!0;let a=c.nominations.filter(u=>u!==n);for(let u of a){let p=A(e).find(b=>b.id===u);p&&E(e,{type:"work-completed",source:"agent-action",agent:p.agent,context:`Debate ${t} resolved \u2014 nomination ${u} not chosen`,data:{debate_id:t,chosen:n,reason:o}});}return JSON.stringify(c)}return m}catch{return m}});return f&&l.writeFileSync(r,d.join(`
25
+ `)+`
26
+ `,"utf8"),f}catch{return false}}function te(e){let t=g.join(e,S,".last-processed"),n="";try{l.existsSync(t)&&(n=l.readFileSync(t,"utf8").trim());}catch{}let o=g.join(e,S,"stream.jsonl");if(!l.existsSync(o))return {processed:0,nominations:[]};let r=[];try{r=l.readFileSync(o,"utf8").trim().split(`
27
+ `).filter(a=>a.trim()).map(a=>{try{return JSON.parse(a)}catch{return null}}).filter(a=>a!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(n){let c=r.findIndex(a=>a.id===n);c>=0&&(i=c+1);}let s=r.slice(i);if(s.length===0)return {processed:0,nominations:[]};let f=[],d=s.slice(0,50);for(let c of d){let{nominations:a}=st(e,c);f.push(...a);}let m=d[d.length-1];try{l.mkdirSync(g.join(e,S),{recursive:!0}),l.writeFileSync(t,m.id,"utf8");}catch{}return {processed:d.length,nominations:f}}function ee(e,t,n){let o=C(e);if(t.path&&!M(o,t.path))return {event:E(e,t),nominations:[],debates:[]};let r=E(e,t);if(n?.skipNominations)return {event:r,nominations:[],debates:[]};let{nominations:i,debates:s}=st(e,r);return i.length>0&&Rt(e,i),{event:r,nominations:i,debates:s}}function ne(e,t){let n=f$1(e,t);if(!n?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let o=n.attention.threshold??.6,{nominationTtlDays:r}=P(e),i=r*24*60*60*1e3,d=A(e,{agent:t}).filter(h=>h.engaged||Date.now()-new Date(h.timestamp).getTime()<i).filter(h=>h.engaged);if(d.length<5)return {adjusted:false,oldThreshold:o,newThreshold:o,reason:`Insufficient data (${d.length}/5 engaged nominations)`};let m=d.filter(h=>h.response==="accepted").length,c=d.filter(h=>h.response==="dismissed").length,a=m/d.length,u=c/d.length,p=o,b="No adjustment needed";if(u>.6?(p=Math.min(.95,o+.05),b=`High dismiss rate (${(u*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):a>.8&&(p=Math.max(.2,o-.05),b=`High accept rate (${(a*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),p===o)return {adjusted:false,oldThreshold:o,newThreshold:p,reason:b};n.attention.threshold=p;let w=g.join(e,".paradigm/agents",`${t}.agent`),N=l.existsSync(w)?"project":"global";return j$1(t,n,N,e),E(e,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${o.toFixed(2)} \u2192 ${p.toFixed(2)} (${b})`,data:{old_threshold:o,new_threshold:p,accept_rate:a,dismiss_rate:u}}),{adjusted:true,oldThreshold:o,newThreshold:p,reason:b}}function Ot(e,t){let{nominationTtlDays:n}=P(e),o=n*24*60*60*1e3,i=A(e,{agent:t}).filter(a=>a.engaged||Date.now()-new Date(a.timestamp).getTime()<o),s=i.filter(a=>a.response==="accepted").length,f=i.filter(a=>a.response==="dismissed").length,d=i.filter(a=>a.response==="deferred").length,m=i.filter(a=>!a.engaged).length,c=s+f+d;return {total:i.length,accepted:s,dismissed:f,deferred:d,pending:m,acceptRate:c>0?s/c:0}}function oe(e){let n=i(e).filter(a=>c$1(a.id,e)).map(a=>{let u=Ot(e,a.id),p=0;try{let b=g.join(T.homedir(),".paradigm","notebooks",a.id);l.existsSync(b)&&(p=l.readdirSync(b).filter(w=>w.endsWith(".yaml")).length);}catch{}return {id:a.id,acceptRate:u.acceptRate,threshold:a.attention?.threshold??.5,expertiseCount:(a.expertise||[]).length,notebookCount:p,transferableCount:(a.transferable||[]).length,totalNominations:u.total}}),o=n.length||1,r=n.reduce((a,u)=>a+u.acceptRate,0)/o,i$1=n.reduce((a,u)=>a+u.threshold,0)/o,s=n.reduce((a,u)=>a+u.expertiseCount,0),f=n.reduce((a,u)=>a+u.notebookCount,0),d=n.reduce((a,u)=>a+u.transferableCount,0),m=n.reduce((a,u)=>a+u.totalNominations,0),c;return m<10?c="cold-start":r<.5?c="accumulating":r<.7?c="calibrating":c="mature",{agents:n,aggregate:{avgAcceptRate:r,avgThreshold:i$1,totalExpertise:s,totalNotebooks:f,totalTransferable:d},healthStatus:c}}function Rt(e,t){if(t.length===0)return;let n=g.join(T.homedir(),".paradigm","score","outbox");if(l.existsSync(n))try{let o=g.join(n,`nom-${Date.now()}.json`),r={type:"nomination_forward",nominations:t.map(i=>({...i})),origin:Ct(e),timestamp:new Date().toISOString()};l.writeFileSync(o,JSON.stringify(r),"utf8");}catch{}}function Ct(e){try{let t=g.join(e,".paradigm","config.yaml");if(l.existsSync(t)){let o=l.readFileSync(t,"utf8").match(/project:\s*(.+)/);if(o)return o[1].trim()}}catch{}return g.basename(e)}function re(e,t){let n=b$3(t,{trigger:"pattern_discovered",limit:100}),o=b$3(t,{trigger:"human_feedback",limit:100}),r=[...n,...o],i=[];for(let s of r){if(s.promoted_to_notebook)continue;let f=(s.tags||[s.pattern?.id||"learned-pattern"]).map(a$1).filter(Boolean),d$1=s.confidence_after??0,m=d$1>=.8,c=.5,a=false;try{let u=d(t,f,e);c=u.value,a=u.found;}catch{}if($t(e,{ts:new Date().toISOString(),agent:t,concepts:f,before:c,after:d$1,delta:d$1-c,promoted:m,priorFound:a,gate:"absolute-0.8"}),!((s.confidence_after??0)<.8))try{let{entry:u}=g$1(t,{context:s.pattern?.applies_when||s.insight.slice(0,80),snippet:s.pattern?.correct_approach||s.insight,confidence:s.confidence_after??.5,concepts:f,tags:s.tags??[],provenance:{source:"lore",loreEntryId:s.id,createdBy:t}},"global",e);i.push({journalId:s.id,notebookId:u.id});try{let p=g.join(T.homedir(),".paradigm","agents",t,"journal");if(l.existsSync(p)){let b=l.readdirSync(p).filter(w=>w.endsWith(".yaml"));for(let w of b){let N=g.join(p,w),h=l.readFileSync(N,"utf8");if(h.includes(s.id)){let U=h.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${u.id}"`);if(U===h){let B=h.trimEnd().split(`
28
+ `);B.push(`promoted_to_notebook: "${u.id}"`),l.writeFileSync(N,B.join(`
29
+ `)+`
30
+ `,"utf8");}else l.writeFileSync(N,U,"utf8");break}}}}catch{}}catch(u){console.error("PROMOTE_THREW",u.message);}}return {promoted:i.length,entries:i}}function ie(e){let t=g.join(e,Mt),n={default_min_urgency:"low",enable_debates:true};if(!l.existsSync(t))return n;try{let o=a("js-yaml"),r=l.readFileSync(t,"utf8"),i=o.load(r);return {...n,...i}}catch{return n}}function se(e,t){let n={critical:0,high:1,medium:2,low:3},o=n[t.default_min_urgency||"low"]??3;return e.filter(r=>{let i=n[r.urgency]??3;if(t.preferences){let s=t.preferences.find(f=>f.agent===r.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(d=>r.urgency===d||r.type===d))return false;if(s.min_urgency){let f=n[s.min_urgency]??3;return i<=f}}}return i<=o})}var S,St,wt,_t,it,Et,Nt,vt,xt,Mt,It=b(()=>{tt();ot();z();f();j();b$1();S=".paradigm/events",St="nominations.jsonl",wt="promotion-decisions.jsonl",_t="debates.jsonl",it=500,Et=200,Nt=7,vt=14,xt=100;Mt=".paradigm/surfacing.yaml";});export{Lt as a,tt as b,C as c,Gt as d,ot as e,st as f,At as g,Dt as h,A as i,Kt as j,Qt as k,Zt as l,te as m,ee as n,ne as o,Ot as p,oe as q,Rt as r,re as s,ie as t,se as u,It as v};