@a-company/paradigm 7.1.0 → 7.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/dist/{accept-orchestration-WMGFGYDK.js → accept-orchestration-JA3A3TSU.js} +1 -1
  2. package/dist/add-CBDU23S2.js +12 -0
  3. package/dist/{aggregate-KZICPVT3.js → aggregate-H7SB2UYT.js} +1 -1
  4. package/dist/{ambient-HAXPDIWK.js → ambient-TFLZFV5Y.js} +1 -1
  5. package/dist/ambient-VCTUHHIG.js +2 -0
  6. package/dist/arch-loader-YVOS3QRY.js +2 -0
  7. package/dist/{beacon-52EWNZPK.js → beacon-WVN264OT.js} +1 -1
  8. package/dist/calibrate-SH6PRZFD.js +2 -0
  9. package/dist/calibration-aggregate-5IVXSBDP.js +2 -0
  10. package/dist/calibration-aggregate-DUEE3LL2.js +4 -0
  11. package/dist/captain-ILBN2IKJ.js +2 -0
  12. package/dist/captain-J4FZ5PRU.js +2 -0
  13. package/dist/{chunk-QDP4G53M.js → chunk-27EK3OQZ.js} +4 -4
  14. package/dist/{chunk-KP5VOYAH.js → chunk-3F4QP2Z5.js} +1 -1
  15. package/dist/{chunk-VPNJL4LS.js → chunk-5VR7FKS5.js} +1 -1
  16. package/dist/{chunk-S3UVQ5RV.js → chunk-6VZSOQ7Y.js} +1 -1
  17. package/dist/chunk-7BZPDOOQ.js +25 -0
  18. package/dist/{chunk-YQK3XU63.js → chunk-7HUPVOAY.js} +12 -12
  19. package/dist/chunk-A5EEY6NO.js +3 -0
  20. package/dist/{chunk-4GC35IFF.js → chunk-D6BSCELB.js} +1 -1
  21. package/dist/{chunk-G6DK3ND3.js → chunk-DH7QVZDI.js} +9 -0
  22. package/dist/chunk-FG3M6VVO.js +30 -0
  23. package/dist/chunk-FNYYQNJY.js +2 -0
  24. package/dist/{chunk-RDWWSQGH.js → chunk-IBKCMLOW.js} +14 -14
  25. package/dist/chunk-K6TLYNRQ.js +7 -0
  26. package/dist/{chunk-W4BW7GXA.js → chunk-KA6QEI3C.js} +1 -1
  27. package/dist/chunk-L3AOKDMU.js +93 -0
  28. package/dist/chunk-M7JHVVDW.js +6 -0
  29. package/dist/chunk-MBKTVQS2.js +2 -0
  30. package/dist/chunk-NFN5UUJB.js +2 -0
  31. package/dist/chunk-O4ADSTSY.js +504 -0
  32. package/dist/chunk-RPGSQQTS.js +2 -0
  33. package/dist/chunk-RQHZUPLO.js +4 -0
  34. package/dist/chunk-SD3KVW5Q.js +2 -0
  35. package/dist/chunk-VKVVIN6J.js +25 -0
  36. package/dist/chunk-VOPJ47QY.js +2 -0
  37. package/dist/chunk-VR2LLUYE.js +17 -0
  38. package/dist/chunk-WMTES556.js +2 -0
  39. package/dist/chunk-XBK244QR.js +6 -0
  40. package/dist/{chunk-MBSY57RN.js → chunk-Y76OIMDO.js} +1 -1
  41. package/dist/{chunk-EG22HDXI.js → chunk-YNFF7XHV.js} +12 -12
  42. package/dist/chunk-YYRP7FLC.js +2 -0
  43. package/dist/{compliance-4P3EE5OA.js → compliance-3M6COUCO.js} +3 -3
  44. package/dist/{constellation-RHZAEFV7.js → constellation-TIKNCZWR.js} +1 -1
  45. package/dist/{cost-24UZSS2P.js → cost-VTHZQKO4.js} +2 -2
  46. package/dist/{diff-VBVIUNL5.js → diff-NZSJW3V3.js} +1 -1
  47. package/dist/dist-6TDAY6TQ-HMSTBL57.js +39 -0
  48. package/dist/{dist-TNE4GFT7.js → dist-PW5YPGFF.js} +1 -1
  49. package/dist/{docs-NTP6UENF.js → docs-DWU3T2BV.js} +1 -1
  50. package/dist/github-GI3HX3N5.js +4 -0
  51. package/dist/{habits-BX2IRSUI.js → habits-UA7YT3CG.js} +3 -3
  52. package/dist/{hooks-AXBWYJ5V.js → hooks-XXJ7CSGJ.js} +1 -1
  53. package/dist/index.js +9 -9
  54. package/dist/{init-F4MSKZIW.js → init-QPMLEQWQ.js} +1 -1
  55. package/dist/{integrity-7TKX3DZ4.js → integrity-FRGF5BFS.js} +1 -1
  56. package/dist/lint-Y4P3MHBV.js +26 -0
  57. package/dist/list-5XRLWD7K.js +12 -0
  58. package/dist/mcp.js +1 -1
  59. package/dist/{migrate-5M4KUQ2L.js → migrate-LIVXILOO.js} +1 -1
  60. package/dist/nomination-engine-EFXDEPZN.js +2 -0
  61. package/dist/{orchestrate-MLUGQOEJ.js → orchestrate-C7SI4J7C.js} +1 -1
  62. package/dist/orchestration-4MJKBSGM.js +2 -0
  63. package/dist/orchestration-S2ESNKSA.js +2 -0
  64. package/dist/platform-server-IOWHNS7Q.js +25 -0
  65. package/dist/{probe-27ARJKRO.js → probe-G3TKOJYW.js} +1 -1
  66. package/dist/quiz-QKIKAVL7.js +10 -0
  67. package/dist/registry-NEW4OJ44.js +2 -0
  68. package/dist/{reindex-ZLDQBFUR.js → reindex-G2JLIGOQ.js} +1 -1
  69. package/dist/reindex-JR3PXYQE.js +2 -0
  70. package/dist/remember-KZYAY77S.js +14 -0
  71. package/dist/{review-BRO2UP4M.js → review-WHRNLW2W.js} +1 -1
  72. package/dist/{ripple-KCVDS3WE.js → ripple-B6U7263T.js} +1 -1
  73. package/dist/{sentinel-EFPEX246.js → sentinel-RIEQWALQ.js} +1 -1
  74. package/dist/{sentinel-bridge-UR2MKARY.js → sentinel-bridge-D4LFDFCH.js} +1 -1
  75. package/dist/{serve-2PKJP65E.js → serve-6RNZYK2I.js} +2 -2
  76. package/dist/serve-PWAFVYYC.js +9 -0
  77. package/dist/{server-4D77LCST.js → server-K7G3IHR3.js} +1 -1
  78. package/dist/{setup-5V2AGLQ6.js → setup-L5OP24US.js} +3 -3
  79. package/dist/{shift-PM4GI736.js → shift-HGXZ5THV.js} +3 -3
  80. package/dist/{show-N5LGB5B2.js → show-VXNGIJE4.js} +3 -3
  81. package/dist/{snapshot-YMX5QRBM.js → snapshot-MT5L6XE4.js} +1 -1
  82. package/dist/status-45KIG32R.js +6 -0
  83. package/dist/{status-3GJXI4IK.js → status-4QGKLOP6.js} +4 -4
  84. package/dist/{summary-RPU2BS3Q.js → summary-6QNVQZJV.js} +1 -1
  85. package/dist/symphony-KQJ6HIXB.js +53 -0
  86. package/dist/symphony-VDNDFK7H.js +2 -0
  87. package/dist/symphony-relay-ASMKPDEE.js +3 -0
  88. package/dist/sync-layer-C2PF273N.js +2 -0
  89. package/dist/task-PRLQ4VPK.js +3 -0
  90. package/dist/task-loader-EIXPKHA3.js +2 -0
  91. package/dist/task-loader-LFEE6OU7.js +2 -0
  92. package/dist/task-settlement-A2T6EACG.js +3 -0
  93. package/dist/task-settlement-ZXOY4YGX.js +3 -0
  94. package/dist/team-KP4HMUB5.js +2 -0
  95. package/dist/thread-2A7QKU72.js +41 -0
  96. package/dist/tools-NOMEIBS7.js +2 -0
  97. package/dist/tools-YW3Q27UI.js +142 -0
  98. package/dist/validate-OZTX3FYX.js +13 -0
  99. package/dist/validate-RIMSY3RP.js +9 -0
  100. package/dist/{workspace-6POCBPDY.js → workspace-4D4TQ637.js} +1 -1
  101. package/package.json +2 -6
  102. package/platform-ui/dist/assets/{AmbientSection-CwatqcBD.js → AmbientSection-xoxr3DQg.js} +1 -1
  103. package/platform-ui/dist/assets/{DocsSection-BZ2SFJBZ.js → DocsSection-Us2qksna.js} +1 -1
  104. package/platform-ui/dist/assets/{GitSection-MNNYU1tO.js → GitSection-DIHZyadf.js} +1 -1
  105. package/platform-ui/dist/assets/{GraphSection-COYjb4Pt.js → GraphSection-9TO0L1IO.js} +1 -1
  106. package/platform-ui/dist/assets/{LoreSection-B0hUbfsJ.js → LoreSection-DVDit8Aw.js} +1 -1
  107. package/platform-ui/dist/assets/{SentinelSection-BCxW1DCp.js → SentinelSection-a5_VNYcx.js} +1 -1
  108. package/platform-ui/dist/assets/{SymphonySection-BsucZRqy.js → SymphonySection-cRHEoJ9t.js} +1 -1
  109. package/platform-ui/dist/assets/TasksSection-44_gDO3L.css +1 -0
  110. package/platform-ui/dist/assets/TasksSection-h8x3qRIj.js +1 -0
  111. package/platform-ui/dist/assets/{TeamSection-C0QNTudW.js → TeamSection-mFoDyNic.js} +1 -1
  112. package/platform-ui/dist/assets/{UniversitySection-DN1-g9pw.js → UniversitySection-D99YRjmC.js} +1 -1
  113. package/platform-ui/dist/assets/{index-DwUT8pju.js → index-D_wB2S_2.js} +11 -11
  114. package/platform-ui/dist/index.html +1 -1
  115. package/dist/add-V6XR7DU5.js +0 -12
  116. package/dist/agent-loader-Z753DQWH.js +0 -2
  117. package/dist/ambient-QB7V4TBR.js +0 -6
  118. package/dist/calibrate-PHVP7RPH.js +0 -4
  119. package/dist/captain-3COP6YTD.js +0 -2
  120. package/dist/chunk-4CGPLLWQ.js +0 -30
  121. package/dist/chunk-7SWEOPWF.js +0 -2
  122. package/dist/chunk-CHSU6LTR.js +0 -2
  123. package/dist/chunk-EKNLG73M.js +0 -6
  124. package/dist/chunk-H55W26AR.js +0 -3
  125. package/dist/chunk-HE2NA5QF.js +0 -8
  126. package/dist/chunk-JIXHEBGK.js +0 -7
  127. package/dist/chunk-MBPLJKE5.js +0 -3
  128. package/dist/chunk-OIYJUU6T.js +0 -25
  129. package/dist/chunk-QO7YPQXC.js +0 -2
  130. package/dist/chunk-XMAV5AG6.js +0 -2
  131. package/dist/chunk-XPPFILCM.js +0 -2
  132. package/dist/chunk-YCDOA5IQ.js +0 -18
  133. package/dist/dist-GQ42YS5N-4HIJZVBB.js +0 -39
  134. package/dist/lint-IGKE6UPS.js +0 -26
  135. package/dist/list-NC3QGT75.js +0 -12
  136. package/dist/lore-loader-HAZ5FRLP.js +0 -2
  137. package/dist/lore-server-FC2GMDLT.js +0 -14
  138. package/dist/nomination-engine-ORHH4L2W.js +0 -2
  139. package/dist/orchestration-O2OVPTIZ.js +0 -2
  140. package/dist/platform-server-Y6TLEXR2.js +0 -25
  141. package/dist/quiz-TNV6APBM.js +0 -10
  142. package/dist/remember-MJRNTXYS.js +0 -14
  143. package/dist/serve-L52ZUTU6.js +0 -10
  144. package/dist/serve-XZ6GBUS3.js +0 -8
  145. package/dist/session-work-log-FF7CKMWP.js +0 -2
  146. package/dist/status-ENAI35NL.js +0 -6
  147. package/dist/symphony-CFAYJGLF.js +0 -2
  148. package/dist/symphony-L56O5ZG3.js +0 -53
  149. package/dist/symphony-relay-Y2UR3YNR.js +0 -3
  150. package/dist/task-loader-H7HQAYGL.js +0 -2
  151. package/dist/task-loader-YZME4RKE.js +0 -2
  152. package/dist/task-settlement-HINBVZBE.js +0 -3
  153. package/dist/task-settlement-XC6E6JNT.js +0 -3
  154. package/dist/team-25LK6CWM.js +0 -2
  155. package/dist/thread-HFXK65D4.js +0 -41
  156. package/dist/tools-GAU5WOEI.js +0 -2
  157. package/dist/validate-IQG7DBFC.js +0 -9
  158. package/dist/validate-LSCDOLBO.js +0 -13
  159. package/dist/work-log-loader-CRVTOMVB.js +0 -2
  160. package/graph-ui/dist/assets/index-BlgXTl53.css +0 -1
  161. package/graph-ui/dist/assets/index-Bq5nXK8p.js +0 -63
  162. package/graph-ui/dist/index.html +0 -13
  163. package/lore-ui/dist/assets/index-C3EixkjW.css +0 -1
  164. package/lore-ui/dist/assets/index-DKhNxgtW.js +0 -56
  165. package/lore-ui/dist/index.html +0 -13
  166. package/platform-ui/dist/assets/CanvasSection-dFAthehN.js +0 -9
  167. package/platform-ui/dist/assets/CanvasSection-flMXU19z.css +0 -1
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import {a,O,l as l$1,D,G,L,F,K,J,I as I$1,N}from'./chunk-3F4QP2Z5.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 I from'fs';import*as E from'path';import*as q from'js-yaml';import {execSync}from'child_process';import*as Et from'os';b();b();var Ht=".paradigm/navigator.yaml";async function st(n){let e=E.join(n,Ht);if(!I.existsSync(e))return {config:null,configPath:null};try{let o=I.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 Mt(n,e.target||"");case "explore":return Bt(n,e.target||"");case "context":return Jt(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Mt(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=Gt(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 Jt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase(),s=qt(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 Gt(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 qt(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 Ut(n){let e=E.resolve(n),o=I.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=E.resolve(n),t=E.resolve(o,e);if(!I.existsSync(t))return a$1.component("#workspace-loader").warn("Workspace file not found",{workspacePath:t}),null;let r;try{r=Ut(t);}catch(c){return a$1.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let s=E.dirname(t),i="";for(let c of r.members){let l=E.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=E.resolve(s,c.path),p=E.join(l,".paradigm","scan-index.json");if(!I.existsSync(p)){a$1.component("#workspace-loader").warn("No scan-index.json for workspace member",{member:c.name,scanIndexPath:p});continue}try{let f=JSON.parse(I.readFileSync(p,"utf8")),k=Kt(f);c.exports&&c.exports.length>0&&(k=zt(k,c.exports));let w=null,x=E.join(l,"portal.yaml");if(I.existsSync(x))try{let y=I.readFileSync(x,"utf8"),j=q.load(y);j&&(w=j);}catch{}a.set(c.name,{index:k,gateConfig:w});}catch(f){a$1.component("#workspace-loader").warn("Could not load index for workspace member",{member:c.name,error:f.message});}}return {config:r,workspacePath:t,currentMember:i,siblingIndices:a}}function zt(n,e){let t=q$1(n).filter(r=>{let s=r.symbol;return e.some(i=>Vt(i,s))});return Qt(t)}function Vt(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||[],p=c.description||"",f=l.some(w=>w===t||w===e||w.endsWith(`/${t}`)),k=p.includes(t);(f||k)&&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 E.resolve(n).replace(/\/+$/,"")}function Kt(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 Qt(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 Yt={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 [Yt]}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:Xt(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 p=xe(o.workspace,t.target);p.length>0&&(l.workspaceResults=p.slice(0,5).map(f=>({symbol:f.symbol,type:f.type,description:f.description,project:f.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(t.intent==="context"&&t.task){let p=xe(o.workspace,t.task);p.length>0&&(l.workspaceContext=p.slice(0,5).map(f=>({symbol:f.symbol,type:f.type,description:f.description,project:f.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=E.join(o.rootDir,".paradigm",".nav-called");I.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a$1}}function Xt(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 p=l.match(/^(.+?):(\d+):(.*)$/);if(p){let[,f,k,w]=p,x=E.relative(n,f),y="unknown";x.includes(".purpose")||x.includes("portal.yaml")?y="purpose":w.includes("//")||w.includes("#")||w.includes("*")?y="comment":y="code",r.push({filePath:x,line:parseInt(k,10),content:w.trim().slice(0,200),context:y});}}return r}b();var en=30*1e3,ut=new Map;async function gt(n){let e=E.resolve(n),o=ut.get(e);if(o&&Date.now()-o.loadedAt<en)return o.index;let t=await tn(e);return t&&ut.set(e,{index:t,loadedAt:Date.now()}),t}async function tn(n){let e=E.join(n,".paradigm","flow-index.json");if(!I.existsSync(e))return null;try{let o=I.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 nn(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(p=>p.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=nn(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 u=on(o$1.rootDir,t);return O(u.length,n$1),{handled:true,text:u}}let c=Math.min(Math.max(r||3,1),5),l$2=n(o$1.index,t),p=new Set([t]),f=new Map;function k$1(u,P){if(P>=c)return;let v=[];for(let b of u){if(p.has(b))continue;p.add(b);let D=n(o$1.index,b);for(let T of D)p.has(T.symbol)||v.push(T.symbol);}v.length>0&&(f.set(P+1,v),k$1(v,P+1));}k$1(l$2.map(u=>u.symbol),1);let w=new Set;for(let[,u]of f)for(let P of u)P!==t&&!l$2.find(v=>v.symbol===P)&&w.add(P);let x=o(o$1.index,t),y=l$2.length+w.size,j="low";y>10?j="high":y>3&&(j="medium");let N=await gt(o$1.rootDir),F=null;if(N){let u=yt(N,t);u.totalFlows>0&&(u.impactLevel==="high"&&j==="low"?j="medium":u.impactLevel==="high"&&(j="high"),F={totalFlows:u.totalFlows,affectedFlows:u.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:u.validationCommands.length>0?`Run: ${u.validationCommands[0]}`:void 0});}let $=new Set([t,...l$2.map(u=>u.symbol),...w]),A=[];try{let u=l(o$1.index,"gate");for(let P of u)$.has(P.symbol)&&A.push({gate:P.symbol,description:P.description});for(let P of l$2)P.type==="gate"&&!A.find(v=>v.gate===P.symbol)&&A.push({gate:P.symbol,description:P.description});}catch{}let d={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:j,analysis:{directlyAffected:l$2.map(u=>({symbol:u.symbol,type:u.type,description:u.description})),indirectlyAffected:Array.from(w),indirectByLevel:Object.fromEntries(f),dependsOn:x.map(u=>({symbol:u.symbol,type:u.type}))},summary:{directCount:l$2.length,indirectCount:w.size,totalAffected:y,dependsOnCount:x.length,levelsAnalyzed:c},recommendation:sn(j)};F&&(d.affectedFlows=F),A.length>0&&(d.affectedGates=A),d.suggestedReviewScope=rn(j,l$2.length,w.size,A.length,F?.totalFlows??0);try{let u=await l$1(o$1.rootDir,t);u.length>0&&(d.personas_affected=u,u.length>2&&j==="low"&&(d.impact="medium"));}catch{}try{let u=D(o$1.rootDir,t);u.length>0&&(d.university_content_affected=u.map(P=>({id:P.id,title:P.title,type:P.type,stale:P.stale})));}catch{}if(s&&o$1.workspace){let u=ct(o$1.workspace,t);if(u.length>0){d.workspaceImpact={siblings:u.map(v=>({project:v.project,references:v.references.map(b=>({symbol:b.symbol,type:b.type,description:b.description}))}))};let P=u.reduce((v,b)=>v+b.references.length,0);P>0&&j==="low"&&(d.impact="medium"),P>5&&(d.impact="high");}}let _=i==="concise"?{symbol:d.symbol,impact:d.impact,summary:d.summary}:d,O$1=JSON.stringify(_,null,2);return O(O$1.length,n$1),{handled:true,text:O$1}}function on(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 sn(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 rn(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 an=30*1e3,ve=new Map,bt=".paradigm/wisdom";async function wt(n){let e=E.resolve(n),o=ve.get(e);if(o&&Date.now()-o.loadedAt<an)return o.context;let t=await cn(e);return ve.set(e,{context:t,loadedAt:Date.now()}),t}async function cn(n){let e$1=E.join(n,bt),o=I.existsSync(e$1),[t,r,s,i]=o?await Promise.all([ln(e$1),dn(e$1),pn(e$1),fn(e$1)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e(),l=f$1();}catch{}let p=new Set(r.map(y=>y.id)),f=r.map(y=>({...y,scope:"project"}));for(let y of a)p.has(y.id)||f.push({...y,scope:"global"});let k=new Set(i.map(y=>y.id)),w=i.map(y=>({...y,scope:"project"}));for(let y of c)k.has(y.id)||w.push({...y,scope:"global"});let x=t;if(l&&!t)x=l;else if(l&&t){let y={...t.by_symbol};if(l.by_symbol)for(let[j,N]of Object.entries(l.by_symbol))y[j]||(y[j]=N);x={...t,by_symbol:y,global:{...l.global,...t.global}};}return {preferences:x,antipatterns:f,decisions:w,expertise:s}}function V(n){let e=E.resolve(n);ve.delete(e);}async function ln(n){let e=E.join(n,"preferences.yaml");if(!I.existsSync(e))return null;try{let o=I.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 dn(n){let e=E.join(n,"antipatterns.yaml");if(!I.existsSync(e))return [];try{let o=I.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 pn(n){let e=E.join(n,"expertise.yaml");if(!I.existsSync(e))return null;try{let o=I.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 fn(n){let e=E.join(n,"decisions");if(!I.existsSync(e))return [];let o=[];try{let t=I.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=E.join(e,s);try{let a=I.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=>mn(n,o))}function mn(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=E.join(n,bt),t=E.join(o,"antipatterns.yaml");I.existsSync(o)||I.mkdirSync(o,{recursive:true});let r={version:"1.0",antipatterns:[]};if(I.existsSync(t))try{let s=I.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()}),I.writeFileSync(t,q.dump(r,{lineWidth:-1})),V(n);}b();var kt=".paradigm/history";async function _t(n){let e=E.join(n,kt);if(!I.existsSync(e))return {index:null,validation:null};let[o,t]=await Promise.all([un(e),gn(e)]);return {index:o,validation:t}}async function un(n){let e=E.join(n,"index.yaml");if(!I.existsSync(e))return null;try{let o=I.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 gn(n){let e=E.join(n,"validation.yaml");if(!I.existsSync(e))return null;try{let o=I.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=>yn(n,o))}function yn(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(p=>p!==i&&!e.includes(p));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 hn(n,e){let o=E.join(n,kt),t=E.join(o,"log.jsonl");I.existsSync(o)||I.mkdirSync(o,{recursive:true});let r=bn(t),s=new Date().toISOString(),i={id:r,ts:s,...e},a=JSON.stringify(i)+`
4
+ `;return I.appendFileSync(t,a),r}async function ko(n,e,o,t){return hn(n,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:o,tests:t})}function bn(n){let e=1;return I.existsSync(n)&&(e=I.readFileSync(n,"utf8").split(`
5
+ `).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}async function Ao(n){let e=E.resolve(n),o=await i(e),t=j$1(o),r=null,s=E.join(e,"portal.yaml");if(I.existsSync(s))try{r=await g(s);}catch(p){let f=p?.name??"Error";a$1.component("#index-loader").warn("Could not parse portal.yaml",{errorClass:f});}let i$1=E.basename(e),a=E.join(e,".premise");if(I.existsSync(a))try{let f=I.readFileSync(a,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);f&&(i$1=f[1].trim());}catch{}let c=null,l=E.join(e,".paradigm","config.yaml");if(I.existsSync(l))try{let p=I.readFileSync(l,"utf8"),f=q.load(p);f&&typeof f=="object"&&(f.version||a$1.component("#index-loader").warn('config.yaml missing "version" field'),f.project||a$1.component("#index-loader").warn('config.yaml missing "project" field')),f&&typeof f.workspace=="string"&&(c=at(e,f.workspace));}catch(p){a$1.component("#index-loader").warn("Failed to load workspace config",{error:p.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(p=>({symbol:p.symbol,preferences:p.preferences,antipatterns:p.antipatterns.map(f=>({id:f.id,description:f.description,reason:f.reason,alternative:f.alternative,scope:f.scope||"project"})),decisions:p.decisions.map(f=>({id:f.id,title:f.title,status:f.status,decision:f.decision,scope:f.scope||"project"})),experts:p.experts.map(f=>f.name)}))};r&&s.preferences?.global&&(a.global_preferences=s.preferences.global);let c=i.reduce((p,f)=>p+f.antipatterns.length,0),l=i.reduce((p,f)=>p+f.decisions.length,0);a.summary={symbols_with_preferences:i.filter(p=>p.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:i.some(p=>p.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let p={},f=[];for(let k of t){let w=await a$3(o.rootDir,{symbol:k,hasAssessment:!0,limit:100});if(w.length===0)continue;let x={correct:0,partial:0,incorrect:0},y=0,j=0;for(let F of w){let $=F.assessment.verdict;x[$]++,F.confidence!=null&&(y+=F.confidence,j++);}p[k]={total:w.length,...x,avgConfidence:j>0?Math.round(y/j*1e3)/1e3:null};let N=(x.correct+x.partial*.5)/w.length;N<.6&&w.length>=3&&f.push(`Low historical accuracy for ${k}: ${Math.round(N*100)}% across ${w.length} entries. Proceed with extra caution.`);}Object.keys(p).length>0&&(a.calibration=p),f.length>0&&(a.calibration_warnings=f);}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:p,rationale:f,consequences:k,scope:w="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 w==="global"?g$1(x):await vt(o.rootDir,x),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,scope:w,message:`Antipattern recorded to ${w} scope`})}}if(t==="decision"){if(!l||!i||!f||!k)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"})),w==="global"){let j={id:r,title:l,status:p||"proposed",date:new Date().toISOString().split("T")[0],symbols:s,context:a||"",decision:i,rationale:f,consequences:k};return h(j),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:f.factors,conclusion:f.conclusion},participants:[{id:"wisdom-record",role:"agent",stance:"proposed"}],symbols_affected:s,status:p==="accepted"?"active":p==="proposed"?"proposed":"active",context:a||void 0,consequences:k,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),y=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})`,...y?{companion_lore_id:y}:{}})}}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=E.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$1(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(wn)}))},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 wn(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=E.join(n,".paradigm","sentinel","sentinel.db");ee=new f(e),await ee.ensureReady(),ke=true;}return ee}async function Sn(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 Sn(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=Et.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:p,lines_removed:f,commit:k,duration_minutes:w,decisions:x,errors_encountered:y,learnings:j,verification:N$1,tags:F,meta:$,body:A,linked_lore:d,linked_tasks:_,linked_commits:O,confidence:u}=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(),h=await Ce(o.rootDir,{dateFrom:S});if(h.total>0){let m=(await It(o.rootDir,{dateFrom:S})).filter(C=>C.rate<60).map(C=>C.category);P={rate:h.rate,followed:h.followed,skipped:h.skipped,partial:h.partial,weakAreas:m.length>0?m:void 0};}}catch{}let v={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:w,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:p,lines_removed:f,commit:k,decisions:x,errors_encountered:y,learnings:j,verification:N$1,tags:F,meta:$||void 0,habit_compliance:P,body:A,linked_lore:d,linked_tasks:_,linked_commits:O,confidence:u!=null&&u>=0&&u<=1?u:void 0},b=await d$2(o.rootDir,v);j$2().setLastLoreEntryId(b);try{let S=process.env.PARADIGM_AGENT_ID;if(S&&i&&i.length>0){let{updateExpertiseFromLore:h}=await import('./agent-loader-W3RQJVW7.js');h(o.rootDir,S,{symbols_touched:i,confidence:u!=null&&u>=0&&u<=1?u:void 0});}}catch{}let D=null;try{c&&c.length>=2&&(D=N(o.rootDir,c,l||[]));}catch{}let T;if(e.stream){let S=e.stream,h=S==="auto"?vn(e):S;try{if(h==="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||b}),T="work-log";}else if(h==="journal"&&v.learnings?.length){let{recordJournalEntry:g}=await import('./journal-loader-CNNA4EAU.js');for(let m of v.learnings)g(v.agent?.model||"unknown",{trigger:"self_reflection",insight:m,project:o.projectName||"unknown",transferable:!1,linked_work_log:v.id||b});T="journal";}else if(h==="decision"&&v.decisions?.length){let{recordDecision:g}=await import('./decision-loader-HELL2AMX.js');for(let m of v.decisions)g(o.rootDir,{title:m.decision.slice(0,100),decision:m.decision,rationale:m.rationale,participants:[{id:`agent/${v.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:v.symbols_touched,status:"active",linked_lore:v.id||b});T="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:b,type:t,title:r,message:"Lore entry recorded successfully",...T?{stream:T}:{},...D?{protocol_suggestion:D}:{}})}}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 p of l.symbols_touched)i[p]=(i[p]||0)+1;let a=Object.entries(i).sort(([,l],[,p])=>p-l).slice(0,10).map(([l,p])=>({symbol:l,count:p})),c$1={};for(let l of s){let p=l.author;c$1[p]||(c$1[p]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c$1[p].count++,l.agent&&(c$1[p].hasAgent=true),l.timestamp>c$1[p].lastActive&&(c$1[p].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,p])=>({id:l,hasAgent:p.hasAgent,entries:p.count,lastActive:p.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 k=process.env.PARADIGM_AGENT_ID;if(k&&c&&i.symbols_touched?.length){let{updateExpertiseFromAssessment:w}=await import('./agent-loader-W3RQJVW7.js');w(o.rootDir,k,{symbols_touched:i.symbols_touched,verdict:r});}}catch{}let l=r==="correct"?1:r==="partial"?.5:0,p=i.confidence!=null?l-i.confidence:null,f=p!=null?p>.1?"Under-confident (actual outcome better than predicted)":p<-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:p,deltaDescription:f,message:c?`Assessment recorded: ${r}${p!=null?` (delta: ${p>0?"+":""}${p.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(A=>A.confidence!=null),i=r.length,a=s.length,c={correct:0,partial:0,incorrect:0},l=0,p=0,f=0;for(let A of r){let d=A.assessment.verdict;c[d]++;let _=d==="correct"?1:d==="partial"?.5:0;l+=_,A.confidence!=null&&(p+=A.confidence,f+=Math.abs(_-A.confidence));}let k=i>0?l/i:0,w=a>0?p/a:null,x=a>0?l/i-p/a:null,y=a>0?1-f/a:null,j=e.groupBy,N;if(j&&i>0){let A=new Map;for(let d of r){let _=[];j==="symbol"?_=d.symbols_touched||[]:j==="tag"?_=d.tags||[]:j==="type"&&(_=[d.type||"agent-session"]);for(let O of _)A.has(O)||A.set(O,[]),A.get(O).push(d);}N=Array.from(A.entries()).map(([d,_])=>{let O=_.filter(D=>D.confidence!=null),u={correct:0,partial:0,incorrect:0},P=0,v=0,b=0;for(let D of _){let T=D.assessment.verdict;u[T]++;let S=T==="correct"?1:T==="partial"?.5:0;P+=S,D.confidence!=null&&(v+=D.confidence,b+=Math.abs(S-D.confidence));}return {key:d,total:_.length,accuracyRate:P/_.length,avgConfidence:O.length>0?v/O.length:null,calibrationScore:O.length>0?1-b/O.length:null,verdictBreakdown:u}}).sort((d,_)=>_.total-d.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($),y!=null&&(y>=.9?F.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):y>=.7?F.push("Good calibration \u2014 some room for improvement in confidence estimates."):y>=.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(k*1e3)/1e3,avgConfidence:w!=null?Math.round(w*1e3)/1e3:null,avgDelta:x!=null?Math.round(x*1e3)/1e3:null,calibrationScore:y!=null?Math.round(y*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 vn(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"?kn(e,o):n==="paradigm_captain_debrief"?_n(e,o):n==="paradigm_captain_board"?Dn(e,o):{handled:false,text:""}}async function kn(n,e){let o=n.taskDescription,t=n.symbols||[],r=n.depth||"standard",s=E.join(e.rootDir,".paradigm"),i=E.join(s,".cid-session"),a=E.join(s,".cid-briefed");try{I.existsSync(a)&&I.unlinkSync(a);let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r};I.mkdirSync(s,{recursive:!0}),I.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let c=Tn(o),l=[],p=new Set;for(let S of t)if(!p.has(S)){p.add(S);let h=Wt(S);l.push({id:S,type:h,description:"Provided as anchor symbol"});}let f=[];try{for(let S of c.slice(0,3)){let g=m(e.index,S).slice(0,5);for(let m of g)if(!p.has(m.symbol)){p.add(m.symbol);let C=Ln(m.type);l.push({id:m.symbol,type:C,description:m.description||"",file:m.file}),f.push(m.symbol);}}}catch{}let k={directories:[],files:[]};try{let S=await pt("paradigm_navigate",{intent:"context",task:o,response_format:"concise"},e);if(S.handled){let h=JSON.parse(S.text);if(h.files)for(let g of h.files){let m=typeof g=="string"?g:g.path||g.file||"";m&&k.files.push(m);}if(h.directories)for(let g of h.directories){let m=typeof g=="string"?g:g.path||g.directory||"";m&&k.directories.push(m);}if(h.symbols)for(let g of h.symbols){let m=typeof g=="string"?g:g.id;m&&!p.has(m)&&(p.add(m),l.push({id:m,type:Wt(m),description:typeof g=="object"&&g.description||""}));}}}catch{}let w=new Set(k.directories);for(let S of k.files){let h=E.dirname(S);h&&h!=="."&&w.add(h);}let x=l.slice(0,r==="deep"?5:3),y={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(r!=="quick"&&x.length>0)for(let S of x)try{let h=await le("paradigm_ripple",{symbol:S.id,depth:2,response_format:"concise"},e);if(h.handled){let g=JSON.parse(h.text);if(g.analysis){for(let m of g.analysis.directlyAffected||[]){let C=m.symbol||m;C&&!y.affectedSymbols.includes(C)&&y.affectedSymbols.push(C);}for(let m of g.analysis.indirectlyAffected||[])m&&!y.affectedSymbols.includes(m)&&y.affectedSymbols.push(m);}if(g.affectedFlows?.affectedFlows)for(let m of g.affectedFlows.affectedFlows){let C=m.flowId||m;C&&!y.affectedFlows.includes(C)&&y.affectedFlows.push(C);}if(g.affectedGates)for(let m of g.affectedGates){let C=m.gate||m;C&&!y.affectedGates.includes(C)&&y.affectedGates.push(C);}g.impact==="high"&&(y.fragileSymbols.includes(S.id)||y.fragileSymbols.push(S.id));}}catch{}let j=[],N=Wn(o);if(N.length>0)try{let{handleGatesForRoute:S}=await import('./tools-NOMEIBS7.js').catch(()=>({handleGatesForRoute:null})),h=E.join(e.rootDir,"portal.yaml");if(I.existsSync(h)){let g=I.readFileSync(h,"utf8");for(let m of N){let C=g.includes(m);j.push({route:m,gate:"^authenticated",declared:C});}}else for(let g of N)j.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),h=await Dt("paradigm_wisdom_context",{symbols:S,include_global:!0},e);if(h.handled){let g=JSON.parse(h.text);if(g.antipatterns)for(let m of g.antipatterns.slice(0,3)){let C=m.pattern||m.description||m.text||String(m);C&&!F.includes(C)&&F.push(C);}if(g.wisdom?.antipatterns)for(let m of g.wisdom.antipatterns.slice(0,3)){let C=m.pattern||m.description||String(m);C&&!F.includes(C)&&F.push(C);}}}catch{}let $={matched:false};try{let S=await Rt("paradigm_protocol_search",{task:o,limit:1},e);if(S.handled){let h=JSON.parse(S.text),g=h.matches||h.protocols||h.results||[];if(g.length>0){let m=g[0];$={matched:!0,id:m.id,name:m.name||m.title,steps:(m.steps||[]).slice(0,5).map(C=>typeof C=="string"?C:C.description||String(C))};}}}catch{}let A=[];if(r!=="quick")try{let S=l[0]?.id,h={limit:r==="deep"?5:3};S&&(h.symbol=S);let g=await je("paradigm_lore_search",h,e);if(g.handled){let C=JSON.parse(g.text).entries||[];for(let B of C.slice(0,3))A.push({id:B.id,summary:(B.summary||B.title||"").slice(0,100),relevance:S?`Related to ${S}`:"Recent project history"});}}catch{}let d=Array.from(w),_=0;for(let S of d){let h=E.join(e.rootDir,S,".purpose");if(I.existsSync(h))try{I.readFileSync(h,"utf8").trim().length>50&&_++;}catch{}}let O$1=d.length>0?_/d.length:.5,u=Hn(O$1),P=Mn(O$1,u,d.length),v=y.affectedSymbols.length+k.files.length,b=v>20?"large":v>8?"medium":v>2?"small":"tiny",D={territory:{directories:d.slice(0,10),files:k.files.slice(0,10),estimatedScope:b},symbols:l.slice(0,10),blastRadius:y,gates:j,protocol:$,warnings:F,coverage:{score:O$1,label:u,note:P},loreRefs:A,archMap:b$2(e.rootDir),renderedBrief:""};D.renderedBrief=Bn(D);try{let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r,coverageScore:O$1};I.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let T=JSON.stringify(D,null,2);return O(T.length,"paradigm_captain_brief"),{handled:true,text:T}}async function _n(n,e){let o=n.orchestrationId,t=n.sessionSummary,r=n.touchedFiles||[],s=n.newSymbols||[],i=n.notes,a=E.join(e.rootDir,".paradigm"),c=E.join(a,".cid-briefed"),l=E.join(a,".pending-review"),p=new Set;for(let b of r){let D=E.dirname(b);D&&D!=="."&&p.add(D);}let f=0,k=p.size;for(let b of p){let D=E.join(e.rootDir,b,".purpose");if(I.existsSync(D))try{I.readFileSync(D,"utf8").trim().length>50&&f++;}catch{}}let w=k>0?f/k:1,x=[],y=[];for(let b of p){let D=E.join(e.rootDir,b,".purpose"),T=E.join(e.rootDir,b),S=false;if(I.existsSync(D))try{S=I.readFileSync(D,"utf8").trim().length>50;}catch{}if(S){if(r.some(g=>E.dirname(g)===b&&s.length>0)){y.push(b);try{let g=JSON.stringify({path:b,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${o}: ${s.join(", ")}`,timestamp:new Date().toISOString()});I.appendFileSync(l,g+`
6
+ `,"utf8");}catch{}}}else try{if(!I.existsSync(T))continue;let h=E.basename(b),g=Jn(h,b,r);I.writeFileSync(D,g,"utf8"),x.push(b),y.push(b);try{let m=JSON.stringify({path:b,reason:"captain-debrief",priority:"high",context:`Touched during orchestration ${o}. Files: ${r.filter(C=>E.dirname(C)===b).join(", ")}`,timestamp:new Date().toISOString()});I.appendFileSync(l,m+`
7
+ `,"utf8");}catch{}}catch{}}let j=0;for(let b of p){let D=E.join(e.rootDir,b,".purpose");if(I.existsSync(D))try{I.readFileSync(D,"utf8").trim().length>50&&j++;}catch{}}let N=k>0?j/k:1,F="";try{let b=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:w,after:N},coverageAdded:x,...i?{notes:i}:{}}},e);if(b.handled){let D=JSON.parse(b.text);F=D.id||D.entry?.id||"";}}catch{}let $={ranThisSession:false,selfHealed:false,blockProposed:false};if($.ranThisSession=jn(a),!$.ranThisSession)try{let{runPostflightLearning:b}=await import('./ambient-OW5M5LVN.js');await b(e.rootDir,{claimant:"navigation"}),$.selfHealed=!0,a$1.flow("$captain-board").info("Cid self-healed postflight (no prior liveness record)",{orchestrationId:o});}catch(b){$.selfHealError=b instanceof Error?b.message:String(b),a$1.flow("$captain-board").warn("Cid postflight self-heal threw \u2014 proposing advise block",{orchestrationId:o,error:$.selfHealError});try{let{handleProposeBlockTool:D}=await import('./propose-block-ZEMEWJQF.js');await D("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 A=false;try{let b={timestamp:new Date().toISOString(),sessionId:o,touchedFiles:r,coverageScore:N};I.mkdirSync(a,{recursive:!0}),I.writeFileSync(c,JSON.stringify(b,null,2),"utf8"),A=!0;}catch{}let d={taskDescription:t,orchestrationId:o,agentContributions:[],coverageDelta:{before:w,after:N},newSymbols:s,touchedFiles:r,notes:i||""};try{let b=E.join(a,"events","session-log.jsonl");if(I.existsSync(b)){let S=I.readFileSync(b,"utf8").split(`
8
+ `).filter(g=>g.trim().length>0).slice(-50),h=new Map;for(let g of S)try{let m=JSON.parse(g),C=m.agentId||m.agent||m.role||"";if(!C)continue;h.has(C)||h.set(C,{contributions:[],symbolsTouched:new Set,patternsObserved:[]});let B=h.get(C),De=m.action||m.event||m.message||"";if(De&&B.contributions.push(String(De).slice(0,120)),Array.isArray(m.symbols))for(let te of m.symbols)B.symbolsTouched.add(String(te));let Re=m.symbol||"";if(Re&&B.symbolsTouched.add(Re),Array.isArray(m.patterns))for(let te of m.patterns)B.patternsObserved.includes(String(te))||B.patternsObserved.push(String(te));}catch{}for(let[g,m]of h.entries())d.agentContributions.push({agentId:g,contribution:m.contributions.slice(-3).join(" | "),symbolsTouched:Array.from(m.symbolsTouched).slice(0,10),patternsObserved:m.patternsObserved.slice(0,5)});}}catch{}let _=d.agentContributions.length;d.agentContributions.length===0&&d.agentContributions.push({agentId:"session",contribution:t.slice(0,200),symbolsTouched:s.slice(0,10),patternsObserved:[]}),_>0&&a$4(e.rootDir,{verdicts:_,source:"debrief"});let O$1={coverageAdded:x,delegatedToDocumentor:y,loreEntryId:F,coverageScore:{before:w,after:N,delta:N-w},stopHookCleared:A,postflight:$,sessionInsights:d},u=["","\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(O$1,null,2)+`
10
+ `+u;return O(v.length,"paradigm_captain_debrief"),{handled:true,text:v}}var Cn=E.join("events","settlement-liveness.jsonl"),Pn=360*60*1e3;function jn(n){let e=E.join(n,Cn);if(!I.existsSync(e))return false;try{let t=I.readFileSync(e,"utf8").split(`
11
+ `).filter(s=>s.trim().length>0),r=Date.now()-Pn;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 Dn(n,e){let o=n.action||"read";if(o==="claim")return En(n,e);if(o==="advance")return $n(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 Rn(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 Fn(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 $t(n,e){let o=Lt(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 Lt(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=Lt(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 Tt={high:0,medium:1,low:2};async function On(n,e={},o){let t=o,{loadTasks:r}=await import('./task-loader-LFEE6OU7.js'),s=[];try{s=await r(n,{status:"all",limit:9999});}catch(d){a$1.flow("$captain-board").warn("Board task load failed",{error:d instanceof Error?d.message:String(d)});}let i=s.filter(d=>d.external_ref?.provider==="orchestration"&&!d.parentTaskId&&!d.settledAt),a=[];for(let d of i){let _=Fn(s.filter(u=>u.parentTaskId===d.id)),O=[];for(let u of _){let P=t?await $t(u,t):[];O.push({taskId:u.id,blurb:u.blurb,stage:u.stage,status:u.status,claimant:u.claimant,dependsOn:u.dependsOn||[],fragileSymbols:P});}a.push({epicTaskId:d.id,blurb:d.blurb,runStatus:Rn(d,_),settledAt:d.settledAt,nodes:O});}let c=s.filter(d=>d.status==="open"&&!d.claimant),l=[];for(let d of c){let{score:_,fragile:O}=t?await An(d,t):{score:0,fragile:[]},u;e.proposeClaimants&&(u=await Nn(d,n)),l.push({taskId:d.id,blurb:d.blurb,priority:d.priority,tags:d.tags||[],rippleScore:_,fragileSymbols:O,proposedClaimant:u});}l.sort((d,_)=>{if(_.rippleScore!==d.rippleScore)return _.rippleScore-d.rippleScore;let O=(Tt[d.priority]??1)-(Tt[_.priority]??1);return O!==0?O:_.taskId.localeCompare(d.taskId)});let p=s.filter(d=>d.status==="in-progress").length,f=s.filter(d=>d.status==="open").length,k=new Set(i.map(d=>d.id)),w=new Set(c.map(d=>d.id)),x=[];for(let d of s){if(!d.id||d.status==="done"||d.status==="shelved"||d.parentTaskId||k.has(d.id)||w.has(d.id))continue;let _=t?await $t(d,t):[];x.push({taskId:d.id,blurb:d.blurb,stage:d.stage,status:d.status,claimant:d.claimant,dependsOn:d.dependsOn||[],fragileSymbols:_});}let{validateTaskDag:y}=await import('./task-loader-LFEE6OU7.js'),j=y(s),N=a.filter(d=>!d.settledAt&&d.nodes.length>0&&d.nodes.every(_=>_.status==="done"||_.status==="shelved")).map(d=>({epicTaskId:d.epicTaskId,blurb:d.blurb,reason:"all children terminal but run never settled"})),F=7,$=Date.now(),A=s.filter(d=>d.status==="open"&&d.claimant?.kind==="archetype"&&!d.started_at).map(d=>({task:d,ageDays:Math.floor(($-new Date(d.created).getTime())/864e5)})).filter(({ageDays:d})=>Number.isFinite(d)&&d>=F).map(({task:d,ageDays:_})=>({taskId:d.id,blurb:d.blurb,claimant:d.claimant,ageDays:_}));return {runs:a,unclaimed:l,loose:x,summary:{runs:a.length,open:f,inFlight:p,unclaimed:l.length,loose:x.length},integrity:j.length>0?j:void 0,settlementDebt:N.length>0?N:void 0,staleClaims:A.length>0?A:void 0}}async function Nn(n,e){try{let{suggestAgentsForTask:o,loadAgentsManifest:t}=await import('./orchestration-S2ESNKSA.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 En(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-LFEE6OU7.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 $n(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-LFEE6OU7.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 Wt(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 Mn(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 Bn(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(p=>p.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 p=n.gates.slice(0,2).map(f=>`${f.route} \u2192 ${f.gate} (${f.declared?"declared \u2713":"UNDECLARED \u2717"})`);e.push(`Gates: ${p.join("; ")}`);}if(n.protocol.matched){let p=n.protocol.steps?.length?` (${n.protocol.steps.length} steps)`:"";e.push(`Protocol: ${n.protocol.name||n.protocol.id}${p} \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=>E.dirname(s)===e).slice(0,3).map(s=>`# - ${E.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,mn as a,xt as b,xo as c,yn as d,vo as e,hn 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,2 @@
1
+ #!/usr/bin/env node
2
+ import {b,a}from'./chunk-EK4ZRIFJ.js';import*as t from'fs';import*as o from'path';b();function p(s,e){try{let r=o.join(s,".paradigm");t.mkdirSync(r,{recursive:!0});let a=o.join(r,".orchestrated"),n={timestamp:new Date().toISOString(),type:"orchestrated",verdicts:e.verdicts,source:e.source};return t.writeFileSync(a,JSON.stringify(n),"utf8"),!0}catch(r){return a.component("#orchestration-marker").warn("Failed to write orchestration completion marker",{source:e.source,error:r instanceof Error?r.message:String(r)}),false}}export{p as a};
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ import {j,a,c,b as b$1,k as k$1}from'./chunk-ACJWUOMA.js';import*as m from'fs';import*as b from'path';import*as k from'js-yaml';function re(o,e="unknown"){j().trackToolCall(e,o);}function W(){k$1();}function J(o,e){switch(o){case "paradigm_search":return {summary:`Searched for "${e.query}"${e.type?` (type: ${e.type})`:""}`,symbol:e.query};case "paradigm_ripple":return {summary:`Ripple analysis on ${e.symbol}${e.depth?` (depth: ${e.depth})`:""}`,symbol:e.symbol};case "paradigm_related":return {summary:`Checked relations for ${e.symbol}`,symbol:e.symbol};case "paradigm_status":return {summary:"Checked project status"};case "paradigm_navigate":{let n=e.intent,t=e.target,s=e.task;return n==="context"&&s?{summary:`Navigate context: "${s}"`}:t?{summary:`Navigate ${n||"find"}: ${t}`,symbol:t}:{summary:`Navigate (${n||"unknown"})`}}case "paradigm_gates_for_route":return {summary:`Gate suggestions for ${e.method||"GET"} ${e.route}`};case "paradigm_wisdom_context":return {summary:`Checked wisdom for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_context":return {summary:`Checked history for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_record":return {summary:`Recorded ${e.type}: ${(e.description||"").slice(0,60)}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_fragility":return {summary:`Checked fragility for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_flows_affected":return {summary:`Checked flows affected by ${e.symbol}`,symbol:e.symbol};case "paradigm_reindex":return {summary:"Rebuilt static index files"};case "paradigm_session_checkpoint":return {summary:`Checkpoint: phase=${e.phase}, ${(e.context||"").slice(0,60)}`};case "paradigm_task_create":return {summary:`Created task: "${(e.blurb||"").slice(0,60)}"`};case "paradigm_task_done":return {summary:`Completed task ${e.id}`};case "paradigm_task_shelve":return {summary:`Shelved task ${e.id}`};case "paradigm_task_list":return {summary:`Listed tasks (status: ${e.status||"open"})`};case "paradigm_task_update":return {summary:`Updated task ${e.id}`};case "paradigm_assessment_record":return {summary:`Assessment: ${(e.title||"").slice(0,60)} \u2192 ${e.arc_id}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_assessment_list":return {summary:e.arc_id?`Listed entries in ${e.arc_id}`:"Listed assessment arcs"};case "paradigm_assessment_search":return {summary:`Searched assessments${e.symbol?` for ${e.symbol}`:""}`,symbol:e.symbol};case "paradigm_assessment_arc_create":return {summary:`Created arc: ${e.id}`};case "paradigm_assessment_arc_close":return {summary:`Closed arc: ${e.arc_id}`};default:{let n=o.replace(/^paradigm_/,""),t=Object.values(e).find(s=>typeof s=="string"&&s.length>0);return {summary:t?`${n}: ${t.slice(0,60)}`:n,symbol:e.symbol||void 0}}}}function ae(o,e){let n=j(),{summary:t,symbol:s}=J(o,e);n.addBreadcrumb("tool-call",t,{tool:o,symbol:s});}function ce(){return [{name:"paradigm_session_health",description:"Check if context handoff is recommended based on session activity. Call this periodically during long sessions. Returns usage percentage and recommendation (continue, consider-handoff, handoff-recommended, handoff-urgent). ~100 tokens.",inputSchema:{type:"object",properties:{estimatedTotalTokens:{type:"number",description:"Optional: Your estimate of total conversation tokens (if available)"},contextWindowSize:{type:"number",description:"Context window size in tokens (default: 200000)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_context_check",description:"DEPRECATED: renamed to paradigm_session_health. This alias will be removed in a future version.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_handoff_prepare",description:"Prepare a handoff summary. Generates a structured handoff file with markdown summary and recovery instructions. Returns structured markdown with summary, modified files, and next steps. ~300 tokens.",inputSchema:{type:"object",properties:{summary:{type:"string",description:"Brief summary of work done in this session"},nextSteps:{type:"array",items:{type:"string"},description:"List of next steps for the continuing session"},agent:{type:"string",description:'Target agent role (e.g., "builder", "architect")'},modifiedFiles:{type:"array",items:{type:"string"},description:"List of files modified in this session"},symbolsTouched:{type:"array",items:{type:"string"},description:"List of symbols (@feature, #component, etc.) touched"},openQuestions:{type:"array",items:{type:"string"},description:"Unresolved questions or decisions needed"}},required:["summary"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_session_stats",description:"Get current session statistics (MCP interactions, estimated tokens). Returns tool call count, estimated tokens used, and cost breakdown. ~100 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_session_recover",description:"Load previous session breadcrumbs for continuity. Call this at the start of a new session to understand what was done before. Returns symbols modified, files explored, recent actions, and suggestions for continuity. ~200 tokens. NOTE: Recovery data is automatically surfaced as a preamble on the first tool call of each session \u2014 explicit calls are retained for direct inspection or forcing a second recovery pass.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["resume","pick up","continue","what was I doing","last session","recover"]},{name:"paradigm_session_checkpoint",description:"Save a cognitive-transition checkpoint for crash recovery. Call when transitioning between phases (planning \u2192 implementing \u2192 validating \u2192 complete). ~100 tokens.",inputSchema:{type:"object",properties:{phase:{type:"string",enum:["planning","implementing","validating","complete"],description:"Current workflow phase"},context:{type:"string",description:"What's top-of-mind right now (1-3 sentences)"},externalId:{type:"string",description:'Optional: deterministic ID from external source for automatic session recovery (e.g. "linear:PROJ-123", "github:owner/repo#42")'},plan:{type:"string",description:"Optional: the current plan or approach"},modifiedFiles:{type:"array",items:{type:"string"},description:"Optional: files modified so far"},symbolsTouched:{type:"array",items:{type:"string"},description:"Optional: symbols touched so far"},decisions:{type:"array",items:{type:"string"},description:"Optional: key decisions made so far"}},required:["phase","context"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function de(o,e,n){let t=j();if(o==="paradigm_session_health"||o==="paradigm_context_check"){let s=e.contextWindowSize||2e5,i=e.estimatedTotalTokens,a=t.getStats(),{recommendation:r,message:u,usagePercent:l,signals:d}=t.getHandoffRecommendation(s,i),c=t.getDurationMinutes();return {handled:true,text:JSON.stringify({recommendation:r,message:u,stats:{sessionDurationMinutes:c,mcpToolCalls:a.totals.toolCallCount,mcpResourceReads:a.totals.resourceReadCount,estimatedMcpTokens:a.totals.totalTokens,estimatedTotalTokens:i||Math.round(a.totals.totalTokens*5),contextWindowSize:s,usagePercent:l},signals:d,action:r==="continue"?null:"Call paradigm_handoff_prepare to create handoff file"},null,2)}}if(o==="paradigm_handoff_prepare"){let s=e.summary,i=e.nextSteps||[],a$1=e.agent||"builder",r=e.modifiedFiles||[],u=e.symbolsTouched||[],l=e.openQuestions||[],d=t.getStats(),c=t.getCostBreakdown(),f=`h${Date.now().toString(36)}`,g=new Date().toISOString(),p={id:f,timestamp:g,from:"current-session",to:a$1,summary:s,nextSteps:i,modifiedFiles:r,symbolsTouched:u,openQuestions:l,sessionStats:{duration:t.getDurationMinutes(),mcpCalls:d.totals.toolCallCount+d.totals.resourceReadCount,estimatedTokens:d.totals.totalTokens,estimatedCostUsd:c.total.costUsd,model:c.model},status:"pending"},y=false;try{a(n.rootDir,p),y=!0;}catch{}let w=`# Handoff: ${g}
3
+
4
+ ## Session Summary
5
+ ${s}
6
+
7
+ ## Next Steps
8
+ ${i.map((S,v)=>`${v+1}. ${S}`).join(`
9
+ `)||"(none specified)"}
10
+
11
+ ## Key Context
12
+ - Modified files: ${r.length>0?r.join(", "):"(not specified)"}
13
+ - Symbols touched: ${u.length>0?u.join(", "):"(not specified)"}
14
+ - Open questions: ${l.length>0?l.join(", "):"(none)"}
15
+ `;return W(),{handled:true,text:JSON.stringify({handoff:p,markdownSummary:w,persisted:y,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(o==="paradigm_session_stats"){let s=t.getStats(),i=t.getCostBreakdown(),a=t.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(s.startTime).toISOString(),durationMinutes:a,lastActivity:new Date(s.lastActivity).toISOString()},model:{name:i.model,id:i.modelId,pricing:{inputPerMillion:`$${i.pricing.input.toFixed(2)}`,outputPerMillion:`$${i.pricing.output.toFixed(2)}`}},interactions:{toolCalls:s.totals.toolCallCount,resourceReads:s.totals.resourceReadCount,totalInteractions:s.totals.toolCallCount+s.totals.resourceReadCount},tokens:{total:s.totals.totalTokens,byCategory:{resources:i.resources.tokens,tools:i.tools.tokens}},cost:{totalUsd:`$${i.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${i.resources.costUsd.toFixed(4)}`,tools:`$${i.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:i.resources.byType,toolsByName:i.tools.byName}},null,2)}}if(o==="paradigm_session_recover"){let{checkpoint:s,pendingHandoffs:i,previousSession:a}=z(n.rootDir);if(!a&&i.length===0&&!s)return {handled:true,text:JSON.stringify({found:false,message:"No previous session breadcrumbs, checkpoints, or pending handoffs found.",tip:"Breadcrumbs persist to ~/.paradigm/sessions/ and handoffs persist via paradigm_handoff_prepare. Checkpoints persist via paradigm_session_checkpoint."},null,2)};let r={found:true};if(s){let l=Date.now()-s.timestamp,d=Math.round(l/6e4),c=Math.round(l/36e5);r.checkpoint={phase:s.phase,context:s.context,age:c>1?`${c} hours ago`:`${d} minutes ago`,timestamp:new Date(s.timestamp).toISOString(),sessionId:s.sessionId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:s.recentBreadcrumbs?.map(f=>({time:new Date(f.timestamp).toISOString(),action:f.action,tool:f.tool,symbol:f.symbol,summary:f.summary}))};}if(a){let l=Date.now()-a.lastActivity,d=Math.round(l/6e4),c=Math.round(l/36e5),g=a.breadcrumbs.slice(-10).map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}));r.previousSession={sessionId:a.sessionId,startTime:new Date(a.startTime).toISOString(),lastActivity:new Date(a.lastActivity).toISOString(),age:c>1?`${c} hours ago`:`${d} minutes ago`},r.context={symbolsModified:a.symbolsModified,filesExplored:a.filesExplored},r.recentActions=g;}if(i.length>0){r.pendingHandoffs=i.map(l=>({id:l.id,timestamp:l.timestamp,from:l.from,to:l.to,summary:l.summary,nextSteps:l.nextSteps,modifiedFiles:l.modifiedFiles,symbolsTouched:l.symbolsTouched,openQuestions:l.openQuestions}));for(let l of i)try{c(n.rootDir,l.id);}catch{}}let u="Continue where the previous session left off.";if(s)u=`Previous session was in "${s.phase}" phase: ${s.context}`,s.decisions?.length&&(u+=` Key decisions: ${s.decisions.slice(0,2).join("; ")}`);else if(i.length>0){let l=i[i.length-1];u=`Handoff received: "${l.summary}". `,l.nextSteps.length>0&&(u+=`Start with: ${l.nextSteps[0]}`);}else if(a){let l=a.breadcrumbs.slice(-10);if(l.length>0){let d=l[l.length-1];d.symbol&&(u=`Last work involved ${d.symbol}. Consider checking its current state with paradigm_ripple.`);}}return r.suggestion=u,r.agentInstruction="Present a brief summary of the previous session, then ask the user what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking.",t.markRecovered(),{handled:true,text:JSON.stringify(r,null,2)}}if(o==="paradigm_session_checkpoint"){t.setRootDir(n.rootDir);let s=e.phase,i=e.context,a=e.externalId,r=e.plan,u=e.modifiedFiles,l=e.symbolsTouched,d=e.decisions,{checkpoint:c,persisted:f}=t.saveCheckpoint({phase:s,context:i,externalId:a,plan:r,modifiedFiles:u,symbolsTouched:l,decisions:d}),g=f.local||f.global;return {handled:true,text:JSON.stringify({saved:g,persisted:f,checkpoint:{phase:c.phase,context:c.context,sessionId:c.sessionId,...c.externalId?{externalId:c.externalId}:{},timestamp:new Date(c.timestamp).toISOString(),modifiedFiles:c.modifiedFiles?.length||0,symbolsTouched:c.symbolsTouched?.length||0,decisions:c.decisions?.length||0,recentBreadcrumbs:c.recentBreadcrumbs?.length||0},...g?{note:"Checkpoint saved. Recovery data will be auto-surfaced on the first tool call of the next session."}:{warning:"Checkpoint was NOT persisted to disk. Both local and global writes failed. Check MCP server stderr for details."}},null,2)}}return {handled:false,text:""}}function z(o){let e=j();e.setRootDir(o);let n=e.loadCheckpoint(),t=e.loadPreviousSession(),s=[];try{s=b$1(o);}catch{}return {checkpoint:n,pendingHandoffs:s,previousSession:t}}async function le(o){let{checkpoint:e,pendingHandoffs:n}=z(o);if(!e&&n.length===0)return null;let t=[];if(t.push("--- SESSION RECOVERY ---"),e){let s=Date.now()-e.timestamp,i=Math.round(s/6e4),a=Math.round(s/36e5),r=a>1?`${a}h ago`:`${i}m ago`;t.push(`Previous session was in "${e.phase}" phase (${r}): ${e.context}`),e.modifiedFiles?.length&&t.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&t.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&t.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&t.push(`Plan: ${e.plan.slice(0,200)}`);}if(n.length>0){let s=n[n.length-1];t.push(`Pending handoff: "${s.summary}"`),s.nextSteps.length>0&&t.push(`Next steps: ${s.nextSteps.slice(0,3).join(", ")}`);}try{try{let{reapStaleInProgress:u}=await import('./task-settlement-ZXOY4YGX.js');await u(o);}catch{}let{assembleCaptainBoard:s,proposeClaimantFor:i}=await import('./captain-J4FZ5PRU.js'),a=await s(o,{proposeClaimants:!0}),r=a.unclaimed.slice(0,5);if(a.summary.open>0||a.summary.inFlight>0||a.summary.runs>0){t.push(""),t.push(`Cid (captain): ${a.summary.open} open, ${a.summary.inFlight} in-flight`+(a.summary.runs>0?`, ${a.summary.runs} active run(s)`:"")+`, ${a.summary.unclaimed} unclaimed`);let{updateTask:u,loadTask:l}=await import('./task-loader-EIXPKHA3.js');for(let d of r){let c=d.tags.length>0?` [${d.tags.join(", ")}]`:"",f=d.proposedClaimant;if(!f){let g=await l(o,d.taskId);g&&(f=await i(g,o));}if(f){try{let g=await l(o,d.taskId);g&&!g.claimant&&g.status==="open"&&await u(o,d.taskId,{claimant:f});}catch{}t.push(` [${d.priority}] ${d.taskId}: ${d.blurb}${c} \u2192 proposed ${f.ref}`);}else t.push(` [${d.priority}] ${d.taskId}: ${d.blurb}${c}`);}}}catch{try{let{loadTasks:s}=await import('./task-loader-EIXPKHA3.js'),i=await s(o,{status:"open",limit:5});if(i.length>0){t.push(""),t.push("Open tasks:");for(let a of i){let r=a.tags.length>0?` [${a.tags.join(", ")}]`:"";t.push(` [${a.priority}] ${a.id}: ${a.blurb}${r}`);}}}catch{}}try{let{loadLoreEntries:s}=await import('./lore-loader-PXFKMKAN.js'),a=(await s(o,{limit:10})).filter(r=>r.tags?.some(u=>u.startsWith("arc:")));if(a.length>0){let r=new Map;for(let d of a){let c=d.tags?.find(f=>f.startsWith("arc:"))||"";r.set(c,(r.get(c)||0)+1);}let u=e?.symbolsTouched||[];if((u.length>0?a.filter(d=>d.symbols_touched?.some(c=>u.includes(c))):a.slice(0,3)).length>0||r.size>0){t.push(""),t.push("Active lore arcs:");for(let[d,c]of r)t.push(` ${d} (${c} entries)`);}}}catch{}try{let{loadNominations:s}=await import('./nomination-engine-EFXDEPZN.js'),i=s(o,{pending_only:!0}).filter(a=>a.urgency==="critical"||a.urgency==="high");if(i.length>0){t.push(""),t.push("Ambient nominations (urgent):");for(let a of i.slice(0,5))t.push(` [${a.urgency}] ${a.brief}`);i.length>5&&t.push(` ... and ${i.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return t.push(""),t.push("IMPORTANT: Present a brief summary of this recovery data to the user, then ask what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking."),t.push("---"),t.join(`
16
+ `)}var T=class{cache=new Map;ttlMs;constructor(e=3e4){this.ttlMs=e;}async getOrCompute(e,n){let t=this.cache.get(e);if(t&&Date.now()-t.createdAt<this.ttlMs)return t.data;let s=await n();return this.cache.set(e,{data:s,createdAt:Date.now()}),s}invalidate(e){this.cache.delete(e);}invalidatePrefix(e){for(let n of this.cache.keys())n.startsWith(e)&&this.cache.delete(n);}clear(){this.cache.clear();}stats(){return {size:this.cache.size,ttlMs:this.ttlMs}}},fe=new T(3e4);var $=".paradigm/personas",B="index.yaml";async function O(o,e){let n=b.join(o,$);if(!m.existsSync(n))return [];let t=m.readdirSync(n).filter(i=>i.endsWith(".persona")),s=[];for(let i of t)try{let a=m.readFileSync(b.join(n,i),"utf8"),r=k.load(a);r&&r.id&&s.push(r);}catch{}return G(s,e)}async function R(o,e){let n=b.join(o,$,`${e}.persona`);if(!m.existsSync(n))return null;try{return k.load(m.readFileSync(n,"utf8"))}catch{return null}}function G(o,e){if(!e)return o;let n=o;return e.tag&&(n=n.filter(t=>t.tags?.includes(e.tag))),e.trigger_type&&(n=n.filter(t=>t.trigger.type===e.trigger_type)),e.gate&&(n=n.filter(t=>t.journey.some(s=>s.gates.includes(e.gate)))),e.flow&&(n=n.filter(t=>t.journey.some(s=>s.flow===e.flow))),e.limit&&(n=n.slice(0,e.limit)),n}async function me(o,e){let n=b.join(o,$);m.mkdirSync(n,{recursive:true});let t=b.join(n,`${e.id}.persona`);if(m.existsSync(t))throw new Error(`Persona ${e.id} already exists`);let s=new Date().toISOString(),i={version:"1.0",id:e.id,name:e.name,description:e.description,traits:e.traits,trigger:e.trigger,fixtures:e.fixtures,tags:e.tags||[],journey:e.journey||[],created:s,updated:s};return m.writeFileSync(t,k.dump(i,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await A(o),e.id}async function H(o,e,n){let t=await R(o,e);if(!t)return false;let s=b.join(o,$,`${e}.persona`),i={...t,...n,id:t.id,version:t.version,created:t.created,updated:new Date().toISOString()};return m.writeFileSync(s,k.dump(i,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await A(o),true}async function ge(o,e){let n=b.join(o,$,`${e}.persona`);if(!m.existsSync(n))return {deleted:false,warnings:[]};let t=[],s=await O(o);for(let i of s)if(i.id!==e){i.trigger.spawned_by?.startsWith(e+".")&&t.push(`Persona ${i.id} is spawned by ${e} \u2014 it will become orphaned`);for(let a of i.journey)a.spawns?.some(r=>r.persona===e)&&t.push(`Persona ${i.id} step ${a.id} spawns ${e} \u2014 spawn will break`);}return m.unlinkSync(n),await A(o),{deleted:true,warnings:t}}async function ye(o,e,n,t){let s=await R(o,e);if(!s)return false;if(s.journey.some(i=>i.id===n.id))throw new Error(`Step ${n.id} already exists in persona ${e}`);if(t){let i=s.journey.findIndex(a=>a.id===t);if(i===-1)throw new Error(`Step ${t} not found in persona ${e}`);s.journey.splice(i+1,0,n);}else s.journey.push(n);return H(o,e,{journey:s.journey})}async function he(o,e,n){let t=await R(o,e);if(!t)return {removed:false,warnings:[]};let s=t.journey.findIndex(r=>r.id===n);if(s===-1)return {removed:false,warnings:[]};let i=t.journey[s],a=[];if(i.produces)for(let r of Object.keys(i.produces)){let u=`{{produces.${r}}}`;for(let l=s+1;l<t.journey.length;l++){let d=t.journey[l];JSON.stringify(d).includes(u)&&a.push(`Step ${d.id} consumes {{produces.${r}}} from this step`);}}if(i.spawns&&i.spawns.length>0)for(let r of i.spawns)a.push(`Step spawns persona ${r.persona} \u2014 spawn chain will break`);return t.journey.splice(s,1),await H(o,e,{journey:t.journey}),{removed:true,warnings:a}}var q=/^[a-z][a-z0-9-]*$/,V=/^[a-z][a-z0-9-]*$/,Q=/^(GET|POST|PUT|PATCH|DELETE)\s+\//;async function we(o,e,n=false){let t=[],s=[];q.test(e.id)||t.push({type:"invalid-id",detail:`ID "${e.id}" must match /^[a-z][a-z0-9-]*$/`}),(!e.name||e.name.trim()==="")&&t.push({type:"missing-name",detail:"Name is required"}),(!e.trigger||!e.trigger.type)&&t.push({type:"missing-trigger",detail:"Trigger with type is required"}),e.trigger.type!=="root"&&!e.trigger.spawned_by&&t.push({type:"missing-spawned-by",detail:`Non-root trigger type "${e.trigger.type}" requires spawned_by`}),(!e.journey||e.journey.length===0)&&t.push({type:"empty-journey",detail:"Journey must have at least one step"});let i=new Set,a=new Set;for(let r of e.journey){V.test(r.id)||t.push({type:"invalid-step-id",step:r.id,detail:"Step ID must match /^[a-z][a-z0-9-]*$/"}),i.has(r.id)&&t.push({type:"duplicate-step-id",step:r.id,detail:`Duplicate step ID "${r.id}"`}),i.add(r.id),Q.test(r.route)||t.push({type:"invalid-route",step:r.id,route:r.route,detail:'Route must match "METHOD /path" (e.g., "POST /api/auth/signup")'}),(!r.gates||r.gates.length===0)&&t.push({type:"missing-gates",step:r.id,detail:"Step must have at least one gate"}),(!r.expect||r.expect.status===void 0)&&t.push({type:"missing-expect",step:r.id,detail:"Step must have expect with status"});let l=JSON.stringify(r).match(/\{\{produces\.([^}]+)\}\}/g)||[];for(let d of l){let c=d.replace("{{produces.","").replace("}}","");a.has(c)||t.push({type:"unresolved-produces",step:r.id,key:c,detail:`{{produces.${c}}} used but not produced by a prior step`});}if(r.produces)for(let d of Object.keys(r.produces))a.add(d);}if(n){let r=b.join(o,"portal.yaml"),u=[],l=[];if(m.existsSync(r))try{let c=k.load(m.readFileSync(r,"utf8"));c.gates&&typeof c.gates=="object"&&(u=Object.keys(c.gates)),c.routes&&typeof c.routes=="object"&&(l=Object.keys(c.routes));}catch{}for(let c of e.journey)for(let f of c.gates)u.length>0&&!u.includes(f)&&t.push({type:"gate-not-found",step:c.id,gate:f,detail:`Gate ${f} not defined in portal.yaml`});for(let c of e.journey)if(l.length>0){let f=c.route;l.some(p=>I(p,f))||s.push({type:"route-not-in-portal",detail:`Route "${f}" (step ${c.id}) not found in portal.yaml`});}for(let c of e.journey)if(c.spawns)for(let f of c.spawns)await R(o,f.persona)||t.push({type:"spawn-target-missing",step:c.id,detail:`Spawn target persona "${f.persona}" does not exist`});let d=await K(o,e.id);if(d&&t.push({type:"spawn-cycle",detail:`Circular spawn dependency: ${d.join(" \u2192 ")}`}),l.length>0||u.length>0){let c=await O(o),f=new Set,g=new Set;for(let S of c)for(let v of S.journey){for(let j of v.gates)f.add(j);g.add(v.route);}let p=[],y=b.join(o,".paradigm","flow-index.json");if(m.existsSync(y))try{let S=JSON.parse(m.readFileSync(y,"utf8"));p=Object.keys(S.flows||{});}catch{}let w=new Set;for(let S of c)for(let v of S.journey)v.flow&&w.add(v.flow);return {persona:e.id,valid:t.length===0,errors:t,warnings:s,coverage:{routes:{covered:g.size,total:l.length,uncovered:l.filter(S=>!g.has(S))},gates:{covered:f.size,total:u.length,uncovered:u.filter(S=>!f.has(S))},flows:{covered:w.size,total:p.length,uncovered:p.filter(S=>!w.has(S))}}}}}return {persona:e.id,valid:t.length===0,errors:t,warnings:s}}function I(o,e){let n=t=>t.replace(/:[a-zA-Z_]+/g,":param").replace(/\{\{[^}]+\}\}/g,":param");return n(o)===n(e)}async function K(o,e){let n=new Set,t=[];async function s(i){if(n.has(i)){let r=t.indexOf(i);return r!==-1?[...t.slice(r),i]:null}n.add(i),t.push(i);let a=await R(o,i);if(a){for(let r of a.journey)if(r.spawns)for(let u of r.spawns){let l=await s(u.persona);if(l)return l}}return t.pop(),null}return s(e)}async function A(o){let e=b.join(o,$);m.mkdirSync(e,{recursive:true});let n=await O(o),t={},s={},i={};for(let c of n){let f=new Set,g=new Set,p=[],y=new Set;for(let w of c.journey){for(let S of w.gates)f.add(S);if(w.flow&&g.add(w.flow),p.push(w.route),w.spawns)for(let S of w.spawns)y.add(S.persona);}t[c.id]={name:c.name,trigger:c.trigger.type,spawned_by:c.trigger.spawned_by,steps:c.journey.length,gates:[...f],flows:[...g],routes:p,spawns:[...y],tags:c.tags||[]};for(let w of f)s[w]||(s[w]=[]),s[w].push(c.id);for(let w of p)i[w]||(i[w]=[]),i[w].push(c.id);}let a=[],r=b.join(o,"portal.yaml");if(m.existsSync(r))try{let c=k.load(m.readFileSync(r,"utf8"));c.routes&&typeof c.routes=="object"&&(a=Object.keys(c.routes).filter(g=>!Object.keys(i).some(p=>I(g,p))));}catch{}let u={},l=b.join(e,"chains");if(m.existsSync(l)){let c=m.readdirSync(l).filter(f=>f.endsWith(".yaml"));for(let f of c)try{let g=m.readFileSync(b.join(l,f),"utf8"),p=k.load(g);if(p&&p.id){let y=p.order.map(v=>v.persona),w=0,S=new Set;for(let v of y){let j=t[v];if(j){w+=j.steps;for(let U of j.gates)S.add(U);}}u[p.id]={description:p.description||"",order:y,total_steps:w,total_gates:S.size};}}catch{}}let d={version:"1.0",generated:new Date().toISOString(),personas:t,chains:u,gate_coverage:s,route_coverage:i,uncovered_routes:a};return m.writeFileSync(b.join(e,B),k.dump(d,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),d}async function be(o){let e=await O(o),n=new Set,t=new Set,s=new Set;for(let d of e)for(let c of d.journey){for(let f of c.gates)n.add(f);t.add(c.route),c.flow&&s.add(c.flow);}let i=[],a=[],r=b.join(o,"portal.yaml");if(m.existsSync(r))try{let d=k.load(m.readFileSync(r,"utf8"));d.gates&&typeof d.gates=="object"&&(i=Object.keys(d.gates)),d.routes&&typeof d.routes=="object"&&(a=Object.keys(d.routes));}catch{}let u=[],l=b.join(o,".paradigm","flow-index.json");if(m.existsSync(l))try{let d=JSON.parse(m.readFileSync(l,"utf8"));u=Object.keys(d.flows||{});}catch{}return {routes:{covered:t.size,total:a.length,uncovered:a.filter(d=>!Array.from(t).some(c=>I(d,c)))},gates:{covered:n.size,total:i.length,uncovered:i.filter(d=>!n.has(d))},flows:{covered:s.size,total:u.length,uncovered:u.filter(d=>!s.has(d))},personas:e.length}}async function Se(o,e){let n=await O(o),t=[];for(let s of n){let i=[],a=[];for(let r of s.journey)if((r.gates.includes(e)||r.flow===e||r.route===e||r.signals?.includes(e))&&(i.push(r.id),r.spawns))for(let l of r.spawns)a.push(l.persona);i.length>0&&t.push({persona:s.id,steps:i,spawns_blocked:a});}return t}function X(o,e){let n=e.split(/[.\[\]]+/).filter(Boolean),t=o;for(let s of n){if(t==null||typeof t!="object")return;t=t[s];}return t}function Y(o,e){let n=[];if(e.status!==o.expect.status&&n.push({type:"status",field:"status",expected:o.expect.status,actual:e.status,message:`Step ${o.id}: status is ${e.status}, expected ${o.expect.status}`}),o.expect.body?.has){let t=e.body;for(let s of o.expect.body.has)(!t||typeof t!="object"||!(s in t))&&n.push({type:"body.has",field:s,expected:true,actual:false,message:`Step ${o.id}: body missing key '${s}'`});}if(o.expect.body?.match){let t=e.body;for(let[s,i]of Object.entries(o.expect.body.match)){let a=t?X(t,s):void 0;JSON.stringify(a)!==JSON.stringify(i)&&n.push({type:"body.match",field:s,expected:i,actual:a??null,message:`Step ${o.id}: '${s}' is ${JSON.stringify(a??null)}, expected ${JSON.stringify(i)}`});}}if(o.signals&&o.signals.length>0){let t=e.signals_fired||[];for(let s of o.signals)t.includes(s)||n.push({type:"signal",field:"signals_fired",expected:s,actual:t,message:`Step ${o.id}: signal '${s}' was not fired`});}if(o.gates.length>0&&e.gates_traversed)for(let t of o.gates)e.gates_traversed.includes(t)||n.push({type:"gate",field:"gates_traversed",expected:t,actual:e.gates_traversed,message:`Step ${o.id}: gate '${t}' was not traversed`});return n}async function xe(o,e={}){let n=[];try{let{SentinelStorage:r}=await import('./dist-VGFSP3XM.js'),u=new r,d=(u.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.complete",scopeValue:o.id,limit:500})||[]).filter(p=>{let y=JSON.parse(p.data_json||"{}");return !(e.run_id&&y.run_id!==e.run_id||e.chain_id&&y.chain_id!==e.chain_id||e.environment&&y.environment!==e.environment)}),f=(u.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.fail",scopeValue:o.id,limit:500})||[]).filter(p=>{let y=JSON.parse(p.data_json||"{}");return !(e.run_id&&y.run_id!==e.run_id||e.chain_id&&y.chain_id!==e.chain_id||e.environment&&y.environment!==e.environment)}),g=new Map;for(let p of [...d,...f]){let y=JSON.parse(p.data_json||"{}");y.step_id&&g.set(y.step_id,y);}for(let p of o.journey){let y=g.get(p.id);if(!y){n.push({step_id:p.id,matched:!1,assertions:[],message:`No Sentinel event found for step '${p.id}' \u2014 step was never exercised`});continue}let w=Y(p,{status:y.status,body:y.body,gates_traversed:y.gates_traversed,signals_fired:y.signals_fired});n.push({step_id:p.id,matched:!0,passed:w.length===0,assertions:w});}}catch{for(let r of o.journey)n.push({step_id:r.id,matched:false,assertions:[],message:"Sentinel unavailable \u2014 cannot validate events"});}let t=n.filter(r=>r.matched).length,s=n.filter(r=>r.passed).length,i=n.filter(r=>r.matched&&!r.passed).length,a=n.reduce((r,u)=>r+u.assertions.length,0);return {run_id:e.run_id,environment:e.environment,steps:n,summary:{total_steps:o.journey.length,matched:t,unmatched:o.journey.length-t,passed:s,failed:i,assertion_failures:a}}}var _=".paradigm/protocols",L="index.yaml";async function E(o){let e=b.join(o,_);if(!m.existsSync(e))return [];let n=m.readdirSync(e).filter(s=>s.endsWith(".protocol")).sort(),t=[];for(let s of n)try{let i=m.readFileSync(b.join(e,s),"utf8"),a=k.load(i);a?.id&&a?.name&&t.push(a);}catch{}return t}async function Z(o,e){let n=e.replace(/^P-/,""),t=b.join(o,_,`${n}.protocol`);if(m.existsSync(t))try{let i=m.readFileSync(t,"utf8");return k.load(i)}catch{return null}return (await E(o)).find(i=>i.id===e)||null}async function Qe(o){let e=b.join(o,_,L);if(!m.existsSync(e))return null;try{let n=m.readFileSync(e,"utf8");return k.load(n)}catch{return null}}async function Ke(o,e,n=3){let t=await E(o);if(t.length===0)return [];let s=te(e);if(s.length===0)return [];let i=[];for(let a of t){let r=0;for(let d of a.trigger){let c=d.toLowerCase();for(let f of s)c.includes(f)&&(r+=3);}for(let d of a.tags){let c=d.toLowerCase();for(let f of s)(c.includes(f)||f.includes(c))&&(r+=2);}let u=a.name.toLowerCase(),l=a.description.toLowerCase();for(let d of s)u.includes(d)&&(r+=1),l.includes(d)&&(r+=1);for(let d of a.steps)if(d.notes){let c=d.notes.toLowerCase();for(let f of s)c.includes(f)&&(r+=.5);}r>0&&i.push({protocol:a,score:r});}return i.sort((a,r)=>r.score-a.score),i.slice(0,n)}async function Xe(o,e){let n=b.join(o,_);m.existsSync(n)||m.mkdirSync(n,{recursive:true});let t=ne(e.name),s=`P-${t}`,i=new Date().toISOString(),a={id:s,name:e.name,description:e.description,trigger:e.trigger,tags:e.tags,symbols:e.symbols||[],exemplar:e.exemplar,steps:e.steps,recorded_from:e.recorded_from,recorded_at:i,last_verified:i,verified_by:e.verified_by||"claude-opus-4-6",status:"current"},r=b.join(n,`${t}.protocol`);return m.writeFileSync(r,k.dump(a,{lineWidth:-1,noRefs:true}),"utf8"),s}async function Ye(o,e,n,t=false){let s=await Z(o,e);if(!s)return false;n.name!==void 0&&(s.name=n.name),n.description!==void 0&&(s.description=n.description),n.trigger!==void 0&&(s.trigger=n.trigger),n.tags!==void 0&&(s.tags=n.tags),n.symbols!==void 0&&(s.symbols=n.symbols),n.exemplar!==void 0&&(s.exemplar=n.exemplar),n.steps!==void 0&&(s.steps=n.steps),n.status!==void 0&&(s.status=n.status),n.verified_by!==void 0&&(s.verified_by=n.verified_by),t&&(s.last_verified=new Date().toISOString(),s.verified_by=n.verified_by||"claude-opus-4-6");let i=e.replace(/^P-/,""),a=b.join(o,_,`${i}.protocol`);return m.writeFileSync(a,k.dump(s,{lineWidth:-1,noRefs:true}),"utf8"),true}function ee(o,e){let n=[],t="current";if(e.exemplar){let s=b.join(o,e.exemplar);m.existsSync(s)?m.statSync(s).mtime.toISOString()>e.last_verified&&(n.push(`Exemplar modified since last verified: ${e.exemplar}`),t!=="broken"&&(t="stale")):(n.push(`Exemplar missing: ${e.exemplar}`),t="broken");}for(let s of e.steps){if(s.template_from){let i=b.join(o,s.template_from);m.existsSync(i)||(n.push(`Template file missing: ${s.template_from}`),t="broken");}if(s.action==="modify"&&s.target){let i=b.join(o,s.target);!s.target.includes("{")&&!m.existsSync(i)&&(n.push(`Modify target missing: ${s.target}`),t="broken");}}return {status:t,issues:n}}async function Ze(o){let e=await E(o),n=[],t=0,s=0,i=0;for(let u of e){let l=ee(o,u);if(u.status!==l.status){u.status=l.status;let d=u.id.replace(/^P-/,""),c=b.join(o,_,`${d}.protocol`);m.existsSync(c)&&m.writeFileSync(c,k.dump(u,{lineWidth:-1,noRefs:true}),"utf8");}switch(l.status){case "current":t++;break;case "stale":s++;break;case "broken":i++;break}n.push({id:u.id,name:u.name,status:l.status,last_verified:u.last_verified,trigger:u.trigger,tags:u.tags});}let a={version:"1.0",generated:new Date().toISOString(),protocols:n,health:{total:e.length,current:t,stale:s,broken:i}},r=b.join(o,_);if(e.length>0){m.existsSync(r)||m.mkdirSync(r,{recursive:true});let u=b.join(r,L);m.writeFileSync(u,k.dump(a,{lineWidth:-1,noRefs:true}),"utf8");}return a}function et(o,e,n){if(!e||e.length<2)return null;let t={};for(let s of e){let i=b.dirname(s);t[i]||(t[i]=[]),t[i].push(s);}for(let[s,i]of Object.entries(t)){if(i.length<2)continue;let a=b.join(o,s);if(!m.existsSync(a))continue;let u=m.readdirSync(a).filter(l=>{let d=b.extname(l);return [".ts",".tsx",".js",".jsx",".rs",".py"].includes(d)}).filter(l=>!i.some(d=>b.basename(d)===l));if(u.length>0){let l=b.join(s,u[0]),d=[...i.map(c=>({action:"create",target:c})),...n.map(c=>({action:"modify",target:c}))];return {hint:`This session created ${i.length} new files in ${s}/ following existing patterns. Consider recording a protocol.`,draft:{name:`Add a ${b.basename(s).replace(/s$/,"")}`,exemplar:l,steps:d}}}}return null}function te(o){return o.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(e=>e.length>1).filter(e=>!se.has(e))}var se=new Set(["a","an","the","is","are","was","were","be","been","to","of","in","for","on","with","at","by","from","it","this","that","and","or","but","if","then","so","as","do","does","did","will","would","can","could","should","may","might","must","shall","i","me","my","we","our","you","your","he","she","how","what","when","where","which","who","whom"]);function ne(o){return o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}
17
+ export{et as A,re as a,ae as b,ce as c,de as d,le as e,fe as f,O as g,R as h,me as i,H as j,ge as k,ye as l,he as m,we as n,A as o,be as p,Se as q,xe as r,E as s,Z as t,Qe as u,Ke as v,Xe as w,Ye as x,ee as y,Ze as z};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {b,c,d}from'./chunk-5TAVYPOV.js';import*as s from'fs';import*as a from'path';import*as h from'js-yaml';var g,ke,x=b(()=>{g={enabled:true,thresholds:{minComplianceRate:90,minEvents:20,timeWindowDays:30,minConsecutiveSessions:5,recencyDays:7},demotion:{failureThreshold:3,failureWindowDays:7,cooldownDays:14},neverGraduate:["explore-before-implement","ripple-before-modify","check-fragility","wisdom-before-implement","confidence-on-decisions","university-onboarded","university-content-valid"]},ke=new Set(["tool-called","context-checked"]);});var D={};c(D,{getAllStates:()=>K,getConfig:()=>Y,getState:()=>S,incrementFailure:()=>X,invalidateGraduationCache:()=>Z,isGraduated:()=>z,loadGraduation:()=>p,markNeverGraduate:()=>Q,saveGraduation:()=>k,setTier:()=>J});function T(e){return a.join(e,".paradigm","graduation.yaml")}function p(e){let t=a.resolve(e);if(m&&y===t&&Date.now()-v<B)return m;let o=T(t),i;if(s.existsSync(o))try{let r=s.readFileSync(o,"utf8");i=h.load(r);}catch{i={version:"1.0",config:{},states:{}};}else i={version:"1.0",config:{},states:{}};return i.version||(i.version="1.0"),i.config||(i.config={}),i.states||(i.states={}),m=i,y=t,v=Date.now(),i}function k(e,t){let o=a.resolve(e),i=T(o),r=a.dirname(i);s.existsSync(r)||s.mkdirSync(r,{recursive:true});let n=h.dump(t,{lineWidth:120,noRefs:true,sortKeys:true});s.writeFileSync(i,n,"utf8"),m=t,y=o,v=Date.now();}function Y(e){let t=p(e);return {...g,...t.config,thresholds:{...g.thresholds,...t.config?.thresholds},demotion:{...g.demotion,...t.config?.demotion},neverGraduate:t.config?.neverGraduate??g.neverGraduate}}function w(e){return {habitId:e,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function S(e,t){let i=p(e).states[t];return i?{...w(t),...i,habitId:t}:w(t)}function K(e){let t=p(e),o={};for(let[i,r]of Object.entries(t.states))o[i]={...w(i),...r,habitId:i};return o}function z(e,t){return S(e,t).tier==="hook"}function J(e,t,o,i){let r=p(e),n=r.states[t]||{};r.states[t]={...n,tier:o,previousTier:n.tier||"habit",...o==="hook"?{graduatedAt:new Date().toISOString(),failureCount:0}:{},...o==="habit"&&n.tier==="hook"?{demotedAt:new Date().toISOString()}:{},...i},k(e,r);}function Q(e,t){let o=p(e);o.states[t]||(o.states[t]={}),o.states[t].neverGraduate=true,o.states[t].tier="habit",k(e,o);}function X(e,t){let o=p(e);o.states[t]||(o.states[t]={});let i=(o.states[t].failureCount||0)+1;return o.states[t].failureCount=i,k(e,o),i}function Z(){m=null,y=null,v=0;}var m,y,v,B,R=b(()=>{x();m=null,y=null,v=0,B=3e4;});var F=[{id:"explore-before-implement",name:"Explore Before Implementing",description:"Call ripple/navigate/search before modifying existing symbols to understand impact",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple","paradigm_navigate","paradigm_search","paradigm_related"]}},enabled:true},{id:"ripple-before-modify",name:"Ripple Before Modifying",description:"Run ripple analysis before modifying symbols with dependents",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple"]}},enabled:true},{id:"check-fragility",name:"Check Fragility",description:"Check history fragility for symbols before modifying frequently-broken code",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_history_fragility"]}},enabled:true},{id:"wisdom-before-implement",name:"Check Team Wisdom",description:"Check team wisdom (preferences, antipatterns, decisions) before implementing",category:"collaboration",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_wisdom_context","paradigm_wisdom_expert"]}},enabled:true},{id:"verify-before-done",name:"Verify Before Done",description:"Run postflight compliance checks before finishing a session",category:"verification",trigger:"on-stop",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight"]}},enabled:true},{id:"postflight-compliance",name:"Postflight Compliance",description:"Ensure postflight checks pass without errors before finishing",category:"verification",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight","paradigm_reindex"]}},enabled:true},{id:"test-new-components",name:"Test New Components",description:"New components should have associated tests or test plan documented",category:"testing",trigger:"postflight",severity:"advisory",check:{type:"tests-exist",params:{patterns:["**/*.test.*","**/*.spec.*","**/tests/**"]}},enabled:true},{id:"purpose-coverage",name:"Purpose File Coverage",description:"All modified source directories should have .purpose file coverage",category:"documentation",trigger:"postflight",severity:"warn",check:{type:"file-exists",params:{patterns:["**/.purpose"]}},enabled:true},{id:"record-lore-for-significant",name:"Record Lore for Significant Changes",description:"Sessions modifying 3+ files should record a lore entry",category:"documentation",trigger:"on-stop",severity:"warn",check:{type:"lore-recorded",params:{}},enabled:true},{id:"confidence-on-decisions",name:"Confidence on Decisions",description:"When recording lore, include a confidence score (0.0-1.0) to enable calibration tracking over time",category:"documentation",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_lore_record"]}},enabled:true},{id:"gates-for-routes",name:"Gates for Routes",description:"API routes should have corresponding gate declarations in portal.yaml",category:"security",trigger:"postflight",severity:"warn",check:{type:"gates-declared",params:{requireRoutes:true}},enabled:true},{id:"university-content-valid",name:"University Content Valid",description:"Validate university content integrity when files in symbol-covered areas change",category:"quality",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_validate"]}},enabled:true},{id:"university-onboarded",name:"University Onboarding",description:"Call paradigm_university_onboard at session start for project-specific learning content",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_onboard"]}},enabled:false},{id:"orchestration-required",name:"Orchestrate Complex Tasks",description:"Tasks affecting 3+ files or touching security symbols should use paradigm_orchestrate_inline to determine which agents are needed. Ensures security review, test coverage, and documentation.",category:"collaboration",trigger:"preflight",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_orchestrate_inline"]}},enabled:true},{id:"agent-coverage-validated",name:"Validate Agent Involvement",description:"After completing work, verify that agents with relevant expertise were consulted. Check nominations that were surfaced but not acted on.",category:"collaboration",trigger:"postflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ambient_nominations","paradigm_agent_list"]}},enabled:true},{id:"hot-mode-incident",name:"Incident Response Acknowledgment",description:"During incident response, orchestration enforcement is waived. But a post-incident lore entry is required and a postflight review should be scheduled.",category:"collaboration",trigger:"on-stop",severity:"advisory",check:{type:"lore-recorded"},enabled:true}],ee=30*1e3,C=new Map;function _e(e){let t=a.resolve(e),o=C.get(t);if(o&&Date.now()-o.loadedAt<ee)return o.habits;let i=te(t);return C.set(t,{habits:i,loadedAt:Date.now()}),i}function te(e){let t=new Map;for(let l of F)t.set(l.id,{...l});let o=process.env.HOME||process.env.USERPROFILE||"~",i=G(a.join(o,".paradigm","habits.yaml"));i&&A(t,i);let r=M(a.join(o,".paradigm","habits"));for(let l of r)t.set(l.id,l);let n=G(a.join(e,".paradigm","habits.yaml"));n&&A(t,n);let u=M(a.join(e,".paradigm","habits"));for(let l of u)t.set(l.id,l);return Array.from(t.values())}function G(e){if(!s.existsSync(e))return null;try{let t=s.readFileSync(e,"utf8");return h.load(t)}catch{return null}}function A(e,t){if(t.habits)for(let o of t.habits)e.set(o.id,{...o});if(t.overrides)for(let[o,i]of Object.entries(t.overrides)){let r=e.get(o);r&&(i.severity!==void 0&&(r.severity=i.severity),i.enabled!==void 0&&(r.enabled=i.enabled));}}function oe(e,t){return e.filter(o=>o.enabled&&o.trigger===t)}function _(e){C.delete(a.resolve(e));}function M(e){if(!s.existsSync(e))return [];try{let t=s.readdirSync(e).filter(i=>i.endsWith(".habit")).sort(),o=[];for(let i of t)try{let r=s.readFileSync(a.join(e,i),"utf8"),n=h.load(r);n?.id&&n?.name&&o.push(n);}catch{}return o}catch{return []}}var j=["discovery","verification","testing","documentation","collaboration","security"],$=["preflight","postflight","on-commit","on-stop"],P=["advisory","warn","block"],W=["tool-called","file-exists","file-modified","lore-recorded","symbols-registered","gates-declared","tests-exist","git-clean","commit-message-format","flow-coverage","context-checked","aspect-anchored"],ie=/^[a-z0-9]+(-[a-z0-9]+)*$/;function He(e){let t=[];if(e.id||t.push("Missing required field: id"),e.name||t.push("Missing required field: name"),e.description||t.push("Missing required field: description"),e.category||t.push("Missing required field: category"),e.trigger||t.push("Missing required field: trigger"),e.severity||t.push("Missing required field: severity"),e.check||t.push("Missing required field: check"),(e.enabled===void 0||e.enabled===null)&&t.push("Missing required field: enabled"),e.id&&!ie.test(e.id)&&t.push(`Invalid id format: "${e.id}" \u2014 must be kebab-case (lowercase, hyphens only)`),e.category&&!j.includes(e.category)&&t.push(`Invalid category: "${e.category}" \u2014 must be one of: ${j.join(", ")}`),e.trigger&&!$.includes(e.trigger)&&t.push(`Invalid trigger: "${e.trigger}" \u2014 must be one of: ${$.join(", ")}`),e.severity&&!P.includes(e.severity)&&t.push(`Invalid severity: "${e.severity}" \u2014 must be one of: ${P.join(", ")}`),e.check){W.includes(e.check.type)||t.push(`Invalid check.type: "${e.check.type}" \u2014 must be one of: ${W.join(", ")}`);let o=e.check.params||{};switch(e.check.type){case "tool-called":(!o.tools||!Array.isArray(o.tools)||o.tools.length===0)&&t.push('check.type "tool-called" requires check.params.tools[] (non-empty array)');break;case "file-exists":case "file-modified":(!o.patterns||!Array.isArray(o.patterns)||o.patterns.length===0)&&t.push(`check.type "${e.check.type}" requires check.params.patterns[] (non-empty array)`);break;case "commit-message-format":(!o.messagePatterns||!Array.isArray(o.messagePatterns)||o.messagePatterns.length===0)&&t.push('check.type "commit-message-format" requires check.params.messagePatterns[] (non-empty array)');break}}return {valid:t.length===0,errors:t}}var re=new Set(F.map(e=>e.id));function ne(e){return re.has(e)}function Ee(e,t,o="project"){let i=o==="global"?a.join(process.env.HOME||process.env.USERPROFILE||"~",".paradigm","habits"):a.join(e,".paradigm","habits");s.existsSync(i)||s.mkdirSync(i,{recursive:true});let r=a.join(i,`${t.id}.habit`),n=h.dump(t,{lineWidth:120,noRefs:true});return s.writeFileSync(r,n,"utf8"),_(e),r}function xe(e,t){if(ne(t))return {removed:false,reason:`"${t}" is a seed habit and cannot be removed. Use overrides in habits.yaml to disable it.`};let o=a.join(e,".paradigm","habits",`${t}.habit`);if(s.existsSync(o))return s.unlinkSync(o),_(e),{removed:true};let i=process.env.HOME||process.env.USERPROFILE||"~",r=a.join(i,".paradigm","habits",`${t}.habit`);return s.existsSync(r)?(s.unlinkSync(r),_(e),{removed:true}):{removed:false,reason:`No .habit file found for "${t}". It may be defined in habits.yaml \u2014 edit that file directly.`}}var se=0;function Te(e,t,o,i,r){let n=oe(e,t);i&&(n=n.filter(d=>!d.platforms||d.platforms.includes(i)));let u=0;if(r)try{let{isGraduated:d$1}=(R(),d(D)),O=n.length;n=n.filter(U=>!d$1(r,U.id)),u=O-n.length;}catch{}se=u;let l=n.map(d=>ae(d,o)),N=l.filter(d=>d.result==="followed").length,q=l.filter(d=>d.result==="skipped").length,I=l.filter(d=>d.result==="partial").length,H=l.filter(d=>d.result==="skipped"&&d.habit.severity==="block").length;return {trigger:t,evaluations:l,summary:{total:l.length,followed:N,skipped:q,partial:I,blockingViolations:H},blocksCompletion:H>0}}function Se(e){return {toolsCalled:e.toolsCalled||[],filesModified:e.filesModified||[],symbolsTouched:e.symbolsTouched||[],loreRecorded:e.loreRecorded||false,hasPortalRoutes:e.hasPortalRoutes||false,taskAddsRoutes:e.taskAddsRoutes||false,taskDescription:e.taskDescription,gitClean:e.gitClean}}function ae(e,t){switch(e.check.type){case "tool-called":return le(e,t);case "file-exists":return de(e,t);case "file-modified":return ge(e,t);case "lore-recorded":return ce(e,t);case "symbols-registered":return ue(e,t);case "gates-declared":return fe(e,t);case "tests-exist":return pe(e,t);case "git-clean":return me(e,t);case "commit-message-format":return he(e,t);case "flow-coverage":return ye(e,t);case "context-checked":return ve(e,t);case "aspect-anchored":return be(e,t);default:return {habit:e,result:"partial",reason:`Unknown check: ${e.check.type}`}}}function le(e,t){let o=e.check.params.tools||[];if(o.length===0)return {habit:e,result:"followed",reason:"No tools required"};let i=o.filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Called: ${i.join(", ")}`,evidence:i}:t.filesModified.length===0&&t.symbolsTouched.length===0?{habit:e,result:"followed",reason:"No modifications, habit not applicable"}:{habit:e,result:"skipped",reason:`None of [${o.join(", ")}] were called before modifying code`}}function de(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};if(t.filesModified.some(r=>r.endsWith(".purpose")||r.includes(".paradigm/")))return {habit:e,result:"followed",reason:"Purpose files updated"};let i=t.filesModified.filter(r=>!r.endsWith(".md")&&!r.endsWith(".json")&&!r.endsWith(".yaml")&&!r.endsWith(".yml")&&!r.endsWith(".lock")&&!r.endsWith(".purpose")&&!r.includes(".paradigm/"));return i.length===0?{habit:e,result:"followed",reason:"Only non-source files modified"}:{habit:e,result:"skipped",reason:`${i.length} source file(s) without .purpose updates`,evidence:i.slice(0,5)}}function ce(e,t){let o=t.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".yml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/"));return o.length<3?{habit:e,result:"followed",reason:"Session not significant (< 3 source files)"}:t.loreRecorded||t.toolsCalled.includes("paradigm_lore_record")?{habit:e,result:"followed",reason:"Lore recorded"}:{habit:e,result:"skipped",reason:`${o.length} source files modified, no lore entry`,evidence:o.slice(0,5)}}function ue(e,t){if(t.symbolsTouched.length===0)return {habit:e,result:"followed",reason:"No symbols touched"};let i=["paradigm_purpose_add_component","paradigm_purpose_add_signal","paradigm_purpose_add_flow","paradigm_purpose_add_gate","paradigm_purpose_add_aspect","paradigm_purpose_init"].filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Purpose tools called: ${i.join(", ")}`,evidence:i}:{habit:e,result:"partial",reason:`${t.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function fe(e,t){if(!t.taskAddsRoutes)return {habit:e,result:"followed",reason:"No routes added"};if(t.hasPortalRoutes)return {habit:e,result:"followed",reason:"Portal.yaml has routes"};let i=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Gate tools called: ${i.join(", ")}`,evidence:i}:{habit:e,result:"skipped",reason:"Routes added without gate declarations"}}function pe(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};let o=t.filesModified.filter(r=>r.includes(".test.")||r.includes(".spec.")||r.includes("/tests/")||r.includes("/test/")||r.includes("__tests__"));if(o.length>0)return {habit:e,result:"followed",reason:`Test files: ${o.length}`,evidence:o.slice(0,5)};let i=t.filesModified.filter(r=>!r.endsWith(".md")&&!r.endsWith(".json")&&!r.endsWith(".yaml")&&!r.endsWith(".lock")&&!r.endsWith(".purpose")&&!r.includes(".paradigm/")&&!r.includes("node_modules/"));return i.length===0?{habit:e,result:"followed",reason:"No source files to test"}:{habit:e,result:"partial",reason:`${i.length} source file(s), no test files updated`,evidence:i.slice(0,5)}}function ge(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};let o=e.check.params.patterns||[];if(o.length===0)return {habit:e,result:"followed",reason:"No patterns specified"};if(e.trigger==="on-stop"&&e.severity==="block"){let r=t.filesModified.filter(n=>o.some(u=>n.includes(u)||a.basename(n)===u));return r.length>0?{habit:e,result:"followed",reason:`Matching files: ${r.join(", ")}`,evidence:r}:{habit:e,result:"partial",reason:`None of [${o.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let i=t.filesModified.filter(r=>o.some(n=>r.includes(n)||a.basename(r)===n));return i.length>0?{habit:e,result:"followed",reason:`Matching files: ${i.join(", ")}`,evidence:i}:{habit:e,result:"skipped",reason:`None of [${o.join(", ")}] found in modified files`}}function me(e,t){return t.filesModified.length===0?{habit:e,result:"followed",reason:"No files modified"}:e.trigger==="on-stop"?{habit:e,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:t.gitClean===void 0?{habit:e,result:"partial",reason:"Git status not available"}:t.gitClean?{habit:e,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:e,result:"skipped",reason:"Uncommitted changes in working tree"}}function he(e,t){if(!t.commitMessage)return {habit:e,result:"followed",reason:"No commit message to check (not a commit trigger)"};let o=e.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],i=o.filter(r=>new RegExp(r,"m").test(t.commitMessage));if(i.length===o.length)return {habit:e,result:"followed",reason:"Commit message matches all required patterns",evidence:i};if(i.length>0){let r=o.filter(n=>!new RegExp(n,"m").test(t.commitMessage));return {habit:e,result:"partial",reason:`Matches ${i.length}/${o.length} patterns. Missing: ${r.join(", ")}`}}return {habit:e,result:"skipped",reason:"Commit message does not match required format patterns"}}function ye(e,t){let o=t.symbolsTouched.filter(n=>n.startsWith("#"));if(o.length<3)return {habit:e,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(t.hasFlowCoverage)return {habit:e,result:"followed",reason:"Flow coverage exists for multi-component changes"};let r=["paradigm_flow_check","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(n=>t.toolsCalled.includes(n));return r.length>0?{habit:e,result:"followed",reason:`Flow tools called: ${r.join(", ")}`,evidence:r}:{habit:e,result:"skipped",reason:`${o.length} components touched without flow coverage`,evidence:o.slice(0,5)}}function ve(e,t){let i=(e.check.params.contextTools||["paradigm_session_health","paradigm_session_recover","paradigm_session_checkpoint"]).filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Context tools called: ${i.join(", ")}`,evidence:i}:t.filesModified.length===0&&t.symbolsTouched.length===0?{habit:e,result:"followed",reason:"No modifications, context check not applicable"}:{habit:e,result:"skipped",reason:"No context/session tools called during session"}}function be(e,t){let o=t.symbolsTouched.filter(i=>i.startsWith("~"));return o.length===0?{habit:e,result:"followed",reason:"No aspects touched"}:t.aspectAnchorsValid===true?{habit:e,result:"followed",reason:"Aspect anchors validated and valid"}:t.toolsCalled.includes("paradigm_aspect_check")?{habit:e,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:e,result:"skipped",reason:`${o.length} aspect(s) touched without anchor validation`,evidence:o.slice(0,5)}}export{ke as a,x as b,Y as c,S as d,K as e,R as f,_e as g,He as h,ne as i,Ee as j,xe as k,se as l,Te as m,Se as n};
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import {v as v$1,b,q,p,o,s as s$1,i,k,l,a,m,t,u,j as j$1}from'./chunk-FG3M6VVO.js';import {e}from'./chunk-Q527BPUF.js';import {s,e as e$1,g,b as b$2,f as f$2,h}from'./chunk-33ERV2MW.js';import {z,f as f$1,p as p$1}from'./chunk-KAFQA7HV.js';import {f,b as b$1,a as a$1}from'./chunk-ECO3LHCE.js';import*as v from'fs';import*as j from'path';v$1();b();z();f();s();function be(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function re(s){let e=Date.now(),t=s.match(/^(\d+)(m|h|d)$/);if(t){let r=parseInt(t[1],10),i=t[2],l=i==="m"?r*6e4:i==="h"?r*36e5:r*864e5;return new Date(e-l).toISOString()}return s}async function ve(s,e$1,t$1){let r=i=>JSON.stringify(i,null,2);switch(s){case "paradigm_ambient_nominations":{m(t$1.rootDir);let l=e$1.pending_only!==false,d=e$1.limit||20,o=i(t$1.rootDir,{agent:e$1.agent,urgency:e$1.urgency,pending_only:l,limit:d+20}),b=t(t$1.rootDir);o=u(o,b).slice(0,d);let y=j.join(t$1.rootDir,".paradigm/events/nominations.jsonl");if(v.existsSync(y))try{let a=v.readFileSync(y,"utf8"),c=new Set(o.map(m=>m.id)),g=a.trim().split(`
3
+ `).map(m=>{try{let f=JSON.parse(m);return c.has(f.id)?(f.surfaced=!0,JSON.stringify(f)):m}catch{return m}});v.writeFileSync(y,g.join(`
4
+ `)+`
5
+ `,"utf8");}catch{}let h={count:o.length,nominations:o.map(a=>({id:a.id,agent:a.agent,urgency:a.urgency,type:a.type,brief:a.brief,relevance:a.relevance,timestamp:a.timestamp,engaged:a.engaged,response:a.response}))};if(e$1.include_debates){let c=j$1(t$1.rootDir).filter(g=>!g.resolution);h.debates=c.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),h.debate_count=c.length;}return {text:r(h),handled:true}}case "paradigm_ambient_events":{let i=e$1.since?re(e$1.since):void 0,l=e$1.limit||50,d=a(t$1.rootDir,{type:e$1.type,source:e$1.source,symbol:e$1.symbol,agent:e$1.agent,since:i,limit:l});return {text:r({count:d.length,events:d.map(o=>({id:o.id,type:o.type,source:o.source,timestamp:o.timestamp,path:o.path,symbols:o.symbols,context:o.context,agent:o.agent,tool:o.tool,severity:o.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i$1=e$1.nomination_id,l$1=e$1.response,d=e$1.reason,o=k(t$1.rootDir,i$1,l$1,d);if(o)try{let{appendSessionWorkEntry:y,appendVerdictEntry:h}=await import('./session-work-log-T2IE4Y4T.js'),c=i(t$1.rootDir,{limit:500}).find(m=>m.id===i$1),g={timestamp:new Date().toISOString(),type:"user-verdict",agent:c?.agent,nominationId:i$1,verdict:l$1,reason:d};y(t$1.rootDir,g),h(t$1.rootDir,g);}catch{}let b=false;return e$1.resolve_debate&&o&&(b=l(t$1.rootDir,e$1.resolve_debate,i$1,e$1.reason)),{text:r({engaged:o,nomination_id:i$1,response:l$1,debate_resolved:b||void 0}),handled:true}}case "paradigm_context_compose":{let i$1=e$1.agent,l=e$1.symbols||[],d=e$1.include_nominations!==false,o=e$1.include_decisions!==false,b=e$1.include_journal!==false,y=e$1.max_decisions||5,h=e$1.max_journal||5,a=f$1(t$1.rootDir,i$1);if(!a)return {text:r({error:`Agent profile not found: ${i$1}`}),handled:true};let c=[],g=p$1(a,l);if(g.trim()&&c.push(g),o){let m=e(t$1.rootDir,{status:"active",limit:y});if(m.length>0){c.push("## Recent Team Decisions");for(let f of m)c.push(`- **${f.title}**: ${f.decision.slice(0,150)}${f.decision.length>150?"...":""}`);c.push("");}}if(b){let m=b$1(i$1,{transferable:true,limit:h});if(m.length>0){c.push("## Transferable Insights");for(let f of m)c.push(`- [${f.trigger}] ${f.insight.slice(0,150)}${f.insight.length>150?"...":""}`);c.push("");}}if(d){let m=i(t$1.rootDir,{pending_only:true,limit:10});if(m.length>0){c.push("## Pending Nominations");for(let f of m)c.push(`- [${f.urgency}] ${f.brief}`);c.push("");}}return {text:r({agent:i$1,context:c.join(`
6
+ `),sections_included:{profile:true,decisions:o,journal:b,nominations:d}}),handled:true}}case "paradigm_ambient_promote":{let i=e$1.agent,l=s$1(t$1.rootDir,i);return {text:r({agent:i,promoted:l.promoted,entries:l.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e$1.agent,l=e$1.dry_run===true,d=p(t$1.rootDir,i);if(l)return {text:r({agent:i,dry_run:true,stats:d,note:d.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(d.acceptRate*100).toFixed(0)}% \u2014 ${d.acceptRate>.8?"would lower threshold":d.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let o$1=o(t$1.rootDir,i);return {text:r({agent:i,...o$1,stats:d}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let i=q(t$1.rootDir);return {text:r(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:r(await de(t$1.rootDir,e$1)),handled:true};default:return {text:`Unknown ambient tool: ${s}`,handled:false}}}var ae={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function ce(s){try{let e=j.join(s,".paradigm","config.yaml");if(v.existsSync(e)){let r=v.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(r)return r[1].trim()}}catch{}return j.basename(s)}async function de(s,e={}){let t=e.dry_run===true,r=ce(s),i=e$1(s).filter(n=>n.verdict&&n.agent),l=g(s).filter(n=>n.agent&&n.corrections.length>0),d=b$2(s);if(i.length===0&&l.length===0)return {sessionEntries:d.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:t,details:[]};let o=new Map;for(let n of i){let u=n.agent;o.has(u)||o.set(u,[]),o.get(u).push(n);}let b=d.filter(n=>n.type==="agent-contribution"),y=new Map;for(let n of b)n.agent&&(y.has(n.agent)||y.set(n.agent,[]),y.get(n.agent).push(n));let h$1=[],a={},c=0;for(let[n,u]of o){a[n]=0;let _=u.filter(p=>p.verdict==="accepted").length;u.filter(p=>p.verdict==="dismissed").length;u.filter(p=>p.verdict==="revised").length;let R=u.length,K=R>0?_/R:0;for(let p of u){let I=ae[p.verdict];if(!I)continue;let X=y.get(n)?.shift(),A=le(p,X,{acceptRate:K,total:R,accepted:_}),Y=typeof p.confidence=="number"?p.confidence:p.verdict==="accepted"?.85:p.verdict==="revised"?.6:.4,Z={agent:n,verdict:p.verdict,trigger:I,insight:A,symbols:p.symbols};if(h$1.push(Z),t)a[n]++,c++;else try{a$1(n,{trigger:I,insight:A,confidence_before:p.verdict==="accepted"?.7:.8,confidence_after:Y,project:r,transferable:p.verdict==="dismissed",tags:["postflight",`verdict:${p.verdict}`,...(p.symbols||[]).map(ee=>`symbol:${ee}`)]}),a[n]++,c++;}catch{}}}let g$1=new Set;for(let n of l){let u=n.agent;g$1.add(u),a[u]===void 0&&(a[u]=0);let _=`Self-revision during iteration round ${n.round}: ${n.corrections.join("; ")}`;if(h$1.push({agent:u,verdict:"iteration-revision",trigger:"self_reflection",insight:_,symbols:n.symbols}),t)a[u]++,c++;else try{a$1(u,{trigger:"self_reflection",insight:_,confidence_before:.6,confidence_after:typeof n.confidence=="number"?n.confidence:.75,project:r,transferable:!1,tags:["postflight","iteration-revision",`round:${n.round}`,...(n.symbols||[]).map($=>`symbol:${$}`)]}),a[u]++,c++;}catch{}}let m={},f=0,k=new Set([...o.keys(),...g$1]);if(!t)for(let n of k)try{let u=s$1(s,n);u.promoted>0&&(m[n]=u.promoted,f+=u.promoted);}catch{}return !t&&i.length>0&&f$2(s,i.map(n=>n.nominationId).filter(Boolean)),!t&&l.length>0&&h(s,l.map(n=>n.id)),{sessionEntries:d.length,agentsProcessed:Array.from(k),journalsWritten:c,journalsByAgent:a,promoted:f,promotedByAgent:m,dryRun:t,details:h$1}}function le(s,e,t){let r=s.symbols?.length?` (symbols: ${s.symbols.join(", ")})`:"",i=s.reason?` Reason: ${s.reason}.`:"";switch(s.verdict){case "accepted":return `Contribution accepted by user${r}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "dismissed":return `Contribution dismissed by user${r}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "revised":return `Contribution revised by user${r}.${i}`+(s.revisionDelta?` Delta: "${s.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;default:return `Unknown verdict "${s.verdict}"${r}.${i}`}}export{be as a,ve as b,de as c};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a,b}from'./chunk-4TXOVRWD.js';import {b as b$1}from'./chunk-VCKKJDLP.js';import {m}from'./chunk-4GC35IFF.js';import*as u from'fs';import*as p from'path';import*as $ from'js-yaml';import g from'chalk';import q from'ora';var _={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},N={features:["src/features/","features/","app/","src/app/","src/modules/","modules/"],components:["src/components/","components/","src/lib/","lib/","src/ui/","ui/"],gates:["middleware/","src/middleware/","auth/","src/auth/","guards/","src/guards/"],flows:["flows/","src/flows/","workflows/","src/workflows/","sagas/","src/sagas/"],integrations:["integrations/","src/integrations/","external/","src/external/","vendors/"],signals:["events/","src/events/","handlers/","src/handlers/"],state:["stores/","src/stores/","state/","src/state/","reducers/","src/reducers/"]},z={config:[".paradigm/config.yaml","package.json","tsconfig.json",".env.example"],entry:["src/index.ts","src/index.tsx","src/main.ts","src/main.tsx","index.ts","main.ts","src/app.ts","src/app.tsx"],types:["src/types/","types/","src/types.ts","types.ts"]},G={always:["node_modules/","dist/","build/",".git/",".next/",".nuxt/",".cache/","*.lock","*.log"],unless_testing:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","__tests__/","test/","tests/"],unless_docs:["docs/","*.md","README*","CHANGELOG*"]};async function A(o,t,n={}){let r=n.quiet?null:q();r?.start("Generating navigator.yaml...");let s=M(o),e=L(o),c=H(o),i=U(t.symbols,t.purposeFiles),f={version:"1.0",generated:new Date().toISOString(),structure:s,key_files:e,skip_patterns:c,symbols:i},a=p.join(o,".paradigm"),l=p.join(a,"navigator.yaml");u.existsSync(a)||u.mkdirSync(a,{recursive:true}),u.writeFileSync(l,$.dump(f,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),r?.succeed(g.green("Navigator generated")),n.quiet||(console.log(g.gray(` Output: ${l}`)),console.log(g.gray(` Structure categories: ${Object.keys(s).length}`)),console.log(g.gray(` Symbol mappings: ${Object.keys(i).length}`)),console.log());}function M(o){let t={};for(let[n,r]of Object.entries(N)){let s=r.filter(e=>{let c=p.join(o,e);return u.existsSync(c)});if(s.length>0){let e=Object.values(_).find(c=>c.category===n);t[n]={paths:s,symbol:e?.prefix||"@"};}}return t}function L(o){let t={};for(let[n,r]of Object.entries(z)){let s=r.filter(e=>{let c=p.join(o,e);return u.existsSync(c)});s.length>0&&(t[n]=s);}return t.config||(t.config=[]),t.entry||(t.entry=[]),t.types||(t.types=[]),t}function H(o){let t={...G},n=p.join(o,".gitignore");if(u.existsSync(n))try{let s=u.readFileSync(n,"utf8").split(`
2
+ import {a,b}from'./chunk-4TXOVRWD.js';import {b as b$1}from'./chunk-VCKKJDLP.js';import {m}from'./chunk-D6BSCELB.js';import*as u from'fs';import*as p from'path';import*as $ from'js-yaml';import g from'chalk';import q from'ora';var _={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},N={features:["src/features/","features/","app/","src/app/","src/modules/","modules/"],components:["src/components/","components/","src/lib/","lib/","src/ui/","ui/"],gates:["middleware/","src/middleware/","auth/","src/auth/","guards/","src/guards/"],flows:["flows/","src/flows/","workflows/","src/workflows/","sagas/","src/sagas/"],integrations:["integrations/","src/integrations/","external/","src/external/","vendors/"],signals:["events/","src/events/","handlers/","src/handlers/"],state:["stores/","src/stores/","state/","src/state/","reducers/","src/reducers/"]},z={config:[".paradigm/config.yaml","package.json","tsconfig.json",".env.example"],entry:["src/index.ts","src/index.tsx","src/main.ts","src/main.tsx","index.ts","main.ts","src/app.ts","src/app.tsx"],types:["src/types/","types/","src/types.ts","types.ts"]},G={always:["node_modules/","dist/","build/",".git/",".next/",".nuxt/",".cache/","*.lock","*.log"],unless_testing:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","__tests__/","test/","tests/"],unless_docs:["docs/","*.md","README*","CHANGELOG*"]};async function A(o,t,n={}){let r=n.quiet?null:q();r?.start("Generating navigator.yaml...");let s=M(o),e=L(o),c=H(o),i=U(t.symbols,t.purposeFiles),f={version:"1.0",generated:new Date().toISOString(),structure:s,key_files:e,skip_patterns:c,symbols:i},a=p.join(o,".paradigm"),l=p.join(a,"navigator.yaml");u.existsSync(a)||u.mkdirSync(a,{recursive:true}),u.writeFileSync(l,$.dump(f,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),r?.succeed(g.green("Navigator generated")),n.quiet||(console.log(g.gray(` Output: ${l}`)),console.log(g.gray(` Structure categories: ${Object.keys(s).length}`)),console.log(g.gray(` Symbol mappings: ${Object.keys(i).length}`)),console.log());}function M(o){let t={};for(let[n,r]of Object.entries(N)){let s=r.filter(e=>{let c=p.join(o,e);return u.existsSync(c)});if(s.length>0){let e=Object.values(_).find(c=>c.category===n);t[n]={paths:s,symbol:e?.prefix||"@"};}}return t}function L(o){let t={};for(let[n,r]of Object.entries(z)){let s=r.filter(e=>{let c=p.join(o,e);return u.existsSync(c)});s.length>0&&(t[n]=s);}return t.config||(t.config=[]),t.entry||(t.entry=[]),t.types||(t.types=[]),t}function H(o){let t={...G},n=p.join(o,".gitignore");if(u.existsSync(n))try{let s=u.readFileSync(n,"utf8").split(`
3
3
  `).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).filter(e=>e.endsWith("/")||e.includes("*")||["node_modules","dist","build",".cache"].some(c=>e.includes(c))).slice(0,20);for(let e of s)t.always.includes(e)||t.always.push(e);}catch{}return t}function U(o,t,n){let r={},s=new Map;for(let e of t){let c=p.dirname(e);s.set(e,c);}for(let e of o){let i=`${W(e.type)}${e.id}`;if(e.path)r[i]=e.path;else if(e.directory)r[i]=e.directory;else {let f=t.find(a=>{let l=p.dirname(a),y=e.id.toLowerCase();return l.toLowerCase().includes(y)});f&&(r[i]=p.dirname(f)+"/");}}return r}function W(o){switch(o){case "feature":return "@";case "component":return "#";case "gate":return "^";case "flow":return "$";case "integration":return "&";case "signal":return "!";case "state":return "%";case "idea":return "?";case "deprecated":return "~";default:return "@"}}function P(o){return $.load(o)}async function ce(o,t){let n=o?p.resolve(o):process.cwd(),r=p.basename(n),s=q(),e=p.join(n,".paradigm"),c=u.existsSync(e)&&u.statSync(e).isFile(),i;t.output?i=p.resolve(t.output):c?i=p.join(n,".paradigm-scan-index.json"):(i=p.join(n,".paradigm","scan-index.json"),u.existsSync(p.dirname(i))||u.mkdirSync(p.dirname(i),{recursive:true})),t.quiet||console.log(g.blue(`
4
4
  \u{1F52D} Generating Paradigm Scan Index
5
5
  `));let f,a$1,l,y=[p.join(n,".paradigm"),p.join(n,".paradigm","config.yaml")];for(let h of y)if(u.existsSync(h)&&u.statSync(h).isFile())try{let m=u.readFileSync(h,"utf8"),F=P(m);f=F.scan,a$1=F.graph,l=F.context?.tiers;break}catch{}s.start("Aggregating symbols from purpose and portal files...");let d;try{d=await m(n);}catch(h){s.fail(g.red("Failed to aggregate symbols")),console.error(g.gray(h.message)),process.exit(1);}if(s.succeed(`Found ${d.symbols.length} symbols`),!t.quiet){let h={components:d.symbols.filter(m=>m.type==="component").length,flows:d.symbols.filter(m=>m.type==="flow").length,gates:d.symbols.filter(m=>m.type==="gate").length,signals:d.symbols.filter(m=>m.type==="signal").length,aspects:d.symbols.filter(m=>m.type==="aspect").length};console.log(g.gray(" Breakdown:"));for(let[m,S]of Object.entries(h))S>0&&console.log(g.gray(` ${m}: ${S}`));console.log();}s.start("Generating scan index...");let b$2=a({symbols:d.symbols,purposeFiles:d.purposeFiles,portalFiles:d.portalFiles},{projectName:r,visualTagMappings:f?.visualTagMappings,screenDefinitions:f?.screens});K(b$2,{hot:l?.["hot-threshold"],warm:l?.["warm-threshold"]});try{u.writeFileSync(i,b(b$2),"utf8"),s.succeed(g.green("Scan index generated"));}catch(h){s.fail(g.red("Failed to write scan index")),console.error(g.gray(h.message)),process.exit(1);}await A(n,d,{quiet:t.quiet});let j=await Y(n,d.purposeFiles,{quiet:t.quiet});if(j&&Object.keys(j.flows).length>0){let h=p.join(n,".paradigm","flow-index.json");u.writeFileSync(h,JSON.stringify(j,null,2),"utf8"),t.quiet||s.succeed(g.green(`Flow index generated (${Object.keys(j.flows).length} flows)`));}if(a$1?.["auto-generate"]!==false)try{let h=b$1(n),m=p.join(n,".paradigm","graphs");u.existsSync(m)||u.mkdirSync(m,{recursive:!0});let S=p.join(m,"auto.graph.json");u.writeFileSync(S,JSON.stringify(h,null,2),"utf8"),t.quiet||s.succeed(g.green(`Symbol graph updated (${h.nodes.length} nodes)`));}catch{t.quiet||s.warn(g.yellow("Could not auto-generate symbol graph"));}return t.quiet||(console.log(g.gray(`