@a-company/paradigm 7.0.0 → 7.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/dist/{accept-orchestration-YO2V2WYA.js → accept-orchestration-XW44LF5Y.js} +1 -1
  2. package/dist/add-CBDU23S2.js +12 -0
  3. package/dist/{aggregate-KZICPVT3.js → aggregate-H7SB2UYT.js} +1 -1
  4. package/dist/ambient-OW5M5LVN.js +2 -0
  5. package/dist/{ambient-OX7YJ4PJ.js → ambient-TFLZFV5Y.js} +1 -1
  6. package/dist/ambient-VCTUHHIG.js +2 -0
  7. package/dist/arch-loader-YVOS3QRY.js +2 -0
  8. package/dist/{beacon-52EWNZPK.js → beacon-WVN264OT.js} +1 -1
  9. package/dist/calibrate-PHVP7RPH.js +4 -0
  10. package/dist/captain-CAXGHC2V.js +2 -0
  11. package/dist/captain-CWCLFOXV.js +2 -0
  12. package/dist/{chunk-QDP4G53M.js → chunk-27EK3OQZ.js} +4 -4
  13. package/dist/chunk-2KK4JQ55.js +17 -0
  14. package/dist/chunk-3I3TITBA.js +25 -0
  15. package/dist/chunk-3YM5ABNX.js +2 -0
  16. package/dist/{chunk-47YPID6H.js → chunk-6HYRS3PH.js} +21 -21
  17. package/dist/{chunk-S3UVQ5RV.js → chunk-6VZSOQ7Y.js} +1 -1
  18. package/dist/chunk-727PXENG.js +2 -0
  19. package/dist/chunk-A5EEY6NO.js +3 -0
  20. package/dist/{chunk-DLMDHS2X.js → chunk-ASBK55FU.js} +1 -1
  21. package/dist/{chunk-4GC35IFF.js → chunk-D6BSCELB.js} +1 -1
  22. package/dist/{chunk-G6DK3ND3.js → chunk-DH7QVZDI.js} +9 -0
  23. package/dist/chunk-ECO3LHCE.js +2 -0
  24. package/dist/chunk-FG3M6VVO.js +30 -0
  25. package/dist/chunk-FNYYQNJY.js +2 -0
  26. package/dist/{chunk-ROU3F2HZ.js → chunk-HSY75GRR.js} +3 -3
  27. package/dist/chunk-K6TLYNRQ.js +7 -0
  28. package/dist/chunk-K7KT6FL3.js +25 -0
  29. package/dist/chunk-KAUGQMXU.js +4 -0
  30. package/dist/chunk-M7JHVVDW.js +6 -0
  31. package/dist/chunk-NFN5UUJB.js +2 -0
  32. package/dist/chunk-NRP2KJ6I.js +33 -0
  33. package/dist/{chunk-WROJSWAO.js → chunk-QPQBXRXX.js} +1 -1
  34. package/dist/chunk-RVXQNS6K.js +30 -0
  35. package/dist/chunk-RZRFYGND.js +504 -0
  36. package/dist/chunk-UNSI6DVD.js +93 -0
  37. package/dist/{chunk-JCGCPAHF.js → chunk-USYV5QYU.js} +1 -1
  38. package/dist/chunk-VOPJ47QY.js +2 -0
  39. package/dist/{chunk-QBIQ2FYB.js → chunk-W3VWORQZ.js} +1 -1
  40. package/dist/chunk-WMTES556.js +2 -0
  41. package/dist/chunk-XBK244QR.js +6 -0
  42. package/dist/chunk-XSKIXXFW.js +504 -0
  43. package/dist/{chunk-MBSY57RN.js → chunk-Y76OIMDO.js} +1 -1
  44. package/dist/chunk-YYRP7FLC.js +2 -0
  45. package/dist/{compliance-MLG4W6S4.js → compliance-3M6COUCO.js} +3 -3
  46. package/dist/{constellation-RHZAEFV7.js → constellation-TIKNCZWR.js} +1 -1
  47. package/dist/{cost-24UZSS2P.js → cost-VTHZQKO4.js} +2 -2
  48. package/dist/{diff-MC6AXLKX.js → diff-Z2YSIRC4.js} +1 -1
  49. package/dist/{dist-TNE4GFT7.js → dist-PW5YPGFF.js} +1 -1
  50. package/dist/{docs-3YFNNZRV.js → docs-OWJ7EPD7.js} +1 -1
  51. package/dist/github-4X4MYINS.js +4 -0
  52. package/dist/{habits-BX2IRSUI.js → habits-UA7YT3CG.js} +3 -3
  53. package/dist/{hooks-AXBWYJ5V.js → hooks-XXJ7CSGJ.js} +1 -1
  54. package/dist/index.js +9 -9
  55. package/dist/{init-F4MSKZIW.js → init-QPMLEQWQ.js} +1 -1
  56. package/dist/{integrity-7TKX3DZ4.js → integrity-FRGF5BFS.js} +1 -1
  57. package/dist/journal-loader-CNNA4EAU.js +2 -0
  58. package/dist/lint-Y4P3MHBV.js +26 -0
  59. package/dist/list-5XRLWD7K.js +12 -0
  60. package/dist/mcp.js +1 -1
  61. package/dist/{migrate-5M4KUQ2L.js → migrate-LIVXILOO.js} +1 -1
  62. package/dist/{nomination-engine-AQHU2KBU.js → nomination-engine-EFXDEPZN.js} +1 -1
  63. package/dist/nomination-engine-YRHZZZUN.js +2 -0
  64. package/dist/notebook-loader-TZVIMNDJ.js +2 -0
  65. package/dist/{orchestrate-GMYEBA5T.js → orchestrate-C5NM5MFN.js} +1 -1
  66. package/dist/orchestration-EVWQWTOV.js +2 -0
  67. package/dist/orchestration-UP3KFUJT.js +2 -0
  68. package/dist/{platform-server-WIBVYHIV.js → platform-server-FXF3XFHM.js} +1 -1
  69. package/dist/{probe-27ARJKRO.js → probe-G3TKOJYW.js} +1 -1
  70. package/dist/quiz-QKIKAVL7.js +10 -0
  71. package/dist/registry-NEW4OJ44.js +2 -0
  72. package/dist/reindex-QZYOD5K4.js +2 -0
  73. package/dist/{reindex-XTRF23F7.js → reindex-W67B2LQP.js} +1 -1
  74. package/dist/remember-KZYAY77S.js +14 -0
  75. package/dist/{review-BRO2UP4M.js → review-WHRNLW2W.js} +1 -1
  76. package/dist/{ripple-KCVDS3WE.js → ripple-B6U7263T.js} +1 -1
  77. package/dist/{serve-2PKJP65E.js → serve-6RNZYK2I.js} +2 -2
  78. package/dist/{serve-SMGWGJLM.js → serve-ZT2Z54NK.js} +1 -1
  79. package/dist/{setup-5V2AGLQ6.js → setup-L5OP24US.js} +3 -3
  80. package/dist/{shift-JBCEDCGA.js → shift-UDKXCIW7.js} +3 -3
  81. package/dist/{show-N5LGB5B2.js → show-VXNGIJE4.js} +3 -3
  82. package/dist/{snapshot-YMX5QRBM.js → snapshot-MT5L6XE4.js} +1 -1
  83. package/dist/{spawn-PHA2SVQ3.js → spawn-I6XG57S2.js} +1 -1
  84. package/dist/status-45KIG32R.js +6 -0
  85. package/dist/{status-3GJXI4IK.js → status-4QGKLOP6.js} +4 -4
  86. package/dist/{summary-RPU2BS3Q.js → summary-6QNVQZJV.js} +1 -1
  87. package/dist/symphony-KQJ6HIXB.js +53 -0
  88. package/dist/symphony-VDNDFK7H.js +2 -0
  89. package/dist/symphony-relay-ASMKPDEE.js +3 -0
  90. package/dist/task-KFND4HLF.js +3 -0
  91. package/dist/task-loader-HBZ3KRH2.js +2 -0
  92. package/dist/task-loader-IO4UVFUD.js +2 -0
  93. package/dist/task-settlement-NF7PFSNE.js +3 -0
  94. package/dist/task-settlement-TATNPY6L.js +3 -0
  95. package/dist/team-6WNNLBAO.js +2 -0
  96. package/dist/thread-2A7QKU72.js +41 -0
  97. package/dist/tools-GDWT74O6.js +2 -0
  98. package/dist/tools-SDWAFQMQ.js +142 -0
  99. package/dist/university-ui/assets/{index-B8hm_MdR.js → index-AbTjHBCf.js} +2 -2
  100. package/dist/university-ui/assets/{index-B8hm_MdR.js.map → index-AbTjHBCf.js.map} +1 -1
  101. package/dist/university-ui/index.html +1 -1
  102. package/dist/validate-OZTX3FYX.js +13 -0
  103. package/dist/validate-RIMSY3RP.js +9 -0
  104. package/dist/{workspace-6POCBPDY.js → workspace-4D4TQ637.js} +1 -1
  105. package/package.json +1 -1
  106. package/dist/add-V6XR7DU5.js +0 -12
  107. package/dist/agent-loader-VGBPL3TH.js +0 -2
  108. package/dist/ambient-7HBJHJL2.js +0 -2
  109. package/dist/ambient-SST5CLEC.js +0 -35
  110. package/dist/captain-YUP3KVCA.js +0 -2
  111. package/dist/chunk-3MZ4J2LF.js +0 -2
  112. package/dist/chunk-6AKNXD22.js +0 -32
  113. package/dist/chunk-7SWEOPWF.js +0 -2
  114. package/dist/chunk-CVPKQ3JH.js +0 -8
  115. package/dist/chunk-EKNLG73M.js +0 -6
  116. package/dist/chunk-FRQRREJ6.js +0 -29
  117. package/dist/chunk-GD4F2HC6.js +0 -3
  118. package/dist/chunk-JIXHEBGK.js +0 -7
  119. package/dist/chunk-K54L6CFR.js +0 -25
  120. package/dist/chunk-MBPLJKE5.js +0 -3
  121. package/dist/chunk-QEQCPVF5.js +0 -4
  122. package/dist/chunk-QGZRM6ZB.js +0 -2
  123. package/dist/chunk-QO7YPQXC.js +0 -2
  124. package/dist/chunk-S4J337EQ.js +0 -504
  125. package/dist/chunk-V6MIKLMY.js +0 -18
  126. package/dist/journal-loader-GLH7XFTK.js +0 -2
  127. package/dist/lint-IGKE6UPS.js +0 -26
  128. package/dist/list-NC3QGT75.js +0 -12
  129. package/dist/lore-loader-D2ISOASW.js +0 -2
  130. package/dist/notebook-loader-6DYFMNJ2.js +0 -2
  131. package/dist/orchestration-G5MAY6IA.js +0 -2
  132. package/dist/quiz-TNV6APBM.js +0 -10
  133. package/dist/remember-MJRNTXYS.js +0 -14
  134. package/dist/session-work-log-QXPAXY5K.js +0 -2
  135. package/dist/status-ENAI35NL.js +0 -6
  136. package/dist/symphony-7INZR43F.js +0 -53
  137. package/dist/symphony-G6IENE4K.js +0 -2
  138. package/dist/symphony-relay-2RHG25Z4.js +0 -3
  139. package/dist/task-loader-IGQQ6ZFL.js +0 -2
  140. package/dist/task-settlement-NW4XMJGJ.js +0 -3
  141. package/dist/team-J2YXPEGX.js +0 -2
  142. package/dist/thread-HFXK65D4.js +0 -41
  143. package/dist/tools-HNJ7D5IO.js +0 -2
  144. package/dist/validate-IQG7DBFC.js +0 -9
  145. package/dist/validate-LSCDOLBO.js +0 -13
@@ -0,0 +1,142 @@
1
+ #!/usr/bin/env node
2
+ import {f,b as b$1,g as g$5,n as n$5,m as m$4,k as k$3,i as i$7,h as h$8,j as j$6,l as l$5,c as c$6,e as e$c,a as a$e,d as d$c}from'./chunk-WMTES556.js';import {a as a$7,d as d$2,g as g$1,f as f$3,c as c$3,e as e$2,h as h$1}from'./chunk-BFD3GFRK.js';import {a,b as b$3}from'./chunk-4UJ4NIEQ.js';import {i as i$5}from'./chunk-XROULIQN.js';import {n as n$4,j as j$4,P,O,K as K$1,Q as Q$1,L as L$1,I as I$1,J,D,H as H$1,m as m$2,l as l$2,E as E$1,v as v$2,N as N$1,q as q$2,C as C$1,S,o as o$3,z as z$2,t as t$1,B as B$1,s}from'./chunk-ZUAUFZRJ.js';import {b as b$5,c as c$2}from'./chunk-RZRFYGND.js';import {d,a as a$2,b as b$4,g,x as x$1,n as n$2,v as v$1,p as p$1,c as c$1,h,y as y$1,o as o$1,w,q,m,j as j$2,l,k,i,e as e$5,f as f$5,s as s$2,t as t$3,r as r$3,u as u$1}from'./chunk-3I3TITBA.js';import {f as f$4,r as r$1,p as p$2,o as o$2,i as i$6}from'./chunk-4QADCWPU.js';import {a as a$c}from'./chunk-NKYNHSA5.js';import {a as a$3,n as n$1,o,c as c$5,d as d$b,l as l$6,k as k$4,e as e$b,i as i$8,f as f$9,g as g$6,h as h$9,m as m$5,j as j$7,b as b$e}from'./chunk-UNSI6DVD.js';import {b as b$2,e as e$1,a as a$1,f as f$2,u,c,d as d$1,h as h$4,q as q$1,p as p$3,n as n$3,r as r$2,g as g$3,m as m$1,l as l$1,k as k$1,j as j$3,i as i$2}from'./chunk-2KK4JQ55.js';import {s as s$1,e as e$7,q as q$3,h as h$5,j as j$5,l as l$3,k as k$2,t as t$2,m as m$3,i as i$3,f as f$7,x as x$2,v as v$3,a as a$d,d as d$a}from'./chunk-M7JHVVDW.js';import'./chunk-M4UMM6DC.js';import {a as a$5,b as b$7}from'./chunk-B5KLSBOZ.js';import {a as a$6,b as b$c,d as d$9,e as e$a}from'./chunk-A5EEY6NO.js';import {j as j$1}from'./chunk-ACJWUOMA.js';import {a as a$4,b as b$6}from'./chunk-XBK244QR.js';import {e,v,n,c as c$4,d as d$3}from'./chunk-FG3M6VVO.js';import'./chunk-3KVVC4WV.js';import {j,h as h$7,g as g$4,e as e$9,b as b$b}from'./chunk-KAUGQMXU.js';import {h as h$2,e as e$3,a as a$8,d as d$4}from'./chunk-Q527BPUF.js';import'./chunk-33ERV2MW.js';import'./chunk-VOPJ47QY.js';import {i as i$1,e as e$6,h as h$3,g as g$2,d as d$7,f as f$6}from'./chunk-3YM5ABNX.js';import {d as d$6,b as b$9,a as a$a}from'./chunk-JNSJVCTU.js';import'./chunk-GRZQIKST.js';import {z as z$1,h as h$6,b as b$a,d as d$8,e as e$8,i as i$4,y as y$2,l as l$4}from'./chunk-KAFQA7HV.js';import {b,a as a$b}from'./chunk-EK4ZRIFJ.js';import {f as f$1,e as e$4,b as b$8,d as d$5,a as a$9}from'./chunk-ECO3LHCE.js';import'./chunk-4TXOVRWD.js';import {r,B,p,x,y,t,C,H,I,J as J$1}from'./chunk-D6BSCELB.js';import {b as b$d,p as p$4,f as f$8,c as c$7}from'./chunk-K6TLYNRQ.js';import {h as h$a}from'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as A from'fs';import*as fi from'os';import*as $ from'path';import {ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import*as Ie from'js-yaml';import*as et from'crypto';import {execSync}from'child_process';import {z}from'zod';import*as Ge from'fs/promises';function Zs(){return [{name:"paradigm_history_context",description:"Get implementation history for symbols before modifying. Shows recent changes, stability, and who has worked on these areas. Returns recent commits, authors, and change frequency. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get history for (e.g., ["@checkout", "#payment-form"])'}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_history_record",description:"Record an implementation event (feature, fix, refactor). Call this after making changes to track what was done. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["implement","refactor","rollback"],description:"Type of change"},symbols:{type:"array",items:{type:"string"},description:"Symbols affected by this change"},intent:{type:"string",enum:["feature","fix","refactor","experimental","confirmed"],description:"Intent of the change"},description:{type:"string",description:"What was done"},commit:{type:"string",description:"Git commit hash (optional)"},files:{type:"array",items:{type:"string"},description:"Files affected (optional)"},reason:{type:"string",description:"Reason for rollback (if type is rollback)"}},required:["type","symbols","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_history_validate",description:"Record a validation result (tests passed/failed). Call this after running tests. ~100 tokens.",inputSchema:{type:"object",properties:{implementation_id:{type:"string",description:"ID of the implementation being validated (from paradigm_history_record)"},result:{type:"string",enum:["pass","fail","partial"],description:"Validation result"},tests:{type:"object",properties:{passed:{type:"number"},failed:{type:"number"},skipped:{type:"number"}},description:"Test counts"}},required:["result"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_history_fragility",description:"Check fragility of symbols before modifying. Returns stability scores and warnings for fragile areas. Returns numeric stability scores (0-100) and actionable warnings. ~150 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:"Symbols to check fragility for"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ei(s,e,i$1){switch(s){case "paradigm_history_context":{let{symbols:t}=e,r=await m(i$1),n=i(r,t),o={symbols:t,history:n.map(c=>({symbol:c.symbol,summary:c.summary?{total_changes:c.summary.total_changes,last_modified:c.summary.last_modified,stability_score:c.summary.stability_score,fragility:c.summary.fragility,contributors:c.summary.contributors}:null,recent:c.recent.slice(0,3).map(a=>({type:a.type,description:a.description,author:a.author,ts:a.ts})),co_changes:c.co_changes.slice(0,5)})),summary:{total_symbols:t.length,with_history:n.filter(c=>c.summary).length,fragile_count:n.filter(c=>c.summary?.fragility==="high"||c.summary?.fragility==="critical").length}};return {handled:true,text:JSON.stringify(o,null,2)}}case "paradigm_history_record":{let{type:t,symbols:r,intent:n,description:o,commit:c,files:a,reason:d}=e,l=await k(i$1.rootDir,{type:t,symbols:r,author:{type:"agent",id:"claude"},intent:n,description:o,commit:c,files:a,reason:d});return {handled:true,text:JSON.stringify({success:true,id:l,type:t,symbols:r,message:"History entry recorded successfully",note:"Run paradigm history reindex to update the index after multiple entries"})}}case "paradigm_history_validate":{let{implementation_id:t,result:r,tests:n}=e,o=await l(i$1.rootDir,t||"unknown",r,n);return {handled:true,text:JSON.stringify({success:true,id:o,result:r,tests:n,message:"Validation recorded successfully"})}}case "paradigm_history_fragility":{let{symbols:t}=e,r=await m(i$1),n=j$2(r,t);return {handled:true,text:JSON.stringify({symbols:t,safe_to_modify:n.safe_to_modify,fragile:n.fragile.map(o=>({symbol:o.symbol,fragility:o.fragility,reason:o.reason})),warnings:n.warnings,recommendations:n.recommendations,summary:n.fragile.length===0?"All symbols are stable - safe to proceed":n.safe_to_modify?"Some fragile symbols detected - proceed with extra testing":"Critical fragility detected - consider deferring changes or adding extensive tests"})}}default:return {handled:false,text:""}}}var bt=null,mn=false;function la(s){if(bt||(bt=new a$c),!mn)try{let e=i$6();for(let i of e)try{bt.addPattern(i);}catch{}mn=!0;}catch{mn=true;}return bt}function ti(){return [{name:"paradigm_sentinel_triage",description:"View and filter incidents with pattern matches. Returns recent errors with symbolic context and resolution suggestions. ~200-400 tokens depending on incident count.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter by symbol (e.g., @checkout, ^auth)"},status:{type:"string",enum:["open","investigating","resolved","wont-fix","all"],description:"Filter by status (default: all)"},environment:{type:"string",description:"Filter by environment"},search:{type:"string",description:"Search in error messages"},limit:{type:"number",description:"Max results (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_show",description:"Get full details of a specific incident including timeline and matched patterns. ~200 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Incident ID (e.g., INC-001)"},includeTimeline:{type:"boolean",description:"Include flow timeline"},includeSimilar:{type:"boolean",description:"Include similar incidents"}},required:["incidentId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_resolve",description:"Mark an incident as resolved with optional pattern and commit reference. ~100 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Incident ID"},patternId:{type:"string",description:"Pattern that led to resolution"},commitHash:{type:"string",description:"Fix commit hash"},prUrl:{type:"string",description:"PR URL"},notes:{type:"string",description:"Resolution notes"},wontFix:{type:"boolean",description:"Mark as wont-fix instead of resolved"}},required:["incidentId"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_patterns",description:"List and filter failure patterns with confidence scores. Returns pattern names, match counts, and confidence scores. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter patterns for this symbol"},minConfidence:{type:"number",description:"Minimum confidence score"},source:{type:"string",enum:["manual","suggested","imported","community"],description:"Filter by source"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_add_pattern",description:"Create a new failure pattern. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Pattern ID (kebab-case)"},name:{type:"string",description:"Human-readable name"},description:{type:"string",description:"What this pattern matches"},pattern:{type:"object",properties:{symbols:{type:"object",description:"Symbol criteria"},errorContains:{type:"array",items:{type:"string"},description:"Error keywords"},missingSignals:{type:"array",items:{type:"string"},description:"Expected missing signals"}}},resolution:{type:"object",properties:{description:{type:"string",description:"Resolution steps"},strategy:{type:"string",enum:["retry","fallback","fix-data","fix-code","ignore","escalate"]},priority:{type:"string",enum:["low","medium","high","critical"]},codeHint:{type:"string",description:"Code fix hint"}},required:["description","strategy"]},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"}},required:["id","name","pattern","resolution"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_record",description:"Manually record a new incident. ~100 tokens.",inputSchema:{type:"object",properties:{error:{type:"object",properties:{message:{type:"string",description:"Error message"},stack:{type:"string",description:"Stack trace"},code:{type:"string",description:"Error code"},type:{type:"string",description:"Error type"}},required:["message"]},symbols:{type:"object",properties:{feature:{type:"string"},component:{type:"string"},flow:{type:"string"},gate:{type:"string"},signal:{type:"string"},state:{type:"string"},integration:{type:"string"}}},environment:{type:"string",description:"Environment (required)"},service:{type:"string",description:"Service name"},version:{type:"string",description:"App version"},flowPosition:{type:"object",properties:{flowId:{type:"string"},expected:{type:"array",items:{type:"string"}},actual:{type:"array",items:{type:"string"}},missing:{type:"array",items:{type:"string"}},failedAt:{type:"string"}}}},required:["error","symbols","environment"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_stats",description:"Get statistics and health metrics. Returns open/resolved counts, MTTR, and symbol breakdown. ~150 tokens.",inputSchema:{type:"object",properties:{period:{type:"string",description:"Period: 1d, 7d, 30d, 90d (default: 7d)"},symbol:{type:"string",description:"Get health for specific symbol"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_suggest_pattern",description:"Get AI suggestions for patterns based on incidents. ~200 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Suggest from specific incident"},minOccurrences:{type:"number",description:"Min similar incidents for suggestion"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_logs",description:"Query structured logs from connected apps. Filters by level, symbol, service, search text, time range. ~200-400 tokens.",inputSchema:{type:"object",properties:{level:{type:"string",enum:["debug","info","warn","error"],description:"Filter by log level"},symbol:{type:"string",description:"Filter by symbol (partial match)"},service:{type:"string",description:"Filter by service name"},search:{type:"string",description:"Search in log messages"},since:{type:"string",description:"ISO timestamp \u2014 logs after this time"},sessionId:{type:"string",description:"Filter by session ID"},correlationId:{type:"string",description:"Filter by correlation ID"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_services",description:"List all registered services with version, environment, and last-seen time. ~100 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_app_state",description:"Get live app state snapshots. Shows current state, active flows, and held gates for connected services. ~200 tokens.",inputSchema:{type:"object",properties:{service:{type:"string",description:"Filter by service name"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_validate_symbol",description:"Check if a symbol exists in the project index. Returns known/unknown status with suggestions for typos. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to validate (e.g., #checkout, ^auth)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_flow_activity",description:"Get recent flow events \u2014 which flow nodes were hit, in what order, by which service. ~200 tokens.",inputSchema:{type:"object",properties:{flowId:{type:"string",description:"Filter by flow ID (e.g., $checkout-flow)"},service:{type:"string",description:"Filter by service name"},since:{type:"string",description:"ISO timestamp \u2014 events after this time"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_metrics",description:"Query metrics (counters, gauges, histograms) from connected apps. Supports filtering and aggregation. ~200 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Metric name filter"},type:{type:"string",enum:["counter","gauge","histogram"],description:"Metric type filter"},service:{type:"string",description:"Service name filter"},since:{type:"string",description:"ISO timestamp \u2014 metrics after this time"},aggregate:{type:"boolean",description:"If true and name is provided, return aggregation (count/sum/min/max/avg) instead of raw data"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_traces",description:"Query distributed traces across services. Shows span trees with timing, status, and service hops. ~200 tokens.",inputSchema:{type:"object",properties:{traceId:{type:"string",description:"Get a specific trace by ID"},service:{type:"string",description:"Filter by service name"},symbol:{type:"string",description:"Filter by symbol"},since:{type:"string",description:"ISO timestamp \u2014 traces after this time"},limit:{type:"number",description:"Max traces (default: 10, max: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_schemas",description:"List or get registered event schemas. Schemas define event types, scopes, causality, and visualization for application-agnostic observability. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Get a specific schema by ID. Omit to list all."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_events",description:"Query generic events from any registered schema. Filters by schema, event type, category, scope, service, severity, time range. ~200-400 tokens.",inputSchema:{type:"object",properties:{schemaId:{type:"string",description:'Filter by schema ID (e.g., "pretend-engine")'},eventType:{type:"string",description:'Filter by event type (e.g., "rule:fire")'},category:{type:"string",description:'Filter by category (e.g., "rules")'},service:{type:"string",description:"Filter by service name"},scopeValue:{type:"string",description:"Filter by scope value (e.g., frame number)"},severity:{type:"string",enum:["debug","info","warn","error"],description:"Filter by severity"},since:{type:"string",description:"ISO timestamp \u2014 events after this time"},search:{type:"string",description:"Full-text search in event data"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_scopes",description:"Get scope summaries for a schema \u2014 e.g., frame list with event counts, request list with category breakdown. ~200 tokens.",inputSchema:{type:"object",properties:{schemaId:{type:"string",description:"Schema ID (required)"},sessionId:{type:"string",description:"Filter by session ID"},limit:{type:"number",description:"Max scopes (default: 50)"}},required:["schemaId"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ni(s,e,i){let t=la(),r=new f$4(t);switch(s){case "paradigm_sentinel_triage":{let{symbol:n,status:o="all",environment:c,search:a,limit:d=10}=e,l=t.getRecentIncidents({limit:d,status:o,symbol:n,environment:c,search:a});if(l.length===0)return {handled:true,text:JSON.stringify({count:0,incidents:[],tip:"No incidents recorded yet. Incidents are created when errors occur in production or via paradigm_sentinel_record.",howToRecord:{description:"Record incidents manually with paradigm_sentinel_record",example:{error:{message:"Connection timeout",code:"ETIMEDOUT"},symbols:{feature:"@checkout",integration:"&stripe"},environment:"production"}}},null,2)};let p=l.map(g=>{let u=r.match(g,{maxResults:3});return {id:g.id,timestamp:g.timestamp,status:g.status,error:g.error.message,symbols:g.symbols,environment:g.environment,matches:u.map(m=>({patternId:m.pattern.id,name:m.pattern.name,confidence:m.confidence,strategy:m.pattern.resolution.strategy,description:m.pattern.resolution.description}))}});return {handled:true,text:JSON.stringify({count:p.length,incidents:p},null,2)}}case "paradigm_sentinel_show":{let{incidentId:n,includeTimeline:o,includeSimilar:c}=e,a=t.getIncident(n);if(!a)return {handled:true,text:JSON.stringify({error:`Incident ${n} not found`})};let d=r.match(a,{maxResults:5}),l={incident:a,matches:d.map(p=>({patternId:p.pattern.id,name:p.pattern.name,confidence:p.confidence,matchedCriteria:p.matchedCriteria,resolution:p.pattern.resolution}))};if(o&&a.flowPosition){let p=new o$2().build(a);p&&(l.timeline=new o$2().renderStructured(p));}if(c){let p=t.getRecentIncidents({symbol:Object.values(a.symbols)[0],limit:5}).filter(g=>g.id!==n);l.similar=p.map(g=>({id:g.id,error:g.error.message,status:g.status}));}return {handled:true,text:JSON.stringify(l,null,2)}}case "paradigm_sentinel_resolve":{let{incidentId:n,patternId:o,commitHash:c,prUrl:a,notes:d,wontFix:l}=e;return t.getIncident(n)?l?(t.updateIncident(n,{status:"wont-fix",resolvedAt:new Date().toISOString(),resolvedBy:"manual",resolution:{notes:d}}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${n} marked as won't fix`})}):(t.recordResolution({incidentId:n,patternId:o,commitHash:c,prUrl:a,notes:d}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${n} resolved`,patternId:o,commitHash:c,prUrl:a})}):{handled:true,text:JSON.stringify({error:`Incident ${n} not found`})}}case "paradigm_sentinel_patterns":{let{symbol:n,minConfidence:o,source:c}=e,a=t.getAllPatterns({source:c,minConfidence:o,includePrivate:false}),d=a;return n&&(d=a.filter(l=>{let p=l.pattern.symbols;return Object.values(p).some(g=>g?Array.isArray(g)?g.includes(n)||g.some(u=>n.match(u.replace("*",".*"))):g===n||n.match(g.replace("*",".*")):false)})),{handled:true,text:JSON.stringify({count:d.length,patterns:d.map(l=>({id:l.id,name:l.name,description:l.description,confidence:l.confidence.score,resolution:l.resolution,tags:l.tags}))},null,2)}}case "paradigm_sentinel_add_pattern":{let{id:n,name:o,description:c,pattern:a,resolution:d,tags:l}=e,p={id:n,name:o,description:c||"",pattern:{symbols:a.symbols||{},errorContains:a.errorContains,missingSignals:a.missingSignals},resolution:{description:d.description,strategy:d.strategy,priority:d.priority||"medium",codeHint:d.codeHint},source:"manual",private:false,tags:l||[]};return t.addPattern(p),{handled:true,text:JSON.stringify({success:true,message:`Pattern ${n} created`,pattern:p})}}case "paradigm_sentinel_record":{let{error:n,symbols:o,environment:c,service:a,version:d,flowPosition:l}=e,p=t.recordIncident({error:n,symbols:o,environment:c,service:a,version:d,flowPosition:l}),g=t.getIncident(p),u=g?r.match(g,{maxResults:3}):[];return {handled:true,text:JSON.stringify({success:true,incidentId:p,matches:u.map(m=>({patternId:m.pattern.id,confidence:m.confidence,resolution:m.pattern.resolution.description}))},null,2)}}case "paradigm_sentinel_stats":{let{period:n="7d",symbol:o}=e,c=new p$2(t);if(o){let p=c.getSymbolHealth(o);return {handled:true,text:JSON.stringify({symbol:o,health:p},null,2)}}let a=n.match(/^(\d+)d$/),d=a?parseInt(a[1],10):7,l=c.getStats(d);return {handled:true,text:JSON.stringify({period:`${d}d`,stats:l},null,2)}}case "paradigm_sentinel_suggest_pattern":{let{incidentId:n,minOccurrences:o}=e,c=new r$1(t);if(n){let d=t.getIncident(n);if(!d)return {handled:true,text:JSON.stringify({error:`Incident ${n} not found`})};let l=c.suggestFromIncident(d);return {handled:true,text:JSON.stringify({source:"incident",incidentId:n,suggestion:l},null,2)}}let a=c.findPatternCandidates(o||3);return {handled:true,text:JSON.stringify({source:"analysis",candidates:a.slice(0,5).map(d=>({occurrences:d.occurrenceCount,sampleIncidents:d.incidents.slice(0,3).map(l=>l.id),suggestion:d.suggestedPattern}))},null,2)}}case "paradigm_sentinel_logs":{let{level:n,symbol:o,service:c,search:a,since:d,sessionId:l,correlationId:p,limit:g=50}=e,u=t.queryLogs({level:n,symbol:o,service:c,search:a,since:d,sessionId:l,correlationId:p,limit:g}),m=t.getLogCount({level:n,symbol:o,service:c,since:d});return {handled:true,text:JSON.stringify({count:u.length,total:m,logs:u.map(y=>({timestamp:y.timestamp,level:y.level,symbol:y.symbol,service:y.service,message:y.message,data:y.data,sessionId:y.sessionId,correlationId:y.correlationId,durationMs:y.durationMs}))},null,2)}}case "paradigm_sentinel_services":{let n=t.getServices();return {handled:true,text:JSON.stringify({count:n.length,services:n.map(o=>({name:o.name,version:o.version,environment:o.environment,lastSeen:o.lastSeenAt,startedAt:o.startedAt,pid:o.pid}))},null,2)}}case "paradigm_sentinel_app_state":{let{service:n}=e,o=n?t.getAppState(n):t.getAllAppStates();return {handled:true,text:JSON.stringify({states:o.map(c=>({service:c.service,sessionId:c.sessionId,state:c.state,activeFlows:c.activeFlows,activeGates:c.activeGates,timestamp:c.timestamp}))},null,2)}}case "paradigm_sentinel_validate_symbol":{let{symbol:n}=e,o=t.getLogCount({symbol:n});return {handled:true,text:JSON.stringify({symbol:n,usedInLogs:o>0,logCount:o,tip:o===0?"This symbol has not appeared in any logs. It may be a typo or unused.":`This symbol has been used in ${o} log entries.`},null,2)}}case "paradigm_sentinel_flow_activity":{let{flowId:n,service:o,since:c}=e,d=t.queryLogs({symbol:n,service:o,since:c,limit:100}).filter(l=>["flow","signal","gate"].includes(l.symbolType)).map(l=>({timestamp:l.timestamp,symbol:l.symbol,symbolType:l.symbolType,service:l.service,message:l.message,level:l.level}));return {handled:true,text:JSON.stringify({count:d.length,events:d},null,2)}}case "paradigm_sentinel_metrics":{let{name:n,type:o,service:c,since:a,aggregate:d,limit:l}=e;if(d&&n){let g=t.aggregateMetric(n,{service:c,since:a});return {handled:true,text:JSON.stringify(g,null,2)}}let p=t.queryMetrics({name:n,type:o,service:c,since:a,limit:Math.min(l||50,100)});return {handled:true,text:JSON.stringify({count:p.length,metrics:p.map(g=>({timestamp:g.timestamp,name:g.name,type:g.type,value:g.value,tags:g.tags,service:g.service}))},null,2)}}case "paradigm_sentinel_traces":{let{traceId:n,service:o,symbol:c,since:a,limit:d}=e;if(n){let p=t.getTrace(n);return p?{handled:true,text:JSON.stringify(p,null,2)}:{handled:true,text:JSON.stringify({error:"Trace not found"})}}let l=t.queryTraces({service:o,symbol:c,since:a,limit:Math.min(d||10,20)});return {handled:true,text:JSON.stringify({count:l.length,traces:l.map(p=>({traceId:p.traceId,services:p.services,spanCount:p.spans.length,totalDurationMs:p.totalDurationMs,startTime:p.startTime,endTime:p.endTime}))},null,2)}}case "paradigm_sentinel_schemas":{let{id:n}=e;if(n){let c=t.getSchema(n);return c?{handled:true,text:JSON.stringify(c,null,2)}:{handled:true,text:JSON.stringify({error:`Schema "${n}" not found`})}}let o=t.listSchemas();return o.length===0?{handled:true,text:JSON.stringify({count:0,schemas:[],tip:"No event schemas registered yet. Applications register schemas via POST /api/schemas or SentinelWebClient.registerSchema()."},null,2)}:{handled:true,text:JSON.stringify({count:o.length,schemas:o.map(c=>({id:c.id,version:c.version,name:c.name,description:c.description,eventTypeCount:c.eventTypes.length,scope:c.scope.label,tags:c.tags,registeredAt:c.registeredAt}))},null,2)}}case "paradigm_sentinel_events":{let{schemaId:n,eventType:o,category:c,service:a,scopeValue:d,severity:l,since:p,search:g,limit:u}=e,m=t.queryEvents({schemaId:n,eventType:o,category:c,service:a,scopeValue:d,severity:l,since:p,search:g,limit:Math.min(u||50,100)});return m.length===0?{handled:true,text:JSON.stringify({count:0,events:[],tip:"No events found. Events are ingested via POST /api/events or SentinelWebClient.emit()."},null,2)}:{handled:true,text:JSON.stringify({count:m.length,events:m.map(y=>({id:y.id,schemaId:y.schemaId,eventType:y.eventType,category:y.category,timestamp:y.timestamp,scopeValue:y.scopeValue,service:y.service,severity:y.severity,data:y.data,parentEventId:y.parentEventId,depth:y.depth}))},null,2)}}case "paradigm_sentinel_scopes":{let{schemaId:n,sessionId:o,limit:c}=e,a=t.getEventScopes(n,{limit:Math.min(c||50,200),sessionId:o});return a.length===0?{handled:true,text:JSON.stringify({count:0,scopes:[],tip:`No scopes found for schema "${n}". Events with scope values are required.`},null,2)}:{handled:true,text:JSON.stringify({count:a.length,scopes:a},null,2)}}default:return {handled:false,text:""}}}function ri(){return [{name:"paradigm_flows_affected",description:"Find flows affected by changes to a symbol. Returns flows that include the symbol in their steps, with downstream impact analysis and validation commands. Returns flow IDs, step positions, and validation commands. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol being modified (e.g., @tasks, ^project-member, !task-created)"},includeValidation:{type:"boolean",description:"Include validation commands in response (default: true)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_flow_check",description:"Check flow definition completeness \u2014 verifies that gates referenced in flows.yaml exist in portal.yaml and that required fields are present. Does not trace code execution paths.",inputSchema:{type:"object",properties:{flowId:{type:"string",description:"Specific flow ID to validate (e.g., $task-creation). If not provided, validates all flows."},checkImplementation:{type:"boolean",description:"Deep check: verify actions and signals exist in codebase (default: false)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function si(s,e,i){switch(s){case "paradigm_flows_affected":{let{symbol:t,includeValidation:r=true}=e,n=await e$5(i.rootDir);if(!n)return {handled:true,text:JSON.stringify({error:"Flow index not found",symbol:t,suggestion:"Run `paradigm scan` to generate the flow index. Ensure .purpose files contain flows definitions.",example:`
3
+ flows:
4
+ $task-creation:
5
+ description: "Full task creation flow"
6
+ trigger: "POST /api/projects/:id/tasks"
7
+ steps:
8
+ - id: validate
9
+ action: "Check project membership"
10
+ symbol: "^project-member"
11
+ expect: "403 if not member"
12
+ - id: create
13
+ action: "Create task record"
14
+ symbol: "@tasks"
15
+ `},null,2)};let o=f$5(n,t),c={symbol:o.symbol,totalFlows:o.totalFlows,impactLevel:o.impactLevel,affectedFlows:o.affectedFlows.map(d=>{let l={flowId:d.flowId,definedIn:d.definedIn,description:d.description,stepAffected:d.stepAffected,downstreamSteps:d.downstreamSteps};return d.trigger&&(l.trigger=d.trigger),r&&d.validation&&(l.validation=d.validation),l}),suggestion:o.suggestion};return r&&o.validationCommands.length>0&&(c.validationCommands=o.validationCommands),{handled:true,text:JSON.stringify(c,null,2)}}case "paradigm_flow_check":case "paradigm_flow_validate":{let{flowId:t,checkImplementation:r=false}=e,n=$.join(i.rootDir,".paradigm","flows.yaml"),o=null;if(A.existsSync(n))try{let h=A.readFileSync(n,"utf-8");o=Ie.load(h);}catch(h){return {handled:true,text:JSON.stringify({error:"Failed to parse flows.yaml",details:String(h)},null,2)}}let c={...o?.flows??{}},a=await e$5(i.rootDir);if(a?.flows)for(let[h,b]of Object.entries(a.flows))c[h]||(c[h]={description:b.description,trigger:b.trigger,steps:(b.steps||[]).map(w=>({type:w.symbol?.startsWith("^")?"gate":w.symbol?.startsWith("!")?"signal":"action",symbol:w.symbol??"",description:w.action}))});if(Object.keys(c).length===0)return {handled:true,text:JSON.stringify({error:"No flows found",suggestion:"Create .paradigm/flows.yaml with flow definitions",example:`
16
+ version: "1.0"
17
+ flows:
18
+ $task-creation:
19
+ name: Task Creation Flow
20
+ description: Complete flow for creating a new task
21
+ trigger: "POST /api/tasks"
22
+ steps:
23
+ - type: gate
24
+ symbol: ^authenticated
25
+ description: User must be logged in
26
+ - type: action
27
+ symbol: @create-task
28
+ description: Create task in database
29
+ - type: signal
30
+ symbol: "!task-created"
31
+ description: Emit success event
32
+ successSignal: "!task-created"
33
+ `},null,2)};let d=$.join(i.rootDir,"portal.yaml"),l=[];if(A.existsSync(d))try{let h=A.readFileSync(d,"utf-8"),b=Ie.load(h);b?.gates&&(l=Object.keys(b.gates).map(w=>w.startsWith("^")?w.slice(1):w));}catch{}let p=new Set(l),g=[],u=t?[[t,c[t]]]:Object.entries(c);for(let[h,b]of u){if(!b){if(t)return {handled:true,text:JSON.stringify({error:`Flow not found: ${t}`,availableFlows:Object.keys(c)},null,2)};continue}let w={flowId:h,status:"valid",coverage:{gatesReferenced:[],gatesMissing:[],actionsReferenced:[],actionsMissing:[],signalsEmitted:[],signalsMissing:[]},suggestions:[]},S=b.steps||[];for(let x=0;x<S.length;x++){let _=S[x],C=_.symbol||"",P=pa(C);if(P)switch(_.type){case "gate":w.coverage.gatesReferenced.push(C),p.has(P.name)||(w.coverage.gatesMissing.push(C),w.status="invalid");break;case "action":w.coverage.actionsReferenced.push(C);break;case "signal":w.coverage.signalsEmitted.push(C);break}}b.successSignal&&w.coverage.signalsEmitted.push(b.successSignal),w.coverage.gatesMissing.length>0&&w.suggestions.push(`Add missing gates to portal.yaml: ${w.coverage.gatesMissing.join(", ")}`),w.status==="valid"&&w.coverage.gatesMissing.length===0&&(w.status="valid"),g.push(w);}let m=g.filter(h=>h.status==="valid").length,y=g.filter(h=>h.status==="invalid").length,f={status:y>0?"invalid":"valid",totalFlows:g.length,validFlows:m,invalidFlows:y,results:g.map(h=>({flowId:h.flowId,status:h.status,gatesReferenced:h.coverage.gatesReferenced,gatesMissing:h.coverage.gatesMissing,actionsReferenced:h.coverage.actionsReferenced,signalsEmitted:h.coverage.signalsEmitted,suggestions:h.suggestions}))};return {handled:true,text:JSON.stringify(f,null,2)}}default:return {handled:false,text:""}}}function pa(s){let e=s.match(/^([#$^!~])(.+)$/);return e?{prefix:e[1],name:e[2]}:null}b();var ua=60*1e3,ii=new Map;async function ai(s){let e=$.resolve(s),i=ii.get(e);if(i&&Date.now()-i.loadedAt<ua)return i.fixtures;let t=await ga(e);return t&&ii.set(e,{fixtures:t,loadedAt:Date.now()}),t}async function ga(s){let e=$.join(s,".paradigm","fixtures.yaml");if(!A.existsSync(e))return null;try{let i=A.readFileSync(e,"utf8");return Ie.load(i)}catch(i){return a$b.component("#fixtures-loader").error("Error parsing fixtures.yaml",{error:i}),null}}function bn(s,e){switch(e){case "users":return s.users||{};case "resources":return s.resources||{};case "payloads":return s.payloads||{};case "all":return {users:s.users||{},resources:s.resources||{},payloads:s.payloads||{}};default:return null}}function ci(s,e,i){return bn(s,e)?.[i]||null}function vn(s){return {users:Object.keys(s.users||{}),resources:Object.keys(s.resources||{}),payloads:Object.keys(s.payloads||{})}}function di(){return [{name:"paradigm_test_fixtures",description:"Get test fixtures for validating flows. Returns users (for auth testing), resources (for entity testing), and sample payloads (for API testing). ~150 tokens.",inputSchema:{type:"object",properties:{category:{type:"string",enum:["users","resources","payloads","all"],description:'Category of fixtures to retrieve. Use "all" to get everything.'},name:{type:"string",description:'Specific fixture name within the category (e.g., "admin", "createTask")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function li(s,e,i){switch(s){case "paradigm_test_fixtures":{let{category:t,name:r}=e,n=await ai(i.rootDir);if(!n)return {handled:true,text:JSON.stringify({error:"Fixtures not found",suggestion:"Create .paradigm/fixtures.yaml with test fixtures. Run `paradigm init` to generate a template.",example:`
34
+ version: "1.0"
35
+
36
+ users:
37
+ admin:
38
+ id: "user-admin"
39
+ email: "admin@test.com"
40
+ role: "org-admin"
41
+ token: "Bearer admin-token-xxx"
42
+ member:
43
+ id: "user-alice"
44
+ email: "alice@test.com"
45
+ role: "member"
46
+ token: "Bearer alice-token-xxx"
47
+
48
+ resources:
49
+ project:
50
+ id: "project-1"
51
+ name: "Test Project"
52
+ members: ["user-alice"]
53
+ admins: ["user-admin"]
54
+
55
+ payloads:
56
+ createTask:
57
+ title: "New Task"
58
+ description: "Task description"
59
+ `},null,2)};if(!t){let a=vn(n);return {handled:true,text:JSON.stringify({available:a,usage:{getAllUsers:'paradigm_test_fixtures({ category: "users" })',getSpecificUser:'paradigm_test_fixtures({ category: "users", name: "admin" })',getAllPayloads:'paradigm_test_fixtures({ category: "payloads" })',getEverything:'paradigm_test_fixtures({ category: "all" })'}},null,2)}}if(r&&t!=="all"){let a=ci(n,t,r);if(!a){let l=vn(n);return {handled:true,text:JSON.stringify({error:`Fixture "${r}" not found in category "${t}"`,availableInCategory:l[t]||[]},null,2)}}return {handled:true,text:JSON.stringify(a,null,2)}}let o=bn(n,t);return {handled:true,text:JSON.stringify(o,null,2)}}default:return {handled:false,text:""}}}function pi(s){let e=$.join(s,".paradigm","tags.yaml");if(!A.existsSync(e))return null;try{let i=A.readFileSync(e,"utf-8");return Ie.load(i)}catch{return null}}function fa(s,e){let i=$.join(s,".paradigm","tags.yaml"),t=Ie.dump(e,{lineWidth:-1});A.writeFileSync(i,t,"utf-8");}function ui(){return [{name:"paradigm_tags",description:"List, search, and manage tags in the Tag Bank. Use to find available tags for classification. Returns tags organized by section (core, project, suggested) with usage counts. ~150 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","search","get"],description:"Action: list all tags, search by query, or get specific tag details"},query:{type:"string",description:"For search action: query string to match tag names and descriptions"},tag:{type:"string",description:"For get action: specific tag name to get details for"},category:{type:"string",enum:["core","project","suggested","all"],description:"Filter by tag category (default: all)"}},required:["action"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_tags_suggest",description:"AI proposes a new tag for human review. Tag will be added to the suggested section for approval. Returns confirmation of suggestion with section placement. ~100 tokens.",inputSchema:{type:"object",properties:{tag:{type:"string",description:'Tag name (kebab-case, e.g., "webhook-handler")'},description:{type:"string",description:"What this tag means and when to apply it"},reason:{type:"string",description:'Why this tag would be useful (e.g., "Found 5 components handling webhooks")'},appliesTo:{type:"array",items:{type:"string"},description:'Symbol types this tag applies to (e.g., ["#", "$"])'},exampleSymbols:{type:"array",items:{type:"string"},description:"Example symbols that would use this tag"}},required:["tag","description","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_aspect_check",description:"Verify an aspect has valid anchors and check coverage. Aspects (~) REQUIRE code anchors. Returns anchor validity, coverage stats, and missing anchor warnings. ~150 tokens.",inputSchema:{type:"object",properties:{aspect:{type:"string",description:'Aspect symbol to check (e.g., "~audit-required")'}},required:["aspect"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["cross-cutting","aspect enforcement","policy check","verify aspect"]}]}async function gi(s,e,i){switch(s){case "paradigm_tags":{let{action:t,query:r,tag:n,category:o="all"}=e,c=pi(i.rootDir);if(!c)return {handled:true,text:JSON.stringify({error:"Tag bank not found",suggestion:"Create .paradigm/tags.yaml or run `paradigm init` to set up tags"})};if(t==="list"){let a={};return (o==="all"||o==="core")&&(a.core=Object.entries(c.core).map(([d,l])=>({tag:d,description:l.description?.split(`
60
+ `)[0].trim(),color:l.color,appliesTo:l["applies-to"]}))),(o==="all"||o==="project")&&(a.project=Object.entries(c.project||{}).map(([d,l])=>({tag:d,description:l.description?.split(`
61
+ `)[0].trim(),color:l.color,appliesTo:l["applies-to"]}))),(o==="all"||o==="suggested")&&(a.suggested=(c.suggested||[]).map(d=>({tag:d.tag,reason:d.reason,proposedBy:d["proposed-by"],proposedAt:d["proposed-at"]}))),a.summary={coreCount:Object.keys(c.core||{}).length,projectCount:Object.keys(c.project||{}).length,suggestedCount:(c.suggested||[]).length},{handled:true,text:JSON.stringify(a,null,2)}}if(t==="search"){if(!r)return {handled:true,text:JSON.stringify({error:"Query required for search action"})};let a=r.toLowerCase(),d=[];for(let[l,p]of Object.entries(c.core||{}))(l.toLowerCase().includes(a)||p.description?.toLowerCase().includes(a)||p.aliases?.some(g=>g.toLowerCase().includes(a)))&&d.push({tag:l,category:"core",description:p.description?.split(`
62
+ `)[0].trim()||""});for(let[l,p]of Object.entries(c.project||{}))(l.toLowerCase().includes(a)||p.description?.toLowerCase().includes(a)||p.aliases?.some(g=>g.toLowerCase().includes(a)))&&d.push({tag:l,category:"project",description:p.description?.split(`
63
+ `)[0].trim()||""});return {handled:true,text:JSON.stringify({query:r,count:d.length,matches:d},null,2)}}if(t==="get"){if(!n)return {handled:true,text:JSON.stringify({error:"Tag name required for get action"})};if(c.core?.[n]){let d=c.core[n];return {handled:true,text:JSON.stringify({tag:n,category:"core",description:d.description,color:d.color,appliesTo:d["applies-to"],aliases:d.aliases,requiresAspect:d["requires-aspect"]},null,2)}}if(c.project?.[n]){let d=c.project[n];return {handled:true,text:JSON.stringify({tag:n,category:"project",description:d.description,color:d.color,appliesTo:d["applies-to"],aliases:d.aliases,requiresAspect:d["requires-aspect"]},null,2)}}let a=c.suggested?.find(d=>d.tag===n);return a?{handled:true,text:JSON.stringify({tag:n,category:"suggested",reason:a.reason,proposedBy:a["proposed-by"],proposedAt:a["proposed-at"],appliesTo:a["applies-to"],exampleSymbols:a["example-symbols"],status:"pending approval"},null,2)}:{handled:true,text:JSON.stringify({error:`Tag "${n}" not found`,suggestion:'Use paradigm_tags with action "list" to see available tags'})}}return {handled:true,text:JSON.stringify({error:`Unknown action: ${t}`})}}case "paradigm_tags_suggest":{let{tag:t,description:r,reason:n,appliesTo:o,exampleSymbols:c}=e,a=pi(i.rootDir);if(!a)return {handled:true,text:JSON.stringify({error:"Tag bank not found",suggestion:"Create .paradigm/tags.yaml first"})};if(a.core?.[t]||a.project?.[t])return {handled:true,text:JSON.stringify({error:`Tag "${t}" already exists`,existing:a.core?.[t]?"core":"project"})};if(a.suggested?.some(l=>l.tag===t))return {handled:true,text:JSON.stringify({error:`Tag "${t}" is already in the suggested queue`,status:"pending approval"})};let d={tag:t,"proposed-by":"claude","proposed-at":new Date().toISOString(),reason:n,"applies-to":o||["#"],"example-symbols":c};return a.suggested||(a.suggested=[]),a.suggested.push(d),fa(i.rootDir,a),{handled:true,text:JSON.stringify({success:true,tag:t,status:"pending approval",message:"Tag suggestion added. Human review required before use.",nextSteps:["Human can approve via Sentinel UI or CLI",'Once approved, tag moves to "project" section',"Then AI can use the tag for classification"]},null,2)}}case "paradigm_aspect_check":{let{aspect:t}=e,r=t.startsWith("~")?t:`~${t}`,n=p(i.index,r);if(!n)return {handled:true,text:JSON.stringify({error:`Aspect "${r}" not found`,suggestion:"Use paradigm_search to find available aspects"})};if(n.type!=="aspect")return {handled:true,text:JSON.stringify({error:`Symbol "${r}" is not an aspect (type: ${n.type})`,note:"Only ~ symbols are aspects"})};let o=n.anchors||[],c=n.filePath?$.isAbsolute(n.filePath)?n.filePath:$.resolve(i.rootDir,n.filePath):i.rootDir,a=n.filePath?$.dirname(c):i.rootDir,d=[];for(let f of o){let v=H(f.path,a,i.rootDir),h=v.resolvedPath,b=v.exists,w;if(b)try{let _=A.readFileSync(h,"utf-8").split(`
64
+ `);typeof f.lines=="number"?w=1:Array.isArray(f.lines)&&f.lines.length===2?w=f.lines[1]-f.lines[0]+1:Array.isArray(f.lines)&&(w=f.lines.length);}catch{}let S;b||I(f.path,a,i.rootDir).mismatch&&(S="Anchor resolves under .purpose-dir base but not project-root base (or vice versa). This indicates a framework path-resolution bug; do NOT hand-edit. Run `paradigm_aspect_drift` for full audit, or file framework-bug task per protocol."),d.push({path:f.path,lines:f.raw.split(":")[1]||"full file",exists:b,lineCount:w,...S?{resolution_hint:S}:{}});}let l=o.length>0&&d.every(f=>f.exists),p$1=n.appliesTo||[],g=C(i.index),u=[],m=[];for(let f of g)for(let v of p$1)if(new RegExp("^"+v.replace(/\*/g,".*").replace(/\?/g,".")+"$").test(f.symbol)){u.push(f.symbol),(f.data?.aspects?.includes?.(r)||f.data?.aspects?.includes?.(t))&&m.push(f.symbol);break}let y=u.filter(f=>!m.includes(f));return {handled:true,text:JSON.stringify({aspect:r,valid:l,description:n.description,enforcement:n.enforcement,anchors:d,coverage:{appliesTo:p$1,matchingSymbols:u.length,symbolsWithAspect:m.length,missing:y.slice(0,10),missingCount:y.length},warnings:[...o.length===0?["CRITICAL: Aspect has no anchors - aspects MUST have code anchors"]:[],...d.filter(f=>!f.exists).map(f=>`Anchor file not found: ${f.path}`),...y.length>0?[`${y.length} symbols match applies-to but don't have this aspect`]:[]],recommendation:l?y.length>0?"Aspect is valid but has coverage gaps - consider applying to matching symbols":"Aspect is valid and fully applied":"INVALID: Add code anchors to this aspect"},null,2)}}default:return {handled:false,text:""}}}b();var Q=class extends Error{code="WRITE_VERIFICATION_FAILED";constructor(e="write verification failed"){super(e),this.name="WriteVerificationError";}},ma=".paradigm-install-key",ya="paradigm-v5.38.0-hmac-fallback-key",fe=null;function ha(){if(fe)return fe;try{let s=fi.homedir(),e=$.join(s,ma);if(A.existsSync(e)){let t=A.readFileSync(e,"utf-8").trim();if(/^[0-9a-f]{64}$/i.test(t))return fe=Buffer.from(t,"hex"),fe}let i=et.randomBytes(32);try{A.writeFileSync(e,i.toString("hex"),{encoding:"utf-8",mode:384});}catch{}return fe=i,fe}catch{return fe=Buffer.from(ya),fe}}function ba(s){let e=et.createHmac("sha256",ha());return e.update(s),e.digest("hex").slice(0,12)}function va(s,e){let i=$.dirname(s),t=`.${$.basename(s)}.${process.pid}.${Date.now()}.${et.randomBytes(4).toString("hex")}.tmp`,r=$.join(i,t);try{A.writeFileSync(r,e,{encoding:"utf-8"}),A.renameSync(r,s);}catch(n){try{A.unlinkSync(r);}catch{}throw n}}async function tt(s,e,i){va(s,e);let t;try{t=A.readFileSync(s,"utf-8");}catch{throw a$b.component("#write-and-confirm").error("read-back failed after atomic write",{stage:"read-back"}),new Q("write verification failed (read-back error)")}let r=false;try{r=i(t);}catch{throw a$b.component("#write-and-confirm").error("verify callback threw",{stage:"verify-callback",strict:b$e()}),new Q("write verification failed (verify callback error)")}if(!r)throw a$b.component("#write-and-confirm").error("verify callback returned false",{stage:"verify-callback-false",strict:b$e()}),new Q("write verification failed");let n=Buffer.byteLength(t,"utf-8"),o=ba(t);return {written:true,path:s,hashHint:o,bytes:n}}b();var wa=["#","$","^","!","~"];function N(s){return s.length>1&&wa.includes(s[0])?s.slice(1):s}function F(s,e){let i=N(s);return `${e}${i}`}function Y(s,e){let i=$.isAbsolute(s)?s:$.resolve(e,s);return i.endsWith(".purpose")?i:$.join(i,".purpose")}function E(s){if(!A.existsSync(s))return {};let e=b$d(s);if(!e.data)throw new Error(`Failed to parse ${s}: ${e.errors.join(", ")}`);return e.data}function me(s,e){let i=$.dirname(s);A.existsSync(i)||A.mkdirSync(i,{recursive:true});let t=c$7(e);A.writeFileSync(s,t,"utf8");}async function _t(s,e,i,t="purpose.yaml"){let r=$.dirname(s);A.existsSync(r)||A.mkdirSync(r,{recursive:true});let n=c$7(e);try{return await tt(s,n,o=>{let c=b$d(s);if(!c.data)return !1;try{return i(c.data)}catch{return !1}})}catch(o){throw o instanceof Q?(a$b.component("#purpose-writer").error("purpose write verification failed",{surface:t,stage:"writeAndConfirm"}),new Error(`purpose write verification failed (${t})`)):o}}function ke(s){if(!s)return {};if(!Array.isArray(s))return s;let e={};for(let i of s){let{id:t,...r}=i;e[t]=r;}return e}function je(s){if(!s)return {};if(!Array.isArray(s)){let i={};for(let[t,r]of Object.entries(s))!t||t==="undefined"||(i[t]=r);return i}let e={};for(let i of s)!i||!i.name||(e[i.name]={description:i.description,steps:i.steps});return e}function Oe(s,e){if(!e||e.length===0)return s;if(!s||s.length===0)return e;let i=new Set(s);for(let t of e)i.add(t);return Array.from(i)}var ka={"#":"#","^":"^","!":"!",$:"$","~":"~"};async function mi(s,e,i,t){let r=ka[t];if(!r)throw new Error(`Invalid symbol type: ${t}. Expected one of: # ^ ! $ ~`);let n=N(e),o=N(i),c=F(n,r),a=F(o,r),d=await f$8(s),l=[];for(let p of d){let g=E(p),u=false,y={"#":"components","^":"gates","!":"signals",$:"flows","~":"aspects"}[r];if(y&&y!=="flows"){let f=g[y];f&&!Array.isArray(f)&&n in f&&(f[o]=f[n],delete f[n],u=true);}if(r==="#")for(let f of ["features","components"]){let v=g[f];v&&!Array.isArray(v)&&n in v&&(v[o]=v[n],delete v[n],u=true);}r==="$"&&g.flows&&!Array.isArray(g.flows)&&n in g.flows&&(g.flows[o]=g.flows[n],delete g.flows[n],u=true);for(let f of ["features","components"]){let v=ke(g[f]);for(let[h,b]of Object.entries(v))u=_a(b,c,a)||u;u&&Object.keys(v).length>0&&(g[f]=v);}if(g.flows){let f=je(g.flows);for(let[v,h]of Object.entries(f)){if(h.gates){let b=h.gates.indexOf(c);b!==-1&&(h.gates[b]=a,u=true);}if(h.signals){let b=h.signals.indexOf(c);b!==-1&&(h.signals[b]=a,u=true);}if(h.components){let b=h.components.indexOf(c);b!==-1&&(h.components[b]=a,u=true);}if(h.steps)for(let b of h.steps)typeof b=="object"&&"component"in b&&(b.component===c||b.component===n)&&(b.component=r==="#"?o:a,u=true);}u&&(g.flows=f);}if(g.gates){for(let[f,v]of Object.entries(g.gates))if(v.signals){let h=v.signals.indexOf(c);h!==-1&&(v.signals[h]=a,u=true);}}if(g.aspects){for(let[f,v]of Object.entries(g.aspects))if(v["applies-to"]){let h=v["applies-to"].indexOf(c);h!==-1&&(v["applies-to"][h]=a,u=true);}}u&&(me(p,g),l.push(p));}return l}function _a(s,e,i){let t=false,r=["signals","gates","flows","components","states"];for(let n of r){let o=s[n];if(o){let c=o.indexOf(e);c!==-1&&(o[c]=i,t=true);}}if(s.aspects&&Array.isArray(s.aspects)){let n=s.aspects.indexOf(e);n!==-1&&(s.aspects[n]=i,t=true);}return t}b();function Sa(s){return h$a(s)}function xt(s,e){if(!A.existsSync(s))return {status:"missing"};let i;try{i=A.readFileSync(s,"utf-8");}catch{return wn({status:"unparseable",errorClass:"other",detail:"file read error"})}let t;try{t=Ie.load(i);}catch(r){let{errorClass:n,detail:o}=Sa(r);return wn({status:"unparseable",errorClass:n,detail:o})}return {status:"ok",data:t}}function wn(s,e){if(!(b$e())||s.status==="ok"||s.status==="missing")return s;throw new Error(`yaml load failed under PARADIGM_STRICT=1 (${s.errorClass}: ${s.detail})`)}function Pt(s){let e=$.join(s,"portal.yaml"),i=xt(e);if(i.status==="missing")return {data:{version:"1.0.0",gates:{}},filePath:e};if(i.status==="unparseable"||i.status==="invalid")throw a$b.component("#portal-writer").error("portal.yaml unparseable on read",{errorClass:i.errorClass}),new Error(`portal.yaml unparseable (${i.errorClass}). Refusing to overwrite. Run 'paradigm doctor' for line-specific details.`);return {data:i.data||{version:"1.0.0",gates:{}},filePath:e}}async function bi(s,e){let{data:i,filePath:t}=Pt(s);if(!i.gates||Array.isArray(i.gates)){let c=i.gates;if(i.gates={},Array.isArray(c)&&c.length>0){for(let a of c)if(a&&typeof a=="object"&&"id"in a){let d=N(a.id);i.gates[d]=a;}}}let r=N(e.id),n=i.gates[r]||{};n.description=e.description,e.type!==void 0&&(n.type=e.type),e.location!==void 0&&(n.location=e.location),e.requires!==void 0&&(n.requires=e.requires),e.check!==void 0&&(n.check=e.check),e.grants!==void 0&&(n.grants=e.grants),e.emits!==void 0&&(n.emits=e.emits),e.prizes!==void 0&&(n.prizes=e.prizes),n.prizes||(n.prizes=[]),i.gates[r]=n;let o=Ie.dump(i,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});try{return await tt(t,o,c=>{let a;try{a=Ie.load(c);}catch{return !1}let d=a?.gates;return !d||Array.isArray(d)?!1:!!d[r]})}catch(c){throw c instanceof Q?(a$b.component("#portal-writer").error("portal_add_gate write verification failed",{stage:"writeAndConfirm"}),new Error("portal_add_gate write verification failed")):c}}async function vi(s,e){let{data:i,filePath:t}=Pt(s);(!i.routes||Array.isArray(i.routes))&&(i.routes={});let r=`${e.method} ${e.route}`,n=e.gates.map(c=>`^${N(c)}`);i.routes[r]=n;let o=Ie.dump(i,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});try{return await tt(t,o,c=>{let a;try{a=Ie.load(c);}catch{return !1}let d=a?.routes;return !d||Array.isArray(d)?!1:!!d[r]})}catch(c){throw c instanceof Q?(a$b.component("#portal-writer").error("portal_add_route write verification failed",{stage:"writeAndConfirm"}),new Error("portal_add_route write verification failed")):c}}var xa={name:"paradigm_purpose_init",description:"Create or update file-level metadata on a .purpose file. Does NOT overwrite existing components/signals/etc \u2014 only touches top-level metadata (name, description, context, version). ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory (relative to project root)"},name:{type:"string",description:"Name/title for this purpose file"},description:{type:"string",description:"Description of what this directory/module does"},context:{type:"array",items:{type:"string"},description:"Context notes for AI agents"},version:{type:"string",description:'Version string (default: "1.0.0")'}},required:["purposeFile","name"]},annotations:{readOnlyHint:false,destructiveHint:false}},Pa={name:"paradigm_purpose_add_component",description:"Add or update a component (#) or feature in a .purpose file. Strips # prefix from id automatically. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Component ID (e.g. "payment-service" or "#payment-service")'},description:{type:"string",description:"What this component does"},section:{type:"string",enum:["components","features"],description:'Which section to add to (default: "components")'},file:{type:"string",description:"Source file path for this component"},status:{type:"string",description:'Component status (e.g. "active", "deprecated")'},endpoints:{type:"array",items:{type:"string"},description:'API endpoints (e.g. ["POST /api/payments"])'},tests:{type:"array",items:{type:"string"},description:"Test file paths"},flows:{type:"array",items:{type:"string"},description:'Flow references (e.g. ["$checkout-flow"])'},gates:{type:"array",items:{type:"string"},description:'Gate references (e.g. ["^authenticated"])'},signals:{type:"array",items:{type:"string"},description:'Signal references (e.g. ["!payment-completed"])'},aspects:{type:"array",items:{type:"string"},description:'Aspect references (e.g. ["~audit-required"])'},components:{type:"array",items:{type:"string"},description:'Component references (e.g. ["#stripe-service"])'},type:{type:"string",description:'Component type (e.g., "view", "service", "model", "tool"). Open string per project vocabulary.'},parent:{type:"string",description:'Parent component (e.g., "#payment-page"). Establishes hierarchy.'}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},Ra={name:"paradigm_purpose_add_aspect",description:'Add or update an aspect (~) with ENFORCED anchors. Anchors are required and must point to code locations. Strips ~ prefix automatically. This prevents the common "~aspect:name" format error. ~100 tokens.',inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Aspect ID (e.g. "audit-required" or "~audit-required")'},description:{type:"string",description:"What this aspect enforces"},anchors:{type:"array",items:{type:"string"},description:'REQUIRED. Code anchor locations (e.g. ["src/middleware/audit.ts:15-35"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g. ["compliance", "security"])'},appliesTo:{type:"array",items:{type:"string"},description:'Glob patterns for symbols this applies to (e.g. ["#*Service"])'},enforcement:{type:"string",description:'How this aspect is enforced (e.g. "middleware", "decorator")'}},required:["purposeFile","id","description","anchors"]},annotations:{readOnlyHint:false,destructiveHint:false}},Ta={name:"paradigm_purpose_add_signal",description:"Add a signal (!) definition. Handles YAML ! quoting automatically. Strips ! prefix from id. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Signal ID (e.g. "payment-completed" or "!payment-completed")'},description:{type:"string",description:"What this signal represents"},category:{type:"string",description:'Signal category (e.g. "business", "system", "security")'},severity:{type:"string",enum:["info","warn","error"],description:"Severity level"},emitters:{type:"array",items:{type:"string"},description:'Components that emit this signal (e.g. ["#payment-service"])'},related:{type:"array",items:{type:"string"},description:"Related signals or symbols"},data:{type:"object",description:"Schema/shape of data emitted with this signal"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},Ca={name:"paradigm_purpose_add_flow",description:"Add a flow ($) definition. Strips $ prefix from id. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Flow ID (e.g. "checkout-flow" or "$checkout-flow")'},description:{type:"string",description:"What this flow does"},gates:{type:"array",items:{type:"string"},description:"Gate references in this flow"},signals:{type:"array",items:{type:"string"},description:"Signals emitted during this flow"},components:{type:"array",items:{type:"string"},description:"Components involved in this flow"},steps:{type:"array",items:{type:"object",properties:{component:{type:"string"},action:{type:"string"},description:{type:"string"}},required:["component","action"]},description:"Ordered steps in the flow"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},ja={name:"paradigm_purpose_add_gate",description:"Add a gate (^) to a .purpose file's gates section. This is for purpose-level gates, NOT portal.yaml. Strips ^ prefix. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Gate ID (e.g. "authenticated" or "^authenticated")'},description:{type:"string",description:"What this gate checks"},requires:{type:"array",items:{type:"string"},description:"Requirements for this gate"},keys:{type:"array",items:{type:"string"},description:"Key expressions for gate evaluation"},signals:{type:"array",items:{type:"string"},description:"Signals emitted by this gate (e.g. on pass/fail)"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},Oa={name:"paradigm_purpose_add_state",description:"Add a state definition to a .purpose file. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'State ID (e.g. "user-store")'},description:{type:"string",description:"What this state represents"},type:{type:"string",description:'Type of state (e.g. "object", "array", "string")'},default:{description:"Default value for the state"},properties:{type:"object",description:"State properties as {name: {type, description}}"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},Ia={name:"paradigm_purpose_link",description:"Add references to an existing component without rewriting all fields. Merges into existing arrays (no clobber). Example: add ~rate-limited to #payment-service's aspects. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},componentId:{type:"string",description:"Component or feature ID to add references to"},section:{type:"string",enum:["components","features"],description:"Which section the component is in (default: auto-detect)"},signals:{type:"array",items:{type:"string"},description:"Signal references to add"},aspects:{type:"array",items:{type:"string"},description:"Aspect references to add"},gates:{type:"array",items:{type:"string"},description:"Gate references to add"},flows:{type:"array",items:{type:"string"},description:"Flow references to add"},components:{type:"array",items:{type:"string"},description:"Component references to add"}},required:["purposeFile","componentId"]},annotations:{readOnlyHint:false,destructiveHint:false}},Aa={name:"paradigm_purpose_remove",description:"Remove any element by section + id from a .purpose file. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},section:{type:"string",enum:["components","features","gates","signals","aspects","flows","states"],description:"Which section to remove from"},id:{type:"string",description:"ID of the element to remove"}},required:["purposeFile","section","id"]},annotations:{readOnlyHint:false,destructiveHint:true}},Da={name:"paradigm_purpose_rename",description:"Rename a symbol across ALL .purpose files in the project. Updates both definitions and references. ~200 tokens.",inputSchema:{type:"object",properties:{oldId:{type:"string",description:'Current symbol ID (e.g. "payment-service")'},newId:{type:"string",description:'New symbol ID (e.g. "billing-service")'},symbolType:{type:"string",enum:["#","^","!","$","~"],description:"Symbol type prefix"}},required:["oldId","newId","symbolType"]},annotations:{readOnlyHint:false,destructiveHint:false}},$a={name:"paradigm_portal_add_gate",description:"Add or update a gate (^) in portal.yaml. Creates portal.yaml if it doesn't exist. Strips ^ prefix. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Gate ID (e.g. "authenticated" or "^authenticated")'},description:{type:"string",description:"What this gate checks"},type:{type:"string",description:'Gate type (e.g. "auth", "role", "ownership")'},location:{type:"string",description:'Where the gate is checked in your code (e.g. "middleware", "route-handler")'},requires:{type:"array",items:{type:"string"},description:"Prerequisite gates"},check:{type:"string",description:'Expression to evaluate (e.g. "req.user != null")'},grants:{type:"array",items:{type:"string"},description:"What passing this gate grants access to"},emits:{type:"array",items:{type:"string"},description:"Signals emitted when gate is checked"},prizes:{type:"array",items:{type:"object",properties:{id:{type:"string"},oneTime:{type:"boolean"}},required:["id"]},description:"Side effects triggered on pass"}},required:["id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},Na={name:"paradigm_portal_add_route",description:"Add a route with gates to portal.yaml. Creates routes section if needed. ~100 tokens.",inputSchema:{type:"object",properties:{route:{type:"string",description:'Route path (e.g. "/api/users/:id")'},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method"},gates:{type:"array",items:{type:"string"},description:'Gate IDs to apply (e.g. ["^authenticated", "^user-owner"])'}},required:["route","method","gates"]},annotations:{readOnlyHint:false,destructiveHint:false}},Fa={name:"paradigm_purpose_validate",description:"Validate .purpose files and portal.yaml. Returns issues found. If no purposeFile specified, validates all files. ~200 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Specific .purpose file to validate (validates all if omitted)"},includePortal:{type:"boolean",description:"Also validate portal.yaml (default: true)"}}},annotations:{readOnlyHint:true,destructiveHint:false}};function ki(){return [xa,Pa,Ra,Ta,Ca,ja,Oa,Ia,Aa,Da,$a,Na,Fa]}async function _i(s,e,i,t){switch(s){case "paradigm_purpose_init":return Ha(e,i,t);case "paradigm_purpose_add_component":return Ea(e,i,t);case "paradigm_purpose_add_aspect":return qa(e,i,t);case "paradigm_purpose_add_signal":return La(e,i,t);case "paradigm_purpose_add_flow":return Ja(e,i,t);case "paradigm_purpose_add_gate":return Ma(e,i,t);case "paradigm_purpose_add_state":return Ga(e,i,t);case "paradigm_purpose_link":return Ua(e,i,t);case "paradigm_purpose_remove":return Wa(e,i,t);case "paradigm_purpose_rename":return za(e,i,t);case "paradigm_portal_add_gate":return Ba(e,i,t);case "paradigm_portal_add_route":return Va(e,i,t);case "paradigm_purpose_validate":return Ka(e,i);default:return {handled:false,text:""}}}function G(s){return {handled:true,text:JSON.stringify(s,null,2)}}function M(s){return {handled:true,text:JSON.stringify({error:s},null,2)}}async function Ha(s,e,i){let{purposeFile:t,name:r,description:n,context:o,version:c}=s,a=Y(t,e.rootDir),d=E(a);return c!==void 0?d.version=c:d.version||(d.version="1.0.0"),n!==void 0?d.description=n:d.description||(d.description=r),o!==void 0&&(d.context=o),me(a,d),await i(),G({action:"purpose_init",file:a,metadata:{name:r,description:d.description,version:d.version}})}async function Ea(s,e,i){let{purposeFile:t,id:r,description:n,section:o="components",file:c,status:a,endpoints:d,tests:l,flows:p,gates:g,signals:u,aspects:m,components:y,type:f,parent:v}=s,h=Y(t,e.rootDir),b=E(h),w=N(r),S=o,x=ke(b[S]),_=x[w]||{description:""};_.description=n,c!==void 0&&(_.file=c),a!==void 0&&(_.status=a),d!==void 0&&(_.endpoints=d),l!==void 0&&(_.tests=l),p!==void 0&&(_.flows=p.map(P=>F(P,"$"))),g!==void 0&&(_.gates=g.map(P=>F(P,"^"))),u!==void 0&&(_.signals=u.map(P=>F(P,"!"))),m!==void 0&&(_.aspects=m.map(P=>F(P,"~"))),y!==void 0&&(_.components=y.map(P=>F(P,"#"))),f!==void 0&&(_.type=f),v!==void 0&&(_.parent=F(v,"#")),x[w]=_,b[S]=x;let C=await _t(h,b,P=>{let j=P[S];return !j||typeof j!="object"||Array.isArray(j)?!1:w in j},S);return await i(),G({action:"add_component",file:C.path,section:S,id:w,symbol:`#${w}`,written:C.written,hashHint:C.hashHint,bytes:C.bytes})}async function qa(s,e,i){let{purposeFile:t,id:r,description:n,anchors:o,tags:c,appliesTo:a,enforcement:d}=s;if(!o||o.length===0)return M('Aspects (~) REQUIRE at least one code anchor. Provide anchors like ["src/middleware/audit.ts:15-35"].');let l=/^[^\s:]+:\d+(-\d+)?(,\d+)*$/;for(let f of o)if(!l.test(f))return M(`Invalid anchor format: "${f}". Expected format: "file.ts:15", "file.ts:15-20", or "file.ts:15,25,30".`);let p=Y(t,e.rootDir),g=$.dirname(p);for(let f of o){let v=f.replace(/:.*$/,""),h=$.resolve(g,v);if(!A.existsSync(h)){let b=$.resolve(e.rootDir,v);if(A.existsSync(b)){let w=$.relative(g,b),S=o.indexOf(f);o[S]=f.replace(v,w);}else return M(`Anchor file not found: "${v}". Anchors must be relative to the .purpose file directory (${g}).`)}}let u=E(p);(!u.aspects||Array.isArray(u.aspects))&&(u.aspects={});let m=N(r);u.aspects[m]={description:n,anchors:o,...c&&{tags:c},...a&&{"applies-to":a},...d&&{enforcement:d}},me(p,u);let y=E(p).aspects;return !y||Array.isArray(y)||!y[m]?M(`add_aspect write verification failed: aspect "${m}" not found in ${p} after write.`):(await i(),G({action:"add_aspect",file:p,id:m,symbol:`~${m}`,anchors:o}))}async function La(s,e,i){let{purposeFile:t,id:r,description:n,category:o,severity:c,emitters:a,related:d,data:l}=s,p=Y(t,e.rootDir),g=E(p);(!g.signals||Array.isArray(g.signals))&&(g.signals={});let u=N(r);g.signals[u]={description:n,...o&&{category:o},...c&&{severity:c},...a&&{emitters:a.map(y=>F(y,"#"))},...d&&{related:d},...l&&{data:l}},me(p,g);let m=E(p).signals;return !m||Array.isArray(m)||!m[u]?M(`add_signal write verification failed: signal "${u}" not found in ${p} after write.`):(await i(),G({action:"add_signal",file:p,id:u,symbol:`!${u}`}))}async function Ja(s,e,i){let{purposeFile:t,id:r,description:n,gates:o,signals:c,components:a,steps:d}=s,l=Y(t,e.rootDir),p=E(l),g=je(p.flows),u=N(r),m={description:n,...o&&{gates:o.map(f=>F(f,"^"))},...c&&{signals:c.map(f=>F(f,"!"))},...a&&{components:a.map(f=>F(f,"#"))},...d&&{steps:d}};return g[u]=m,p.flows=g,me(l,p),je(E(l).flows)[u]?(await i(),G({action:"add_flow",file:l,id:u,symbol:`$${u}`})):M(`add_flow write verification failed: flow "${u}" not found in ${l} after write.`)}async function Ma(s,e,i){let{purposeFile:t,id:r,description:n,requires:o,keys:c,signals:a}=s,d=Y(t,e.rootDir),l=E(d);(!l.gates||Array.isArray(l.gates))&&(l.gates={});let p=N(r);l.gates[p]={description:n,...o&&{requires:o},...c&&{keys:c},...a&&{signals:a.map(u=>F(u,"!"))}},me(d,l);let g=E(d).gates;return !g||Array.isArray(g)||!g[p]?M(`add_gate write verification failed: gate "${p}" not found in ${d} after write.`):(await i(),G({action:"add_gate",file:d,id:p,symbol:`^${p}`}))}async function Ga(s,e,i){let{purposeFile:t,id:r,description:n,type:o,default:c,properties:a}=s,d=Y(t,e.rootDir),l=E(d);(!l.states||Array.isArray(l.states))&&(l.states={});let p=N(r),g={description:n};o!==void 0&&(g.type=o),c!==void 0&&(g.default=c),a!==void 0&&(g.properties=a),l.states[p]=g,me(d,l);let u=E(d).states;return !u||Array.isArray(u)||!u[p]?M(`add_state write verification failed: state "${p}" not found in ${d} after write.`):(await i(),G({action:"add_state",file:d,id:p}))}async function Ua(s,e,i){let{purposeFile:t,componentId:r,section:n,signals:o,aspects:c,gates:a,flows:d,components:l}=s,p=Y(t,e.rootDir),g=E(p),u=N(r),m=n;if(!m){let b=ke(g.components),w=ke(g.features);if(u in b)m="components";else if(u in w)m="features";else return M(`Component "${u}" not found in components or features. Specify section explicitly.`)}let y=ke(g[m]);if(!(u in y))return M(`Component "${u}" not found in ${m} section.`);let f=y[u];o&&(f.signals=Oe(f.signals,o.map(b=>F(b,"!")))),a&&(f.gates=Oe(f.gates,a.map(b=>F(b,"^")))),d&&(f.flows=Oe(f.flows,d.map(b=>F(b,"$")))),l&&(f.components=Oe(f.components,l.map(b=>F(b,"#")))),c&&(f.aspects=Oe(f.aspects,c.map(b=>F(b,"~")))),y[u]=f,g[m]=y;let v=await _t(p,g,b=>{let w=b[m];return !w||typeof w!="object"||Array.isArray(w)?!1:u in w},m);await i();let h=[];return o&&h.push(`signals: ${o.join(", ")}`),c&&h.push(`aspects: ${c.join(", ")}`),a&&h.push(`gates: ${a.join(", ")}`),d&&h.push(`flows: ${d.join(", ")}`),l&&h.push(`components: ${l.join(", ")}`),G({action:"link",file:v.path,componentId:u,section:m,added:h,written:v.written,hashHint:v.hashHint,bytes:v.bytes})}async function Wa(s,e,i){let{purposeFile:t,section:r,id:n}=s,o=Y(t,e.rootDir),c=E(o),a=N(n);if(r==="flows"){let l=je(c.flows);if(!(a in l))return M(`Flow "${a}" not found in flows section.`);delete l[a],c.flows=l;}else if(r==="components"||r==="features"){let l=ke(c[r]);if(!(a in l))return M(`"${a}" not found in ${r} section.`);delete l[a],c[r]=l;}else {let l=c[r];if(!l||!(a in l))return M(`"${a}" not found in ${r} section.`);delete l[a];}let d=await _t(o,c,l=>{if(r==="flows"){let g=je(l.flows);return !(a in g)}let p=l[r];return !p||typeof p!="object"||Array.isArray(p)?!0:!(a in p)},r);return await i(),G({action:"remove",file:d.path,section:r,id:a,written:d.written,hashHint:d.hashHint,bytes:d.bytes})}async function za(s,e,i){let{oldId:t,newId:r,symbolType:n}=s,o=await mi(e.rootDir,t,r,n);return await i(),G({action:"rename",oldSymbol:`${n}${N(t)}`,newSymbol:`${n}${N(r)}`,filesModified:o.length,files:o})}async function Ba(s,e,i){let{id:t,description:r,type:n,location:o,requires:c,check:a,grants:d,emits:l,prizes:p}=s,g=await bi(e.rootDir,{id:t,description:r,type:n,location:o,requires:c,check:a,grants:d,emits:l,prizes:p});await i();let u=N(t);return G({action:"portal_add_gate",file:g.path,id:u,symbol:`^${u}`,written:g.written,hashHint:g.hashHint,bytes:g.bytes})}async function Va(s,e,i){let{route:t,method:r,gates:n}=s,o=await vi(e.rootDir,{route:t,method:r,gates:n});return await i(),G({action:"portal_add_route",file:o.path,route:`${r} ${t}`,gates:n,written:o.written,hashHint:o.hashHint,bytes:o.bytes})}var Ya=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi;function wi(s,e){let i=[];function t(n,o){if(typeof n=="string"){let c=n.match(Ya);if(c)for(let a of c)i.push({type:"warning",message:`Clarification needed: ${a}`,path:o});}}t(s.description,"description");let r=[{key:"components",items:s.components},{key:"features",items:s.features},{key:"gates",items:s.gates},{key:"signals",items:s.signals},{key:"aspects",items:s.aspects}];for(let n of r)if(n.items&&typeof n.items=="object")for(let[o,c]of Object.entries(n.items))c&&typeof c.description=="string"&&t(c.description,`${n.key}.${o}.description`);if(s.flows&&typeof s.flows=="object"){let n=Array.isArray(s.flows)?[]:Object.entries(s.flows);for(let[o,c]of n)c&&typeof c.description=="string"&&t(c.description,`flows.${o}.description`);}return i}async function Ka(s,e){let{purposeFile:i,includePortal:t=true}=s,r=[];if(i){let c=Y(i,e.rootDir),a=b$d(c);if(!a.data)r.push({file:c,valid:false,issues:a.errors.map(d=>({type:"error",message:d}))});else {let d=p$4(a.data,c);if(a.data.aspects)for(let[p,g]of Object.entries(a.data.aspects))(!g.anchors||g.anchors.length===0)&&(d.issues.push({type:"error",message:`Aspect "${p}" is missing required anchors`,path:`aspects.${p}`}),d.valid=false);let l=wi(a.data);d.issues.push(...l),r.push({file:c,valid:d.valid,issues:d.issues});}}else {let c=await f$8(e.rootDir);for(let a of c){let d=b$d(a);if(!d.data){r.push({file:a,valid:false,issues:d.errors.map(g=>({type:"error",message:g}))});continue}let l=p$4(d.data,a);if(d.data.aspects)for(let[g,u]of Object.entries(d.data.aspects))(!u.anchors||u.anchors.length===0)&&(l.issues.push({type:"error",message:`Aspect "${g}" is missing required anchors`,path:`aspects.${g}`}),l.valid=false);let p=wi(d.data);l.issues.push(...p),r.push({file:a,valid:l.valid,issues:l.issues});}}if(t){let{data:c,filePath:a}=Pt(e.rootDir),d=[];if(c.gates)for(let[l,p]of Object.entries(c.gates))p.description||d.push({type:"warning",message:`Gate "${l}" has no description`,path:`gates.${l}`}),p.prizes||d.push({type:"warning",message:`Gate "${l}" is missing prizes array (v2 requirement)`,path:`gates.${l}`});d.length>0&&r.push({file:a,valid:d.every(l=>l.type!=="error"),issues:d});}let n=r.reduce((c,a)=>c+a.issues.length,0),o=r.every(c=>c.valid);return G({action:"validate",valid:o,totalFiles:r.length,totalIssues:n,results:r})}var Xa={"missing-purpose":s=>`${s.target?`"${s.target}"`:"a directory"} is missing a .purpose file. Without it, agents cannot discover what this directory contains or which components live here. The stop hook will block if source files were modified in a directory with no .purpose. Fix: run paradigm_purpose_init for this directory, then add components with paradigm_purpose_add_component.`,"stale-purpose":s=>{let e=s.target?`"${s.target}"`:"a .purpose file",i=s.context?.ageHours!=null?` (${s.context.ageHours}h old)`:"";return `The .purpose file at ${e}${i} has not been updated since the last code change in its directory. Stale purposes mislead agents about what components exist, causing incorrect context injection. Fix: update the .purpose to reflect any added, removed, or changed components, then run paradigm_reindex.`},"missing-gate":s=>`${s.target?`"${s.target}"`:"a route or endpoint"} appears to require authentication or authorization but has no gate declared in portal.yaml. Gates are how Paradigm tracks security enforcement \u2014 missing gates mean agents cannot verify that the route is protected. Fix: add the gate to portal.yaml using paradigm_portal_add_route or paradigm_purpose_add_component with the appropriate gates array.`,"orphan-signal":s=>`${s.target?`"${s.target}"`:"a signal"} is emitted in code but not declared in any .purpose file. Undeclared signals cannot be traced by agents during ripple analysis, meaning downstream effects may be missed when the signal's emitter changes. Fix: add the signal to the nearest .purpose file under its component's signals array (e.g., signals: ["!${s.target||"event-name"}"]). `,"undocumented-flow":s=>`${s.target?`"${s.target}"`:"a multi-step flow"} spans multiple components but has no $flow declaration. Flows with 3 or more steps should be documented so agents can reason about the sequence end-to-end. Without a flow record, agents may implement duplicate logic or miss ordering constraints. Fix: add a flow entry to .paradigm/flows.yaml with the steps and participants.`,"aspect-drift":s=>`${s.target?`"${s.target}"`:"an aspect anchor"} has drifted \u2014 the code at the anchored location no longer matches the fingerprint recorded when the aspect was first applied. This means the aspect may no longer be enforced correctly at that site. Drift is common after refactors that move or rewrite anchored code. Fix: re-anchor the aspect at its new location using paradigm_aspect_anchor, then delete the stale anchor.`,"portal-mismatch":s=>`${s.target?`"${s.target}"`:"a portal.yaml entry"} has a mismatch between what portal.yaml declares and what the code enforces. This could mean a gate is declared but never applied in middleware, or code enforces a check that is not tracked in portal.yaml. Both directions create audit gaps. Fix: reconcile portal.yaml with actual middleware usage \u2014 run paradigm portal check to see specifics.`,"missing-test":s=>`${s.target?`"${s.target}"`:"a component"} has no associated test file. Agents are expected to write tests alongside every implementation. Missing tests increase regression risk and reduce confidence scores for the affected component. Fix: create a test file alongside the implementation (e.g., ${s.target?s.target.replace(/\.[^.]+$/,".test$&"):"component.test.ts"}).`,"uncovered-route":s=>`${s.target?`"${s.target}"`:"a route"} appears in the codebase but is not listed in portal.yaml. All routes \u2014 protected or public \u2014 should be tracked in portal.yaml so the full API surface is visible to agents and reviewers. Uncovered routes are invisible to ripple analysis and gate audits. Fix: add the route to portal.yaml with paradigm_portal_add_route.`,"broken-reference":s=>`${s.target?`"${s.target}"`:"a symbol reference"} references a symbol or file that no longer exists. Broken references in .purpose files cause agents to load stale context and may indicate a renamed or deleted component. Fix: update the reference to the new symbol name, or remove it if the component was deleted. Run paradigm_reindex after fixing to regenerate the scan index.`,"missing-description":s=>`${s.target?`"${s.target}"`:"a component or gate"} has no description. Descriptions are required for agents to understand purpose and context during context injection. Without descriptions, agents may misapply the component or skip it when it would have been relevant. Fix: add a description field to the component or gate entry in its .purpose or portal.yaml file.`,"enforcement-level-violation":s=>{let e=s.target?`"${s.target}"`:"a data category",i=s.context?.ring,t=s.context?.boundary;return `${e} is being transmitted across a boundary (${t||"unknown boundary"}) that exceeds its trust ring${i?` (Ring: ${i})`:""}. Data policy requires project-locked content to never leave the project boundary. This gap could expose internal compliance data externally. Fix: check the data-policy.yaml configuration and ensure the content category is listed in the deny_content for the relevant stream.`},"index-stale":s=>{let e=s.target?`"${s.target}"`:"the scan index",i=s.context?.ageHours,t=i!=null?` (${i} hours old)`:"";return `${e}${t} is stale. The scan index drives context injection, navigator, and ripple analysis. When the index is out of date, agents work from stale symbol maps and may miss recently added components or references. Fix: run paradigm_reindex (or "paradigm index") to regenerate the index.`}};function Qa(s,e){let i=Xa[s];return i?i({...e,type:s}):`Unknown check type "${s}" \u2014 no narration template available.`}function xi(s){let e=[],i=[],t=[];for(let o of s){let c=Qa(o.type,o),a=o.severity??"improvement",d={type:o.type,target:o.target,narration:c,severity:a};a==="blocking"?e.push(d):a==="note"?t.push(d):i.push(d);}let r=e.length+i.length+t.length,n=Za(e,i,t);return {gapCount:r,blocking:e,improvement:i,note:t,narrative:n}}function Za(s,e,i){let t=[],r=s.length+e.length+i.length;if(r===0)return "No gaps found. All enforcement checks passed.";if(t.push(`Found ${r} gap${r!==1?"s":""} across ${Si(s,e,i)} check type${Si(s,e,i)!==1?"s":""}.`),t.push(""),s.length>0){t.push(`BLOCKING (${s.length})`),t.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let n of s)t.push(`[${n.type}]${n.target?` \u2014 ${n.target}`:""}`),t.push(n.narration),t.push("");}if(e.length>0){t.push(`IMPROVEMENTS (${e.length})`),t.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let n of e)t.push(`[${n.type}]${n.target?` \u2014 ${n.target}`:""}`),t.push(n.narration),t.push("");}if(i.length>0){t.push(`NOTES (${i.length})`),t.push("\u2500\u2500\u2500\u2500\u2500\u2500");for(let n of i)t.push(`[${n.type}]${n.target?` \u2014 ${n.target}`:""}`),t.push(n.narration),t.push("");}return t.join(`
65
+ `).trimEnd()}function Si(s,e,i){let t=new Set;for(let r of [...s,...e,...i])t.add(r.type);return t.size}function _n(s){if(!s)return [];let e=s.gates;if(e==null)return [];if(Array.isArray(e))return e.map(i=>{if(i&&typeof i=="object"&&"id"in i&&typeof i.id=="string"){let t=i.id;return t.startsWith("^")?t.slice(1):t}return null}).filter(i=>i!==null);if(typeof e=="object")return Object.keys(e).map(i=>i.startsWith("^")?i.slice(1):i);throw new Error(`Invalid gateConfig.gates shape: expected Array or Record, got ${typeof e}`)}var tc=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,nc=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"],rc=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi];function Pi(){return [{name:"paradigm_pm_preflight",description:`REQUIRED before implementing features. Call with mode="plan" to get the right agents and cost estimate. Skipping this for complex tasks leads to missed security reviews and wasted tokens.
66
+
67
+ Runs pre-flight compliance checks: extracts affected symbols, runs ripple analysis, checks portal.yaml status, and suggests required agents. Returns affected symbols, ripple summary, gate recommendations, and suggested agents. ~300 tokens.`,inputSchema:{type:"object",properties:{task:{type:"string",description:"The task description to analyze for compliance requirements"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_pm_postflight",description:"Run after completing a task to check compliance. Verifies that new components, routes, and events are properly registered in .purpose files and portal.yaml. Flags unregistered symbols and uncaptured wisdom. Returns compliance checklist with pass/fail status for purpose files, portal.yaml, and wisdom capture. ~200 tokens.",inputSchema:{type:"object",properties:{filesModified:{type:"array",items:{type:"string"},description:"List of files modified during the task"},symbolsTouched:{type:"array",items:{type:"string"},description:'List of symbols (e.g., ["#auth-handler", "^authenticated"]) touched during the task'}},required:["filesModified","symbolsTouched"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Ri(s,e,i){switch(s){case "paradigm_pm_preflight":{let{task:t}=e,r=await sc(t,i),n=JSON.stringify(r,null,2);return a$1(n.length,s),{text:n,handled:true}}case "paradigm_pm_postflight":{let{filesModified:t,symbolsTouched:r}=e,n=oc(t,r,i),o=JSON.stringify(n,null,2);return a$1(o.length,s),{text:o,handled:true}}default:return {text:"",handled:false}}}async function sc(s,e){let i=s.toLowerCase(),t$1=s.match(tc)||[],r=[...new Set(t$1)],n=r.map(g=>{let u=t(e.index,g),m=u.length>0?u[0]:null;return {symbol:g,exists:!!m,type:m?.type,description:m?.description}}),o=n.filter(g=>g.exists).map(g=>{let u=x(e.index,g.symbol),m=new Set;for(let v of u){let h=x(e.index,v.symbol);for(let b of h)b.symbol!==g.symbol&&!u.find(w=>w.symbol===b.symbol)&&m.add(b.symbol);}let y=u.length+m.size,f="low";return y>10?f="high":y>3&&(f="medium"),{symbol:g.symbol,directDependents:u.length,indirectDependents:m.size,impact:f}}),c={exists:e.gateConfig!==null,gateCount:0,gates:[],routeCount:0};if(e.gateConfig){let g=_n(e.gateConfig);c.gateCount=g.length,c.gates=g.map(m=>`^${m}`);let u=e.gateConfig.routes;c.routeCount=u&&!Array.isArray(u)&&typeof u=="object"?Object.keys(u).length:0;}let a=nc.some(g=>i.includes(g)),d=[];n.some(g=>g.exists)&&d.push("ripple-analysis"),a&&d.push("portal-compliance"),r.some(g=>g.startsWith("^"))&&d.push("gate-validation"),r.some(g=>g.startsWith("!"))&&d.push("signal-registration"),d.push("purpose-coverage");let l=null,p=null;try{let g=g$5(e.rootDir),m=j$1().getStats(),y=[...new Set(m.toolCalls.map(b=>b.toolName))],f=n$5({toolsCalled:y,filesModified:[],symbolsTouched:r,loreRecorded:!1,hasPortalRoutes:c.exists&&c.routeCount>0,taskAddsRoutes:a,taskDescription:s}),v=m$4(g,"preflight",f,void 0,e.rootDir);l={total:v.summary.total,followed:v.summary.followed,skipped:v.summary.skipped,partial:v.summary.partial,results:v.evaluations.map(b=>({id:b.habit.id,name:b.habit.name,severity:b.habit.severity,result:b.result,reason:b.reason}))};let h=new Date(Date.now()-720*60*60*1e3).toISOString();p=await s$2(e.rootDir,{dateFrom:h});}catch{}return {task:s.slice(0,100)+(s.length>100?"...":""),affectedSymbols:n,rippleAnalysis:o,portalStatus:c,taskAddsRoutes:a,requiredChecks:d,recommendations:ic(n,o,c,a),habits:{evaluation:l,recentCompliance:p?{rate:p.rate,totalEvents:p.total}:null}}}function ic(s,e,i,t){let r=[],n=s.filter(a=>!a.exists);n.length>0&&r.push(`New symbols detected: ${n.map(a=>a.symbol).join(", ")}. Register in .purpose files after implementation.`);let o=e.filter(a=>a.impact==="high");o.length>0&&r.push(`HIGH IMPACT: ${o.map(a=>a.symbol).join(", ")} \u2014 review all dependents before modifying.`),t&&!i.exists?r.push("Task adds routes but no portal.yaml exists. Create one with appropriate ^gates."):t&&r.push("Task adds routes. Update portal.yaml with gate entries after implementation.");let c=s.filter(a=>a.symbol.startsWith("^")&&!a.exists);return c.length>0&&r.push(`New gates referenced: ${c.map(a=>a.symbol).join(", ")}. Add to portal.yaml.`),r}function oc(s,e,i){let t$1=[],r$1=i.gateConfig?.routes,n=r$1&&!Array.isArray(r$1)&&typeof r$1=="object"?Object.keys(r$1):[];for(let m of s){let y=$.isAbsolute(m)?m:$.join(i.rootDir,m);if(!A.existsSync(y))continue;let f;try{f=A.readFileSync(y,"utf-8");}catch{continue}for(let v of rc){v.lastIndex=0;let h;for(;(h=v.exec(f))!==null;){let b=h[2]||h[0];b&&b.startsWith("/")&&(!n.some(S=>S.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===b)&&i.gateConfig?t$1.push({type:"missing-portal-gate",severity:"warning",message:`Route "${b}" in ${$.relative(i.rootDir,y)} not in portal.yaml`,file:$.relative(i.rootDir,y),suggestion:"Add route to portal.yaml with ^gates. Use paradigm_gates_for_route for suggestions."}):!i.gateConfig&&b.startsWith("/api/")&&t$1.push({type:"missing-portal-gate",severity:"warning",message:`API route "${b}" found but no portal.yaml exists`,file:$.relative(i.rootDir,y),suggestion:"Create portal.yaml to declare gates for API routes."}));}}}for(let m of e)t(i.index,m).length===0&&t$1.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${m}" is not registered in any .purpose file`,suggestion:"Add to nearest .purpose file using paradigm_purpose_add_component or paradigm_purpose_add_signal."});let o=_n(i.gateConfig);for(let m of e)if(m.startsWith("^")){let y=m.slice(1);o.includes(y)||t$1.push({type:"missing-portal-gate",severity:"error",message:`Gate "${m}" referenced but not declared in portal.yaml`,suggestion:`Add ${m} to portal.yaml with description and check expression.`});}for(let m of J$1(i.index,e,i.rootDir))t$1.push({type:"stale-aspect",severity:"warning",message:m.kind==="no-anchors"?`Aspect "${m.aspectSymbol}" has no code anchors`:`Aspect "${m.aspectSymbol}" anchor "${m.anchorRaw}" points to missing file`,suggestion:m.kind==="no-anchors"?`Add anchors to ${m.aspectSymbol} in .purpose file. Run paradigm_aspect_check for details.`:`Update anchors for ${m.aspectSymbol} in .purpose file.`});let c=r(i.index,"aspect");for(let m of c){let y=m.appliesTo||[];if(y.length!==0)for(let f of e){if(!f.startsWith("#"))continue;(m.data||{}).aspects||[];for(let b of y){if(!b.includes("*"))continue;if(new RegExp("^"+b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(f))break}}}s.length>=5&&e.length>=3&&t$1.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${s.length} files, ${e.length} symbols) \u2014 consider recording decisions`,suggestion:"Use paradigm_wisdom_record to capture architectural decisions or antipatterns."});for(let m of e){let y=t(i.index,m);if(y.length===0)continue;let f=y[0];f.parentSymbol&&t(i.index,f.parentSymbol).length===0&&t$1.push({type:"broken-reference",severity:"warning",message:`Symbol "${m}" references parent "${f.parentSymbol}" which does not exist`,suggestion:"Create the parent symbol or update the parent reference in the .purpose file."});}let a=t$1.filter(m=>m.severity==="error").length,d=t$1.filter(m=>m.severity==="warning").length,l="pass";a>0?l="violations":d>0&&(l="warnings");let p=null;try{let m=g$5(i.rootDir),f=j$1().getStats(),v=[...new Set(f.toolCalls.map(_=>_.toolName))],h=v.includes("paradigm_lore_record"),b;try{b=execSync("git status --porcelain",{cwd:i.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let w=n$5({toolsCalled:v,filesModified:s,symbolsTouched:e,loreRecorded:h,hasPortalRoutes:i.gateConfig!==null&&i.gateConfig.routes!=null,taskAddsRoutes:!1,gitClean:b}),S=m$4(m,"postflight",w,void 0,i.rootDir);p={trigger:"postflight",total:S.summary.total,followed:S.summary.followed,skipped:S.summary.skipped,partial:S.summary.partial,blockingViolations:S.summary.blockingViolations,results:S.evaluations.map(_=>({id:_.habit.id,name:_.habit.name,severity:_.habit.severity,result:_.result,reason:_.reason}))};let x=$.join(i.rootDir,".paradigm",".habits-blocking");if(S.blocksCompletion){let _=S.evaluations.filter(C=>C.result==="skipped"&&C.habit.severity==="block").map(C=>`${C.habit.name}: ${C.reason}`);A.writeFileSync(x,_.join(`
68
+ `),"utf8");}else A.existsSync(x)&&A.unlinkSync(x);}catch{}let g=t$1.map(m=>({type:{"missing-purpose":"missing-purpose","missing-portal-gate":"missing-gate","unregistered-symbol":"missing-purpose","uncaptured-wisdom":"missing-description","stale-aspect":"aspect-drift","broken-reference":"broken-reference"}[m.type]??"missing-description",target:m.file||m.message.slice(0,80),severity:m.severity==="error"?"blocking":"improvement"})),u=g.length>0?xi(g):null;return {status:l,violations:t$1,summary:{totalChecks:7,passed:7-(a>0?1:0)-(d>0?1:0),warnings:d,errors:a},blocksCompletion:a>0,habitsEvaluation:p,...u?{narrations:u}:{}}}function Ci(){return [{name:"paradigm_habits_list",description:"List all habit definitions: seed (built-in), global (~/.paradigm/habits.yaml), and project (.paradigm/habits.yaml). Shows what habits exist, their triggers, severity, and enabled state. Use to discover available habits before evaluating them. Returns habit definitions with id, check type, trigger, severity, category, and enabled state. ~300 tokens.",inputSchema:{type:"object",properties:{trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"],description:"Filter by trigger point"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"],description:"Filter by category"},enabled:{type:"boolean",description:"Filter by enabled state (default: show all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_habits_check",description:"Evaluate habit compliance for the current session and record practice events. Call at preflight (before implementing), postflight (after implementing), or on-stop (session end). Returns which habits were followed, skipped, or partially met. Returns per-habit follow/skip/partial results and blocking status. ~200 tokens.",inputSchema:{type:"object",properties:{trigger:{type:"string",enum:["preflight","postflight","on-stop","on-commit"],description:"When to evaluate: preflight (before task), postflight (after task), on-stop (session end)"},filesModified:{type:"array",items:{type:"string"},description:"Files modified during the session/task"},symbolsTouched:{type:"array",items:{type:"string"},description:"Symbols touched during the session/task"},taskDescription:{type:"string",description:"Description of the task being performed"},record:{type:"boolean",description:"Whether to record practice events (default: true)"}},required:["trigger"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_status",description:"View practice profile: compliance rates by category, trends, and incident correlations. Shows how well habits are being followed over time. Returns overall rate, per-category rates, trend direction, and incident correlations. ~200 tokens.",inputSchema:{type:"object",properties:{engineer:{type:"string",description:"Filter by engineer name (default: all)"},period:{type:"string",enum:["7d","30d","90d","all"],description:"Time period for analysis (default: 30d)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_practice_context",description:"Get proactive practice warnings before modifying symbols. Shows recent compliance gaps and team-aware suggestions. Call this alongside paradigm_wisdom_context for full context. Returns relevant habits, compliance gaps, and behavioral suggestions. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:"Symbols about to be modified"},task:{type:"string",description:"Description of the upcoming task"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_habits_add",description:'Create a new custom habit as an individual .habit file. Validates all fields and checks for ID collisions with seed habits. Use scope "global" for ~/.paradigm/habits/ or "project" (default) for .paradigm/habits/. ~150 tokens.',inputSchema:{type:"object",properties:{id:{type:"string",description:'Unique habit ID in kebab-case (e.g. "check-changelog")'},name:{type:"string",description:"Human-readable habit name"},description:{type:"string",description:"What this habit checks and why"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"],description:"Habit category"},trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"],description:"When the habit is evaluated"},severity:{type:"string",enum:["advisory","warn","block"],description:"How strictly to enforce (block prevents session completion)"},check:{type:"object",description:"Check definition with type and params",properties:{type:{type:"string",enum:["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"]},params:{type:"object",description:"Check-specific parameters (tools[], patterns[], etc.)"}},required:["type","params"]},enabled:{type:"boolean",description:"Whether the habit is active (default: true)"},platforms:{type:"array",items:{type:"string"},description:'Platforms this habit applies to (e.g. ["claude", "cursor"]). Omit for all.'},scope:{type:"string",enum:["project","global"],description:'Where to save: "project" (default) or "global" (~/.paradigm/habits/)'}},required:["id","name","description","category","trigger","severity","check"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_edit",description:"Update fields on an existing custom .habit file. Cannot edit seed habits \u2014 use overrides in habits.yaml instead. Merges provided fields with existing definition and re-validates. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"ID of the habit to edit"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"]},trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"]},severity:{type:"string",enum:["advisory","warn","block"]},check:{type:"object",properties:{type:{type:"string"},params:{type:"object"}},required:["type","params"]},enabled:{type:"boolean"},platforms:{type:"array",items:{type:"string"}}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_remove",description:"Delete a custom .habit file. Cannot remove seed habits \u2014 use overrides to disable them instead. Searches both project and global habit directories. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"ID of the habit to remove"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function ji(s,e,i){switch(s){case "paradigm_habits_list":{let t=cc(e,i);return a$1(t.length,s),{text:t,handled:true}}case "paradigm_habits_check":{let t=await dc(e,i);return a$1(t.length,s),{text:t,handled:true}}case "paradigm_habits_status":{let t=await fc(e,i);return a$1(t.length,s),{text:t,handled:true}}case "paradigm_practice_context":{let t=await mc(e,i);return a$1(t.length,s),{text:t,handled:true}}case "paradigm_habits_add":{let t=pc(e,i);return a$1(t.length,s),{text:t,handled:true}}case "paradigm_habits_edit":{let t=uc(e,i);return a$1(t.length,s),{text:t,handled:true}}case "paradigm_habits_remove":{let t=gc(e,i);return a$1(t.length,s),{text:t,handled:true}}default:return {text:"",handled:false}}}function cc(s,e){let i=s.trigger,t=s.category,r=s.enabled,n=g$5(e.rootDir);i&&(n=n.filter(c=>c.trigger===i)),t&&(n=n.filter(c=>c.category===t)),r!==void 0&&(n=n.filter(c=>c.enabled===r));let o={};for(let c of n)o[c.trigger]||(o[c.trigger]=[]),o[c.trigger].push(c);return JSON.stringify({total:n.length,filters:Object.fromEntries(Object.entries({trigger:i,category:t,enabled:r}).filter(([,c])=>c!==void 0)),byTrigger:Object.fromEntries(Object.entries(o).map(([c,a])=>[c,a.map(d=>({id:d.id,name:d.name,description:d.description,category:d.category,severity:d.severity,enabled:d.enabled,check:{type:d.check.type,params:d.check.params},platforms:d.platforms||null}))]))},null,2)}async function dc(s,e){let i=s.trigger,t=s.filesModified||[],r=s.symbolsTouched||[],n=s.taskDescription,o=s.record!==false,c=g$5(e.rootDir),a=j$1(),d=a.getStats(),l=[...new Set(d.toolCalls.map(S=>S.toolName))],p=l.includes("paradigm_lore_record"),g=(n||"").toLowerCase(),u=["endpoint","route","api","handler","get","post","put","patch","delete"].some(S=>g.includes(S)),m;try{m=execSync("git status --porcelain",{cwd:e.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let y=n$5({toolsCalled:l,filesModified:t,symbolsTouched:r,loreRecorded:p,hasPortalRoutes:e.gateConfig!==null&&e.gateConfig.routes!=null,taskAddsRoutes:u,taskDescription:n,gitClean:m}),v=m$4(c,i,y,"claude",e.rootDir),h=[];if(o&&v.evaluations.length>0)try{let S=a.getLastLoreEntryId()??void 0;h=await u$1(e.rootDir,v.evaluations.map(x=>({habitId:x.habit.id,habitCategory:x.habit.category,result:x.result,notes:x.reason})),{engineer:"agent",sessionId:d.sessionId,loreEntryId:S,taskDescription:n,symbolsTouched:r,filesModified:t});}catch{}let b=$.join(e.rootDir,".paradigm",".habits-blocking");try{if(i==="on-stop"&&v.blocksCompletion){let S=v.evaluations.filter(x=>x.result==="skipped"&&x.habit.severity==="block").map(x=>`${x.habit.name}: ${x.reason}`);A.writeFileSync(b,S.join(`
69
+ `),"utf8");}else i==="on-stop"&&A.existsSync(b)&&A.unlinkSync(b);}catch{}let w=l$5;return JSON.stringify({trigger:i,evaluation:{total:v.summary.total,followed:v.summary.followed,skipped:v.summary.skipped,partial:v.summary.partial,blockingViolations:v.summary.blockingViolations,blocksCompletion:v.blocksCompletion},...w>0?{graduatedToHooks:w,graduatedNote:`${w} habit(s) enforced by hooks (zero context cost). Not re-evaluated here.`}:{},habits:v.evaluations.map(S=>({id:S.habit.id,name:S.habit.name,category:S.habit.category,severity:S.habit.severity,result:S.result,reason:S.reason,evidence:S.evidence})),recorded:o?h.length:0,recommendations:lc(v)},null,2)}function lc(s){let e=[];for(let i of s.evaluations)if(i.result==="skipped")switch(i.habit.id){case "explore-before-implement":case "ripple-before-modify":e.push("Call paradigm_ripple or paradigm_navigate before modifying symbols.");break;case "check-fragility":e.push("Call paradigm_history_fragility to check for fragile symbols.");break;case "wisdom-before-implement":e.push("Call paradigm_wisdom_context to check team preferences and antipatterns.");break;case "verify-before-done":e.push("Call paradigm_pm_postflight to verify compliance before finishing.");break;case "record-lore-for-significant":e.push("Call paradigm_lore_record to document this session.");break;case "gates-for-routes":e.push("Call paradigm_gates_for_route and update portal.yaml for new routes.");break;case "purpose-coverage":e.push("Update .purpose files using paradigm_purpose_add_component.");break;case "changelog-updated":e.push("Update CHANGELOG.md with the changes made in this phase.");break;case "changes-committed":e.push("Commit all changes to git before finishing this phase.");break;default:e.push(`${i.habit.name}: ${i.reason}`);}return [...new Set(e)]}function pc(s,e){let i=s.id,t=s.scope||"project";if(i$7(i))return JSON.stringify({error:true,message:`Cannot create habit "${i}" \u2014 it collides with a seed habit. Choose a different ID or use overrides in habits.yaml to customize the seed habit.`},null,2);if(g$5(e.rootDir).find(d=>d.id===i))return JSON.stringify({error:true,message:`Habit "${i}" already exists. Use paradigm_habits_edit to update it, or choose a different ID.`},null,2);let o={id:i,name:s.name,description:s.description,category:s.category,trigger:s.trigger,severity:s.severity,check:s.check,enabled:s.enabled!==void 0?s.enabled:true};s.platforms&&(o.platforms=s.platforms);let c=h$8(o);if(!c.valid)return JSON.stringify({error:true,message:"Validation failed",errors:c.errors},null,2);let a=j$6(e.rootDir,o,t);return JSON.stringify({created:true,id:o.id,filePath:a,scope:t,message:`Habit "${o.name}" created at ${a}`},null,2)}function uc(s,e){let i=s.id;if(i$7(i))return JSON.stringify({error:true,message:`Cannot edit "${i}" \u2014 it is a seed habit. To customize it, add an override in .paradigm/habits.yaml under the "overrides:" key.`},null,2);let t=$.join(e.rootDir,".paradigm","habits",`${i}.habit`),r=process.env.HOME||process.env.USERPROFILE||"~",n=$.join(r,".paradigm","habits",`${i}.habit`),o=null,c="project";if(A.existsSync(t)?(o=t,c="project"):A.existsSync(n)&&(o=n,c="global"),!o)return JSON.stringify({error:true,message:`No .habit file found for "${i}". It may be defined in habits.yaml \u2014 edit that file directly.`},null,2);let a;try{let p=A.readFileSync(o,"utf8");a=Ie.load(p);}catch{return JSON.stringify({error:true,message:`Failed to read ${o}`},null,2)}let d={...a};s.name!==void 0&&(d.name=s.name),s.description!==void 0&&(d.description=s.description),s.category!==void 0&&(d.category=s.category),s.trigger!==void 0&&(d.trigger=s.trigger),s.severity!==void 0&&(d.severity=s.severity),s.check!==void 0&&(d.check=s.check),s.enabled!==void 0&&(d.enabled=s.enabled),s.platforms!==void 0&&(d.platforms=s.platforms);let l=h$8(d);return l.valid?(j$6(e.rootDir,d,c),JSON.stringify({updated:true,id:d.id,filePath:o,message:`Habit "${d.name}" updated`},null,2)):JSON.stringify({error:true,message:"Validation failed after merge",errors:l.errors},null,2)}function gc(s,e){let i=s.id,t=k$3(e.rootDir,i);return t.removed?JSON.stringify({removed:true,id:i,message:`Habit "${i}" removed`},null,2):JSON.stringify({error:true,message:t.reason},null,2)}async function fc(s,e){let i=s.engineer,t=s.period||"30d",r=new Date,n;if(t!=="all"){let h=parseInt(t.replace("d",""),10)||30;n=new Date(r.getTime()-h*24*60*60*1e3).toISOString();}let o={engineer:i,dateFrom:n},c=await s$2(e.rootDir,o),a=await t$3(e.rootDir,o),d=await r$3(e.rootDir,{...o,limit:200}),l=new Map;for(let h of d){let b=l.get(h.habitId)||{followed:0,skipped:0,partial:0},w=h.result;b[w]++,l.set(h.habitId,b);}let p=null,g=null,u=-1,m=101;for(let h of a)h.rate>u&&(u=h.rate,p=h.category),h.rate<m&&(m=h.rate,g=h.category);let y=g$5(e.rootDir),f=new Map(y.map(h=>[h.id,h.name])),v=Array.from(l.entries()).map(([h,b])=>{let w=b.followed+b.skipped+b.partial,S=w>0?Math.round((b.followed+b.partial*.5)/w*100):100;return {habitId:h,habitName:f.get(h)||h,...b,total:w,rate:S}}).sort((h,b)=>h.rate-b.rate);return JSON.stringify({period:t,engineer:i||"all",overall:{totalEvents:c.total,complianceRate:c.rate,followed:c.followed,skipped:c.skipped,partial:c.partial,strongestCategory:p,weakestCategory:g},byCategory:a.map(h=>({category:h.category,rate:h.rate,total:h.total,followed:h.followed,skipped:h.skipped,partial:h.partial})),byHabit:v,activeHabits:y.filter(h=>h.enabled).length,totalHabits:y.length},null,2)}async function mc(s,e){let i=s.symbols||[],t=s.task,n=g$5(e.rootDir).filter(m=>m.enabled&&m.trigger==="preflight"),c=j$1().getStats(),a=[...new Set(c.toolCalls.map(m=>m.toolName))],d=[];for(let m of n)if(m.check.type==="tool-called"){let y=m.check.params.tools||[];!y.some(v=>a.includes(v))&&i.length>0&&d.push({habitId:m.id,habitName:m.name,category:m.category,severity:m.severity,message:`${m.name}: ${m.description}`,suggestion:`Call one of: ${y.join(", ")}`});}let l=new Date(Date.now()-720*60*60*1e3).toISOString(),p=await s$2(e.rootDir,{dateFrom:l}),u=(await t$3(e.rootDir,{dateFrom:l})).filter(m=>m.rate<60).map(m=>m.category);return JSON.stringify({symbols:i,task:t||null,warnings:d,recentCompliance:{rate:p.rate,totalEvents:p.total,weakAreas:u},preflightReminders:d.length>0?`${d.length} habit(s) not yet followed this session. See warnings above.`:"All preflight habits satisfied."},null,2)}f();b$1();async function Oi(s){let e=c$6(s);if(!e.enabled)return [];let i=g$5(s),t=[];for(let r of i){if(!r.enabled)continue;let n=await yc(s,r,e);t.push(n);}return t}async function yc(s,e,i){let t=d$c(s,e.id),r={habitId:e.id,habitName:e.name,currentTier:t.tier,neverGraduate:false,inCooldown:false};if(t.tier==="hook")return {...r,eligible:false,reason:"Already graduated to hook"};if(t.neverGraduate||i.neverGraduate.includes(e.id))return {...r,eligible:false,reason:"Marked as never-graduate (requires agent cognition)",neverGraduate:true};if(a$e.has(e.check.type))return {...r,eligible:false,reason:`Check type "${e.check.type}" cannot graduate \u2014 requires MCP tool output`,neverGraduate:true};if(t.cooldownUntil&&new Date(t.cooldownUntil)>new Date)return {...r,eligible:false,reason:`In cooldown until ${t.cooldownUntil.split("T")[0]} (demoted recently)`,inCooldown:true};let{thresholds:n}=i,o=new Date;o.setDate(o.getDate()-n.timeWindowDays);try{let c=await s$2(s,{habitId:e.id,dateFrom:o.toISOString()});if(c.total<n.minEvents)return {...r,eligible:!1,reason:`Insufficient data: ${c.total}/${n.minEvents} events in ${n.timeWindowDays}d window`,complianceRate:c.rate,eventCount:c.total};if(c.rate<n.minComplianceRate)return {...r,eligible:!1,reason:`Compliance ${c.rate.toFixed(0)}% < ${n.minComplianceRate}% threshold`,complianceRate:c.rate,eventCount:c.total};let a=new Date;return a.setDate(a.getDate()-n.recencyDays),(await s$2(s,{habitId:e.id,dateFrom:a.toISOString()})).total===0?{...r,eligible:!1,reason:`No events in last ${n.recencyDays} days \u2014 habit may be dormant`,complianceRate:c.rate,eventCount:c.total}:{...r,eligible:!0,reason:`Ready: ${c.rate.toFixed(0)}% compliance over ${c.total} events in ${n.timeWindowDays}d`,complianceRate:c.rate,eventCount:c.total}}catch{return {...r,eligible:false,reason:"Unable to query practice events (Sentinel DB unavailable)"}}}function Ii(s){let e=g$5(s),i=c$6(s),t=e$c(s),r=0,n=0,o=0,c=0;for(let a of e){if(!a.enabled)continue;let d=t[a.id],l=d?.tier||"habit",p=d?.neverGraduate||i.neverGraduate.includes(a.id)||a$e.has(a.check.type);l==="hook"?r++:l==="mcp"?o++:n++,p&&c++;}return {hookCount:r,habitCount:n,mcpCount:o,neverGraduateCount:c,states:t}}f();var hc=[{name:"paradigm_graduate_check",description:"Check which habits are eligible for graduation from habit tier to hook tier. Returns eligibility status for each habit with compliance data and reasoning. ~300 tokens.",inputSchema:{type:"object",properties:{habitId:{type:"string",description:"Check a specific habit by ID. Omit to check all."}}}},{name:"paradigm_graduate_status",description:"Show the current automation tier of every habit. Returns tier map grouped by hook/habit/mcp with graduation dates and savings estimate. ~200 tokens.",inputSchema:{type:"object",properties:{}}}];async function bc(s,e){let i=await Oi(s.rootDir),t=i;if(e.habitId&&(t=i.filter(c=>c.habitId===e.habitId),t.length===0))return JSON.stringify({error:`No habit found with ID "${e.habitId}"`});let r=t.filter(c=>c.eligible),n=t.filter(c=>!c.eligible&&!c.neverGraduate),o=t.filter(c=>c.neverGraduate);return JSON.stringify({summary:{checked:t.length,eligible:r.length,ineligible:n.length,neverGraduate:o.length},...r.length>0?{eligible:r.map(Ai),action:"Run `paradigm graduate promote <id>` to graduate eligible habits."}:{},...n.length>0?{ineligible:n.map(Ai)}:{},...o.length>0?{neverGraduate:o.map(c=>({id:c.habitId,name:c.habitName,reason:c.reason}))}:{}},null,2)}async function vc(s){let e=Ii(s.rootDir),i=c$6(s.rootDir),t={hook:[],habit:[],mcp:[]};for(let[r,n]of Object.entries(e.states)){let o=n.tier||"habit";t[o]||(t[o]=[]),t[o].push({id:r,...n.graduatedAt?{graduatedAt:n.graduatedAt}:{},...n.neverGraduate?{neverGraduate:true}:{}});}return JSON.stringify({tiers:{hook:e.hookCount,habit:e.habitCount,mcp:e.mcpCount},neverGraduate:e.neverGraduateCount,estimatedSavingsPerSession:`~${e.hookCount*150} tokens`,byTier:t,thresholds:i.thresholds},null,2)}function Di(){return hc}async function $i(s,e,i){switch(s){case "paradigm_graduate_check":return {handled:true,text:await bc(i,e)};case "paradigm_graduate_status":return {handled:true,text:await vc(i)};default:return {handled:false,text:""}}}function Ai(s){return {id:s.habitId,name:s.habitName,tier:s.currentTier,reason:s.reason,...s.complianceRate!==void 0?{complianceRate:s.complianceRate}:{},...s.eventCount!==void 0?{eventCount:s.eventCount}:{},...s.inCooldown?{inCooldown:true}:{}}}var Ni=new Set(["the","a","an","is","how","does","what","why","when","where","do","can","will","should","would","could","are","was","were","been","being","have","has","had","this","that","it","its","of","in","to","for","with","on","at","by","from","or","and","but","not"]),wc=.95,kc=.3,_c=10;function Sc(s,e){let i=s.length,t=e.length;if(i===0)return t;if(t===0)return i;let r=Array.from({length:i+1},()=>Array.from({length:t+1},()=>0));for(let n=0;n<=i;n++)r[n][0]=n;for(let n=0;n<=t;n++)r[0][n]=n;for(let n=1;n<=i;n++)for(let o=1;o<=t;o++){let c=s[n-1]===e[o-1]?0:1;r[n][o]=Math.min(r[n-1][o]+1,r[n][o-1]+1,r[n-1][o-1]+c);}return r[i][t]}function Fi(s){let e=s.toLowerCase().split(/\s+/).filter(i=>i.length>0&&!Ni.has(i));return e.sort(),e.join(" ")}function xc(s){try{let e=s.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'aspects_fts'");return e.length>0&&e[0].values.length>0}catch{return false}}function Hi(s,e,i){let t=i?.limit??_c,r=Fi(e);if(r.length===0)return [];let n=Pc(s,r,i);if(n.length>0)return n.slice(0,t);if(xc(s)){let c=Rc(s,r,i);if(c.length>0)return c.slice(0,t)}return Tc(s,r,i).slice(0,t)}function Pc(s,e,i){try{let t=`
70
+ SELECT
71
+ a.id, a.description, a.category, a.severity, a.tags,
72
+ sw.weight,
73
+ (SELECT COUNT(*) FROM anchors anc WHERE anc.aspect_id = a.id) AS anchor_count
74
+ FROM search_weights sw
75
+ JOIN aspects a ON sw.aspect_id = a.id
76
+ WHERE sw.query_normalized LIKE ? || '%'
77
+ `,r=[e];i?.category&&(t+=" AND a.category = ?",r.push(i.category)),i?.severity&&(t+=" AND a.severity = ?",r.push(i.severity)),t+=" ORDER BY sw.weight DESC";let n=s.prepare(t);n.bind(r);let o=[];for(;n.step();){let c=n.getAsObject();o.push({id:c.id,description:c.description,category:c.category||void 0,severity:c.severity||void 0,score:c.weight,tier:1,tags:c.tags?Sn(c.tags):void 0,anchorCount:c.anchor_count});}return n.free(),o}catch{return []}}function Rc(s,e,i){try{let t=e.split(/\s+/).filter(a=>a.length>0).map(a=>`"${a}"*`).join(" ");if(t.length===0)return [];let r=`
78
+ SELECT
79
+ a.id, a.description, a.category, a.severity, a.tags,
80
+ rank AS fts_rank,
81
+ (SELECT COUNT(*) FROM anchors anc WHERE anc.aspect_id = a.id) AS anchor_count
82
+ FROM aspects_fts fts
83
+ JOIN aspects a ON fts.rowid = a.rowid
84
+ WHERE aspects_fts MATCH ?
85
+ `,n=[t];i?.category&&(r+=" AND a.category = ?",n.push(i.category)),i?.severity&&(r+=" AND a.severity = ?",n.push(i.severity)),r+=" ORDER BY rank";let o=s.prepare(r);o.bind(n);let c=[];for(;o.step();){let a=o.getAsObject(),d=Math.abs(a.fts_rank);c.push({id:a.id,description:a.description,category:a.category||void 0,severity:a.severity||void 0,score:d,tier:2,tags:a.tags?Sn(a.tags):void 0,anchorCount:a.anchor_count});}return o.free(),c}catch{return []}}function Tc(s,e,i){try{let t=`
86
+ SELECT
87
+ a.id, a.description, a.category, a.severity, a.tags,
88
+ (SELECT COUNT(*) FROM anchors anc WHERE anc.aspect_id = a.id) AS anchor_count
89
+ FROM aspects a
90
+ WHERE 1=1
91
+ `,r=[];i?.category&&(t+=" AND a.category = ?",r.push(i.category)),i?.severity&&(t+=" AND a.severity = ?",r.push(i.severity));let n=s.prepare(t);n.bind(r);let o=[];for(;n.step();){let a=n.getAsObject();o.push({id:a.id,description:a.description,category:a.category,severity:a.severity,tags:a.tags,anchorCount:a.anchor_count});}n.free();let c=[];for(let a of o){let d=Cc(e,a.id,a.description);d>kc&&c.push({id:a.id,description:a.description,category:a.category||void 0,severity:a.severity||void 0,score:d,tier:3,tags:a.tags?Sn(a.tags):void 0,anchorCount:a.anchorCount});}return c.sort((a,d)=>d.score-a.score),c}catch{return []}}function Cc(s,e,i){let r=[(e.startsWith("~")?e.slice(1):e).toLowerCase()],n=i.toLowerCase().split(/\s+/).filter(a=>a.length>0&&!Ni.has(a));r.push(...n);let o=s.split(/\s+/).filter(a=>a.length>0);if(o.length===0)return 0;let c=0;for(let a of o){let d=0;for(let l of r){let g=1/(1+Sc(a,l));g>d&&(d=g);}c+=d;}return c/o.length}function Ei(s,e,i){let t=Fi(e),r=new Date().toISOString();try{s.run(`INSERT INTO search_log (query, results, selected, timestamp)
92
+ VALUES (?, ?, ?, ?)`,[e,JSON.stringify([i]),i,r]);}catch{}try{s.run(`INSERT INTO search_weights (query_normalized, aspect_id, weight, hit_count, last_hit)
93
+ VALUES (?, ?, 1.0, 1, ?)
94
+ ON CONFLICT(query_normalized, aspect_id) DO UPDATE SET
95
+ weight = weight + 1.0,
96
+ hit_count = hit_count + 1,
97
+ last_hit = ?`,[t,i,r,r]);}catch{return}try{s.run(`UPDATE search_weights
98
+ SET weight = weight * ?
99
+ WHERE query_normalized = ? AND aspect_id != ?`,[wc,t,i]);}catch{}}function Sn(s){try{let e=JSON.parse(s);return Array.isArray(e)&&e.length>0?e:void 0}catch{let e=s.split(",").map(i=>i.trim()).filter(i=>i.length>0);return e.length>0?e:void 0}}function Li(){return [{name:"paradigm_aspect_search",description:"Search aspects using three-tier learning search (learned mappings > FTS5 > fuzzy). Returns ranked results. Call paradigm_aspect_confirm after selecting a result to improve future searches. ~200 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:'Search query (natural language or keyword, e.g., "token expiry", "pricing rule")'},limit:{type:"number",description:"Maximum results to return (default: 10)"}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_get",description:"Get full detail for a single aspect: description, category, severity, code anchors with snippets, edges, and linked lore entries. ~300 tokens.",inputSchema:{type:"object",properties:{aspectId:{type:"string",description:'Aspect identifier without ~ prefix (e.g., "token-expiry-24h")'}},required:["aspectId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_graph",description:"Traverse the aspect graph from a symbol to visualize its neighborhood. Returns nodes and edges within N hops (BFS). Useful for understanding how aspects relate to each other. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Starting symbol for graph traversal (e.g., "~token-expiry-24h", "#auth-service")'},hops:{type:"number",description:"Maximum number of hops to traverse (default: 2, max: 5)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_heatmap",description:"View the most frequently accessed aspects, ranked by total access count. Shows which aspects are queried most often. ~150 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Maximum entries to return (default: 20)"},accessType:{type:"string",enum:["search","ripple","navigate","direct"],description:"Optional: filter by access type"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_suggest_scan",description:"Scan a source file for implicit aspects (magic numbers, hardcoded limits, configuration values) and suggest aspect definitions. ~200 tokens.",inputSchema:{type:"object",properties:{filePath:{type:"string",description:"Relative or absolute path to the source file to scan"}},required:["filePath"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_drift",description:"Smart drift detection for code anchors. Layer 1: normalized hash (ignores formatting). Layer 2: git-aware line mapping (detects shifts, auto-heals .purpose files). ~200 tokens.",inputSchema:{type:"object",properties:{aspectId:{type:"string",description:"Optional: check a specific aspect. If omitted, checks all aspects."},autoHeal:{type:"boolean",description:"Auto-update anchors for high-confidence shifts (default: true)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_aspect_confirm",description:"Confirm a search result to improve future search accuracy. Call this after the user selects or uses a result from paradigm_aspect_search. Reinforces the query-to-aspect mapping. ~50 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"The original search query used"},aspectId:{type:"string",description:"The aspect ID that was selected/confirmed"}},required:["query","aspectId"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Ji(s,e,i){switch(s){case "paradigm_aspect_search":return jc(e,i);case "paradigm_aspect_get":return Oc(e,i);case "paradigm_aspect_graph":return Ic(e,i);case "paradigm_aspect_heatmap":return Ac(e,i);case "paradigm_aspect_suggest_scan":return Dc(e,i);case "paradigm_aspect_drift":return $c(e,i);case "paradigm_aspect_confirm":return Nc(e,i);default:return {handled:false,text:""}}}async function jc(s,e){let{query:i,limit:t=10}=s,r=null;try{r=await c$5(e.rootDir);let n=Hi(r,i,{limit:t});for(let a of n)try{j$7(r,a.id,"search");}catch{}let o={query:i,count:n.length,results:n.map(a=>({id:a.id,description:a.description,category:a.category,severity:a.severity,score:Math.round(a.score*1e3)/1e3,tier:a.tier,tags:a.tags,anchorCount:a.anchorCount})),tip:n.length>0?"Call paradigm_aspect_confirm with the query and selected aspectId to improve future searches.":"No results found. Try broader terms or check that aspects are defined in .purpose files."},c=JSON.stringify(o,null,2);return d$b(r,e.rootDir),r=null,a$1(c.length,"paradigm_aspect_search"),{handled:!0,text:c}}catch(n){if(r)try{d$b(r);}catch{}let o=JSON.stringify({error:"Failed to search aspects",details:String(n),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return a$1(o.length,"paradigm_aspect_search"),{handled:true,text:o}}}async function Oc(s,e){let{aspectId:i}=s,t=i.startsWith("~")?i.slice(1):i,r=null;try{r=await c$5(e.rootDir);let n=e$b(r,t);if(n||(n=e$b(r,`~${t}`)),!n){d$b(r),r=null;let f=JSON.stringify({error:"Aspect not found",aspectId:t,suggestion:"Use paradigm_aspect_search to find aspects by keyword."},null,2);return a$1(f.length,"paradigm_aspect_get"),{handled:!0,text:f}}let o=n.id,a=f$9(r,o).map(f=>{let v=Fc(e.rootDir,f);return {filePath:f.file_path,startLine:f.start_line,endLine:f.end_line,drifted:f.drifted===1,snippet:v}}),d=g$6(r,o),l=h$9(r,o),p=[...d.map(f=>({direction:"outgoing",source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin})),...l.map(f=>({direction:"incoming",source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin}))],g=[];try{g=await m$5(r,e.rootDir,o);}catch{}try{j$7(r,o,"direct");}catch{}let u;if(n.tags)try{let f=JSON.parse(n.tags);Array.isArray(f)&&(u=f);}catch{u=n.tags.split(",").map(f=>f.trim()).filter(f=>f.length>0);}let m={id:o,description:n.description,category:n.category,severity:n.severity,value:n.value,enforcement:n.enforcement,definedIn:n.defined_in,tags:u,createdAt:n.created_at,updatedAt:n.updated_at,anchors:a,edges:p,lore:g},y=JSON.stringify(m,null,2);return d$b(r,e.rootDir),r=null,a$1(y.length,"paradigm_aspect_get"),{handled:!0,text:y}}catch(n){if(r)try{d$b(r);}catch{}let o=JSON.stringify({error:"Failed to get aspect",details:String(n),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return a$1(o.length,"paradigm_aspect_get"),{handled:true,text:o}}}async function Ic(s,e){let{symbol:i,hops:t=2}=s,r=Math.min(Math.max(t,1),5),n=null;try{n=await c$5(e.rootDir);let o=new Set,c=new Map,a=[],d=[{symbol:i,depth:0}];o.add(i);let l=e$b(n,i);for(c.set(i,{aspectId:i,category:l?.category,severity:l?.severity,depth:0});d.length>0;){let m=d.shift();if(m.depth>=r)continue;let y=i$8(n,m.symbol);for(let f of y){let v=f.source===m.symbol?f.target:f.source;if(a.some(b=>b.source===f.source&&b.target===f.target&&b.relation===f.relation)||a.push({source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin,inferred:f.origin==="inferred"}),!o.has(v)){o.add(v);let b=e$b(n,v);c.set(v,{aspectId:v,category:b?.category,severity:b?.severity,depth:m.depth+1}),d.push({symbol:v,depth:m.depth+1});}}}let p=Array.from(c.values()),g={startSymbol:i,maxHops:r,nodeCount:p.length,edgeCount:a.length,nodes:p,edges:a},u=JSON.stringify(g,null,2);return d$b(n),n=null,a$1(u.length,"paradigm_aspect_graph"),{handled:!0,text:u}}catch(o){if(n)try{d$b(n);}catch{}let c=JSON.stringify({error:"Failed to traverse aspect graph",details:String(o),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return a$1(c.length,"paradigm_aspect_graph"),{handled:true,text:c}}}async function Ac(s,e){let{limit:i=20,accessType:t}=s,r=null;try{r=await c$5(e.rootDir);let n=k$4(r,i*4,t),o=new Map;for(let l of n){let p=o.get(l.aspect_id);if(!p){let g=e$b(r,l.aspect_id);p={aspectId:l.aspect_id,description:g?.description,totalCount:0,byType:{},lastAccessed:l.last_accessed},o.set(l.aspect_id,p);}p.totalCount+=l.count,p.byType[l.access_type]=l.count,l.last_accessed>p.lastAccessed&&(p.lastAccessed=l.last_accessed);}let c=Array.from(o.values()).sort((l,p)=>p.totalCount-l.totalCount).slice(0,i),a={count:c.length,...t?{filteredBy:t}:{},entries:c},d=JSON.stringify(a,null,2);return d$b(r),r=null,a$1(d.length,"paradigm_aspect_heatmap"),{handled:!0,text:d}}catch(n){if(r)try{d$b(r);}catch{}let o=JSON.stringify({error:"Failed to get aspect heatmap",details:String(n),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return a$1(o.length,"paradigm_aspect_heatmap"),{handled:true,text:o}}}async function Dc(s,e){let{filePath:i}=s,t=$.isAbsolute(i)?i:$.join(e.rootDir,i);if(!A.existsSync(t)){let r=JSON.stringify({error:"File not found",filePath:t,suggestion:"Provide a valid relative or absolute file path."},null,2);return a$1(r.length,"paradigm_aspect_suggest_scan"),{handled:true,text:r}}try{let o=(await import('../utils/aspect-suggest.js')).suggestAspects(t),c={filePath:t,count:o.length,suggestions:o.map(d=>({line:d.line,code:d.code,suggestedName:d.suggestedName,category:d.suggestedCategory,description:d.suggestedDescription,confidence:d.confidence,reason:d.reason,inferred:!0})),tip:o.length>0?"Review suggestions and add confirmed aspects to your .purpose files with ~ prefix and code anchors.":"No implicit aspects detected in this file."},a=JSON.stringify(c,null,2);return a$1(a.length,"paradigm_aspect_suggest_scan"),{handled:!0,text:a}}catch(r){let n=String(r);if(n.includes("Cannot find module")||n.includes("MODULE_NOT_FOUND")){let c=JSON.stringify({error:"Aspect suggestion engine not available",details:"The aspect-suggest utility has not been implemented yet.",suggestion:"This feature will be available in a future release. For now, manually identify implicit aspects in your code."},null,2);return a$1(c.length,"paradigm_aspect_suggest_scan"),{handled:true,text:c}}let o=JSON.stringify({error:"Failed to scan for aspect suggestions",details:n},null,2);return a$1(o.length,"paradigm_aspect_suggest_scan"),{handled:true,text:o}}}async function $c(s,e){let{aspectId:i,autoHeal:t}=s,r=t!==false,n=i?i.startsWith("~")?i.slice(1):i:void 0,o=.7,c=.85;try{let d=$.join(e.rootDir,".paradigm","config.yaml");if(A.existsSync(d)){let p=Ie.load(A.readFileSync(d,"utf-8"))?.drift;typeof p?.["suggest-threshold"]=="number"&&(o=p["suggest-threshold"]),typeof p?.["auto-heal-threshold"]=="number"&&(c=p["auto-heal-threshold"]);}}catch{}let a=null;try{a=await c$5(e.rootDir);let d=l$6(a,e.rootDir,n,r,o,c),l=d.filter(w=>w.status==="clean").length,p=d.filter(w=>w.status==="cosmetic").length,g=d.filter(w=>w.status==="shifted").length,u=d.filter(w=>w.status==="modified").length,m=d.filter(w=>w.status==="missing").length,y=u>0||m>0,f=p>0||g>0,v=y?"drift-detected":f?"clean-with-heals":"clean",h={...n?{aspectId:n}:{scope:"all"},totalAnchors:d.length,clean:l,cosmetic:p,shifted:g,modified:u,missing:m,status:v,results:d.map(w=>({aspectId:w.aspectId,path:w.path,startLine:w.startLine,endLine:w.endLine,status:w.status,resolvedBy:w.resolvedBy,exists:w.exists,...w.status==="shifted"?{suggestedStart:w.suggestedStart,suggestedEnd:w.suggestedEnd,autoHealed:w.autoHealed}:{},...w.status==="modified"&&w.currentContent?{currentContent:w.currentContent.slice(0,500)}:{}})),...p>0||g>0?{healed:[p>0?`${p} cosmetic (whitespace/formatting \u2014 hashes updated)`:"",g>0?`${g} shifted (line numbers updated via git diff${r?" \u2014 .purpose files patched":""})`:""].filter(Boolean).join(", ")}:{},...y?{suggestion:"Review drifted anchors to ensure aspects still apply. Run `paradigm scan` to re-materialize after fixing."}:{}},b=JSON.stringify(h,null,2);return d$b(a,e.rootDir),a=null,a$1(b.length,"paradigm_aspect_drift"),{handled:!0,text:b}}catch(d){if(a)try{d$b(a);}catch{}let l=JSON.stringify({error:"Failed to check aspect drift",details:String(d),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return a$1(l.length,"paradigm_aspect_drift"),{handled:true,text:l}}}async function Nc(s,e){let{query:i,aspectId:t}=s,r=null;try{r=await c$5(e.rootDir),Ei(r,i,t);let n={confirmed:!0,query:i,aspectId:t,message:`Search mapping reinforced: "${i}" -> ${t}. Future searches for similar queries will rank this aspect higher.`},o=JSON.stringify(n,null,2);return d$b(r,e.rootDir),r=null,a$1(o.length,"paradigm_aspect_confirm"),{handled:!0,text:o}}catch(n){if(r)try{d$b(r);}catch{}let o=JSON.stringify({error:"Failed to confirm search",details:String(n)},null,2);return a$1(o.length,"paradigm_aspect_confirm"),{handled:true,text:o}}}function Fc(s,e){let i=$.isAbsolute(e.file_path)?e.file_path:$.join(s,e.file_path);if(!A.existsSync(i))return null;try{let r=A.readFileSync(i,"utf8").split(`
100
+ `),n=Math.max(0,e.start_line-1),o=Math.min(r.length,e.end_line),c=r.slice(n,o).join(`
101
+ `);return c.length>1e3?c.slice(0,1e3)+`
102
+ ... (truncated)`:c}catch{return null}}function Mi(){return [{name:"paradigm_task_create",description:"Create a task (persistent scratch-pad item that survives context windows). Returns the created task ID. ~100 tokens.",inputSchema:{type:"object",properties:{blurb:{type:"string",description:"One-line task description"},priority:{type:"string",enum:["high","medium","low"],description:"Priority level (default: medium)"},tags:{type:"array",items:{type:"string"},description:"Tags \u2014 symbols (#component), freeform labels, etc."},related_lore:{type:"array",items:{type:"string"},description:"Linked lore entry IDs"},claimant:{type:"object",description:"Owner of this task (v7 DAG). kind: archetype|human|peer; ref: role id / git user / agentId",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},parentTaskId:{type:"string",description:"Parent task id (v7 DAG edge)"},dependsOn:{type:"array",items:{type:"string"},description:"Task ids this task depends on (v7 DAG edges)"},stage:{type:"number",description:"Orchestration stage index (v7 DAG)"},external_ref:{type:"object",description:"External anchor (provider-agnostic). provider: a free string \u2014 known: github (synced), session|symphony|orchestration|url (inert anchors). url/syncedAt populated by a provider push/link.",properties:{provider:{type:"string",description:"Provider/anchor id. Known: github (the only synced provider), session, symphony, orchestration, url."},ref:{type:"string"},url:{type:"string"},syncedAt:{type:"string"}}},session_link:{type:"string",description:"(Deprecated \u2014 use external_ref) Legacy external anchor; aliased to external_ref"}},required:["blurb"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_list",description:"List/filter tasks by status, priority, tags, or symbols. Returns task list sorted by priority then date. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",enum:["open","in-progress","done","shelved","active","all"],description:"Filter by status (default: open). 'active' = open \u222A in-progress"},priority:{type:"string",enum:["high","medium","low"],description:"Filter by priority"},tag:{type:"string",description:"Filter by tag (symbol or freeform)"},limit:{type:"number",description:"Maximum results (default: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_task_update",description:"Update a task (blurb, priority, status, tags). Returns updated task. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Task ID (e.g., "T-2026-02-26-001")'},blurb:{type:"string",description:"New description"},priority:{type:"string",enum:["high","medium","low"]},status:{type:"string",enum:["open","in-progress","done","shelved"]},tags:{type:"array",items:{type:"string"},description:"Replace tags"},related_lore:{type:"array",items:{type:"string"},description:"Related lore entry IDs (includes former assessment entries)"},related_assessments:{type:"array",items:{type:"string"},description:"(Deprecated \u2014 use related_lore) Alias for related_lore"},claimant:{type:"object",description:"Owner of this task (v7 DAG). kind: archetype|human|peer; ref: role id / git user / agentId",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},parentTaskId:{type:"string",description:"Parent task id (v7 DAG edge)"},dependsOn:{type:"array",items:{type:"string"},description:"Task ids this task depends on (v7 DAG edges)"},stage:{type:"number",description:"Orchestration stage index (v7 DAG)"},external_ref:{type:"object",description:"External anchor (provider-agnostic). provider: a free string \u2014 known: github (synced), session|symphony|orchestration|url (inert anchors). url/syncedAt populated by a provider push/link.",properties:{provider:{type:"string",description:"Provider/anchor id. Known: github (the only synced provider), session, symphony, orchestration, url."},ref:{type:"string"},url:{type:"string"},syncedAt:{type:"string"}}},session_link:{type:"string",description:"(Deprecated \u2014 use external_ref) Legacy external anchor; aliased to external_ref"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_done",description:"Mark a task as done. Shorthand for update with status=done. Returns confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_shelve",description:"Shelve a task (not now, not never). Shorthand for update with status=shelved. Returns confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Gi(s,e,i){switch(s){case "paradigm_task_create":{let t=await f$6(i.rootDir,{blurb:e.blurb,priority:e.priority,tags:e.tags,related_lore:e.related_lore,claimant:e.claimant,parentTaskId:e.parentTaskId,dependsOn:e.dependsOn,stage:e.stage,external_ref:e.external_ref,session_link:e.session_link}),r=await e$6(i.rootDir,t);return {handled:true,text:JSON.stringify({created:t,task:r},null,2)}}case "paradigm_task_list":{let t=await d$7(i.rootDir,{status:e.status||"open",priority:e.priority,tag:e.tag,limit:e.limit||20}),r=e.status||"open",n=[`${t.length} ${r} task(s):`];for(let o of t){let c=o.tags.length>0?` [${o.tags.join(", ")}]`:"";n.push(` [${o.priority}] ${o.id}: ${o.blurb}${c}`);}return {handled:true,text:n.join(`
103
+ `)}}case "paradigm_task_update":{let t=e.id,r={};if(e.blurb!==void 0&&(r.blurb=e.blurb),e.priority!==void 0&&(r.priority=e.priority),e.status!==void 0&&(r.status=e.status),e.tags!==void 0&&(r.tags=e.tags),e.related_lore!==void 0&&(r.related_lore=e.related_lore),e.related_assessments!==void 0&&(r.related_assessments=e.related_assessments),e.claimant!==void 0&&(r.claimant=e.claimant),e.parentTaskId!==void 0&&(r.parentTaskId=e.parentTaskId),e.dependsOn!==void 0&&(r.dependsOn=e.dependsOn),e.stage!==void 0&&(r.stage=e.stage),e.external_ref!==void 0&&(r.external_ref=e.external_ref),e.session_link!==void 0&&e.external_ref===void 0){let c=e.session_link,a=c.toLowerCase(),d=a.includes("github")?"github":a.includes("session")?"session":"url";r.external_ref={provider:d,ref:c};}if(!await g$2(i.rootDir,t,r))return {handled:true,text:JSON.stringify({error:`Task ${t} not found`})};let o=await e$6(i.rootDir,t);return {handled:true,text:JSON.stringify({updated:t,task:o},null,2)}}case "paradigm_task_done":{let t=e.id;if(!await h$3(i.rootDir,t))return {handled:true,text:JSON.stringify({error:`Task ${t} not found`})};let n=await e$6(i.rootDir,t);return {handled:true,text:JSON.stringify({completed:t,task:n,hint:"Consider recording a lore entry with arc:* tags if this was a significant milestone."},null,2)}}case "paradigm_task_shelve":{let t=e.id;if(!await i$1(i.rootDir,t))return {handled:true,text:JSON.stringify({error:`Task ${t} not found`})};let n=await e$6(i.rootDir,t);return {handled:true,text:JSON.stringify({shelved:t,task:n},null,2)}}default:return {handled:false,text:""}}}var Ui=0;function Wi(){let s=new Date().toISOString().slice(0,10);return Ui++,`run_${s}_${String(Ui).padStart(3,"0")}`}var zi=/\{\{([^}]+)\}\}/g;function Ae(s,e){if(typeof s=="string")return s.replace(zi,(i,t)=>{let r=Hc(t.trim(),e);return r!==void 0?String(r):i});if(Array.isArray(s))return s.map(i=>Ae(i,e));if(s&&typeof s=="object"){let i={};for(let[t,r]of Object.entries(s))i[t]=Ae(r,e);return i}return s}function Hc(s,e){let[i,...t]=s.split("."),r=t.join(".");switch(i){case "fixtures":return e.fixtures[r];case "produces":return xn(e.produces,r);case "context":case "parent":return e.context[r];case "env":return e.env[r]??process.env[r];default:return}}function xn(s,e){let i=e.split(/[.\[\]]+/).filter(Boolean),t=s;for(let r of i){if(t==null||typeof t!="object")return;t=t[r];}return t}function Ec(s,e){let i={};for(let[t,r]of Object.entries(s)){let n=r.match(/\{\{response\.(.+)\}\}/);if(n){let o=n[1],c=xn(e,o);c!==void 0&&(i[t]=c);}}return i}function qc(s,e){if(e.status!==s.status)return {pass:false,failure:`Status mismatch: expected ${s.status}, got ${e.status}`};if(s.body){let i=e.body;if(s.body.has){for(let t of s.body.has)if(i===null||typeof i!="object"||!(t in i))return {pass:false,failure:`Expected body to have key "${t}"`}}if(s.body.match)for(let[t,r]of Object.entries(s.body.match)){let n=xn(i,t);if(JSON.stringify(n)!==JSON.stringify(r))return {pass:false,failure:`Body mismatch at "${t}": expected ${JSON.stringify(r)}, got ${JSON.stringify(n)}`}}}return {pass:true}}async function Lc(s,e,i){let t=Date.now(),r=s.route.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(.*)/);if(!r)return {id:s.id,status:"fail",route:s.route,gates:s.gates,failure:`Invalid route format: ${s.route}`,duration_ms:Date.now()-t};let n=r[1],o=r[2],c=Ae(o,i),a=`${e.baseUrl.replace(/\/$/,"")}${c}`,d={"Content-Type":"application/json",...s.headers?Ae(s.headers,i):{}},l=s.payload?Ae(s.payload,i):void 0,p={url:a,method:n,headers:s.headers?d:void 0,payload:l};if(e.dryRun)return {id:s.id,status:"pass",route:s.route,gates:s.gates,request:p,produced:s.produces?Object.fromEntries(Object.keys(s.produces).map(g=>[g,`<dry-run:${g}>`])):void 0,duration_ms:Date.now()-t};try{let g={method:n,headers:d};l&&["POST","PUT","PATCH"].includes(n)&&(g.body=JSON.stringify(l));let u=await fetch(a,g),m;(u.headers.get("content-type")||"").includes("application/json")?m=await u.json():m=await u.text();let f={status:u.status,body:m},v=qc(s.expect,f),h;s.produces&&v.pass&&(h=Ec(s.produces,m));let b;return (u.status===401||u.status===403)&&(b=s.gates[s.gates.length-1]),{id:s.id,status:v.pass?"pass":"fail",route:s.route,gates:s.gates,request:p,response:f,produced:h,expected_status:v.pass?void 0:s.expect.status,failure:v.failure,gate_that_blocked:b,duration_ms:Date.now()-t}}catch(g){return {id:s.id,status:"fail",route:s.route,gates:s.gates,request:p,failure:`Request failed: ${g.message}`,duration_ms:Date.now()-t}}}async function Bi(s,e,i){let t=Date.now(),r=await h$4(s,e);return r?Vi(s,r,i):{persona:e,run_id:Wi(),status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${e} not found`,duration_ms:Date.now()-t}}async function Vi(s,e,i){let t=Date.now(),r=i.stopOnFailure!==false,n={fixtures:e.fixtures||{},produces:{},context:i.context||{},env:process.env},o=[],c=[],a=[],d=false;for(let y of e.journey){if(d&&r){if(o.push({id:y.id,status:"skip",route:y.route,gates:y.gates,duration_ms:0}),y.spawns)for(let v of y.spawns)a.push(v.persona);continue}let f=await Lc(y,i,n);if(o.push(f),f.status==="pass"){if(f.produced&&Object.assign(n.produces,f.produced),y.spawns)for(let v of y.spawns)c.push(v.persona);}else if(d=true,y.spawns)for(let v of y.spawns)a.push(v.persona);}let l=o.filter(y=>y.status==="pass").length,p=o.filter(y=>y.status==="fail").length,g=e.journey.length,u=o.find(y=>y.status==="fail"),m;return p===0?m=`${l}/${g} passed. All steps succeeded.`:m=`${l}/${g} passed. Failed at step ${o.indexOf(u)+1} (${u.id}): ${u.failure}`,{persona:e.id,run_id:Wi(),status:p>0?"fail":"pass",steps:o,spawns_triggered:c,spawns_blocked:a,summary:m,duration_ms:Date.now()-t}}async function Yi(s,e,i){let t=Date.now(),r=await import('fs'),n=await import('path'),o=await import('js-yaml'),c=n.join(s,".paradigm","personas","chains",`${e}.yaml`);if(!r.existsSync(c))return {chain_id:e,status:"error",persona_results:[],summary:`Chain ${e} not found`,duration_ms:Date.now()-t};let a=o.load(r.readFileSync(c,"utf8")),d;if(i.permutation&&a.permutations&&(d=a.permutations.find(y=>y.id===i.permutation),!d))return {chain_id:e,status:"error",persona_results:[],summary:`Permutation ${i.permutation} not found in chain ${e}`,duration_ms:Date.now()-t};let l=[],p={},g=i.stopOnFailure!==false;for(let y of a.order){let f=await h$4(s,y.persona);if(!f){if(l.push({persona:y.persona,status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${y.persona} not found`,duration_ms:0}),g)break;continue}if(d&&d.overrides[y.persona]){let w=d.overrides[y.persona];if(w.traits&&(f.traits={...f.traits,...w.traits}),w.journey)for(let[S,x]of Object.entries(w.journey)){let _=f.journey.find(C=>C.id===S);_&&(x.payload&&(_.payload={..._.payload,...x.payload}),x.expect&&(_.expect={..._.expect,...x.expect}));}}let v={};if(y.wait_for){let[w,S]=y.wait_for.split("."),x=l.find(C=>C.persona===w);if(x){let C=x.steps.find(P=>P.id===S);C?.produced&&(v=Object.fromEntries(Object.entries(C.produced).map(([P,j])=>[P,String(j)])));}let _=await h$4(s,w);if(_){let C=_.journey.find(P=>P.id===S);if(C?.spawns){let P=C.spawns.find(j=>j.persona===y.persona);if(P?.context){let j=p[w]||{};for(let[I,R]of Object.entries(P.context))v[I]=String(Ae(R,{fixtures:{},produces:j,context:{},env:process.env}));}}}}let h=await Vi(s,f,{...i,context:v});l.push(h);let b={};for(let w of h.steps)w.produced&&Object.assign(b,w.produced);if(p[y.persona]=b,h.status==="fail"&&g)break}let u=l.filter(y=>y.status==="pass").length,m=a.order.length;return {chain_id:e,status:l.some(y=>y.status!=="pass")?"fail":"pass",persona_results:l,summary:`${u}/${m} personas passed.`,duration_ms:Date.now()-t}}function Ki(s){let e=[],i=new Set;for(let t of s.journey){let n=JSON.stringify(t).match(zi)||[];for(let o of n){let c=o.replace("{{","").replace("}}","").trim(),[a,...d]=c.split("."),l=d.join(".");switch(a){case "fixtures":!s.fixtures||l in s.fixtures;break;case "produces":i.has(l)||e.push({step:t.id,template:o,error:`{{produces.${l}}} used but not produced by a prior step`});break;case "context":case "parent":break;case "env":break;case "response":break;default:e.push({step:t.id,template:o,error:`Unknown namespace "${a}" in ${o}`});}}if(t.produces)for(let o of Object.keys(t.produces))i.add(o);}return {valid:e.length===0,errors:e}}var Qi="paradigm-personas",Jc={id:Qi,version:"1.0",name:"Paradigm Personas",description:"Events from persona journey and chain execution",scope:{key:"persona_id",label:"Persona"},eventTypes:{"persona.run.start":{category:"lifecycle",severity:"info"},"persona.step.pass":{category:"assertion",severity:"info"},"persona.step.fail":{category:"assertion",severity:"warning"},"persona.step.skip":{category:"lifecycle",severity:"info"},"persona.run.complete":{category:"lifecycle",severity:"info"},"persona.chain.complete":{category:"lifecycle",severity:"info"},"persona.coverage.report":{category:"analysis",severity:"info"}}},Pn=false;async function Xi(s){try{let{SentinelStorage:e}=await import('./dist-VGFSP3XM.js'),i=new e;if(!Pn)try{i.registerSchema(Jc),Pn=!0;}catch{Pn=!0;}let t=[];if("persona"in s){let r=s;t.push({type:"persona.run.start",timestamp:new Date().toISOString(),scopeValue:r.persona,data:{persona_id:r.persona,run_id:r.run_id,total_steps:r.steps.length}});for(let n of r.steps){let o=n.status==="pass"?"persona.step.complete":`persona.step.${n.status}`;t.push({type:o,timestamp:new Date().toISOString(),scopeValue:r.persona,data:{persona_id:r.persona,run_id:r.run_id,step_id:n.id,route:n.route,gates:n.gates,gates_traversed:n.gates,status:n.response?.status,body:n.response?.body,signals_fired:[],duration_ms:n.duration_ms,failure:n.failure,gate_that_blocked:n.gate_that_blocked,produced_keys:n.produced?Object.keys(n.produced):[]}});}t.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:r.persona,data:{persona_id:r.persona,run_id:r.run_id,status:r.status,total_steps:r.steps.length,passed:r.steps.filter(n=>n.status==="pass").length,failed:r.steps.filter(n=>n.status==="fail").length,skipped:r.steps.filter(n=>n.status==="skip").length,duration_ms:r.duration_ms,spawns_triggered:r.spawns_triggered,spawns_blocked:r.spawns_blocked}});}else {let r=s;for(let n of r.persona_results)t.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:n.persona,data:{persona_id:n.persona,run_id:n.run_id,chain_id:r.chain_id,status:n.status,total_steps:n.steps.length,passed:n.steps.filter(o=>o.status==="pass").length,failed:n.steps.filter(o=>o.status==="fail").length,duration_ms:n.duration_ms}});t.push({type:"persona.chain.complete",timestamp:new Date().toISOString(),data:{chain_id:r.chain_id,status:r.status,personas_run:r.persona_results.length,personas_passed:r.persona_results.filter(n=>n.status==="pass").length,duration_ms:r.duration_ms}});}t.length>0&&i.insertEventBatch(Qi,"paradigm-personas",t);}catch{}}function Zi(){return [{name:"paradigm_persona_create",description:"Create a persona \u2014 named test actor with traits, trigger, fixtures, and journey steps. Writes a .persona file. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Persona ID (kebab-case, e.g., "alice-admin")'},name:{type:"string",description:'Human-readable name (e.g., "Agency Owner (Annual Billing)")'},description:{type:"string",description:"What this persona represents"},traits:{type:"object",description:"Key-value actor attributes (tier, billing, role, etc.)"},trigger:{type:"object",properties:{type:{type:"string",enum:["root","invitation","signup","api"],description:"How this persona enters the system"},spawned_by:{type:"string",description:"persona-id.step-id (required if type != root)"},context:{type:"object",description:"Data passed from parent spawn"}},required:["type"]},fixtures:{type:"object",description:"Test data for this persona (email, password, API keys, etc.)"},tags:{type:"array",items:{type:"string"},description:"Tags for filtering"},journey:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Step ID (kebab-case)"},description:{type:"string"},route:{type:"string",description:'METHOD /path (e.g., "POST /api/auth/signup")'},flow:{type:"string",description:"$flow reference"},gates:{type:"array",items:{type:"string"},description:"^gate references"},headers:{type:"object"},payload:{type:"object",description:"Request body. Supports {{produces.X}} and {{fixtures.X}} interpolation."},expect:{type:"object",properties:{status:{type:"number"},body:{type:"object",properties:{has:{type:"array",items:{type:"string"}},match:{type:"object"}}}},required:["status"]},produces:{type:"object",description:"Values to extract from response for later steps"},spawns:{type:"array",items:{type:"object",properties:{persona:{type:"string"},via:{type:"string"},context:{type:"object"}},required:["persona","via"]}},signals:{type:"array",items:{type:"string"},description:"!signal references expected to fire"}},required:["id","route","gates","expect"]}}},required:["id","name","trigger"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_get",description:"Get full persona detail \u2014 journey, traits, spawn chain, validation status. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_list",description:"List personas with optional filters \u2014 tag, trigger type, gate, flow. ~200 tokens.",inputSchema:{type:"object",properties:{tag:{type:"string",description:"Filter by tag"},trigger_type:{type:"string",enum:["root","invitation","signup","api"],description:"Filter by trigger type"},gate:{type:"string",description:"Filter by gate (show personas that traverse this gate)"},flow:{type:"string",description:"Filter by flow (show personas that exercise this flow)"},limit:{type:"number",description:"Maximum results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_update",description:"Update persona fields \u2014 traits, fixtures, journey steps, tags. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"},name:{type:"string"},description:{type:"string"},traits:{type:"object"},trigger:{type:"object",properties:{type:{type:"string",enum:["root","invitation","signup","api"]},spawned_by:{type:"string"},context:{type:"object"}}},fixtures:{type:"object"},tags:{type:"array",items:{type:"string"}},journey:{type:"array",description:"Replace entire journey. Use paradigm_persona_add_step for surgical edits."}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_delete",description:"Delete a persona. Warns if other personas spawn from it. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_persona_add_step",description:"Add a journey step to a persona. Validates gates, route format, and produce/consume chains. ~150 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Persona ID"},step:{type:"object",properties:{id:{type:"string",description:"Step ID (kebab-case, unique within persona)"},description:{type:"string"},route:{type:"string",description:"METHOD /path"},flow:{type:"string",description:"$flow reference"},gates:{type:"array",items:{type:"string"},description:"^gate references"},headers:{type:"object"},payload:{type:"object"},expect:{type:"object",properties:{status:{type:"number"},body:{type:"object"}},required:["status"]},produces:{type:"object"},spawns:{type:"array"},signals:{type:"array",items:{type:"string"}}},required:["id","route","gates","expect"]},after:{type:"string",description:"Insert after this step ID. Omit to append."}},required:["persona_id","step"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_remove_step",description:"Remove a journey step. Warns if it produces data consumed by later steps or spawns other personas. ~100 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Persona ID"},step_id:{type:"string",description:"Step ID to remove"}},required:["persona_id","step_id"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_persona_validate",description:"Full persona validation \u2014 schema + cross-refs + Sentinel event matching with exact assertion results. Compares expected journey outcomes against actual Sentinel events. ~300 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Validate one persona. Omit for all."},deep:{type:"boolean",description:"Include cross-reference and coverage analysis (default: false)"},sentinel:{type:"boolean",description:"Compare against Sentinel events (default: true when available)"},run_id:{type:"string",description:"Validate against a specific run. Omit for latest."},chain_id:{type:"string",description:"Validate against a specific chain execution."},environment:{type:"string",description:"Filter Sentinel events by environment (dev, staging, prod, ci)."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_coverage",description:"Coverage report \u2014 which routes/gates/flows have persona coverage, which don't. Compares against portal.yaml. ~250 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_affected",description:"Given a symbol (^gate, $flow, route), return affected personas and their steps. Used by ripple. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to check (e.g., "^authenticated", "$checkout-flow", "POST /api/orders")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_run",description:"Execute a persona journey or chain against a running server. Interpolates templates, sends requests step-by-step, validates responses. Supports dry-run mode. ~500 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Run a single persona journey"},chain_id:{type:"string",description:"Run a named chain (overrides persona_id)"},base_url:{type:"string",description:'Server base URL (e.g., "http://localhost:3000")'},dry_run:{type:"boolean",description:"Validate and interpolate without making requests (default: false)"},stop_on_failure:{type:"boolean",description:"Stop on first failing step (default: true)"},permutation:{type:"string",description:"Permutation ID from chain definition"}},required:["base_url"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function eo(s,e,i){switch(s){case "paradigm_persona_create":try{let t=await i$2(i.rootDir,{id:e.id,name:e.name,description:e.description,traits:e.traits,trigger:e.trigger,fixtures:e.fixtures,tags:e.tags,journey:e.journey}),r=await h$4(i.rootDir,t);return {handled:!0,text:JSON.stringify({created:t,persona:r},null,2)}}catch(t){return {handled:true,text:JSON.stringify({error:t.message})}}case "paradigm_persona_get":{let t=e.id,r=await h$4(i.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Persona ${t} not found`})};let n=await n$3(i.rootDir,r);return {handled:true,text:JSON.stringify({persona:r,validation:n},null,2)}}case "paradigm_persona_list":{let t=await g$3(i.rootDir,{tag:e.tag,trigger_type:e.trigger_type,gate:e.gate,flow:e.flow,limit:e.limit||50}),r=t.map(n=>({id:n.id,name:n.name,trigger:n.trigger.type,steps:n.journey.length,gates:[...new Set(n.journey.flatMap(o=>o.gates))],tags:n.tags||[]}));return {handled:true,text:JSON.stringify({count:t.length,personas:r},null,2)}}case "paradigm_persona_update":{let t=e.id,r={};if(e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),e.traits!==void 0&&(r.traits=e.traits),e.trigger!==void 0&&(r.trigger=e.trigger),e.fixtures!==void 0&&(r.fixtures=e.fixtures),e.tags!==void 0&&(r.tags=e.tags),e.journey!==void 0&&(r.journey=e.journey),!await j$3(i.rootDir,t,r))return {handled:true,text:JSON.stringify({error:`Persona ${t} not found`})};let o=await h$4(i.rootDir,t);return {handled:true,text:JSON.stringify({updated:t,persona:o},null,2)}}case "paradigm_persona_delete":{let t=e.id,r=await k$1(i.rootDir,t);return r.deleted?{handled:true,text:JSON.stringify({deleted:t,warnings:r.warnings,hint:r.warnings.length>0?"Other personas reference this one. Update or delete them to avoid broken spawn chains.":void 0},null,2)}:{handled:true,text:JSON.stringify({error:`Persona ${t} not found`})}}case "paradigm_persona_add_step":try{if(!await l$1(i.rootDir,e.persona_id,e.step,e.after))return {handled:!0,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let r=await h$4(i.rootDir,e.persona_id);return {handled:!0,text:JSON.stringify({added:e.step.id,persona_id:e.persona_id,total_steps:r?.journey.length},null,2)}}catch(t){return {handled:true,text:JSON.stringify({error:t.message})}}case "paradigm_persona_remove_step":{let t=await m$1(i.rootDir,e.persona_id,e.step_id);return t.removed?{handled:true,text:JSON.stringify({removed:e.step_id,persona_id:e.persona_id,warnings:t.warnings},null,2)}:{handled:true,text:JSON.stringify({error:`Step ${e.step_id} not found in persona ${e.persona_id}`})}}case "paradigm_persona_validate":{let t=e.deep??false,r=e.sentinel??true,n={run_id:e.run_id,chain_id:e.chain_id,environment:e.environment};if(e.persona_id){let l=await h$4(i.rootDir,e.persona_id);if(!l)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let p=await n$3(i.rootDir,l,t);if(r)try{let g=await r$2(l,n);p.sentinel_assertions=g,(g.summary.failed>0||g.summary.unmatched>0)&&(p.valid=!1);}catch{}return {handled:true,text:JSON.stringify(p,null,2)}}let o=await g$3(i.rootDir),c=await Promise.all(o.map(async l=>{let p=await n$3(i.rootDir,l,t);if(r)try{let g=await r$2(l,n);p.sentinel_assertions=g,(g.summary.failed>0||g.summary.unmatched>0)&&(p.valid=!1);}catch{}return p})),a=c.filter(l=>l.valid).length,d=c.filter(l=>!l.valid).length;return {handled:true,text:JSON.stringify({total:c.length,valid:a,invalid:d,results:c.filter(l=>!l.valid||l.warnings.length>0||l.sentinel_assertions)},null,2)}}case "paradigm_persona_coverage":{let t=await p$3(i.rootDir);return {handled:true,text:JSON.stringify(t,null,2)}}case "paradigm_persona_affected":{let t=e.symbol,r=await q$1(i.rootDir,t);return r.length===0?{handled:true,text:JSON.stringify({symbol:t,affected:[],note:"No personas reference this symbol."})}:{handled:true,text:JSON.stringify({symbol:t,affected:r},null,2)}}case "paradigm_persona_run":{let t=e.base_url,r=e.dry_run??false,n=e.stop_on_failure??true;if(e.chain_id){let o=await Yi(i.rootDir,e.chain_id,{baseUrl:t,dryRun:r,stopOnFailure:n,permutation:e.permutation});return r||await Xi(o),{handled:true,text:JSON.stringify(o,null,2)}}if(e.persona_id){let o=await h$4(i.rootDir,e.persona_id);if(!o)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let c=Ki(o);if(!c.valid&&!r)return {handled:true,text:JSON.stringify({error:"Template interpolation errors \u2014 fix before running",errors:c.errors,hint:"Use dry_run: true to see interpolated values without executing requests"},null,2)};let a=await Bi(i.rootDir,e.persona_id,{baseUrl:t,dryRun:r,stopOnFailure:n});return r||await Xi(a),{handled:true,text:JSON.stringify(a,null,2)}}return {handled:true,text:JSON.stringify({error:"Either persona_id or chain_id is required"})}}default:return {handled:false,text:""}}}var Mc=".paradigm/graphs",Cn={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},Rn=200,Tn=60,De=20,Tt=40,to=50,Gc=60;function ro(){return [{name:"paradigm_graph_generate",description:"Generate a named GraphState JSON file for the Paradigm Symbol Graph UI. Writes to .paradigm/graphs/{name}.graph.json. View saved graphs with `paradigm graph` CLI. Returns a summary with node/edge counts and file path. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Graph name (kebab-case). Used as filename: {name}.graph.json. E.g. "auth-flow", "full-project", "checkout-subsystem".'},symbols:{type:"array",items:{type:"string"},description:'Symbol names to include (e.g. ["#auth-middleware", "^authenticated"]). Omit to include all from scan-index.'},groups:{type:"array",items:{type:"object",properties:{label:{type:"string",description:"Group display label"},symbols:{type:"array",items:{type:"string"},description:"Symbol names belonging to this group"}},required:["label","symbols"]},description:"Optional groupings of symbols."},links:{type:"array",items:{type:"object",properties:{source:{type:"string",description:"Source group label"},target:{type:"string",description:"Target group label"},label:{type:"string",description:"Edge label"}},required:["source","target"]},description:"Edges between groups (by label name)."}},required:["name"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function so(s,e,i){if(s!=="paradigm_graph_generate")return {handled:false,text:""};try{let t=e.name||"untitled",r=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),n=zc(i.rootDir,e.symbols,e.groups,e.links,t),o=JSON.stringify(n,null,2),c=$.join(i.rootDir,Mc);A.existsSync(c)||A.mkdirSync(c,{recursive:!0});let a=$.join(c,`${r}.graph.json`);A.writeFileSync(a,o,"utf8");let d=JSON.stringify({file:a,name:t,slug:r,nodes:n.nodes.length,edges:n.edges.length,size:`${(o.length/1024).toFixed(1)} KB`,hint:"Graph saved. Run `paradigm graph` to view in browser."},null,2);return a$1(d.length,s),{handled:!0,text:d}}catch(t){let r=JSON.stringify({error:t.message},null,2);return a$1(r.length,s),{handled:true,text:r}}}var Uc={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"};function Wc(s){let e=$.join(s,".paradigm","scan-index.json");if(!A.existsSync(e))return [];let i=JSON.parse(A.readFileSync(e,"utf8")),t=[];for(let[r,n]of Object.entries(Uc)){let o=i[r];if(!(!o||typeof o!="object"))for(let[c,a]of Object.entries(o)){let d=a;t.push({id:c,name:c,category:n,prefix:Cn[n]||"#",description:d.description,path:d.path,tags:d.tags});}}return t}function no(s,e){let i=s.replace(/^[#$^!~]/,"");return e.find(t=>t.id===i||t.name===i||t.id===s||t.name===s)}function zc(s,e,i,t,r="Generated Graph"){let n=Wc(s),o;e&&e.length>0?o=e.map(u=>no(u,n)).filter(Boolean):o=n;let c=[],a=[],d=new Map,l=new Set,p=0;if(i&&i.length>0)for(let u of i){let m=`group-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;d.set(u.label,m);let y=u.symbols.map(x=>no(x,o)).filter(Boolean),f=Math.ceil(Math.sqrt(y.length)),v=Math.ceil(y.length/f);for(let x=0;x<y.length;x++){let _=y[x],C=x%f,P=Math.floor(x/f),j=Cn[_.category]||"#";c.push({id:`sym-${_.id}`,type:"symbolNode",position:{x:Tt+C*(Rn+De),y:to+Tt+P*(Tn+De)},parentId:m,data:{type:"symbol",symbol:_,label:`${j}${_.name}`}}),l.add(_.id);}let h=Math.max(f,1),b=Math.max(v,1),w=Tt*2+h*Rn+(h-1)*De,S=to+Tt*2+b*Tn+(b-1)*De;c.unshift({id:m,type:"groupNode",position:{x:p,y:0},style:{width:w,height:S},data:{type:"group",label:u.label}}),p+=w+Gc;}let g=o.filter(u=>!l.has(u.id));if(g.length>0){let u=i&&i.length>0?400:0,m=Math.ceil(Math.sqrt(g.length));for(let y=0;y<g.length;y++){let f=g[y],v=y%m,h=Math.floor(y/m),b=Cn[f.category]||"#";c.push({id:`sym-${f.id}`,type:"symbolNode",position:{x:v*(Rn+De),y:u+h*(Tn+De)},data:{type:"symbol",symbol:f,label:`${b}${f.name}`}});}}if(t&&t.length>0)for(let u of t){let m=d.get(u.source),y=d.get(u.target);m&&y&&a.push({id:`e-${m}-${y}`,source:m,target:y,type:"default",label:u.label,data:{label:u.label}});}return {version:"1.0",name:r,projectId:$.basename(s),lastModified:new Date().toISOString(),nodes:c,edges:a}}var K=["specify","plan","task","implement","validate"],st=".paradigm/pipeline",io={"add-feature":{gates:{specify:"manual",plan:"manual",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Standard feature addition with manual spec/plan review"},"bug-fix":{gates:{specify:"auto",plan:"auto",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Quick bug fix with automated gates except validation"},"security-change":{gates:{specify:"manual",plan:"manual",task:"manual",implement:"manual",validate:"manual"},description:"Security-sensitive change with all-manual gates"},refactor:{gates:{specify:"auto",plan:"manual",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Code refactoring with manual plan review"}};function Ct(s){return s.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function nt(s,e){let i=Ct(e),t=$.join(s,st,`${i}.yaml`);return A.existsSync(t)?Ie.load(A.readFileSync(t,"utf8")):null}function rt(s,e){let i=Ct(e.feature),t=$.join(s,st);A.existsSync(t)||A.mkdirSync(t,{recursive:true});let r=$.join(t,`${i}.yaml`);return A.writeFileSync(r,Ie.dump(e,{lineWidth:120}),"utf8"),r}function oo(s){let e=$.join(s,st);return A.existsSync(e)?A.readdirSync(e).filter(i=>i.endsWith(".yaml")&&!i.startsWith("completed")).map(i=>{try{return Ie.load(A.readFileSync($.join(e,i),"utf8"))}catch{return null}}).filter(Boolean):[]}function Bc(s,e,i){let t={specify:{status:"pending"},plan:{status:"pending"},task:{status:"pending"},implement:{status:"pending"},validate:{status:"pending"}};return t.specify.status="in-progress",{version:"1.0",feature:Ct(s),created:new Date().toISOString(),current_stage:"specify",gate_config:e,template:i,stages:t}}function Vc(s){let e=K.indexOf(s);return e<K.length-1?K[e+1]:null}function ao(s,e){let i=Ct(e.feature),t=$.join(s,st,"completed");A.existsSync(t)||A.mkdirSync(t,{recursive:true});let r=$.join(t,`${i}.yaml`);A.writeFileSync(r,Ie.dump(e,{lineWidth:120}),"utf8");let n=$.join(s,st,`${i}.yaml`);A.existsSync(n)&&A.unlinkSync(n);}function co(){return [{name:"paradigm_pipeline_start",description:"Create a new spec pipeline for a feature. Uses templates (add-feature, bug-fix, security-change, refactor) or custom gate config. Returns pipeline state. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name or description (will be slugified)"},template:{type:"string",enum:["add-feature","bug-fix","security-change","refactor"],description:"Pipeline template (default: add-feature)"},gates:{type:"object",properties:{specify:{type:"string",enum:["auto","manual","sentinel"]},plan:{type:"string",enum:["auto","manual","sentinel"]},task:{type:"string",enum:["auto","manual","sentinel"]},implement:{type:"string",enum:["auto","manual","sentinel"]},validate:{type:"string",enum:["auto","manual","sentinel"]}},description:"Custom gate config (overrides template)"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_status",description:"Get pipeline status \u2014 current stage, progress, gate config. Pass feature name for specific pipeline, or omit for all active pipelines. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name (omit to list all active pipelines)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_pipeline_advance",description:"Advance pipeline past the current gate. Marks current stage as approved and moves to the next stage. ~150 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},approved_by:{type:"string",description:"Who approved this gate (default: agent)"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_configure",description:"Change gate modes on an active pipeline. Use to escalate or relax gates during development. ~150 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},updates:{type:"object",properties:{specify:{type:"string",enum:["auto","manual","sentinel"]},plan:{type:"string",enum:["auto","manual","sentinel"]},task:{type:"string",enum:["auto","manual","sentinel"]},implement:{type:"string",enum:["auto","manual","sentinel"]},validate:{type:"string",enum:["auto","manual","sentinel"]}},description:"Stage-to-gate-mode updates"},reason:{type:"string",description:"Reason for the configuration change"}},required:["feature","updates","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_escalate",description:"Flag a pipeline stage for user input. Use when a gate requires a decision the agent cannot make autonomously. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},stage:{type:"string",enum:["specify","plan","task","implement","validate"],description:"Stage to escalate"},question:{type:"string",description:"Question for the user"},options:{type:"array",items:{type:"string"},description:"Available options for the user"},context:{type:"object",description:"Additional context for the decision"}},required:["feature","stage","question","options"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_abort",description:"Cancel and archive an active pipeline. Use when a feature is abandoned or no longer needed. ~100 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_pipeline_list",description:"List all active pipelines with current stages and progress. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function lo(s,e,i){switch(s){case "paradigm_pipeline_start":{let t=e.feature,r=e.template||"add-feature",n=e.gates,o;if(n)o={specify:n.specify||"manual",plan:n.plan||"manual",task:n.task||"auto",implement:n.implement||"sentinel",validate:n.validate||"sentinel"};else {let d=io[r];if(!d)return {handled:true,text:JSON.stringify({error:`Unknown template: ${r}`,available:Object.keys(io)})};o=d.gates;}let c=Bc(t,o,r),a=rt(i.rootDir,c);return {handled:true,text:JSON.stringify({created:true,feature:c.feature,template:r,file:a,current_stage:c.current_stage,gate_config:c.gate_config,stages:c.stages,hint:`Pipeline '${c.feature}' started at 'specify' stage. Create your spec, then call paradigm_pipeline_advance to move to 'plan'.`},null,2)}}case "paradigm_pipeline_status":{let t=e.feature;if(t){let n=nt(i.rootDir,t);if(!n)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${t}`})};let o=K.filter(c=>n.stages[c].status==="approved").length;return {handled:true,text:JSON.stringify({feature:n.feature,created:n.created,template:n.template,current_stage:n.current_stage,progress:`${o}/${K.length}`,gate_config:n.gate_config,stages:n.stages},null,2)}}let r=oo(i.rootDir);return r.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines. Use paradigm_pipeline_start to create one."})}:{handled:true,text:JSON.stringify({count:r.length,pipelines:r.map(n=>{let o=K.filter(c=>n.stages[c].status==="approved").length;return {feature:n.feature,current_stage:n.current_stage,progress:`${o}/${K.length}`,template:n.template,created:n.created}})},null,2)}}case "paradigm_pipeline_advance":{let t=e.feature,r=e.approved_by||"agent",n=nt(i.rootDir,t);if(!n)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${t}`})};let o=n.current_stage,c=n.gate_config[o],a=Vc(o);return n.stages[o].status="approved",n.stages[o].approved_by=r,n.stages[o].approved_at=new Date().toISOString(),c==="auto"&&(n.stages[o].auto_passed_at=new Date().toISOString()),a?(n.current_stage=a,n.stages[a].status="in-progress",rt(i.rootDir,n),{handled:true,text:JSON.stringify({advanced:true,from:o,to:a,gate_mode:c,approved_by:r,pipeline:{feature:n.feature,current_stage:n.current_stage,stages:n.stages}},null,2)}):(rt(i.rootDir,n),ao(i.rootDir,n),{handled:true,text:JSON.stringify({completed:true,feature:n.feature,message:`Pipeline '${n.feature}' completed and archived.`,stages:n.stages},null,2)})}case "paradigm_pipeline_configure":{let t=e.feature,r=e.updates,n=e.reason,o=nt(i.rootDir,t);if(!o)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${t}`})};let c=[];for(let[a,d]of Object.entries(r))if(K.includes(a)&&["auto","manual","sentinel"].includes(d)){let l=o.gate_config[a];o.gate_config[a]=d,c.push({stage:a,from:l,to:d});}return c.length===0?{handled:true,text:JSON.stringify({error:"No valid gate updates provided",valid_stages:K,valid_modes:["auto","manual","sentinel"]})}:(rt(i.rootDir,o),{handled:true,text:JSON.stringify({configured:true,feature:o.feature,changes:c,reason:n,gate_config:o.gate_config},null,2)})}case "paradigm_pipeline_escalate":{let t=e.feature,r=e.stage,n=e.question,o=e.options,c=e.context,a=nt(i.rootDir,t);return a?(a.stages[r].status="blocked",a.stages[r].block_reason=n,rt(i.rootDir,a),{handled:true,text:JSON.stringify({escalated:true,feature:a.feature,stage:r,question:n,options:o,context:c||{},current_gate:a.gate_config[r],instruction:"This pipeline stage requires user input. Present the question and options to the user, then use paradigm_pipeline_advance or paradigm_pipeline_configure based on their response."},null,2)}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${t}`})}}case "paradigm_pipeline_abort":{let t=e.feature,r=nt(i.rootDir,t);return r?(ao(i.rootDir,r),{handled:true,text:JSON.stringify({aborted:true,feature:r.feature,message:`Pipeline '${r.feature}' aborted and archived.`})}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${t}`})}}case "paradigm_pipeline_list":{let t=oo(i.rootDir);return t.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines."})}:{handled:true,text:JSON.stringify({count:t.length,pipelines:t.map(r=>{let n=K.filter(o=>r.stages[o].status==="approved").length;return {feature:r.feature,current_stage:r.current_stage,progress:`${n}/${K.length}`,template:r.template,created:r.created}})},null,2)}}default:return {handled:false,text:""}}}b();var Yc=$.join(fi.homedir(),".conductor"),Fe=$.join(Yc,"sessions");function go(){A.existsSync(Fe)||A.mkdirSync(Fe,{recursive:true});}function fo(s){go();let e={...s,registeredAt:new Date().toISOString()},i=$.join(Fe,`${s.pid}.json`);return A.writeFileSync(i,JSON.stringify(e,null,2),"utf-8"),e}function jn(s){let e=$.join(Fe,`${s}.json`);return A.existsSync(e)?(A.unlinkSync(e),true):false}function On(){go();let s=A.readdirSync(Fe).filter(i=>i.endsWith(".json")),e=[];for(let i of s)try{let t=A.readFileSync($.join(Fe,i),"utf-8"),r=JSON.parse(t);e.push(r);}catch{}return e}function mo(){let s=On(),e=0;for(let i of s)Kc(i.pid)||(jn(i.pid),e++);return e}function Kc(s){try{return process.kill(s,0),!0}catch{return false}}function yo(){try{return execSync(`osascript -e '
104
+ tell application "System Events"
105
+ set frontApp to first application process whose frontmost is true
106
+ return bundle identifier of frontApp
107
+ end tell
108
+ '`,{encoding:"utf-8",timeout:3e3}).trim()||void 0}catch{return}}function ho(s){try{return execSync("git rev-parse --abbrev-ref HEAD",{cwd:s,encoding:"utf-8",timeout:3e3}).trim()||void 0}catch{return}}function bo(){return [{name:"paradigm_conductor_register",description:'Register this Claude Code session with Paradigm Conductor. Makes the session visible in the Conductor overlay for voice/gesture/gaze dispatch. Call this when the user says "/conduct" or wants to surface a session to Conductor. ~100 tokens.',inputSchema:{type:"object",properties:{label:{type:"string",description:'Human-readable label for this session (e.g., "backend refactor", "auth feature")'},terminal:{type:"string",description:'Terminal bundle ID (e.g., "com.mitchellh.ghostty"). Auto-detected if omitted.'}},required:[]},annotations:{title:"Register with Conductor",readOnlyHint:false,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"paradigm_conductor_unregister",description:"Unregister this Claude Code session from Paradigm Conductor. Removes it from the Conductor overlay. Call when ending a session or when the user wants to hide from Conductor. ~50 tokens.",inputSchema:{type:"object",properties:{},required:[]},annotations:{title:"Unregister from Conductor",readOnlyHint:false,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"paradigm_conductor_list",description:"List all Claude Code sessions currently registered with Paradigm Conductor. Shows PIDs, project dirs, and labels. ~150 tokens.",inputSchema:{type:"object",properties:{clean:{type:"boolean",description:"If true, clean up stale sessions (dead PIDs) before listing"}},required:[]},annotations:{title:"List Conductor sessions",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}}]}async function vo(s,e,i){switch(s){case "paradigm_conductor_register":{let t=process.pid,r=i.rootDir,n=e.terminal||yo(),o=ho(r),c;try{let l=execSync(`ps -o ppid= -p ${t}`,{encoding:"utf-8",timeout:3e3}).trim();c=parseInt(l,10),isNaN(c)&&(c=void 0);}catch{}let a=fo({pid:t,parentPid:c,projectDir:r,terminal:n,label:e.label,branch:o}),d=["\u2713 Registered with Conductor","",` PID: ${a.pid}`,` Project: ${a.projectDir}`];return a.branch&&d.push(` Branch: ${a.branch}`),a.label&&d.push(` Label: ${a.label}`),a.terminal&&d.push(` Terminal: ${a.terminal}`),d.push(` File: ~/.conductor/sessions/${a.pid}.json`),d.push(""),d.push("This session is now visible in Paradigm Conductor."),d.push("Conductor will auto-discover it via the registration file."),{text:d.join(`
109
+ `),handled:true}}case "paradigm_conductor_unregister":{let t=process.pid;return jn(t)?{text:`\u2713 Unregistered from Conductor (PID ${t}).
110
+ This session is no longer visible in the Conductor overlay.`,handled:true}:{text:`Session (PID ${t}) was not registered with Conductor.`,handled:true}}case "paradigm_conductor_list":{e.clean&&mo()>0;let t=On();if(t.length===0)return {text:`No sessions registered with Conductor.
111
+ Use paradigm_conductor_register or /conduct to register.`,handled:true};let r=[`${t.length} session(s) registered with Conductor:
112
+ `];for(let n of t){let o=[` PID ${n.pid}`];n.label&&o.push(`"${n.label}"`),o.push(`\u2014 ${n.projectDir}`),n.branch&&o.push(`(${n.branch})`),r.push(o.join(" "));}return e.clean&&r.push(`
113
+ (Stale sessions cleaned)`),{text:r.join(`
114
+ `),handled:true}}default:return {text:"",handled:false}}}b();function ko(){return [{name:"paradigm_symphony_peek",description:"Ultra-cheap inbox check \u2014 file stat only, no parsing. Returns { hasNew: true/false }. Use with /loop 10s for near-free monitoring. When hasNew is true, call paradigm_symphony_poll to read messages. ~15 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",description:"Short status blurb (same as poll). Updates heartbeat."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_poll",description:"Read inbox notes and process them. Call when paradigm_symphony_peek returns hasNew: true, or directly via /loop for continuous messaging. Returns unread notes formatted as markdown with thread context and suggested actions. Updates heartbeat and optional status blurb. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",description:'Short status blurb describing what you are currently working on (e.g., "Implementing auth middleware \u2014 3 files modified"). Visible to humans and other agents in the Network view.'}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_send",description:"Send a note to other agents or broadcast. Auto-creates thread if no threadRoot provided. Supports intents: question, context, proposal, decision, action, etc. ~100 tokens.",inputSchema:{type:"object",properties:{intent:{type:"string",enum:["question","context","clarification","proposal","verification","action","decision","alert","approval","rejection","reference","handoff","task","task-ack","progress","approval-request","approval-response","task-complete","task-failed"],description:"Message intent (what kind of message this is). Task protocol intents: task (assignment), task-ack, progress, approval-request, approval-response, task-complete, task-failed."},text:{type:"string",description:"Message text content"},parentId:{type:"string",description:"ID of message being replied to"},threadRoot:{type:"string",description:"Thread ID to post in (auto-created if omitted)"},recipients:{type:"array",items:{type:"string"},description:"Agent IDs to send to (omit for broadcast)"},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols referenced (e.g., ["#auth-service", "$login-flow"])'},diff:{type:"string",description:"Code diff to include with the message"},decision:{type:"string",description:"Decision text to record (for intent=decision)"}},required:["intent","text"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_status",description:"Show Symphony network status: linked agents (with awake/asleep detection), active threads, unread count, pending file requests. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_thread",description:"Get full thread context: all notes in order, participants, extracted decisions, and referenced symbols. ~200 tokens.",inputSchema:{type:"object",properties:{threadId:{type:"string",description:"Thread ID (thr-XXXXXXXX format)"},depth:{type:"number",description:"Maximum messages to return (default: 50)"}},required:["threadId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_request_file",description:"Request a file from another agent's project. Human approval required (unless auto-approved in trust config). Files matching hard-deny patterns (.env, *.key, etc.) are always blocked. ~100 tokens.",inputSchema:{type:"object",properties:{filePath:{type:"string",description:'Relative file path to request (e.g., "src/auth/middleware.ts")'},from:{type:"string",description:'Agent ID to request file from (e.g., "backend/core")'},reason:{type:"string",description:"Why this file is needed"},snippet:{type:"string",description:'Specific function or line range needed (e.g., "validateToken function" or "lines 50-100")'}},required:["filePath","from","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_approve_file",description:'Approve or deny a pending file request. Use action "approve" to send file, "deny" to reject, or "approve-redacted" to send with secrets stripped. ~100 tokens.',inputSchema:{type:"object",properties:{requestId:{type:"string",description:"File request ID (freq-XXXXXXXX format)"},action:{type:"string",enum:["approve","deny","approve-redacted"],description:"Approve, deny, or approve with redaction"},reason:{type:"string",description:"Reason for denial (required for deny action)"}},required:["requestId","action"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Qc(s,e){let i={progress:"in-progress","task-complete":"done","task-failed":"shelved"};try{let{updateTask:t,completeTask:r,shelveTask:n}=await import('./task-loader-HBZ3KRH2.js');for(let o of s){let c=i[o.intent];if(!c)continue;let a=o.metadata?.task?.taskId;if(a)try{let d=!1;if(c==="done")d=await r(e,a);else if(c==="shelved"){if(d=await n(e,a),d){let l=o.content?.text?`peer task-failed: ${o.content.text.slice(0,200)}`:"peer reported task-failed";await t(e,a,{crash_reason:l});}}else d=await t(e,a,{status:c});d?a$b.signal("!symphony-status-flowback").info("Applied peer status flow-back to local task",{taskId:a,intent:o.intent,status:c}):a$b.signal("!symphony-status-flowback").debug("Flow-back no-op (task absent or terminal already)",{taskId:a,intent:o.intent,status:c});}catch(d){a$b.signal("!symphony-status-flowback").warn("Per-note flow-back failed (non-fatal)",{taskId:a,intent:o.intent,error:d instanceof Error?d.message:String(d)});}}}catch(t){a$b.signal("!symphony-status-flowback").warn("Status flow-back pass failed (non-fatal)",{error:t instanceof Error?t.message:String(t)});}}async function _o(s$1,e,i){let t=n$4(i.rootDir);switch(t||(t=j$4(i.rootDir)),s$1){case "paradigm_symphony_peek":{let r=e.status;o$3(t.id,r);let{hasNew:n}=s(t.id),o=n?N$1("pending").length:0;return {handled:true,text:JSON.stringify(n?{hasNew:true,pendingFileRequests:o,action:"call paradigm_symphony_poll to read"}:{hasNew:false})}}case "paradigm_symphony_poll":{m$2(),S();let r=e.status;o$3(t.id,r);let n=v$2(t.id);if(n.length>0){let a=n[n.length-1].id;z$2(t.id,a),t$1(t.id);}B$1(t.id),n.length>0&&await Qc(n,i.rootDir);let o=N$1("pending");return n.length===0&&o.length===0?{handled:true,text:JSON.stringify({messages:0,note:"No new notes. Score is quiet.",identity:t.id})}:{handled:true,text:Zc(n,o)}}case "paradigm_symphony_send":{let r=e.intent,n=e.text,o=e.parentId,c=e.threadRoot,a=e.recipients,d=e.symbols,l=e.diff,p=e.decision,g=false;if(!c&&!o){let f=n.length>60?n.slice(0,60)+"...":n;c=C$1(f,it(t)).id,g=true;}let u;if(a&&a.length>0){let f=l$2();u=a.map(v=>{let h=f.find(b=>b.id===v);return h?it(h):{id:v,name:v,type:"agent"}});}let m=I$1({sender:it(t),recipients:u,intent:r,text:n,parentId:o,threadRoot:c,symbols:d,diff:l,decision:p}),y=J(m);if(sd(m).catch(()=>{}),g&&c){({timestamp:m.timestamp,sender:m.sender,content:{text:`Thread created: ${m.content.text.slice(0,60)}`}});fetch(`${In}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:"thread:created",category:"lifecycle",timestamp:m.timestamp,scopeValue:c,service:m.sender.project||"symphony",severity:"info",data:{topic:m.content.text.slice(0,60),initiator:m.sender.name,threadId:c}})}).catch(()=>{});}return {handled:true,text:JSON.stringify({sent:true,messageId:m.id,threadId:c,threadCreated:g,deliveredTo:y,intent:r})}}case "paradigm_symphony_status":{m$2();let r=l$2(),n=E$1("active"),o=v$2(t.id),c=N$1("pending"),a=[];try{let{loadPeers:d}=await import('./symphony-peers-X5NGWXFP.js');a=d().filter(p=>!p.revoked).map(p=>({id:p.id,address:p.address,agents:p.agents?.length??0,lastSeen:p.lastSeen}));}catch{}return {handled:true,text:JSON.stringify({identity:{id:t.id,project:t.project,role:t.role},agents:r.map(d=>({id:d.id,name:d.name,project:d.project,role:d.role,status:q$2(d)?"asleep":"awake",lastPoll:d.lastPoll,statusBlurb:d.statusBlurb})),peers:a,activeThreads:n.map(d=>({id:d.id,topic:d.topic,participants:d.participants.length,messageCount:d.messageCount,lastActivity:d.lastActivity})),unreadCount:o.length,pendingFileRequests:c.length},null,2)}}case "paradigm_symphony_thread":{let r=e.threadId,n=e.depth||50,o=D(r);if(!o)return {handled:true,text:JSON.stringify({error:`Thread not found: ${r}`})};let c=H$1(r).slice(0,n),a=[],d=new Set,l=new Set;for(let p of c){p.content.decision&&a.push(p.content.decision),p.intent==="decision"&&p.content.text&&a.push(p.content.text);for(let g of p.symbols)d.add(g);if(p.attachments)for(let g of p.attachments)g.type==="file"&&l.add(g.name);}return {handled:true,text:JSON.stringify({thread:{id:o.id,topic:o.topic,status:o.status,createdAt:o.createdAt,decision:o.decision},participants:o.participants,messages:c.map(p=>({id:p.id,sender:p.sender.name,intent:p.intent,text:p.content.text,timestamp:p.timestamp,symbols:p.symbols,hasDiff:!!p.content.diff,hasDecision:!!p.content.decision})),decisions:a,symbolsDiscussed:[...d],filesReferenced:[...l]},null,2)}}case "paradigm_symphony_request_file":{let r=e.filePath,n=e.from,o=e.reason,c=e.snippet,a=K$1();if(Q$1(r,a))return {handled:true,text:JSON.stringify({error:`File path "${r}" is on the hard-deny list and cannot be requested.`,deniedPatterns:a.defaults.neverApprove})};let d=L$1({filePath:r,requester:it(t),reason:o,snippet:c,threadRoot:void 0}),l=I$1({sender:it(t),recipients:[{id:n,name:n,type:"agent"}],intent:"fileRequest",text:`Requesting file: ${r}
115
+ Reason: ${o}${c?`
116
+ Snippet: ${c}`:""}`,symbols:[]});return J(l),{handled:true,text:JSON.stringify({requestId:d.request.requestId,status:"pending",filePath:r,from:n,message:`File request created. The owning agent's human must approve via "paradigm symphony approve ${d.request.requestId}" or "paradigm_symphony_approve_file".`})}}case "paradigm_symphony_approve_file":{let r=e.requestId,n=e.action,o=e.reason;if(n==="deny"){let d=P(r,o);return {handled:true,text:JSON.stringify({success:d,requestId:r,action:"denied",reason:o||"No reason provided"})}}let c=n==="approve-redacted",a=O(r,i.rootDir,c);return a.success?{handled:true,text:JSON.stringify({success:true,requestId:r,action:c?"approved-redacted":"approved",filePath:a.delivery?.filePath,size:a.delivery?.size,hash:a.delivery?.hash})}:{handled:true,text:JSON.stringify({success:false,requestId:r,error:a.error})}}default:return {handled:false,text:""}}}function it(s){return {id:s.id,name:s.name,type:s.type||"agent",project:s.project,role:s.role}}function Zc(s,e){let i=[],t=new Map;for(let r of s){let n=r.threadRoot||"direct";t.has(n)||t.set(n,[]),t.get(n).push(r);}for(let[r,n]of t){let o=r;if(r!=="direct"){let c=D(r);c&&(o=c.topic);}i.push(`## Symphony: ${n.length} new note${n.length!==1?"s":""} in "${o}"
117
+ `);for(let c=0;c<n.length;c++){let a=n[c],d=new Date(a.timestamp).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),l=`${a.sender.name}${a.sender.project?` (${a.sender.project})`:""}`;i.push(`### ${c+1}. ${l} \u2014 ${td(a.intent)} (${d})`),i.push(`> ${a.content.text.split(`
118
+ `).join(`
119
+ > `)}`),a.symbols.length>0&&i.push(`> Symbols: ${a.symbols.join(", ")}`),a.content.diff&&i.push(`
120
+ \`\`\`diff
121
+ ${a.content.diff}
122
+ \`\`\``),a.content.decision&&i.push(`
123
+ **Decision:** ${a.content.decision}`);let p=ed(a);p&&i.push(`
124
+ **Suggested action:** ${p}`),i.push("");}}if(e.length>0){i.push(`## Pending File Requests (${e.length})
125
+ `);for(let r of e)i.push(`- **${r.request.filePath}** from ${r.request.requester.name}: ${r.request.reason}`),i.push(` Approve: \`paradigm_symphony_approve_file({ requestId: "${r.request.requestId}", action: "approve" })\``);i.push("");}return i.join(`
126
+ `)}function ed(s){switch(s.intent){case "question":return 'Reply with paradigm_symphony_send using intent "context" or "clarification"';case "proposal":return 'Reply with intent "approval" or "rejection"';case "fileRequest":return "Use paradigm_symphony_approve_file to approve or deny";case "handoff":return "Review handoff context and continue the work";case "alert":return 'Investigate the alert and reply with intent "action"';case "verification":return 'Confirm with intent "approval" or clarify with "clarification"';default:return null}}function td(s){return s.charAt(0).toUpperCase()+s.slice(1)}var In="http://localhost:3838",wo=false;function nd(s){switch(s){case "question":return "note:question";case "context":return "note:context";case "clarification":return "note:clarification";case "proposal":return "note:proposal";case "verification":return "note:verification";case "action":return "note:action";case "decision":return "note:decision";case "alert":return "note:alert";case "approval":return "note:approval";case "rejection":return "note:rejection";case "reference":return "note:reference";case "handoff":return "note:handoff";case "fileRequest":return "file:requested";case "fileApproved":return "file:approved";case "fileDenied":return "file:denied";case "fileDelivery":return "file:delivered";default:return "note:context"}}function rd(s){if(s.startsWith("note:")){let e=s.split(":")[1];if(["question","context","clarification","verification","reference"].includes(e))return "dialogue";if(["proposal","action"].includes(e))return "action";if(["decision","approval","rejection"].includes(e))return "outcome";if(e==="alert")return "system";if(e==="handoff")return "lifecycle"}return s.startsWith("thread:")||s.startsWith("participant:")?"lifecycle":s.startsWith("file:")?"transfer":"dialogue"}async function sd(s){try{wo||(await fetch(`${In}/api/schemas`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:"paradigm-symphony",version:"1.0.0",name:"Symphony Conversations",description:"Agent-to-agent messaging events from The Score protocol"})}).catch(()=>{}),wo=!0);let e=nd(s.intent),i=rd(e);await fetch(`${In}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:e,category:i,timestamp:s.timestamp,scopeValue:s.threadRoot||s.id,service:s.sender.project||"symphony",severity:i==="system"?"error":i==="outcome"?"warn":"info",parentEventId:s.parentId,data:{sender:s.sender.name,senderRole:s.sender.role||"core",text:s.content.text,symbols:s.symbols,diff:s.content.diff,decision:s.content.decision,parentId:s.parentId,threadId:s.threadRoot}})});}catch{}}b();var So=/^[a-z0-9][a-z0-9-]{0,63}$/,An=["track","index","chronological","featured"],Dn=64,id=z.object({id:z.string().regex(So,"invalid section id"),name:z.string().min(1).max(120),order:z.number().int().min(0).max(9999),style:z.enum(An,{errorMap:()=>({message:`section.style must be one of ${An.join("|")}`})}),description:z.string().max(1e3).optional(),default:z.boolean({invalid_type_error:"section.default must be a boolean"}).optional()}).strict(),$n=z.array(id).max(Dn,`sections must contain \u2264${Dn} entries`);z.object({sections:$n.optional()}).passthrough();z.object({section:z.string().regex(So).optional(),order:z.number().int().min(0).max(9999).optional()}).passthrough();var Po="@a-company/university",Ro=".paradigm/university",To=".paradigm/cache/packs.json",L=class extends Error{constructor(i,t){super(`pack-load failed (${i}: ${t})`);this.errorClass=i;this.detail=t;this.name="PackLoadError";}},od=["id","name","version","schema_version","tenant_kind"],ad=new Set(["first-party","project","external"]),xo={id:"main",name:"Curriculum",order:1,style:"track",default:true};function cd(s){if(s==null)return [{...xo}];if(Array.isArray(s)&&s.length===0)return [{...xo}];let e=$n.safeParse(s);if(!e.success){let n=e.error.issues[0],o=n?`${n.path.join(".")||"sections"}: ${n.message}`:"sections failed schema validation";throw new L("manifest-invalid",o)}let i=e.data.map(n=>({...n})),t=new Set;for(let n of i){if(t.has(n.id))throw new L("manifest-invalid",`duplicate section id "${n.id}"`);t.add(n.id);}i.length===1&&!i[0].default&&(i[0]={...i[0],default:true});let r=i.filter(n=>n.default===true);if(r.length>1)throw new L("manifest-invalid",`at most one section may set default: true (found ${r.length})`);return i.sort((n,o)=>n.order-o.order||n.id.localeCompare(o.id)),i}function jt(s){let e=$.join(s,a$d),i=xt(e);switch(i.status){case "missing":throw new L("missing-manifest",`no ${a$d} at pack root`);case "unparseable":throw new L("manifest-unparseable",i.detail);case "invalid":throw new L("manifest-invalid",i.detail);case "ok":{let t=i.data;if(!t||typeof t!="object")throw new L("manifest-invalid","manifest is not an object");for(let r of od){let n=t[r];if(n==null||n==="")throw new L("missing-required-field",`required field ${String(r)} is missing or empty`)}if(!ad.has(String(t.tenant_kind)))throw new L("missing-required-field","tenant_kind must be one of first-party|project|external");return t.sections=cd(t.sections),t}}}function Nn(s){let e=pd(s);if(e)return e;let i=[],t=$.join(s,"node_modules",Po);if(A.existsSync($.join(t,a$d)))try{let n=jt(t);i.push({manifest:n,rootDir:t,source:"first-party"});}catch(n){a$b.component("#pack-loader").warn("first-party pack manifest invalid",{errorClass:n instanceof L?n.errorClass:"other"});}for(let n of dd(s))try{let o=jt(n);i.push({manifest:o,rootDir:n,source:"npm"});}catch(o){a$b.component("#pack-loader").warn("npm pack manifest invalid",{errorClass:o instanceof L?o.errorClass:"other"});}let r=$.join(s,Ro);if(A.existsSync(r)&&A.statSync(r).isDirectory()){let n=$.join(r,a$d),o;if(A.existsSync(n))try{o=jt(r),i.push({manifest:o,rootDir:r,source:"local"});}catch(a){a$b.component("#pack-loader").warn("local pack manifest invalid",{errorClass:a instanceof L?a.errorClass:"other"});}let c=o?.id??"project";for(let a of ld(r))try{let d=jt(a);i.push({manifest:d,rootDir:a,source:"local",parentPackId:c});}catch(d){a$b.component("#pack-loader").warn("discipline sub-pack manifest invalid",{errorClass:d instanceof L?d.errorClass:"other"});}}return ud(s,i),i}function dd(s){let e=$.join(s,"package.json");if(!A.existsSync(e))return [];let i;try{i=JSON.parse(A.readFileSync(e,"utf8"));}catch{return []}let t=new Set([...Object.keys(i.dependencies||{}),...Object.keys(i.devDependencies||{}),...Object.keys(i.peerDependencies||{})]);if(t.size===0)return [];let r=$.join(s,"node_modules");if(!A.existsSync(r))return [];let n=[];for(let o of t){if(o===Po)continue;let c=$.join(r,o,"package.json");if(!A.existsSync(c))continue;let a;try{a=JSON.parse(A.readFileSync(c,"utf8"));}catch{continue}let d=a.paradigm?.universityPack;if(typeof d!="string"||d.length===0)continue;let l=$.resolve($.dirname(c),d);A.existsSync($.join(l,a$d))&&n.push(l);}return n}function ld(s){let e=[],i;try{i=A.readdirSync(s,{withFileTypes:!0});}catch{return e}for(let t of i){if(!t.isDirectory()||t.name.startsWith("."))continue;let r=$.join(s,t.name);A.existsSync($.join(r,a$d))&&e.push(r);}return e}function Ot(s,e){if(typeof s!="string"||s.length===0)throw new Error("resolveEntryAddress: address must be a non-empty string");let i=s.indexOf(":");if(i!==-1){let r=s.slice(0,i),n=s.slice(i+1);if(!r||!n)throw new Error("resolveEntryAddress: malformed <pack-id>:<entry-id> address");return {packId:r,entryId:n}}let t=s;if(e.candidatePacks&&e.entryExistsIn){let r=e.candidatePacks.filter(n=>e.entryExistsIn(n,t));if(r.length>1){let n=r.map(o=>`${o}:${t}`).join(", ");throw new Error(`resolveEntryAddress: bare entry id "${t}" is ambiguous across packs. Candidates: ${n}`)}if(r.length===1)return {packId:r[0],entryId:t}}return {packId:e.activePack,entryId:t}}function Co(s){try{return A.statSync($.join(s,"node_modules")).mtime.getTime()}catch{return}}function jo(s){try{return A.statSync($.join(s,Ro)).mtime.getTime()}catch{return}}function pd(s){let e=$.join(s,To);if(!A.existsSync(e))return null;let i;try{i=JSON.parse(A.readFileSync(e,"utf8"));}catch{return null}if(i.version!==1||!Array.isArray(i.packs))return null;let t=Co(s),r=jo(s);return i.node_modules_mtime_ms!==t||i.local_university_mtime_ms!==r?null:i.packs.map(n=>({manifest:n.manifest,rootDir:n.rootDir,source:n.source,...n.parentPackId?{parentPackId:n.parentPackId}:{}}))}function ud(s,e){let i=$.join(s,To);try{A.mkdirSync($.dirname(i),{recursive:!0});let t={version:1,node_modules_mtime_ms:Co(s),local_university_mtime_ms:jo(s),packs:e.map(r=>({manifest:r.manifest,rootDir:r.rootDir,source:r.source,...r.parentPackId?{parentPackId:r.parentPackId}:{}}))};A.writeFileSync(i,JSON.stringify(t,null,2),"utf8");}catch{}}function Oo(){let s=process.env.PARADIGM_AUTHOR;if(s)return Fn(s);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Fn(e)}catch{}try{let e=fi.userInfo().username;if(e)return Fn(e)}catch{}return "unknown"}function Fn(s){return s.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function Io(){return new Date().toISOString().slice(0,10)}function Ee(s,e){let i=[];try{i=Nn(s);}catch{}if(e){let a=i.find(d=>d.manifest.id===e);if(a)return {packId:a.manifest.id,packRoot:a.rootDir,packs:i}}let t=i.find(a=>a.manifest.tenant_kind==="project");if(t)return {packId:t.manifest.id,packRoot:t.rootDir,packs:i};let r=i.find(a=>a.manifest.tenant_kind==="first-party");if(r)return {packId:r.manifest.id,packRoot:r.rootDir,packs:i};let n=d$a(s);return {packId:e$7(n)?.id??"project",packRoot:n,packs:i}}var fd=$.join(".paradigm","university");function qe(s,e){return $.resolve(e)===$.resolve(s,fd)}function Do(){return [{name:"paradigm_university_search",description:"Search university content by type, tag, difficulty, or symbol. v6.0: result ids are <pack-id>:<entry-id> (minor-breaking). ~150 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["note","policy","guide","runbook","quiz","path"],description:"Filter by content type"},tag:{type:"string",description:"Filter by tag prefix"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"],description:"Filter by difficulty level"},symbol:{type:"string",description:'Filter by Paradigm symbol (e.g., "#api-gateway")'},query:{type:"string",description:"Free-text search in title and tags"},category:{type:"string",description:'Filter by category ID (e.g., "paradigm-core", "extracurricular")'},track:{type:"string",enum:["core","extracurricular"],description:"Filter by track"},pack:{type:"string",description:"v6.0: target a specific content pack by id (default: project pack if present, else first-party)"},section:{type:"string",description:"v6.5: filter by section id (within the active pack)"},limit:{type:"number",description:"Maximum results (default: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_get",description:"Fetch a content item by ID. Accepts bare id or <pack-id>:<entry-id>. Returns full content (body for notes/policies, questions for quizzes). ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID: bare (N-foo) or qualified (paradigm:N-foo)"},pack:{type:"string",description:"v6.0: disambiguate a bare id against a specific pack (optional)"}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_create",description:"Create a new university content item (note, policy, quiz, or path). v6.0: honors optional pack selector. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["note","policy","guide","runbook","quiz","path"],description:"Content type to create"},title:{type:"string",description:"Content title"},body:{type:"string",description:"Markdown body for notes/policies. Quiz/path YAML content for those types."},tags:{type:"array",items:{type:"string"},description:"Tags for classification"},symbols:{type:"array",items:{type:"string"},description:"Paradigm symbols referenced by this content"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"],description:"Difficulty level (default: beginner)"},estimatedMinutes:{type:"number",description:"Estimated reading/completion time in minutes"},prerequisites:{type:"array",items:{type:"string"},description:"IDs of prerequisite content items"},category:{type:"string",description:"Category ID for the content (default: project defaultCategory)"},pack:{type:"string",description:"v6.0: target a specific pack by id (default: project pack)"},passThreshold:{type:"number",description:"For quizzes: pass threshold 0.0-1.0 (default: 0.7)"},questions:{type:"array",description:"For quizzes: array of {id, question, choices: {A:..., B:...}, correct, explanation?}"},ordered:{type:"boolean",description:"For learning paths: whether steps must be completed in order"},steps:{type:"array",description:"For learning paths: array of {content, required, passRequired?, note?}"}},required:["type","title"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_university_update",description:"Update an existing content item. id accepts bare or <pack-id>:<entry-id>. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID to update (bare or qualified)"},pack:{type:"string",description:"v6.0: disambiguate a bare id against a specific pack (optional)"},title:{type:"string",description:"New title"},body:{type:"string",description:"New body content"},tags:{type:"array",items:{type:"string"},description:"New tags"},symbols:{type:"array",items:{type:"string"},description:"New symbols"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"]},estimatedMinutes:{type:"number"},category:{type:"string",description:"Category ID for the content"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_university_onboard",description:"Get recommended onboarding sequence. v6.0: honors optional pack selector. ~200 tokens.",inputSchema:{type:"object",properties:{student:{type:"string",description:"Student name to check completion (auto-resolved if omitted)"},pack:{type:"string",description:"v6.0: target a specific pack (default: project pack)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_validate",description:"Validate content integrity. v6.0: honors optional pack selector. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID to validate (bare or qualified; validates all if omitted)"},pack:{type:"string",description:"v6.0: target a specific pack (default: all packs)"},deep:{type:"boolean",description:"Enable deep cross-reference checks against scan-index (default: false)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_pack_list",description:"v6.0: List discovered content packs with manifest metadata. ~200 tokens.",inputSchema:{type:"object",properties:{tenant_kind:{type:"string",enum:["first-party","project","external"],description:"Filter by tenant kind"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function $o(s,e,i){if(s==="paradigm_university_pack_list"){let t=e.tenant_kind,r=[];try{r=Nn(i.rootDir);}catch{r=[];}let o={packs:(t?r.filter(a=>a.manifest.tenant_kind===t):r).map(a=>{let d=(a.manifest.sections??[]).slice().sort((l,p)=>l.order-p.order||l.id.localeCompare(p.id));return {id:a.manifest.id,name:a.manifest.name,version:a.manifest.version,tenant_kind:a.manifest.tenant_kind,...a.manifest.disciplines&&a.manifest.disciplines.length>0?{discipline:a.manifest.disciplines[0]}:{},entry_count:s$1(a.rootDir),sections:d,path:a.rootDir}})},c=JSON.stringify(o,null,2);return a$1(c.length,s),{handled:true,text:c}}if(s==="paradigm_university_search"){let t=e.pack,{packId:r,packRoot:n}=Ee(i.rootDir,t),c=e$7(n)?.sections?.find(g=>g.default===true)?.id??"main",{entries:a,total:d,returned:l}=q$3(i.rootDir,{type:e.type,tag:e.tag,difficulty:e.difficulty,symbol:e.symbol,query:e.query,category:e.category,track:e.track,section:e.section,limit:e.limit},t?n:void 0),p=JSON.stringify({count:a.length,total:d,returned:l,truncated:d>l,pack:r,results:a.map(g=>({id:`${r}:${g.id}`,title:g.title,type:g.type,difficulty:g.difficulty,tags:g.tags,symbols:g.symbols,section:g.section??c,...typeof g.order=="number"?{order:g.order}:{}}))},null,2);return a$1(p.length,s),{handled:true,text:p}}if(s==="paradigm_university_get"){let t=e.id;if(!t)return {handled:true,text:JSON.stringify({error:"id is required"})};let r=e.pack,{packId:n,packRoot:o}=Ee(i.rootDir,r),c;try{c=Ot(t,{activePack:n}).entryId;}catch{c=t;}let a=h$5(i.rootDir,c,o);if(a){let g=JSON.stringify({id:a.frontmatter.id,title:a.frontmatter.title,type:a.frontmatter.type,author:a.frontmatter.author,created:a.frontmatter.created,updated:a.frontmatter.updated,tags:a.frontmatter.tags,symbols:a.frontmatter.symbols,difficulty:a.frontmatter.difficulty,prerequisites:a.frontmatter.prerequisites,body:a.body},null,2);return a$1(g.length,s),{handled:true,text:g}}let d=j$5(i.rootDir,c,o);if(d){let g=JSON.stringify(d,null,2);return a$1(g.length,s),{handled:true,text:g}}let l=l$3(i.rootDir,c,o);if(l){let g=JSON.stringify(l,null,2);return a$1(g.length,s),{handled:true,text:g}}let p=JSON.stringify({error:`Content "${t}" not found`});return a$1(p.length,s),{handled:true,text:p}}if(s==="paradigm_university_create"){let t=e.type,r=e.title;if(!t||!r)return {handled:true,text:JSON.stringify({error:"type and title are required"})};let n=e.pack,{packRoot:o}=Ee(i.rootDir,n),c=Oo(),a=Io(),d=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40);if(t==="quiz"){let y=`Q-${d}`,f={id:y,title:r,description:e.body||"",author:c,created:a,updated:a,tags:e.tags||[],symbols:e.symbols||[],difficulty:e.difficulty||"beginner",estimatedMinutes:e.estimatedMinutes,passThreshold:e.passThreshold??.7,questions:e.questions||[],...e.category?{category:e.category}:{}};k$2(i.rootDir,f,o),qe(i.rootDir,o)&&t$2(i.rootDir);let v=JSON.stringify({created:y,type:"quiz",file:`content/quizzes/${y}.yaml`},null,2);return a$1(v.length,s),{handled:true,text:v}}if(t==="path"){let y=`LP-${d}`,f={id:y,title:r,description:e.body||"",author:c,created:a,updated:a,tags:e.tags||[],ordered:e.ordered??true,steps:e.steps||[],...e.category?{category:e.category}:{}};m$3(i.rootDir,f,o),qe(i.rootDir,o)&&t$2(i.rootDir);let v=JSON.stringify({created:y,type:"path",file:`content/paths/${y}.yaml`},null,2);return a$1(v.length,s),{handled:true,text:v}}let p=`${t==="policy"?"P":"N"}-${d}`,g={id:p,title:r,type:t,author:c,created:a,updated:a,tags:e.tags||[],symbols:e.symbols||[],difficulty:e.difficulty||"beginner",estimatedMinutes:e.estimatedMinutes,prerequisites:e.prerequisites||[],...e.category?{category:e.category}:{}};i$3(i.rootDir,g,e.body||"",o),qe(i.rootDir,o)&&t$2(i.rootDir);let m=JSON.stringify({created:p,type:t,file:`content/${t==="policy"?"policies":"notes"}/${p}.md`},null,2);return a$1(m.length,s),{handled:true,text:m}}if(s==="paradigm_university_update"){let t=e.id;if(!t)return {handled:true,text:JSON.stringify({error:"id is required"})};let r=e.pack,{packId:n,packRoot:o}=Ee(i.rootDir,r),c;try{c=Ot(t,{activePack:n}).entryId;}catch{c=t;}let a=Io(),d=h$5(i.rootDir,c,o);if(d){let u={...d.frontmatter};e.title&&(u.title=e.title),e.tags&&(u.tags=e.tags),e.symbols&&(u.symbols=e.symbols),e.difficulty&&(u.difficulty=e.difficulty),e.estimatedMinutes!==void 0&&(u.estimatedMinutes=e.estimatedMinutes),e.category!==void 0&&(u.category=e.category),u.updated=a;let m=e.body??d.body;i$3(i.rootDir,u,m,o),qe(i.rootDir,o)&&t$2(i.rootDir);let y=JSON.stringify({updated:c,type:u.type},null,2);return a$1(y.length,s),{handled:true,text:y}}let l=j$5(i.rootDir,c,o);if(l){e.title&&(l.title=e.title),e.tags&&(l.tags=e.tags),e.symbols&&(l.symbols=e.symbols),e.difficulty&&(l.difficulty=e.difficulty),e.category!==void 0&&(l.category=e.category),l.updated=a,k$2(i.rootDir,l,o),qe(i.rootDir,o)&&t$2(i.rootDir);let u=JSON.stringify({updated:c,type:"quiz"},null,2);return a$1(u.length,s),{handled:true,text:u}}let p=l$3(i.rootDir,c,o);if(p){e.title&&(p.title=e.title),e.tags&&(p.tags=e.tags),e.category!==void 0&&(p.category=e.category),p.updated=a,m$3(i.rootDir,p,o),qe(i.rootDir,o)&&t$2(i.rootDir);let u=JSON.stringify({updated:c,type:"path"},null,2);return a$1(u.length,s),{handled:true,text:u}}let g=JSON.stringify({error:`Content "${t}" not found`});return a$1(g.length,s),{handled:true,text:g}}if(s==="paradigm_university_onboard"){let t=e.student||Oo(),r=e.pack,{packId:n,packRoot:o}=Ee(i.rootDir,r),c=f$7(i.rootDir).branding.name;if(r){let l=e$7(o);l?.name&&(c=l.name);}let a=x$2(i.rootDir,t,r?o:void 0),d=JSON.stringify({university:c,pack:n,student:t,...a},null,2);return a$1(d.length,s),{handled:true,text:d}}if(s==="paradigm_university_validate"){let t=e.pack,{packId:r,packRoot:n}=Ee(i.rootDir,t),o=e.id,c=o;if(o)try{c=Ot(o,{activePack:r}).entryId;}catch{}let a=v$3(i.rootDir,{id:c,deep:e.deep},t?n:void 0),d=JSON.stringify({pack:r,...a},null,2);return a$1(d.length,s),{handled:true,text:d}}return {handled:false,text:""}}function md(s){try{let e=$.join(s,".paradigm","config.yaml");if(A.existsSync(e)){let t=Ie.load(A.readFileSync(e,"utf-8")).platform;if(t?.port&&typeof t.port=="number")return t.port}}catch{}return 3850}function yd(s){try{let e=$.join(s,".paradigm","config.yaml");if(A.existsSync(e)){let i=Ie.load(A.readFileSync(e,"utf-8")),t=i.project||$.basename(s),r=i.role||"core";return `${t}/${r}`}}catch{}return `${$.basename(s)}/core`}async function Me(s,e,i){let t=md(s),r=yd(s),n=`http://localhost:${t}/api/platform/agent-command`;try{let o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:e,agentId:r,payload:i}),signal:AbortSignal.timeout(5e3)});if(!o.ok){let a=await o.text();return {ok:!1,error:`HTTP ${o.status}: ${a}`}}return {ok:!0,data:await o.json()}}catch(o){return {ok:false,error:`Platform server unreachable (${o instanceof Error?o.message:String(o)}). Is \`paradigm serve\` running?`}}}function No(){return [{name:"paradigm_platform_navigate",description:"Navigate the Platform UI to a section, select a symbol, or open a lore entry. The browser updates in real-time. If the user is actively interacting, shows a prompt instead of auto-navigating. ~100 tokens.",inputSchema:{type:"object",properties:{section:{type:"string",enum:["overview","lore","graph","sentinel","university","symphony"],description:"Section to navigate to"},symbol:{type:"string",description:'Symbol to select (e.g., "#payment-service")'},loreId:{type:"string",description:"Lore entry ID to open in lore section"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_highlight",description:"Temporarily highlight symbols in the Platform UI with a pulsing glow. Auto-expires after duration. Use to draw attention to specific components during explanations. ~100 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbol IDs to highlight (e.g., ["#payment-service", "#api-gateway"])'},color:{type:"string",description:"Highlight color (CSS color, defaults to agent color)"},duration:{type:"number",description:"Duration in milliseconds (default: 5000)"},pulse:{type:"boolean",description:"Whether to pulse the highlight (default: true)"},label:{type:"string",description:"Optional label shown near highlighted symbols"}},required:["symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_annotate",description:"Show a toast notification, callout on a graph node, or badge in the Platform UI. Use for communicating decisions, warnings, or context to the user visually. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["toast","callout","badge"],description:"Annotation type: toast (notification), callout (floating note on graph node), badge (icon on symbol)"},message:{type:"string",description:"Annotation message text"},symbol:{type:"string",description:"Symbol to attach callout/badge to (required for callout/badge)"},severity:{type:"string",enum:["info","warning","error","success"],description:"Visual severity (default: info)"},duration:{type:"number",description:"Auto-dismiss duration in milliseconds (default: 6000, 0 = persistent)"}},required:["type","message"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_observe",description:"Read the current Platform UI state: what section the user is viewing, what symbol is selected, theme, connected agents, and active highlights/annotations. ~150 tokens.",inputSchema:{type:"object",properties:{detail:{type:"string",enum:["summary","full"],description:"Level of detail (default: summary)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_platform_clear",description:"Remove agent highlights, annotations, or all agent effects from the Platform UI. ~50 tokens.",inputSchema:{type:"object",properties:{target:{type:"string",enum:["highlights","annotations","all"],description:"What to clear (default: all)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Fo(s,e,i){switch(s){case "paradigm_platform_navigate":{let t=await Me(i.projectDir,"navigate",{section:e.section,symbol:e.symbol,loreId:e.loreId});if(!t.ok)return {handled:true,text:`**Navigate failed:** ${t.error}`};let r=t.data;if(r.navigated){let n=[];r.section&&n.push(`section: **${r.section}**`),r.symbol&&n.push(`symbol: **${r.symbol}**`);let o=r.userActive?" (user was active \u2014 shown as prompt)":"";return {handled:true,text:`Navigated to ${n.join(", ")}${o}`}}return {handled:true,text:`Navigation skipped: ${r.reason}`}}case "paradigm_platform_highlight":{let t=await Me(i.projectDir,"highlight",{symbols:e.symbols,color:e.color,duration:e.duration,pulse:e.pulse,label:e.label});if(!t.ok)return {handled:true,text:`**Highlight failed:** ${t.error}`};let r=t.data;return r.highlighted?{handled:true,text:`Highlighted **${r.count}** symbol(s)${e.label?` with label "${e.label}"`:""}`}:{handled:true,text:`Highlight skipped: ${r.reason}`}}case "paradigm_platform_annotate":{let t=await Me(i.projectDir,"annotate",{type:e.type,message:e.message,symbol:e.symbol,severity:e.severity,duration:e.duration});if(!t.ok)return {handled:true,text:`**Annotate failed:** ${t.error}`};let r=t.data;return r.annotated?{handled:true,text:`Created ${e.type} annotation: "${e.message}"`}:{handled:true,text:`Annotation skipped: ${r.reason}`}}case "paradigm_platform_observe":{let t=await Me(i.projectDir,"observe",{detail:e.detail});if(!t.ok)return {handled:true,text:`**Observe failed:** ${t.error}`};let r=t.data,n=r.state,o=[`## Platform UI State
127
+ `];o.push(`- **Connected:** ${r.connected?"Yes":"No"} (${r.users} browser client(s))`),o.push(`- **Section:** ${n.section}`),o.push(`- **Selected symbol:** ${n.selectedSymbol||"none"}`),o.push(`- **Theme:** ${n.theme}`),o.push(`- **Muted:** ${n.muted?"Yes \u2014 agent actions silently discarded":"No"}`);let c=r.agents;if(c?.length){o.push(`
128
+ ### Connected Agents (${c.length})`);for(let a of c)o.push(`- \`${a.agentId}\` (since ${a.connectedAt})`);}if(e.detail==="full"){let a=r.highlights,d=r.annotations;a?.length&&o.push(`
129
+ ### Active Highlights: ${a.length}`),d?.length&&o.push(`
130
+ ### Active Annotations: ${d.length}`);}return {handled:true,text:o.join(`
131
+ `)}}case "paradigm_platform_clear":{let t=await Me(i.projectDir,"clear",{target:e.target});return t.ok?{handled:true,text:`Cleared ${t.data.target} agent effects`}:{handled:true,text:`**Clear failed:** ${t.error}`}}default:return {handled:false,text:""}}}z$1();function Ho(){return [{name:"paradigm_agent_list",description:"List all agent identity profiles with top expertise areas. Shows agents from both global (~/.paradigm/agents/) and project (.paradigm/agents/) scopes. Returns profile summaries with personality and top symbols. ~150 tokens.",inputSchema:{type:"object",properties:{scope:{type:"string",enum:["all","global","project"],description:"Filter by scope (default: all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_expertise",description:"Find which agents are best qualified to work on a specific symbol. Returns agents ranked by confidence score from their expertise history. Use for symbol-to-agent routing. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to query (e.g., "#auth-middleware", "$checkout-flow")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns only top agent (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_get",description:"Get full agent profile including personality, expertise table, transferable patterns, and per-project contexts. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID or nickname (e.g., "architect", "Apex", "Jinx")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_bench",description:"Bench an agent \u2014 Maestro will skip this agent during orchestration and nomination scoring. Use when an agent is noisy or unhelpful. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to bench (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_agent_activate",description:"Activate a benched agent \u2014 restore it to active Maestro orchestration. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to activate (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Eo(s,e,i){switch(s){case "paradigm_agent_list":{let t=i$4(i.rootDir),r=b$a(i.rootDir);if(t.length===0)return {handled:true,text:JSON.stringify({count:0,agents:[],note:"No .agent profiles found. Create one with `paradigm agent create <id> --global` or via paradigm_agent_create."},null,2)};let n=r?t.filter(d=>r.includes(d.id)):t,o=r?t.length-n.length:0,c=i$5(i.rootDir),a=new Map(c.map(d=>[d.id,d]));return {handled:true,text:JSON.stringify({count:n.length,totalAvailable:t.length,...r?{rosterActive:true,inactiveCount:o}:{rosterActive:false},agents:n.map(d=>{let l=a.get(d.id);return {id:d.id,role:d.role,nickname:d.nickname,personality:d.personality,...l?{lastSession:l.lastSession?.summary?.slice(0,100),lastSessionAge:l.lastSession?.date,pendingWork:l.pendingWork?.length||0,sessionsOnProject:l.sessionsOnProject||0}:{},topExpertise:(d.expertise||[]).sort((p,g)=>g.confidence-p.confidence).slice(0,5).map(p=>({symbol:p.symbol,confidence:parseFloat(p.confidence.toFixed(2)),sessions:p.sessions})),projectContexts:Object.keys(d.contexts||{}),transferableCount:(d.transferable||[]).length,...d.attention?.threshold!=null?{threshold:d.attention.threshold}:{}}})},null,2)}}case "paradigm_agent_expertise":{let t=e.symbol,r=e.response_format,n=l$4(i.rootDir,t);return r==="concise"?{handled:true,text:JSON.stringify({symbol:t,topAgent:n.length>0?{id:n[0].agentId,confidence:parseFloat(n[0].entry.confidence.toFixed(2))}:null},null,2)}:{handled:true,text:JSON.stringify({symbol:t,agents:n.map(o=>({agentId:o.agentId,confidence:parseFloat(o.entry.confidence.toFixed(2)),sessions:o.entry.sessions,lastTouch:o.entry.lastTouch})),count:n.length,...n.length===0?{note:`No agents have recorded expertise on ${t}. Run \`paradigm agent sync\` to bootstrap from lore history.`}:{}},null,2)}}case "paradigm_agent_get":{let t=e.id,r=h$6(i.rootDir,t);if(!r){let o=i$4(i.rootDir),c=t.toLowerCase(),a=o.filter(d=>d.nickname?.toLowerCase().includes(c)||d.id.includes(c));return {handled:true,text:JSON.stringify({error:`Agent "${t}" not found by ID or nickname`,...a.length>0?{didYouMean:a.map(d=>({id:d.id,nickname:d.nickname}))}:{suggestion:`Create with \`paradigm agent create ${t} --global\``}},null,2)}}let n=y$2(r);return {handled:true,text:JSON.stringify({id:r.id,role:r.role,description:r.description,version:r.version,personality:r.personality,expertise:(r.expertise||[]).sort((o,c)=>c.confidence-o.confidence).map(o=>({symbol:o.symbol,confidence:parseFloat(o.confidence.toFixed(2)),sessions:o.sessions,lastTouch:o.lastTouch})),transferable:(r.transferable||[]).map(o=>({id:o.id,description:o.description,learnedIn:o.learnedIn,appliedIn:o.appliedIn,successRate:o.successRate})),contexts:r.contexts,created:r.created,updated:r.updated,...r.permissions?{permissions:r.permissions}:{},integrity:n},null,2)}}case "paradigm_agent_bench":{let t=e.id,r=h$6(i.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Agent "${t}" not found`},null,2)};let n=r.id,o=b$a(i.rootDir);return o?o=o.filter(c=>c!==n):o=e$8().filter(c=>c!==n),d$8(i.rootDir,o),{handled:true,text:JSON.stringify({id:n,...r.nickname?{nickname:r.nickname}:{},removedFromRoster:true,rosterCount:o.length,note:`${r.nickname||n} (${n}) removed from this project's roster. Still available globally.`},null,2)}}case "paradigm_agent_activate":{let t=e.id,r=h$6(i.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Agent "${t}" not found`},null,2)};let n=r.id,o=b$a(i.rootDir);return o&&(o.includes(n)||(o.push(n),d$8(i.rootDir,o))),{handled:true,text:JSON.stringify({id:n,...r.nickname?{nickname:r.nickname}:{},addedToRoster:true,rosterCount:o?.length??"all (no roster)",note:`${r.nickname||n} (${n}) is active on this project's roster.`},null,2)}}default:return {handled:false,text:""}}}var Jo=$.join(".paradigm","authority.yaml");async function qo(s){let e=$.join(s,Jo),i;try{i=await Ge.readFile(e,"utf8");}catch(r){if(r.code==="ENOENT")return null;throw r}let t=Ie.load(i);return t==null||typeof t!="object"?{version:"1.0",schema:"v0-experimental",claims:{}}:((!t.claims||typeof t.claims!="object")&&(t.claims={}),t)}async function Lo(s,e){let i=$.join(s,Jo);await Ge.mkdir($.dirname(i),{recursive:true});let t=Ie.dump(e,{lineWidth:100,sortKeys:false});await Ge.writeFile(i,t,"utf8");}function Mo(){return [{name:"paradigm_authority_claim",description:"Claim authority over a scope in .paradigm/authority.yaml. Idempotent on `scope` \u2014 re-claiming overwrites severity/claimant. Single-claimant-per-scope at v6.1. Severity vocab: advise|warn|block (policy stance, distinct from remediation severity). ~100 tokens.",inputSchema:{type:"object",properties:{claimant:{type:"string",description:'Archetype id (e.g., "compliance")'},scope:{type:"string",description:'Scope key (e.g., "aspect-coverage", "aspect-drift", "anchor-staleness")'},severity:{type:"string",enum:["advise","warn","block"],description:"Policy stance. Default: advise."}},required:["claimant","scope"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_authority_release",description:"Release authority over a scope. Removes the claim entry from .paradigm/authority.yaml. Succeeds on archetype-default-created scopes (user/agent can override defaults). ~80 tokens.",inputSchema:{type:"object",properties:{claimant:{type:"string",description:"Archetype id (used for audit; release is by scope key)"},scope:{type:"string",description:"Scope key to release"}},required:["claimant","scope"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function Go(s,e,i){if(s==="paradigm_authority_claim"){let t=e.claimant,r=e.scope,n=e.severity??"advise";if(!t||!r)return {handled:true,text:JSON.stringify({error:"Missing required field: claimant, scope"},null,2)};let o=new Date().toISOString(),c={claimant:t,severity:n,since:o,source:"explicit"},a=await qo(i.rootDir)??{version:"1.0",schema:"v0-experimental",claims:{}};return a.claims[r]=c,await Lo(i.rootDir,a),{handled:true,text:JSON.stringify({scope:r,claimant:t,severity:n,source:"explicit",since:o},null,2)}}if(s==="paradigm_authority_release"){let t=e.claimant,r=e.scope;if(!t||!r)return {handled:true,text:JSON.stringify({error:"Missing required field: claimant, scope"},null,2)};let n=await qo(i.rootDir);if(!n||!(r in n.claims))return {handled:true,text:JSON.stringify({scope:r,released:false,note:"no active claim on this scope"},null,2)};let o=n.claims[r].claimant;return delete n.claims[r],await Lo(i.rootDir,n),{handled:true,text:JSON.stringify({scope:r,released:true,previousClaimant:o},null,2)}}return {handled:false,text:""}}j();function Uo(){return [{name:"paradigm_notebook_search",description:"Search agent notebook entries by concept, tag, or keyword. Notebooks are curated snippet libraries distilled from lore for reuse in orchestration. ~150 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:'Agent ID to search notebooks for (e.g., "architect", "builder")'},query:{type:"string",description:"Search query \u2014 matches concepts, tags, context, and snippet content"},concepts:{type:"array",items:{type:"string"},description:'Filter by concept tags (e.g., ["auth", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Filter by classification tags"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level (default: "detailed")'}},required:["agentId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_notebook_add",description:"Add a new entry to an agent's notebook. Use for curated, reusable snippets that should be available across sessions. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add notebook entry for"},context:{type:"string",description:"When to apply this snippet \u2014 the retrieval context"},snippet:{type:"string",description:"The reusable code/knowledge snippet"},concepts:{type:"array",items:{type:"string"},description:'Concept tags for retrieval (e.g., ["auth", "jwt", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Classification tags"},confidence:{type:"number",description:"Confidence score 0.0-1.0 (default: 0.7)"},scope:{type:"string",enum:["global","project"],description:'Where to store: global travels across projects (default: "global")'},parentId:{type:"string",description:"Optional: ID of the parent notebook entry this was derived from (soft provenance, no validation)"},lineageType:{type:"string",enum:["fix","derive","capture","promote"],description:"Optional: relationship to parent \u2014 fix (corrects parent), derive (modified from parent), capture (new observation), promote (promoted from lower confidence)"}},required:["agentId","context","snippet","concepts"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_notebook_promote",description:"Extract a lore entry into a notebook entry. Distills the lore into a reusable snippet with provenance linking. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add the promoted entry to"},loreEntryId:{type:"string",description:'Lore entry ID to promote (e.g., "L-2026-03-15-...")'},scope:{type:"string",enum:["global","project"],description:'Where to store (default: "global")'}},required:["agentId","loreEntryId"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Wo(s,e,i){switch(s){case "paradigm_notebook_search":{let t=e.agentId,r=e.query,n=e.concepts,o=e.tags,c=e.response_format,a;return r?a=e$9(t,r,i.rootDir):a=b$b(t,i.rootDir,{concepts:n,tags:o}),c==="concise"?{handled:true,text:JSON.stringify({agentId:t,count:a.length,entries:a.map(d=>({id:d.id,context:d.context,concepts:d.concepts}))},null,2)}:{handled:true,text:JSON.stringify({agentId:t,count:a.length,entries:a.map(d=>({id:d.id,context:d.context,snippet:d.snippet.length>500?d.snippet.slice(0,500)+"...":d.snippet,concepts:d.concepts,tags:d.tags,appliedCount:d.appliedCount,confidence:d.confidence,provenance:d.provenance}))},null,2)}}case "paradigm_notebook_add":{let t=e.agentId,r=e.context,n=e.snippet,o=e.concepts||[],c=e.tags||[],a=e.confidence??.7,d=e.scope||(i.rootDir?"project":"global"),l=e.parentId,p=e.lineageType,g=e.publishable,u=e.scope,m={context:r,snippet:n,provenance:{source:"manual",createdBy:t},confidence:a,concepts:o,tags:c,...u?{scope:u}:{},...g!==void 0?{publishable:g}:{},...l?{parentId:l}:{},...p?{lineageType:p}:{}},y=g$4(t,m,d,i.rootDir);return {handled:true,text:JSON.stringify({action:"notebook_add",id:y.entry.id,agentId:t,scope:d,filePath:y.filePath,concepts:y.entry.concepts,...l?{parentId:l}:{},...p?{lineageType:p}:{}},null,2)}}case "paradigm_notebook_promote":{let t=e.agentId,r=e.loreEntryId,n=e.scope||(i.rootDir?"project":"global"),o=await h$7(t,r,i.rootDir,n);return o?{handled:true,text:JSON.stringify({action:"notebook_promote",id:o.entry.id,agentId:t,loreEntryId:r,scope:n,publishScope:o.entry.scope,publishable:o.entry.publishable,filePath:o.filePath,concepts:o.entry.concepts,confidence:o.entry.confidence,note:o.entry.scope!=="generalizable"?`scope auto-classified as "${o.entry.scope}" \u2014 confirm or override with "nevr notebook audit"`:void 0},null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry "${r}" not found`,suggestion:"Check the lore entry ID with paradigm_lore_search"},null,2)}}default:return {handled:false,text:""}}}function zo(){return [{name:"paradigm_docs_manifest",description:"Get the documentation sidebar manifest \u2014 all symbols grouped by type with counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_docs_page",description:"Get page data for a symbol, flow, portal, or custom docs page. Returns structured data for rendering. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol ID (e.g., "cli-commands", "checkout-flow", "authenticated"). Do not include the prefix (#, $, ^, !, ~).'},flow:{type:"string",description:'Flow ID (e.g., "$init-flow"). Include the $ prefix.'},portal:{type:"boolean",description:"Set to true to get the portal overview page (gates + routes)."},slug:{type:"string",description:'Custom page slug (e.g., "getting-started").'}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_docs_search",description:"Search across all documentation content \u2014 symbols, descriptions, tags, custom pages. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query string"},limit:{type:"number",description:"Maximum results (default: 20)"}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Bo(s,e,i){if(s==="paradigm_docs_manifest"){let t=a$7(i.rootDir),r=d$2(i.rootDir,t),n=JSON.stringify(r,null,2);return a$1(n.length,s),{handled:true,text:n}}if(s==="paradigm_docs_page"){if(e.portal){let r=g$1(i.rootDir),n=JSON.stringify(r,null,2);return a$1(n.length,s),{handled:true,text:n}}if(e.flow){let r=e.flow,n=f$3(i.rootDir,r);if(!n){let c=JSON.stringify({error:`Flow "${r}" not found`});return a$1(c.length,s),{handled:true,text:c}}let o=JSON.stringify(n,null,2);return a$1(o.length,s),{handled:true,text:o}}if(e.slug){let r=a$7(i.rootDir),n=c$3(i.rootDir,e.slug,r);if(!n){let c=JSON.stringify({error:`Page "${e.slug}" not found`});return a$1(c.length,s),{handled:true,text:c}}let o=JSON.stringify(n,null,2);return a$1(o.length,s),{handled:true,text:o}}if(e.symbol){let r=e$2(i.rootDir,e.symbol);if(!r){let o=JSON.stringify({error:`Symbol "${e.symbol}" not found`});return a$1(o.length,s),{handled:true,text:o}}let n=JSON.stringify(r,null,2);return a$1(n.length,s),{handled:true,text:n}}let t=JSON.stringify({error:"Provide one of: symbol, flow, portal, or slug"});return a$1(t.length,s),{handled:true,text:t}}if(s==="paradigm_docs_search"){let t=e.query;if(!t)return {handled:true,text:JSON.stringify({error:"query is required"})};let r=h$1(i.rootDir,t,e.limit),n=JSON.stringify({count:r.length,results:r},null,2);return a$1(n.length,s),{handled:true,text:n}}return {handled:false,text:""}}f$1();e();function Vo(){return [{name:"paradigm_work_log_record",description:"Record a work log entry \u2014 what got done. Auto-attached to sprint boards and standup summaries. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent that did the work (e.g., "builder")'},summary:{type:"string",description:"What was done"},outcome:{type:"string",enum:["pass","fail","partial","blocked"],description:"How it went"},task_ref:{type:"string",description:'Ticket/issue reference (e.g., "ENG-142")'},files_modified:{type:"array",items:{type:"string"},description:"Files that were modified"},symbols_touched:{type:"array",items:{type:"string"},description:"Paradigm symbols touched"},next_steps:{type:"array",items:{type:"string"},description:"What's left to do"},blockers:{type:"array",items:{type:"string"},description:"What's blocking progress"},duration_minutes:{type:"number",description:"How long it took"},commit:{type:"string",description:"Git commit hash"}},required:["agent","summary","outcome"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_work_log_search",description:"Search work log entries \u2014 what got done. Returns recent work, filterable by agent, outcome, symbol, date. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent"},outcome:{type:"string",enum:["pass","fail","partial","blocked"]},task_ref:{type:"string",description:"Filter by ticket reference"},symbol:{type:"string",description:"Filter by symbol touched"},dateFrom:{type:"string",description:"Start date (YYYY-MM-DD)"},dateTo:{type:"string",description:"End date (YYYY-MM-DD)"},limit:{type:"number",description:"Max entries to return (default 20)"},summary:{type:"boolean",description:"Return aggregate summary instead of entries"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_journal_record",description:"Record a learning journal entry \u2014 what an agent learned. Agent-private, travels across projects. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent who learned this (e.g., "security")'},trigger:{type:"string",enum:["correction_received","confidence_miss","pattern_discovered","debate_loss","failure_analysis","human_feedback","self_reflection"],description:"What triggered this learning moment"},insight:{type:"string",description:"The insight itself"},project:{type:"string",description:"Project where this happened"},transferable:{type:"boolean",description:"Whether this applies to other projects"},confidence_before:{type:"number",description:"Confidence before (0.0-1.0)"},confidence_after:{type:"number",description:"Confidence after (0.0-1.0)"},pattern:{type:"object",properties:{id:{type:"string"},applies_when:{type:"string"},correct_approach:{type:"string"}}},linked_work_log:{type:"string",description:"Work log entry that prompted this"},tags:{type:"array",items:{type:"string"}}},required:["agent","trigger","insight","project","transferable"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_journal_search",description:"Search learning journal entries \u2014 what agents learned. Can search across all agents or a specific one. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent (omit for all agents)"},trigger:{type:"string",description:"Filter by trigger type"},project:{type:"string",description:"Filter by project"},transferable:{type:"boolean",description:"Only show transferable insights"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},stats:{type:"boolean",description:"Return stats instead of entries (requires agent)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_decision_record",description:"Record a team decision \u2014 what we decided and why. Institutional memory with rationale and alternatives. ~100 tokens.",inputSchema:{type:"object",properties:{title:{type:"string",description:"Decision title"},decision:{type:"string",description:"The decision itself"},rationale:{type:"string",description:"Why this was chosen"},participants:{type:"array",items:{type:"object",properties:{id:{type:"string"},role:{type:"string",enum:["human","agent"]},stance:{type:"string",enum:["proposed","supported","dissented","abstained","neutral"]}},required:["id","role","stance"]}},alternatives_considered:{type:"array",items:{type:"object",properties:{option:{type:"string"},rejected_because:{type:"string"}}}},symbols_affected:{type:"array",items:{type:"string"}},status:{type:"string",enum:["active","proposed"],description:"Decision status (default: active)"},tags:{type:"array",items:{type:"string"}}},required:["title","decision","rationale","participants"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_decision_search",description:"Search team decisions \u2014 what we decided. Find active decisions by symbol, participant, status. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",enum:["active","superseded","deprecated","proposed","rejected"]},participant:{type:"string",description:"Filter by participant ID"},symbol:{type:"string",description:"Filter by affected symbol"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},summary:{type:"boolean",description:"Return aggregate summary"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Yo(s,e,i){let t=r=>JSON.stringify(r,null,2);switch(s){case "paradigm_work_log_record":{let r=c$4(i.rootDir),{filtered:n}=d$3(e.summary,r,"work_log"),o=a$a(i.rootDir,{agent:e.agent,summary:n,outcome:e.outcome,task_ref:e.task_ref,files_modified:e.files_modified,symbols_touched:e.symbols_touched,next_steps:e.next_steps,blockers:e.blockers,duration_minutes:e.duration_minutes,commit:e.commit});return {text:t({recorded:true,id:o.id,timestamp:o.timestamp}),handled:true}}case "paradigm_work_log_search":{if(e.summary){let n=d$6(i.rootDir,7);return {text:t(n),handled:true}}let r=b$9(i.rootDir,{agent:e.agent,outcome:e.outcome,task_ref:e.task_ref,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:t({count:r.length,entries:r.map(n=>({id:n.id,agent:n.agent,summary:n.summary,outcome:n.outcome,timestamp:n.timestamp,symbols_touched:n.symbols_touched,task_ref:n.task_ref}))}),handled:true}}case "paradigm_journal_record":{let r=c$4(i.rootDir),{filtered:n}=d$3(e.insight,r,"learning_journal"),o=a$9(e.agent,{trigger:e.trigger,insight:n,project:e.project,transferable:e.transferable,confidence_before:e.confidence_before,confidence_after:e.confidence_after,pattern:e.pattern,linked_work_log:e.linked_work_log,tags:e.tags});return {text:t({recorded:true,id:o.id,agent:o.agent,timestamp:o.timestamp}),handled:true}}case "paradigm_journal_search":{if(e.stats&&e.agent){let n=e$4(e.agent);return {text:t(n),handled:true}}let r=e.agent?b$8(e.agent,{trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20}):d$5({trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:t({count:r.length,entries:r.map(n=>({id:n.id,agent:n.agent,trigger:n.trigger,insight:n.insight.slice(0,200),project:n.project,transferable:n.transferable,timestamp:n.timestamp}))}),handled:true}}case "paradigm_decision_record":{let r=c$4(i.rootDir),{filtered:n}=d$3(e.decision,r,"team_decisions"),{filtered:o}=d$3(e.rationale,r,"team_decisions"),c=a$8(i.rootDir,{title:e.title,decision:n,rationale:o,participants:e.participants,alternatives_considered:e.alternatives_considered,symbols_affected:e.symbols_affected,status:e.status||"active",tags:e.tags}),a=d$4(i.rootDir,c.id);return {text:t({recorded:true,id:c.id,title:c.title,timestamp:c.timestamp,...a?{companion_lore_id:a}:{}}),handled:true}}case "paradigm_decision_search":{if(e.summary){let n=h$2(i.rootDir);return {text:t(n),handled:true}}let r=e$3(i.rootDir,{status:e.status,participant:e.participant,symbol:e.symbol,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:t({count:r.length,entries:r.map(n=>({id:n.id,title:n.title,status:n.status,decision:n.decision.slice(0,200),participants:n.participants.map(o=>`${o.id} (${o.stance})`),symbols_affected:n.symbols_affected,timestamp:n.timestamp}))}),handled:true}}default:return {text:`Unknown streams tool: ${s}`,handled:false}}}var at=["purpose-coverage","purpose-exists","portal-gates","aspect-anchors","purpose-freshness","aspect-advisory","lore-required","habits-blocking","purpose-required-patterns","drift-detection","portal-compliance","graduation-tracking","orchestration-required"],Ko={strict:{"purpose-coverage":"block","purpose-exists":"block","portal-gates":"block","aspect-anchors":"block","purpose-freshness":"warn","aspect-advisory":"warn","lore-required":"block","habits-blocking":"block","purpose-required-patterns":"block","drift-detection":"block","portal-compliance":"block","graduation-tracking":"warn","orchestration-required":"block"},balanced:{"purpose-coverage":"block","purpose-exists":"warn","portal-gates":"warn","aspect-anchors":"warn","purpose-freshness":"warn","aspect-advisory":"off","lore-required":"warn","habits-blocking":"block","purpose-required-patterns":"warn","drift-detection":"warn","portal-compliance":"warn","graduation-tracking":"off","orchestration-required":"warn"},minimal:{"purpose-coverage":"warn","purpose-exists":"off","portal-gates":"off","aspect-anchors":"off","purpose-freshness":"off","aspect-advisory":"off","lore-required":"off","habits-blocking":"warn","purpose-required-patterns":"off","drift-detection":"off","portal-compliance":"off","graduation-tracking":"off","orchestration-required":"off"},none:{"purpose-coverage":"off","purpose-exists":"off","portal-gates":"off","aspect-anchors":"off","purpose-freshness":"off","aspect-advisory":"off","lore-required":"off","habits-blocking":"off","purpose-required-patterns":"off","drift-detection":"off","portal-compliance":"off","graduation-tracking":"off","orchestration-required":"off"}};function At(s){let e=$.join(s,".paradigm","config.yaml");if(!A.existsSync(e))return {};try{return Ie.load(A.readFileSync(e,"utf8"))||{}}catch{return {}}}function En(s,e){let i=$.join(s,".paradigm","config.yaml");A.writeFileSync(i,Ie.dump(e,{lineWidth:120,noRefs:true}),"utf8");}function Dt(s){let e=s.enforcement?.level||"none",i=Ko[e]||Ko.none,t=s.enforcement?.checks||{},r=s.enforcement?.orchestration?.threshold??3,n={...i};for(let[o,c]of Object.entries(t))at.includes(o)&&Xo(c)&&(n[o]=c);return n.orchestrationThreshold=r,n}function Xo(s){return s==="block"||s==="warn"||s==="off"}function hd(s){return s==="strict"||s==="balanced"||s==="minimal"||s==="none"}function bd(s){return at.includes(s)}var vd=[{name:"paradigm_compliance_promote",description:"Record a user's response to Rune's enforcement-level promotion offer. Call this after presenting the symbol-tracking invitation. Response 'minimal' or 'balanced' enables enforcement at that level and records the promotion state; 'snooze' defers for 7 days; 'never' suppresses the offer permanently.",inputSchema:{type:"object",properties:{response:{type:"string",enum:["minimal","balanced","snooze","never"],description:"User's chosen response to the promotion offer"}},required:["response"]}},{name:"paradigm_enforcement_configure",description:"View or modify stop hook enforcement levels. Actions: status (view current), set-level (change preset), override (set per-check severity), reset (clear overrides). ~250 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["status","set-level","override","reset"],description:"Action to perform."},level:{type:"string",enum:["strict","balanced","minimal","none"],description:"Enforcement preset level (for set-level action)."},checkId:{type:"string",description:"Check ID to override (for override action). One of: "+at.join(", ")},severity:{type:"string",enum:["block","warn","off"],description:"Severity to set for the check (for override action)."}},required:["action"]}}];async function wd(s,e){let{action:i,level:t,checkId:r,severity:n}=e;switch(i){case "status":{let o=At(s.rootDir),c=Dt(o),a=o.enforcement?.level||"none",d=o.enforcement?.checks||{},l=o.enforcement?.orchestration?.threshold??3;return JSON.stringify({level:a,orchestrationThreshold:l,orchestrationNote:"Threshold is compared against magnitude score (not just file count). Magnitude = source files + cross-package penalty + security-adjacent penalty + symbol file changes.",overrides:Object.keys(d).length>0?d:void 0,effective:c,checkIds:[...at],presetLevels:["strict","balanced","minimal","none"]},null,2)}case "set-level":{if(!t||!hd(t))return JSON.stringify({error:`Invalid level "${t}". Must be one of: strict, balanced, minimal, none`});let o=At(s.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.level=t,o.enforcement.checks={},En(s.rootDir,o);let c=Dt(o);return JSON.stringify({success:true,level:t,message:`Enforcement level set to "${t}". Per-check overrides cleared.`,effective:c},null,2)}case "override":{if(!r||!bd(r))return JSON.stringify({error:`Invalid checkId "${r}". Must be one of: ${at.join(", ")}`});if(!n||!Xo(n))return JSON.stringify({error:`Invalid severity "${n}". Must be one of: block, warn, off`});let o=At(s.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.checks||(o.enforcement.checks={}),o.enforcement.checks[r]=n,En(s.rootDir,o);let c=Dt(o);return JSON.stringify({success:true,checkId:r,severity:n,message:`Override set: ${r} = ${n}`,effective:c},null,2)}case "reset":{let o=At(s.rootDir);o.enforcement&&(o.enforcement.checks={}),En(s.rootDir,o);let c=Dt(o),a=o.enforcement?.level||"none";return JSON.stringify({success:true,message:`All per-check overrides cleared. Preset "${a}" is now fully in effect.`,effective:c},null,2)}default:return JSON.stringify({error:`Unknown action "${i}". Must be one of: status, set-level, override, reset`})}}function Qo(){return vd}async function Zo(s,e,i){if(s==="paradigm_enforcement_configure"){let t=await wd(i,e);return a$1(t.length,"paradigm_enforcement_configure"),{handled:true,text:t}}if(s==="paradigm_compliance_promote"){let t=e.response,{recordPromotion:r}=await import('./rune-promotion-3JQ5LMWK.js');r(i.rootDir,t);let n;if(t==="minimal"||t==="balanced"){let o=$.join(i.rootDir,".paradigm","config.yaml");if(A.existsSync(o)){let c=Ie.load(A.readFileSync(o,"utf8"));c&&typeof c=="object"&&((!c.enforcement||typeof c.enforcement!="object")&&(c.enforcement={}),c.enforcement.level=t,A.writeFileSync(o,Ie.dump(c,{lineWidth:-1,noRefs:true,sortKeys:false}),"utf8"));}n=JSON.stringify({ok:true,message:`Symbol tracking enabled at "${t}". Rune is now active.`,level:t});}else t==="snooze"?n=JSON.stringify({ok:true,message:"Got it \u2014 I'll ask again in 7 days.",state:"snoozed"}):n=JSON.stringify({ok:true,message:"Understood. I won't bring this up again.",state:"never"});return a$1(n.length,"paradigm_compliance_promote"),{handled:true,text:n}}return {handled:false,text:""}}b();function ea(){return [{name:"paradigm_arch_status",description:"Get the architectural layer map summary and drift report. Shows tiers, their components, and any symbols that are unassigned (not in any tier) or missing from the index. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_arch_diagram",description:"Render the architectural map as a Mermaid diagram. Returns a Mermaid graph TD string showing tiers and their links. ~150 tokens.",inputSchema:{type:"object",properties:{format:{type:"string",enum:["mermaid"],description:'Output format. Only "mermaid" supported (default: "mermaid").'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ta(s,e,i){try{if(s==="paradigm_arch_status"){let t=b$c(i.rootDir);if(!t)return {text:JSON.stringify({exists:!1,message:"No arch.yaml found. Create .paradigm/arch.yaml to start mapping your architecture."}),handled:!0};let r=d$9(i.rootDir,i);return {text:JSON.stringify({exists:!0,version:t.version,tierCount:t.tiers.length,tiers:t.tiers.map(n=>({id:n.id,label:n.label,responsibility:n.responsibility,framework:n.tech?.framework??"",componentCount:n.components.length,components:n.components})),links:t.links,drift:{unassigned:r.unassigned,missing_purpose:r.missing_purpose,clean:r.unassigned.length===0&&r.missing_purpose.length===0}}),handled:!0}}if(s==="paradigm_arch_diagram"){let t=b$c(i.rootDir);if(!t)return {text:JSON.stringify({error:"No arch.yaml found. Cannot render diagram."}),handled:!0};let r=e$a(t);return {text:JSON.stringify({format:"mermaid",diagram:r}),handled:!0}}return {handled:!1,text:""}}catch(t){return a$b.component("#arch-tools").warn(`Unexpected error in arch tool ${s}`,{error:String(t)}),{text:JSON.stringify({error:String(t)}),handled:true}}}function kd(s,e){let i=[];for(let t=0;t<=e.length;t++)i[t]=[t];for(let t=0;t<=s.length;t++)i[0][t]=t;for(let t=1;t<=e.length;t++)for(let r=1;r<=s.length;r++)e.charAt(t-1)===s.charAt(r-1)?i[t][r]=i[t-1][r-1]:i[t][r]=Math.min(i[t-1][r-1]+1,i[t][r-1]+1,i[t-1][r]+1);return i[e.length][s.length]}function na(s,e,i={}){let{maxDistance:t=3,maxResults:r=5}=i,n=s.toLowerCase(),o=[];for(let c of e){let a=c.toLowerCase();if(a===n){o.push({match:c,distance:0});continue}if(a.includes(n)||n.includes(a)){o.push({match:c,distance:1});continue}let d=kd(n,a);d<=t&&o.push({match:c,distance:d});}return o.sort((c,a)=>c.distance!==a.distance?c.distance-a.distance:c.match.localeCompare(a.match)),o.slice(0,r)}v();function xd(s,e){let i=new a$3(s),t=e||(async()=>{}),r=o=>async(c,a,d)=>o(c,a,d),n=o=>async(c,a,d)=>o(c,a,d,t);return i.registerAll([{key:"context",tier:"core",getToolsList:c,handleTool:r(d$1)},{key:"navigate",tier:"core",getToolsList:b$4,handleTool:r(c$1)},{key:"tags",tier:"core",getToolsList:ui,handleTool:r(gi)},{key:"purpose-portal",tier:"core",getToolsList:ki,handleTool:n(_i)},{key:"pm",tier:"core",getToolsList:Pi,handleTool:r(Ri)},{key:"reindex",tier:"core",getToolsList:n$1,handleTool:n(o)},{key:"docs",tier:"core",getToolsList:zo,handleTool:r(Bo)},{key:"ripple",tier:"core",getToolsList:g,handleTool:r(h)},{key:"captain",tier:"core",getToolsList:x$1,handleTool:r(y$1)}]),i.registerAll([{key:"wisdom",tier:"feature",getToolsList:n$2,handleTool:r(o$1)},{key:"history",tier:"feature",getToolsList:Zs,handleTool:r(ei)},{key:"lore",tier:"feature",getToolsList:v$1,handleTool:r(w)},{key:"streams",tier:"feature",getToolsList:Vo,handleTool:r(Yo)},{key:"ambient",tier:"feature",getToolsList:a$4,handleTool:r(b$6)},{key:"sentinel",tier:"feature",getToolsList:ti,handleTool:r(ni)},{key:"flows",tier:"feature",getToolsList:ri,handleTool:r(si)},{key:"fixtures",tier:"feature",getToolsList:di,handleTool:r(li)},{key:"orchestration",tier:"feature",getToolsList:b$5,handleTool:r(c$2)},{key:"habits",tier:"feature",getToolsList:Ci,handleTool:r(ji)},{key:"tasks",tier:"feature",getToolsList:Mi,handleTool:r(Gi)},{key:"personas",tier:"feature",getToolsList:Zi,handleTool:r(eo)},{key:"protocols",tier:"feature",getToolsList:p$1,handleTool:r(q)},{key:"symphony",tier:"feature",getToolsList:ko,handleTool:r(_o)},{key:"university",tier:"feature",getToolsList:Do,handleTool:r($o)},{key:"agents",tier:"feature",getToolsList:Ho,handleTool:r(Eo)},{key:"authority",tier:"feature",getToolsList:Mo,handleTool:r(Go)},{key:"propose-block",tier:"feature",getToolsList:a$5,handleTool:r(b$7)},{key:"notebooks",tier:"feature",getToolsList:Uo,handleTool:r(Wo)},{key:"aspect-graph",tier:"feature",getToolsList:Li,handleTool:r(Ji)},{key:"enforcement",tier:"feature",getToolsList:Qo,handleTool:r(Zo),detect:o=>A.existsSync($.join(o,".paradigm","config.yaml"))},{key:"graph",tier:"feature",getToolsList:ro,handleTool:r(so),detect:o=>A.existsSync($.join(o,".paradigm","aspect-graph.db"))},{key:"arch",tier:"feature",getToolsList:ea,handleTool:r(ta),detect:o=>A.existsSync($.join(o,a$6))}]),i.registerAll([{key:"conductor",tier:"advanced",getToolsList:bo,handleTool:r(vo)},{key:"platform",tier:"advanced",getToolsList:No,handleTool:r(Fo)},{key:"pipeline",tier:"advanced",getToolsList:co,handleTool:r(lo)},{key:"graduation",tier:"advanced",getToolsList:Di,handleTool:r($i)}]),i}function Pd(s,e){let i=u=>u.toLowerCase().replace(/\/+$/,""),t=i(s),r=i(e);if(t===r)return 1;let n=u=>!u.includes("/")&&u.includes("."),o=u=>n(u)?u.split("."):u.split("/").filter(Boolean),c=o(t),a=o(r);if(n(t)||n(r)){let u=n(t)?t.split("."):t.split("/").filter(Boolean),m=n(r)?r.split("."):r.split("/").filter(Boolean),y=0;for(let f=0;f<Math.min(u.length,m.length)&&u[f]===m[f];f++)y++;return y>0?Math.min(1,.5+y/Math.max(u.length,m.length)*.5):0}let d=0,l=Math.max(c.length,a.length);for(let u=0;u<l;u++){let m=c[u]||"",y=a[u]||"";m===y?d++:m.startsWith(":")&&y.startsWith(":")?d+=.9:m.startsWith(":")||y.startsWith(":")?d+=.7:(m.replace(/s$/,"")===y.replace(/s$/,"")||y.replace(/s$/,"")===m.replace(/s$/,""))&&(d+=.8);}let p=d/l,g=c.length===a.length?.1:0;return Math.min(1,p+g)}function Rd(){return [{name:"paradigm_search",description:"Search for Paradigm symbols by name, description, or tags. Includes fuzzy matching for typo tolerance. Returns matching symbols with names, paths, types, and descriptions. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query (matches symbol names, descriptions, tags)"},type:{type:"string",enum:["component","flow","gate","signal","aspect"],description:"Optional: filter by symbol type (v2: #component, $flow, ^gate, !signal, ~aspect)"},limit:{type:"number",description:"Maximum results to return (default: 10)"},fuzzy:{type:"boolean",description:"Enable fuzzy matching for typos (default: true)"},includeWorkspace:{type:"boolean",description:"Also search sibling workspace projects (default: false). Requires workspace configured in config.yaml."},componentType:{type:"string",description:'Filter components by type (e.g., "view", "service", "tool"). Only applies to #component symbols.'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["find","lookup","locate","where is","which symbol","find symbol"]},{name:"paradigm_related",description:"Get all symbols related to a given symbol. Call before modifying code to understand what uses this symbol and what it depends on. Returns uses/used-by lists with symbol types. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to find relations for"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_status",description:"Get project overview \u2014 call this at session start for orientation. Shows symbol counts, project health, and a pointer to the full capability guide. ~100 tokens.",inputSchema:{type:"object",properties:{response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["health","overview","dashboard","project status","orientation"]},{name:"paradigm_gates_for_route",description:"Suggest which gates should be applied to a route based on patterns in the project. Returns suggested gates with confidence scores and existing patterns. ~150 tokens.",inputSchema:{type:"object",properties:{route:{type:"string",description:"Route path (e.g., /api/users, /admin/settings)"},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["route"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["auth","permissions","route security","what gates","protect route"]},{name:"paradigm_plugin_check",description:"Check for updates to installed Claude Code plugins. Reports which marketplace clones have newer remote commits and which cached versions are stale.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_workspace_reindex",description:"Rebuild scan-index.json for all workspace members. Requires workspace configured in config.yaml. Returns per-member symbol counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_tool_activate",description:"Activate an advanced-tier tool module for this session. Advanced tools are not loaded by default to reduce tool count. Call with a feature key to make its tools available. ~50 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:'Feature key to activate (e.g., "graph", "heatmap", "pipeline", "conductor", "platform")'}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}function eg(s,e,i){let t$1=e(),r$1=xd(t$1.rootDir,i);s.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[...Rd(),...r$1.getActiveTools()]})),s.setRequestHandler(CallToolRequestSchema,async n$1=>{let{name:o,arguments:c}=n$1.params;b$2(o,c??{});let a$3=e(),d$1=j$1();d$1.setRootDir(a$3.rootDir);let l=null,p$1=null;d$1.hasRecoveredThisSession()||(l=await e$1(a$3.rootDir),p$1=a(),b$3(),d$1.markRecovered());let g=await(async()=>{switch(o){case "paradigm_search":{let{query:u,type:m,limit:y=10,fuzzy:f=true,includeWorkspace:v=false,componentType:h,response_format:b}=c,w=`search:${u}:${m||""}:${y}:${f}:${v}:${h||""}`,S=await f$2.getOrCompute(w,()=>{let P=t(a$3.index,u);return m&&(P=P.filter(j=>j.type===m)),h&&(P=P.filter(j=>j.componentType===h)),P}),x=[];if(S.length===0&&f){let P=C(a$3.index),j=P.map(I=>I.symbol);x=na(u,j,{maxDistance:3,maxResults:5}),x.length>0&&(S=x.map(I=>P.find(R=>R.symbol===I.match)).filter(I=>I!=null),m&&(S=S.filter(I=>I.type===m)));}S=S.slice(0,y);let _={query:u,count:S.length,results:S.map(P=>({symbol:P.symbol,type:P.type,description:P.description,filePath:P.filePath,...P.componentType?{componentType:P.componentType}:{},...P.parentSymbol?{parentSymbol:P.parentSymbol}:{}}))};if(x.length>0&&(_.fuzzyMatched=true,_.fuzzyNote=`No exact matches for "${u}". Showing similar symbols.`,_.suggestions=x.map(P=>({symbol:P.match,distance:P.distance}))),v&&a$3.workspace){let P=a$2(a$3.workspace,u),j=m?P.filter(I=>I.type===m):P;j.length>0&&(_.workspaceResults=j.slice(0,y).map(I=>({symbol:I.symbol,type:I.type,description:I.description,filePath:I.filePath,project:I.project})),_.workspaceCount=j.length);}b==="concise"&&(_.results=S.map(P=>({symbol:P.symbol,type:P.type})),delete _.fuzzyMatched,delete _.fuzzyNote,delete _.suggestions,delete _.workspaceResults,delete _.workspaceCount);let C$1=JSON.stringify(_,null,2);return a$1(C$1.length,o),{content:[{type:"text",text:C$1}]}}case "paradigm_related":{let{symbol:u}=c,m=p(a$3.index,u);if(!m){let h=d(a$3.rootDir,u,{maxResults:20});if(h.length===0){let _=JSON.stringify({error:"Symbol not found",symbol:u,fallback:"searched",referencesFound:0,recovery:["Run `paradigm_search` with a partial name to find similar symbols","Check `.purpose` files for symbol definitions","Use `paradigm_status` to see available symbols by type","The symbol may not be indexed yet - run `paradigm scan`"]},null,2);return a$1(_.length,o),{content:[{type:"text",text:_}]}}let b=[...new Set(h.map(_=>_.filePath))],w=h.filter(_=>_.context==="purpose"),S=h.filter(_=>_.context==="code"),x=JSON.stringify({symbol:u,status:"not-indexed",fallback:"grep-search",note:"Approximate relationships from grep \u2014 run `paradigm scan` for accurate graph data.",usedBy:b.slice(0,10).map(_=>({file:_,references:h.filter(C=>C.filePath===_).length})),uses:[],summary:{totalFiles:b.length,totalReferences:h.length,purposeFileRefs:w.length,codeRefs:S.length},suggestion:"Run `paradigm scan` to enable full relationship tracking"},null,2);return a$1(x.length,o),{content:[{type:"text",text:x}]}}let y$1=x(a$3.index,u),f=y(a$3.index,u),v=JSON.stringify({symbol:m.symbol,type:m.type,description:m.description,usedBy:y$1.map(h=>({symbol:h.symbol,type:h.type,description:h.description})),uses:f.map(h=>({symbol:h.symbol,type:h.type,description:h.description}))},null,2);return a$1(v.length,o),{content:[{type:"text",text:v}]}}case "paradigm_status":{let u$1=c.response_format,m=await f$2.getOrCompute("status",async()=>{let f=B(a$3.index),v=Object.values(f).reduce((T,D)=>T+D,0),h={};for(let T of Object.keys(f)){let D=r(a$3.index,T);h[T]=D.slice(0,3).map(q=>q.symbol);}let b=fi.platform(),w=b==="win32",S=w?"PowerShell/CMD":b==="darwin"?"zsh/bash":"bash",x;try{let T=await u(a$3.rootDir);T&&T.health.total>0&&(x=T.health);}catch{}let _=r(a$3.index,"component"),C={};for(let T of _)T.componentType&&(C[T.componentType]=(C[T.componentType]||0)+1);let P=_.filter(T=>!T.componentType).length,j;try{let{checkPurposeHealth:T}=await import('./integrity-checker-DHGMZQDG.js');j=T(a$3.aggregation.purposeFiles,a$3.rootDir).healthScore;}catch{}let I;try{let{countNotebookReferences:T}=await import('./session-work-log-T2IE4Y4T.js'),D=T(a$3.rootDir);D>0&&(I=D);}catch{}let R;try{let{getComplianceTrend:T,getHealthDot:D}=await import('./compliance-health-JNP3P35P.js'),q=T(a$3.rootDir);q&&(R={trend:q,dot:D(q,a$3.rootDir)});}catch{}return JSON.stringify({project:a$3.projectName,symbolSystem:"v2",counts:{"# components":f.component,"$ flows":f.flow,"^ gates":f.gate,"! signals":f.signal,"~ aspects":f.aspect},total:v,...Object.keys(C).length>0?{componentTypes:{...C,...P>0?{"(untyped)":P}:{}}}:{},examples:h,hasPortalYaml:a$3.gateConfig!==null,purposeFiles:a$3.aggregation.purposeFiles.length,...j!==void 0?{purposeHealthScore:j}:{},...x?{protocols:x}:{},...I!==void 0?{notebookReferences:I}:{},...R?{complianceHealth:R}:{},capabilities:"paradigm://context/agent-protocol",...await(async()=>{try{let{loadArchMap:T}=await import('./arch-loader-YVOS3QRY.js'),D=T(a$3.rootDir);if(D)return {arch:{present:!0,tiers:D.tiers.length,links:D.links.length}}}catch{}return {}})(),note:"Symbol System v2: Use tags [feature], [state], [integration], [idea] for classification. Use type field for structural role (view, service, tool, etc.)",environment:{os:b,shell:S,terminalNote:w?"Use PowerShell syntax: semicolons for command chaining, backslashes for paths, $env:VAR for env vars":"Use Unix syntax: && for command chaining, forward slashes for paths, $VAR for env vars"}},null,2)}),y=m;if(u$1==="concise")try{let f=JSON.parse(m);y=JSON.stringify({project:f.project,counts:f.counts,total:f.total},null,2);}catch{}return a$1(y.length,o),{content:[{type:"text",text:y}]}}case "paradigm_gates_for_route":{let{route:u,response_format:m}=c,f=typeof u=="string"&&!u.includes("/")&&u.includes(".")?"POST":c.method||"GET",v=r(a$3.index,"gate"),h=[],b=[];if(a$3.gateConfig?.routes)for(let[R,T]of Object.entries(a$3.gateConfig.routes))T.gates&&b.push({route:R,gates:T.gates,method:T.method});if(a$3.workspace)for(let[R,T]of a$3.workspace.siblingIndices){let D=T.gateConfig;if(D?.routes)for(let[q,ce]of Object.entries(D.routes)){let ze=ce,qn=Array.isArray(ze)?ze:ze?.gates;qn&&b.push({route:q,gates:qn,method:Array.isArray(ze)?void 0:ze?.method,source:R});}}for(let R of b){let T=Pd(u,R.route);if(T>=.6&&(!R.method||R.method===f))for(let D of R.gates){let q=v.find(ce=>ce.symbol===D||ce.symbol===`^${D}`);if(q&&!h.find(ce=>ce.gate===q.symbol)){let ce=R.source?`${R.source}/portal.yaml`:"portal.yaml";h.push({gate:q.symbol,reason:`Similar route "${R.route}" uses this gate`,confidence:T>=.8?"high":"medium",source:ce});}}}let x=u.split("/").filter(Boolean).find(R=>!R.startsWith(":")&&R!=="api")?.replace(/s$/,"")||"",_=u.match(/\/:(id|[a-z]+Id)($|\/)/i);if(_&&x){let R=v.find(T=>{let D=T.symbol.toLowerCase(),q=(T.description||"").toLowerCase();return D.includes(`${x}-owner`)||D.includes("owner")||D.includes("ownership")||q.includes("owner")||q.includes("ownership")||q.includes("belongs to")});R?h.push({gate:R.symbol,reason:`Resource ID route (${x}) typically needs ownership verification`,confidence:"high"}):h.push({gate:`^${x}-owner`,reason:`Consider adding ownership gate for ${x} resource`,confidence:"medium"});}if(u.includes("/admin")||u.includes("/settings")){let R=v.find(T=>T.symbol.includes("admin")||T.description?.toLowerCase().includes("admin"));R&&h.push({gate:R.symbol,reason:"Route appears to be admin-related",confidence:"high"});}if(u.startsWith("/api/")||u.includes("/user")||u.includes("/account")){let R=v.find(T=>T.symbol.includes("authenticated")||T.symbol.includes("auth"));R&&h.push({gate:R.symbol,reason:"API/user routes typically require authentication",confidence:"high"});}if(u.includes("/premium")||u.includes("/pro")||u.includes("/export")){let R=v.find(T=>T.symbol.includes("subscription")||T.symbol.includes("premium"));R&&h.push({gate:R.symbol,reason:"Route appears to be a premium feature",confidence:"medium"});}if(f==="DELETE"){let R=v.find(T=>T.symbol.includes("authenticated"));R&&!h.find(T=>T.gate===R.symbol)&&h.push({gate:R.symbol,reason:"DELETE operations require authentication",confidence:"high"});}if(["POST","PUT","PATCH"].includes(f)){let R=v.find(T=>T.symbol.includes("authenticated"));R&&!h.find(T=>T.gate===R.symbol)&&h.push({gate:R.symbol,reason:"Write operations typically require authentication",confidence:"high"});}let C=new Set,P=h.filter(R=>C.has(R.gate)?false:(C.add(R.gate),true)),j=m==="concise"?{suggestions:P.map(R=>({gate:R.gate,confidence:R.confidence}))}:{route:u,method:f,suggestions:P,availableGates:v.map(R=>({symbol:R.symbol,description:R.description})),note:_?"Resource ID routes should verify the user owns/has access to the specific resource.":"These are suggestions based on route patterns. Review your portal.yaml for exact requirements."},I=JSON.stringify(j,null,2);a$1(I.length,o);try{n(a$3.rootDir,{type:"gate-checked",source:"mcp-tool-call",tool:"paradigm_gates_for_route",symbols:P.map(R=>R.gate),context:`Gate check for ${f} ${u}`});}catch{}return {content:[{type:"text",text:I}]}}case "paradigm_plugin_check":{let{runPluginUpdateCheck:u}=await import('./plugin-update-checker-M7PW434O.js'),m=await u(),y=m.filter(b=>b.hasRemoteUpdate||b.hasCacheStale);if(y.length===0){let b=m.length===0?"No Claude Code plugins found in ~/.claude/plugins/marketplaces/.":"All installed plugins are up to date.";return a$1(b.length,o),{content:[{type:"text",text:b}]}}let f=[`Plugin updates available:
132
+ `],v=[];for(let b of y)b.hasRemoteUpdate?(f.push(` ${b.plugin} (${b.repo}): remote has newer commits`),v.push(`git -C ${b.marketplacePath} pull origin main`)):b.hasCacheStale&&f.push(` ${b.plugin} (${b.repo}): ${b.installedVersion} \u2192 ${b.localVersion} (restart needed)`);v.length>0?(f.push(`
133
+ Update command:
134
+ ${v.join(` && \\
135
+ `)}`),f.push(`
136
+ After running, restart the session to apply updates.`)):f.push(`
137
+ Restart the session to apply cached updates.`);let h=f.join(`
138
+ `);return a$1(h.length,o),{content:[{type:"text",text:h}]}}case "paradigm_workspace_reindex":{if(!a$3.workspace){let f=JSON.stringify({error:"No workspace configured",suggestion:'Add a "workspace" field to .paradigm/config.yaml pointing to your .paradigm-workspace file, then run `paradigm workspace init` to create one.'},null,2);return a$1(f.length,o),{content:[{type:"text",text:f}]}}let{rebuildStaticFiles:u}=await import('./reindex-QZYOD5K4.js'),m=[];for(let f of a$3.workspace.config.members){let v=$.resolve($.dirname(a$3.workspace.workspacePath),f.path);try{let h=await u(v);m.push({name:f.name,symbolCount:h.symbolCount,status:"ok"});}catch(h){m.push({name:f.name,symbolCount:0,status:`error: ${h.message}`});}}let y=JSON.stringify({action:"workspace_reindex",workspace:a$3.workspace.config.name,members:m,totalSymbols:m.reduce((f,v)=>f+v.symbolCount,0)},null,2);return a$1(y.length,o),f$2.clear(),{content:[{type:"text",text:y}]}}case "paradigm_tool_activate":{let u=c.feature,m=r$1.activateAdvanced(u);if(m){let h=JSON.stringify({action:"tool_activate",feature:u,status:"activated",toolsAdded:m.map(b=>b.name),note:`Advanced module "${u}" activated for this session. ${m.length} tool(s) now available.`},null,2);return a$1(h.length,o),{content:[{type:"text",text:h}]}}let y=r$1.getRegistryInfo(),f=y.activeFeatures.includes(u),v=JSON.stringify({action:"tool_activate",feature:u,status:f?"already_active":"not_found",note:f?`Module "${u}" is already active (auto-detected or core tier).`:`Module "${u}" not found. Available advanced modules: ${y.availableAdvanced.join(", ")||"(none)"}`,availableAdvanced:y.availableAdvanced},null,2);return a$1(v.length,o),{content:[{type:"text",text:v}]}}default:{let u=await r$1.dispatch(o,c,a$3);if(u&&u.handled)return o.startsWith("paradigm_context_")||o.startsWith("paradigm_session_")||o==="paradigm_handoff_prepare"||a$1(u.text.length,o),Td(o,c,a$3.rootDir),{content:[{type:"text",text:u.text}]};throw new Error(`Unknown tool: ${o}`)}}})();if(l||p$1){let u=g.content?.[0];if(u&&typeof u=="object"&&"text"in u&&typeof u.text=="string"){let m=[p$1,l].filter(Boolean).join(`
139
+
140
+ `);u.text=m+`
141
+
142
+ `+u.text;}}return g});}function Td(s,e,i){try{switch(s){case "paradigm_sentinel_record":n(i,{type:"error-encountered",source:"mcp-tool-call",tool:s,severity:e.severity||"warning",context:`Sentinel: ${e.title||e.summary||"incident recorded"}`});break;case "paradigm_lore_record":n(i,{type:"work-completed",source:"mcp-tool-call",tool:s,symbols:Array.isArray(e.symbols_touched)?e.symbols_touched.map(String):[],context:`Lore recorded: ${e.title||"untitled"}`});break;case "paradigm_work_log_record":case "paradigm_journal_record":n(i,{type:"work-completed",source:"mcp-tool-call",tool:s,symbols:Array.isArray(e.symbols)?e.symbols.map(String):[],context:`Work logged: ${e.summary||e.title||"entry"}`});break;case "paradigm_decision_record":n(i,{type:"decision-made",source:"mcp-tool-call",tool:s,symbols:Array.isArray(e.symbols)?e.symbols.map(String):[],context:`Decision: ${e.title||e.summary||"recorded"}`});break;case "paradigm_persona_run":n(i,{type:"work-completed",source:"mcp-tool-call",tool:s,context:`Persona run: ${e.persona||"unknown"}`});break;case "paradigm_protocol_record":n(i,{type:"work-completed",source:"mcp-tool-call",tool:s,context:`Protocol recorded: ${e.name||e.id||"unknown"}`});break;case "paradigm_reindex":n(i,{type:"work-completed",source:"mcp-tool-call",tool:s,context:"Index rebuilt"},{skipNominations:!0});break;default:(s.startsWith("paradigm_purpose_")||s.startsWith("paradigm_portal_"))&&(s.includes("_add_")||s.includes("_update_")||s.includes("_remove_"))&&n(i,{type:"file-modified",source:"mcp-tool-call",tool:s,symbols:e.id?[`#${e.id}`]:e.symbol?[String(e.symbol)]:[],context:`Purpose/portal update via ${s}`});break}}catch{}}export{eg as registerTools};