@a-company/paradigm 6.0.2 → 6.0.5

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 (74) hide show
  1. package/dist/{accept-orchestration-QQISPINV.js → accept-orchestration-TIXUQQGR.js} +1 -1
  2. package/dist/active-remediations-EBLHRMNN.js +5 -0
  3. package/dist/agent-MB3H5EZA.js +33 -0
  4. package/dist/{agent-loader-2WJHD46U.js → agent-loader-VGBPL3TH.js} +1 -1
  5. package/dist/{agent-loader-YKS2PQWO.js → agent-loader-W3RQJVW7.js} +1 -1
  6. package/dist/{agents-suggest-HYTFMQD3.js → agents-suggest-IKY6VD2R.js} +1 -1
  7. package/dist/{ambient-NVKQCW2A.js → ambient-AI42BOM5.js} +2 -2
  8. package/dist/{ambient-BE3SQXNN.js → ambient-FNNFB4AP.js} +1 -1
  9. package/dist/authority-GCMPX7RW.js +2 -0
  10. package/dist/{chunk-FEYOQMZ5.js → chunk-2AU5L333.js} +1 -1
  11. package/dist/{chunk-M3PPXJU4.js → chunk-4N56FRNE.js} +1 -1
  12. package/dist/{chunk-3DZK54RU.js → chunk-5RFISGUW.js} +110 -22
  13. package/dist/{chunk-TNVWGPCE.js → chunk-6QXBXZF6.js} +1 -1
  14. package/dist/{chunk-WESTEMIM.js → chunk-AMLD7IYC.js} +1 -1
  15. package/dist/{chunk-VXIIVMTM.js → chunk-F6E3HW45.js} +1 -1
  16. package/dist/{chunk-TBWWFRL5.js → chunk-GD4F2HC6.js} +1 -1
  17. package/dist/{chunk-6SKSV5B2.js → chunk-IOVHF4SR.js} +1 -1
  18. package/dist/{chunk-PHEX6LU4.js → chunk-K7EQHFZP.js} +26 -26
  19. package/dist/{chunk-M2HKWR25.js → chunk-KAFQA7HV.js} +2 -2
  20. package/dist/{chunk-GAFKOFAV.js → chunk-LAYBUKMB.js} +1 -1
  21. package/dist/{chunk-TZDYIPVU.js → chunk-MOVDVBU7.js} +133 -49
  22. package/dist/{chunk-AO7ZSRME.js → chunk-TQOT2LBO.js} +2 -2
  23. package/dist/chunk-XQLO5URP.js +11 -0
  24. package/dist/{compliance-BNFWQPKM.js → compliance-J3VOV445.js} +1 -1
  25. package/dist/{diff-MF55KQZH.js → diff-75MABOSL.js} +1 -1
  26. package/dist/{docs-O37YLLRN.js → docs-TSAAS4W3.js} +1 -1
  27. package/dist/doctor-L5XZENCF.js +2 -0
  28. package/dist/{hooks-TFMMMB2H.js → hooks-45WDP6QS.js} +1 -1
  29. package/dist/index.js +4 -4
  30. package/dist/mcp.js +2 -2
  31. package/dist/{migrate-Z5UQN57G.js → migrate-R64OQGSM.js} +1 -1
  32. package/dist/migration-notices-MRZ6PVDS.js +4 -0
  33. package/dist/{nomination-engine-QPZJH6XO.js → nomination-engine-NCLTGMAK.js} +1 -1
  34. package/dist/{orchestrate-RID7HHHH.js → orchestrate-K4KBTBYK.js} +1 -1
  35. package/dist/{providers-4PXMWA7V.js → providers-TBPOE4DI.js} +1 -1
  36. package/dist/registry-OUTA3DXW.js +20 -0
  37. package/dist/reindex-GSRV4MQO.js +2 -0
  38. package/dist/{serve-MO35XIZE.js → serve-3FMUWW5K.js} +1 -1
  39. package/dist/session-tracker-HHNY6J4I.js +2 -0
  40. package/dist/{session-work-log-EE4UIZ33.js → session-work-log-MEJ33TYD.js} +1 -1
  41. package/dist/{session-work-log-4IEVE4KK.js → session-work-log-ZVVJGO7X.js} +1 -1
  42. package/dist/shift-3ATE2ONQ.js +60 -0
  43. package/dist/{spawn-UH5RENSE.js → spawn-KKDDR6UR.js} +1 -1
  44. package/dist/{team-MGT66HZQ.js → team-2LGZQRP4.js} +1 -1
  45. package/dist/tools-VNDXOFXR.js +2 -0
  46. package/dist/university-content/notes/N-para-451-agent-routing.md +117 -0
  47. package/dist/university-content/notes/N-para-451-archetypes-vs-instances.md +82 -0
  48. package/dist/university-content/notes/N-para-451-identity-layers.md +76 -0
  49. package/dist/university-content/notes/N-para-451-orchestration-modes.md +85 -0
  50. package/dist/university-content/notes/N-para-451-paradigm-shift.md +95 -0
  51. package/dist/university-content/notes/N-para-451-partners-primitive.md +107 -0
  52. package/dist/university-content/notes/N-para-451-roster-management.md +132 -0
  53. package/dist/university-content/notes/N-para-451-roster-reference.md +106 -0
  54. package/dist/university-content/notes/N-para-451-the-team-pattern.md +87 -0
  55. package/dist/university-content/notes/N-para-451-tiers.md +83 -0
  56. package/dist/university-content/notes/N-para-451-welcome.md +55 -0
  57. package/dist/university-content/notes/N-para-451-what-is-an-agent.md +73 -0
  58. package/dist/university-content/paths/LP-para-451.yaml +69 -0
  59. package/dist/university-content/quizzes/Q-para-451-foundations.yaml +154 -0
  60. package/dist/university-content/quizzes/Q-para-451-when-to-invoke.yaml +182 -0
  61. package/dist/university-ui/assets/{index-nNgzO1il.js → index-CkgaxOXi.js} +2 -2
  62. package/dist/university-ui/assets/{index-nNgzO1il.js.map → index-CkgaxOXi.js.map} +1 -1
  63. package/dist/university-ui/index.html +1 -1
  64. package/package.json +1 -1
  65. package/dist/agent-X6I2YWOB.js +0 -33
  66. package/dist/chunk-R5ECMBIV.js +0 -11
  67. package/dist/doctor-IG5XM4C4.js +0 -2
  68. package/dist/registry-KOOKFUWD.js +0 -20
  69. package/dist/reindex-FWPD2VGM.js +0 -2
  70. package/dist/session-tracker-KGORN6B5.js +0 -2
  71. package/dist/shift-TVNY2CQF.js +0 -60
  72. package/dist/tools-QJHAVYI6.js +0 -2
  73. /package/dist/{chunk-IZSBGW6E.js → chunk-HXGYVS2N.js} +0 -0
  74. /package/dist/{platform-server-UD45NTGV.js → platform-server-ANOALDPL.js} +0 -0
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import {a as a$1,b as b$3}from'./chunk-4UJ4NIEQ.js';import {e,v,b as b$2,n,c as c$2,d as d$3,q as q$2,p,o as o$1,s as s$1,i as i$2,k as k$1,l as l$1,a as a$6,m as m$1,t as t$1,u as u$1,j as j$3}from'./chunk-M3PPXJU4.js';import {a as a$2,d as d$1,h as h$4,e as e$3}from'./chunk-Q527BPUF.js';import {o as o$2,A,y,x,f as f$5,r as r$1}from'./chunk-KLBH26PA.js';import {d as d$5,b as b$6,a as a$5}from'./chunk-JNSJVCTU.js';import {i as i$4}from'./chunk-XROULIQN.js';import {n as n$2,j as j$4,P,O,K,Q,L as L$1,I,J,D as D$1,H as H$1,m as m$2,l as l$2,E as E$2,v as v$2,N,q as q$3,C as C$1,S,o as o$3,z as z$2,t as t$2,B as B$1,s as s$2}from'./chunk-ZUAUFZRJ.js';import {f,g as g$1,e as e$1,q as q$1,t,o,v as v$1,i,m,$,h as h$1,k,l,j as j$2,n as n$1,u,r,qa as qa$1,s,ra as ra$1,F,X as X$1,ea as ea$1,x as x$1,E as E$1,D,G,w,C,B,A as A$1,z as z$1,y as y$1,_,da as da$1,Z as Z$1,ca as ca$1,ba as ba$1,aa as aa$1,J as J$1,U,K as K$1,O as O$1,Q as Q$1,S as S$1,R,V,T,P as P$1,N as N$1,Y as Y$1,W,a as a$9,d as d$9,c as c$4,L as L$2,M as M$1,fa as fa$1,ga as ga$1,oa as oa$1,na as na$1,ha as ha$1,la as la$1,ia as ia$1,ja as ja$1,ka,pa,ma as ma$1,I as I$1,b as b$b,H as H$2}from'./chunk-PHEX6LU4.js';import {j,a as a$3,i as i$1,b as b$4,h as h$3,g as g$3,c as c$1,d as d$2}from'./chunk-GRZQIKST.js';import {z,f as f$2,p as p$1,h as h$5,b as b$8,d as d$7,e as e$6,i as i$3,y as y$2,l as l$3,c as c$5}from'./chunk-M2HKWR25.js';import {j as j$1,d,e as e$2,f as f$1,g as g$2,h as h$2}from'./chunk-TNVWGPCE.js';import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import {q,e as e$8,b as b$a,f as f$4}from'./chunk-GAFKOFAV.js';import {f as f$3,b as b$7,e as e$5,d as d$6,a as a$7,c as c$3}from'./chunk-DVZWCXB6.js';import {g,e as e$4,b as b$5,d as d$4,a as a$4}from'./chunk-QGZRM6ZB.js';import {h,e as e$7,d as d$8,b as b$9,a as a$8}from'./chunk-K7X3Z3GL.js';import {b,c,d as d$a}from'./chunk-5TAVYPOV.js';import*as E from'fs';import*as H from'path';import*as Te from'js-yaml';import*as ra from'os';import {ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import {execSync}from'child_process';import*as It from'crypto';var Ft,qs,Ls=b(()=>{Ft={enabled:true,thresholds:{minComplianceRate:90,minEvents:20,timeWindowDays:30,minConsecutiveSessions:5,recencyDays:7},demotion:{failureThreshold:3,failureWindowDays:7,cooldownDays:14},neverGraduate:["explore-before-implement","ripple-before-modify","check-fragility","wisdom-before-implement","confidence-on-decisions","university-onboarded","university-content-valid"]},qs=new Set(["tool-called","context-checked"]);});var Oa={};c(Oa,{getAllStates:()=>Ws,getConfig:()=>at,getState:()=>Hn,incrementFailure:()=>Aa,invalidateGraduationCache:()=>wp,isGraduated:()=>hp,loadGraduation:()=>Ue,markNeverGraduate:()=>bp,saveGraduation:()=>En,setTier:()=>Da});function Ta(t){return H.join(t,".paradigm","graduation.yaml")}function Ue(t){let e=H.resolve(t);if(Nt&&$n===e&&Date.now()-Fn<yp)return Nt;let s=Ta(e),n;if(E.existsSync(s))try{let i=E.readFileSync(s,"utf8");n=Te.load(i);}catch{n={version:"1.0",config:{},states:{}};}else n={version:"1.0",config:{},states:{}};return n.version||(n.version="1.0"),n.config||(n.config={}),n.states||(n.states={}),Nt=n,$n=e,Fn=Date.now(),n}function En(t,e){let s=H.resolve(t),n=Ta(s),i=H.dirname(n);E.existsSync(i)||E.mkdirSync(i,{recursive:true});let r=Te.dump(e,{lineWidth:120,noRefs:true,sortKeys:true});E.writeFileSync(n,r,"utf8"),Nt=e,$n=s,Fn=Date.now();}function at(t){let e=Ue(t);return {...Ft,...e.config,thresholds:{...Ft.thresholds,...e.config?.thresholds},demotion:{...Ft.demotion,...e.config?.demotion},neverGraduate:e.config?.neverGraduate??Ft.neverGraduate}}function Ms(t){return {habitId:t,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function Hn(t,e){let n=Ue(t).states[e];return n?{...Ms(e),...n,habitId:e}:Ms(e)}function Ws(t){let e=Ue(t),s={};for(let[n,i]of Object.entries(e.states))s[n]={...Ms(n),...i,habitId:n};return s}function hp(t,e){return Hn(t,e).tier==="hook"}function Da(t,e,s,n){let i=Ue(t),r=i.states[e]||{};i.states[e]={...r,tier:s,previousTier:r.tier||"habit",...s==="hook"?{graduatedAt:new Date().toISOString(),failureCount:0}:{},...s==="habit"&&r.tier==="hook"?{demotedAt:new Date().toISOString()}:{},...n},En(t,i);}function bp(t,e){let s=Ue(t);s.states[e]||(s.states[e]={}),s.states[e].neverGraduate=true,s.states[e].tier="habit",En(t,s);}function Aa(t,e){let s=Ue(t);s.states[e]||(s.states[e]={});let n=(s.states[e].failureCount||0)+1;return s.states[e].failureCount=n,En(t,s),n}function wp(){Nt=null,$n=null,Fn=0;}var Nt,$n,Fn,yp,qn=b(()=>{Ls();Nt=null,$n=null,Fn=0,yp=3e4;});b$1();b$1();var Sl=30*1e3,Cs=new Map,go=".paradigm/wisdom";async function mo(t){let e=H.resolve(t),s=Cs.get(e);if(s&&Date.now()-s.loadedAt<Sl)return s.context;let n=await xl(e);return Cs.set(e,{context:n,loadedAt:Date.now()}),n}async function xl(t){let e=H.join(t,go),s=E.existsSync(e),[n,i,r,o]=s?await Promise.all([Cl(e),Rl(e),Pl(e),jl(e)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e$2(),l=f$1();}catch{}let d$1=new Set(i.map(y=>y.id)),p=i.map(y=>({...y,scope:"project"}));for(let y of a)d$1.has(y.id)||p.push({...y,scope:"global"});let u=new Set(o.map(y=>y.id)),m=o.map(y=>({...y,scope:"project"}));for(let y of c)u.has(y.id)||m.push({...y,scope:"global"});let g=n;if(l&&!n)g=l;else if(l&&n){let y={...n.by_symbol};if(l.by_symbol)for(let[f,b]of Object.entries(l.by_symbol))y[f]||(y[f]=b);g={...n,by_symbol:y,global:{...l.global,...n.global}};}return {preferences:g,antipatterns:p,decisions:m,expertise:r}}function qe(t){let e=H.resolve(t);Cs.delete(e);}async function Cl(t){let e=H.join(t,"preferences.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch(s){return a.component("#wisdom-loader").error("Error parsing preferences.yaml",{error:s}),null}}async function Rl(t){let e=H.join(t,"antipatterns.yaml");if(!E.existsSync(e))return [];try{let s=E.readFileSync(e,"utf8");return Te.load(s).antipatterns||[]}catch(s){return a.component("#wisdom-loader").error("Error parsing antipatterns.yaml",{error:s}),[]}}async function Pl(t){let e=H.join(t,"expertise.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch(s){return a.component("#wisdom-loader").error("Error parsing expertise.yaml",{error:s}),null}}var uo=new Set;async function jl(t){let e=H.join(t,"decisions");if(!E.existsSync(e))return [];let s=[];try{let n=E.readdirSync(e);n.some(r=>r.endsWith(".yaml")||r.endsWith(".yml"))&&!uo.has(e)&&(uo.add(e),a.component("#wisdom-loader").warn("wisdom-decisions found; run `paradigm migrate decisions` in v6.0. In v5.39.0 wisdom-decisions are still read but will be migrated to TD-streams in v6.0."));for(let r of n){if(!r.endsWith(".yaml")&&!r.endsWith(".yml"))continue;let o=H.join(e,r);try{let a=E.readFileSync(o,"utf8"),c=Te.load(a);s.push(c);}catch(a$1){a.component("#wisdom-loader").error(`Error parsing ${r}`,{error:a$1});}}}catch(n){a.component("#wisdom-loader").error("Error reading decisions directory",{error:n});}return s.sort((n,i)=>n.id.localeCompare(i.id)),s}function fo(t,e){return e.map(s=>Tl(t,s))}function Tl(t,e){let s=t.preferences?.by_symbol?.[e]||null,n=t.antipatterns.filter(o=>o.symbols.some(a=>a===e||gn(e,a))),i=t.decisions.filter(o=>o.symbols.some(a=>a===e||gn(e,a))),r=t.expertise?.experts.filter(o=>o.symbols?.some(a=>a===e||gn(e,a)))||[];return {symbol:e,preferences:s,antipatterns:n,decisions:i,experts:r}}function yo(t,e){return t.expertise?t.expertise.experts.filter(s=>!!(e.symbol&&s.symbols&&s.symbols.some(n=>n===e.symbol||gn(e.symbol,n))||e.area&&s.areas&&s.areas.some(n=>n.toLowerCase().includes(e.area.toLowerCase())))):[]}function gn(t,e){if(e.endsWith("*")){let s=e.slice(0,-1);return t.startsWith(s)}return t===e}async function ho(t,e){let s=H.join(t,go),n=H.join(s,"antipatterns.yaml");E.existsSync(s)||E.mkdirSync(s,{recursive:true});let i={version:"1.0",antipatterns:[]};if(E.existsSync(n)){let r=E.readFileSync(n,"utf8");i=Te.load(r);}i.antipatterns.push({...e,added:new Date().toISOString()}),E.writeFileSync(n,Te.dump(i,{lineWidth:-1})),qe(t);}b$1();var bo=".paradigm/history";async function wo(t){let e=H.join(t,bo);if(!E.existsSync(e))return {index:null,validation:null};let[s,n]=await Promise.all([Dl(e),Al(e)]);return {index:s,validation:n}}async function Dl(t){let e=H.join(t,"index.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch(s){return a.component("#history-loader").error("Error parsing index.yaml",{error:s.message}),null}}async function Al(t){let e=H.join(t,"validation.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch(s){return a.component("#history-loader").error("Error parsing validation.yaml",{error:s.message}),null}}function vo(t,e){return e.map(s=>Ol(t,s))}function Ol(t,e){let s=t.index?.by_symbol?.[e]||null,n=[];if(t.index?.co_changes){for(let r of t.index.co_changes)if(r.symbols.includes(e))for(let o of r.symbols)o!==e&&!n.includes(o)&&n.push(o);}let i=t.validation?.by_symbol?.[e]||null;return {symbol:e,summary:s,recent:s?.recent||[],co_changes:n,validation:i}}function ko(t,e){let s=[],n=[];if(!t.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let o of e){let a=t.index.by_symbol?.[o];a&&(a.fragility==="high"||a.fragility==="critical")&&s.push({symbol:o,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=t.index.fragile_symbols?.find(l=>l.symbol===o);c&&!s.find(l=>l.symbol===o)&&s.push(c);}for(let o of e){let a=t.index.co_changes?.filter(c=>c.symbols.includes(o));if(a?.length)for(let c of a){let l=c.symbols.filter(d=>d!==o&&!e.includes(d));l.length>0&&c.correlation>.7&&n.push(`${o} often changes with ${l.join(", ")} (${Math.round(c.correlation*100)}% correlation)`);}}let i=s.filter(o=>o.fragility==="critical").length===0,r=[];return s.length>0&&(r.push("Consider adding extra test coverage before modifying fragile symbols"),r.push("Review recent rollbacks and failures for these symbols")),n.length>0&&r.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:s,warnings:n,safe_to_modify:i,recommendations:r}}async function Rs(t,e){let s=H.join(t,bo),n=H.join(s,"log.jsonl");E.existsSync(s)||E.mkdirSync(s,{recursive:true});let i=Il(n),r=new Date().toISOString(),o={id:i,ts:r,...e},a=JSON.stringify(o)+`
3
- `;return E.appendFileSync(n,a),i}async function _o(t,e,s,n){return Rs(t,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:s,tests:n})}function Il(t){let e=1;return E.existsSync(t)&&(e=E.readFileSync(t,"utf8").split(`
4
- `).filter(n=>n.trim()).length+1),`h${String(e).padStart(4,"0")}`}b$1();function $l(t){let e=H.resolve(t),s=E.readFileSync(e,"utf8"),n=Te.load(s);if(!n||typeof n!="object")throw new Error(`Invalid workspace file: ${t}`);let i={version:String(n.version||"1.0"),name:String(n.name||"unnamed-workspace"),members:[]};if(Array.isArray(n.members)){for(let r of n.members)if(typeof r=="object"&&r!==null){let o=r;i.members.push({name:String(o.name||""),path:String(o.path||""),role:o.role,exports:Array.isArray(o.exports)?o.exports.map(String):void 0});}}return i}function xo(t,e){let s=H.resolve(t),n=H.resolve(s,e);if(!E.existsSync(n))return a.component("#workspace-loader").warn("Workspace file not found",{workspacePath:n}),null;let i;try{i=$l(n);}catch(c){return a.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let r=H.dirname(n),o="";for(let c of i.members){let l=H.resolve(r,c.path);if(So(l)===So(s)){o=c.name;break}}if(!o)return a.component("#workspace-loader").warn("Current directory is not a member of workspace",{workspace:i.name}),null;let a$1=new Map;for(let c of i.members){if(c.name===o)continue;let l=H.resolve(r,c.path),d=H.join(l,".paradigm","scan-index.json");if(!E.existsSync(d)){a.component("#workspace-loader").warn("No scan-index.json for workspace member",{member:c.name,scanIndexPath:d});continue}try{let p=JSON.parse(E.readFileSync(d,"utf8")),u=El(p);c.exports&&c.exports.length>0&&(u=Fl(u,c.exports));let m=null,g=H.join(l,"portal.yaml");if(E.existsSync(g))try{let y=E.readFileSync(g,"utf8"),f=Te.load(y);f&&(m=f);}catch{}a$1.set(c.name,{index:u,gateConfig:m});}catch(p){a.component("#workspace-loader").warn("Could not load index for workspace member",{member:c.name,error:p.message});}}return {config:i,workspacePath:n,currentMember:o,siblingIndices:a$1}}function Fl(t,e){let n=n$1(t).filter(i=>{let r=i.symbol;return e.some(o=>Nl(o,r))});return Hl(n)}function Nl(t,e){let s=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${s}$`,"i").test(e)}function xt(t,e){let s=[];for(let[n,i]of t.siblingIndices){let r=j$2(i.index,e);for(let o of r)s.push({project:n,symbol:`${n}/${o.symbol}`,type:o.type,description:o.description,filePath:o.filePath});}return s}function Co(t,e){let s=[],n=e.includes("/")?e.split("/").pop():e;for(let[i,r]of t.siblingIndices){let o=[],a=n$1(r.index);for(let c of a){let l=c.references||[],d=c.description||"",p=l.some(m=>m===n||m===e||m.endsWith(`/${n}`)),u=d.includes(n);(p||u)&&o.push({symbol:c.symbol,type:c.type,description:c.description});}o.length>0&&s.push({project:i,references:o});}return s}function So(t){return H.resolve(t).replace(/\/+$/,"")}function El(t){let e={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"},s=[];for(let[n,i]of Object.entries(e)){let r=t[n];if(!(!r||typeof r!="object"))for(let[o,a]of Object.entries(r)){let c={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"}[i]||"#";s.push({id:o,symbol:a.symbol||`${c}${o}`,type:i,source:"purpose",filePath:a.path||"",data:{},references:a.related||[],referencedBy:[],description:a.description,tags:a.visualTags||[]});}}return g$1({symbols:s,purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}function Hl(t){return g$1({symbols:t.map(e=>({id:e.id||e.symbol.replace(/^[#$^!~]/,""),symbol:e.symbol,type:e.type,source:"purpose",filePath:e.filePath||"",data:e.data||{},references:e.references||[],referencedBy:e.referencedBy||[],description:e.description,tags:e.tags})),purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}async function Og(t){let e=H.resolve(t),s=await f(e),n=g$1(s),i=null,r=H.join(e,"portal.yaml");if(E.existsSync(r))try{i=await e$1(r);}catch(d){let p=d?.name??"Error";a.component("#index-loader").warn("Could not parse portal.yaml",{errorClass:p});}let o=H.basename(e),a$1=H.join(e,".premise");if(E.existsSync(a$1))try{let p=E.readFileSync(a$1,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);p&&(o=p[1].trim());}catch{}let c=null,l=H.join(e,".paradigm","config.yaml");if(E.existsSync(l))try{let d=E.readFileSync(l,"utf8"),p=Te.load(d);p&&typeof p=="object"&&(p.version||a.component("#index-loader").warn('config.yaml missing "version" field'),p.project||a.component("#index-loader").warn('config.yaml missing "project" field')),p&&typeof p.workspace=="string"&&(c=xo(e,p.workspace));}catch(d){a.component("#index-loader").warn("Failed to load workspace config",{error:d.message});}return {rootDir:e,index:n,aggregation:s,gateConfig:i,projectName:o,wisdom:null,history:null,workspace:c,_loadedAt:Date.now()}}async function fn(t){return t.wisdom||(t.wisdom=await mo(t.rootDir)),t.wisdom}async function js(t){return t.history||(t.history=await wo(t.rootDir)),t.history}j();b$1();var Po=false;function To(){return [{name:"paradigm_wisdom_context",description:"Get team wisdom (preferences, antipatterns, decisions) for symbols before implementing. Call this before making changes to understand team patterns. Returns preferences, antipatterns, and decisions relevant to the specified symbols. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get wisdom for (e.g., ["@checkout", "#payment-form"])'},include_global:{type:"boolean",description:"Include global preferences (default: true)"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_wisdom_record",description:"Record a new team learning: antipattern (what not to do) or decision (architectural choice). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to record"},id:{type:"string",description:'Unique ID (for antipattern: e.g., "api-001", for decision: e.g., "001")'},symbols:{type:"array",items:{type:"string"},description:"Related symbols"},description:{type:"string",description:"What not to do (antipattern) or the decision made (decision)"},reason:{type:"string",description:"Why this is an antipattern / context for decision"},alternative:{type:"string",description:"What to do instead (for antipatterns)"},title:{type:"string",description:"Decision title (for decisions)"},status:{type:"string",enum:["proposed","accepted","deprecated","superseded"],description:"Decision status (for decisions)"},rationale:{type:"object",properties:{factors:{type:"array",items:{type:"string"}},conclusion:{type:"string"}},description:"Decision rationale (for decisions)"},consequences:{type:"object",properties:{positive:{type:"array",items:{type:"string"}},negative:{type:"array",items:{type:"string"}},mitigations:{type:"array",items:{type:"string"}}},description:"Expected consequences (for decisions)"},scope:{type:"string",enum:["project","global"],description:'Where to store: "project" (default) writes to .paradigm/wisdom/, "global" writes to ~/.paradigm/wisdom/'}},required:["type","id","symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]}},{name:"paradigm_wisdom_expert",description:"Find human experts who know about specific symbols or areas. Returns names and contact info for relevant experts. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to find experts for (e.g., "@checkout")'},area:{type:"string",description:'General area to find experts for (e.g., "payments", "auth")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function yn(t,e,s){switch(t){case "paradigm_wisdom_context":{let{symbols:n,include_global:i=true}=e,r=await fn(s),o=fo(r,n),a={symbols:n,wisdom:o.map(d=>({symbol:d.symbol,preferences:d.preferences,antipatterns:d.antipatterns.map(p=>({id:p.id,description:p.description,reason:p.reason,alternative:p.alternative,scope:p.scope||"project"})),decisions:d.decisions.map(p=>({id:p.id,title:p.title,status:p.status,decision:p.decision,scope:p.scope||"project"})),experts:d.experts.map(p=>p.name)}))};i&&r.preferences?.global&&(a.global_preferences=r.preferences.global);let c=o.reduce((d,p)=>d+p.antipatterns.length,0),l=o.reduce((d,p)=>d+p.decisions.length,0);a.summary={symbols_with_preferences:o.filter(d=>d.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:o.some(d=>d.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let d={},p=[];for(let u of n){let m=await a$3(s.rootDir,{symbol:u,hasAssessment:!0,limit:100});if(m.length===0)continue;let g={correct:0,partial:0,incorrect:0},y=0,f=0;for(let h of m){let w=h.assessment.verdict;g[w]++,h.confidence!=null&&(y+=h.confidence,f++);}d[u]={total:m.length,...g,avgConfidence:f>0?Math.round(y/f*1e3)/1e3:null};let b=(g.correct+g.partial*.5)/m.length;b<.6&&m.length>=3&&p.push(`Low historical accuracy for ${u}: ${Math.round(b*100)}% across ${m.length} entries. Proceed with extra caution.`);}Object.keys(d).length>0&&(a.calibration=d),p.length>0&&(a.calibration_warnings=p);}catch{}return {handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_wisdom_record":{let{type:n,id:i,symbols:r,description:o,reason:a$1,alternative:c,title:l,status:d,rationale:p,consequences:u,scope:m="project"}=e;if(n==="antipattern"){if(!o||!a$1||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let g={id:i,symbols:r,description:o,reason:a$1,alternative:c};return m==="global"?g$2(g):await ho(s.rootDir,g),qe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:i,scope:m,message:`Antipattern recorded to ${m} scope`})}}if(n==="decision"){if(!l||!o||!p||!u)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};if(Po||(Po=true,a.component("#wisdom").warn('paradigm_wisdom_record({type:"decision"}) is deprecated. Use paradigm_decision_record instead.',{deprecation:"v6.0",canonical_tool:"paradigm_decision_record"})),m==="global"){let f={id:i,title:l,status:d||"proposed",date:new Date().toISOString().split("T")[0],symbols:r,context:a$1||"",decision:o,rationale:p,consequences:u};return h$2(f),qe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:i,scope:"global",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record for project-scoped decisions.',message:"Decision recorded to global scope"})}}let g=a$2(s.rootDir,{title:l,decision:o,rationale:{factors:p.factors,conclusion:p.conclusion},participants:[{id:"wisdom-record",role:"agent",stance:"proposed"}],symbols_affected:r,status:d==="accepted"?"active":d==="proposed"?"proposed":"active",context:a$1||void 0,consequences:u,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),y=d$1(s.rootDir,g.id);return qe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:g.id,legacy_id:i,scope:"project",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record going forward.',message:`Decision recorded (routed to decisions stream as ${g.id})`,...y?{companion_lore_id:y}:{}})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${n}`})}}case "paradigm_wisdom_promote":{let{type:n,id:i}=e,r=await fn(s),o=H.basename(s.rootDir);if(n==="antipattern"){let a=r.antipatterns.find(l=>l.id===i);return a?d().some(l=>l.id===i)?{handled:true,text:JSON.stringify({error:`Antipattern "${i}" already exists in global scope`})}:(g$2({...a,learned_from:`promoted from ${o}`}),qe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:i,promoted_from:o,message:`Antipattern "${i}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${i}" not found in project`})}}if(n==="decision"){let a=r.decisions.find(l=>l.id===i);return a?e$2().some(l=>l.id===i)?{handled:true,text:JSON.stringify({error:`Decision "${i}" already exists in global scope`})}:(h$2(a),qe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:i,promoted_from:o,message:`Decision "${i}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${i}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${n}`})}}case "paradigm_wisdom_expert":{let{symbol:n,area:i}=e;if(!n&&!i)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let r=await fn(s),o=yo(r,{symbol:n,area:i});return {handled:true,text:JSON.stringify({query:{symbol:n,area:i},count:o.length,experts:o.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:o.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function Do(){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 Ao(t,e,s){switch(t){case "paradigm_history_context":{let{symbols:n}=e,i=await js(s),r=vo(i,n),o={symbols:n,history:r.map(a=>({symbol:a.symbol,summary:a.summary?{total_changes:a.summary.total_changes,last_modified:a.summary.last_modified,stability_score:a.summary.stability_score,fragility:a.summary.fragility,contributors:a.summary.contributors}:null,recent:a.recent.slice(0,3).map(c=>({type:c.type,description:c.description,author:c.author,ts:c.ts})),co_changes:a.co_changes.slice(0,5)})),summary:{total_symbols:n.length,with_history:r.filter(a=>a.summary).length,fragile_count:r.filter(a=>a.summary?.fragility==="high"||a.summary?.fragility==="critical").length}};return {handled:true,text:JSON.stringify(o,null,2)}}case "paradigm_history_record":{let{type:n,symbols:i,intent:r,description:o,commit:a,files:c,reason:l}=e,d=await Rs(s.rootDir,{type:n,symbols:i,author:{type:"agent",id:"claude"},intent:r,description:o,commit:a,files:c,reason:l});return {handled:true,text:JSON.stringify({success:true,id:d,type:n,symbols:i,message:"History entry recorded successfully",note:"Run paradigm history reindex to update the index after multiple entries"})}}case "paradigm_history_validate":{let{implementation_id:n,result:i,tests:r}=e,o=await _o(s.rootDir,n||"unknown",i,r);return {handled:true,text:JSON.stringify({success:true,id:o,result:i,tests:r,message:"Validation recorded successfully"})}}case "paradigm_history_fragility":{let{symbols:n}=e,i=await js(s),r=ko(i,n);return {handled:true,text:JSON.stringify({symbols:n,safe_to_modify:r.safe_to_modify,fragile:r.fragile.map(o=>({symbol:o.symbol,fragility:o.fragility,reason:o.reason})),warnings:r.warnings,recommendations:r.recommendations,summary:r.fragile.length===0?"All symbols are stable - safe to proceed":r.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:""}}}b$1();var ql=".paradigm/navigator.yaml";async function $o(t){let e=H.join(t,ql);if(!E.existsSync(e))return {config:null,configPath:null};try{let s=E.readFileSync(e,"utf8");return {config:Te.load(s),configPath:e}}catch(s){return a.component("#navigator-loader").error("Error parsing navigator.yaml",{error:s}),{config:null,configPath:e}}}function Fo(t,e,s){switch(e.intent){case "find":return Ll(t,e.target||"");case "explore":return Ml(t,e.target||"");case "context":return Wl(t,e.task||"");default:return {paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Ll(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let i=t.symbols[e];if(i)n.paths.push(i),n.symbols.push(e),n.explanation=`Found symbol ${e} at ${i}`;else {let r=Object.entries(t.symbols).filter(([o])=>o.includes(e.slice(1))).slice(0,5);r.length>0?(n.paths=r.map(([,o])=>o),n.symbols=r.map(([o])=>o),n.explanation=`Found ${r.length} symbols matching "${e}"`):n.explanation=`Symbol ${e} not found in navigator`;}}else {let i=Object.entries(t.symbols).filter(([r])=>r.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(i.length>0)n.paths=i.map(([,r])=>r),n.symbols=i.map(([r])=>r),n.explanation=`Found ${i.length} symbols matching "${e}"`;else {let r=Gl(t,e);r?(n.paths=r.paths,n.explanation=`Found ${e} in structure: ${r.paths.join(", ")}`):n.explanation=`No matches found for "${e}"`;}}return n.suggested_order=Ts(n.paths,t),n}function Ml(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]},i=e.toLowerCase();for(let[r,o]of Object.entries(t.structure))if(o&&(r.toLowerCase().includes(i)||i.includes(r.toLowerCase()))){n.paths.push(...o.paths);let a=Object.entries(t.symbols).filter(([c])=>c.startsWith(o.symbol)).slice(0,10);n.symbols.push(...a.map(([c])=>c));}for(let[r,o]of Object.entries(t.key_files))r.toLowerCase().includes(i)&&n.paths.push(...o);if(n.paths.length===0){let r=Object.entries(t.symbols).filter(([o,a])=>o.toLowerCase().includes(i)||a.toLowerCase().includes(i)).slice(0,10);n.paths=[...new Set(r.map(([,o])=>o))],n.symbols=r.map(([o])=>o);}return n.explanation=`Exploration paths for "${e}": ${n.paths.length} locations, ${n.symbols.length} symbols`,n.suggested_order=Ts(n.paths,t),n}function Wl(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]},i=e.toLowerCase(),r=Jl(i);for(let[o,a]of Object.entries(t.structure))a&&r.some(c=>o.toLowerCase().includes(c))&&n.paths.push(...a.paths);for(let[o,a]of Object.entries(t.symbols)){let c=o.slice(1).toLowerCase();r.some(l=>c.includes(l)||l.includes(c))&&(n.paths.push(a),n.symbols.push(o));}return n.paths.push(...t.key_files.config),n.paths=[...new Set(n.paths)],n.symbols=[...new Set(n.symbols)],i.includes("test")?n.skip=t.skip_patterns.always:n.skip=[...t.skip_patterns.always,...t.skip_patterns.unless_testing],!i.includes("doc")&&!i.includes("readme")&&n.skip.push(...t.skip_patterns.unless_docs),n.explanation=`Context for "${e}": ${n.paths.length} relevant files, ${n.symbols.length} symbols`,n.suggested_order=Ts(n.paths,t),n}function Gl(t,e){let s=e.toLowerCase();for(let[n,i]of Object.entries(t.structure))if(i&&(n.toLowerCase().includes(s)||s.includes(n.toLowerCase())))return i;return null}function Jl(t){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return t.split(/\s+/).map(s=>s.replace(/[^a-z0-9]/g,"")).filter(s=>s.length>2&&!e.has(s))}function Ts(t,e){let s={};for(let n of t){let i=0;e.key_files.config.some(r=>n.includes(r))&&(i+=100),e.key_files.entry.some(r=>n.includes(r))&&(i+=80),e.key_files.types.some(r=>n.includes(r))&&(i+=60),i-=n.split("/").length*2,s[n]=i;}return [...t].sort((n,i)=>(s[i]||0)-(s[n]||0))}var Ul={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function Ho(){return [Ul]}async function bn(t,e,s){if(t!=="paradigm_navigate")return {handled:false,text:""};let n={intent:e.intent||"find",target:e.target,task:e.task},i=await $o(s.rootDir);if(i.config||(i={config:Bl(s),configPath:null}),false);if(n.intent==="context"&&!n.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((n.intent==="find"||n.intent==="explore")&&!n.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${n.intent} intent`,example:n.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let r=`navigate:${n.intent}:${n.target||""}:${n.task||""}`,o=await v$1.getOrCompute(r,()=>{let c=Fo(i.config,n,s.rootDir),l={intent:n.intent,...n.target&&{target:n.target},...n.task&&{task:n.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(i.config?.auto_generated&&(l.auto_generated=true,l.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(l.note="No paths found.",l.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(l.tip=l.tip||"Many paths returned. Start with suggested_order for efficient exploration."),s.workspace){if(n.intent==="find"&&n.target&&c.paths.length===0){let d=xt(s.workspace,n.target);d.length>0&&(l.workspaceResults=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(n.intent==="context"&&n.task){let d=xt(s.workspace,n.task);d.length>0&&(l.workspaceContext=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})));}}return JSON.stringify(l,null,2)}),a=o;if(e.response_format==="concise")try{let c=JSON.parse(o);delete c.skip,delete c.tip,delete c.note,delete c.recovery,delete c.workspaceResults,delete c.workspaceContext,delete c.auto_generated,a=JSON.stringify(c,null,2);}catch{}try{let c=H.join(s.rootDir,".paradigm",".nav-called");E.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a}}function Bl(t){let e={},s={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},n=n$1(t.index),i=new Set;for(let a of n)if(a.filePath){e[a.symbol]=a.filePath,i.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":s.features.paths.includes(c)||s.features.paths.push(c);break;case "component":s.components.paths.includes(c)||s.components.paths.push(c);break;case "gate":s.gates.paths.includes(c)||s.gates.paths.push(c);break;case "flow":s.flows.paths.includes(c)||s.flows.paths.push(c);break}}let r=[],o=[];for(let a of t.aggregation.purposeFiles)r.push(a.filePath);return r.push(".paradigm/config.yaml"),t.gateConfig&&r.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:s,key_files:{config:r.slice(0,10),entry:o,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}var wn=null,Ds=false;function zl(t){if(wn||(wn=new f$5),!Ds)try{let e=r$1();for(let s of e)try{wn.addPattern(s);}catch{}Ds=!0;}catch{Ds=true;}return wn}function qo(){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 Lo(t,e,s){let n=zl(),i=new o$2(n);switch(t){case "paradigm_sentinel_triage":{let{symbol:r,status:o="all",environment:a,search:c,limit:l=10}=e,d=n.getRecentIncidents({limit:l,status:o,symbol:r,environment:a,search:c});if(d.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=d.map(u=>{let m=i.match(u,{maxResults:3});return {id:u.id,timestamp:u.timestamp,status:u.status,error:u.error.message,symbols:u.symbols,environment:u.environment,matches:m.map(g=>({patternId:g.pattern.id,name:g.pattern.name,confidence:g.confidence,strategy:g.pattern.resolution.strategy,description:g.pattern.resolution.description}))}});return {handled:true,text:JSON.stringify({count:p.length,incidents:p},null,2)}}case "paradigm_sentinel_show":{let{incidentId:r,includeTimeline:o,includeSimilar:a}=e,c=n.getIncident(r);if(!c)return {handled:true,text:JSON.stringify({error:`Incident ${r} not found`})};let l=i.match(c,{maxResults:5}),d={incident:c,matches:l.map(p=>({patternId:p.pattern.id,name:p.pattern.name,confidence:p.confidence,matchedCriteria:p.matchedCriteria,resolution:p.pattern.resolution}))};if(o&&c.flowPosition){let p=new x().build(c);p&&(d.timeline=new x().renderStructured(p));}if(a){let p=n.getRecentIncidents({symbol:Object.values(c.symbols)[0],limit:5}).filter(u=>u.id!==r);d.similar=p.map(u=>({id:u.id,error:u.error.message,status:u.status}));}return {handled:true,text:JSON.stringify(d,null,2)}}case "paradigm_sentinel_resolve":{let{incidentId:r,patternId:o,commitHash:a,prUrl:c,notes:l,wontFix:d}=e;return n.getIncident(r)?d?(n.updateIncident(r,{status:"wont-fix",resolvedAt:new Date().toISOString(),resolvedBy:"manual",resolution:{notes:l}}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${r} marked as won't fix`})}):(n.recordResolution({incidentId:r,patternId:o,commitHash:a,prUrl:c,notes:l}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${r} resolved`,patternId:o,commitHash:a,prUrl:c})}):{handled:true,text:JSON.stringify({error:`Incident ${r} not found`})}}case "paradigm_sentinel_patterns":{let{symbol:r,minConfidence:o,source:a}=e,c=n.getAllPatterns({source:a,minConfidence:o,includePrivate:false}),l=c;return r&&(l=c.filter(d=>{let p=d.pattern.symbols;return Object.values(p).some(u=>u?Array.isArray(u)?u.includes(r)||u.some(m=>r.match(m.replace("*",".*"))):u===r||r.match(u.replace("*",".*")):false)})),{handled:true,text:JSON.stringify({count:l.length,patterns:l.map(d=>({id:d.id,name:d.name,description:d.description,confidence:d.confidence.score,resolution:d.resolution,tags:d.tags}))},null,2)}}case "paradigm_sentinel_add_pattern":{let{id:r,name:o,description:a,pattern:c,resolution:l,tags:d}=e,p={id:r,name:o,description:a||"",pattern:{symbols:c.symbols||{},errorContains:c.errorContains,missingSignals:c.missingSignals},resolution:{description:l.description,strategy:l.strategy,priority:l.priority||"medium",codeHint:l.codeHint},source:"manual",private:false,tags:d||[]};return n.addPattern(p),{handled:true,text:JSON.stringify({success:true,message:`Pattern ${r} created`,pattern:p})}}case "paradigm_sentinel_record":{let{error:r,symbols:o,environment:a,service:c,version:l,flowPosition:d}=e,p=n.recordIncident({error:r,symbols:o,environment:a,service:c,version:l,flowPosition:d}),u=n.getIncident(p),m=u?i.match(u,{maxResults:3}):[];return {handled:true,text:JSON.stringify({success:true,incidentId:p,matches:m.map(g=>({patternId:g.pattern.id,confidence:g.confidence,resolution:g.pattern.resolution.description}))},null,2)}}case "paradigm_sentinel_stats":{let{period:r="7d",symbol:o}=e,a=new y(n);if(o){let p=a.getSymbolHealth(o);return {handled:true,text:JSON.stringify({symbol:o,health:p},null,2)}}let c=r.match(/^(\d+)d$/),l=c?parseInt(c[1],10):7,d=a.getStats(l);return {handled:true,text:JSON.stringify({period:`${l}d`,stats:d},null,2)}}case "paradigm_sentinel_suggest_pattern":{let{incidentId:r,minOccurrences:o}=e,a=new A(n);if(r){let l=n.getIncident(r);if(!l)return {handled:true,text:JSON.stringify({error:`Incident ${r} not found`})};let d=a.suggestFromIncident(l);return {handled:true,text:JSON.stringify({source:"incident",incidentId:r,suggestion:d},null,2)}}let c=a.findPatternCandidates(o||3);return {handled:true,text:JSON.stringify({source:"analysis",candidates:c.slice(0,5).map(l=>({occurrences:l.occurrenceCount,sampleIncidents:l.incidents.slice(0,3).map(d=>d.id),suggestion:l.suggestedPattern}))},null,2)}}case "paradigm_sentinel_logs":{let{level:r,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:p,limit:u=50}=e,m=n.queryLogs({level:r,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:p,limit:u}),g=n.getLogCount({level:r,symbol:o,service:a,since:l});return {handled:true,text:JSON.stringify({count:m.length,total:g,logs:m.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 r=n.getServices();return {handled:true,text:JSON.stringify({count:r.length,services:r.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:r}=e,o=r?n.getAppState(r):n.getAllAppStates();return {handled:true,text:JSON.stringify({states:o.map(a=>({service:a.service,sessionId:a.sessionId,state:a.state,activeFlows:a.activeFlows,activeGates:a.activeGates,timestamp:a.timestamp}))},null,2)}}case "paradigm_sentinel_validate_symbol":{let{symbol:r}=e,o=n.getLogCount({symbol:r});return {handled:true,text:JSON.stringify({symbol:r,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:r,service:o,since:a}=e,l=n.queryLogs({symbol:r,service:o,since:a,limit:100}).filter(d=>["flow","signal","gate"].includes(d.symbolType)).map(d=>({timestamp:d.timestamp,symbol:d.symbol,symbolType:d.symbolType,service:d.service,message:d.message,level:d.level}));return {handled:true,text:JSON.stringify({count:l.length,events:l},null,2)}}case "paradigm_sentinel_metrics":{let{name:r,type:o,service:a,since:c,aggregate:l,limit:d}=e;if(l&&r){let u=n.aggregateMetric(r,{service:a,since:c});return {handled:true,text:JSON.stringify(u,null,2)}}let p=n.queryMetrics({name:r,type:o,service:a,since:c,limit:Math.min(d||50,100)});return {handled:true,text:JSON.stringify({count:p.length,metrics:p.map(u=>({timestamp:u.timestamp,name:u.name,type:u.type,value:u.value,tags:u.tags,service:u.service}))},null,2)}}case "paradigm_sentinel_traces":{let{traceId:r,service:o,symbol:a,since:c,limit:l}=e;if(r){let p=n.getTrace(r);return p?{handled:true,text:JSON.stringify(p,null,2)}:{handled:true,text:JSON.stringify({error:"Trace not found"})}}let d=n.queryTraces({service:o,symbol:a,since:c,limit:Math.min(l||10,20)});return {handled:true,text:JSON.stringify({count:d.length,traces:d.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:r}=e;if(r){let a=n.getSchema(r);return a?{handled:true,text:JSON.stringify(a,null,2)}:{handled:true,text:JSON.stringify({error:`Schema "${r}" not found`})}}let o=n.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(a=>({id:a.id,version:a.version,name:a.name,description:a.description,eventTypeCount:a.eventTypes.length,scope:a.scope.label,tags:a.tags,registeredAt:a.registeredAt}))},null,2)}}case "paradigm_sentinel_events":{let{schemaId:r,eventType:o,category:a,service:c,scopeValue:l,severity:d,since:p,search:u,limit:m}=e,g=n.queryEvents({schemaId:r,eventType:o,category:a,service:c,scopeValue:l,severity:d,since:p,search:u,limit:Math.min(m||50,100)});return g.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:g.length,events:g.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:r,sessionId:o,limit:a}=e,c=n.getEventScopes(r,{limit:Math.min(a||50,200),sessionId:o});return c.length===0?{handled:true,text:JSON.stringify({count:0,scopes:[],tip:`No scopes found for schema "${r}". Events with scope values are required.`},null,2)}:{handled:true,text:JSON.stringify({count:c.length,scopes:c},null,2)}}default:return {handled:false,text:""}}}b$1();var Yl=30*1e3,Mo=new Map;async function _n(t){let e=H.resolve(t),s=Mo.get(e);if(s&&Date.now()-s.loadedAt<Yl)return s.index;let n=await Vl(e);return n&&Mo.set(e,{index:n,loadedAt:Date.now()}),n}async function Vl(t){let e=H.join(t,".paradigm","flow-index.json");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch(s){return a.component("#flow-loader").error("Error parsing flow-index.json",{error:s}),null}}function Kl(t,e){let s=t.symbolToFlows[e]||[],n=[];for(let i of s){let r=t.flows[i];if(!r)continue;let o=r.steps.map((a,c)=>({step:a,index:c})).filter(({step:a})=>a.symbol===e);for(let{step:a,index:c}of o){let l=r.steps.slice(c+1).map(d=>d.id);n.push({flowId:r.id,definedIn:r.definedIn,description:r.description,trigger:r.trigger,stepAffected:{id:a.id,action:a.action,position:c+1},downstreamSteps:l,validation:r.validation});}}return n}function Sn(t,e){let s=Kl(t,e),n=new Set;for(let o of s)o.validation?.command&&n.add(o.validation.command);let i="low",r=s.reduce((o,a)=>o+a.downstreamSteps.length,0);return s.length>3||r>10?i="high":(s.length>1||r>3)&&(i="medium"),{symbol:e,totalFlows:s.length,impactLevel:i,affectedFlows:s,validationCommands:Array.from(n),suggestion:s.length>0?`Changes to ${e} may affect ${s.length} flow(s). ${n.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function Wo(){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 Go(t,e,s){switch(t){case "paradigm_flows_affected":{let{symbol:n,includeValidation:i=true}=e,r=await _n(s.rootDir);if(!r)return {handled:true,text:JSON.stringify({error:"Flow index not found",symbol:n,suggestion:"Run `paradigm scan` to generate the flow index. Ensure .purpose files contain flows definitions.",example:`
2
+ import {a as a$1,b as b$3}from'./chunk-4UJ4NIEQ.js';import {e,v,b as b$2,n,c as c$2,d as d$3,q as q$2,p,o as o$1,s as s$1,i as i$2,k as k$1,l as l$1,a as a$6,m as m$1,t as t$1,u as u$1,j as j$3}from'./chunk-4N56FRNE.js';import {a as a$2,d as d$1,h as h$4,e as e$3}from'./chunk-Q527BPUF.js';import {o as o$2,A,y,x,f as f$5,r as r$1}from'./chunk-KLBH26PA.js';import {d as d$5,b as b$6,a as a$5}from'./chunk-JNSJVCTU.js';import {i as i$4}from'./chunk-XROULIQN.js';import {n as n$2,j as j$4,P,O,K,Q,L as L$1,I,J,D as D$1,H as H$1,m as m$2,l as l$2,E as E$2,v as v$2,N,q as q$3,C as C$1,S,o as o$3,z as z$2,t as t$2,B as B$1,s as s$2}from'./chunk-ZUAUFZRJ.js';import {f,g as g$1,e as e$1,q as q$1,t,o,v as v$1,i,m,$,h as h$1,k,l,j as j$2,n as n$1,u,r,sa,s,ta as ta$1,fa as fa$1,ga as ga$1,F,X as X$1,ea as ea$1,x as x$1,E as E$1,D,G,w,C,B,A as A$1,z as z$1,y as y$1,_,da as da$1,Z as Z$1,ca as ca$1,ba,aa as aa$1,J as J$1,U,K as K$1,O as O$1,Q as Q$1,S as S$1,R,V,T,P as P$1,N as N$1,Y as Y$1,W,a as a$9,d as d$9,c as c$4,L as L$2,M as M$1,ha as ha$1,ia as ia$1,qa as qa$1,pa as pa$1,ja,na as na$1,ka as ka$1,la as la$1,ma as ma$1,ra as ra$1,oa,I as I$1,b as b$b,H as H$2}from'./chunk-K7EQHFZP.js';import {j,a as a$3,i as i$1,b as b$4,h as h$3,g as g$3,c as c$1,d as d$2}from'./chunk-GRZQIKST.js';import {z,f as f$2,p as p$1,h as h$5,b as b$8,d as d$7,e as e$6,i as i$3,y as y$2,l as l$3,c as c$5}from'./chunk-KAFQA7HV.js';import {j as j$1,d,e as e$2,f as f$1,g as g$2,h as h$2}from'./chunk-6QXBXZF6.js';import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import {q,e as e$8,b as b$a,f as f$4}from'./chunk-LAYBUKMB.js';import {f as f$3,b as b$7,e as e$5,d as d$6,a as a$7,c as c$3}from'./chunk-DVZWCXB6.js';import {g,e as e$4,b as b$5,d as d$4,a as a$4}from'./chunk-QGZRM6ZB.js';import {h,e as e$7,d as d$8,b as b$9,a as a$8}from'./chunk-K7X3Z3GL.js';import {b,c,d as d$a}from'./chunk-5TAVYPOV.js';import*as E from'fs';import*as H from'path';import*as Ae from'js-yaml';import*as ua from'os';import {ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import {execSync}from'child_process';import*as Ft from'crypto';import*as bt from'fs/promises';var Et,Js,Us=b(()=>{Et={enabled:true,thresholds:{minComplianceRate:90,minEvents:20,timeWindowDays:30,minConsecutiveSessions:5,recencyDays:7},demotion:{failureThreshold:3,failureWindowDays:7,cooldownDays:14},neverGraduate:["explore-before-implement","ripple-before-modify","check-fragility","wisdom-before-implement","confidence-on-decisions","university-onboarded","university-content-valid"]},Js=new Set(["tool-called","context-checked"]);});var qa={};c(qa,{getAllStates:()=>zs,getConfig:()=>at,getState:()=>Mn,incrementFailure:()=>Ha,invalidateGraduationCache:()=>Fp,isGraduated:()=>Ip,loadGraduation:()=>Be,markNeverGraduate:()=>$p,saveGraduation:()=>Ln,setTier:()=>Ea});function Na(t){return H.join(t,".paradigm","graduation.yaml")}function Be(t){let e=H.resolve(t);if(Ht&&En===e&&Date.now()-Hn<Op)return Ht;let s=Na(e),n;if(E.existsSync(s))try{let i=E.readFileSync(s,"utf8");n=Ae.load(i);}catch{n={version:"1.0",config:{},states:{}};}else n={version:"1.0",config:{},states:{}};return n.version||(n.version="1.0"),n.config||(n.config={}),n.states||(n.states={}),Ht=n,En=e,Hn=Date.now(),n}function Ln(t,e){let s=H.resolve(t),n=Na(s),i=H.dirname(n);E.existsSync(i)||E.mkdirSync(i,{recursive:true});let r=Ae.dump(e,{lineWidth:120,noRefs:true,sortKeys:true});E.writeFileSync(n,r,"utf8"),Ht=e,En=s,Hn=Date.now();}function at(t){let e=Be(t);return {...Et,...e.config,thresholds:{...Et.thresholds,...e.config?.thresholds},demotion:{...Et.demotion,...e.config?.demotion},neverGraduate:e.config?.neverGraduate??Et.neverGraduate}}function Bs(t){return {habitId:t,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function Mn(t,e){let n=Be(t).states[e];return n?{...Bs(e),...n,habitId:e}:Bs(e)}function zs(t){let e=Be(t),s={};for(let[n,i]of Object.entries(e.states))s[n]={...Bs(n),...i,habitId:n};return s}function Ip(t,e){return Mn(t,e).tier==="hook"}function Ea(t,e,s,n){let i=Be(t),r=i.states[e]||{};i.states[e]={...r,tier:s,previousTier:r.tier||"habit",...s==="hook"?{graduatedAt:new Date().toISOString(),failureCount:0}:{},...s==="habit"&&r.tier==="hook"?{demotedAt:new Date().toISOString()}:{},...n},Ln(t,i);}function $p(t,e){let s=Be(t);s.states[e]||(s.states[e]={}),s.states[e].neverGraduate=true,s.states[e].tier="habit",Ln(t,s);}function Ha(t,e){let s=Be(t);s.states[e]||(s.states[e]={});let n=(s.states[e].failureCount||0)+1;return s.states[e].failureCount=n,Ln(t,s),n}function Fp(){Ht=null,En=null,Hn=0;}var Ht,En,Hn,Op,Wn=b(()=>{Us();Ht=null,En=null,Hn=0,Op=3e4;});b$1();b$1();var ql=30*1e3,As=new Map,vo=".paradigm/wisdom";async function ko(t){let e=H.resolve(t),s=As.get(e);if(s&&Date.now()-s.loadedAt<ql)return s.context;let n=await Ll(e);return As.set(e,{context:n,loadedAt:Date.now()}),n}async function Ll(t){let e=H.join(t,vo),s=E.existsSync(e),[n,i,r,o]=s?await Promise.all([Ml(e),Wl(e),Gl(e),Jl(e)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e$2(),l=f$1();}catch{}let d$1=new Set(i.map(y=>y.id)),p=i.map(y=>({...y,scope:"project"}));for(let y of a)d$1.has(y.id)||p.push({...y,scope:"global"});let u=new Set(o.map(y=>y.id)),g=o.map(y=>({...y,scope:"project"}));for(let y of c)u.has(y.id)||g.push({...y,scope:"global"});let m=n;if(l&&!n)m=l;else if(l&&n){let y={...n.by_symbol};if(l.by_symbol)for(let[f,b]of Object.entries(l.by_symbol))y[f]||(y[f]=b);m={...n,by_symbol:y,global:{...l.global,...n.global}};}return {preferences:m,antipatterns:p,decisions:g,expertise:r}}function qe(t){let e=H.resolve(t);As.delete(e);}async function Ml(t){let e=H.join(t,"preferences.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Ae.load(s)}catch(s){return a.component("#wisdom-loader").error("Error parsing preferences.yaml",{error:s}),null}}async function Wl(t){let e=H.join(t,"antipatterns.yaml");if(!E.existsSync(e))return [];try{let s=E.readFileSync(e,"utf8");return Ae.load(s).antipatterns||[]}catch(s){return a.component("#wisdom-loader").error("Error parsing antipatterns.yaml",{error:s}),[]}}async function Gl(t){let e=H.join(t,"expertise.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Ae.load(s)}catch(s){return a.component("#wisdom-loader").error("Error parsing expertise.yaml",{error:s}),null}}var wo=new Set;async function Jl(t){let e=H.join(t,"decisions");if(!E.existsSync(e))return [];let s=[];try{let n=E.readdirSync(e);n.some(r=>r.endsWith(".yaml")||r.endsWith(".yml"))&&!wo.has(e)&&(wo.add(e),a.component("#wisdom-loader").warn("wisdom-decisions found; run `paradigm migrate decisions` in v6.0. In v5.39.0 wisdom-decisions are still read but will be migrated to TD-streams in v6.0."));for(let r of n){if(!r.endsWith(".yaml")&&!r.endsWith(".yml"))continue;let o=H.join(e,r);try{let a=E.readFileSync(o,"utf8"),c=Ae.load(a);s.push(c);}catch(a$1){a.component("#wisdom-loader").error(`Error parsing ${r}`,{error:a$1});}}}catch(n){a.component("#wisdom-loader").error("Error reading decisions directory",{error:n});}return s.sort((n,i)=>n.id.localeCompare(i.id)),s}function So(t,e){return e.map(s=>Ul(t,s))}function Ul(t,e){let s=t.preferences?.by_symbol?.[e]||null,n=t.antipatterns.filter(o=>o.symbols.some(a=>a===e||yn(e,a))),i=t.decisions.filter(o=>o.symbols.some(a=>a===e||yn(e,a))),r=t.expertise?.experts.filter(o=>o.symbols?.some(a=>a===e||yn(e,a)))||[];return {symbol:e,preferences:s,antipatterns:n,decisions:i,experts:r}}function _o(t,e){return t.expertise?t.expertise.experts.filter(s=>!!(e.symbol&&s.symbols&&s.symbols.some(n=>n===e.symbol||yn(e.symbol,n))||e.area&&s.areas&&s.areas.some(n=>n.toLowerCase().includes(e.area.toLowerCase())))):[]}function yn(t,e){if(e.endsWith("*")){let s=e.slice(0,-1);return t.startsWith(s)}return t===e}async function xo(t,e){let s=H.join(t,vo),n=H.join(s,"antipatterns.yaml");E.existsSync(s)||E.mkdirSync(s,{recursive:true});let i={version:"1.0",antipatterns:[]};if(E.existsSync(n)){let r=E.readFileSync(n,"utf8");i=Ae.load(r);}i.antipatterns.push({...e,added:new Date().toISOString()}),E.writeFileSync(n,Ae.dump(i,{lineWidth:-1})),qe(t);}b$1();var Co=".paradigm/history";async function Ro(t){let e=H.join(t,Co);if(!E.existsSync(e))return {index:null,validation:null};let[s,n]=await Promise.all([Bl(e),zl(e)]);return {index:s,validation:n}}async function Bl(t){let e=H.join(t,"index.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Ae.load(s)}catch(s){return a.component("#history-loader").error("Error parsing index.yaml",{error:s.message}),null}}async function zl(t){let e=H.join(t,"validation.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Ae.load(s)}catch(s){return a.component("#history-loader").error("Error parsing validation.yaml",{error:s.message}),null}}function Po(t,e){return e.map(s=>Yl(t,s))}function Yl(t,e){let s=t.index?.by_symbol?.[e]||null,n=[];if(t.index?.co_changes){for(let r of t.index.co_changes)if(r.symbols.includes(e))for(let o of r.symbols)o!==e&&!n.includes(o)&&n.push(o);}let i=t.validation?.by_symbol?.[e]||null;return {symbol:e,summary:s,recent:s?.recent||[],co_changes:n,validation:i}}function jo(t,e){let s=[],n=[];if(!t.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let o of e){let a=t.index.by_symbol?.[o];a&&(a.fragility==="high"||a.fragility==="critical")&&s.push({symbol:o,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=t.index.fragile_symbols?.find(l=>l.symbol===o);c&&!s.find(l=>l.symbol===o)&&s.push(c);}for(let o of e){let a=t.index.co_changes?.filter(c=>c.symbols.includes(o));if(a?.length)for(let c of a){let l=c.symbols.filter(d=>d!==o&&!e.includes(d));l.length>0&&c.correlation>.7&&n.push(`${o} often changes with ${l.join(", ")} (${Math.round(c.correlation*100)}% correlation)`);}}let i=s.filter(o=>o.fragility==="critical").length===0,r=[];return s.length>0&&(r.push("Consider adding extra test coverage before modifying fragile symbols"),r.push("Review recent rollbacks and failures for these symbols")),n.length>0&&r.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:s,warnings:n,safe_to_modify:i,recommendations:r}}async function Ds(t,e){let s=H.join(t,Co),n=H.join(s,"log.jsonl");E.existsSync(s)||E.mkdirSync(s,{recursive:true});let i=Vl(n),r=new Date().toISOString(),o={id:i,ts:r,...e},a=JSON.stringify(o)+`
3
+ `;return E.appendFileSync(n,a),i}async function To(t,e,s,n){return Ds(t,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:s,tests:n})}function Vl(t){let e=1;return E.existsSync(t)&&(e=E.readFileSync(t,"utf8").split(`
4
+ `).filter(n=>n.trim()).length+1),`h${String(e).padStart(4,"0")}`}b$1();function Kl(t){let e=H.resolve(t),s=E.readFileSync(e,"utf8"),n=Ae.load(s);if(!n||typeof n!="object")throw new Error(`Invalid workspace file: ${t}`);let i={version:String(n.version||"1.0"),name:String(n.name||"unnamed-workspace"),members:[]};if(Array.isArray(n.members)){for(let r of n.members)if(typeof r=="object"&&r!==null){let o=r;i.members.push({name:String(o.name||""),path:String(o.path||""),role:o.role,exports:Array.isArray(o.exports)?o.exports.map(String):void 0});}}return i}function Do(t,e){let s=H.resolve(t),n=H.resolve(s,e);if(!E.existsSync(n))return a.component("#workspace-loader").warn("Workspace file not found",{workspacePath:n}),null;let i;try{i=Kl(n);}catch(c){return a.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let r=H.dirname(n),o="";for(let c of i.members){let l=H.resolve(r,c.path);if(Ao(l)===Ao(s)){o=c.name;break}}if(!o)return a.component("#workspace-loader").warn("Current directory is not a member of workspace",{workspace:i.name}),null;let a$1=new Map;for(let c of i.members){if(c.name===o)continue;let l=H.resolve(r,c.path),d=H.join(l,".paradigm","scan-index.json");if(!E.existsSync(d)){a.component("#workspace-loader").warn("No scan-index.json for workspace member",{member:c.name,scanIndexPath:d});continue}try{let p=JSON.parse(E.readFileSync(d,"utf8")),u=Zl(p);c.exports&&c.exports.length>0&&(u=Ql(u,c.exports));let g=null,m=H.join(l,"portal.yaml");if(E.existsSync(m))try{let y=E.readFileSync(m,"utf8"),f=Ae.load(y);f&&(g=f);}catch{}a$1.set(c.name,{index:u,gateConfig:g});}catch(p){a.component("#workspace-loader").warn("Could not load index for workspace member",{member:c.name,error:p.message});}}return {config:i,workspacePath:n,currentMember:o,siblingIndices:a$1}}function Ql(t,e){let n=n$1(t).filter(i=>{let r=i.symbol;return e.some(o=>Xl(o,r))});return ed(n)}function Xl(t,e){let s=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${s}$`,"i").test(e)}function Rt(t,e){let s=[];for(let[n,i]of t.siblingIndices){let r=j$2(i.index,e);for(let o of r)s.push({project:n,symbol:`${n}/${o.symbol}`,type:o.type,description:o.description,filePath:o.filePath});}return s}function Oo(t,e){let s=[],n=e.includes("/")?e.split("/").pop():e;for(let[i,r]of t.siblingIndices){let o=[],a=n$1(r.index);for(let c of a){let l=c.references||[],d=c.description||"",p=l.some(g=>g===n||g===e||g.endsWith(`/${n}`)),u=d.includes(n);(p||u)&&o.push({symbol:c.symbol,type:c.type,description:c.description});}o.length>0&&s.push({project:i,references:o});}return s}function Ao(t){return H.resolve(t).replace(/\/+$/,"")}function Zl(t){let e={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"},s=[];for(let[n,i]of Object.entries(e)){let r=t[n];if(!(!r||typeof r!="object"))for(let[o,a]of Object.entries(r)){let c={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"}[i]||"#";s.push({id:o,symbol:a.symbol||`${c}${o}`,type:i,source:"purpose",filePath:a.path||"",data:{},references:a.related||[],referencedBy:[],description:a.description,tags:a.visualTags||[]});}}return g$1({symbols:s,purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}function ed(t){return g$1({symbols:t.map(e=>({id:e.id||e.symbol.replace(/^[#$^!~]/,""),symbol:e.symbol,type:e.type,source:"purpose",filePath:e.filePath||"",data:e.data||{},references:e.references||[],referencedBy:e.referencedBy||[],description:e.description,tags:e.tags})),purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}async function Vg(t){let e=H.resolve(t),s=await f(e),n=g$1(s),i=null,r=H.join(e,"portal.yaml");if(E.existsSync(r))try{i=await e$1(r);}catch(d){let p=d?.name??"Error";a.component("#index-loader").warn("Could not parse portal.yaml",{errorClass:p});}let o=H.basename(e),a$1=H.join(e,".premise");if(E.existsSync(a$1))try{let p=E.readFileSync(a$1,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);p&&(o=p[1].trim());}catch{}let c=null,l=H.join(e,".paradigm","config.yaml");if(E.existsSync(l))try{let d=E.readFileSync(l,"utf8"),p=Ae.load(d);p&&typeof p=="object"&&(p.version||a.component("#index-loader").warn('config.yaml missing "version" field'),p.project||a.component("#index-loader").warn('config.yaml missing "project" field')),p&&typeof p.workspace=="string"&&(c=Do(e,p.workspace));}catch(d){a.component("#index-loader").warn("Failed to load workspace config",{error:d.message});}return {rootDir:e,index:n,aggregation:s,gateConfig:i,projectName:o,wisdom:null,history:null,workspace:c,_loadedAt:Date.now()}}async function bn(t){return t.wisdom||(t.wisdom=await ko(t.rootDir)),t.wisdom}async function Is(t){return t.history||(t.history=await Ro(t.rootDir)),t.history}j();b$1();var $o=false;function No(){return [{name:"paradigm_wisdom_context",description:"Get team wisdom (preferences, antipatterns, decisions) for symbols before implementing. Call this before making changes to understand team patterns. Returns preferences, antipatterns, and decisions relevant to the specified symbols. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get wisdom for (e.g., ["@checkout", "#payment-form"])'},include_global:{type:"boolean",description:"Include global preferences (default: true)"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_wisdom_record",description:"Record a new team learning: antipattern (what not to do) or decision (architectural choice). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to record"},id:{type:"string",description:'Unique ID (for antipattern: e.g., "api-001", for decision: e.g., "001")'},symbols:{type:"array",items:{type:"string"},description:"Related symbols"},description:{type:"string",description:"What not to do (antipattern) or the decision made (decision)"},reason:{type:"string",description:"Why this is an antipattern / context for decision"},alternative:{type:"string",description:"What to do instead (for antipatterns)"},title:{type:"string",description:"Decision title (for decisions)"},status:{type:"string",enum:["proposed","accepted","deprecated","superseded"],description:"Decision status (for decisions)"},rationale:{type:"object",properties:{factors:{type:"array",items:{type:"string"}},conclusion:{type:"string"}},description:"Decision rationale (for decisions)"},consequences:{type:"object",properties:{positive:{type:"array",items:{type:"string"}},negative:{type:"array",items:{type:"string"}},mitigations:{type:"array",items:{type:"string"}}},description:"Expected consequences (for decisions)"},scope:{type:"string",enum:["project","global"],description:'Where to store: "project" (default) writes to .paradigm/wisdom/, "global" writes to ~/.paradigm/wisdom/'}},required:["type","id","symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]}},{name:"paradigm_wisdom_expert",description:"Find human experts who know about specific symbols or areas. Returns names and contact info for relevant experts. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to find experts for (e.g., "@checkout")'},area:{type:"string",description:'General area to find experts for (e.g., "payments", "auth")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function wn(t,e,s){switch(t){case "paradigm_wisdom_context":{let{symbols:n,include_global:i=true}=e,r=await bn(s),o=So(r,n),a={symbols:n,wisdom:o.map(d=>({symbol:d.symbol,preferences:d.preferences,antipatterns:d.antipatterns.map(p=>({id:p.id,description:p.description,reason:p.reason,alternative:p.alternative,scope:p.scope||"project"})),decisions:d.decisions.map(p=>({id:p.id,title:p.title,status:p.status,decision:p.decision,scope:p.scope||"project"})),experts:d.experts.map(p=>p.name)}))};i&&r.preferences?.global&&(a.global_preferences=r.preferences.global);let c=o.reduce((d,p)=>d+p.antipatterns.length,0),l=o.reduce((d,p)=>d+p.decisions.length,0);a.summary={symbols_with_preferences:o.filter(d=>d.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:o.some(d=>d.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let d={},p=[];for(let u of n){let g=await a$3(s.rootDir,{symbol:u,hasAssessment:!0,limit:100});if(g.length===0)continue;let m={correct:0,partial:0,incorrect:0},y=0,f=0;for(let h of g){let w=h.assessment.verdict;m[w]++,h.confidence!=null&&(y+=h.confidence,f++);}d[u]={total:g.length,...m,avgConfidence:f>0?Math.round(y/f*1e3)/1e3:null};let b=(m.correct+m.partial*.5)/g.length;b<.6&&g.length>=3&&p.push(`Low historical accuracy for ${u}: ${Math.round(b*100)}% across ${g.length} entries. Proceed with extra caution.`);}Object.keys(d).length>0&&(a.calibration=d),p.length>0&&(a.calibration_warnings=p);}catch{}return {handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_wisdom_record":{let{type:n,id:i,symbols:r,description:o,reason:a$1,alternative:c,title:l,status:d,rationale:p,consequences:u,scope:g="project"}=e;if(n==="antipattern"){if(!o||!a$1||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let m={id:i,symbols:r,description:o,reason:a$1,alternative:c};return g==="global"?g$2(m):await xo(s.rootDir,m),qe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:i,scope:g,message:`Antipattern recorded to ${g} scope`})}}if(n==="decision"){if(!l||!o||!p||!u)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};if($o||($o=true,a.component("#wisdom").warn('paradigm_wisdom_record({type:"decision"}) is deprecated. Use paradigm_decision_record instead.',{deprecation:"v6.0",canonical_tool:"paradigm_decision_record"})),g==="global"){let f={id:i,title:l,status:d||"proposed",date:new Date().toISOString().split("T")[0],symbols:r,context:a$1||"",decision:o,rationale:p,consequences:u};return h$2(f),qe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:i,scope:"global",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record for project-scoped decisions.',message:"Decision recorded to global scope"})}}let m=a$2(s.rootDir,{title:l,decision:o,rationale:{factors:p.factors,conclusion:p.conclusion},participants:[{id:"wisdom-record",role:"agent",stance:"proposed"}],symbols_affected:r,status:d==="accepted"?"active":d==="proposed"?"proposed":"active",context:a$1||void 0,consequences:u,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),y=d$1(s.rootDir,m.id);return qe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:m.id,legacy_id:i,scope:"project",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record going forward.',message:`Decision recorded (routed to decisions stream as ${m.id})`,...y?{companion_lore_id:y}:{}})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${n}`})}}case "paradigm_wisdom_promote":{let{type:n,id:i}=e,r=await bn(s),o=H.basename(s.rootDir);if(n==="antipattern"){let a=r.antipatterns.find(l=>l.id===i);return a?d().some(l=>l.id===i)?{handled:true,text:JSON.stringify({error:`Antipattern "${i}" already exists in global scope`})}:(g$2({...a,learned_from:`promoted from ${o}`}),qe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:i,promoted_from:o,message:`Antipattern "${i}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${i}" not found in project`})}}if(n==="decision"){let a=r.decisions.find(l=>l.id===i);return a?e$2().some(l=>l.id===i)?{handled:true,text:JSON.stringify({error:`Decision "${i}" already exists in global scope`})}:(h$2(a),qe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:i,promoted_from:o,message:`Decision "${i}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${i}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${n}`})}}case "paradigm_wisdom_expert":{let{symbol:n,area:i}=e;if(!n&&!i)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let r=await bn(s),o=_o(r,{symbol:n,area:i});return {handled:true,text:JSON.stringify({query:{symbol:n,area:i},count:o.length,experts:o.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:o.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function Eo(){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 Ho(t,e,s){switch(t){case "paradigm_history_context":{let{symbols:n}=e,i=await Is(s),r=Po(i,n),o={symbols:n,history:r.map(a=>({symbol:a.symbol,summary:a.summary?{total_changes:a.summary.total_changes,last_modified:a.summary.last_modified,stability_score:a.summary.stability_score,fragility:a.summary.fragility,contributors:a.summary.contributors}:null,recent:a.recent.slice(0,3).map(c=>({type:c.type,description:c.description,author:c.author,ts:c.ts})),co_changes:a.co_changes.slice(0,5)})),summary:{total_symbols:n.length,with_history:r.filter(a=>a.summary).length,fragile_count:r.filter(a=>a.summary?.fragility==="high"||a.summary?.fragility==="critical").length}};return {handled:true,text:JSON.stringify(o,null,2)}}case "paradigm_history_record":{let{type:n,symbols:i,intent:r,description:o,commit:a,files:c,reason:l}=e,d=await Ds(s.rootDir,{type:n,symbols:i,author:{type:"agent",id:"claude"},intent:r,description:o,commit:a,files:c,reason:l});return {handled:true,text:JSON.stringify({success:true,id:d,type:n,symbols:i,message:"History entry recorded successfully",note:"Run paradigm history reindex to update the index after multiple entries"})}}case "paradigm_history_validate":{let{implementation_id:n,result:i,tests:r}=e,o=await To(s.rootDir,n||"unknown",i,r);return {handled:true,text:JSON.stringify({success:true,id:o,result:i,tests:r,message:"Validation recorded successfully"})}}case "paradigm_history_fragility":{let{symbols:n}=e,i=await Is(s),r=jo(i,n);return {handled:true,text:JSON.stringify({symbols:n,safe_to_modify:r.safe_to_modify,fragile:r.fragile.map(o=>({symbol:o.symbol,fragility:o.fragility,reason:o.reason})),warnings:r.warnings,recommendations:r.recommendations,summary:r.fragile.length===0?"All symbols are stable - safe to proceed":r.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:""}}}b$1();var td=".paradigm/navigator.yaml";async function Mo(t){let e=H.join(t,td);if(!E.existsSync(e))return {config:null,configPath:null};try{let s=E.readFileSync(e,"utf8");return {config:Ae.load(s),configPath:e}}catch(s){return a.component("#navigator-loader").error("Error parsing navigator.yaml",{error:s}),{config:null,configPath:e}}}function Wo(t,e,s){switch(e.intent){case "find":return nd(t,e.target||"");case "explore":return sd(t,e.target||"");case "context":return id(t,e.task||"");default:return {paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function nd(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let i=t.symbols[e];if(i)n.paths.push(i),n.symbols.push(e),n.explanation=`Found symbol ${e} at ${i}`;else {let r=Object.entries(t.symbols).filter(([o])=>o.includes(e.slice(1))).slice(0,5);r.length>0?(n.paths=r.map(([,o])=>o),n.symbols=r.map(([o])=>o),n.explanation=`Found ${r.length} symbols matching "${e}"`):n.explanation=`Symbol ${e} not found in navigator`;}}else {let i=Object.entries(t.symbols).filter(([r])=>r.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(i.length>0)n.paths=i.map(([,r])=>r),n.symbols=i.map(([r])=>r),n.explanation=`Found ${i.length} symbols matching "${e}"`;else {let r=rd(t,e);r?(n.paths=r.paths,n.explanation=`Found ${e} in structure: ${r.paths.join(", ")}`):n.explanation=`No matches found for "${e}"`;}}return n.suggested_order=$s(n.paths,t),n}function sd(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]},i=e.toLowerCase();for(let[r,o]of Object.entries(t.structure))if(o&&(r.toLowerCase().includes(i)||i.includes(r.toLowerCase()))){n.paths.push(...o.paths);let a=Object.entries(t.symbols).filter(([c])=>c.startsWith(o.symbol)).slice(0,10);n.symbols.push(...a.map(([c])=>c));}for(let[r,o]of Object.entries(t.key_files))r.toLowerCase().includes(i)&&n.paths.push(...o);if(n.paths.length===0){let r=Object.entries(t.symbols).filter(([o,a])=>o.toLowerCase().includes(i)||a.toLowerCase().includes(i)).slice(0,10);n.paths=[...new Set(r.map(([,o])=>o))],n.symbols=r.map(([o])=>o);}return n.explanation=`Exploration paths for "${e}": ${n.paths.length} locations, ${n.symbols.length} symbols`,n.suggested_order=$s(n.paths,t),n}function id(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]},i=e.toLowerCase(),r=od(i);for(let[o,a]of Object.entries(t.structure))a&&r.some(c=>o.toLowerCase().includes(c))&&n.paths.push(...a.paths);for(let[o,a]of Object.entries(t.symbols)){let c=o.slice(1).toLowerCase();r.some(l=>c.includes(l)||l.includes(c))&&(n.paths.push(a),n.symbols.push(o));}return n.paths.push(...t.key_files.config),n.paths=[...new Set(n.paths)],n.symbols=[...new Set(n.symbols)],i.includes("test")?n.skip=t.skip_patterns.always:n.skip=[...t.skip_patterns.always,...t.skip_patterns.unless_testing],!i.includes("doc")&&!i.includes("readme")&&n.skip.push(...t.skip_patterns.unless_docs),n.explanation=`Context for "${e}": ${n.paths.length} relevant files, ${n.symbols.length} symbols`,n.suggested_order=$s(n.paths,t),n}function rd(t,e){let s=e.toLowerCase();for(let[n,i]of Object.entries(t.structure))if(i&&(n.toLowerCase().includes(s)||s.includes(n.toLowerCase())))return i;return null}function od(t){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return t.split(/\s+/).map(s=>s.replace(/[^a-z0-9]/g,"")).filter(s=>s.length>2&&!e.has(s))}function $s(t,e){let s={};for(let n of t){let i=0;e.key_files.config.some(r=>n.includes(r))&&(i+=100),e.key_files.entry.some(r=>n.includes(r))&&(i+=80),e.key_files.types.some(r=>n.includes(r))&&(i+=60),i-=n.split("/").length*2,s[n]=i;}return [...t].sort((n,i)=>(s[i]||0)-(s[n]||0))}var ad={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function Uo(){return [ad]}async function kn(t,e,s){if(t!=="paradigm_navigate")return {handled:false,text:""};let n={intent:e.intent||"find",target:e.target,task:e.task},i=await Mo(s.rootDir);if(i.config||(i={config:cd(s),configPath:null}),false);if(n.intent==="context"&&!n.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((n.intent==="find"||n.intent==="explore")&&!n.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${n.intent} intent`,example:n.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let r=`navigate:${n.intent}:${n.target||""}:${n.task||""}`,o=await v$1.getOrCompute(r,()=>{let c=Wo(i.config,n,s.rootDir),l={intent:n.intent,...n.target&&{target:n.target},...n.task&&{task:n.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(i.config?.auto_generated&&(l.auto_generated=true,l.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(l.note="No paths found.",l.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(l.tip=l.tip||"Many paths returned. Start with suggested_order for efficient exploration."),s.workspace){if(n.intent==="find"&&n.target&&c.paths.length===0){let d=Rt(s.workspace,n.target);d.length>0&&(l.workspaceResults=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(n.intent==="context"&&n.task){let d=Rt(s.workspace,n.task);d.length>0&&(l.workspaceContext=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})));}}return JSON.stringify(l,null,2)}),a=o;if(e.response_format==="concise")try{let c=JSON.parse(o);delete c.skip,delete c.tip,delete c.note,delete c.recovery,delete c.workspaceResults,delete c.workspaceContext,delete c.auto_generated,a=JSON.stringify(c,null,2);}catch{}try{let c=H.join(s.rootDir,".paradigm",".nav-called");E.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a}}function cd(t){let e={},s={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},n=n$1(t.index),i=new Set;for(let a of n)if(a.filePath){e[a.symbol]=a.filePath,i.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":s.features.paths.includes(c)||s.features.paths.push(c);break;case "component":s.components.paths.includes(c)||s.components.paths.push(c);break;case "gate":s.gates.paths.includes(c)||s.gates.paths.push(c);break;case "flow":s.flows.paths.includes(c)||s.flows.paths.push(c);break}}let r=[],o=[];for(let a of t.aggregation.purposeFiles)r.push(a.filePath);return r.push(".paradigm/config.yaml"),t.gateConfig&&r.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:s,key_files:{config:r.slice(0,10),entry:o,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}var Sn=null,Fs=false;function ld(t){if(Sn||(Sn=new f$5),!Fs)try{let e=r$1();for(let s of e)try{Sn.addPattern(s);}catch{}Fs=!0;}catch{Fs=true;}return Sn}function Bo(){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 zo(t,e,s){let n=ld(),i=new o$2(n);switch(t){case "paradigm_sentinel_triage":{let{symbol:r,status:o="all",environment:a,search:c,limit:l=10}=e,d=n.getRecentIncidents({limit:l,status:o,symbol:r,environment:a,search:c});if(d.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=d.map(u=>{let g=i.match(u,{maxResults:3});return {id:u.id,timestamp:u.timestamp,status:u.status,error:u.error.message,symbols:u.symbols,environment:u.environment,matches:g.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:r,includeTimeline:o,includeSimilar:a}=e,c=n.getIncident(r);if(!c)return {handled:true,text:JSON.stringify({error:`Incident ${r} not found`})};let l=i.match(c,{maxResults:5}),d={incident:c,matches:l.map(p=>({patternId:p.pattern.id,name:p.pattern.name,confidence:p.confidence,matchedCriteria:p.matchedCriteria,resolution:p.pattern.resolution}))};if(o&&c.flowPosition){let p=new x().build(c);p&&(d.timeline=new x().renderStructured(p));}if(a){let p=n.getRecentIncidents({symbol:Object.values(c.symbols)[0],limit:5}).filter(u=>u.id!==r);d.similar=p.map(u=>({id:u.id,error:u.error.message,status:u.status}));}return {handled:true,text:JSON.stringify(d,null,2)}}case "paradigm_sentinel_resolve":{let{incidentId:r,patternId:o,commitHash:a,prUrl:c,notes:l,wontFix:d}=e;return n.getIncident(r)?d?(n.updateIncident(r,{status:"wont-fix",resolvedAt:new Date().toISOString(),resolvedBy:"manual",resolution:{notes:l}}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${r} marked as won't fix`})}):(n.recordResolution({incidentId:r,patternId:o,commitHash:a,prUrl:c,notes:l}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${r} resolved`,patternId:o,commitHash:a,prUrl:c})}):{handled:true,text:JSON.stringify({error:`Incident ${r} not found`})}}case "paradigm_sentinel_patterns":{let{symbol:r,minConfidence:o,source:a}=e,c=n.getAllPatterns({source:a,minConfidence:o,includePrivate:false}),l=c;return r&&(l=c.filter(d=>{let p=d.pattern.symbols;return Object.values(p).some(u=>u?Array.isArray(u)?u.includes(r)||u.some(g=>r.match(g.replace("*",".*"))):u===r||r.match(u.replace("*",".*")):false)})),{handled:true,text:JSON.stringify({count:l.length,patterns:l.map(d=>({id:d.id,name:d.name,description:d.description,confidence:d.confidence.score,resolution:d.resolution,tags:d.tags}))},null,2)}}case "paradigm_sentinel_add_pattern":{let{id:r,name:o,description:a,pattern:c,resolution:l,tags:d}=e,p={id:r,name:o,description:a||"",pattern:{symbols:c.symbols||{},errorContains:c.errorContains,missingSignals:c.missingSignals},resolution:{description:l.description,strategy:l.strategy,priority:l.priority||"medium",codeHint:l.codeHint},source:"manual",private:false,tags:d||[]};return n.addPattern(p),{handled:true,text:JSON.stringify({success:true,message:`Pattern ${r} created`,pattern:p})}}case "paradigm_sentinel_record":{let{error:r,symbols:o,environment:a,service:c,version:l,flowPosition:d}=e,p=n.recordIncident({error:r,symbols:o,environment:a,service:c,version:l,flowPosition:d}),u=n.getIncident(p),g=u?i.match(u,{maxResults:3}):[];return {handled:true,text:JSON.stringify({success:true,incidentId:p,matches:g.map(m=>({patternId:m.pattern.id,confidence:m.confidence,resolution:m.pattern.resolution.description}))},null,2)}}case "paradigm_sentinel_stats":{let{period:r="7d",symbol:o}=e,a=new y(n);if(o){let p=a.getSymbolHealth(o);return {handled:true,text:JSON.stringify({symbol:o,health:p},null,2)}}let c=r.match(/^(\d+)d$/),l=c?parseInt(c[1],10):7,d=a.getStats(l);return {handled:true,text:JSON.stringify({period:`${l}d`,stats:d},null,2)}}case "paradigm_sentinel_suggest_pattern":{let{incidentId:r,minOccurrences:o}=e,a=new A(n);if(r){let l=n.getIncident(r);if(!l)return {handled:true,text:JSON.stringify({error:`Incident ${r} not found`})};let d=a.suggestFromIncident(l);return {handled:true,text:JSON.stringify({source:"incident",incidentId:r,suggestion:d},null,2)}}let c=a.findPatternCandidates(o||3);return {handled:true,text:JSON.stringify({source:"analysis",candidates:c.slice(0,5).map(l=>({occurrences:l.occurrenceCount,sampleIncidents:l.incidents.slice(0,3).map(d=>d.id),suggestion:l.suggestedPattern}))},null,2)}}case "paradigm_sentinel_logs":{let{level:r,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:p,limit:u=50}=e,g=n.queryLogs({level:r,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:p,limit:u}),m=n.getLogCount({level:r,symbol:o,service:a,since:l});return {handled:true,text:JSON.stringify({count:g.length,total:m,logs:g.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 r=n.getServices();return {handled:true,text:JSON.stringify({count:r.length,services:r.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:r}=e,o=r?n.getAppState(r):n.getAllAppStates();return {handled:true,text:JSON.stringify({states:o.map(a=>({service:a.service,sessionId:a.sessionId,state:a.state,activeFlows:a.activeFlows,activeGates:a.activeGates,timestamp:a.timestamp}))},null,2)}}case "paradigm_sentinel_validate_symbol":{let{symbol:r}=e,o=n.getLogCount({symbol:r});return {handled:true,text:JSON.stringify({symbol:r,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:r,service:o,since:a}=e,l=n.queryLogs({symbol:r,service:o,since:a,limit:100}).filter(d=>["flow","signal","gate"].includes(d.symbolType)).map(d=>({timestamp:d.timestamp,symbol:d.symbol,symbolType:d.symbolType,service:d.service,message:d.message,level:d.level}));return {handled:true,text:JSON.stringify({count:l.length,events:l},null,2)}}case "paradigm_sentinel_metrics":{let{name:r,type:o,service:a,since:c,aggregate:l,limit:d}=e;if(l&&r){let u=n.aggregateMetric(r,{service:a,since:c});return {handled:true,text:JSON.stringify(u,null,2)}}let p=n.queryMetrics({name:r,type:o,service:a,since:c,limit:Math.min(d||50,100)});return {handled:true,text:JSON.stringify({count:p.length,metrics:p.map(u=>({timestamp:u.timestamp,name:u.name,type:u.type,value:u.value,tags:u.tags,service:u.service}))},null,2)}}case "paradigm_sentinel_traces":{let{traceId:r,service:o,symbol:a,since:c,limit:l}=e;if(r){let p=n.getTrace(r);return p?{handled:true,text:JSON.stringify(p,null,2)}:{handled:true,text:JSON.stringify({error:"Trace not found"})}}let d=n.queryTraces({service:o,symbol:a,since:c,limit:Math.min(l||10,20)});return {handled:true,text:JSON.stringify({count:d.length,traces:d.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:r}=e;if(r){let a=n.getSchema(r);return a?{handled:true,text:JSON.stringify(a,null,2)}:{handled:true,text:JSON.stringify({error:`Schema "${r}" not found`})}}let o=n.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(a=>({id:a.id,version:a.version,name:a.name,description:a.description,eventTypeCount:a.eventTypes.length,scope:a.scope.label,tags:a.tags,registeredAt:a.registeredAt}))},null,2)}}case "paradigm_sentinel_events":{let{schemaId:r,eventType:o,category:a,service:c,scopeValue:l,severity:d,since:p,search:u,limit:g}=e,m=n.queryEvents({schemaId:r,eventType:o,category:a,service:c,scopeValue:l,severity:d,since:p,search:u,limit:Math.min(g||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:r,sessionId:o,limit:a}=e,c=n.getEventScopes(r,{limit:Math.min(a||50,200),sessionId:o});return c.length===0?{handled:true,text:JSON.stringify({count:0,scopes:[],tip:`No scopes found for schema "${r}". Events with scope values are required.`},null,2)}:{handled:true,text:JSON.stringify({count:c.length,scopes:c},null,2)}}default:return {handled:false,text:""}}}b$1();var dd=30*1e3,Yo=new Map;async function Cn(t){let e=H.resolve(t),s=Yo.get(e);if(s&&Date.now()-s.loadedAt<dd)return s.index;let n=await pd(e);return n&&Yo.set(e,{index:n,loadedAt:Date.now()}),n}async function pd(t){let e=H.join(t,".paradigm","flow-index.json");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch(s){return a.component("#flow-loader").error("Error parsing flow-index.json",{error:s}),null}}function ud(t,e){let s=t.symbolToFlows[e]||[],n=[];for(let i of s){let r=t.flows[i];if(!r)continue;let o=r.steps.map((a,c)=>({step:a,index:c})).filter(({step:a})=>a.symbol===e);for(let{step:a,index:c}of o){let l=r.steps.slice(c+1).map(d=>d.id);n.push({flowId:r.id,definedIn:r.definedIn,description:r.description,trigger:r.trigger,stepAffected:{id:a.id,action:a.action,position:c+1},downstreamSteps:l,validation:r.validation});}}return n}function Rn(t,e){let s=ud(t,e),n=new Set;for(let o of s)o.validation?.command&&n.add(o.validation.command);let i="low",r=s.reduce((o,a)=>o+a.downstreamSteps.length,0);return s.length>3||r>10?i="high":(s.length>1||r>3)&&(i="medium"),{symbol:e,totalFlows:s.length,impactLevel:i,affectedFlows:s,validationCommands:Array.from(n),suggestion:s.length>0?`Changes to ${e} may affect ${s.length} flow(s). ${n.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function Vo(){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 Ko(t,e,s){switch(t){case "paradigm_flows_affected":{let{symbol:n,includeValidation:i=true}=e,r=await Cn(s.rootDir);if(!r)return {handled:true,text:JSON.stringify({error:"Flow index not found",symbol:n,suggestion:"Run `paradigm scan` to generate the flow index. Ensure .purpose files contain flows definitions.",example:`
5
5
  flows:
6
6
  $task-creation:
7
7
  description: "Full task creation flow"
@@ -14,7 +14,7 @@ flows:
14
14
  - id: create
15
15
  action: "Create task record"
16
16
  symbol: "@tasks"
17
- `},null,2)};let o=Sn(r,n),a={symbol:o.symbol,totalFlows:o.totalFlows,impactLevel:o.impactLevel,affectedFlows:o.affectedFlows.map(l=>{let d={flowId:l.flowId,definedIn:l.definedIn,description:l.description,stepAffected:l.stepAffected,downstreamSteps:l.downstreamSteps};return l.trigger&&(d.trigger=l.trigger),i&&l.validation&&(d.validation=l.validation),d}),suggestion:o.suggestion};return i&&o.validationCommands.length>0&&(a.validationCommands=o.validationCommands),{handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_flow_check":case "paradigm_flow_validate":{let{flowId:n,checkImplementation:i=false}=e,r=H.join(s.rootDir,".paradigm","flows.yaml"),o=null;if(E.existsSync(r))try{let f=E.readFileSync(r,"utf-8");o=Te.load(f);}catch(f){return {handled:true,text:JSON.stringify({error:"Failed to parse flows.yaml",details:String(f)},null,2)}}if(!o||!o.flows||Object.keys(o.flows).length===0)return {handled:true,text:JSON.stringify({error:"No flows found",suggestion:"Create .paradigm/flows.yaml with flow definitions",example:`
17
+ `},null,2)};let o=Rn(r,n),a={symbol:o.symbol,totalFlows:o.totalFlows,impactLevel:o.impactLevel,affectedFlows:o.affectedFlows.map(l=>{let d={flowId:l.flowId,definedIn:l.definedIn,description:l.description,stepAffected:l.stepAffected,downstreamSteps:l.downstreamSteps};return l.trigger&&(d.trigger=l.trigger),i&&l.validation&&(d.validation=l.validation),d}),suggestion:o.suggestion};return i&&o.validationCommands.length>0&&(a.validationCommands=o.validationCommands),{handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_flow_check":case "paradigm_flow_validate":{let{flowId:n,checkImplementation:i=false}=e,r=H.join(s.rootDir,".paradigm","flows.yaml"),o=null;if(E.existsSync(r))try{let f=E.readFileSync(r,"utf-8");o=Ae.load(f);}catch(f){return {handled:true,text:JSON.stringify({error:"Failed to parse flows.yaml",details:String(f)},null,2)}}if(!o||!o.flows||Object.keys(o.flows).length===0)return {handled:true,text:JSON.stringify({error:"No flows found",suggestion:"Create .paradigm/flows.yaml with flow definitions",example:`
18
18
  version: "1.0"
19
19
  flows:
20
20
  $task-creation:
@@ -32,7 +32,7 @@ flows:
32
32
  symbol: "!task-created"
33
33
  description: Emit success event
34
34
  successSignal: "!task-created"
35
- `},null,2)};let a=H.join(s.rootDir,"portal.yaml"),c=[];if(E.existsSync(a))try{let f=E.readFileSync(a,"utf-8"),b=Te.load(f);b?.gates&&(c=Object.keys(b.gates).map(h=>h.startsWith("^")?h.slice(1):h));}catch{}let l=new Set(c),d=[],p=n?[[n,o.flows[n]]]:Object.entries(o.flows);for(let[f,b]of p){if(!b){if(n)return {handled:true,text:JSON.stringify({error:`Flow not found: ${n}`,availableFlows:Object.keys(o.flows)},null,2)};continue}let h={flowId:f,status:"valid",coverage:{gatesReferenced:[],gatesMissing:[],actionsReferenced:[],actionsMissing:[],signalsEmitted:[],signalsMissing:[]},suggestions:[]},w=b.steps||[];for(let v=0;v<w.length;v++){let k=w[v],_=k.symbol||"",x=Ql(_);if(x)switch(k.type){case "gate":h.coverage.gatesReferenced.push(_),l.has(x.name)||(h.coverage.gatesMissing.push(_),h.status="invalid");break;case "action":h.coverage.actionsReferenced.push(_);break;case "signal":h.coverage.signalsEmitted.push(_);break}}b.successSignal&&h.coverage.signalsEmitted.push(b.successSignal),h.coverage.gatesMissing.length>0&&h.suggestions.push(`Add missing gates to portal.yaml: ${h.coverage.gatesMissing.join(", ")}`),h.status==="valid"&&h.coverage.gatesMissing.length===0&&(h.status="valid"),d.push(h);}let u=d.filter(f=>f.status==="valid").length,m=d.filter(f=>f.status==="invalid").length,g={status:m>0?"invalid":"valid",totalFlows:d.length,validFlows:u,invalidFlows:m,results:d.map(f=>({flowId:f.flowId,status:f.status,gatesReferenced:f.coverage.gatesReferenced,gatesMissing:f.coverage.gatesMissing,actionsReferenced:f.coverage.actionsReferenced,signalsEmitted:f.coverage.signalsEmitted,suggestions:f.suggestions}))};return {handled:true,text:JSON.stringify(g,null,2)}}default:return {handled:false,text:""}}}function Ql(t){let e=t.match(/^([#$^!~])(.+)$/);return e?{prefix:e[1],name:e[2]}:null}b$1();var Xl=60*1e3,Jo=new Map;async function Bo(t){let e=H.resolve(t),s=Jo.get(e);if(s&&Date.now()-s.loadedAt<Xl)return s.fixtures;let n=await Zl(e);return n&&Jo.set(e,{fixtures:n,loadedAt:Date.now()}),n}async function Zl(t){let e=H.join(t,".paradigm","fixtures.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch(s){return a.component("#fixtures-loader").error("Error parsing fixtures.yaml",{error:s}),null}}function Is(t,e){switch(e){case "users":return t.users||{};case "resources":return t.resources||{};case "payloads":return t.payloads||{};case "all":return {users:t.users||{},resources:t.resources||{},payloads:t.payloads||{}};default:return null}}function zo(t,e,s){return Is(t,e)?.[s]||null}function $s(t){return {users:Object.keys(t.users||{}),resources:Object.keys(t.resources||{}),payloads:Object.keys(t.payloads||{})}}function Yo(){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 Vo(t,e,s){switch(t){case "paradigm_test_fixtures":{let{category:n,name:i}=e,r=await Bo(s.rootDir);if(!r)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:`
35
+ `},null,2)};let a=H.join(s.rootDir,"portal.yaml"),c=[];if(E.existsSync(a))try{let f=E.readFileSync(a,"utf-8"),b=Ae.load(f);b?.gates&&(c=Object.keys(b.gates).map(h=>h.startsWith("^")?h.slice(1):h));}catch{}let l=new Set(c),d=[],p=n?[[n,o.flows[n]]]:Object.entries(o.flows);for(let[f,b]of p){if(!b){if(n)return {handled:true,text:JSON.stringify({error:`Flow not found: ${n}`,availableFlows:Object.keys(o.flows)},null,2)};continue}let h={flowId:f,status:"valid",coverage:{gatesReferenced:[],gatesMissing:[],actionsReferenced:[],actionsMissing:[],signalsEmitted:[],signalsMissing:[]},suggestions:[]},w=b.steps||[];for(let v=0;v<w.length;v++){let k=w[v],S=k.symbol||"",x=gd(S);if(x)switch(k.type){case "gate":h.coverage.gatesReferenced.push(S),l.has(x.name)||(h.coverage.gatesMissing.push(S),h.status="invalid");break;case "action":h.coverage.actionsReferenced.push(S);break;case "signal":h.coverage.signalsEmitted.push(S);break}}b.successSignal&&h.coverage.signalsEmitted.push(b.successSignal),h.coverage.gatesMissing.length>0&&h.suggestions.push(`Add missing gates to portal.yaml: ${h.coverage.gatesMissing.join(", ")}`),h.status==="valid"&&h.coverage.gatesMissing.length===0&&(h.status="valid"),d.push(h);}let u=d.filter(f=>f.status==="valid").length,g=d.filter(f=>f.status==="invalid").length,m={status:g>0?"invalid":"valid",totalFlows:d.length,validFlows:u,invalidFlows:g,results:d.map(f=>({flowId:f.flowId,status:f.status,gatesReferenced:f.coverage.gatesReferenced,gatesMissing:f.coverage.gatesMissing,actionsReferenced:f.coverage.actionsReferenced,signalsEmitted:f.coverage.signalsEmitted,suggestions:f.suggestions}))};return {handled:true,text:JSON.stringify(m,null,2)}}default:return {handled:false,text:""}}}function gd(t){let e=t.match(/^([#$^!~])(.+)$/);return e?{prefix:e[1],name:e[2]}:null}b$1();var md=60*1e3,Qo=new Map;async function Zo(t){let e=H.resolve(t),s=Qo.get(e);if(s&&Date.now()-s.loadedAt<md)return s.fixtures;let n=await fd(e);return n&&Qo.set(e,{fixtures:n,loadedAt:Date.now()}),n}async function fd(t){let e=H.join(t,".paradigm","fixtures.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Ae.load(s)}catch(s){return a.component("#fixtures-loader").error("Error parsing fixtures.yaml",{error:s}),null}}function Hs(t,e){switch(e){case "users":return t.users||{};case "resources":return t.resources||{};case "payloads":return t.payloads||{};case "all":return {users:t.users||{},resources:t.resources||{},payloads:t.payloads||{}};default:return null}}function ea(t,e,s){return Hs(t,e)?.[s]||null}function qs(t){return {users:Object.keys(t.users||{}),resources:Object.keys(t.resources||{}),payloads:Object.keys(t.payloads||{})}}function ta(){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 na(t,e,s){switch(t){case "paradigm_test_fixtures":{let{category:n,name:i}=e,r=await Zo(s.rootDir);if(!r)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:`
36
36
  version: "1.0"
37
37
 
38
38
  users:
@@ -58,14 +58,14 @@ payloads:
58
58
  createTask:
59
59
  title: "New Task"
60
60
  description: "Task description"
61
- `},null,2)};if(!n){let c=$s(r);return {handled:true,text:JSON.stringify({available:c,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(i&&n!=="all"){let c=zo(r,n,i);if(!c){let d=$s(r);return {handled:true,text:JSON.stringify({error:`Fixture "${i}" not found in category "${n}"`,availableInCategory:d[n]||[]},null,2)}}return {handled:true,text:JSON.stringify(c,null,2)}}let o=Is(r,n);return {handled:true,text:JSON.stringify(o,null,2)}}default:return {handled:false,text:""}}}z();function Rn(t,e,s={}){let{maxResults:n=20}=s,i=[],r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=[`rg -n --no-heading "${r}" "${t}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${r}" "${t}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of o)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return i;let c=a.trim().split(`
62
- `);for(let l of c.slice(0,n)){let d=l.match(/^(.+?):(\d+):(.*)$/);if(d){let[,p,u,m]=d,g=H.relative(t,p),y="unknown";g.includes(".purpose")||g.includes("portal.yaml")?y="purpose":m.includes("//")||m.includes("#")||m.includes("*")?y="comment":y="code",i.push({filePath:g,line:parseInt(u,10),content:m.trim().slice(0,200),context:y});}}return i}function Qo(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["dependencies","impact","blast radius","what would break","dependents","affects"]}]}async function Pn(t,e,s){if(t!=="paradigm_ripple")return {handled:false,text:""};let{symbol:n,depth:i$1=3,includeWorkspace:r=false,response_format:o$1}=e,a=h$1(s.index,n);if(!a){let C=td(s.rootDir,n);return o(C.length,t),{handled:true,text:C}}let c=Math.min(Math.max(i$1||3,1),5),l$1=k(s.index,n),d=new Set([n]),p=new Map;function u(C,S){if(S>=c)return;let R=[];for(let I of C){if(d.has(I))continue;d.add(I);let P=k(s.index,I);for(let D of P)d.has(D.symbol)||R.push(D.symbol);}R.length>0&&(p.set(S+1,R),u(R,S+1));}u(l$1.map(C=>C.symbol),1);let m=new Set;for(let[,C]of p)for(let S of C)S!==n&&!l$1.find(R=>R.symbol===S)&&m.add(S);let g=l(s.index,n),y=l$1.length+m.size,f="low";y>10?f="high":y>3&&(f="medium");let b=await _n(s.rootDir),h=null;if(b){let C=Sn(b,n);C.totalFlows>0&&(C.impactLevel==="high"&&f==="low"?f="medium":C.impactLevel==="high"&&(f="high"),h={totalFlows:C.totalFlows,affectedFlows:C.affectedFlows.map(S=>({flowId:S.flowId,impactLevel:S.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${S.stepAffected.position}, affects ${S.downstreamSteps.length} downstream steps`})),validationSuggestion:C.validationCommands.length>0?`Run: ${C.validationCommands[0]}`:void 0});}let w=new Set([n,...l$1.map(C=>C.symbol),...m]),v=[];try{let C=i(s.index,"gate");for(let S of C)w.has(S.symbol)&&v.push({gate:S.symbol,description:S.description});for(let S of l$1)S.type==="gate"&&!v.find(R=>R.gate===S.symbol)&&v.push({gate:S.symbol,description:S.description});}catch{}let k$1={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:f,analysis:{directlyAffected:l$1.map(C=>({symbol:C.symbol,type:C.type,description:C.description})),indirectlyAffected:Array.from(m),indirectByLevel:Object.fromEntries(p),dependsOn:g.map(C=>({symbol:C.symbol,type:C.type}))},summary:{directCount:l$1.length,indirectCount:m.size,totalAffected:y,dependsOnCount:g.length,levelsAnalyzed:c},recommendation:nd(f)};h&&(k$1.affectedFlows=h),v.length>0&&(k$1.affectedGates=v),k$1.suggestedReviewScope=sd(f,l$1.length,m.size,v.length,h?.totalFlows??0);try{let C=await F(s.rootDir,n);C.length>0&&(k$1.personas_affected=C,C.length>2&&f==="low"&&(k$1.impact="medium"));}catch{}try{let C=X$1(s.rootDir,n);C.length>0&&(k$1.university_content_affected=C.map(S=>({id:S.id,title:S.title,type:S.type,stale:S.stale})));}catch{}if(r&&s.workspace){let C=Co(s.workspace,n);if(C.length>0){k$1.workspaceImpact={siblings:C.map(R=>({project:R.project,references:R.references.map(I=>({symbol:I.symbol,type:I.type,description:I.description}))}))};let S=C.reduce((R,I)=>R+I.references.length,0);S>0&&f==="low"&&(k$1.impact="medium"),S>5&&(k$1.impact="high");}}let _=o$1==="concise"?{symbol:k$1.symbol,impact:k$1.impact,summary:k$1.summary}:k$1,x=JSON.stringify(_,null,2);return o(x.length,t),{handled:true,text:x}}function td(t,e){let s=Rn(t,e,{maxResults:20});if(s.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let n=[...new Set(s.map(o=>o.filePath))],i={};for(let o of s)i[o.context]=(i[o.context]||0)+1;let r="low";return n.length>10||s.length>20?r="high":(n.length>3||s.length>5)&&(r="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:r,analysis:{filesAffected:n.slice(0,10),totalFilesAffected:n.length,totalReferences:s.length,contextBreakdown:i,sampleReferences:s.slice(0,5).map(o=>({file:o.filePath,line:o.line,preview:o.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function nd(t){switch(t){case "high":return "High impact change - review all affected symbols carefully before modifying";case "medium":return "Moderate impact - check direct dependencies for breaking changes";case "low":return "Low impact - safe to modify with standard review"}}function sd(t,e,s,n,i){let r=[];return e>0&&r.push(`Review ${e} direct dependent(s) for breaking changes`),s>0&&r.push(`Scan ${s} indirect dependent(s) for cascading effects`),n>0&&r.push(`Verify ${n} affected gate(s) still enforce correct auth/access`),i>0&&r.push(`Validate ${i} affected flow(s) end-to-end`),t==="high"?r.push("Consider running full test suite before merging"):t==="medium"&&r.push("Run targeted tests for affected components"),r.length===0&&r.push("No downstream dependents detected - safe to proceed"),r}function Xo(){return [{name:"paradigm_protocol_search",description:"Search for protocols matching a task description. Call BEFORE exploring the codebase \u2014 if a matching protocol exists, follow its steps instead of discovering the pattern from scratch. Returns top matches with steps, exemplar, and freshness info. ~200 tokens.",inputSchema:{type:"object",properties:{task:{type:"string",description:'Task description to search for (e.g., "add a new page", "add API route")'},limit:{type:"number",description:"Maximum results (default: 3)"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_get",description:"Get a specific protocol by ID with full details and freshness check. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID (e.g., "P-add-view")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_record",description:"Record a new protocol after completing repeatable work. Captures the steps you followed so future agents can skip exploration. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Protocol name (e.g., "Add a new view")'},description:{type:"string",description:"What this protocol accomplishes"},trigger:{type:"array",items:{type:"string"},description:'Phrases that should match this protocol (e.g., ["add view", "new page"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g., ["ui", "frontend"])'},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols involved (e.g., ["#logs-view"])'},exemplar:{type:"string",description:'Canonical file to study for this pattern (e.g., "ui/src/views/LogsView.tsx")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"],description:"Step action type"},target:{type:"string",description:"File path (supports {Name}/{name} placeholders)"},template_from:{type:"string",description:"File to use as template (for create actions)"},reference:{type:"string",description:"Where in the file to make changes (for modify actions)"},command:{type:"string",description:"Command to execute (for run actions)"},notes:{type:"string",description:"Additional guidance for this step"}},required:["action"]},description:"Ordered steps to follow"},recorded_from:{type:"string",description:'Lore entry ID this protocol was learned from (e.g., "L-2026-03-01-001")'}},required:["name","description","trigger","tags","steps"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_update",description:"Update an existing protocol. Use refresh:true after successfully following a protocol to bump last_verified. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID to update (e.g., "P-add-view")'},refresh:{type:"boolean",description:"Set true to bump last_verified to now (use after successfully following the protocol)"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},trigger:{type:"array",items:{type:"string"},description:"Updated trigger phrases"},tags:{type:"array",items:{type:"string"},description:"Updated tags"},symbols:{type:"array",items:{type:"string"},description:"Updated symbols"},exemplar:{type:"string",description:"Updated exemplar path"},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"]},target:{type:"string"},template_from:{type:"string"},reference:{type:"string"},command:{type:"string"},notes:{type:"string"}},required:["action"]},description:"Updated steps"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_validate",description:"Validate protocol references \u2014 check that referenced files exist, exemplars haven't drifted. Validates all protocols if no ID given. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Protocol ID to validate (omit to validate all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function jn(t,e,s){switch(t){case "paradigm_protocol_search":{let n=e.task,i=e.limit||3,r=await aa$1(s.rootDir,n,i);return r.length===0?{handled:true,text:JSON.stringify({count:0,task:n,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:r.length,task:n,matches:r.map(o=>({id:o.protocol.id,name:o.protocol.name,description:o.protocol.description,score:o.score,status:o.protocol.status,exemplar:o.protocol.exemplar,last_verified:o.protocol.last_verified,steps:o.protocol.steps.map(id)}))},null,2)}}case "paradigm_protocol_get":{let n=e.id,i=await _(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${n}`})};let r=da$1(s.rootDir,i);return {handled:true,text:JSON.stringify({...i,freshness:{status:r.status,issues:r.issues}},null,2)}}case "paradigm_protocol_record":{let n=e.steps||[],i=await ba$1(s.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:n,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:i,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let n=e.id,i=e.refresh,r={};e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),e.trigger!==void 0&&(r.trigger=e.trigger),e.tags!==void 0&&(r.tags=e.tags),e.symbols!==void 0&&(r.symbols=e.symbols),e.exemplar!==void 0&&(r.exemplar=e.exemplar),e.steps!==void 0&&(r.steps=e.steps);let o=await ca$1(s.rootDir,n,r,i===true);return {handled:true,text:JSON.stringify({success:o,id:n,refreshed:i===true,message:o?i?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${n}`})}}case "paradigm_protocol_validate":{let n=e.id;if(n){let a=await _(s.rootDir,n);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${n}`})};let c=da$1(s.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let r=(await Z$1(s.rootDir)).map(a=>{let c=da$1(s.rootDir,a);return {id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified}}),o={total:r.length,current:r.filter(a=>a.status==="current").length,stale:r.filter(a=>a.status==="stale").length,broken:r.filter(a=>a.status==="broken").length};return {handled:true,text:JSON.stringify({protocols:r,health:o},null,2)}}default:return {handled:false,text:""}}}function id(t){let e={action:t.action};return t.target&&(e.target=t.target),t.template_from&&(e.template_from=t.template_from),t.reference&&(e.reference=t.reference),t.command&&(e.command=t.command),t.notes&&(e.notes=t.notes),e}j();var Ct=null,Fs=false;async function Ns(t){if(Ct)Fs||(await Ct.ensureReady(),Fs=true);else {let e=H.join(t,".paradigm","sentinel","sentinel.db");Ct=new f$5(e),await Ct.ensureReady(),Fs=true;}return Ct}async function rd(t,e){return (await Ns(t)).recordPracticeEvent(e)}async function ea(t,e){return (await Ns(t)).getPracticeEvents(e)}async function le(t,e){return (await Ns(t)).getComplianceRate(e)}async function Rt(t,e){let s=["discovery","verification","testing","documentation","collaboration","security"],n=[];for(let i of s){let r=await le(t,{...e,habitCategory:i});r.total>0&&n.push({category:i,...r});}return n}async function ta(t,e,s){let n=[];for(let i of e){let r=await rd(t,{habitId:i.habitId,habitCategory:i.habitCategory,result:i.result,engineer:s.engineer,sessionId:s.sessionId,loreEntryId:s.loreEntryId,taskDescription:s.taskDescription,symbolsTouched:s.symbolsTouched,filesModified:s.filesModified,notes:i.notes});n.push(r);}return n}b$1();function na(t){return {handled:true,text:JSON.stringify({error:t},null,2)}}var Tn={code:"lore_type_decision_removed",message:"lore type 'decision' was removed in v6.0. Use paradigm_decision_record instead. The decision will be stored in .paradigm/decisions/ and a companion lore insight entry (type:'insight' with references.decision_id) will be written automatically so the timeline stays complete. For narrative-only references, use paradigm_lore_record({type:'insight', references:{decision_id}}).",successor_tool:"paradigm_decision_record",doc:"docs/private/plans/v6.0-decisions-locked.md",removed_in:"6.0.0"};function sa(){let t=process.env.PARADIGM_AUTHOR;if(t)return Es(t);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Es(e)}catch{}try{let e=ra.userInfo().username;if(e)return Es(e)}catch{}return "unknown"}function Es(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function oa(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, milestone, retro, insight, etc.). Call after completing significant work. Returns the created entry ID and file path. For decisions, use paradigm_decision_record (a companion lore insight is auto-written). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function Pt(t,e,s){switch(t){case "paradigm_lore_search":{let n={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},i=await a$3(s.rootDir,n);return {handled:true,text:JSON.stringify({count:i.length,filter:Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0)),entries:i.map(ia)},null,2)}}case "paradigm_lore_record":{let{type:n,title:i,summary:r,symbols_touched:o,symbols_created:a$1,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:u,duration_minutes:m,decisions:g,errors_encountered:y,learnings:f,verification:b,tags:h,meta:w,body:v,linked_lore:k,linked_tasks:_,linked_commits:x,confidence:C}=e;if(n==="decision")return a.component("#lore").warn("rejected paradigm_lore_record({type:'decision'}) \u2014 removed in v6.0",{removed_in:Tn.removed_in,successor_tool:Tn.successor_tool}),na(Tn);let S;try{let j=new Date(Date.now()-2592e6).toISOString(),T=await le(s.rootDir,{dateFrom:j});if(T.total>0){let $=(await Rt(s.rootDir,{dateFrom:j})).filter(F=>F.rate<60).map(F=>F.category);S={rate:T.rate,followed:T.followed,skipped:T.skipped,partial:T.partial,weakAreas:$.length>0?$:void 0};}}catch{}let R={id:"",type:n||"agent-session",timestamp:new Date().toISOString(),duration_minutes:m,author:sa(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:i,summary:r,symbols_touched:o,symbols_created:a$1,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:u,decisions:g,errors_encountered:y,learnings:f,verification:b,tags:h,meta:w||void 0,habit_compliance:S,body:v,linked_lore:k,linked_tasks:_,linked_commits:x,confidence:C!=null&&C>=0&&C<=1?C:void 0},I=await d$2(s.rootDir,R);j$1().setLastLoreEntryId(I);try{let j=process.env.PARADIGM_AGENT_ID;if(j&&o&&o.length>0){let{updateExpertiseFromLore:T}=await import('./agent-loader-YKS2PQWO.js');T(s.rootDir,j,{symbols_touched:o,confidence:C!=null&&C>=0&&C<=1?C:void 0});}}catch{}let P=null;try{c&&c.length>=2&&(P=ea$1(s.rootDir,c,l||[]));}catch{}let D;if(e.stream){let j=e.stream,T=j==="auto"?ad(e):j;try{if(T==="work-log"){let{recordWorkLog:O}=await import('./work-log-loader-DL5GZ2BQ.js');O(s.rootDir,{agent:R.agent?.model||"unknown",summary:R.summary,outcome:R.verification?.status==="pass"?"pass":R.verification?.status==="fail"?"fail":"partial",files_modified:R.files_modified,symbols_touched:R.symbols_touched,commit:R.commit,linked_lore:R.id||I}),D="work-log";}else if(T==="journal"&&R.learnings?.length){let{recordJournalEntry:O}=await import('./journal-loader-GLH7XFTK.js');for(let $ of R.learnings)O(R.agent?.model||"unknown",{trigger:"self_reflection",insight:$,project:s.projectName||"unknown",transferable:!1,linked_work_log:R.id||I});D="journal";}else if(T==="decision"&&R.decisions?.length){let{recordDecision:O}=await import('./decision-loader-HELL2AMX.js');for(let $ of R.decisions)O(s.rootDir,{title:$.decision.slice(0,100),decision:$.decision,rationale:$.rationale,participants:[{id:`agent/${R.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:R.symbols_touched,status:"active",linked_lore:R.id||I});D="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:I,type:n,title:i,message:"Lore entry recorded successfully",...D?{stream:D}:{},...P?{protocol_suggestion:P}:{}})}}case "paradigm_lore_timeline":{let n=e.limit||10,i=await c$1(s.rootDir),r=await a$3(s.rootDir,{limit:n}),o={};for(let l of r)for(let d of l.symbols_touched)o[d]=(o[d]||0)+1;let a=Object.entries(o).sort(([,l],[,d])=>d-l).slice(0,10).map(([l,d])=>({symbol:l,count:d})),c={};for(let l of r){let d=l.author;c[d]||(c[d]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c[d].count++,l.agent&&(c[d].hasAgent=true),l.timestamp>c[d].lastActive&&(c[d].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:i||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:r.map(ia),hotSymbols:a,authors:Object.entries(c).map(([l,d])=>({id:l,hasAgent:d.hasAgent,entries:d.count,lastActive:d.lastActive}))},null,2)}}case "paradigm_lore_get":{let n=e.id,i=await b$4(s.rootDir,n);return i?{handled:true,text:JSON.stringify(i,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${n}`})}}case "paradigm_lore_update":{let n=e.id,{id:i,...r}=e,o={};for(let[c,l]of Object.entries(r))l!==void 0&&(o[c]=l);let a=await g$3(s.rootDir,n,o);return {handled:true,text:JSON.stringify({success:a,id:n,message:a?"Lore entry updated":`Lore entry not found: ${n}`})}}case "paradigm_lore_assess":{let n=e.id,i=e.verdict,r=e.notes,o=await b$4(s.rootDir,n);if(!o)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${n}`})};let a={verdict:i,assessed_by:sa(),assessed_at:new Date().toISOString(),notes:r},c=await h$3(s.rootDir,n,a);try{let u=process.env.PARADIGM_AGENT_ID;if(u&&c&&o.symbols_touched?.length){let{updateExpertiseFromAssessment:m}=await import('./agent-loader-YKS2PQWO.js');m(s.rootDir,u,{symbols_touched:o.symbols_touched,verdict:i});}}catch{}let l=i==="correct"?1:i==="partial"?.5:0,d=o.confidence!=null?l-o.confidence:null,p=d!=null?d>.1?"Under-confident (actual outcome better than predicted)":d<-0.1?"Over-confident (actual outcome worse than predicted)":"Well-calibrated":"No confidence recorded \u2014 delta not computed";return {handled:true,text:JSON.stringify({success:c,id:n,verdict:i,confidence:o.confidence??null,delta:d,deltaDescription:p,message:c?`Assessment recorded: ${i}${d!=null?` (delta: ${d>0?"+":""}${d.toFixed(2)})`:""}`:`Failed to assess: ${n}`})}}case "paradigm_lore_calibration":{let n={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},i=await a$3(s.rootDir,n),r=i.filter(v=>v.confidence!=null),o=i.length,a=r.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,p=0;for(let v of i){let k=v.assessment.verdict;c[k]++;let _=k==="correct"?1:k==="partial"?.5:0;l+=_,v.confidence!=null&&(d+=v.confidence,p+=Math.abs(_-v.confidence));}let u=o>0?l/o:0,m=a>0?d/a:null,g=a>0?l/o-d/a:null,y=a>0?1-p/a:null,f=e.groupBy,b;if(f&&o>0){let v=new Map;for(let k of i){let _=[];f==="symbol"?_=k.symbols_touched||[]:f==="tag"?_=k.tags||[]:f==="type"&&(_=[k.type||"agent-session"]);for(let x of _)v.has(x)||v.set(x,[]),v.get(x).push(k);}b=Array.from(v.entries()).map(([k,_])=>{let x=_.filter(P=>P.confidence!=null),C={correct:0,partial:0,incorrect:0},S=0,R=0,I=0;for(let P of _){let D=P.assessment.verdict;C[D]++;let j=D==="correct"?1:D==="partial"?.5:0;S+=j,P.confidence!=null&&(R+=P.confidence,I+=Math.abs(j-P.confidence));}return {key:k,total:_.length,accuracyRate:S/_.length,avgConfidence:x.length>0?R/x.length:null,calibrationScore:x.length>0?1-I/x.length:null,verdictBreakdown:C}}).sort((k,_)=>_.total-k.total);}let h=[],w=o<5?`Low sample size (N=${o}). Stats may not be representative.`:o<15?`Moderate sample (N=${o}). Trends are directional, not conclusive.`:null;return w&&h.push(w),y!=null&&(y>=.9?h.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):y>=.7?h.push("Good calibration \u2014 some room for improvement in confidence estimates."):y>=.5?h.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):h.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),g!=null&&(g>.15?h.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):g<-0.15&&h.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>o*.3&&o>=5&&h.push(`High error rate: ${c.incorrect}/${o} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:o,totalWithConfidence:a,accuracyRate:Math.round(u*1e3)/1e3,avgConfidence:m!=null?Math.round(m*1e3)/1e3:null,avgDelta:g!=null?Math.round(g*1e3)/1e3:null,calibrationScore:y!=null?Math.round(y*1e3)/1e3:null,verdictBreakdown:c,...b?{groups:b}:{},insights:h},null,2)}}case "paradigm_lore_delete":{let n=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let r=await i$1(s.rootDir,n);return {handled:true,text:JSON.stringify({success:r,id:n,message:r?"Lore entry deleted":`Lore entry not found: ${n}`})}}default:return {handled:false,text:""}}}function ad(t){return t.task_ref||t.files_modified||t.commit?"work-log":t.learnings||t.confidence!==void 0?"journal":t.decisions?.some(s=>s.rationale)?"decision":"work-log"}function ia(t){return {id:t.id,type:t.type,title:t.title,summary:t.summary,author:t.author,agent:t.agent,timestamp:t.timestamp,duration_minutes:t.duration_minutes,symbols_touched:t.symbols_touched,verification:t.verification?.status,review:t.review?{completeness:t.review.completeness,quality:t.review.quality}:null,confidence:t.confidence??null,assessment:t.assessment?t.assessment.verdict:null,assessment_delta:t.assessment_delta??null,tags:t.tags}}function ca(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function jt(t,e,s){return t==="paradigm_captain_brief"?cd(e,s):t==="paradigm_captain_debrief"?ld(e,s):{handled:false,text:""}}async function cd(t,e){let s=t.taskDescription,n=t.symbols||[],i=t.depth||"standard",r=H.join(e.rootDir,".paradigm"),o$1=H.join(r,".cid-session"),a=H.join(r,".cid-briefed");try{E.existsSync(a)&&E.unlinkSync(a);let j={timestamp:new Date().toISOString(),taskDescription:s.slice(0,200),depth:i};E.mkdirSync(r,{recursive:!0}),E.writeFileSync(o$1,JSON.stringify(j,null,2),"utf8");}catch{}let c=dd(s),l=[],d=new Set;for(let j of n)if(!d.has(j)){d.add(j);let T=aa(j);l.push({id:j,type:T,description:"Provided as anchor symbol"});}let p=[];try{for(let j of c.slice(0,3)){let O=j$2(e.index,j).slice(0,5);for(let $ of O)if(!d.has($.symbol)){d.add($.symbol);let F=ud($.type);l.push({id:$.symbol,type:F,description:$.description||"",file:$.file}),p.push($.symbol);}}}catch{}let u={directories:[],files:[]};try{let j=await bn("paradigm_navigate",{intent:"context",task:s,response_format:"concise"},e);if(j.handled){let T=JSON.parse(j.text);if(T.files)for(let O of T.files){let $=typeof O=="string"?O:O.path||O.file||"";$&&u.files.push($);}if(T.directories)for(let O of T.directories){let $=typeof O=="string"?O:O.path||O.directory||"";$&&u.directories.push($);}if(T.symbols)for(let O of T.symbols){let $=typeof O=="string"?O:O.id;$&&!d.has($)&&(d.add($),l.push({id:$,type:aa($),description:typeof O=="object"&&O.description||""}));}}}catch{}let m=new Set(u.directories);for(let j of u.files){let T=H.dirname(j);T&&T!=="."&&m.add(T);}let g=l.slice(0,i==="deep"?5:3),y={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(i!=="quick"&&g.length>0)for(let j of g)try{let T=await Pn("paradigm_ripple",{symbol:j.id,depth:2,response_format:"concise"},e);if(T.handled){let O=JSON.parse(T.text);if(O.analysis){for(let $ of O.analysis.directlyAffected||[]){let F=$.symbol||$;F&&!y.affectedSymbols.includes(F)&&y.affectedSymbols.push(F);}for(let $ of O.analysis.indirectlyAffected||[])$&&!y.affectedSymbols.includes($)&&y.affectedSymbols.push($);}if(O.affectedFlows?.affectedFlows)for(let $ of O.affectedFlows.affectedFlows){let F=$.flowId||$;F&&!y.affectedFlows.includes(F)&&y.affectedFlows.push(F);}if(O.affectedGates)for(let $ of O.affectedGates){let F=$.gate||$;F&&!y.affectedGates.includes(F)&&y.affectedGates.push(F);}O.impact==="high"&&(y.fragileSymbols.includes(j.id)||y.fragileSymbols.push(j.id));}}catch{}let f=[],b=pd(s);if(b.length>0)try{let{handleGatesForRoute:j}=await import('./tools-QJHAVYI6.js').catch(()=>({handleGatesForRoute:null})),T=H.join(e.rootDir,"portal.yaml");if(E.existsSync(T)){let O=E.readFileSync(T,"utf8");for(let $ of b){let F=O.includes($);f.push({route:$,gate:"^authenticated",declared:F});}}else for(let O of b)f.push({route:O,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let h=[];if(i!=="quick"&&l.length>0)try{let j=l.slice(0,5).map(O=>O.id),T=await yn("paradigm_wisdom_context",{symbols:j,include_global:!0},e);if(T.handled){let O=JSON.parse(T.text);if(O.antipatterns)for(let $ of O.antipatterns.slice(0,3)){let F=$.pattern||$.description||$.text||String($);F&&!h.includes(F)&&h.push(F);}if(O.wisdom?.antipatterns)for(let $ of O.wisdom.antipatterns.slice(0,3)){let F=$.pattern||$.description||String($);F&&!h.includes(F)&&h.push(F);}}}catch{}let w={matched:false};try{let j=await jn("paradigm_protocol_search",{task:s,limit:1},e);if(j.handled){let T=JSON.parse(j.text),O=T.matches||T.protocols||T.results||[];if(O.length>0){let $=O[0];w={matched:!0,id:$.id,name:$.name||$.title,steps:($.steps||[]).slice(0,5).map(F=>typeof F=="string"?F:F.description||String(F))};}}}catch{}let v=[];if(i!=="quick")try{let j=l[0]?.id,T={limit:i==="deep"?5:3};j&&(T.symbol=j);let O=await Pt("paradigm_lore_search",T,e);if(O.handled){let F=JSON.parse(O.text).entries||[];for(let G of F.slice(0,3))v.push({id:G.id,summary:(G.summary||G.title||"").slice(0,100),relevance:j?`Related to ${j}`:"Recent project history"});}}catch{}let k=Array.from(m),_=0;for(let j of k){let T=H.join(e.rootDir,j,".purpose");if(E.existsSync(T))try{E.readFileSync(T,"utf8").trim().length>50&&_++;}catch{}}let x=k.length>0?_/k.length:.5,C=gd(x),S=md(x,C,k.length),R=y.affectedSymbols.length+u.files.length,I=R>20?"large":R>8?"medium":R>2?"small":"tiny",P={territory:{directories:k.slice(0,10),files:u.files.slice(0,10),estimatedScope:I},symbols:l.slice(0,10),blastRadius:y,gates:f,protocol:w,warnings:h,coverage:{score:x,label:C,note:S},loreRefs:v,renderedBrief:""};P.renderedBrief=fd(P);try{let j={timestamp:new Date().toISOString(),taskDescription:s.slice(0,200),depth:i,coverageScore:x};E.writeFileSync(o$1,JSON.stringify(j,null,2),"utf8");}catch{}let D=JSON.stringify(P,null,2);return o(D.length,"paradigm_captain_brief"),{handled:true,text:D}}async function ld(t,e){let s=t.orchestrationId,n=t.sessionSummary,i=t.touchedFiles||[],r=t.newSymbols||[],o$1=t.notes,a=H.join(e.rootDir,".paradigm"),c=H.join(a,".cid-briefed"),l=H.join(a,".pending-review"),d=new Set;for(let S of i){let R=H.dirname(S);R&&R!=="."&&d.add(R);}let p=0,u=d.size;for(let S of d){let R=H.join(e.rootDir,S,".purpose");if(E.existsSync(R))try{E.readFileSync(R,"utf8").trim().length>50&&p++;}catch{}}let m=u>0?p/u:1,g=[],y=[];for(let S of d){let R=H.join(e.rootDir,S,".purpose"),I=H.join(e.rootDir,S),P=false;if(E.existsSync(R))try{P=E.readFileSync(R,"utf8").trim().length>50;}catch{}if(P){if(i.some(j=>H.dirname(j)===S&&r.length>0)){y.push(S);try{let j=JSON.stringify({path:S,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${s}: ${r.join(", ")}`,timestamp:new Date().toISOString()});E.appendFileSync(l,j+`
63
- `,"utf8");}catch{}}}else try{if(!E.existsSync(I))continue;let D=H.basename(S),j=yd(D,S,i);E.writeFileSync(R,j,"utf8"),g.push(S),y.push(S);try{let T=JSON.stringify({path:S,reason:"captain-debrief",priority:"high",context:`Touched during orchestration ${s}. Files: ${i.filter(O=>H.dirname(O)===S).join(", ")}`,timestamp:new Date().toISOString()});E.appendFileSync(l,T+`
64
- `,"utf8");}catch{}}catch{}}let f=0;for(let S of d){let R=H.join(e.rootDir,S,".purpose");if(E.existsSync(R))try{E.readFileSync(R,"utf8").trim().length>50&&f++;}catch{}}let b=u>0?f/u:1,h="";try{let S=await Pt("paradigm_lore_record",{type:"agent-session",title:`Cid Debrief: ${n.slice(0,80)}`,summary:n,symbols_touched:r,files_modified:i,tags:["arc:cid-debrief",`orch:${s}`],meta:{orchestrationId:s,coverageScore:{before:m,after:b},coverageAdded:g,...o$1?{notes:o$1}:{}}},e);if(S.handled){let R=JSON.parse(S.text);h=R.id||R.entry?.id||"";}}catch{}let w=false;try{let S={timestamp:new Date().toISOString(),sessionId:s,touchedFiles:i,coverageScore:b};E.mkdirSync(a,{recursive:!0}),E.writeFileSync(c,JSON.stringify(S,null,2),"utf8"),w=!0;}catch{}let v={taskDescription:n,orchestrationId:s,agentContributions:[],coverageDelta:{before:m,after:b},newSymbols:r,touchedFiles:i,notes:o$1||""};try{let S=H.join(a,"events","session-log.jsonl");if(E.existsSync(S)){let P=E.readFileSync(S,"utf8").split(`
65
- `).filter(j=>j.trim().length>0).slice(-50),D=new Map;for(let j of P)try{let T=JSON.parse(j),O=T.agentId||T.agent||T.role||"";if(!O)continue;D.has(O)||D.set(O,{contributions:[],symbolsTouched:new Set,patternsObserved:[]});let $=D.get(O),F=T.action||T.event||T.message||"";if(F&&$.contributions.push(String(F).slice(0,120)),Array.isArray(T.symbols))for(let Pe of T.symbols)$.symbolsTouched.add(String(Pe));let G=T.symbol||"";if(G&&$.symbolsTouched.add(G),Array.isArray(T.patterns))for(let Pe of T.patterns)$.patternsObserved.includes(String(Pe))||$.patternsObserved.push(String(Pe));}catch{}for(let[j,T]of D.entries())v.agentContributions.push({agentId:j,contribution:T.contributions.slice(-3).join(" | "),symbolsTouched:Array.from(T.symbolsTouched).slice(0,10),patternsObserved:T.patternsObserved.slice(0,5)});}}catch{}v.agentContributions.length===0&&v.agentContributions.push({agentId:"session",contribution:n.slice(0,200),symbolsTouched:r.slice(0,10),patternsObserved:[]});let k={coverageAdded:g,delegatedToDocumentor:y,loreEntryId:h,coverageScore:{before:m,after:b,delta:b-m},stopHookCleared:w,sessionInsights:v},_=["","\u2501\u2501\u2501 LEARNING HANDOFF (\u2192 Loid) \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501","","Cid has prepared session insights for Loid's learning pass.","Call paradigm_ambient_learn_postflight with the sessionInsights","from this debrief to complete the session.","","sessionInsights available in: debrief.sessionInsights"].join(`
61
+ `},null,2)};if(!n){let c=qs(r);return {handled:true,text:JSON.stringify({available:c,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(i&&n!=="all"){let c=ea(r,n,i);if(!c){let d=qs(r);return {handled:true,text:JSON.stringify({error:`Fixture "${i}" not found in category "${n}"`,availableInCategory:d[n]||[]},null,2)}}return {handled:true,text:JSON.stringify(c,null,2)}}let o=Hs(r,n);return {handled:true,text:JSON.stringify(o,null,2)}}default:return {handled:false,text:""}}}z();function Tn(t,e,s={}){let{maxResults:n=20}=s,i=[],r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=[`rg -n --no-heading "${r}" "${t}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${r}" "${t}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of o)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return i;let c=a.trim().split(`
62
+ `);for(let l of c.slice(0,n)){let d=l.match(/^(.+?):(\d+):(.*)$/);if(d){let[,p,u,g]=d,m=H.relative(t,p),y="unknown";m.includes(".purpose")||m.includes("portal.yaml")?y="purpose":g.includes("//")||g.includes("#")||g.includes("*")?y="comment":y="code",i.push({filePath:m,line:parseInt(u,10),content:g.trim().slice(0,200),context:y});}}return i}function ia(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["dependencies","impact","blast radius","what would break","dependents","affects"]}]}async function An(t,e,s){if(t!=="paradigm_ripple")return {handled:false,text:""};let{symbol:n,depth:i$1=3,includeWorkspace:r=false,response_format:o$1}=e,a=h$1(s.index,n);if(!a){let C=hd(s.rootDir,n);return o(C.length,t),{handled:true,text:C}}let c=Math.min(Math.max(i$1||3,1),5),l$1=k(s.index,n),d=new Set([n]),p=new Map;function u(C,_){if(_>=c)return;let R=[];for(let I of C){if(d.has(I))continue;d.add(I);let P=k(s.index,I);for(let A of P)d.has(A.symbol)||R.push(A.symbol);}R.length>0&&(p.set(_+1,R),u(R,_+1));}u(l$1.map(C=>C.symbol),1);let g=new Set;for(let[,C]of p)for(let _ of C)_!==n&&!l$1.find(R=>R.symbol===_)&&g.add(_);let m=l(s.index,n),y=l$1.length+g.size,f="low";y>10?f="high":y>3&&(f="medium");let b=await Cn(s.rootDir),h=null;if(b){let C=Rn(b,n);C.totalFlows>0&&(C.impactLevel==="high"&&f==="low"?f="medium":C.impactLevel==="high"&&(f="high"),h={totalFlows:C.totalFlows,affectedFlows:C.affectedFlows.map(_=>({flowId:_.flowId,impactLevel:_.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${_.stepAffected.position}, affects ${_.downstreamSteps.length} downstream steps`})),validationSuggestion:C.validationCommands.length>0?`Run: ${C.validationCommands[0]}`:void 0});}let w=new Set([n,...l$1.map(C=>C.symbol),...g]),v=[];try{let C=i(s.index,"gate");for(let _ of C)w.has(_.symbol)&&v.push({gate:_.symbol,description:_.description});for(let _ of l$1)_.type==="gate"&&!v.find(R=>R.gate===_.symbol)&&v.push({gate:_.symbol,description:_.description});}catch{}let k$1={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:f,analysis:{directlyAffected:l$1.map(C=>({symbol:C.symbol,type:C.type,description:C.description})),indirectlyAffected:Array.from(g),indirectByLevel:Object.fromEntries(p),dependsOn:m.map(C=>({symbol:C.symbol,type:C.type}))},summary:{directCount:l$1.length,indirectCount:g.size,totalAffected:y,dependsOnCount:m.length,levelsAnalyzed:c},recommendation:bd(f)};h&&(k$1.affectedFlows=h),v.length>0&&(k$1.affectedGates=v),k$1.suggestedReviewScope=wd(f,l$1.length,g.size,v.length,h?.totalFlows??0);try{let C=await F(s.rootDir,n);C.length>0&&(k$1.personas_affected=C,C.length>2&&f==="low"&&(k$1.impact="medium"));}catch{}try{let C=X$1(s.rootDir,n);C.length>0&&(k$1.university_content_affected=C.map(_=>({id:_.id,title:_.title,type:_.type,stale:_.stale})));}catch{}if(r&&s.workspace){let C=Oo(s.workspace,n);if(C.length>0){k$1.workspaceImpact={siblings:C.map(R=>({project:R.project,references:R.references.map(I=>({symbol:I.symbol,type:I.type,description:I.description}))}))};let _=C.reduce((R,I)=>R+I.references.length,0);_>0&&f==="low"&&(k$1.impact="medium"),_>5&&(k$1.impact="high");}}let S=o$1==="concise"?{symbol:k$1.symbol,impact:k$1.impact,summary:k$1.summary}:k$1,x=JSON.stringify(S,null,2);return o(x.length,t),{handled:true,text:x}}function hd(t,e){let s=Tn(t,e,{maxResults:20});if(s.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let n=[...new Set(s.map(o=>o.filePath))],i={};for(let o of s)i[o.context]=(i[o.context]||0)+1;let r="low";return n.length>10||s.length>20?r="high":(n.length>3||s.length>5)&&(r="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:r,analysis:{filesAffected:n.slice(0,10),totalFilesAffected:n.length,totalReferences:s.length,contextBreakdown:i,sampleReferences:s.slice(0,5).map(o=>({file:o.filePath,line:o.line,preview:o.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function bd(t){switch(t){case "high":return "High impact change - review all affected symbols carefully before modifying";case "medium":return "Moderate impact - check direct dependencies for breaking changes";case "low":return "Low impact - safe to modify with standard review"}}function wd(t,e,s,n,i){let r=[];return e>0&&r.push(`Review ${e} direct dependent(s) for breaking changes`),s>0&&r.push(`Scan ${s} indirect dependent(s) for cascading effects`),n>0&&r.push(`Verify ${n} affected gate(s) still enforce correct auth/access`),i>0&&r.push(`Validate ${i} affected flow(s) end-to-end`),t==="high"?r.push("Consider running full test suite before merging"):t==="medium"&&r.push("Run targeted tests for affected components"),r.length===0&&r.push("No downstream dependents detected - safe to proceed"),r}function ra(){return [{name:"paradigm_protocol_search",description:"Search for protocols matching a task description. Call BEFORE exploring the codebase \u2014 if a matching protocol exists, follow its steps instead of discovering the pattern from scratch. Returns top matches with steps, exemplar, and freshness info. ~200 tokens.",inputSchema:{type:"object",properties:{task:{type:"string",description:'Task description to search for (e.g., "add a new page", "add API route")'},limit:{type:"number",description:"Maximum results (default: 3)"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_get",description:"Get a specific protocol by ID with full details and freshness check. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID (e.g., "P-add-view")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_record",description:"Record a new protocol after completing repeatable work. Captures the steps you followed so future agents can skip exploration. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Protocol name (e.g., "Add a new view")'},description:{type:"string",description:"What this protocol accomplishes"},trigger:{type:"array",items:{type:"string"},description:'Phrases that should match this protocol (e.g., ["add view", "new page"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g., ["ui", "frontend"])'},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols involved (e.g., ["#logs-view"])'},exemplar:{type:"string",description:'Canonical file to study for this pattern (e.g., "ui/src/views/LogsView.tsx")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"],description:"Step action type"},target:{type:"string",description:"File path (supports {Name}/{name} placeholders)"},template_from:{type:"string",description:"File to use as template (for create actions)"},reference:{type:"string",description:"Where in the file to make changes (for modify actions)"},command:{type:"string",description:"Command to execute (for run actions)"},notes:{type:"string",description:"Additional guidance for this step"}},required:["action"]},description:"Ordered steps to follow"},recorded_from:{type:"string",description:'Lore entry ID this protocol was learned from (e.g., "L-2026-03-01-001")'}},required:["name","description","trigger","tags","steps"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_update",description:"Update an existing protocol. Use refresh:true after successfully following a protocol to bump last_verified. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID to update (e.g., "P-add-view")'},refresh:{type:"boolean",description:"Set true to bump last_verified to now (use after successfully following the protocol)"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},trigger:{type:"array",items:{type:"string"},description:"Updated trigger phrases"},tags:{type:"array",items:{type:"string"},description:"Updated tags"},symbols:{type:"array",items:{type:"string"},description:"Updated symbols"},exemplar:{type:"string",description:"Updated exemplar path"},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"]},target:{type:"string"},template_from:{type:"string"},reference:{type:"string"},command:{type:"string"},notes:{type:"string"}},required:["action"]},description:"Updated steps"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_validate",description:"Validate protocol references \u2014 check that referenced files exist, exemplars haven't drifted. Validates all protocols if no ID given. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Protocol ID to validate (omit to validate all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Dn(t,e,s){switch(t){case "paradigm_protocol_search":{let n=e.task,i=e.limit||3,r=await aa$1(s.rootDir,n,i);return r.length===0?{handled:true,text:JSON.stringify({count:0,task:n,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:r.length,task:n,matches:r.map(o=>({id:o.protocol.id,name:o.protocol.name,description:o.protocol.description,score:o.score,status:o.protocol.status,exemplar:o.protocol.exemplar,last_verified:o.protocol.last_verified,steps:o.protocol.steps.map(vd)}))},null,2)}}case "paradigm_protocol_get":{let n=e.id,i=await _(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${n}`})};let r=da$1(s.rootDir,i);return {handled:true,text:JSON.stringify({...i,freshness:{status:r.status,issues:r.issues}},null,2)}}case "paradigm_protocol_record":{let n=e.steps||[],i=await ba(s.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:n,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:i,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let n=e.id,i=e.refresh,r={};e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),e.trigger!==void 0&&(r.trigger=e.trigger),e.tags!==void 0&&(r.tags=e.tags),e.symbols!==void 0&&(r.symbols=e.symbols),e.exemplar!==void 0&&(r.exemplar=e.exemplar),e.steps!==void 0&&(r.steps=e.steps);let o=await ca$1(s.rootDir,n,r,i===true);return {handled:true,text:JSON.stringify({success:o,id:n,refreshed:i===true,message:o?i?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${n}`})}}case "paradigm_protocol_validate":{let n=e.id;if(n){let a=await _(s.rootDir,n);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${n}`})};let c=da$1(s.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let r=(await Z$1(s.rootDir)).map(a=>{let c=da$1(s.rootDir,a);return {id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified}}),o={total:r.length,current:r.filter(a=>a.status==="current").length,stale:r.filter(a=>a.status==="stale").length,broken:r.filter(a=>a.status==="broken").length};return {handled:true,text:JSON.stringify({protocols:r,health:o},null,2)}}default:return {handled:false,text:""}}}function vd(t){let e={action:t.action};return t.target&&(e.target=t.target),t.template_from&&(e.template_from=t.template_from),t.reference&&(e.reference=t.reference),t.command&&(e.command=t.command),t.notes&&(e.notes=t.notes),e}j();var Pt=null,Ls=false;async function Ms(t){if(Pt)Ls||(await Pt.ensureReady(),Ls=true);else {let e=H.join(t,".paradigm","sentinel","sentinel.db");Pt=new f$5(e),await Pt.ensureReady(),Ls=true;}return Pt}async function kd(t,e){return (await Ms(t)).recordPracticeEvent(e)}async function aa(t,e){return (await Ms(t)).getPracticeEvents(e)}async function le(t,e){return (await Ms(t)).getComplianceRate(e)}async function jt(t,e){let s=["discovery","verification","testing","documentation","collaboration","security"],n=[];for(let i of s){let r=await le(t,{...e,habitCategory:i});r.total>0&&n.push({category:i,...r});}return n}async function ca(t,e,s){let n=[];for(let i of e){let r=await kd(t,{habitId:i.habitId,habitCategory:i.habitCategory,result:i.result,engineer:s.engineer,sessionId:s.sessionId,loreEntryId:s.loreEntryId,taskDescription:s.taskDescription,symbolsTouched:s.symbolsTouched,filesModified:s.filesModified,notes:i.notes});n.push(r);}return n}b$1();function la(t){return {handled:true,text:JSON.stringify({error:t},null,2)}}var On={code:"lore_type_decision_removed",message:"lore type 'decision' was removed in v6.0. Use paradigm_decision_record instead. The decision will be stored in .paradigm/decisions/ and a companion lore insight entry (type:'insight' with references.decision_id) will be written automatically so the timeline stays complete. For narrative-only references, use paradigm_lore_record({type:'insight', references:{decision_id}}).",successor_tool:"paradigm_decision_record",doc:"docs/private/plans/v6.0-decisions-locked.md",removed_in:"6.0.0"};function da(){let t=process.env.PARADIGM_AUTHOR;if(t)return Ws(t);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Ws(e)}catch{}try{let e=ua.userInfo().username;if(e)return Ws(e)}catch{}return "unknown"}function Ws(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function ga(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, milestone, retro, insight, etc.). Call after completing significant work. Returns the created entry ID and file path. For decisions, use paradigm_decision_record (a companion lore insight is auto-written). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function Tt(t,e,s){switch(t){case "paradigm_lore_search":{let n={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},i=await a$3(s.rootDir,n);return {handled:true,text:JSON.stringify({count:i.length,filter:Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0)),entries:i.map(pa)},null,2)}}case "paradigm_lore_record":{let{type:n,title:i,summary:r,symbols_touched:o,symbols_created:a$1,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:u,duration_minutes:g,decisions:m,errors_encountered:y,learnings:f,verification:b,tags:h,meta:w,body:v,linked_lore:k,linked_tasks:S,linked_commits:x,confidence:C}=e;if(n==="decision")return a.component("#lore").warn("rejected paradigm_lore_record({type:'decision'}) \u2014 removed in v6.0",{removed_in:On.removed_in,successor_tool:On.successor_tool}),la(On);let _;try{let j=new Date(Date.now()-2592e6).toISOString(),T=await le(s.rootDir,{dateFrom:j});if(T.total>0){let $=(await jt(s.rootDir,{dateFrom:j})).filter(F=>F.rate<60).map(F=>F.category);_={rate:T.rate,followed:T.followed,skipped:T.skipped,partial:T.partial,weakAreas:$.length>0?$:void 0};}}catch{}let R={id:"",type:n||"agent-session",timestamp:new Date().toISOString(),duration_minutes:g,author:da(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:i,summary:r,symbols_touched:o,symbols_created:a$1,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:u,decisions:m,errors_encountered:y,learnings:f,verification:b,tags:h,meta:w||void 0,habit_compliance:_,body:v,linked_lore:k,linked_tasks:S,linked_commits:x,confidence:C!=null&&C>=0&&C<=1?C:void 0},I=await d$2(s.rootDir,R);j$1().setLastLoreEntryId(I);try{let j=process.env.PARADIGM_AGENT_ID;if(j&&o&&o.length>0){let{updateExpertiseFromLore:T}=await import('./agent-loader-W3RQJVW7.js');T(s.rootDir,j,{symbols_touched:o,confidence:C!=null&&C>=0&&C<=1?C:void 0});}}catch{}let P=null;try{c&&c.length>=2&&(P=ea$1(s.rootDir,c,l||[]));}catch{}let A;if(e.stream){let j=e.stream,T=j==="auto"?_d(e):j;try{if(T==="work-log"){let{recordWorkLog:O}=await import('./work-log-loader-DL5GZ2BQ.js');O(s.rootDir,{agent:R.agent?.model||"unknown",summary:R.summary,outcome:R.verification?.status==="pass"?"pass":R.verification?.status==="fail"?"fail":"partial",files_modified:R.files_modified,symbols_touched:R.symbols_touched,commit:R.commit,linked_lore:R.id||I}),A="work-log";}else if(T==="journal"&&R.learnings?.length){let{recordJournalEntry:O}=await import('./journal-loader-GLH7XFTK.js');for(let $ of R.learnings)O(R.agent?.model||"unknown",{trigger:"self_reflection",insight:$,project:s.projectName||"unknown",transferable:!1,linked_work_log:R.id||I});A="journal";}else if(T==="decision"&&R.decisions?.length){let{recordDecision:O}=await import('./decision-loader-HELL2AMX.js');for(let $ of R.decisions)O(s.rootDir,{title:$.decision.slice(0,100),decision:$.decision,rationale:$.rationale,participants:[{id:`agent/${R.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:R.symbols_touched,status:"active",linked_lore:R.id||I});A="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:I,type:n,title:i,message:"Lore entry recorded successfully",...A?{stream:A}:{},...P?{protocol_suggestion:P}:{}})}}case "paradigm_lore_timeline":{let n=e.limit||10,i=await c$1(s.rootDir),r=await a$3(s.rootDir,{limit:n}),o={};for(let l of r)for(let d of l.symbols_touched)o[d]=(o[d]||0)+1;let a=Object.entries(o).sort(([,l],[,d])=>d-l).slice(0,10).map(([l,d])=>({symbol:l,count:d})),c={};for(let l of r){let d=l.author;c[d]||(c[d]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c[d].count++,l.agent&&(c[d].hasAgent=true),l.timestamp>c[d].lastActive&&(c[d].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:i||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:r.map(pa),hotSymbols:a,authors:Object.entries(c).map(([l,d])=>({id:l,hasAgent:d.hasAgent,entries:d.count,lastActive:d.lastActive}))},null,2)}}case "paradigm_lore_get":{let n=e.id,i=await b$4(s.rootDir,n);return i?{handled:true,text:JSON.stringify(i,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${n}`})}}case "paradigm_lore_update":{let n=e.id,{id:i,...r}=e,o={};for(let[c,l]of Object.entries(r))l!==void 0&&(o[c]=l);let a=await g$3(s.rootDir,n,o);return {handled:true,text:JSON.stringify({success:a,id:n,message:a?"Lore entry updated":`Lore entry not found: ${n}`})}}case "paradigm_lore_assess":{let n=e.id,i=e.verdict,r=e.notes,o=await b$4(s.rootDir,n);if(!o)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${n}`})};let a={verdict:i,assessed_by:da(),assessed_at:new Date().toISOString(),notes:r},c=await h$3(s.rootDir,n,a);try{let u=process.env.PARADIGM_AGENT_ID;if(u&&c&&o.symbols_touched?.length){let{updateExpertiseFromAssessment:g}=await import('./agent-loader-W3RQJVW7.js');g(s.rootDir,u,{symbols_touched:o.symbols_touched,verdict:i});}}catch{}let l=i==="correct"?1:i==="partial"?.5:0,d=o.confidence!=null?l-o.confidence:null,p=d!=null?d>.1?"Under-confident (actual outcome better than predicted)":d<-0.1?"Over-confident (actual outcome worse than predicted)":"Well-calibrated":"No confidence recorded \u2014 delta not computed";return {handled:true,text:JSON.stringify({success:c,id:n,verdict:i,confidence:o.confidence??null,delta:d,deltaDescription:p,message:c?`Assessment recorded: ${i}${d!=null?` (delta: ${d>0?"+":""}${d.toFixed(2)})`:""}`:`Failed to assess: ${n}`})}}case "paradigm_lore_calibration":{let n={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},i=await a$3(s.rootDir,n),r=i.filter(v=>v.confidence!=null),o=i.length,a=r.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,p=0;for(let v of i){let k=v.assessment.verdict;c[k]++;let S=k==="correct"?1:k==="partial"?.5:0;l+=S,v.confidence!=null&&(d+=v.confidence,p+=Math.abs(S-v.confidence));}let u=o>0?l/o:0,g=a>0?d/a:null,m=a>0?l/o-d/a:null,y=a>0?1-p/a:null,f=e.groupBy,b;if(f&&o>0){let v=new Map;for(let k of i){let S=[];f==="symbol"?S=k.symbols_touched||[]:f==="tag"?S=k.tags||[]:f==="type"&&(S=[k.type||"agent-session"]);for(let x of S)v.has(x)||v.set(x,[]),v.get(x).push(k);}b=Array.from(v.entries()).map(([k,S])=>{let x=S.filter(P=>P.confidence!=null),C={correct:0,partial:0,incorrect:0},_=0,R=0,I=0;for(let P of S){let A=P.assessment.verdict;C[A]++;let j=A==="correct"?1:A==="partial"?.5:0;_+=j,P.confidence!=null&&(R+=P.confidence,I+=Math.abs(j-P.confidence));}return {key:k,total:S.length,accuracyRate:_/S.length,avgConfidence:x.length>0?R/x.length:null,calibrationScore:x.length>0?1-I/x.length:null,verdictBreakdown:C}}).sort((k,S)=>S.total-k.total);}let h=[],w=o<5?`Low sample size (N=${o}). Stats may not be representative.`:o<15?`Moderate sample (N=${o}). Trends are directional, not conclusive.`:null;return w&&h.push(w),y!=null&&(y>=.9?h.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):y>=.7?h.push("Good calibration \u2014 some room for improvement in confidence estimates."):y>=.5?h.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):h.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),m!=null&&(m>.15?h.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):m<-0.15&&h.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>o*.3&&o>=5&&h.push(`High error rate: ${c.incorrect}/${o} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:o,totalWithConfidence:a,accuracyRate:Math.round(u*1e3)/1e3,avgConfidence:g!=null?Math.round(g*1e3)/1e3:null,avgDelta:m!=null?Math.round(m*1e3)/1e3:null,calibrationScore:y!=null?Math.round(y*1e3)/1e3:null,verdictBreakdown:c,...b?{groups:b}:{},insights:h},null,2)}}case "paradigm_lore_delete":{let n=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let r=await i$1(s.rootDir,n);return {handled:true,text:JSON.stringify({success:r,id:n,message:r?"Lore entry deleted":`Lore entry not found: ${n}`})}}default:return {handled:false,text:""}}}function _d(t){return t.task_ref||t.files_modified||t.commit?"work-log":t.learnings||t.confidence!==void 0?"journal":t.decisions?.some(s=>s.rationale)?"decision":"work-log"}function pa(t){return {id:t.id,type:t.type,title:t.title,summary:t.summary,author:t.author,agent:t.agent,timestamp:t.timestamp,duration_minutes:t.duration_minutes,symbols_touched:t.symbols_touched,verification:t.verification?.status,review:t.review?{completeness:t.review.completeness,quality:t.review.quality}:null,confidence:t.confidence??null,assessment:t.assessment?t.assessment.verdict:null,assessment_delta:t.assessment_delta??null,tags:t.tags}}function fa(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function At(t,e,s){return t==="paradigm_captain_brief"?xd(e,s):t==="paradigm_captain_debrief"?Cd(e,s):{handled:false,text:""}}async function xd(t,e){let s=t.taskDescription,n=t.symbols||[],i=t.depth||"standard",r=H.join(e.rootDir,".paradigm"),o$1=H.join(r,".cid-session"),a=H.join(r,".cid-briefed");try{E.existsSync(a)&&E.unlinkSync(a);let j={timestamp:new Date().toISOString(),taskDescription:s.slice(0,200),depth:i};E.mkdirSync(r,{recursive:!0}),E.writeFileSync(o$1,JSON.stringify(j,null,2),"utf8");}catch{}let c=Rd(s),l=[],d=new Set;for(let j of n)if(!d.has(j)){d.add(j);let T=ma(j);l.push({id:j,type:T,description:"Provided as anchor symbol"});}let p=[];try{for(let j of c.slice(0,3)){let O=j$2(e.index,j).slice(0,5);for(let $ of O)if(!d.has($.symbol)){d.add($.symbol);let F=jd($.type);l.push({id:$.symbol,type:F,description:$.description||"",file:$.file}),p.push($.symbol);}}}catch{}let u={directories:[],files:[]};try{let j=await kn("paradigm_navigate",{intent:"context",task:s,response_format:"concise"},e);if(j.handled){let T=JSON.parse(j.text);if(T.files)for(let O of T.files){let $=typeof O=="string"?O:O.path||O.file||"";$&&u.files.push($);}if(T.directories)for(let O of T.directories){let $=typeof O=="string"?O:O.path||O.directory||"";$&&u.directories.push($);}if(T.symbols)for(let O of T.symbols){let $=typeof O=="string"?O:O.id;$&&!d.has($)&&(d.add($),l.push({id:$,type:ma($),description:typeof O=="object"&&O.description||""}));}}}catch{}let g=new Set(u.directories);for(let j of u.files){let T=H.dirname(j);T&&T!=="."&&g.add(T);}let m=l.slice(0,i==="deep"?5:3),y={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(i!=="quick"&&m.length>0)for(let j of m)try{let T=await An("paradigm_ripple",{symbol:j.id,depth:2,response_format:"concise"},e);if(T.handled){let O=JSON.parse(T.text);if(O.analysis){for(let $ of O.analysis.directlyAffected||[]){let F=$.symbol||$;F&&!y.affectedSymbols.includes(F)&&y.affectedSymbols.push(F);}for(let $ of O.analysis.indirectlyAffected||[])$&&!y.affectedSymbols.includes($)&&y.affectedSymbols.push($);}if(O.affectedFlows?.affectedFlows)for(let $ of O.affectedFlows.affectedFlows){let F=$.flowId||$;F&&!y.affectedFlows.includes(F)&&y.affectedFlows.push(F);}if(O.affectedGates)for(let $ of O.affectedGates){let F=$.gate||$;F&&!y.affectedGates.includes(F)&&y.affectedGates.push(F);}O.impact==="high"&&(y.fragileSymbols.includes(j.id)||y.fragileSymbols.push(j.id));}}catch{}let f=[],b=Pd(s);if(b.length>0)try{let{handleGatesForRoute:j}=await import('./tools-VNDXOFXR.js').catch(()=>({handleGatesForRoute:null})),T=H.join(e.rootDir,"portal.yaml");if(E.existsSync(T)){let O=E.readFileSync(T,"utf8");for(let $ of b){let F=O.includes($);f.push({route:$,gate:"^authenticated",declared:F});}}else for(let O of b)f.push({route:O,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let h=[];if(i!=="quick"&&l.length>0)try{let j=l.slice(0,5).map(O=>O.id),T=await wn("paradigm_wisdom_context",{symbols:j,include_global:!0},e);if(T.handled){let O=JSON.parse(T.text);if(O.antipatterns)for(let $ of O.antipatterns.slice(0,3)){let F=$.pattern||$.description||$.text||String($);F&&!h.includes(F)&&h.push(F);}if(O.wisdom?.antipatterns)for(let $ of O.wisdom.antipatterns.slice(0,3)){let F=$.pattern||$.description||String($);F&&!h.includes(F)&&h.push(F);}}}catch{}let w={matched:false};try{let j=await Dn("paradigm_protocol_search",{task:s,limit:1},e);if(j.handled){let T=JSON.parse(j.text),O=T.matches||T.protocols||T.results||[];if(O.length>0){let $=O[0];w={matched:!0,id:$.id,name:$.name||$.title,steps:($.steps||[]).slice(0,5).map(F=>typeof F=="string"?F:F.description||String(F))};}}}catch{}let v=[];if(i!=="quick")try{let j=l[0]?.id,T={limit:i==="deep"?5:3};j&&(T.symbol=j);let O=await Tt("paradigm_lore_search",T,e);if(O.handled){let F=JSON.parse(O.text).entries||[];for(let G of F.slice(0,3))v.push({id:G.id,summary:(G.summary||G.title||"").slice(0,100),relevance:j?`Related to ${j}`:"Recent project history"});}}catch{}let k=Array.from(g),S=0;for(let j of k){let T=H.join(e.rootDir,j,".purpose");if(E.existsSync(T))try{E.readFileSync(T,"utf8").trim().length>50&&S++;}catch{}}let x=k.length>0?S/k.length:.5,C=Td(x),_=Ad(x,C,k.length),R=y.affectedSymbols.length+u.files.length,I=R>20?"large":R>8?"medium":R>2?"small":"tiny",P={territory:{directories:k.slice(0,10),files:u.files.slice(0,10),estimatedScope:I},symbols:l.slice(0,10),blastRadius:y,gates:f,protocol:w,warnings:h,coverage:{score:x,label:C,note:_},loreRefs:v,renderedBrief:""};P.renderedBrief=Dd(P);try{let j={timestamp:new Date().toISOString(),taskDescription:s.slice(0,200),depth:i,coverageScore:x};E.writeFileSync(o$1,JSON.stringify(j,null,2),"utf8");}catch{}let A=JSON.stringify(P,null,2);return o(A.length,"paradigm_captain_brief"),{handled:true,text:A}}async function Cd(t,e){let s=t.orchestrationId,n=t.sessionSummary,i=t.touchedFiles||[],r=t.newSymbols||[],o$1=t.notes,a=H.join(e.rootDir,".paradigm"),c=H.join(a,".cid-briefed"),l=H.join(a,".pending-review"),d=new Set;for(let _ of i){let R=H.dirname(_);R&&R!=="."&&d.add(R);}let p=0,u=d.size;for(let _ of d){let R=H.join(e.rootDir,_,".purpose");if(E.existsSync(R))try{E.readFileSync(R,"utf8").trim().length>50&&p++;}catch{}}let g=u>0?p/u:1,m=[],y=[];for(let _ of d){let R=H.join(e.rootDir,_,".purpose"),I=H.join(e.rootDir,_),P=false;if(E.existsSync(R))try{P=E.readFileSync(R,"utf8").trim().length>50;}catch{}if(P){if(i.some(j=>H.dirname(j)===_&&r.length>0)){y.push(_);try{let j=JSON.stringify({path:_,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${s}: ${r.join(", ")}`,timestamp:new Date().toISOString()});E.appendFileSync(l,j+`
63
+ `,"utf8");}catch{}}}else try{if(!E.existsSync(I))continue;let A=H.basename(_),j=Od(A,_,i);E.writeFileSync(R,j,"utf8"),m.push(_),y.push(_);try{let T=JSON.stringify({path:_,reason:"captain-debrief",priority:"high",context:`Touched during orchestration ${s}. Files: ${i.filter(O=>H.dirname(O)===_).join(", ")}`,timestamp:new Date().toISOString()});E.appendFileSync(l,T+`
64
+ `,"utf8");}catch{}}catch{}}let f=0;for(let _ of d){let R=H.join(e.rootDir,_,".purpose");if(E.existsSync(R))try{E.readFileSync(R,"utf8").trim().length>50&&f++;}catch{}}let b=u>0?f/u:1,h="";try{let _=await Tt("paradigm_lore_record",{type:"agent-session",title:`Cid Debrief: ${n.slice(0,80)}`,summary:n,symbols_touched:r,files_modified:i,tags:["arc:cid-debrief",`orch:${s}`],meta:{orchestrationId:s,coverageScore:{before:g,after:b},coverageAdded:m,...o$1?{notes:o$1}:{}}},e);if(_.handled){let R=JSON.parse(_.text);h=R.id||R.entry?.id||"";}}catch{}let w=false;try{let _={timestamp:new Date().toISOString(),sessionId:s,touchedFiles:i,coverageScore:b};E.mkdirSync(a,{recursive:!0}),E.writeFileSync(c,JSON.stringify(_,null,2),"utf8"),w=!0;}catch{}let v={taskDescription:n,orchestrationId:s,agentContributions:[],coverageDelta:{before:g,after:b},newSymbols:r,touchedFiles:i,notes:o$1||""};try{let _=H.join(a,"events","session-log.jsonl");if(E.existsSync(_)){let P=E.readFileSync(_,"utf8").split(`
65
+ `).filter(j=>j.trim().length>0).slice(-50),A=new Map;for(let j of P)try{let T=JSON.parse(j),O=T.agentId||T.agent||T.role||"";if(!O)continue;A.has(O)||A.set(O,{contributions:[],symbolsTouched:new Set,patternsObserved:[]});let $=A.get(O),F=T.action||T.event||T.message||"";if(F&&$.contributions.push(String(F).slice(0,120)),Array.isArray(T.symbols))for(let je of T.symbols)$.symbolsTouched.add(String(je));let G=T.symbol||"";if(G&&$.symbolsTouched.add(G),Array.isArray(T.patterns))for(let je of T.patterns)$.patternsObserved.includes(String(je))||$.patternsObserved.push(String(je));}catch{}for(let[j,T]of A.entries())v.agentContributions.push({agentId:j,contribution:T.contributions.slice(-3).join(" | "),symbolsTouched:Array.from(T.symbolsTouched).slice(0,10),patternsObserved:T.patternsObserved.slice(0,5)});}}catch{}v.agentContributions.length===0&&v.agentContributions.push({agentId:"session",contribution:n.slice(0,200),symbolsTouched:r.slice(0,10),patternsObserved:[]});let k={coverageAdded:m,delegatedToDocumentor:y,loreEntryId:h,coverageScore:{before:g,after:b,delta:b-g},stopHookCleared:w,sessionInsights:v},S=["","\u2501\u2501\u2501 LEARNING HANDOFF (\u2192 Loid) \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501","","Cid has prepared session insights for Loid's learning pass.","Call paradigm_ambient_learn_postflight with the sessionInsights","from this debrief to complete the session.","","sessionInsights available in: debrief.sessionInsights"].join(`
66
66
  `),C=JSON.stringify(k,null,2)+`
67
- `+_;return o(C.length,"paradigm_captain_debrief"),{handled:true,text:C}}function dd(t){let e=new Set(["the","a","an","to","of","in","and","or","for","with","that","this","is","it","be","as","at","by","from","add","create","update","fix","implement","make","build","change","modify","new","old","get","set","use","using"]),s=t.match(/[#$^!~@&%?][a-z][a-z0-9-]*/g)||[],n=t.replace(/[#$^!~@&%?]/g," ").split(/[\s\-_\/.,;:'"()\[\]{}!?]+/).map(r=>r.toLowerCase()).filter(r=>r.length>2&&!e.has(r));return [...new Set([...s,...n])].slice(0,6)}function pd(t){let e=[],s=/(?:GET|POST|PUT|PATCH|DELETE)\s+(\/[a-z0-9\-\/:_{}]+)/gi,n;for(;(n=s.exec(t))!==null;)e.push(n[1]);let i=/\/api\/[a-z0-9\-\/:_{}]+/g;for(;(n=i.exec(t))!==null;)e.includes(n[0])||e.push(n[0]);return e}function aa(t){return t.startsWith("#")?"component":t.startsWith("$")?"flow":t.startsWith("^")?"gate":t.startsWith("!")?"signal":t.startsWith("~")?"aspect":"component"}function ud(t){switch(t){case "component":return "component";case "flow":return "flow";case "gate":return "gate";case "signal":return "signal";case "aspect":return "aspect";default:return "component"}}function gd(t){return t>=.85?"comprehensive":t>=.6?"reliable":t>=.3?"partial":"sparse"}function md(t,e,s){let n=Math.round(t*100);switch(e){case "sparse":return `${n}% of ${s} director(ies) covered. Brief may be significantly incomplete. Builder should explore directly.`;case "partial":return `${n}% of ${s} director(ies) covered. Brief covers key symbols. Some areas uncharted.`;case "reliable":return `${n}% of ${s} director(ies) covered. Brief is reliable for this task.`;case "comprehensive":return `${n}% of ${s} director(ies) covered. Area is fully mapped.`}}function fd(t){let e=[],s="\u2501".repeat(52);e.push(`${s}`),e.push("");let n=t.territory.directories.slice(0,3).join(", ")||"(none detected)";e.push(`Territory: ${n}`);let i=t.symbols.slice(0,5).map(d=>d.id).join(", ")||"(none found)";e.push(`Symbols: ${i}`);let r=t.blastRadius.affectedFiles.length+t.territory.files.length,o=t.blastRadius.affectedFlows.length,a=t.blastRadius.affectedGates.length,c=t.blastRadius.fragileSymbols.length>0?` \xB7 \u26A0 ${t.blastRadius.fragileSymbols.slice(0,2).join(", ")} (fragile)`:"";if(e.push(`Blast Radius: ${r} files \xB7 ${o} flows \xB7 ${a} gates${c}`),t.gates.length>0){let d=t.gates.slice(0,2).map(p=>`${p.route} \u2192 ${p.gate} (${p.declared?"declared \u2713":"UNDECLARED \u2717"})`);e.push(`Gates: ${d.join("; ")}`);}if(t.protocol.matched){let d=t.protocol.steps?.length?` (${t.protocol.steps.length} steps)`:"";e.push(`Protocol: ${t.protocol.name||t.protocol.id}${d} \u2014 matched`);}else e.push("Protocol: (none matched)");t.warnings.length>0&&e.push(`Warnings: "${t.warnings[0].slice(0,80)}"`);let l=Math.round(t.coverage.score*100);return e.push(`Coverage: ${l}% \u2014 brief is ${t.coverage.label}`),e.push(""),e.push(`${s}`),e.join(`
68
- `)}function yd(t,e,s){let i=s.filter(r=>H.dirname(r)===e).slice(0,3).map(r=>`# - ${H.basename(r)}`).join(`
67
+ `+S;return o(C.length,"paradigm_captain_debrief"),{handled:true,text:C}}function Rd(t){let e=new Set(["the","a","an","to","of","in","and","or","for","with","that","this","is","it","be","as","at","by","from","add","create","update","fix","implement","make","build","change","modify","new","old","get","set","use","using"]),s=t.match(/[#$^!~@&%?][a-z][a-z0-9-]*/g)||[],n=t.replace(/[#$^!~@&%?]/g," ").split(/[\s\-_\/.,;:'"()\[\]{}!?]+/).map(r=>r.toLowerCase()).filter(r=>r.length>2&&!e.has(r));return [...new Set([...s,...n])].slice(0,6)}function Pd(t){let e=[],s=/(?:GET|POST|PUT|PATCH|DELETE)\s+(\/[a-z0-9\-\/:_{}]+)/gi,n;for(;(n=s.exec(t))!==null;)e.push(n[1]);let i=/\/api\/[a-z0-9\-\/:_{}]+/g;for(;(n=i.exec(t))!==null;)e.includes(n[0])||e.push(n[0]);return e}function ma(t){return t.startsWith("#")?"component":t.startsWith("$")?"flow":t.startsWith("^")?"gate":t.startsWith("!")?"signal":t.startsWith("~")?"aspect":"component"}function jd(t){switch(t){case "component":return "component";case "flow":return "flow";case "gate":return "gate";case "signal":return "signal";case "aspect":return "aspect";default:return "component"}}function Td(t){return t>=.85?"comprehensive":t>=.6?"reliable":t>=.3?"partial":"sparse"}function Ad(t,e,s){let n=Math.round(t*100);switch(e){case "sparse":return `${n}% of ${s} director(ies) covered. Brief may be significantly incomplete. Builder should explore directly.`;case "partial":return `${n}% of ${s} director(ies) covered. Brief covers key symbols. Some areas uncharted.`;case "reliable":return `${n}% of ${s} director(ies) covered. Brief is reliable for this task.`;case "comprehensive":return `${n}% of ${s} director(ies) covered. Area is fully mapped.`}}function Dd(t){let e=[],s="\u2501".repeat(52);e.push(`${s}`),e.push("");let n=t.territory.directories.slice(0,3).join(", ")||"(none detected)";e.push(`Territory: ${n}`);let i=t.symbols.slice(0,5).map(d=>d.id).join(", ")||"(none found)";e.push(`Symbols: ${i}`);let r=t.blastRadius.affectedFiles.length+t.territory.files.length,o=t.blastRadius.affectedFlows.length,a=t.blastRadius.affectedGates.length,c=t.blastRadius.fragileSymbols.length>0?` \xB7 \u26A0 ${t.blastRadius.fragileSymbols.slice(0,2).join(", ")} (fragile)`:"";if(e.push(`Blast Radius: ${r} files \xB7 ${o} flows \xB7 ${a} gates${c}`),t.gates.length>0){let d=t.gates.slice(0,2).map(p=>`${p.route} \u2192 ${p.gate} (${p.declared?"declared \u2713":"UNDECLARED \u2717"})`);e.push(`Gates: ${d.join("; ")}`);}if(t.protocol.matched){let d=t.protocol.steps?.length?` (${t.protocol.steps.length} steps)`:"";e.push(`Protocol: ${t.protocol.name||t.protocol.id}${d} \u2014 matched`);}else e.push("Protocol: (none matched)");t.warnings.length>0&&e.push(`Warnings: "${t.warnings[0].slice(0,80)}"`);let l=Math.round(t.coverage.score*100);return e.push(`Coverage: ${l}% \u2014 brief is ${t.coverage.label}`),e.push(""),e.push(`${s}`),e.join(`
68
+ `)}function Od(t,e,s){let i=s.filter(r=>H.dirname(r)===e).slice(0,3).map(r=>`# - ${H.basename(r)}`).join(`
69
69
  `);return `# Auto-generated .purpose stub \u2014 created by Cid (captain debrief)
70
70
  # Delegate to Scribe (Documentor) for rich documentation
71
71
  name: ${t}
@@ -78,7 +78,7 @@ components:
78
78
  ${t}:
79
79
  description: "TODO: describe this component"
80
80
  tags: []
81
- `}var hd=/[@#$%^!?&~][a-zA-Z0-9_-]+/g;var Tt={architect:"tier-1",ftux:"tier-1",security:"tier-1",advocate:"tier-1",product:"tier-1",operations:"tier-1",sales:"tier-1",legal:"tier-1",ethicist:"tier-1",futurist:"tier-1",compliance:"tier-2",reviewer:"tier-2",designer:"tier-2",copywriter:"tier-2",researcher:"tier-2",analyst:"tier-2",dx:"tier-2",qa:"tier-2",debugger:"tier-2",performance:"tier-2",creative:"tier-2",pm:"tier-2",narrator:"tier-2",e2e:"tier-2",educator:"tier-2",community:"tier-2","content-intel":"tier-2",ai:"tier-2",mediator:"tier-2",presenter:"tier-2",mentor:"tier-2",trainer:"tier-2",a11y:"tier-2",seo:"tier-2",builder:"tier-3",tester:"tier-3",documentor:"tier-3",sysadmin:"tier-3",archivist:"tier-3",release:"tier-3",devops:"tier-3",dba:"tier-3",dataeng:"tier-3",integrator:"tier-3",network:"tier-3",streaming:"tier-3",mobile:"tier-3",gamedev:"tier-3","3d":"tier-3",i18n:"tier-3",translator:"tier-3",forge:"tier-3",secretary:"tier-3",reverser:"tier-3",audio:"tier-3",finance:"tier-3"},Dn={"tier-1":"opus","tier-2":"sonnet","tier-3":"haiku"};function ua(t,e,s){try{let i=H.join(e,".paradigm","config.yaml");if(E.existsSync(i)){let o=Te.load(E.readFileSync(i,"utf8"))?.["model-resolution"];if(o){let a=s?.modelTier||Tt[t]||"tier-2";if(o[a])return o[a]}}}catch{}if(s?.defaultModel)return s.defaultModel;let n=Tt[t]||"tier-2";return Dn[n]||"sonnet"}var bd={architect:{min:5e3,max:2e4},ftux:{min:4e3,max:18e3},security:{min:3e3,max:15e3},reviewer:{min:2e3,max:1e4},builder:{min:1e4,max:5e4},tester:{min:5e3,max:2e4}},Dt={architect:`You are the ARCHITECT agent.
81
+ `}var Id=/[@#$%^!?&~][a-zA-Z0-9_-]+/g;var Dt={architect:"tier-1",ftux:"tier-1",scholar:"tier-1",security:"tier-1",advocate:"tier-1",product:"tier-1",operations:"tier-1",sales:"tier-1",legal:"tier-1",ethicist:"tier-1",futurist:"tier-1",compliance:"tier-2",reviewer:"tier-2",designer:"tier-2",copywriter:"tier-2",researcher:"tier-2",analyst:"tier-2",dx:"tier-2",qa:"tier-2",debugger:"tier-2",performance:"tier-2",creative:"tier-2",pm:"tier-2",narrator:"tier-2",e2e:"tier-2",educator:"tier-2",community:"tier-2","content-intel":"tier-2",ai:"tier-2",mediator:"tier-2",presenter:"tier-2",mentor:"tier-2",trainer:"tier-2",a11y:"tier-2",seo:"tier-2",swift:"tier-2",builder:"tier-3",tester:"tier-3",documentor:"tier-3",sysadmin:"tier-3",archivist:"tier-3",release:"tier-3",devops:"tier-3",dba:"tier-3",dataeng:"tier-3",integrator:"tier-3",network:"tier-3",streaming:"tier-3",mobile:"tier-3",gamedev:"tier-3","3d":"tier-3",i18n:"tier-3",translator:"tier-3",forge:"tier-3",secretary:"tier-3",reverser:"tier-3",audio:"tier-3",finance:"tier-3"},In={"tier-1":"opus","tier-2":"sonnet","tier-3":"haiku"};function wa(t,e,s){try{let i=H.join(e,".paradigm","config.yaml");if(E.existsSync(i)){let o=Ae.load(E.readFileSync(i,"utf8"))?.["model-resolution"];if(o){let a=s?.modelTier||Dt[t]||"tier-2";if(o[a])return o[a]}}}catch{}if(s?.defaultModel)return s.defaultModel;let n=Dt[t]||"tier-2";return In[n]||"sonnet"}var $d={architect:{min:5e3,max:2e4},ftux:{min:4e3,max:18e3},security:{min:3e3,max:15e3},reviewer:{min:2e3,max:1e4},builder:{min:1e4,max:5e4},tester:{min:5e3,max:2e4}},Ot={architect:`You are the ARCHITECT agent.
82
82
 
83
83
  ## Your Role
84
84
  You design system architecture, write specifications, and plan features.
@@ -320,7 +320,91 @@ Severity: critical | high | medium | low
320
320
  - After Builder completes work that touches a user-visible surface
321
321
  - When triggered by keywords: ftux, onboarding, "new user", "public ready", release
322
322
  - Before Documentor, so gaps can be fixed before .purpose files are updated
323
- - On demand for any feature when the team needs a first-time user perspective`,compliance:`You are the COMPLIANCE agent (Rune).
323
+ - On demand for any feature when the team needs a first-time user perspective`,scholar:`You are SCHOLAR, the RESEARCH & CURATION agent.
324
+
325
+ ## Your Role
326
+ You research, synthesize, and curate written knowledge across the project: University packs, docs/guides/**, README, CHANGELOG context, and external reference material. You are paired with SHEILA (educator) as a research-pair: you produce the source material; she shapes it into learning experiences.
327
+ You do NOT write source code, .purpose files, or portal.yaml. You produce prose, outlines, citations, and curated indexes.
328
+
329
+ ## Key Responsibilities
330
+ 1. Research topics across the codebase, docs, lore, and external sources before writing
331
+ 2. Curate and refresh University content packs (packages/university/**, project-tenant packs)
332
+ 3. Maintain docs/guides/** accuracy against current behavior (cross-check with code, but never edit code)
333
+ 4. Audit README and top-level marketing/docs surfaces for staleness vs. shipped reality
334
+ 5. Produce structured research briefs that Sheila can convert into lessons/PLSAT items
335
+ 6. Track citations and source-of-truth \u2014 every claim links to a file, commit, or external URL
336
+
337
+ ## Pair Protocol with Sheila (educator)
338
+ - Scholar OWNS: research briefs, curated reference material, fact-checking, source citations, CHANGELOG/lore digestion
339
+ - Sheila OWNS: lesson structure, learning objectives, PLSAT question authoring, pedagogical sequencing
340
+ - Handoff direction: Scholar \u2192 Sheila (research brief \u2192 lesson). Sheila may request follow-up research; Scholar replies with a citation pack, not a finished lesson.
341
+ - Shared notebooks: yes (read-write) \u2014 research patterns + content-gap signals compound across both agents
342
+
343
+ ## Methodology
344
+ 1. Scope the question \u2014 restate what's being researched and why (single sentence)
345
+ 2. Survey existing material \u2014 read .paradigm/lore, CHANGELOG, relevant docs/guides, related packs
346
+ 3. Cross-reference reality \u2014 confirm claims against current code via read-only inspection
347
+ 4. Cite everything \u2014 every assertion gets a path:line or URL
348
+ 5. Hand off \u2014 produce a research brief with: topic, summary, key facts (cited), open questions, suggested learning angles for Sheila
349
+
350
+ ## What You Produce
351
+ - Research briefs (markdown, in .paradigm/research/ or inline handoff)
352
+ - Curated University content (packages/university/** content files \u2014 prose only)
353
+ - docs/guides/** updates (prose accuracy, not structure overhauls)
354
+ - README content suggestions (handed to Documentor for any structural change)
355
+ - Citation packs for Sheila
356
+
357
+ ## Forbidden Actions
358
+ - Writing source code (.ts, .js, .swift, .rs, .py)
359
+ - Editing .purpose files or portal.yaml (Documentor's domain)
360
+ - Authoring PLSAT questions or lesson structures (Sheila's domain)
361
+ - Making claims without a path:line or URL citation
362
+ - Updating CHANGELOG entries (release process owns that)
363
+ - Refactoring docs structure unilaterally \u2014 propose to Documentor`,swift:`You are SWIFT, the SWIFT-LANGUAGE ECOSYSTEM agent.
364
+
365
+ ## Your Role
366
+ You bring deep Swift/SwiftUI/Apple-platform expertise to any project that contains Swift code. You operate as an ecosystem specialist alongside macro-role agents (architect, builder, reviewer) \u2014 they own role; you own language idiom and platform reality.
367
+ You auto-roster when paradigm shift detects *.swift files or a Package.swift / *.xcodeproj.
368
+
369
+ ## Ecosystem Expertise
370
+ What you know that a generic Builder doesn't:
371
+ - Swift 6 strict concurrency: actor isolation, @MainActor placement on protocols, Sendable, region-based isolation
372
+ - SwiftUI lifecycle: @Observable vs ObservableObject, @State/@Binding/@Environment scoping, view-identity bugs
373
+ - Apple platform APIs: AppKit/UIKit interop, AX (Accessibility), AVFoundation, Vision, Metal
374
+ - Swift Package Manager: target graphs, conditional dependencies, resource bundling, plugin targets
375
+ - Build/codesign reality: entitlements, sandbox rules, notarization, .app bundle layout
376
+ - Native concurrency idioms: structured concurrency, AsyncSequence, TaskGroup, cancellation propagation
377
+ - Conductor codebase patterns specifically \u2014 packages/conductor/ is the canonical Swift surface in this monorepo
378
+
379
+ ## Notebook Compounding (cross-project)
380
+ Your notebook accumulates patterns that recur across every Swift project you visit:
381
+ - Concurrency pitfalls observed and their fixes (actor reentrancy, MainActor escape hatches)
382
+ - SwiftUI re-render traps (identity instability, @Observable migration gotchas)
383
+ - SPM target-graph patterns that work / fail
384
+ - Apple SDK quirks per OS version
385
+ - Test patterns: XCTest vs swift-testing migration notes
386
+ Notebooks live globally (~/.paradigm/notebooks/swift/) and compound per-ecosystem, not per-project.
387
+
388
+ ## Methodology
389
+ 1. Detect Swift surface \u2014 confirm files, target type (app/library/CLI/plugin), platform, Swift version
390
+ 2. Apply ecosystem lens \u2014 review the architect's plan or builder's draft for language-idiom violations
391
+ 3. Annotate with Swift-specific guidance \u2014 concurrency, lifecycle, platform-API choice
392
+ 4. Hand back to macro role \u2014 Swift advises; Builder writes the code unless explicitly assigned
393
+
394
+ ## What You Produce
395
+ - Swift-idiom annotations on specs and PRs
396
+ - Concurrency-correctness review notes
397
+ - SPM/Xcode build configuration guidance
398
+ - Platform-API recommendations with version constraints
399
+ - Code (when explicitly assigned as builder for a Swift task)
400
+
401
+ ## Forbidden Actions
402
+ - Editing non-Swift source (TypeScript, Python, Rust) \u2014 hand to the appropriate ecosystem or builder
403
+ - Making cross-package architectural decisions without Architect involvement
404
+ - Editing .purpose / portal.yaml (Documentor)
405
+ - Suggesting Objective-C bridges when a pure-Swift path exists, unless platform requires it
406
+ - Approving code that compiles under Swift 5 mode if project is Swift 6 strict-concurrency
407
+ - Skipping the platform-version check before recommending an API`,compliance:`You are the COMPLIANCE agent (Rune).
324
408
 
325
409
  ## Your Role
326
410
  You plan symbols before implementation and validate coverage after.
@@ -381,7 +465,7 @@ to break plans before code breaks in production.
381
465
  - Write implementation code
382
466
  - Block progress without justification \u2014 you challenge, not obstruct
383
467
  - Repeat concerns already addressed in the task description
384
- - Produce lengthy analysis \u2014 be sharp and concise`};function ga(){return [{name:"paradigm_orchestrate_inline",description:`REQUIRED before implementing features. Start with mode="quick" for fast pre-check, or mode="plan" for full orchestration planning.
468
+ - Produce lengthy analysis \u2014 be sharp and concise`};function va(){return [{name:"paradigm_orchestrate_inline",description:`REQUIRED before implementing features. Start with mode="quick" for fast pre-check, or mode="plan" for full orchestration planning.
385
469
 
386
470
  Plans and coordinates multi-agent task execution within the same session.
387
471
  - mode: "quick" - Lightweight pre-implementation check (~3-4k tokens). Jinx (advocate) stress-tests assumptions, reviewer checks feasibility. Returns greenlight or escalates to full orchestration. Satisfies enforcement.
@@ -404,13 +488,13 @@ Examples:
404
488
  - "Fix the login bug" \u2192 quick (greenlight or escalate)
405
489
  - "Add user authentication with JWT" \u2192 plan \u2192 architect + security + builder + tester
406
490
  - "Should I use soft delete or hard delete?" \u2192 plan \u2192 architect only (analysis)
407
- - "Refactor the payment module" \u2192 plan \u2192 architect + builder`,inputSchema:{type:"object",properties:{task:{type:"string",description:'The task to orchestrate (e.g., "Build @payment-system with Stripe integration")'},mode:{type:"string",enum:["quick","plan","execute"],description:'Mode: "quick" for lightweight pre-check (advocate + reviewer), "plan" returns suggested agents and plan, "execute" returns prompts ready for Task tool'},agents:{type:"array",items:{type:"string"},description:'Optional: Override which agents to use (e.g., ["architect", "builder"])'}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["plan","coordinate","team","multi-agent","orchestrate","agents","spawn agents"]},{name:"paradigm_agent_prompt",description:"Get the complete prompt for a specific agent to execute a task. Use this when you need to spawn an agent via the Task tool with full context.",inputSchema:{type:"object",properties:{agent:{type:"string",enum:["advocate","architect","builder","compliance","ftux","tester","reviewer","security","documentor"],description:"The agent role to get prompt for"},task:{type:"string",description:"The specific task for this agent"},handoffContext:{type:"string",description:"Optional: Context passed from a previous agent"},previousAgent:{type:"string",description:"Optional: Name of the agent that handed off"}},required:["agent","task"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ma(t,e,s){return t==="paradigm_orchestrate_inline"?wd(e,s):t==="paradigm_agent_prompt"?kd(e,s):{handled:false,text:""}}async function wd(t,e){let s=t.task,n=t.mode||"execute",i=t.agents;try{let h=H.join(e.rootDir,".paradigm",".orchestrated");E.writeFileSync(h,new Date().toISOString(),"utf8");}catch{}let r=ha(e.rootDir);if(!r){let h=JSON.stringify({error:"No agents.yaml found",suggestion:"Run `paradigm team init` to set up multi-agent orchestration"},null,2);return o(h.length,"paradigm_orchestrate_inline"),{handled:true,text:h}}let o$1=b$8(e.rootDir);if(o$1&&r.agents){let h={};for(let[w,v]of Object.entries(r.agents))o$1.includes(w)&&(h[w]=v);r.agents=h;}let a=Ot(s),c=[];try{let{processPendingEvents:h,loadNominations:w}=await import('./nomination-engine-QPZJH6XO.js');h(e.rootDir),c=w(e.rootDir,{pending_only:!0,limit:10}).filter(k=>k.urgency==="high"||k.urgency==="critical").map(k=>({agent:k.agent,urgency:k.urgency,brief:k.brief}));}catch{}let l=Dd(s);if(n==="quick")return vd(s,a,l,c,r,e);let d=Sd(s,r.agents,i,l,r.orchestration);if(n==="plan"){let h=Od(s,r.agents),w=Ad(d,l),v;try{let{loadNotebookEntries:S}=await import('./notebook-loader-3J2OFMS3.js'),R=a.map(D=>D.replace(/^[#$^!~@&%?]/,"").toLowerCase()),I={},P=new Set;for(let D of d.stages)for(let j of D.agents){if(P.has(j.name))continue;P.add(j.name);let T=S(j.name,e.rootDir),O=R.length>0?S(j.name,e.rootDir,{concepts:R}):T;T.length>0&&(I[j.name]={totalEntries:T.length,relevantEntries:O.length});}Object.keys(I).length>0&&(v=I);}catch{}let k=d.stages.flatMap(S=>S.agents.map(R=>R.name)),_=fa(k,r.agents),x=_.length>0?{edges:_,note:"Shows which agents hand off to which based on agents.yaml handoff_to. Stage ordering was derived from this graph."}:void 0,C=JSON.stringify({task:s,mode:"plan",classification:{type:l.type,complexity:l.complexity,securityRequired:l.securityRequired,costMultiplier:l.costMultiplier},plan:d,suggestedAgents:h,costPreview:w,...x?{collaborationGraph:x}:{},...v?{notebookKnowledge:v,notebookNote:"Agents with relevant notebook entries will have curated knowledge injected into their prompts during execute mode."}:{},...c.length>0?{activeNominations:c,nominationNote:`${c.length} high-urgency agent nomination(s) pending. These agents have been flagged by the system for attention on this project.`}:{},instructions:["Review task classification and cost preview above","Review suggested agents based on task triggers",...x?["Review collaboration graph \u2014 stage ordering was derived from agent handoff_to edges"]:[],...v?["Review notebook knowledge \u2014 agents with relevant entries will receive curated snippets in execute mode"]:[],...c.length>0?["Review active nominations \u2014 agents flagged by the system may need to be included"]:[],'Call again with mode="execute" to get full prompts and execution strategy',"Stages marked canRunParallel: true can be launched simultaneously","After each agent completes, pass handoff context to the next stage"]},null,2);return o(C.length,"paradigm_orchestrate_inline"),{handled:true,text:C}}let p=new Map;try{let{loadAgentProfile:h,buildProfileEnrichment:w}=await import('./agent-loader-YKS2PQWO.js'),{loadDecisions:v}=await import('./decision-loader-HELL2AMX.js'),{loadJournalEntries:k}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:_}=await import('./nomination-engine-QPZJH6XO.js'),{loadAgentState:x}=await import('./agent-state-KSQ3S7OB.js'),{loadNotebookEntries:C}=await import('./notebook-loader-3J2OFMS3.js'),S=v(e.rootDir,{status:"active",limit:5}).map(P=>({title:P.title,decision:P.decision.slice(0,150)})),R=_(e.rootDir,{pending_only:!0,limit:10}).map(P=>({urgency:P.urgency,brief:P.brief})),I=a.map(P=>P.replace(/^[#$^!~@&%?]/,"").toLowerCase());for(let P of d.stages)for(let D of P.agents)if(!p.has(D.name)){let j=h(e.rootDir,D.name);if(j){if(!c$5(D.name,e.rootDir))continue;let T=k(D.name,{transferable:!0,limit:5}).map(G=>({trigger:G.trigger,insight:G.insight.slice(0,150)})),O=x(D.name,e.rootDir),$;try{let G=C(D.name,e.rootDir,I.length>0?{concepts:I}:void 0);if(G.length>0){let Pe=G.sort((me,Ve)=>Ve.confidence-me.confidence||new Date(Ve.updated).getTime()-new Date(me.updated).getTime()).slice(0,5);$=Pe.map(me=>({context:me.context,snippet:me.snippet,concepts:me.concepts}));try{let{recordNotebookReference:me}=await import('./session-work-log-EE4UIZ33.js');me(e.rootDir,D.name,Pe.map(Ve=>Ve.id));}catch{}try{let{incrementApplied:me}=await import('./notebook-loader-3J2OFMS3.js');for(let Ve of Pe)me(D.name,Ve.id,e.rootDir);}catch{}}}catch{}let F=w(j,a,$,{recentDecisions:S,journalInsights:T,pendingNominations:R},O?{lastSession:O.lastSession,pendingWork:O.pendingWork,recentPatterns:O.recentPatterns,sessionsOnProject:O.sessionsOnProject}:void 0);if(j.permissions){let G=[`
491
+ - "Refactor the payment module" \u2192 plan \u2192 architect + builder`,inputSchema:{type:"object",properties:{task:{type:"string",description:'The task to orchestrate (e.g., "Build @payment-system with Stripe integration")'},mode:{type:"string",enum:["quick","plan","execute"],description:'Mode: "quick" for lightweight pre-check (advocate + reviewer), "plan" returns suggested agents and plan, "execute" returns prompts ready for Task tool'},agents:{type:"array",items:{type:"string"},description:'Optional: Override which agents to use (e.g., ["architect", "builder"])'}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["plan","coordinate","team","multi-agent","orchestrate","agents","spawn agents"]},{name:"paradigm_agent_prompt",description:"Get the complete prompt for a specific agent to execute a task. Use this when you need to spawn an agent via the Task tool with full context.",inputSchema:{type:"object",properties:{agent:{type:"string",enum:["advocate","architect","builder","compliance","ftux","scholar","swift","tester","reviewer","security","documentor"],description:"The agent role to get prompt for"},task:{type:"string",description:"The specific task for this agent"},handoffContext:{type:"string",description:"Optional: Context passed from a previous agent"},previousAgent:{type:"string",description:"Optional: Name of the agent that handed off"}},required:["agent","task"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ka(t,e,s){return t==="paradigm_orchestrate_inline"?Fd(e,s):t==="paradigm_agent_prompt"?Ed(e,s):{handled:false,text:""}}async function Fd(t,e){let s=t.task,n=t.mode||"execute",i=t.agents;try{let h=H.join(e.rootDir,".paradigm",".orchestrated");E.writeFileSync(h,new Date().toISOString(),"utf8");}catch{}let r=xa(e.rootDir);if(!r){let h=JSON.stringify({error:"No agents.yaml found",suggestion:"Run `paradigm team init` to set up multi-agent orchestration"},null,2);return o(h.length,"paradigm_orchestrate_inline"),{handled:true,text:h}}let o$1=b$8(e.rootDir);if(o$1&&r.agents){let h={};for(let[w,v]of Object.entries(r.agents))o$1.includes(w)&&(h[w]=v);r.agents=h;}let a=$t(s),c=[];try{let{processPendingEvents:h,loadNominations:w}=await import('./nomination-engine-NCLTGMAK.js');h(e.rootDir),c=w(e.rootDir,{pending_only:!0,limit:10}).filter(k=>k.urgency==="high"||k.urgency==="critical").map(k=>({agent:k.agent,urgency:k.urgency,brief:k.brief}));}catch{}let l=Bd(s);if(n==="quick")return Nd(s,a,l,c,r,e);let d=qd(s,r.agents,i,l,r.orchestration);if(n==="plan"){let h=Yd(s,r.agents),w=zd(d,l),v;try{let{loadNotebookEntries:_}=await import('./notebook-loader-3J2OFMS3.js'),R=a.map(A=>A.replace(/^[#$^!~@&%?]/,"").toLowerCase()),I={},P=new Set;for(let A of d.stages)for(let j of A.agents){if(P.has(j.name))continue;P.add(j.name);let T=_(j.name,e.rootDir),O=R.length>0?_(j.name,e.rootDir,{concepts:R}):T;T.length>0&&(I[j.name]={totalEntries:T.length,relevantEntries:O.length});}Object.keys(I).length>0&&(v=I);}catch{}let k=d.stages.flatMap(_=>_.agents.map(R=>R.name)),S=Sa(k,r.agents),x=S.length>0?{edges:S,note:"Shows which agents hand off to which based on agents.yaml handoff_to. Stage ordering was derived from this graph."}:void 0,C=JSON.stringify({task:s,mode:"plan",classification:{type:l.type,complexity:l.complexity,securityRequired:l.securityRequired,costMultiplier:l.costMultiplier},plan:d,suggestedAgents:h,costPreview:w,...x?{collaborationGraph:x}:{},...v?{notebookKnowledge:v,notebookNote:"Agents with relevant notebook entries will have curated knowledge injected into their prompts during execute mode."}:{},...c.length>0?{activeNominations:c,nominationNote:`${c.length} high-urgency agent nomination(s) pending. These agents have been flagged by the system for attention on this project.`}:{},instructions:["Review task classification and cost preview above","Review suggested agents based on task triggers",...x?["Review collaboration graph \u2014 stage ordering was derived from agent handoff_to edges"]:[],...v?["Review notebook knowledge \u2014 agents with relevant entries will receive curated snippets in execute mode"]:[],...c.length>0?["Review active nominations \u2014 agents flagged by the system may need to be included"]:[],'Call again with mode="execute" to get full prompts and execution strategy',"Stages marked canRunParallel: true can be launched simultaneously","After each agent completes, pass handoff context to the next stage"]},null,2);return o(C.length,"paradigm_orchestrate_inline"),{handled:true,text:C}}let p=new Map;try{let{loadAgentProfile:h,buildProfileEnrichment:w}=await import('./agent-loader-W3RQJVW7.js'),{loadDecisions:v}=await import('./decision-loader-HELL2AMX.js'),{loadJournalEntries:k}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:S}=await import('./nomination-engine-NCLTGMAK.js'),{loadAgentState:x}=await import('./agent-state-KSQ3S7OB.js'),{loadNotebookEntries:C}=await import('./notebook-loader-3J2OFMS3.js'),_=v(e.rootDir,{status:"active",limit:5}).map(P=>({title:P.title,decision:P.decision.slice(0,150)})),R=S(e.rootDir,{pending_only:!0,limit:10}).map(P=>({urgency:P.urgency,brief:P.brief})),I=a.map(P=>P.replace(/^[#$^!~@&%?]/,"").toLowerCase());for(let P of d.stages)for(let A of P.agents)if(!p.has(A.name)){let j=h(e.rootDir,A.name);if(j){if(!c$5(A.name,e.rootDir))continue;let T=k(A.name,{transferable:!0,limit:5}).map(G=>({trigger:G.trigger,insight:G.insight.slice(0,150)})),O=x(A.name,e.rootDir),$;try{let G=C(A.name,e.rootDir,I.length>0?{concepts:I}:void 0);if(G.length>0){let je=G.sort((me,Ke)=>Ke.confidence-me.confidence||new Date(Ke.updated).getTime()-new Date(me.updated).getTime()).slice(0,5);$=je.map(me=>({context:me.context,snippet:me.snippet,concepts:me.concepts}));try{let{recordNotebookReference:me}=await import('./session-work-log-MEJ33TYD.js');me(e.rootDir,A.name,je.map(Ke=>Ke.id));}catch{}try{let{incrementApplied:me}=await import('./notebook-loader-3J2OFMS3.js');for(let Ke of je)me(A.name,Ke.id,e.rootDir);}catch{}}}catch{}let F=w(j,a,$,{recentDecisions:_,journalInsights:T,pendingNominations:R},O?{lastSession:O.lastSession,pendingWork:O.pendingWork,recentPatterns:O.recentPatterns,sessionsOnProject:O.sessionsOnProject}:void 0);if(j.permissions){let G=[`
408
492
  ## Permission Constraints`];j.permissions.paths?.deny?.length&&G.push(`**Denied paths:** ${j.permissions.paths.deny.join(", ")}`),j.permissions.paths?.write?.length&&G.push(`**Writable paths:** ${j.permissions.paths.write.join(", ")}`),j.permissions.tools?.deny?.length&&G.push(`**Denied tools:** ${j.permissions.tools.deny.join(", ")}`),j.permissions.dangerous_actions?.length&&G.push(`**Requires approval for:** ${j.permissions.dangerous_actions.join(", ")}`),F+=`
409
493
  `+G.join(`
410
- `);}F.trim()&&p.set(D.name,{enrichment:F,nickname:j.nickname});}}}catch{}let u;try{let h=await jt("paradigm_captain_brief",{taskDescription:s,symbols:a,depth:"standard"},e);h.handled&&(u=JSON.parse(h.text).renderedBrief);}catch{}let m=[];for(let h of d.stages){let w=[];for(let v of h.agents){let k=r.agents[v.name],_={name:k?.name||v.name,role:k?.role||Dt[v.name]||`${v.name} agent`,focus:k?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:ua(v.name,e.rootDir,k),triggers:k?.triggers,handoff_to:k?.handoff_to,context:k?.context,protocol:k?.protocol},x=p.get(v.name),C=ya({agent:_,task:v.task,symbols:a,dependsOn:v.dependsOn,profileEnrichment:x?.enrichment,nickname:x?.nickname,captainBrief:u});w.push(C);}m.push({stage:h.stage,canRunParallel:h.canRunParallel,agents:w});}let g=`orch-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`;Id(e.rootDir,g,s,d);try{let{appendSessionWorkEntry:h}=await import('./session-work-log-EE4UIZ33.js');for(let w of m)for(let v of w.agents)h(e.rootDir,{timestamp:new Date().toISOString(),type:"agent-contribution",agent:v.agent,contribution:v.taskDescription?.slice(0,200)||s.slice(0,200),attribution:v.attribution,symbols:a});}catch{}try{let{recordAgentSession:h}=await import('./agent-state-KSQ3S7OB.js'),v=(await import('./session-tracker-KGORN6B5.js')).default?.session?.sessionId||g;for(let k of m)for(let _ of k.agents)h(_.agent,e.rootDir,{sessionId:v,summary:`${_.attribution||_.agent}: ${(_.taskDescription||s).slice(0,200)}`,symbolsTouched:a});}catch{}let y=`thr-orch-${g}`;try{let h=await import('./symphony-loader-VA4UREOM.js'),w=H.basename(e.rootDir),v=`${w}/maestro`;try{h.getMyIdentity(e.rootDir)||h.registerAgent(e.rootDir,"maestro","Maestro (orchestrator)");}catch{}h.createThread(`Orchestration: ${s.slice(0,80)}`,{id:v,name:"Maestro",type:"agent",project:w,role:"orchestrator"});let k=H.join(ra.homedir(),".paradigm","score","threads"),_=E.readdirSync(k).filter(C=>C.endsWith(".json")).sort(),x=_[_.length-1];if(x){let C=H.join(k,x),S=H.join(k,`${y}.json`),R=JSON.parse(E.readFileSync(C,"utf8"));R.id=y,E.writeFileSync(S,JSON.stringify(R,null,2),"utf8"),C!==S&&E.unlinkSync(C);}for(let C of m)for(let S of C.agents){let R=h.buildMessage({threadRoot:y,sender:{id:v,name:"Maestro",type:"agent",project:w,role:"orchestrator"},intent:"task",text:`[Maestro] Stage ${C.stage}: Assigned to ${S.attribution||S.agent} \u2014 ${S.taskDescription||s}`,symbols:a,metadata:{task:{stage:C.stage,canRunParallel:C.canRunParallel}}});h.routeMessage(R);}}catch{}let f={orchestrationId:g,task:s,mode:"execute",symbols:a,totalAgents:d.estimatedAgents,...c.length>0?{activeNominations:c}:{},stages:m,executionInstructions:["Execute stages in order (stage 0, then stage 1, etc.)","Agents within a stage can be run in parallel if your environment supports it","Pass handoff context between stages",'Present each agent response as an attributed message using the attribution prefix (e.g., "[architect] Rate limiter should go before ^authenticated")',"Do NOT synthesize agent responses \u2014 show them as distinct contributions from each agent","After all agents in a stage complete, reconcile their outputs before proceeding to the next stage"],finalStep:{mandatory:true,description:"FINAL STEPS (mandatory, in order):",steps:[{order:1,action:"Call paradigm_captain_debrief",args:{orchestrationId:`${g} (use the orchestrationId from this response)`,sessionSummary:"(summarize what was accomplished)",touchedFiles:"(list all files modified during this session)",newSymbols:"(optional: list any new symbols registered)"}},{order:2,action:"Take the sessionInsights from the debrief result and call paradigm_ambient_learn_postflight",args:{sessionId:`${g} (use the orchestrationId from this response)`,context:"(pass the sessionInsights object from the debrief result here)"},note:"This is Loid's learning pass \u2014 she processes what the crew learned and ensures it compounds."},{order:3,action:"Session is complete."}],note:"Step 1 closes the session, updates .purpose coverage, records lore, and clears the stop hook. Step 2 runs Loid's learning pass on the session insights. Both steps are required \u2014 the session is NOT complete until both run."},claudeCode:{method:"Task tool",example:{description:m[0]?.agents[0]?.taskDescription||"Agent task",prompt:"(see agent prompts above)",subagent_type:"general-purpose"},parallel:"Launch multiple Task calls in one message for parallel stages"},sequential:{method:"Execute each role in sequence within this session",steps:d.stages.map((h,w)=>({stage:w,rolePrompt:`Adopt the ${h.agents[0]?.name} role. Focus ONLY on: ${h.agents.map(v=>v.task).join(", ")}`,constraint:w===0?"Design/plan only \u2014 do NOT write implementation code":w===d.stages.length-1?"Verify and test \u2014 do NOT change implementation":"Implement following the design from the previous stage"}))},cli:{method:"paradigm team orchestrate",command:`paradigm team orchestrate "${s}"`,note:"Spawns independent agent processes \u2014 works from any terminal"},symphony:{enabled:true,orchestrationThread:y,instructions:["After each agent completes, call paradigm_symphony_send to report progress. This makes the work visible in Conductor.",'Use intent "context" for analysis, "proposal" for recommendations, "decision" for decisions made',`Set threadRoot to "${y}" so all contributions are in one thread`,"Include the symbols array from the agent relay output"],perAgentInstruction:`When each agent finishes, run: paradigm_symphony_send threadId="${y}" intent="task-complete" text="[agentName] Summary of completed work" symbols=[touched symbols]`,exampleCall:{intent:"context",text:"[architect] Rate limiter should be placed before ^authenticated gate to prevent unauthenticated flood",threadRoot:y,symbols:["#rate-limiter","^authenticated"]}}},b=JSON.stringify(f,null,2);return o(b.length,"paradigm_orchestrate_inline"),{handled:true,text:b}}async function vd(t,e,s,n,i,r){let o$1=t.toLowerCase(),a;try{let b=await jt("paradigm_captain_brief",{taskDescription:t,symbols:e,depth:"quick"},r);if(b.handled){let h=JSON.parse(b.text);a={coverage:`${h.coverage?.label||"unknown"} (${Math.round((h.coverage?.score||0)*100)}%)`,warnings:h.warnings||[]};}}catch{}let c=[];s.securityRequired&&c.push("security-adjacent task (auth, gates, permissions detected)"),s.complexity==="high"&&c.push(`high complexity task (type: ${s.type})`),e.length>=4&&c.push(`${e.length} symbols in scope \u2014 cross-cutting change`);let l=n.filter(b=>b.urgency==="critical");l.length>0&&c.push(`${l.length} critical agent nomination(s) pending`);let d={assumptions:[],risks:[],edgeCases:[],questions:[]};(o$1.includes("simple")||o$1.includes("just")||o$1.includes("only"))&&d.assumptions.push("Task framed as simple \u2014 verify no hidden complexity"),(o$1.includes("always")||o$1.includes("never"))&&d.assumptions.push("Absolute language detected \u2014 edge cases likely exist"),!o$1.includes("error")&&!o$1.includes("fail")&&!o$1.includes("invalid")&&d.assumptions.push("No error/failure handling mentioned \u2014 what happens when it fails?"),e.some(b=>b.startsWith("$"))&&d.risks.push("Flow symbols detected \u2014 multi-step changes have ordering/rollback risk"),e.some(b=>b.startsWith("^"))&&(d.risks.push("Gate symbols detected \u2014 authorization changes require security review"),c.some(b=>b.includes("security"))||c.push("gate symbols in scope \u2014 security review recommended")),s.matchedKeywords.some(b=>["migration","database","schema"].includes(b))&&d.risks.push("Data migration risk \u2014 irreversible changes need rollback plan"),s.matchedKeywords.some(b=>["delete","remove","drop"].includes(b))&&d.risks.push("Destructive operation \u2014 verify nothing depends on removed items"),(o$1.includes("add")||o$1.includes("new"))&&d.edgeCases.push("New feature \u2014 how does it interact with existing features?"),(o$1.includes("refactor")||o$1.includes("rename"))&&d.edgeCases.push("Refactor \u2014 all callers updated? Integration tests cover the change?"),(o$1.includes("fix")||o$1.includes("bug"))&&d.edgeCases.push("Bug fix \u2014 does the fix address the root cause or just the symptom?"),o$1.includes("test")||d.questions.push("How will this be tested?"),e.length===0&&d.questions.push("No symbols referenced \u2014 which components are actually affected?");let p={concerns:[],suggestions:[]};for(let b of e){let h=b.replace(/^[#$^!~@&%?]/,"");!i.agents[h]&&b.startsWith("#");}s.costMultiplier.max>1&&p.concerns.push(`Higher-than-average complexity (${s.costMultiplier.min}x-${s.costMultiplier.max}x baseline) \u2014 consider breaking into smaller tasks`);let u=[];try{let{loadNotebookEntries:b}=await import('./notebook-loader-3J2OFMS3.js'),h=e.map(v=>v.replace(/^[#$^!~@&%?]/,"").toLowerCase()),w=b("advocate",r.rootDir,h.length>0?{concepts:h}:void 0);w.length>0&&(u=w.sort((v,k)=>k.confidence-v.confidence).slice(0,3).map(v=>v.snippet));}catch{}let g=c.length>=2||c.some(b=>b.includes("security")||b.includes("critical"))?"escalate":"greenlight",y={mode:"quick",task:t,verdict:g,classification:{type:s.type,complexity:s.complexity,securityRequired:s.securityRequired},advocate:{agent:"Jinx (advocate)",...d.assumptions.length>0?{assumptions:d.assumptions}:{},...d.risks.length>0?{risks:d.risks}:{},...d.edgeCases.length>0?{edgeCases:d.edgeCases}:{},...d.questions.length>0?{questions:d.questions}:{},...u.length>0?{notebookInsights:u}:{}},reviewer:{agent:"reviewer",...p.concerns.length>0?{concerns:p.concerns}:{},...p.suggestions.length>0?{suggestions:p.suggestions}:{}},...c.length>0?{escalationSignals:c}:{},...n.length>0?{activeNominations:n}:{},...a?{captainBrief:a}:{},symbols:e,instructions:g==="greenlight"?["Quick check passed \u2014 proceed with implementation.","Orchestration enforcement is satisfied.",d.questions.length>0?`Address Jinx's questions during implementation: ${d.questions.join("; ")}`:"No open questions from advocate."]:["Quick check recommends full orchestration.",`Escalation reasons: ${c.join("; ")}`,'Call paradigm_orchestrate_inline mode="plan" for full agent planning.',"Orchestration enforcement is satisfied regardless of verdict."]},f=JSON.stringify(y,null,2);return o(f.length,"paradigm_orchestrate_inline"),{handled:true,text:f}}async function kd(t,e){let s=t.agent,n=t.task,i=t.handoffContext,r=t.previousAgent,o$1=ha(e.rootDir),a=b$8(e.rootDir);if(a&&!a.includes(s)){let f=JSON.stringify({warning:`Agent "${s}" is not on this project's roster`,suggestion:`Run paradigm_agent_activate id="${s}" to add it, or check .paradigm/roster.yaml`,activeRoster:a},null,2);return o(f.length,"paradigm_agent_prompt"),{handled:true,text:f}}let c=o$1?.agents[s],l={name:c?.name||s,role:c?.role||Dt[s]||Dt.builder,focus:c?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:ua(s,e.rootDir,c),triggers:c?.triggers,handoff_to:c?.handoff_to,context:c?.context,protocol:c?.protocol},d=Ot(n),p,u;try{let{loadAgentProfile:f,buildProfileEnrichment:b}=await import('./agent-loader-YKS2PQWO.js'),{loadDecisions:h}=await import('./decision-loader-HELL2AMX.js'),{loadJournalEntries:w}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:v}=await import('./nomination-engine-QPZJH6XO.js'),{loadNotebookEntries:k}=await import('./notebook-loader-3J2OFMS3.js'),_=f(e.rootDir,s);if(_){u=_.nickname;let x=h(e.rootDir,{status:"active",limit:5}).map(P=>({title:P.title,decision:P.decision.slice(0,150)})),C=w(s,{transferable:!0,limit:5}).map(P=>({trigger:P.trigger,insight:P.insight.slice(0,150)})),S=v(e.rootDir,{pending_only:!0,limit:10}).map(P=>({urgency:P.urgency,brief:P.brief})),R;try{let P=d.map(j=>j.replace(/^[#$^!~@&%?]/,"").toLowerCase()),D=k(s,e.rootDir,P.length>0?{concepts:P}:void 0);if(D.length>0){let j=D.sort((T,O)=>O.confidence-T.confidence||new Date(O.updated).getTime()-new Date(T.updated).getTime()).slice(0,5);R=j.map(T=>({context:T.context,snippet:T.snippet,concepts:T.concepts}));try{let{recordNotebookReference:T}=await import('./session-work-log-EE4UIZ33.js');T(e.rootDir,s,j.map(O=>O.id));}catch{}}}catch{}let I=b(_,d,R,{recentDecisions:x,journalInsights:C,pendingNominations:S});if(_.permissions){let P=[`
411
- ## Permission Constraints`];_.permissions.paths?.deny?.length&&P.push(`**Denied paths:** ${_.permissions.paths.deny.join(", ")}`),_.permissions.paths?.write?.length&&P.push(`**Writable paths:** ${_.permissions.paths.write.join(", ")}`),_.permissions.tools?.deny?.length&&P.push(`**Denied tools:** ${_.permissions.tools.deny.join(", ")}`),_.permissions.dangerous_actions?.length&&P.push(`**Requires approval for:** ${_.permissions.dangerous_actions.join(", ")}`),I+=`
494
+ `);}F.trim()&&p.set(A.name,{enrichment:F,nickname:j.nickname});}}}catch{}let u;try{let h=await At("paradigm_captain_brief",{taskDescription:s,symbols:a,depth:"standard"},e);h.handled&&(u=JSON.parse(h.text).renderedBrief);}catch{}let g=[];for(let h of d.stages){let w=[];for(let v of h.agents){let k=r.agents[v.name],S={name:k?.name||v.name,role:k?.role||Ot[v.name]||`${v.name} agent`,focus:k?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:wa(v.name,e.rootDir,k),triggers:k?.triggers,handoff_to:k?.handoff_to,context:k?.context,protocol:k?.protocol},x=p.get(v.name),C=_a({agent:S,task:v.task,symbols:a,dependsOn:v.dependsOn,profileEnrichment:x?.enrichment,nickname:x?.nickname,captainBrief:u});w.push(C);}g.push({stage:h.stage,canRunParallel:h.canRunParallel,agents:w});}let m=`orch-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`;Vd(e.rootDir,m,s,d);try{let{appendSessionWorkEntry:h}=await import('./session-work-log-MEJ33TYD.js');for(let w of g)for(let v of w.agents)h(e.rootDir,{timestamp:new Date().toISOString(),type:"agent-contribution",agent:v.agent,contribution:v.taskDescription?.slice(0,200)||s.slice(0,200),attribution:v.attribution,symbols:a});}catch{}try{let{recordAgentSession:h}=await import('./agent-state-KSQ3S7OB.js'),v=(await import('./session-tracker-HHNY6J4I.js')).default?.session?.sessionId||m;for(let k of g)for(let S of k.agents)h(S.agent,e.rootDir,{sessionId:v,summary:`${S.attribution||S.agent}: ${(S.taskDescription||s).slice(0,200)}`,symbolsTouched:a});}catch{}let y=`thr-orch-${m}`;try{let h=await import('./symphony-loader-VA4UREOM.js'),w=H.basename(e.rootDir),v=`${w}/maestro`;try{h.getMyIdentity(e.rootDir)||h.registerAgent(e.rootDir,"maestro","Maestro (orchestrator)");}catch{}h.createThread(`Orchestration: ${s.slice(0,80)}`,{id:v,name:"Maestro",type:"agent",project:w,role:"orchestrator"});let k=H.join(ua.homedir(),".paradigm","score","threads"),S=E.readdirSync(k).filter(C=>C.endsWith(".json")).sort(),x=S[S.length-1];if(x){let C=H.join(k,x),_=H.join(k,`${y}.json`),R=JSON.parse(E.readFileSync(C,"utf8"));R.id=y,E.writeFileSync(_,JSON.stringify(R,null,2),"utf8"),C!==_&&E.unlinkSync(C);}for(let C of g)for(let _ of C.agents){let R=h.buildMessage({threadRoot:y,sender:{id:v,name:"Maestro",type:"agent",project:w,role:"orchestrator"},intent:"task",text:`[Maestro] Stage ${C.stage}: Assigned to ${_.attribution||_.agent} \u2014 ${_.taskDescription||s}`,symbols:a,metadata:{task:{stage:C.stage,canRunParallel:C.canRunParallel}}});h.routeMessage(R);}}catch{}let f={orchestrationId:m,task:s,mode:"execute",symbols:a,totalAgents:d.estimatedAgents,...c.length>0?{activeNominations:c}:{},stages:g,executionInstructions:["Execute stages in order (stage 0, then stage 1, etc.)","Agents within a stage can be run in parallel if your environment supports it","Pass handoff context between stages",'Present each agent response as an attributed message using the attribution prefix (e.g., "[architect] Rate limiter should go before ^authenticated")',"Do NOT synthesize agent responses \u2014 show them as distinct contributions from each agent","After all agents in a stage complete, reconcile their outputs before proceeding to the next stage"],finalStep:{mandatory:true,description:"FINAL STEPS (mandatory, in order):",steps:[{order:1,action:"Call paradigm_captain_debrief",args:{orchestrationId:`${m} (use the orchestrationId from this response)`,sessionSummary:"(summarize what was accomplished)",touchedFiles:"(list all files modified during this session)",newSymbols:"(optional: list any new symbols registered)"}},{order:2,action:"Take the sessionInsights from the debrief result and call paradigm_ambient_learn_postflight",args:{sessionId:`${m} (use the orchestrationId from this response)`,context:"(pass the sessionInsights object from the debrief result here)"},note:"This is Loid's learning pass \u2014 she processes what the crew learned and ensures it compounds."},{order:3,action:"Session is complete."}],note:"Step 1 closes the session, updates .purpose coverage, records lore, and clears the stop hook. Step 2 runs Loid's learning pass on the session insights. Both steps are required \u2014 the session is NOT complete until both run."},claudeCode:{method:"Task tool",example:{description:g[0]?.agents[0]?.taskDescription||"Agent task",prompt:"(see agent prompts above)",subagent_type:"general-purpose"},parallel:"Launch multiple Task calls in one message for parallel stages"},sequential:{method:"Execute each role in sequence within this session",steps:d.stages.map((h,w)=>({stage:w,rolePrompt:`Adopt the ${h.agents[0]?.name} role. Focus ONLY on: ${h.agents.map(v=>v.task).join(", ")}`,constraint:w===0?"Design/plan only \u2014 do NOT write implementation code":w===d.stages.length-1?"Verify and test \u2014 do NOT change implementation":"Implement following the design from the previous stage"}))},cli:{method:"paradigm team orchestrate",command:`paradigm team orchestrate "${s}"`,note:"Spawns independent agent processes \u2014 works from any terminal"},symphony:{enabled:true,orchestrationThread:y,instructions:["After each agent completes, call paradigm_symphony_send to report progress. This makes the work visible in Conductor.",'Use intent "context" for analysis, "proposal" for recommendations, "decision" for decisions made',`Set threadRoot to "${y}" so all contributions are in one thread`,"Include the symbols array from the agent relay output"],perAgentInstruction:`When each agent finishes, run: paradigm_symphony_send threadId="${y}" intent="task-complete" text="[agentName] Summary of completed work" symbols=[touched symbols]`,exampleCall:{intent:"context",text:"[architect] Rate limiter should be placed before ^authenticated gate to prevent unauthenticated flood",threadRoot:y,symbols:["#rate-limiter","^authenticated"]}}},b=JSON.stringify(f,null,2);return o(b.length,"paradigm_orchestrate_inline"),{handled:true,text:b}}async function Nd(t,e,s,n,i,r){let o$1=t.toLowerCase(),a;try{let b=await At("paradigm_captain_brief",{taskDescription:t,symbols:e,depth:"quick"},r);if(b.handled){let h=JSON.parse(b.text);a={coverage:`${h.coverage?.label||"unknown"} (${Math.round((h.coverage?.score||0)*100)}%)`,warnings:h.warnings||[]};}}catch{}let c=[];s.securityRequired&&c.push("security-adjacent task (auth, gates, permissions detected)"),s.complexity==="high"&&c.push(`high complexity task (type: ${s.type})`),e.length>=4&&c.push(`${e.length} symbols in scope \u2014 cross-cutting change`);let l=n.filter(b=>b.urgency==="critical");l.length>0&&c.push(`${l.length} critical agent nomination(s) pending`);let d={assumptions:[],risks:[],edgeCases:[],questions:[]};(o$1.includes("simple")||o$1.includes("just")||o$1.includes("only"))&&d.assumptions.push("Task framed as simple \u2014 verify no hidden complexity"),(o$1.includes("always")||o$1.includes("never"))&&d.assumptions.push("Absolute language detected \u2014 edge cases likely exist"),!o$1.includes("error")&&!o$1.includes("fail")&&!o$1.includes("invalid")&&d.assumptions.push("No error/failure handling mentioned \u2014 what happens when it fails?"),e.some(b=>b.startsWith("$"))&&d.risks.push("Flow symbols detected \u2014 multi-step changes have ordering/rollback risk"),e.some(b=>b.startsWith("^"))&&(d.risks.push("Gate symbols detected \u2014 authorization changes require security review"),c.some(b=>b.includes("security"))||c.push("gate symbols in scope \u2014 security review recommended")),s.matchedKeywords.some(b=>["migration","database","schema"].includes(b))&&d.risks.push("Data migration risk \u2014 irreversible changes need rollback plan"),s.matchedKeywords.some(b=>["delete","remove","drop"].includes(b))&&d.risks.push("Destructive operation \u2014 verify nothing depends on removed items"),(o$1.includes("add")||o$1.includes("new"))&&d.edgeCases.push("New feature \u2014 how does it interact with existing features?"),(o$1.includes("refactor")||o$1.includes("rename"))&&d.edgeCases.push("Refactor \u2014 all callers updated? Integration tests cover the change?"),(o$1.includes("fix")||o$1.includes("bug"))&&d.edgeCases.push("Bug fix \u2014 does the fix address the root cause or just the symptom?"),o$1.includes("test")||d.questions.push("How will this be tested?"),e.length===0&&d.questions.push("No symbols referenced \u2014 which components are actually affected?");let p={concerns:[],suggestions:[]};for(let b of e){let h=b.replace(/^[#$^!~@&%?]/,"");!i.agents[h]&&b.startsWith("#");}s.costMultiplier.max>1&&p.concerns.push(`Higher-than-average complexity (${s.costMultiplier.min}x-${s.costMultiplier.max}x baseline) \u2014 consider breaking into smaller tasks`);let u=[];try{let{loadNotebookEntries:b}=await import('./notebook-loader-3J2OFMS3.js'),h=e.map(v=>v.replace(/^[#$^!~@&%?]/,"").toLowerCase()),w=b("advocate",r.rootDir,h.length>0?{concepts:h}:void 0);w.length>0&&(u=w.sort((v,k)=>k.confidence-v.confidence).slice(0,3).map(v=>v.snippet));}catch{}let m=c.length>=2||c.some(b=>b.includes("security")||b.includes("critical"))?"escalate":"greenlight",y={mode:"quick",task:t,verdict:m,classification:{type:s.type,complexity:s.complexity,securityRequired:s.securityRequired},advocate:{agent:"Jinx (advocate)",...d.assumptions.length>0?{assumptions:d.assumptions}:{},...d.risks.length>0?{risks:d.risks}:{},...d.edgeCases.length>0?{edgeCases:d.edgeCases}:{},...d.questions.length>0?{questions:d.questions}:{},...u.length>0?{notebookInsights:u}:{}},reviewer:{agent:"reviewer",...p.concerns.length>0?{concerns:p.concerns}:{},...p.suggestions.length>0?{suggestions:p.suggestions}:{}},...c.length>0?{escalationSignals:c}:{},...n.length>0?{activeNominations:n}:{},...a?{captainBrief:a}:{},symbols:e,instructions:m==="greenlight"?["Quick check passed \u2014 proceed with implementation.","Orchestration enforcement is satisfied.",d.questions.length>0?`Address Jinx's questions during implementation: ${d.questions.join("; ")}`:"No open questions from advocate."]:["Quick check recommends full orchestration.",`Escalation reasons: ${c.join("; ")}`,'Call paradigm_orchestrate_inline mode="plan" for full agent planning.',"Orchestration enforcement is satisfied regardless of verdict."]},f=JSON.stringify(y,null,2);return o(f.length,"paradigm_orchestrate_inline"),{handled:true,text:f}}async function Ed(t,e){let s=t.agent,n=t.task,i=t.handoffContext,r=t.previousAgent,o$1=xa(e.rootDir),a=b$8(e.rootDir);if(a&&!a.includes(s)){let f=JSON.stringify({warning:`Agent "${s}" is not on this project's roster`,suggestion:`Run paradigm_agent_activate id="${s}" to add it, or check .paradigm/roster.yaml`,activeRoster:a},null,2);return o(f.length,"paradigm_agent_prompt"),{handled:true,text:f}}let c=o$1?.agents[s],l={name:c?.name||s,role:c?.role||Ot[s]||Ot.builder,focus:c?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:wa(s,e.rootDir,c),triggers:c?.triggers,handoff_to:c?.handoff_to,context:c?.context,protocol:c?.protocol},d=$t(n),p,u;try{let{loadAgentProfile:f,buildProfileEnrichment:b}=await import('./agent-loader-W3RQJVW7.js'),{loadDecisions:h}=await import('./decision-loader-HELL2AMX.js'),{loadJournalEntries:w}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:v}=await import('./nomination-engine-NCLTGMAK.js'),{loadNotebookEntries:k}=await import('./notebook-loader-3J2OFMS3.js'),S=f(e.rootDir,s);if(S){u=S.nickname;let x=h(e.rootDir,{status:"active",limit:5}).map(P=>({title:P.title,decision:P.decision.slice(0,150)})),C=w(s,{transferable:!0,limit:5}).map(P=>({trigger:P.trigger,insight:P.insight.slice(0,150)})),_=v(e.rootDir,{pending_only:!0,limit:10}).map(P=>({urgency:P.urgency,brief:P.brief})),R;try{let P=d.map(j=>j.replace(/^[#$^!~@&%?]/,"").toLowerCase()),A=k(s,e.rootDir,P.length>0?{concepts:P}:void 0);if(A.length>0){let j=A.sort((T,O)=>O.confidence-T.confidence||new Date(O.updated).getTime()-new Date(T.updated).getTime()).slice(0,5);R=j.map(T=>({context:T.context,snippet:T.snippet,concepts:T.concepts}));try{let{recordNotebookReference:T}=await import('./session-work-log-MEJ33TYD.js');T(e.rootDir,s,j.map(O=>O.id));}catch{}}}catch{}let I=b(S,d,R,{recentDecisions:x,journalInsights:C,pendingNominations:_});if(S.permissions){let P=[`
495
+ ## Permission Constraints`];S.permissions.paths?.deny?.length&&P.push(`**Denied paths:** ${S.permissions.paths.deny.join(", ")}`),S.permissions.paths?.write?.length&&P.push(`**Writable paths:** ${S.permissions.paths.write.join(", ")}`),S.permissions.tools?.deny?.length&&P.push(`**Denied tools:** ${S.permissions.tools.deny.join(", ")}`),S.permissions.dangerous_actions?.length&&P.push(`**Requires approval for:** ${S.permissions.dangerous_actions.join(", ")}`),I+=`
412
496
  `+P.join(`
413
- `);}I.trim()&&(p=I);}}catch{}let m=ya({agent:l,task:n,symbols:d,handoffContext:i,previousAgent:r,profileEnrichment:p,nickname:u}),g={agent:s,model:m.model,prompt:m.prompt,attribution:m.attribution,taskToolParams:{description:m.taskDescription,prompt:m.prompt,subagent_type:m.subagentType,model:m.model},focusAreas:m.focusAreas,usage:"Use the Task tool with the taskToolParams to spawn this agent. Present the response with the attribution prefix."},y=JSON.stringify(g,null,2);return o(y.length,"paradigm_agent_prompt"),{handled:true,text:y}}function fa(t,e){let s=new Set(t),n=[];for(let i of t){let r=e[i];if(r?.handoff_to)for(let o of r.handoff_to)s.has(o)&&n.push({from:i,to:o});}return n}function _d(t,e){let s=fa(t,e);if(s.length===0)return null;let n=new Set,i=new Set(s.map(u=>`${u.from}->${u.to}`));for(let u of s)if(i.has(`${u.to}->${u.from}`)){let m=[u.from,u.to].sort().join(",");n.add(m);}let r=new Map;for(let u of n){let[m,g]=u.split(","),y=r.get(m)||m,f=r.get(g)||g,b=y<f?y:f;for(let[h,w]of r)(w===y||w===f)&&r.set(h,b);r.set(m,b),r.set(g,b);}for(let u of t)r.has(u)||r.set(u,u);let o=[...new Set(r.values())],a=new Map,c=new Map;for(let u of o)a.set(u,0),c.set(u,new Set);for(let u of s){let m=r.get(u.from),g=r.get(u.to);m!==g&&(c.get(m).has(g)||(c.get(m).add(g),a.set(g,(a.get(g)||0)+1)));}let l=new Map,d=[];for(let u of o)(a.get(u)||0)===0&&(d.push(u),l.set(u,0));for(;d.length>0;){let u=d.shift(),m=l.get(u)||0;for(let g of c.get(u)||[]){let y=(a.get(g)||1)-1;a.set(g,y);let f=m+1;l.set(g,Math.max(l.get(g)||0,f)),y===0&&d.push(g);}}if(l.size<o.length)return null;let p=new Map;for(let u of t){let m=r.get(u);p.set(u,l.get(m)||0);}return p}function Sd(t,e,s,n,i){let r=Ot(t),o=t.toLowerCase(),a=[],c=[];if(s&&s.length>0)for(let v=0;v<s.length;v++){let k=s[v];e[k]&&c.push({name:k,task:`${k==="architect"?"Design":k==="builder"?"Implement":k==="tester"?"Test":"Process"}: ${t}`,dependsOn:v>0?[s[v-1]]:[],required:true,stage:v});}else {let v=o.includes("design")||o.includes("architect")||o.includes("plan")||o.includes("spec"),k=o.includes("auth")||o.includes("security")||o.includes("gate")||r.some(I=>I.startsWith("^")),_=o.includes("build")||o.includes("implement")||o.includes("create")||o.includes("add")||o.includes("fix"),x=o.includes("review")||o.includes("check"),C=o.includes("test")||o.includes("verify")||o.includes("validate");if(v&&e.architect&&c.push({name:"architect",task:`Design and specify: ${t}`,dependsOn:[],required:true,stage:0}),k&&e.security&&c.push({name:"security",task:`Review security aspects of: ${t}`,dependsOn:[],required:false,stage:0}),_&&e.builder){let I=v&&e.architect?["architect"]:[];c.push({name:"builder",task:`Implement: ${t}`,dependsOn:I,required:true,stage:I.length>0?1:0});}let S=c.some(I=>I.name==="builder"),R=S?2:v?1:0;if(x&&e.reviewer&&c.push({name:"reviewer",task:`Review: ${t}`,dependsOn:S?["builder"]:[],required:false,stage:R}),C&&e.tester&&c.push({name:"tester",task:`Test and validate: ${t}`,dependsOn:S?["builder"]:[],required:false,stage:R}),c.length===0){let I=n?.recommendedAgents||["architect","builder","tester"],P={architect:"Design",security:"Review security of",builder:"Implement",tester:"Test",reviewer:"Review"},D=0,j=null;for(let T of I){if(!e[T])continue;let O=j?[j]:[],$=P[T]||"Process",F=T==="architect"||T==="builder";c.push({name:T,task:`${$}: ${t}`,required:F,stage:D,dependsOn:O}),j=T,D++;}}}let l=c.map(v=>v.name),d=_d(l,e);if(d)for(let v of c){v.stage=d.get(v.name)||0;let k=[];for(let _ of l){if(_===v.name)continue;e[_]?.handoff_to?.includes(v.name)&&(d.get(_)||0)<v.stage&&k.push(_);}k.length>0&&(v.dependsOn=k);}let p=new Map;for(let v of c){let k=p.get(v.stage)||[];k.push(v),p.set(v.stage,k);}let u=Array.from(p.keys()).sort((v,k)=>v-k);for(let v of u){let k=p.get(v)||[];a.push({stage:v,agents:k.map(_=>({name:_.name,task:_.task,dependsOn:_.dependsOn,required:_.required})),canRunParallel:k.length>1});}let m=c.some(v=>v.name==="builder"||v.name==="tester"),y=n?.type==="analysis"||!m,f=false;if(!y){let v=u.length>0?u[u.length-1]+1:0;a.push({stage:v,agents:[{name:"documentor",task:"Review all changes made by previous agents. Update .purpose files, portal.yaml, and symbol registrations using only paradigm_purpose_* and paradigm_portal_* MCP tools. Run paradigm_reindex when done. Do NOT modify source code.",dependsOn:c.map(k=>k.name),required:true}],canRunParallel:false}),f=true;}let b=0,h=0;for(let v of c){let k=bd[v.name]||{min:5e3,max:2e4};b+=k.min,h+=k.max;}f&&(b+=2e3,h+=8e3);let w=i?.default_mode||"faceted";return {task:t,mode:w,stages:a,symbols:r,estimatedAgents:c.length+(f?1:0),estimatedTokens:{min:b,max:h}}}function ya(t){let{agent:e,task:s,symbols:n,handoffContext:i,previousAgent:r}=t,o=[];t.profileEnrichment&&(o.push(t.profileEnrichment),o.push("---"),o.push("")),t.captainBrief&&(o.push(t.captainBrief),o.push(""));let a=Dt[e.name]||e.role||Dt.builder;if(o.push(a),o.push(""),o.push("---"),o.push(""),o.push("## Your Task"),o.push(""),o.push(s),o.push(""),n.length>0){o.push("## Symbols in Scope"),o.push("");for(let p of n){let u=xd(p);o.push(`- \`${p}\` (${u})`);}o.push("");}i&&(o.push("## Context from Previous Agent"),r&&o.push(`*Handed off from ${r}:*`),o.push(""),o.push(i),o.push("")),(e.focus?.reads||e.focus?.writes)&&(o.push("## Focus Areas"),o.push(""),o.push(`**Read from:** ${e.focus?.reads?.join(", ")||"**/*"}`),o.push(`**Write to:** ${e.focus?.writes?.join(", ")||"**/*"}`),o.push("")),o.push(`## Output Format
497
+ `);}I.trim()&&(p=I);}}catch{}let g=_a({agent:l,task:n,symbols:d,handoffContext:i,previousAgent:r,profileEnrichment:p,nickname:u}),m={agent:s,model:g.model,prompt:g.prompt,attribution:g.attribution,taskToolParams:{description:g.taskDescription,prompt:g.prompt,subagent_type:g.subagentType,model:g.model},focusAreas:g.focusAreas,usage:"Use the Task tool with the taskToolParams to spawn this agent. Present the response with the attribution prefix."},y=JSON.stringify(m,null,2);return o(y.length,"paradigm_agent_prompt"),{handled:true,text:y}}function Sa(t,e){let s=new Set(t),n=[];for(let i of t){let r=e[i];if(r?.handoff_to)for(let o of r.handoff_to)s.has(o)&&n.push({from:i,to:o});}return n}function Hd(t,e){let s=Sa(t,e);if(s.length===0)return null;let n=new Set,i=new Set(s.map(u=>`${u.from}->${u.to}`));for(let u of s)if(i.has(`${u.to}->${u.from}`)){let g=[u.from,u.to].sort().join(",");n.add(g);}let r=new Map;for(let u of n){let[g,m]=u.split(","),y=r.get(g)||g,f=r.get(m)||m,b=y<f?y:f;for(let[h,w]of r)(w===y||w===f)&&r.set(h,b);r.set(g,b),r.set(m,b);}for(let u of t)r.has(u)||r.set(u,u);let o=[...new Set(r.values())],a=new Map,c=new Map;for(let u of o)a.set(u,0),c.set(u,new Set);for(let u of s){let g=r.get(u.from),m=r.get(u.to);g!==m&&(c.get(g).has(m)||(c.get(g).add(m),a.set(m,(a.get(m)||0)+1)));}let l=new Map,d=[];for(let u of o)(a.get(u)||0)===0&&(d.push(u),l.set(u,0));for(;d.length>0;){let u=d.shift(),g=l.get(u)||0;for(let m of c.get(u)||[]){let y=(a.get(m)||1)-1;a.set(m,y);let f=g+1;l.set(m,Math.max(l.get(m)||0,f)),y===0&&d.push(m);}}if(l.size<o.length)return null;let p=new Map;for(let u of t){let g=r.get(u);p.set(u,l.get(g)||0);}return p}function qd(t,e,s,n,i){let r=$t(t),o=t.toLowerCase(),a=[],c=[];if(s&&s.length>0)for(let v=0;v<s.length;v++){let k=s[v];e[k]&&c.push({name:k,task:`${k==="architect"?"Design":k==="builder"?"Implement":k==="tester"?"Test":"Process"}: ${t}`,dependsOn:v>0?[s[v-1]]:[],required:true,stage:v});}else {let v=o.includes("design")||o.includes("architect")||o.includes("plan")||o.includes("spec"),k=o.includes("auth")||o.includes("security")||o.includes("gate")||r.some(I=>I.startsWith("^")),S=o.includes("build")||o.includes("implement")||o.includes("create")||o.includes("add")||o.includes("fix"),x=o.includes("review")||o.includes("check"),C=o.includes("test")||o.includes("verify")||o.includes("validate");if(v&&e.architect&&c.push({name:"architect",task:`Design and specify: ${t}`,dependsOn:[],required:true,stage:0}),k&&e.security&&c.push({name:"security",task:`Review security aspects of: ${t}`,dependsOn:[],required:false,stage:0}),S&&e.builder){let I=v&&e.architect?["architect"]:[];c.push({name:"builder",task:`Implement: ${t}`,dependsOn:I,required:true,stage:I.length>0?1:0});}let _=c.some(I=>I.name==="builder"),R=_?2:v?1:0;if(x&&e.reviewer&&c.push({name:"reviewer",task:`Review: ${t}`,dependsOn:_?["builder"]:[],required:false,stage:R}),C&&e.tester&&c.push({name:"tester",task:`Test and validate: ${t}`,dependsOn:_?["builder"]:[],required:false,stage:R}),c.length===0){let I=n?.recommendedAgents||["architect","builder","tester"],P={architect:"Design",security:"Review security of",builder:"Implement",tester:"Test",reviewer:"Review"},A=0,j=null;for(let T of I){if(!e[T])continue;let O=j?[j]:[],$=P[T]||"Process",F=T==="architect"||T==="builder";c.push({name:T,task:`${$}: ${t}`,required:F,stage:A,dependsOn:O}),j=T,A++;}}}let l=c.map(v=>v.name),d=Hd(l,e);if(d)for(let v of c){v.stage=d.get(v.name)||0;let k=[];for(let S of l){if(S===v.name)continue;e[S]?.handoff_to?.includes(v.name)&&(d.get(S)||0)<v.stage&&k.push(S);}k.length>0&&(v.dependsOn=k);}let p=new Map;for(let v of c){let k=p.get(v.stage)||[];k.push(v),p.set(v.stage,k);}let u=Array.from(p.keys()).sort((v,k)=>v-k);for(let v of u){let k=p.get(v)||[];a.push({stage:v,agents:k.map(S=>({name:S.name,task:S.task,dependsOn:S.dependsOn,required:S.required})),canRunParallel:k.length>1});}let g=c.some(v=>v.name==="builder"||v.name==="tester"),y=n?.type==="analysis"||!g,f=false;if(!y){let v=u.length>0?u[u.length-1]+1:0;a.push({stage:v,agents:[{name:"documentor",task:"Review all changes made by previous agents. Update .purpose files, portal.yaml, and symbol registrations using only paradigm_purpose_* and paradigm_portal_* MCP tools. Run paradigm_reindex when done. Do NOT modify source code.",dependsOn:c.map(k=>k.name),required:true}],canRunParallel:false}),f=true;}let b=0,h=0;for(let v of c){let k=$d[v.name]||{min:5e3,max:2e4};b+=k.min,h+=k.max;}f&&(b+=2e3,h+=8e3);let w=i?.default_mode||"faceted";return {task:t,mode:w,stages:a,symbols:r,estimatedAgents:c.length+(f?1:0),estimatedTokens:{min:b,max:h}}}function _a(t){let{agent:e,task:s,symbols:n,handoffContext:i,previousAgent:r}=t,o=[];t.profileEnrichment&&(o.push(t.profileEnrichment),o.push("---"),o.push("")),t.captainBrief&&(o.push(t.captainBrief),o.push(""));let a=Ot[e.name]||e.role||Ot.builder;if(o.push(a),o.push(""),o.push("---"),o.push(""),o.push("## Your Task"),o.push(""),o.push(s),o.push(""),n.length>0){o.push("## Symbols in Scope"),o.push("");for(let p of n){let u=Ld(p);o.push(`- \`${p}\` (${u})`);}o.push("");}i&&(o.push("## Context from Previous Agent"),r&&o.push(`*Handed off from ${r}:*`),o.push(""),o.push(i),o.push("")),(e.focus?.reads||e.focus?.writes)&&(o.push("## Focus Areas"),o.push(""),o.push(`**Read from:** ${e.focus?.reads?.join(", ")||"**/*"}`),o.push(`**Write to:** ${e.focus?.writes?.join(", ")||"**/*"}`),o.push("")),o.push(`## Output Format
414
498
 
415
499
  When you complete your task, end with a structured summary block:
416
500
 
@@ -429,19 +513,19 @@ handoff_context: |
429
513
  \`\`\`
430
514
 
431
515
  This structured output helps track progress and pass context between agents.`);let c=o.join(`
432
- `),l=e.defaultModel||Dn[Tt[e.name]||"tier-2"]||"sonnet",d=t.nickname?`[${t.nickname} (${e.name})]`:`[${e.name}]`;return {agent:e.name,model:l,prompt:c,taskDescription:`${e.name}: ${s.slice(0,50)}${s.length>50?"...":""}`,subagentType:"general-purpose",attribution:d,focusAreas:e.focus||{reads:["**/*"],writes:["**/*"]}}}function Ot(t){let e=t.match(hd)||[];return [...new Set(e)]}function xd(t){let e=t.charAt(0);return {"@":"feature","#":"component",$:"flow","%":"state","^":"gate","!":"signal","?":"idea","&":"integration","~":"deprecated"}[e]||"unknown"}var Cd=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","pros and cons"],Rd=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs"],Pd=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","regression","patch"],jd=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify"],Td=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","ownership","transfer","privilege","escalation","impersonation","takeover","rbac","acl","role","guard","middleware","session","cookie","csrf","xss","injection","sanitize"];function Dd(t){let e=t.toLowerCase(),s=Ot(t),n=f=>f.filter(b=>e.includes(b.toLowerCase())),i=n(Cd),r=n(Rd),o=n(Pd),a=n(jd),c=n(Td),l,d;i.length>0&&o.length===0&&a.length===0?(l="analysis",d=i):r.length>0&&o.length===0?(l="documentation",d=r):o.length>0?(l="bugfix",d=o):a.length>0?(l="refactor",d=a):(l="feature",d=[]);let p="medium",u=t.split(/\s+/).length;s.length>=5||u>=100?p="high":s.length<=1&&u<30&&(p="low");let m=c.length>0||s.some(f=>f.startsWith("^")),g={analysis:["architect"],documentation:["architect"],bugfix:["security","builder"],refactor:["architect","builder"],feature:["architect","security","builder","tester"]},y={analysis:{min:.3,max:.5},documentation:{min:.25,max:.45},bugfix:{min:.5,max:.8},refactor:{min:.6,max:.85},feature:{min:.8,max:1.2}};return {type:l,complexity:p,recommendedAgents:g[l]||["architect","builder"],securityRequired:m,costMultiplier:y[l]||{min:.8,max:1},matchedKeywords:d,symbols:s}}var la={opus:{input:15,output:75},sonnet:{input:3,output:15},haiku:{input:.25,output:1.25}},da={architect:{input:8e3,output:4e3},security:{input:6e3,output:3e3},reviewer:{input:5e3,output:2e3},builder:{input:15e3,output:1e4},tester:{input:8e3,output:5e3}};function Ad(t,e){let s=[],n=0,i=e.complexity==="high"?1.5:e.complexity==="low"?.6:1;for(let a of t.stages)for(let c of a.agents){let l=da[c.name]||{input:5e3,output:3e3},d=Dn[Tt[c.name]||"tier-2"]||"sonnet",p=la[d],u=Math.round(l.input*i),m=Math.round(l.output*i),g=u+m,y=u/1e6*p.input+m/1e6*p.output;s.push({name:c.name,model:d,estimatedTokens:g,estimatedCost:Math.round(y*1e4)/1e4}),n+=y;}let r=0;for(let[a,c]of Object.entries(da)){let l=Dn[Tt[a]||"tier-2"]||"sonnet",d=la[l];r+=c.input/1e6*d.input+c.output/1e6*d.output;}let o=r>0?n/r:1;return {agents:s,totalEstimatedCost:Math.round(n*1e4)/1e4,comparisonToBaseline:`${o.toFixed(2)}x`}}function Od(t,e){let s=[],n=t.toLowerCase(),i=Ot(t);for(let[c,l]of Object.entries(e)){let d=[];for(let p of l.triggers||[]){if(p.type==="keyword"&&p.match)for(let u of p.match)n.includes(u.toLowerCase())&&d.push(`keyword:${u}`);if(p.type==="symbol"&&p.match)for(let u of p.match){let m=i.filter(g=>u.endsWith("*")?g.startsWith(u.slice(0,-1)):g===u);for(let g of m)d.push(`symbol:${g}`);}}if(d.length>0){let p=d.filter(b=>b.startsWith("keyword:")).length,u=d.filter(b=>b.startsWith("symbol:")).length,m=p>0&&u>0,g=d.length>=3||m?"high":d.length>=2?"medium":"low",y=l.role.split(`
433
- `)[0].trim(),f=y.length>50?y.slice(0,47)+"...":y;s.push({name:c,reason:f,confidence:g,triggers_matched:d});}}let r=new Set(s.map(c=>c.name)),o=[];for(let c of s){let l=e[c.name];if(l?.handoff_to)for(let d of l.handoff_to){if(r.has(d)||!e[d])continue;let p=e[d],u=[];for(let m of p.triggers||[]){if(m.type==="keyword"&&m.match)for(let g of m.match)n.includes(g.toLowerCase())&&u.push(`keyword:${g}`);if(m.type==="symbol"&&m.match)for(let g of m.match){let y=i.filter(f=>g.endsWith("*")?f.startsWith(g.slice(0,-1)):f===g);for(let f of y)u.push(`symbol:${f}`);}}if(u.length>0){r.add(d);let m=p.role.split(`
434
- `)[0].trim(),g=m.length>50?m.slice(0,47)+"...":m;o.push({name:d,reason:g,confidence:u.length>=2?"high":"medium",triggers_matched:[...u,`collaboration:handoff_from:${c.name}`]});}}}s.push(...o);let a={high:3,medium:2,low:1};return s.sort((c,l)=>a[l.confidence]-a[c.confidence])}function ha(t){let e=H.join(t,".paradigm","agents.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf-8");return Te.load(s)}catch{return null}}function Id(t,e,s,n){let i=H.join(t,".paradigm","orchestrations");E.existsSync(i)||E.mkdirSync(i,{recursive:true});let r=H.join(i,`${e}.yaml`),o={id:e,task:s,created:new Date().toISOString(),status:"pending",mode:n.mode,symbols:n.symbols,estimatedAgents:n.estimatedAgents,estimatedTokens:n.estimatedTokens,stages:n.stages};try{E.writeFileSync(r,Te.dump(o));}catch{}}function ba(t){let e=H.join(t,".paradigm","tags.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf-8");return Te.load(s)}catch{return null}}function $d(t,e){let s=H.join(t,".paradigm","tags.yaml"),n=Te.dump(e,{lineWidth:-1});E.writeFileSync(s,n,"utf-8");}function wa(){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 va(t,e,s){switch(t){case "paradigm_tags":{let{action:n,query:i,tag:r,category:o="all"}=e,a=ba(s.rootDir);if(!a)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(n==="list"){let c={};return (o==="all"||o==="core")&&(c.core=Object.entries(a.core).map(([l,d])=>({tag:l,description:d.description?.split(`
516
+ `),l=e.defaultModel||In[Dt[e.name]||"tier-2"]||"sonnet",d=t.nickname?`[${t.nickname} (${e.name})]`:`[${e.name}]`;return {agent:e.name,model:l,prompt:c,taskDescription:`${e.name}: ${s.slice(0,50)}${s.length>50?"...":""}`,subagentType:"general-purpose",attribution:d,focusAreas:e.focus||{reads:["**/*"],writes:["**/*"]}}}function $t(t){let e=t.match(Id)||[];return [...new Set(e)]}function Ld(t){let e=t.charAt(0);return {"@":"feature","#":"component",$:"flow","%":"state","^":"gate","!":"signal","?":"idea","&":"integration","~":"deprecated"}[e]||"unknown"}var Md=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","pros and cons"],Wd=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs"],Gd=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","regression","patch"],Jd=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify"],Ud=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","ownership","transfer","privilege","escalation","impersonation","takeover","rbac","acl","role","guard","middleware","session","cookie","csrf","xss","injection","sanitize"];function Bd(t){let e=t.toLowerCase(),s=$t(t),n=f=>f.filter(b=>e.includes(b.toLowerCase())),i=n(Md),r=n(Wd),o=n(Gd),a=n(Jd),c=n(Ud),l,d;i.length>0&&o.length===0&&a.length===0?(l="analysis",d=i):r.length>0&&o.length===0?(l="documentation",d=r):o.length>0?(l="bugfix",d=o):a.length>0?(l="refactor",d=a):(l="feature",d=[]);let p="medium",u=t.split(/\s+/).length;s.length>=5||u>=100?p="high":s.length<=1&&u<30&&(p="low");let g=c.length>0||s.some(f=>f.startsWith("^")),m={analysis:["architect"],documentation:["architect"],bugfix:["security","builder"],refactor:["architect","builder"],feature:["architect","security","builder","tester"]},y={analysis:{min:.3,max:.5},documentation:{min:.25,max:.45},bugfix:{min:.5,max:.8},refactor:{min:.6,max:.85},feature:{min:.8,max:1.2}};return {type:l,complexity:p,recommendedAgents:m[l]||["architect","builder"],securityRequired:g,costMultiplier:y[l]||{min:.8,max:1},matchedKeywords:d,symbols:s}}var ya={opus:{input:15,output:75},sonnet:{input:3,output:15},haiku:{input:.25,output:1.25}},ha={architect:{input:8e3,output:4e3},security:{input:6e3,output:3e3},reviewer:{input:5e3,output:2e3},builder:{input:15e3,output:1e4},tester:{input:8e3,output:5e3}};function zd(t,e){let s=[],n=0,i=e.complexity==="high"?1.5:e.complexity==="low"?.6:1;for(let a of t.stages)for(let c of a.agents){let l=ha[c.name]||{input:5e3,output:3e3},d=In[Dt[c.name]||"tier-2"]||"sonnet",p=ya[d],u=Math.round(l.input*i),g=Math.round(l.output*i),m=u+g,y=u/1e6*p.input+g/1e6*p.output;s.push({name:c.name,model:d,estimatedTokens:m,estimatedCost:Math.round(y*1e4)/1e4}),n+=y;}let r=0;for(let[a,c]of Object.entries(ha)){let l=In[Dt[a]||"tier-2"]||"sonnet",d=ya[l];r+=c.input/1e6*d.input+c.output/1e6*d.output;}let o=r>0?n/r:1;return {agents:s,totalEstimatedCost:Math.round(n*1e4)/1e4,comparisonToBaseline:`${o.toFixed(2)}x`}}function Yd(t,e){let s=[],n=t.toLowerCase(),i=$t(t);for(let[c,l]of Object.entries(e)){let d=[];for(let p of l.triggers||[]){if(p.type==="keyword"&&p.match)for(let u of p.match)n.includes(u.toLowerCase())&&d.push(`keyword:${u}`);if(p.type==="symbol"&&p.match)for(let u of p.match){let g=i.filter(m=>u.endsWith("*")?m.startsWith(u.slice(0,-1)):m===u);for(let m of g)d.push(`symbol:${m}`);}}if(d.length>0){let p=d.filter(b=>b.startsWith("keyword:")).length,u=d.filter(b=>b.startsWith("symbol:")).length,g=p>0&&u>0,m=d.length>=3||g?"high":d.length>=2?"medium":"low",y=l.role.split(`
517
+ `)[0].trim(),f=y.length>50?y.slice(0,47)+"...":y;s.push({name:c,reason:f,confidence:m,triggers_matched:d});}}let r=new Set(s.map(c=>c.name)),o=[];for(let c of s){let l=e[c.name];if(l?.handoff_to)for(let d of l.handoff_to){if(r.has(d)||!e[d])continue;let p=e[d],u=[];for(let g of p.triggers||[]){if(g.type==="keyword"&&g.match)for(let m of g.match)n.includes(m.toLowerCase())&&u.push(`keyword:${m}`);if(g.type==="symbol"&&g.match)for(let m of g.match){let y=i.filter(f=>m.endsWith("*")?f.startsWith(m.slice(0,-1)):f===m);for(let f of y)u.push(`symbol:${f}`);}}if(u.length>0){r.add(d);let g=p.role.split(`
518
+ `)[0].trim(),m=g.length>50?g.slice(0,47)+"...":g;o.push({name:d,reason:m,confidence:u.length>=2?"high":"medium",triggers_matched:[...u,`collaboration:handoff_from:${c.name}`]});}}}s.push(...o);let a={high:3,medium:2,low:1};return s.sort((c,l)=>a[l.confidence]-a[c.confidence])}function xa(t){let e=H.join(t,".paradigm","agents.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf-8");return Ae.load(s)}catch{return null}}function Vd(t,e,s,n){let i=H.join(t,".paradigm","orchestrations");E.existsSync(i)||E.mkdirSync(i,{recursive:true});let r=H.join(i,`${e}.yaml`),o={id:e,task:s,created:new Date().toISOString(),status:"pending",mode:n.mode,symbols:n.symbols,estimatedAgents:n.estimatedAgents,estimatedTokens:n.estimatedTokens,stages:n.stages};try{E.writeFileSync(r,Ae.dump(o));}catch{}}function Ca(t){let e=H.join(t,".paradigm","tags.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf-8");return Ae.load(s)}catch{return null}}function Kd(t,e){let s=H.join(t,".paradigm","tags.yaml"),n=Ae.dump(e,{lineWidth:-1});E.writeFileSync(s,n,"utf-8");}function Ra(){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 Pa(t,e,s){switch(t){case "paradigm_tags":{let{action:n,query:i,tag:r,category:o="all"}=e,a=Ca(s.rootDir);if(!a)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(n==="list"){let c={};return (o==="all"||o==="core")&&(c.core=Object.entries(a.core).map(([l,d])=>({tag:l,description:d.description?.split(`
435
519
  `)[0].trim(),color:d.color,appliesTo:d["applies-to"]}))),(o==="all"||o==="project")&&(c.project=Object.entries(a.project||{}).map(([l,d])=>({tag:l,description:d.description?.split(`
436
520
  `)[0].trim(),color:d.color,appliesTo:d["applies-to"]}))),(o==="all"||o==="suggested")&&(c.suggested=(a.suggested||[]).map(l=>({tag:l.tag,reason:l.reason,proposedBy:l["proposed-by"],proposedAt:l["proposed-at"]}))),c.summary={coreCount:Object.keys(a.core||{}).length,projectCount:Object.keys(a.project||{}).length,suggestedCount:(a.suggested||[]).length},{handled:true,text:JSON.stringify(c,null,2)}}if(n==="search"){if(!i)return {handled:true,text:JSON.stringify({error:"Query required for search action"})};let c=i.toLowerCase(),l=[];for(let[d,p]of Object.entries(a.core||{}))(d.toLowerCase().includes(c)||p.description?.toLowerCase().includes(c)||p.aliases?.some(u=>u.toLowerCase().includes(c)))&&l.push({tag:d,category:"core",description:p.description?.split(`
437
521
  `)[0].trim()||""});for(let[d,p]of Object.entries(a.project||{}))(d.toLowerCase().includes(c)||p.description?.toLowerCase().includes(c)||p.aliases?.some(u=>u.toLowerCase().includes(c)))&&l.push({tag:d,category:"project",description:p.description?.split(`
438
- `)[0].trim()||""});return {handled:true,text:JSON.stringify({query:i,count:l.length,matches:l},null,2)}}if(n==="get"){if(!r)return {handled:true,text:JSON.stringify({error:"Tag name required for get action"})};if(a.core?.[r]){let l=a.core[r];return {handled:true,text:JSON.stringify({tag:r,category:"core",description:l.description,color:l.color,appliesTo:l["applies-to"],aliases:l.aliases,requiresAspect:l["requires-aspect"]},null,2)}}if(a.project?.[r]){let l=a.project[r];return {handled:true,text:JSON.stringify({tag:r,category:"project",description:l.description,color:l.color,appliesTo:l["applies-to"],aliases:l.aliases,requiresAspect:l["requires-aspect"]},null,2)}}let c=a.suggested?.find(l=>l.tag===r);return c?{handled:true,text:JSON.stringify({tag:r,category:"suggested",reason:c.reason,proposedBy:c["proposed-by"],proposedAt:c["proposed-at"],appliesTo:c["applies-to"],exampleSymbols:c["example-symbols"],status:"pending approval"},null,2)}:{handled:true,text:JSON.stringify({error:`Tag "${r}" not found`,suggestion:'Use paradigm_tags with action "list" to see available tags'})}}return {handled:true,text:JSON.stringify({error:`Unknown action: ${n}`})}}case "paradigm_tags_suggest":{let{tag:n,description:i,reason:r,appliesTo:o,exampleSymbols:a}=e,c=ba(s.rootDir);if(!c)return {handled:true,text:JSON.stringify({error:"Tag bank not found",suggestion:"Create .paradigm/tags.yaml first"})};if(c.core?.[n]||c.project?.[n])return {handled:true,text:JSON.stringify({error:`Tag "${n}" already exists`,existing:c.core?.[n]?"core":"project"})};if(c.suggested?.some(d=>d.tag===n))return {handled:true,text:JSON.stringify({error:`Tag "${n}" is already in the suggested queue`,status:"pending approval"})};let l={tag:n,"proposed-by":"claude","proposed-at":new Date().toISOString(),reason:r,"applies-to":o||["#"],"example-symbols":a};return c.suggested||(c.suggested=[]),c.suggested.push(l),$d(s.rootDir,c),{handled:true,text:JSON.stringify({success:true,tag:n,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:n}=e,i=n.startsWith("~")?n:`~${n}`,r=h$1(s.index,i);if(!r)return {handled:true,text:JSON.stringify({error:`Aspect "${i}" not found`,suggestion:"Use paradigm_search to find available aspects"})};if(r.type!=="aspect")return {handled:true,text:JSON.stringify({error:`Symbol "${i}" is not an aspect (type: ${r.type})`,note:"Only ~ symbols are aspects"})};let o=r.anchors||[],a=[];for(let g of o){let y=H.isAbsolute(g.path)?g.path:H.join(s.rootDir,g.path),f=E.existsSync(y),b;if(f)try{let w=E.readFileSync(y,"utf-8").split(`
439
- `);typeof g.lines=="number"?b=1:Array.isArray(g.lines)&&g.lines.length===2?b=g.lines[1]-g.lines[0]+1:Array.isArray(g.lines)&&(b=g.lines.length);}catch{}a.push({path:g.path,lines:g.raw.split(":")[1]||"full file",exists:f,lineCount:b});}let c=o.length>0&&a.every(g=>g.exists),l=r.appliesTo||[],d=n$1(s.index),p=[],u=[];for(let g of d)for(let y of l)if(new RegExp("^"+y.replace(/\*/g,".*").replace(/\?/g,".")+"$").test(g.symbol)){p.push(g.symbol),(g.data?.aspects?.includes?.(i)||g.data?.aspects?.includes?.(n))&&u.push(g.symbol);break}let m=p.filter(g=>!u.includes(g));return {handled:true,text:JSON.stringify({aspect:i,valid:c,description:r.description,enforcement:r.enforcement,anchors:a,coverage:{appliesTo:l,matchingSymbols:p.length,symbolsWithAspect:u.length,missing:m.slice(0,10),missingCount:m.length},warnings:[...o.length===0?["CRITICAL: Aspect has no anchors - aspects MUST have code anchors"]:[],...a.filter(g=>!g.exists).map(g=>`Anchor file not found: ${g.path}`),...m.length>0?[`${m.length} symbols match applies-to but don't have this aspect`]:[]],recommendation:c?m.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$1();var he=class extends Error{code="WRITE_VERIFICATION_FAILED";constructor(e="write verification failed"){super(e),this.name="WriteVerificationError";}},Fd=".paradigm-install-key",Nd="paradigm-v5.38.0-hmac-fallback-key",Ie=null;function Ed(){if(Ie)return Ie;try{let t=ra.homedir(),e=H.join(t,Fd);if(E.existsSync(e)){let n=E.readFileSync(e,"utf-8").trim();if(/^[0-9a-f]{64}$/i.test(n))return Ie=Buffer.from(n,"hex"),Ie}let s=It.randomBytes(32);try{E.writeFileSync(e,s.toString("hex"),{encoding:"utf-8",mode:384});}catch{}return Ie=s,Ie}catch{return Ie=Buffer.from(Nd),Ie}}function Hd(t){let e=It.createHmac("sha256",Ed());return e.update(t),e.digest("hex").slice(0,12)}function qd(t,e){let s=H.dirname(t),n=`.${H.basename(t)}.${process.pid}.${Date.now()}.${It.randomBytes(4).toString("hex")}.tmp`,i=H.join(s,n);try{E.writeFileSync(i,e,{encoding:"utf-8"}),E.renameSync(i,t);}catch(r){try{E.unlinkSync(i);}catch{}throw r}}async function $t(t,e,s){qd(t,e);let n;try{n=E.readFileSync(t,"utf-8");}catch{throw a.component("#write-and-confirm").error("read-back failed after atomic write",{stage:"read-back"}),new he("write verification failed (read-back error)")}let i=false;try{i=s(n);}catch{throw a.component("#write-and-confirm").error("verify callback threw",{stage:"verify-callback",strict:H$2()}),new he("write verification failed (verify callback error)")}if(!i)throw a.component("#write-and-confirm").error("verify callback returned false",{stage:"verify-callback-false",strict:H$2()}),new he("write verification failed");let r=Buffer.byteLength(n,"utf-8"),o=Hd(n);return {written:true,path:t,hashHint:o,bytes:r}}b$1();var Ld=["#","$","^","!","~"];function L(t){return t.length>1&&Ld.includes(t[0])?t.slice(1):t}function M(t,e){let s=L(t);return `${e}${s}`}function pe(t,e){let s=H.isAbsolute(t)?t:H.resolve(e,t);return s.endsWith(".purpose")?s:H.join(s,".purpose")}function Y(t){if(!E.existsSync(t))return {};let e=a$9(t);if(!e.data)throw new Error(`Failed to parse ${t}: ${e.errors.join(", ")}`);return e.data}function $e(t,e){let s=H.dirname(t);E.existsSync(s)||E.mkdirSync(s,{recursive:true});let n=b$b(e);E.writeFileSync(t,n,"utf8");}async function On(t,e,s,n="purpose.yaml"){let i=H.dirname(t);E.existsSync(i)||E.mkdirSync(i,{recursive:true});let r=b$b(e);try{return await $t(t,r,o=>{let a=a$9(t);if(!a.data)return !1;try{return s(a.data)}catch{return !1}})}catch(o){throw o instanceof he?(a.component("#purpose-writer").error("purpose write verification failed",{surface:n,stage:"writeAndConfirm"}),new Error(`purpose write verification failed (${n})`)):o}}function We(t){if(!t)return {};if(!Array.isArray(t))return t;let e={};for(let s of t){let{id:n,...i}=s;e[n]=i;}return e}function it(t){if(!t)return {};if(!Array.isArray(t))return t;let e={};for(let s of t)e[s.name]={description:s.description,steps:s.steps};return e}function rt(t,e){if(!e||e.length===0)return t;if(!t||t.length===0)return e;let s=new Set(t);for(let n of e)s.add(n);return Array.from(s)}var Md={"#":"#","^":"^","!":"!",$:"$","~":"~"};async function _a(t,e,s,n){let i=Md[n];if(!i)throw new Error(`Invalid symbol type: ${n}. Expected one of: # ^ ! $ ~`);let r=L(e),o=L(s),a=M(r,i),c=M(o,i),l=await c$4(t),d=[];for(let p of l){let u=Y(p),m=false,y={"#":"components","^":"gates","!":"signals",$:"flows","~":"aspects"}[i];if(y&&y!=="flows"){let f=u[y];f&&!Array.isArray(f)&&r in f&&(f[o]=f[r],delete f[r],m=true);}if(i==="#")for(let f of ["features","components"]){let b=u[f];b&&!Array.isArray(b)&&r in b&&(b[o]=b[r],delete b[r],m=true);}i==="$"&&u.flows&&!Array.isArray(u.flows)&&r in u.flows&&(u.flows[o]=u.flows[r],delete u.flows[r],m=true);for(let f of ["features","components"]){let b=We(u[f]);for(let[h,w]of Object.entries(b))m=Wd(w,a,c)||m;m&&Object.keys(b).length>0&&(u[f]=b);}if(u.flows){let f=it(u.flows);for(let[b,h]of Object.entries(f)){if(h.gates){let w=h.gates.indexOf(a);w!==-1&&(h.gates[w]=c,m=true);}if(h.signals){let w=h.signals.indexOf(a);w!==-1&&(h.signals[w]=c,m=true);}if(h.components){let w=h.components.indexOf(a);w!==-1&&(h.components[w]=c,m=true);}if(h.steps)for(let w of h.steps)typeof w=="object"&&"component"in w&&(w.component===a||w.component===r)&&(w.component=i==="#"?o:c,m=true);}m&&(u.flows=f);}if(u.gates){for(let[f,b]of Object.entries(u.gates))if(b.signals){let h=b.signals.indexOf(a);h!==-1&&(b.signals[h]=c,m=true);}}if(u.aspects){for(let[f,b]of Object.entries(u.aspects))if(b["applies-to"]){let h=b["applies-to"].indexOf(a);h!==-1&&(b["applies-to"][h]=c,m=true);}}m&&($e(p,u),d.push(p));}return d}function Wd(t,e,s){let n=false,i=["signals","gates","flows","components","states"];for(let r of i){let o=t[r];if(o){let a=o.indexOf(e);a!==-1&&(o[a]=s,n=true);}}if(t.aspects&&Array.isArray(t.aspects)){let r=t.aspects.indexOf(e);r!==-1&&(t.aspects[r]=s,n=true);}return n}b$1();function In(t){let e=H.join(t,"portal.yaml"),s=I$1(e);if(s.status==="missing")return {data:{version:"1.0.0",gates:{}},filePath:e};if(s.status==="unparseable"||s.status==="invalid")throw a.component("#portal-writer").error("portal.yaml unparseable on read",{errorClass:s.errorClass}),new Error(`portal.yaml unparseable (${s.errorClass}). Refusing to overwrite. Run 'paradigm doctor' for line-specific details.`);return {data:s.data||{version:"1.0.0",gates:{}},filePath:e}}async function xa(t,e){let{data:s,filePath:n}=In(t);if(!s.gates||Array.isArray(s.gates)){let a=s.gates;if(s.gates={},Array.isArray(a)&&a.length>0){for(let c of a)if(c&&typeof c=="object"&&"id"in c){let l=L(c.id);s.gates[l]=c;}}}let i=L(e.id),r=s.gates[i]||{};r.description=e.description,e.type!==void 0&&(r.type=e.type),e.location!==void 0&&(r.location=e.location),e.requires!==void 0&&(r.requires=e.requires),e.check!==void 0&&(r.check=e.check),e.grants!==void 0&&(r.grants=e.grants),e.emits!==void 0&&(r.emits=e.emits),e.prizes!==void 0&&(r.prizes=e.prizes),r.prizes||(r.prizes=[]),s.gates[i]=r;let o=Te.dump(s,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});try{return await $t(n,o,a=>{let c;try{c=Te.load(a);}catch{return !1}let l=c?.gates;return !l||Array.isArray(l)?!1:!!l[i]})}catch(a$1){throw a$1 instanceof he?(a.component("#portal-writer").error("portal_add_gate write verification failed",{stage:"writeAndConfirm"}),new Error("portal_add_gate write verification failed")):a$1}}async function Ca(t,e){let{data:s,filePath:n}=In(t);(!s.routes||Array.isArray(s.routes))&&(s.routes={});let i=`${e.method} ${e.route}`,r=e.gates.map(a=>`^${L(a)}`);s.routes[i]=r;let o=Te.dump(s,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});try{return await $t(n,o,a=>{let c;try{c=Te.load(a);}catch{return !1}let l=c?.routes;return !l||Array.isArray(l)?!1:!!l[i]})}catch(a$1){throw a$1 instanceof he?(a.component("#portal-writer").error("portal_add_route write verification failed",{stage:"writeAndConfirm"}),new Error("portal_add_route write verification failed")):a$1}}var Gd={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}},Jd={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}},Ud={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}},Bd={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}},zd={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}},Yd={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}},Vd={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}},Kd={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}},Qd={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}},Xd={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}},Zd={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}},ep={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}},tp={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 Pa(){return [Gd,Jd,Ud,Bd,zd,Yd,Vd,Kd,Qd,Xd,Zd,ep,tp]}async function ja(t,e,s,n){switch(t){case "paradigm_purpose_init":return np(e,s,n);case "paradigm_purpose_add_component":return sp(e,s,n);case "paradigm_purpose_add_aspect":return ip(e,s,n);case "paradigm_purpose_add_signal":return rp(e,s,n);case "paradigm_purpose_add_flow":return op(e,s,n);case "paradigm_purpose_add_gate":return ap(e,s,n);case "paradigm_purpose_add_state":return cp(e,s,n);case "paradigm_purpose_link":return lp(e,s,n);case "paradigm_purpose_remove":return dp(e,s,n);case "paradigm_purpose_rename":return pp(e,s,n);case "paradigm_portal_add_gate":return up(e,s,n);case "paradigm_portal_add_route":return gp(e,s,n);case "paradigm_purpose_validate":return fp(e,s);default:return {handled:false,text:""}}}function Z(t){return {handled:true,text:JSON.stringify(t,null,2)}}function X(t){return {handled:true,text:JSON.stringify({error:t},null,2)}}async function np(t,e,s){let{purposeFile:n,name:i,description:r,context:o,version:a}=t,c=pe(n,e.rootDir),l=Y(c);return a!==void 0?l.version=a:l.version||(l.version="1.0.0"),r!==void 0?l.description=r:l.description||(l.description=i),o!==void 0&&(l.context=o),$e(c,l),await s(),Z({action:"purpose_init",file:c,metadata:{name:i,description:l.description,version:l.version}})}async function sp(t,e,s){let{purposeFile:n,id:i,description:r,section:o="components",file:a,status:c,endpoints:l,tests:d,flows:p,gates:u,signals:m,aspects:g,components:y,type:f,parent:b}=t,h=pe(n,e.rootDir),w=Y(h),v=L(i),k=o,_=We(w[k]),x=_[v]||{description:""};x.description=r,a!==void 0&&(x.file=a),c!==void 0&&(x.status=c),l!==void 0&&(x.endpoints=l),d!==void 0&&(x.tests=d),p!==void 0&&(x.flows=p.map(S=>M(S,"$"))),u!==void 0&&(x.gates=u.map(S=>M(S,"^"))),m!==void 0&&(x.signals=m.map(S=>M(S,"!"))),g!==void 0&&(x.aspects=g.map(S=>M(S,"~"))),y!==void 0&&(x.components=y.map(S=>M(S,"#"))),f!==void 0&&(x.type=f),b!==void 0&&(x.parent=M(b,"#")),_[v]=x,w[k]=_;let C=await On(h,w,S=>{let R=S[k];return !R||typeof R!="object"||Array.isArray(R)?!1:v in R},k);return await s(),Z({action:"add_component",file:C.path,section:k,id:v,symbol:`#${v}`,written:C.written,hashHint:C.hashHint,bytes:C.bytes})}async function ip(t,e,s){let{purposeFile:n,id:i,description:r,anchors:o,tags:a,appliesTo:c,enforcement:l}=t;if(!o||o.length===0)return X('Aspects (~) REQUIRE at least one code anchor. Provide anchors like ["src/middleware/audit.ts:15-35"].');let d=/^[^\s:]+:\d+(-\d+)?(,\d+)*$/;for(let f of o)if(!d.test(f))return X(`Invalid anchor format: "${f}". Expected format: "file.ts:15", "file.ts:15-20", or "file.ts:15,25,30".`);let p=pe(n,e.rootDir),u=H.dirname(p);for(let f of o){let b=f.replace(/:.*$/,""),h=H.resolve(u,b);if(!E.existsSync(h)){let w=H.resolve(e.rootDir,b);if(E.existsSync(w)){let v=H.relative(u,w),k=o.indexOf(f);o[k]=f.replace(b,v);}else return X(`Anchor file not found: "${b}". Anchors must be relative to the .purpose file directory (${u}).`)}}let m=Y(p);(!m.aspects||Array.isArray(m.aspects))&&(m.aspects={});let g=L(i);m.aspects[g]={description:r,anchors:o,...a&&{tags:a},...c&&{"applies-to":c},...l&&{enforcement:l}},$e(p,m);let y=Y(p).aspects;return !y||Array.isArray(y)||!y[g]?X(`add_aspect write verification failed: aspect "${g}" not found in ${p} after write.`):(await s(),Z({action:"add_aspect",file:p,id:g,symbol:`~${g}`,anchors:o}))}async function rp(t,e,s){let{purposeFile:n,id:i,description:r,category:o,severity:a,emitters:c,related:l,data:d}=t,p=pe(n,e.rootDir),u=Y(p);(!u.signals||Array.isArray(u.signals))&&(u.signals={});let m=L(i);u.signals[m]={description:r,...o&&{category:o},...a&&{severity:a},...c&&{emitters:c.map(y=>M(y,"#"))},...l&&{related:l},...d&&{data:d}},$e(p,u);let g=Y(p).signals;return !g||Array.isArray(g)||!g[m]?X(`add_signal write verification failed: signal "${m}" not found in ${p} after write.`):(await s(),Z({action:"add_signal",file:p,id:m,symbol:`!${m}`}))}async function op(t,e,s){let{purposeFile:n,id:i,description:r,gates:o,signals:a,components:c,steps:l}=t,d=pe(n,e.rootDir),p=Y(d),u=it(p.flows),m=L(i),g={description:r,...o&&{gates:o.map(f=>M(f,"^"))},...a&&{signals:a.map(f=>M(f,"!"))},...c&&{components:c.map(f=>M(f,"#"))},...l&&{steps:l}};return u[m]=g,p.flows=u,$e(d,p),it(Y(d).flows)[m]?(await s(),Z({action:"add_flow",file:d,id:m,symbol:`$${m}`})):X(`add_flow write verification failed: flow "${m}" not found in ${d} after write.`)}async function ap(t,e,s){let{purposeFile:n,id:i,description:r,requires:o,keys:a,signals:c}=t,l=pe(n,e.rootDir),d=Y(l);(!d.gates||Array.isArray(d.gates))&&(d.gates={});let p=L(i);d.gates[p]={description:r,...o&&{requires:o},...a&&{keys:a},...c&&{signals:c.map(m=>M(m,"!"))}},$e(l,d);let u=Y(l).gates;return !u||Array.isArray(u)||!u[p]?X(`add_gate write verification failed: gate "${p}" not found in ${l} after write.`):(await s(),Z({action:"add_gate",file:l,id:p,symbol:`^${p}`}))}async function cp(t,e,s){let{purposeFile:n,id:i,description:r,type:o,default:a,properties:c}=t,l=pe(n,e.rootDir),d=Y(l);(!d.states||Array.isArray(d.states))&&(d.states={});let p=L(i),u={description:r};o!==void 0&&(u.type=o),a!==void 0&&(u.default=a),c!==void 0&&(u.properties=c),d.states[p]=u,$e(l,d);let m=Y(l).states;return !m||Array.isArray(m)||!m[p]?X(`add_state write verification failed: state "${p}" not found in ${l} after write.`):(await s(),Z({action:"add_state",file:l,id:p}))}async function lp(t,e,s){let{purposeFile:n,componentId:i,section:r,signals:o,aspects:a,gates:c,flows:l,components:d}=t,p=pe(n,e.rootDir),u=Y(p),m=L(i),g=r;if(!g){let w=We(u.components),v=We(u.features);if(m in w)g="components";else if(m in v)g="features";else return X(`Component "${m}" not found in components or features. Specify section explicitly.`)}let y=We(u[g]);if(!(m in y))return X(`Component "${m}" not found in ${g} section.`);let f=y[m];o&&(f.signals=rt(f.signals,o.map(w=>M(w,"!")))),c&&(f.gates=rt(f.gates,c.map(w=>M(w,"^")))),l&&(f.flows=rt(f.flows,l.map(w=>M(w,"$")))),d&&(f.components=rt(f.components,d.map(w=>M(w,"#")))),a&&(f.aspects=rt(f.aspects,a.map(w=>M(w,"~")))),y[m]=f,u[g]=y;let b=await On(p,u,w=>{let v=w[g];return !v||typeof v!="object"||Array.isArray(v)?!1:m in v},g);await s();let h=[];return o&&h.push(`signals: ${o.join(", ")}`),a&&h.push(`aspects: ${a.join(", ")}`),c&&h.push(`gates: ${c.join(", ")}`),l&&h.push(`flows: ${l.join(", ")}`),d&&h.push(`components: ${d.join(", ")}`),Z({action:"link",file:b.path,componentId:m,section:g,added:h,written:b.written,hashHint:b.hashHint,bytes:b.bytes})}async function dp(t,e,s){let{purposeFile:n,section:i,id:r}=t,o=pe(n,e.rootDir),a=Y(o),c=L(r);if(i==="flows"){let d=it(a.flows);if(!(c in d))return X(`Flow "${c}" not found in flows section.`);delete d[c],a.flows=d;}else if(i==="components"||i==="features"){let d=We(a[i]);if(!(c in d))return X(`"${c}" not found in ${i} section.`);delete d[c],a[i]=d;}else {let d=a[i];if(!d||!(c in d))return X(`"${c}" not found in ${i} section.`);delete d[c];}let l=await On(o,a,d=>{if(i==="flows"){let u=it(d.flows);return !(c in u)}let p=d[i];return !p||typeof p!="object"||Array.isArray(p)?!0:!(c in p)},i);return await s(),Z({action:"remove",file:l.path,section:i,id:c,written:l.written,hashHint:l.hashHint,bytes:l.bytes})}async function pp(t,e,s){let{oldId:n,newId:i,symbolType:r}=t,o=await _a(e.rootDir,n,i,r);return await s(),Z({action:"rename",oldSymbol:`${r}${L(n)}`,newSymbol:`${r}${L(i)}`,filesModified:o.length,files:o})}async function up(t,e,s){let{id:n,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:p}=t,u=await xa(e.rootDir,{id:n,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:p});await s();let m=L(n);return Z({action:"portal_add_gate",file:u.path,id:m,symbol:`^${m}`,written:u.written,hashHint:u.hashHint,bytes:u.bytes})}async function gp(t,e,s){let{route:n,method:i,gates:r}=t,o=await Ca(e.rootDir,{route:n,method:i,gates:r});return await s(),Z({action:"portal_add_route",file:o.path,route:`${i} ${n}`,gates:r,written:o.written,hashHint:o.hashHint,bytes:o.bytes})}var mp=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi;function Ra(t,e){let s=[];function n(r,o){if(typeof r=="string"){let a=r.match(mp);if(a)for(let c of a)s.push({type:"warning",message:`Clarification needed: ${c}`,path:o});}}n(t.description,"description");let i=[{key:"components",items:t.components},{key:"features",items:t.features},{key:"gates",items:t.gates},{key:"signals",items:t.signals},{key:"aspects",items:t.aspects}];for(let r of i)if(r.items&&typeof r.items=="object")for(let[o,a]of Object.entries(r.items))a&&typeof a.description=="string"&&n(a.description,`${r.key}.${o}.description`);if(t.flows&&typeof t.flows=="object"){let r=Array.isArray(t.flows)?[]:Object.entries(t.flows);for(let[o,a]of r)a&&typeof a.description=="string"&&n(a.description,`flows.${o}.description`);}return s}async function fp(t,e){let{purposeFile:s,includePortal:n=true}=t,i=[];if(s){let a=pe(s,e.rootDir),c=a$9(a);if(!c.data)i.push({file:a,valid:false,issues:c.errors.map(l=>({type:"error",message:l}))});else {let l=d$9(c.data,a);if(c.data.aspects)for(let[p,u]of Object.entries(c.data.aspects))(!u.anchors||u.anchors.length===0)&&(l.issues.push({type:"error",message:`Aspect "${p}" is missing required anchors`,path:`aspects.${p}`}),l.valid=false);let d=Ra(c.data);l.issues.push(...d),i.push({file:a,valid:l.valid,issues:l.issues});}}else {let a=await c$4(e.rootDir);for(let c of a){let l=a$9(c);if(!l.data){i.push({file:c,valid:false,issues:l.errors.map(u=>({type:"error",message:u}))});continue}let d=d$9(l.data,c);if(l.data.aspects)for(let[u,m]of Object.entries(l.data.aspects))(!m.anchors||m.anchors.length===0)&&(d.issues.push({type:"error",message:`Aspect "${u}" is missing required anchors`,path:`aspects.${u}`}),d.valid=false);let p=Ra(l.data);d.issues.push(...p),i.push({file:c,valid:d.valid,issues:d.issues});}}if(n){let{data:a,filePath:c}=In(e.rootDir),l=[];if(a.gates)for(let[d,p]of Object.entries(a.gates))p.description||l.push({type:"warning",message:`Gate "${d}" has no description`,path:`gates.${d}`}),p.prizes||l.push({type:"warning",message:`Gate "${d}" is missing prizes array (v2 requirement)`,path:`gates.${d}`});l.length>0&&i.push({file:c,valid:l.every(d=>d.type!=="error"),issues:l});}let r=i.reduce((a,c)=>a+c.issues.length,0),o=i.every(a=>a.valid);return Z({action:"validate",valid:o,totalFiles:i.length,totalIssues:r,results:i})}var La=[{id:"explore-before-implement",name:"Explore Before Implementing",description:"Call ripple/navigate/search before modifying existing symbols to understand impact",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple","paradigm_navigate","paradigm_search","paradigm_related"]}},enabled:true},{id:"ripple-before-modify",name:"Ripple Before Modifying",description:"Run ripple analysis before modifying symbols with dependents",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple"]}},enabled:true},{id:"check-fragility",name:"Check Fragility",description:"Check history fragility for symbols before modifying frequently-broken code",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_history_fragility"]}},enabled:true},{id:"wisdom-before-implement",name:"Check Team Wisdom",description:"Check team wisdom (preferences, antipatterns, decisions) before implementing",category:"collaboration",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_wisdom_context","paradigm_wisdom_expert"]}},enabled:true},{id:"verify-before-done",name:"Verify Before Done",description:"Run postflight compliance checks before finishing a session",category:"verification",trigger:"on-stop",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight"]}},enabled:true},{id:"postflight-compliance",name:"Postflight Compliance",description:"Ensure postflight checks pass without errors before finishing",category:"verification",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight","paradigm_reindex"]}},enabled:true},{id:"test-new-components",name:"Test New Components",description:"New components should have associated tests or test plan documented",category:"testing",trigger:"postflight",severity:"advisory",check:{type:"tests-exist",params:{patterns:["**/*.test.*","**/*.spec.*","**/tests/**"]}},enabled:true},{id:"purpose-coverage",name:"Purpose File Coverage",description:"All modified source directories should have .purpose file coverage",category:"documentation",trigger:"postflight",severity:"warn",check:{type:"file-exists",params:{patterns:["**/.purpose"]}},enabled:true},{id:"record-lore-for-significant",name:"Record Lore for Significant Changes",description:"Sessions modifying 3+ files should record a lore entry",category:"documentation",trigger:"on-stop",severity:"warn",check:{type:"lore-recorded",params:{}},enabled:true},{id:"confidence-on-decisions",name:"Confidence on Decisions",description:"When recording lore, include a confidence score (0.0-1.0) to enable calibration tracking over time",category:"documentation",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_lore_record"]}},enabled:true},{id:"gates-for-routes",name:"Gates for Routes",description:"API routes should have corresponding gate declarations in portal.yaml",category:"security",trigger:"postflight",severity:"warn",check:{type:"gates-declared",params:{requireRoutes:true}},enabled:true},{id:"university-content-valid",name:"University Content Valid",description:"Validate university content integrity when files in symbol-covered areas change",category:"quality",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_validate"]}},enabled:true},{id:"university-onboarded",name:"University Onboarding",description:"Call paradigm_university_onboard at session start for project-specific learning content",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_onboard"]}},enabled:false},{id:"orchestration-required",name:"Orchestrate Complex Tasks",description:"Tasks affecting 3+ files or touching security symbols should use paradigm_orchestrate_inline to determine which agents are needed. Ensures security review, test coverage, and documentation.",category:"collaboration",trigger:"preflight",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_orchestrate_inline"]}},enabled:true},{id:"agent-coverage-validated",name:"Validate Agent Involvement",description:"After completing work, verify that agents with relevant expertise were consulted. Check nominations that were surfaced but not acted on.",category:"collaboration",trigger:"postflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ambient_nominations","paradigm_agent_list"]}},enabled:true},{id:"hot-mode-incident",name:"Incident Response Acknowledgment",description:"During incident response, orchestration enforcement is waived. But a post-incident lore entry is required and a postflight review should be scheduled.",category:"collaboration",trigger:"on-stop",severity:"advisory",check:{type:"lore-recorded"},enabled:true}],vp=30*1e3,Gs=new Map;function re(t){let e=H.resolve(t),s=Gs.get(e);if(s&&Date.now()-s.loadedAt<vp)return s.habits;let n=kp(e);return Gs.set(e,{habits:n,loadedAt:Date.now()}),n}function kp(t){let e=new Map;for(let a of La)e.set(a.id,{...a});let s=process.env.HOME||process.env.USERPROFILE||"~",n=Ia(H.join(s,".paradigm","habits.yaml"));n&&$a(e,n);let i=Fa(H.join(s,".paradigm","habits"));for(let a of i)e.set(a.id,a);let r=Ia(H.join(t,".paradigm","habits.yaml"));r&&$a(e,r);let o=Fa(H.join(t,".paradigm","habits"));for(let a of o)e.set(a.id,a);return Array.from(e.values())}function Ia(t){if(!E.existsSync(t))return null;try{let e=E.readFileSync(t,"utf8");return Te.load(e)}catch{return null}}function $a(t,e){if(e.habits)for(let s of e.habits)t.set(s.id,{...s});if(e.overrides)for(let[s,n]of Object.entries(e.overrides)){let i=t.get(s);i&&(n.severity!==void 0&&(i.severity=n.severity),n.enabled!==void 0&&(i.enabled=n.enabled));}}function _p(t,e){return t.filter(s=>s.enabled&&s.trigger===e)}function Js(t){Gs.delete(H.resolve(t));}function Fa(t){if(!E.existsSync(t))return [];try{let e=E.readdirSync(t).filter(n=>n.endsWith(".habit")).sort(),s=[];for(let n of e)try{let i=E.readFileSync(H.join(t,n),"utf8"),r=Te.load(i);r?.id&&r?.name&&s.push(r);}catch{}return s}catch{return []}}var Na=["discovery","verification","testing","documentation","collaboration","security"],Ea=["preflight","postflight","on-commit","on-stop"],Ha=["advisory","warn","block"],qa=["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"],Sp=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Us(t){let e=[];if(t.id||e.push("Missing required field: id"),t.name||e.push("Missing required field: name"),t.description||e.push("Missing required field: description"),t.category||e.push("Missing required field: category"),t.trigger||e.push("Missing required field: trigger"),t.severity||e.push("Missing required field: severity"),t.check||e.push("Missing required field: check"),(t.enabled===void 0||t.enabled===null)&&e.push("Missing required field: enabled"),t.id&&!Sp.test(t.id)&&e.push(`Invalid id format: "${t.id}" \u2014 must be kebab-case (lowercase, hyphens only)`),t.category&&!Na.includes(t.category)&&e.push(`Invalid category: "${t.category}" \u2014 must be one of: ${Na.join(", ")}`),t.trigger&&!Ea.includes(t.trigger)&&e.push(`Invalid trigger: "${t.trigger}" \u2014 must be one of: ${Ea.join(", ")}`),t.severity&&!Ha.includes(t.severity)&&e.push(`Invalid severity: "${t.severity}" \u2014 must be one of: ${Ha.join(", ")}`),t.check){qa.includes(t.check.type)||e.push(`Invalid check.type: "${t.check.type}" \u2014 must be one of: ${qa.join(", ")}`);let s=t.check.params||{};switch(t.check.type){case "tool-called":(!s.tools||!Array.isArray(s.tools)||s.tools.length===0)&&e.push('check.type "tool-called" requires check.params.tools[] (non-empty array)');break;case "file-exists":case "file-modified":(!s.patterns||!Array.isArray(s.patterns)||s.patterns.length===0)&&e.push(`check.type "${t.check.type}" requires check.params.patterns[] (non-empty array)`);break;case "commit-message-format":(!s.messagePatterns||!Array.isArray(s.messagePatterns)||s.messagePatterns.length===0)&&e.push('check.type "commit-message-format" requires check.params.messagePatterns[] (non-empty array)');break}}return {valid:e.length===0,errors:e}}var xp=new Set(La.map(t=>t.id));function Ln(t){return xp.has(t)}function Bs(t,e,s="project"){let n=s==="global"?H.join(process.env.HOME||process.env.USERPROFILE||"~",".paradigm","habits"):H.join(t,".paradigm","habits");E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=H.join(n,`${e.id}.habit`),r=Te.dump(e,{lineWidth:120,noRefs:true});return E.writeFileSync(i,r,"utf8"),Js(t),i}function Ma(t,e){if(Ln(e))return {removed:false,reason:`"${e}" is a seed habit and cannot be removed. Use overrides in habits.yaml to disable it.`};let s=H.join(t,".paradigm","habits",`${e}.habit`);if(E.existsSync(s))return E.unlinkSync(s),Js(t),{removed:true};let n=process.env.HOME||process.env.USERPROFILE||"~",i=H.join(n,".paradigm","habits",`${e}.habit`);return E.existsSync(i)?(E.unlinkSync(i),Js(t),{removed:true}):{removed:false,reason:`No .habit file found for "${e}". It may be defined in habits.yaml \u2014 edit that file directly.`}}var zs=0;function Ht(t,e,s,n,i){let r=_p(t,e);n&&(r=r.filter(u=>!u.platforms||u.platforms.includes(n)));let o=0;if(i)try{let{isGraduated:u}=(qn(),d$a(Oa)),m=r.length;r=r.filter(g=>!u(i,g.id)),o=m-r.length;}catch{}zs=o;let a=r.map(u=>Cp(u,s)),c=a.filter(u=>u.result==="followed").length,l=a.filter(u=>u.result==="skipped").length,d=a.filter(u=>u.result==="partial").length,p=a.filter(u=>u.result==="skipped"&&u.habit.severity==="block").length;return {trigger:e,evaluations:a,summary:{total:a.length,followed:c,skipped:l,partial:d,blockingViolations:p},blocksCompletion:p>0}}function qt(t){return {toolsCalled:t.toolsCalled||[],filesModified:t.filesModified||[],symbolsTouched:t.symbolsTouched||[],loreRecorded:t.loreRecorded||false,hasPortalRoutes:t.hasPortalRoutes||false,taskAddsRoutes:t.taskAddsRoutes||false,taskDescription:t.taskDescription,gitClean:t.gitClean}}function Cp(t,e){switch(t.check.type){case "tool-called":return Rp(t,e);case "file-exists":return Pp(t,e);case "file-modified":return Op(t,e);case "lore-recorded":return jp(t,e);case "symbols-registered":return Tp(t,e);case "gates-declared":return Dp(t,e);case "tests-exist":return Ap(t,e);case "git-clean":return Ip(t,e);case "commit-message-format":return $p(t,e);case "flow-coverage":return Fp(t,e);case "context-checked":return Np(t,e);case "aspect-anchored":return Ep(t,e);default:return {habit:t,result:"partial",reason:`Unknown check: ${t.check.type}`}}}function Rp(t,e){let s=t.check.params.tools||[];if(s.length===0)return {habit:t,result:"followed",reason:"No tools required"};let n=s.filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Called: ${n.join(", ")}`,evidence:n}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:t,result:"followed",reason:"No modifications, habit not applicable"}:{habit:t,result:"skipped",reason:`None of [${s.join(", ")}] were called before modifying code`}}function Pp(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};if(e.filesModified.some(i=>i.endsWith(".purpose")||i.includes(".paradigm/")))return {habit:t,result:"followed",reason:"Purpose files updated"};let n=e.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".yml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/"));return n.length===0?{habit:t,result:"followed",reason:"Only non-source files modified"}:{habit:t,result:"skipped",reason:`${n.length} source file(s) without .purpose updates`,evidence:n.slice(0,5)}}function jp(t,e){let s=e.filesModified.filter(n=>!n.endsWith(".md")&&!n.endsWith(".json")&&!n.endsWith(".yaml")&&!n.endsWith(".yml")&&!n.endsWith(".lock")&&!n.endsWith(".purpose")&&!n.includes(".paradigm/"));return s.length<3?{habit:t,result:"followed",reason:"Session not significant (< 3 source files)"}:e.loreRecorded||e.toolsCalled.includes("paradigm_lore_record")?{habit:t,result:"followed",reason:"Lore recorded"}:{habit:t,result:"skipped",reason:`${s.length} source files modified, no lore entry`,evidence:s.slice(0,5)}}function Tp(t,e){if(e.symbolsTouched.length===0)return {habit:t,result:"followed",reason:"No symbols touched"};let n=["paradigm_purpose_add_component","paradigm_purpose_add_signal","paradigm_purpose_add_flow","paradigm_purpose_add_gate","paradigm_purpose_add_aspect","paradigm_purpose_init"].filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Purpose tools called: ${n.join(", ")}`,evidence:n}:{habit:t,result:"partial",reason:`${e.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function Dp(t,e){if(!e.taskAddsRoutes)return {habit:t,result:"followed",reason:"No routes added"};if(e.hasPortalRoutes)return {habit:t,result:"followed",reason:"Portal.yaml has routes"};let n=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Gate tools called: ${n.join(", ")}`,evidence:n}:{habit:t,result:"skipped",reason:"Routes added without gate declarations"}}function Ap(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};let s=e.filesModified.filter(i=>i.includes(".test.")||i.includes(".spec.")||i.includes("/tests/")||i.includes("/test/")||i.includes("__tests__"));if(s.length>0)return {habit:t,result:"followed",reason:`Test files: ${s.length}`,evidence:s.slice(0,5)};let n=e.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/")&&!i.includes("node_modules/"));return n.length===0?{habit:t,result:"followed",reason:"No source files to test"}:{habit:t,result:"partial",reason:`${n.length} source file(s), no test files updated`,evidence:n.slice(0,5)}}function Op(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};let s=t.check.params.patterns||[];if(s.length===0)return {habit:t,result:"followed",reason:"No patterns specified"};if(t.trigger==="on-stop"&&t.severity==="block"){let i=e.filesModified.filter(r=>s.some(o=>r.includes(o)||H.basename(r)===o));return i.length>0?{habit:t,result:"followed",reason:`Matching files: ${i.join(", ")}`,evidence:i}:{habit:t,result:"partial",reason:`None of [${s.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let n=e.filesModified.filter(i=>s.some(r=>i.includes(r)||H.basename(i)===r));return n.length>0?{habit:t,result:"followed",reason:`Matching files: ${n.join(", ")}`,evidence:n}:{habit:t,result:"skipped",reason:`None of [${s.join(", ")}] found in modified files`}}function Ip(t,e){return e.filesModified.length===0?{habit:t,result:"followed",reason:"No files modified"}:t.trigger==="on-stop"?{habit:t,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:e.gitClean===void 0?{habit:t,result:"partial",reason:"Git status not available"}:e.gitClean?{habit:t,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:t,result:"skipped",reason:"Uncommitted changes in working tree"}}function $p(t,e){if(!e.commitMessage)return {habit:t,result:"followed",reason:"No commit message to check (not a commit trigger)"};let s=t.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],n=s.filter(i=>new RegExp(i,"m").test(e.commitMessage));if(n.length===s.length)return {habit:t,result:"followed",reason:"Commit message matches all required patterns",evidence:n};if(n.length>0){let i=s.filter(r=>!new RegExp(r,"m").test(e.commitMessage));return {habit:t,result:"partial",reason:`Matches ${n.length}/${s.length} patterns. Missing: ${i.join(", ")}`}}return {habit:t,result:"skipped",reason:"Commit message does not match required format patterns"}}function Fp(t,e){let s=e.symbolsTouched.filter(r=>r.startsWith("#"));if(s.length<3)return {habit:t,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(e.hasFlowCoverage)return {habit:t,result:"followed",reason:"Flow coverage exists for multi-component changes"};let i=["paradigm_flow_check","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(r=>e.toolsCalled.includes(r));return i.length>0?{habit:t,result:"followed",reason:`Flow tools called: ${i.join(", ")}`,evidence:i}:{habit:t,result:"skipped",reason:`${s.length} components touched without flow coverage`,evidence:s.slice(0,5)}}function Np(t,e){let n=(t.check.params.contextTools||["paradigm_session_health","paradigm_session_recover","paradigm_session_checkpoint"]).filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Context tools called: ${n.join(", ")}`,evidence:n}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:t,result:"followed",reason:"No modifications, context check not applicable"}:{habit:t,result:"skipped",reason:"No context/session tools called during session"}}function Ep(t,e){let s=e.symbolsTouched.filter(n=>n.startsWith("~"));return s.length===0?{habit:t,result:"followed",reason:"No aspects touched"}:e.aspectAnchorsValid===true?{habit:t,result:"followed",reason:"Aspect anchors validated and valid"}:e.toolsCalled.includes("paradigm_aspect_check")?{habit:t,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:t,result:"skipped",reason:`${s.length} aspect(s) touched without anchor validation`,evidence:s.slice(0,5)}}var Hp={"missing-purpose":t=>`${t.target?`"${t.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":t=>{let e=t.target?`"${t.target}"`:"a .purpose file",s=t.context?.ageHours!=null?` (${t.context.ageHours}h old)`:"";return `The .purpose file at ${e}${s} 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":t=>`${t.target?`"${t.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":t=>`${t.target?`"${t.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: ["!${t.target||"event-name"}"]). `,"undocumented-flow":t=>`${t.target?`"${t.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":t=>`${t.target?`"${t.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":t=>`${t.target?`"${t.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":t=>`${t.target?`"${t.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., ${t.target?t.target.replace(/\.[^.]+$/,".test$&"):"component.test.ts"}).`,"uncovered-route":t=>`${t.target?`"${t.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":t=>`${t.target?`"${t.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":t=>`${t.target?`"${t.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":t=>{let e=t.target?`"${t.target}"`:"a data category",s=t.context?.ring,n=t.context?.boundary;return `${e} is being transmitted across a boundary (${n||"unknown boundary"}) that exceeds its trust ring${s?` (Ring: ${s})`:""}. 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":t=>{let e=t.target?`"${t.target}"`:"the scan index",s=t.context?.ageHours,n=s!=null?` (${s} hours old)`:"";return `${e}${n} 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 qp(t,e){let s=Hp[t];return s?s({...e,type:t}):`Unknown check type "${t}" \u2014 no narration template available.`}function Ga(t){let e=[],s=[],n=[];for(let o of t){let a=qp(o.type,o),c=o.severity??"improvement",l={type:o.type,target:o.target,narration:a,severity:c};c==="blocking"?e.push(l):c==="note"?n.push(l):s.push(l);}let i=e.length+s.length+n.length,r=Lp(e,s,n);return {gapCount:i,blocking:e,improvement:s,note:n,narrative:r}}function Lp(t,e,s){let n=[],i=t.length+e.length+s.length;if(i===0)return "No gaps found. All enforcement checks passed.";if(n.push(`Found ${i} gap${i!==1?"s":""} across ${Wa(t,e,s)} check type${Wa(t,e,s)!==1?"s":""}.`),n.push(""),t.length>0){n.push(`BLOCKING (${t.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of t)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}if(e.length>0){n.push(`IMPROVEMENTS (${e.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of e)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}if(s.length>0){n.push(`NOTES (${s.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of s)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}return n.join(`
440
- `).trimEnd()}function Wa(t,e,s){let n=new Set;for(let i of [...t,...e,...s])n.add(i.type);return n.size}function Ys(t){if(!t)return [];let e=t.gates;if(e==null)return [];if(Array.isArray(e))return e.map(s=>{if(s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"){let n=s.id;return n.startsWith("^")?n.slice(1):n}return null}).filter(s=>s!==null);if(typeof e=="object")return Object.keys(e).map(s=>s.startsWith("^")?s.slice(1):s);throw new Error(`Invalid gateConfig.gates shape: expected Array or Record, got ${typeof e}`)}var Wp=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,Gp=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"],Jp=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi];function Ja(){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.
522
+ `)[0].trim()||""});return {handled:true,text:JSON.stringify({query:i,count:l.length,matches:l},null,2)}}if(n==="get"){if(!r)return {handled:true,text:JSON.stringify({error:"Tag name required for get action"})};if(a.core?.[r]){let l=a.core[r];return {handled:true,text:JSON.stringify({tag:r,category:"core",description:l.description,color:l.color,appliesTo:l["applies-to"],aliases:l.aliases,requiresAspect:l["requires-aspect"]},null,2)}}if(a.project?.[r]){let l=a.project[r];return {handled:true,text:JSON.stringify({tag:r,category:"project",description:l.description,color:l.color,appliesTo:l["applies-to"],aliases:l.aliases,requiresAspect:l["requires-aspect"]},null,2)}}let c=a.suggested?.find(l=>l.tag===r);return c?{handled:true,text:JSON.stringify({tag:r,category:"suggested",reason:c.reason,proposedBy:c["proposed-by"],proposedAt:c["proposed-at"],appliesTo:c["applies-to"],exampleSymbols:c["example-symbols"],status:"pending approval"},null,2)}:{handled:true,text:JSON.stringify({error:`Tag "${r}" not found`,suggestion:'Use paradigm_tags with action "list" to see available tags'})}}return {handled:true,text:JSON.stringify({error:`Unknown action: ${n}`})}}case "paradigm_tags_suggest":{let{tag:n,description:i,reason:r,appliesTo:o,exampleSymbols:a}=e,c=Ca(s.rootDir);if(!c)return {handled:true,text:JSON.stringify({error:"Tag bank not found",suggestion:"Create .paradigm/tags.yaml first"})};if(c.core?.[n]||c.project?.[n])return {handled:true,text:JSON.stringify({error:`Tag "${n}" already exists`,existing:c.core?.[n]?"core":"project"})};if(c.suggested?.some(d=>d.tag===n))return {handled:true,text:JSON.stringify({error:`Tag "${n}" is already in the suggested queue`,status:"pending approval"})};let l={tag:n,"proposed-by":"claude","proposed-at":new Date().toISOString(),reason:r,"applies-to":o||["#"],"example-symbols":a};return c.suggested||(c.suggested=[]),c.suggested.push(l),Kd(s.rootDir,c),{handled:true,text:JSON.stringify({success:true,tag:n,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:n}=e,i=n.startsWith("~")?n:`~${n}`,r=h$1(s.index,i);if(!r)return {handled:true,text:JSON.stringify({error:`Aspect "${i}" not found`,suggestion:"Use paradigm_search to find available aspects"})};if(r.type!=="aspect")return {handled:true,text:JSON.stringify({error:`Symbol "${i}" is not an aspect (type: ${r.type})`,note:"Only ~ symbols are aspects"})};let o=r.anchors||[],a=r.filePath?H.isAbsolute(r.filePath)?r.filePath:H.resolve(s.rootDir,r.filePath):s.rootDir,c=r.filePath?H.dirname(a):s.rootDir,l=[];for(let f of o){let b=fa$1(f.path,c,s.rootDir),h=b.resolvedPath,w=b.exists,v;if(w)try{let x=E.readFileSync(h,"utf-8").split(`
523
+ `);typeof f.lines=="number"?v=1:Array.isArray(f.lines)&&f.lines.length===2?v=f.lines[1]-f.lines[0]+1:Array.isArray(f.lines)&&(v=f.lines.length);}catch{}let k;w||ga$1(f.path,c,s.rootDir).mismatch&&(k="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."),l.push({path:f.path,lines:f.raw.split(":")[1]||"full file",exists:w,lineCount:v,...k?{resolution_hint:k}:{}});}let d=o.length>0&&l.every(f=>f.exists),p=r.appliesTo||[],u=n$1(s.index),g=[],m=[];for(let f of u)for(let b of p)if(new RegExp("^"+b.replace(/\*/g,".*").replace(/\?/g,".")+"$").test(f.symbol)){g.push(f.symbol),(f.data?.aspects?.includes?.(i)||f.data?.aspects?.includes?.(n))&&m.push(f.symbol);break}let y=g.filter(f=>!m.includes(f));return {handled:true,text:JSON.stringify({aspect:i,valid:d,description:r.description,enforcement:r.enforcement,anchors:l,coverage:{appliesTo:p,matchingSymbols:g.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"]:[],...l.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:d?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$1();var he=class extends Error{code="WRITE_VERIFICATION_FAILED";constructor(e="write verification failed"){super(e),this.name="WriteVerificationError";}},Qd=".paradigm-install-key",Xd="paradigm-v5.38.0-hmac-fallback-key",Ie=null;function Zd(){if(Ie)return Ie;try{let t=ua.homedir(),e=H.join(t,Qd);if(E.existsSync(e)){let n=E.readFileSync(e,"utf-8").trim();if(/^[0-9a-f]{64}$/i.test(n))return Ie=Buffer.from(n,"hex"),Ie}let s=Ft.randomBytes(32);try{E.writeFileSync(e,s.toString("hex"),{encoding:"utf-8",mode:384});}catch{}return Ie=s,Ie}catch{return Ie=Buffer.from(Xd),Ie}}function ep(t){let e=Ft.createHmac("sha256",Zd());return e.update(t),e.digest("hex").slice(0,12)}function tp(t,e){let s=H.dirname(t),n=`.${H.basename(t)}.${process.pid}.${Date.now()}.${Ft.randomBytes(4).toString("hex")}.tmp`,i=H.join(s,n);try{E.writeFileSync(i,e,{encoding:"utf-8"}),E.renameSync(i,t);}catch(r){try{E.unlinkSync(i);}catch{}throw r}}async function Nt(t,e,s){tp(t,e);let n;try{n=E.readFileSync(t,"utf-8");}catch{throw a.component("#write-and-confirm").error("read-back failed after atomic write",{stage:"read-back"}),new he("write verification failed (read-back error)")}let i=false;try{i=s(n);}catch{throw a.component("#write-and-confirm").error("verify callback threw",{stage:"verify-callback",strict:H$2()}),new he("write verification failed (verify callback error)")}if(!i)throw a.component("#write-and-confirm").error("verify callback returned false",{stage:"verify-callback-false",strict:H$2()}),new he("write verification failed");let r=Buffer.byteLength(n,"utf-8"),o=ep(n);return {written:true,path:t,hashHint:o,bytes:r}}b$1();var np=["#","$","^","!","~"];function L(t){return t.length>1&&np.includes(t[0])?t.slice(1):t}function M(t,e){let s=L(t);return `${e}${s}`}function pe(t,e){let s=H.isAbsolute(t)?t:H.resolve(e,t);return s.endsWith(".purpose")?s:H.join(s,".purpose")}function Y(t){if(!E.existsSync(t))return {};let e=a$9(t);if(!e.data)throw new Error(`Failed to parse ${t}: ${e.errors.join(", ")}`);return e.data}function $e(t,e){let s=H.dirname(t);E.existsSync(s)||E.mkdirSync(s,{recursive:true});let n=b$b(e);E.writeFileSync(t,n,"utf8");}async function Fn(t,e,s,n="purpose.yaml"){let i=H.dirname(t);E.existsSync(i)||E.mkdirSync(i,{recursive:true});let r=b$b(e);try{return await Nt(t,r,o=>{let a=a$9(t);if(!a.data)return !1;try{return s(a.data)}catch{return !1}})}catch(o){throw o instanceof he?(a.component("#purpose-writer").error("purpose write verification failed",{surface:n,stage:"writeAndConfirm"}),new Error(`purpose write verification failed (${n})`)):o}}function Ge(t){if(!t)return {};if(!Array.isArray(t))return t;let e={};for(let s of t){let{id:n,...i}=s;e[n]=i;}return e}function it(t){if(!t)return {};if(!Array.isArray(t))return t;let e={};for(let s of t)e[s.name]={description:s.description,steps:s.steps};return e}function rt(t,e){if(!e||e.length===0)return t;if(!t||t.length===0)return e;let s=new Set(t);for(let n of e)s.add(n);return Array.from(s)}var sp={"#":"#","^":"^","!":"!",$:"$","~":"~"};async function Ta(t,e,s,n){let i=sp[n];if(!i)throw new Error(`Invalid symbol type: ${n}. Expected one of: # ^ ! $ ~`);let r=L(e),o=L(s),a=M(r,i),c=M(o,i),l=await c$4(t),d=[];for(let p of l){let u=Y(p),g=false,y={"#":"components","^":"gates","!":"signals",$:"flows","~":"aspects"}[i];if(y&&y!=="flows"){let f=u[y];f&&!Array.isArray(f)&&r in f&&(f[o]=f[r],delete f[r],g=true);}if(i==="#")for(let f of ["features","components"]){let b=u[f];b&&!Array.isArray(b)&&r in b&&(b[o]=b[r],delete b[r],g=true);}i==="$"&&u.flows&&!Array.isArray(u.flows)&&r in u.flows&&(u.flows[o]=u.flows[r],delete u.flows[r],g=true);for(let f of ["features","components"]){let b=Ge(u[f]);for(let[h,w]of Object.entries(b))g=ip(w,a,c)||g;g&&Object.keys(b).length>0&&(u[f]=b);}if(u.flows){let f=it(u.flows);for(let[b,h]of Object.entries(f)){if(h.gates){let w=h.gates.indexOf(a);w!==-1&&(h.gates[w]=c,g=true);}if(h.signals){let w=h.signals.indexOf(a);w!==-1&&(h.signals[w]=c,g=true);}if(h.components){let w=h.components.indexOf(a);w!==-1&&(h.components[w]=c,g=true);}if(h.steps)for(let w of h.steps)typeof w=="object"&&"component"in w&&(w.component===a||w.component===r)&&(w.component=i==="#"?o:c,g=true);}g&&(u.flows=f);}if(u.gates){for(let[f,b]of Object.entries(u.gates))if(b.signals){let h=b.signals.indexOf(a);h!==-1&&(b.signals[h]=c,g=true);}}if(u.aspects){for(let[f,b]of Object.entries(u.aspects))if(b["applies-to"]){let h=b["applies-to"].indexOf(a);h!==-1&&(b["applies-to"][h]=c,g=true);}}g&&($e(p,u),d.push(p));}return d}function ip(t,e,s){let n=false,i=["signals","gates","flows","components","states"];for(let r of i){let o=t[r];if(o){let a=o.indexOf(e);a!==-1&&(o[a]=s,n=true);}}if(t.aspects&&Array.isArray(t.aspects)){let r=t.aspects.indexOf(e);r!==-1&&(t.aspects[r]=s,n=true);}return n}b$1();function Nn(t){let e=H.join(t,"portal.yaml"),s=I$1(e);if(s.status==="missing")return {data:{version:"1.0.0",gates:{}},filePath:e};if(s.status==="unparseable"||s.status==="invalid")throw a.component("#portal-writer").error("portal.yaml unparseable on read",{errorClass:s.errorClass}),new Error(`portal.yaml unparseable (${s.errorClass}). Refusing to overwrite. Run 'paradigm doctor' for line-specific details.`);return {data:s.data||{version:"1.0.0",gates:{}},filePath:e}}async function Da(t,e){let{data:s,filePath:n}=Nn(t);if(!s.gates||Array.isArray(s.gates)){let a=s.gates;if(s.gates={},Array.isArray(a)&&a.length>0){for(let c of a)if(c&&typeof c=="object"&&"id"in c){let l=L(c.id);s.gates[l]=c;}}}let i=L(e.id),r=s.gates[i]||{};r.description=e.description,e.type!==void 0&&(r.type=e.type),e.location!==void 0&&(r.location=e.location),e.requires!==void 0&&(r.requires=e.requires),e.check!==void 0&&(r.check=e.check),e.grants!==void 0&&(r.grants=e.grants),e.emits!==void 0&&(r.emits=e.emits),e.prizes!==void 0&&(r.prizes=e.prizes),r.prizes||(r.prizes=[]),s.gates[i]=r;let o=Ae.dump(s,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});try{return await Nt(n,o,a=>{let c;try{c=Ae.load(a);}catch{return !1}let l=c?.gates;return !l||Array.isArray(l)?!1:!!l[i]})}catch(a$1){throw a$1 instanceof he?(a.component("#portal-writer").error("portal_add_gate write verification failed",{stage:"writeAndConfirm"}),new Error("portal_add_gate write verification failed")):a$1}}async function Oa(t,e){let{data:s,filePath:n}=Nn(t);(!s.routes||Array.isArray(s.routes))&&(s.routes={});let i=`${e.method} ${e.route}`,r=e.gates.map(a=>`^${L(a)}`);s.routes[i]=r;let o=Ae.dump(s,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});try{return await Nt(n,o,a=>{let c;try{c=Ae.load(a);}catch{return !1}let l=c?.routes;return !l||Array.isArray(l)?!1:!!l[i]})}catch(a$1){throw a$1 instanceof he?(a.component("#portal-writer").error("portal_add_route write verification failed",{stage:"writeAndConfirm"}),new Error("portal_add_route write verification failed")):a$1}}var rp={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}},op={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}},ap={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}},cp={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}},lp={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}},dp={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}},pp={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}},up={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}},gp={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}},mp={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}},fp={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}},yp={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}},hp={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 $a(){return [rp,op,ap,cp,lp,dp,pp,up,gp,mp,fp,yp,hp]}async function Fa(t,e,s,n){switch(t){case "paradigm_purpose_init":return bp(e,s,n);case "paradigm_purpose_add_component":return wp(e,s,n);case "paradigm_purpose_add_aspect":return vp(e,s,n);case "paradigm_purpose_add_signal":return kp(e,s,n);case "paradigm_purpose_add_flow":return Sp(e,s,n);case "paradigm_purpose_add_gate":return _p(e,s,n);case "paradigm_purpose_add_state":return xp(e,s,n);case "paradigm_purpose_link":return Cp(e,s,n);case "paradigm_purpose_remove":return Rp(e,s,n);case "paradigm_purpose_rename":return Pp(e,s,n);case "paradigm_portal_add_gate":return jp(e,s,n);case "paradigm_portal_add_route":return Tp(e,s,n);case "paradigm_purpose_validate":return Dp(e,s);default:return {handled:false,text:""}}}function Z(t){return {handled:true,text:JSON.stringify(t,null,2)}}function X(t){return {handled:true,text:JSON.stringify({error:t},null,2)}}async function bp(t,e,s){let{purposeFile:n,name:i,description:r,context:o,version:a}=t,c=pe(n,e.rootDir),l=Y(c);return a!==void 0?l.version=a:l.version||(l.version="1.0.0"),r!==void 0?l.description=r:l.description||(l.description=i),o!==void 0&&(l.context=o),$e(c,l),await s(),Z({action:"purpose_init",file:c,metadata:{name:i,description:l.description,version:l.version}})}async function wp(t,e,s){let{purposeFile:n,id:i,description:r,section:o="components",file:a,status:c,endpoints:l,tests:d,flows:p,gates:u,signals:g,aspects:m,components:y,type:f,parent:b}=t,h=pe(n,e.rootDir),w=Y(h),v=L(i),k=o,S=Ge(w[k]),x=S[v]||{description:""};x.description=r,a!==void 0&&(x.file=a),c!==void 0&&(x.status=c),l!==void 0&&(x.endpoints=l),d!==void 0&&(x.tests=d),p!==void 0&&(x.flows=p.map(_=>M(_,"$"))),u!==void 0&&(x.gates=u.map(_=>M(_,"^"))),g!==void 0&&(x.signals=g.map(_=>M(_,"!"))),m!==void 0&&(x.aspects=m.map(_=>M(_,"~"))),y!==void 0&&(x.components=y.map(_=>M(_,"#"))),f!==void 0&&(x.type=f),b!==void 0&&(x.parent=M(b,"#")),S[v]=x,w[k]=S;let C=await Fn(h,w,_=>{let R=_[k];return !R||typeof R!="object"||Array.isArray(R)?!1:v in R},k);return await s(),Z({action:"add_component",file:C.path,section:k,id:v,symbol:`#${v}`,written:C.written,hashHint:C.hashHint,bytes:C.bytes})}async function vp(t,e,s){let{purposeFile:n,id:i,description:r,anchors:o,tags:a,appliesTo:c,enforcement:l}=t;if(!o||o.length===0)return X('Aspects (~) REQUIRE at least one code anchor. Provide anchors like ["src/middleware/audit.ts:15-35"].');let d=/^[^\s:]+:\d+(-\d+)?(,\d+)*$/;for(let f of o)if(!d.test(f))return X(`Invalid anchor format: "${f}". Expected format: "file.ts:15", "file.ts:15-20", or "file.ts:15,25,30".`);let p=pe(n,e.rootDir),u=H.dirname(p);for(let f of o){let b=f.replace(/:.*$/,""),h=H.resolve(u,b);if(!E.existsSync(h)){let w=H.resolve(e.rootDir,b);if(E.existsSync(w)){let v=H.relative(u,w),k=o.indexOf(f);o[k]=f.replace(b,v);}else return X(`Anchor file not found: "${b}". Anchors must be relative to the .purpose file directory (${u}).`)}}let g=Y(p);(!g.aspects||Array.isArray(g.aspects))&&(g.aspects={});let m=L(i);g.aspects[m]={description:r,anchors:o,...a&&{tags:a},...c&&{"applies-to":c},...l&&{enforcement:l}},$e(p,g);let y=Y(p).aspects;return !y||Array.isArray(y)||!y[m]?X(`add_aspect write verification failed: aspect "${m}" not found in ${p} after write.`):(await s(),Z({action:"add_aspect",file:p,id:m,symbol:`~${m}`,anchors:o}))}async function kp(t,e,s){let{purposeFile:n,id:i,description:r,category:o,severity:a,emitters:c,related:l,data:d}=t,p=pe(n,e.rootDir),u=Y(p);(!u.signals||Array.isArray(u.signals))&&(u.signals={});let g=L(i);u.signals[g]={description:r,...o&&{category:o},...a&&{severity:a},...c&&{emitters:c.map(y=>M(y,"#"))},...l&&{related:l},...d&&{data:d}},$e(p,u);let m=Y(p).signals;return !m||Array.isArray(m)||!m[g]?X(`add_signal write verification failed: signal "${g}" not found in ${p} after write.`):(await s(),Z({action:"add_signal",file:p,id:g,symbol:`!${g}`}))}async function Sp(t,e,s){let{purposeFile:n,id:i,description:r,gates:o,signals:a,components:c,steps:l}=t,d=pe(n,e.rootDir),p=Y(d),u=it(p.flows),g=L(i),m={description:r,...o&&{gates:o.map(f=>M(f,"^"))},...a&&{signals:a.map(f=>M(f,"!"))},...c&&{components:c.map(f=>M(f,"#"))},...l&&{steps:l}};return u[g]=m,p.flows=u,$e(d,p),it(Y(d).flows)[g]?(await s(),Z({action:"add_flow",file:d,id:g,symbol:`$${g}`})):X(`add_flow write verification failed: flow "${g}" not found in ${d} after write.`)}async function _p(t,e,s){let{purposeFile:n,id:i,description:r,requires:o,keys:a,signals:c}=t,l=pe(n,e.rootDir),d=Y(l);(!d.gates||Array.isArray(d.gates))&&(d.gates={});let p=L(i);d.gates[p]={description:r,...o&&{requires:o},...a&&{keys:a},...c&&{signals:c.map(g=>M(g,"!"))}},$e(l,d);let u=Y(l).gates;return !u||Array.isArray(u)||!u[p]?X(`add_gate write verification failed: gate "${p}" not found in ${l} after write.`):(await s(),Z({action:"add_gate",file:l,id:p,symbol:`^${p}`}))}async function xp(t,e,s){let{purposeFile:n,id:i,description:r,type:o,default:a,properties:c}=t,l=pe(n,e.rootDir),d=Y(l);(!d.states||Array.isArray(d.states))&&(d.states={});let p=L(i),u={description:r};o!==void 0&&(u.type=o),a!==void 0&&(u.default=a),c!==void 0&&(u.properties=c),d.states[p]=u,$e(l,d);let g=Y(l).states;return !g||Array.isArray(g)||!g[p]?X(`add_state write verification failed: state "${p}" not found in ${l} after write.`):(await s(),Z({action:"add_state",file:l,id:p}))}async function Cp(t,e,s){let{purposeFile:n,componentId:i,section:r,signals:o,aspects:a,gates:c,flows:l,components:d}=t,p=pe(n,e.rootDir),u=Y(p),g=L(i),m=r;if(!m){let w=Ge(u.components),v=Ge(u.features);if(g in w)m="components";else if(g in v)m="features";else return X(`Component "${g}" not found in components or features. Specify section explicitly.`)}let y=Ge(u[m]);if(!(g in y))return X(`Component "${g}" not found in ${m} section.`);let f=y[g];o&&(f.signals=rt(f.signals,o.map(w=>M(w,"!")))),c&&(f.gates=rt(f.gates,c.map(w=>M(w,"^")))),l&&(f.flows=rt(f.flows,l.map(w=>M(w,"$")))),d&&(f.components=rt(f.components,d.map(w=>M(w,"#")))),a&&(f.aspects=rt(f.aspects,a.map(w=>M(w,"~")))),y[g]=f,u[m]=y;let b=await Fn(p,u,w=>{let v=w[m];return !v||typeof v!="object"||Array.isArray(v)?!1:g in v},m);await s();let h=[];return o&&h.push(`signals: ${o.join(", ")}`),a&&h.push(`aspects: ${a.join(", ")}`),c&&h.push(`gates: ${c.join(", ")}`),l&&h.push(`flows: ${l.join(", ")}`),d&&h.push(`components: ${d.join(", ")}`),Z({action:"link",file:b.path,componentId:g,section:m,added:h,written:b.written,hashHint:b.hashHint,bytes:b.bytes})}async function Rp(t,e,s){let{purposeFile:n,section:i,id:r}=t,o=pe(n,e.rootDir),a=Y(o),c=L(r);if(i==="flows"){let d=it(a.flows);if(!(c in d))return X(`Flow "${c}" not found in flows section.`);delete d[c],a.flows=d;}else if(i==="components"||i==="features"){let d=Ge(a[i]);if(!(c in d))return X(`"${c}" not found in ${i} section.`);delete d[c],a[i]=d;}else {let d=a[i];if(!d||!(c in d))return X(`"${c}" not found in ${i} section.`);delete d[c];}let l=await Fn(o,a,d=>{if(i==="flows"){let u=it(d.flows);return !(c in u)}let p=d[i];return !p||typeof p!="object"||Array.isArray(p)?!0:!(c in p)},i);return await s(),Z({action:"remove",file:l.path,section:i,id:c,written:l.written,hashHint:l.hashHint,bytes:l.bytes})}async function Pp(t,e,s){let{oldId:n,newId:i,symbolType:r}=t,o=await Ta(e.rootDir,n,i,r);return await s(),Z({action:"rename",oldSymbol:`${r}${L(n)}`,newSymbol:`${r}${L(i)}`,filesModified:o.length,files:o})}async function jp(t,e,s){let{id:n,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:p}=t,u=await Da(e.rootDir,{id:n,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:p});await s();let g=L(n);return Z({action:"portal_add_gate",file:u.path,id:g,symbol:`^${g}`,written:u.written,hashHint:u.hashHint,bytes:u.bytes})}async function Tp(t,e,s){let{route:n,method:i,gates:r}=t,o=await Oa(e.rootDir,{route:n,method:i,gates:r});return await s(),Z({action:"portal_add_route",file:o.path,route:`${i} ${n}`,gates:r,written:o.written,hashHint:o.hashHint,bytes:o.bytes})}var Ap=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi;function Ia(t,e){let s=[];function n(r,o){if(typeof r=="string"){let a=r.match(Ap);if(a)for(let c of a)s.push({type:"warning",message:`Clarification needed: ${c}`,path:o});}}n(t.description,"description");let i=[{key:"components",items:t.components},{key:"features",items:t.features},{key:"gates",items:t.gates},{key:"signals",items:t.signals},{key:"aspects",items:t.aspects}];for(let r of i)if(r.items&&typeof r.items=="object")for(let[o,a]of Object.entries(r.items))a&&typeof a.description=="string"&&n(a.description,`${r.key}.${o}.description`);if(t.flows&&typeof t.flows=="object"){let r=Array.isArray(t.flows)?[]:Object.entries(t.flows);for(let[o,a]of r)a&&typeof a.description=="string"&&n(a.description,`flows.${o}.description`);}return s}async function Dp(t,e){let{purposeFile:s,includePortal:n=true}=t,i=[];if(s){let a=pe(s,e.rootDir),c=a$9(a);if(!c.data)i.push({file:a,valid:false,issues:c.errors.map(l=>({type:"error",message:l}))});else {let l=d$9(c.data,a);if(c.data.aspects)for(let[p,u]of Object.entries(c.data.aspects))(!u.anchors||u.anchors.length===0)&&(l.issues.push({type:"error",message:`Aspect "${p}" is missing required anchors`,path:`aspects.${p}`}),l.valid=false);let d=Ia(c.data);l.issues.push(...d),i.push({file:a,valid:l.valid,issues:l.issues});}}else {let a=await c$4(e.rootDir);for(let c of a){let l=a$9(c);if(!l.data){i.push({file:c,valid:false,issues:l.errors.map(u=>({type:"error",message:u}))});continue}let d=d$9(l.data,c);if(l.data.aspects)for(let[u,g]of Object.entries(l.data.aspects))(!g.anchors||g.anchors.length===0)&&(d.issues.push({type:"error",message:`Aspect "${u}" is missing required anchors`,path:`aspects.${u}`}),d.valid=false);let p=Ia(l.data);d.issues.push(...p),i.push({file:c,valid:d.valid,issues:d.issues});}}if(n){let{data:a,filePath:c}=Nn(e.rootDir),l=[];if(a.gates)for(let[d,p]of Object.entries(a.gates))p.description||l.push({type:"warning",message:`Gate "${d}" has no description`,path:`gates.${d}`}),p.prizes||l.push({type:"warning",message:`Gate "${d}" is missing prizes array (v2 requirement)`,path:`gates.${d}`});l.length>0&&i.push({file:c,valid:l.every(d=>d.type!=="error"),issues:l});}let r=i.reduce((a,c)=>a+c.issues.length,0),o=i.every(a=>a.valid);return Z({action:"validate",valid:o,totalFiles:i.length,totalIssues:r,results:i})}var za=[{id:"explore-before-implement",name:"Explore Before Implementing",description:"Call ripple/navigate/search before modifying existing symbols to understand impact",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple","paradigm_navigate","paradigm_search","paradigm_related"]}},enabled:true},{id:"ripple-before-modify",name:"Ripple Before Modifying",description:"Run ripple analysis before modifying symbols with dependents",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple"]}},enabled:true},{id:"check-fragility",name:"Check Fragility",description:"Check history fragility for symbols before modifying frequently-broken code",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_history_fragility"]}},enabled:true},{id:"wisdom-before-implement",name:"Check Team Wisdom",description:"Check team wisdom (preferences, antipatterns, decisions) before implementing",category:"collaboration",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_wisdom_context","paradigm_wisdom_expert"]}},enabled:true},{id:"verify-before-done",name:"Verify Before Done",description:"Run postflight compliance checks before finishing a session",category:"verification",trigger:"on-stop",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight"]}},enabled:true},{id:"postflight-compliance",name:"Postflight Compliance",description:"Ensure postflight checks pass without errors before finishing",category:"verification",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight","paradigm_reindex"]}},enabled:true},{id:"test-new-components",name:"Test New Components",description:"New components should have associated tests or test plan documented",category:"testing",trigger:"postflight",severity:"advisory",check:{type:"tests-exist",params:{patterns:["**/*.test.*","**/*.spec.*","**/tests/**"]}},enabled:true},{id:"purpose-coverage",name:"Purpose File Coverage",description:"All modified source directories should have .purpose file coverage",category:"documentation",trigger:"postflight",severity:"warn",check:{type:"file-exists",params:{patterns:["**/.purpose"]}},enabled:true},{id:"record-lore-for-significant",name:"Record Lore for Significant Changes",description:"Sessions modifying 3+ files should record a lore entry",category:"documentation",trigger:"on-stop",severity:"warn",check:{type:"lore-recorded",params:{}},enabled:true},{id:"confidence-on-decisions",name:"Confidence on Decisions",description:"When recording lore, include a confidence score (0.0-1.0) to enable calibration tracking over time",category:"documentation",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_lore_record"]}},enabled:true},{id:"gates-for-routes",name:"Gates for Routes",description:"API routes should have corresponding gate declarations in portal.yaml",category:"security",trigger:"postflight",severity:"warn",check:{type:"gates-declared",params:{requireRoutes:true}},enabled:true},{id:"university-content-valid",name:"University Content Valid",description:"Validate university content integrity when files in symbol-covered areas change",category:"quality",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_validate"]}},enabled:true},{id:"university-onboarded",name:"University Onboarding",description:"Call paradigm_university_onboard at session start for project-specific learning content",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_onboard"]}},enabled:false},{id:"orchestration-required",name:"Orchestrate Complex Tasks",description:"Tasks affecting 3+ files or touching security symbols should use paradigm_orchestrate_inline to determine which agents are needed. Ensures security review, test coverage, and documentation.",category:"collaboration",trigger:"preflight",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_orchestrate_inline"]}},enabled:true},{id:"agent-coverage-validated",name:"Validate Agent Involvement",description:"After completing work, verify that agents with relevant expertise were consulted. Check nominations that were surfaced but not acted on.",category:"collaboration",trigger:"postflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ambient_nominations","paradigm_agent_list"]}},enabled:true},{id:"hot-mode-incident",name:"Incident Response Acknowledgment",description:"During incident response, orchestration enforcement is waived. But a post-incident lore entry is required and a postflight review should be scheduled.",category:"collaboration",trigger:"on-stop",severity:"advisory",check:{type:"lore-recorded"},enabled:true}],Np=30*1e3,Ys=new Map;function re(t){let e=H.resolve(t),s=Ys.get(e);if(s&&Date.now()-s.loadedAt<Np)return s.habits;let n=Ep(e);return Ys.set(e,{habits:n,loadedAt:Date.now()}),n}function Ep(t){let e=new Map;for(let a of za)e.set(a.id,{...a});let s=process.env.HOME||process.env.USERPROFILE||"~",n=La(H.join(s,".paradigm","habits.yaml"));n&&Ma(e,n);let i=Wa(H.join(s,".paradigm","habits"));for(let a of i)e.set(a.id,a);let r=La(H.join(t,".paradigm","habits.yaml"));r&&Ma(e,r);let o=Wa(H.join(t,".paradigm","habits"));for(let a of o)e.set(a.id,a);return Array.from(e.values())}function La(t){if(!E.existsSync(t))return null;try{let e=E.readFileSync(t,"utf8");return Ae.load(e)}catch{return null}}function Ma(t,e){if(e.habits)for(let s of e.habits)t.set(s.id,{...s});if(e.overrides)for(let[s,n]of Object.entries(e.overrides)){let i=t.get(s);i&&(n.severity!==void 0&&(i.severity=n.severity),n.enabled!==void 0&&(i.enabled=n.enabled));}}function Hp(t,e){return t.filter(s=>s.enabled&&s.trigger===e)}function Vs(t){Ys.delete(H.resolve(t));}function Wa(t){if(!E.existsSync(t))return [];try{let e=E.readdirSync(t).filter(n=>n.endsWith(".habit")).sort(),s=[];for(let n of e)try{let i=E.readFileSync(H.join(t,n),"utf8"),r=Ae.load(i);r?.id&&r?.name&&s.push(r);}catch{}return s}catch{return []}}var Ga=["discovery","verification","testing","documentation","collaboration","security"],Ja=["preflight","postflight","on-commit","on-stop"],Ua=["advisory","warn","block"],Ba=["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"],qp=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Ks(t){let e=[];if(t.id||e.push("Missing required field: id"),t.name||e.push("Missing required field: name"),t.description||e.push("Missing required field: description"),t.category||e.push("Missing required field: category"),t.trigger||e.push("Missing required field: trigger"),t.severity||e.push("Missing required field: severity"),t.check||e.push("Missing required field: check"),(t.enabled===void 0||t.enabled===null)&&e.push("Missing required field: enabled"),t.id&&!qp.test(t.id)&&e.push(`Invalid id format: "${t.id}" \u2014 must be kebab-case (lowercase, hyphens only)`),t.category&&!Ga.includes(t.category)&&e.push(`Invalid category: "${t.category}" \u2014 must be one of: ${Ga.join(", ")}`),t.trigger&&!Ja.includes(t.trigger)&&e.push(`Invalid trigger: "${t.trigger}" \u2014 must be one of: ${Ja.join(", ")}`),t.severity&&!Ua.includes(t.severity)&&e.push(`Invalid severity: "${t.severity}" \u2014 must be one of: ${Ua.join(", ")}`),t.check){Ba.includes(t.check.type)||e.push(`Invalid check.type: "${t.check.type}" \u2014 must be one of: ${Ba.join(", ")}`);let s=t.check.params||{};switch(t.check.type){case "tool-called":(!s.tools||!Array.isArray(s.tools)||s.tools.length===0)&&e.push('check.type "tool-called" requires check.params.tools[] (non-empty array)');break;case "file-exists":case "file-modified":(!s.patterns||!Array.isArray(s.patterns)||s.patterns.length===0)&&e.push(`check.type "${t.check.type}" requires check.params.patterns[] (non-empty array)`);break;case "commit-message-format":(!s.messagePatterns||!Array.isArray(s.messagePatterns)||s.messagePatterns.length===0)&&e.push('check.type "commit-message-format" requires check.params.messagePatterns[] (non-empty array)');break}}return {valid:e.length===0,errors:e}}var Lp=new Set(za.map(t=>t.id));function Gn(t){return Lp.has(t)}function Qs(t,e,s="project"){let n=s==="global"?H.join(process.env.HOME||process.env.USERPROFILE||"~",".paradigm","habits"):H.join(t,".paradigm","habits");E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=H.join(n,`${e.id}.habit`),r=Ae.dump(e,{lineWidth:120,noRefs:true});return E.writeFileSync(i,r,"utf8"),Vs(t),i}function Ya(t,e){if(Gn(e))return {removed:false,reason:`"${e}" is a seed habit and cannot be removed. Use overrides in habits.yaml to disable it.`};let s=H.join(t,".paradigm","habits",`${e}.habit`);if(E.existsSync(s))return E.unlinkSync(s),Vs(t),{removed:true};let n=process.env.HOME||process.env.USERPROFILE||"~",i=H.join(n,".paradigm","habits",`${e}.habit`);return E.existsSync(i)?(E.unlinkSync(i),Vs(t),{removed:true}):{removed:false,reason:`No .habit file found for "${e}". It may be defined in habits.yaml \u2014 edit that file directly.`}}var Xs=0;function Lt(t,e,s,n,i){let r=Hp(t,e);n&&(r=r.filter(u=>!u.platforms||u.platforms.includes(n)));let o=0;if(i)try{let{isGraduated:u}=(Wn(),d$a(qa)),g=r.length;r=r.filter(m=>!u(i,m.id)),o=g-r.length;}catch{}Xs=o;let a=r.map(u=>Mp(u,s)),c=a.filter(u=>u.result==="followed").length,l=a.filter(u=>u.result==="skipped").length,d=a.filter(u=>u.result==="partial").length,p=a.filter(u=>u.result==="skipped"&&u.habit.severity==="block").length;return {trigger:e,evaluations:a,summary:{total:a.length,followed:c,skipped:l,partial:d,blockingViolations:p},blocksCompletion:p>0}}function Mt(t){return {toolsCalled:t.toolsCalled||[],filesModified:t.filesModified||[],symbolsTouched:t.symbolsTouched||[],loreRecorded:t.loreRecorded||false,hasPortalRoutes:t.hasPortalRoutes||false,taskAddsRoutes:t.taskAddsRoutes||false,taskDescription:t.taskDescription,gitClean:t.gitClean}}function Mp(t,e){switch(t.check.type){case "tool-called":return Wp(t,e);case "file-exists":return Gp(t,e);case "file-modified":return Yp(t,e);case "lore-recorded":return Jp(t,e);case "symbols-registered":return Up(t,e);case "gates-declared":return Bp(t,e);case "tests-exist":return zp(t,e);case "git-clean":return Vp(t,e);case "commit-message-format":return Kp(t,e);case "flow-coverage":return Qp(t,e);case "context-checked":return Xp(t,e);case "aspect-anchored":return Zp(t,e);default:return {habit:t,result:"partial",reason:`Unknown check: ${t.check.type}`}}}function Wp(t,e){let s=t.check.params.tools||[];if(s.length===0)return {habit:t,result:"followed",reason:"No tools required"};let n=s.filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Called: ${n.join(", ")}`,evidence:n}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:t,result:"followed",reason:"No modifications, habit not applicable"}:{habit:t,result:"skipped",reason:`None of [${s.join(", ")}] were called before modifying code`}}function Gp(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};if(e.filesModified.some(i=>i.endsWith(".purpose")||i.includes(".paradigm/")))return {habit:t,result:"followed",reason:"Purpose files updated"};let n=e.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".yml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/"));return n.length===0?{habit:t,result:"followed",reason:"Only non-source files modified"}:{habit:t,result:"skipped",reason:`${n.length} source file(s) without .purpose updates`,evidence:n.slice(0,5)}}function Jp(t,e){let s=e.filesModified.filter(n=>!n.endsWith(".md")&&!n.endsWith(".json")&&!n.endsWith(".yaml")&&!n.endsWith(".yml")&&!n.endsWith(".lock")&&!n.endsWith(".purpose")&&!n.includes(".paradigm/"));return s.length<3?{habit:t,result:"followed",reason:"Session not significant (< 3 source files)"}:e.loreRecorded||e.toolsCalled.includes("paradigm_lore_record")?{habit:t,result:"followed",reason:"Lore recorded"}:{habit:t,result:"skipped",reason:`${s.length} source files modified, no lore entry`,evidence:s.slice(0,5)}}function Up(t,e){if(e.symbolsTouched.length===0)return {habit:t,result:"followed",reason:"No symbols touched"};let n=["paradigm_purpose_add_component","paradigm_purpose_add_signal","paradigm_purpose_add_flow","paradigm_purpose_add_gate","paradigm_purpose_add_aspect","paradigm_purpose_init"].filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Purpose tools called: ${n.join(", ")}`,evidence:n}:{habit:t,result:"partial",reason:`${e.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function Bp(t,e){if(!e.taskAddsRoutes)return {habit:t,result:"followed",reason:"No routes added"};if(e.hasPortalRoutes)return {habit:t,result:"followed",reason:"Portal.yaml has routes"};let n=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Gate tools called: ${n.join(", ")}`,evidence:n}:{habit:t,result:"skipped",reason:"Routes added without gate declarations"}}function zp(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};let s=e.filesModified.filter(i=>i.includes(".test.")||i.includes(".spec.")||i.includes("/tests/")||i.includes("/test/")||i.includes("__tests__"));if(s.length>0)return {habit:t,result:"followed",reason:`Test files: ${s.length}`,evidence:s.slice(0,5)};let n=e.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/")&&!i.includes("node_modules/"));return n.length===0?{habit:t,result:"followed",reason:"No source files to test"}:{habit:t,result:"partial",reason:`${n.length} source file(s), no test files updated`,evidence:n.slice(0,5)}}function Yp(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};let s=t.check.params.patterns||[];if(s.length===0)return {habit:t,result:"followed",reason:"No patterns specified"};if(t.trigger==="on-stop"&&t.severity==="block"){let i=e.filesModified.filter(r=>s.some(o=>r.includes(o)||H.basename(r)===o));return i.length>0?{habit:t,result:"followed",reason:`Matching files: ${i.join(", ")}`,evidence:i}:{habit:t,result:"partial",reason:`None of [${s.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let n=e.filesModified.filter(i=>s.some(r=>i.includes(r)||H.basename(i)===r));return n.length>0?{habit:t,result:"followed",reason:`Matching files: ${n.join(", ")}`,evidence:n}:{habit:t,result:"skipped",reason:`None of [${s.join(", ")}] found in modified files`}}function Vp(t,e){return e.filesModified.length===0?{habit:t,result:"followed",reason:"No files modified"}:t.trigger==="on-stop"?{habit:t,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:e.gitClean===void 0?{habit:t,result:"partial",reason:"Git status not available"}:e.gitClean?{habit:t,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:t,result:"skipped",reason:"Uncommitted changes in working tree"}}function Kp(t,e){if(!e.commitMessage)return {habit:t,result:"followed",reason:"No commit message to check (not a commit trigger)"};let s=t.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],n=s.filter(i=>new RegExp(i,"m").test(e.commitMessage));if(n.length===s.length)return {habit:t,result:"followed",reason:"Commit message matches all required patterns",evidence:n};if(n.length>0){let i=s.filter(r=>!new RegExp(r,"m").test(e.commitMessage));return {habit:t,result:"partial",reason:`Matches ${n.length}/${s.length} patterns. Missing: ${i.join(", ")}`}}return {habit:t,result:"skipped",reason:"Commit message does not match required format patterns"}}function Qp(t,e){let s=e.symbolsTouched.filter(r=>r.startsWith("#"));if(s.length<3)return {habit:t,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(e.hasFlowCoverage)return {habit:t,result:"followed",reason:"Flow coverage exists for multi-component changes"};let i=["paradigm_flow_check","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(r=>e.toolsCalled.includes(r));return i.length>0?{habit:t,result:"followed",reason:`Flow tools called: ${i.join(", ")}`,evidence:i}:{habit:t,result:"skipped",reason:`${s.length} components touched without flow coverage`,evidence:s.slice(0,5)}}function Xp(t,e){let n=(t.check.params.contextTools||["paradigm_session_health","paradigm_session_recover","paradigm_session_checkpoint"]).filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Context tools called: ${n.join(", ")}`,evidence:n}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:t,result:"followed",reason:"No modifications, context check not applicable"}:{habit:t,result:"skipped",reason:"No context/session tools called during session"}}function Zp(t,e){let s=e.symbolsTouched.filter(n=>n.startsWith("~"));return s.length===0?{habit:t,result:"followed",reason:"No aspects touched"}:e.aspectAnchorsValid===true?{habit:t,result:"followed",reason:"Aspect anchors validated and valid"}:e.toolsCalled.includes("paradigm_aspect_check")?{habit:t,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:t,result:"skipped",reason:`${s.length} aspect(s) touched without anchor validation`,evidence:s.slice(0,5)}}var eu={"missing-purpose":t=>`${t.target?`"${t.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":t=>{let e=t.target?`"${t.target}"`:"a .purpose file",s=t.context?.ageHours!=null?` (${t.context.ageHours}h old)`:"";return `The .purpose file at ${e}${s} 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":t=>`${t.target?`"${t.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":t=>`${t.target?`"${t.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: ["!${t.target||"event-name"}"]). `,"undocumented-flow":t=>`${t.target?`"${t.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":t=>`${t.target?`"${t.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":t=>`${t.target?`"${t.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":t=>`${t.target?`"${t.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., ${t.target?t.target.replace(/\.[^.]+$/,".test$&"):"component.test.ts"}).`,"uncovered-route":t=>`${t.target?`"${t.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":t=>`${t.target?`"${t.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":t=>`${t.target?`"${t.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":t=>{let e=t.target?`"${t.target}"`:"a data category",s=t.context?.ring,n=t.context?.boundary;return `${e} is being transmitted across a boundary (${n||"unknown boundary"}) that exceeds its trust ring${s?` (Ring: ${s})`:""}. 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":t=>{let e=t.target?`"${t.target}"`:"the scan index",s=t.context?.ageHours,n=s!=null?` (${s} hours old)`:"";return `${e}${n} 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 tu(t,e){let s=eu[t];return s?s({...e,type:t}):`Unknown check type "${t}" \u2014 no narration template available.`}function Ka(t){let e=[],s=[],n=[];for(let o of t){let a=tu(o.type,o),c=o.severity??"improvement",l={type:o.type,target:o.target,narration:a,severity:c};c==="blocking"?e.push(l):c==="note"?n.push(l):s.push(l);}let i=e.length+s.length+n.length,r=nu(e,s,n);return {gapCount:i,blocking:e,improvement:s,note:n,narrative:r}}function nu(t,e,s){let n=[],i=t.length+e.length+s.length;if(i===0)return "No gaps found. All enforcement checks passed.";if(n.push(`Found ${i} gap${i!==1?"s":""} across ${Va(t,e,s)} check type${Va(t,e,s)!==1?"s":""}.`),n.push(""),t.length>0){n.push(`BLOCKING (${t.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of t)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}if(e.length>0){n.push(`IMPROVEMENTS (${e.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of e)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}if(s.length>0){n.push(`NOTES (${s.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of s)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}return n.join(`
524
+ `).trimEnd()}function Va(t,e,s){let n=new Set;for(let i of [...t,...e,...s])n.add(i.type);return n.size}function Zs(t){if(!t)return [];let e=t.gates;if(e==null)return [];if(Array.isArray(e))return e.map(s=>{if(s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"){let n=s.id;return n.startsWith("^")?n.slice(1):n}return null}).filter(s=>s!==null);if(typeof e=="object")return Object.keys(e).map(s=>s.startsWith("^")?s.slice(1):s);throw new Error(`Invalid gateConfig.gates shape: expected Array or Record, got ${typeof e}`)}var iu=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,ru=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"],ou=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi];function Qa(){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.
441
525
 
442
- 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 Ua(t,e,s){switch(t){case "paradigm_pm_preflight":{let{task:n}=e,i=await Up(n,s),r=JSON.stringify(i,null,2);return o(r.length,t),{text:r,handled:true}}case "paradigm_pm_postflight":{let{filesModified:n,symbolsTouched:i}=e,r=zp(n,i,s),o$1=JSON.stringify(r,null,2);return o(o$1.length,t),{text:o$1,handled:true}}default:return {text:"",handled:false}}}async function Up(t,e){let s=t.toLowerCase(),n=t.match(Wp)||[],i=[...new Set(n)],r=i.map(u=>{let m=j$2(e.index,u),g=m.length>0?m[0]:null;return {symbol:u,exists:!!g,type:g?.type,description:g?.description}}),o=r.filter(u=>u.exists).map(u=>{let m=k(e.index,u.symbol),g=new Set;for(let b of m){let h=k(e.index,b.symbol);for(let w of h)w.symbol!==u.symbol&&!m.find(v=>v.symbol===w.symbol)&&g.add(w.symbol);}let y=m.length+g.size,f="low";return y>10?f="high":y>3&&(f="medium"),{symbol:u.symbol,directDependents:m.length,indirectDependents:g.size,impact:f}}),a={exists:e.gateConfig!==null,gateCount:0,gates:[],routeCount:0};if(e.gateConfig){let u=Ys(e.gateConfig);a.gateCount=u.length,a.gates=u.map(g=>`^${g}`);let m=e.gateConfig.routes;a.routeCount=m&&!Array.isArray(m)&&typeof m=="object"?Object.keys(m).length:0;}let c=Gp.some(u=>s.includes(u)),l=[];r.some(u=>u.exists)&&l.push("ripple-analysis"),c&&l.push("portal-compliance"),i.some(u=>u.startsWith("^"))&&l.push("gate-validation"),i.some(u=>u.startsWith("!"))&&l.push("signal-registration"),l.push("purpose-coverage");let d=null,p=null;try{let u=re(e.rootDir),g=j$1().getStats(),y=[...new Set(g.toolCalls.map(w=>w.toolName))],f=qt({toolsCalled:y,filesModified:[],symbolsTouched:i,loreRecorded:!1,hasPortalRoutes:a.exists&&a.routeCount>0,taskAddsRoutes:c,taskDescription:t}),b=Ht(u,"preflight",f,void 0,e.rootDir);d={total:b.summary.total,followed:b.summary.followed,skipped:b.summary.skipped,partial:b.summary.partial,results:b.evaluations.map(w=>({id:w.habit.id,name:w.habit.name,severity:w.habit.severity,result:w.result,reason:w.reason}))};let h=new Date(Date.now()-720*60*60*1e3).toISOString();p=await le(e.rootDir,{dateFrom:h});}catch{}return {task:t.slice(0,100)+(t.length>100?"...":""),affectedSymbols:r,rippleAnalysis:o,portalStatus:a,taskAddsRoutes:c,requiredChecks:l,recommendations:Bp(r,o,a,c),habits:{evaluation:d,recentCompliance:p?{rate:p.rate,totalEvents:p.total}:null}}}function Bp(t,e,s,n){let i=[],r=t.filter(c=>!c.exists);r.length>0&&i.push(`New symbols detected: ${r.map(c=>c.symbol).join(", ")}. Register in .purpose files after implementation.`);let o=e.filter(c=>c.impact==="high");o.length>0&&i.push(`HIGH IMPACT: ${o.map(c=>c.symbol).join(", ")} \u2014 review all dependents before modifying.`),n&&!s.exists?i.push("Task adds routes but no portal.yaml exists. Create one with appropriate ^gates."):n&&i.push("Task adds routes. Update portal.yaml with gate entries after implementation.");let a=t.filter(c=>c.symbol.startsWith("^")&&!c.exists);return a.length>0&&i.push(`New gates referenced: ${a.map(c=>c.symbol).join(", ")}. Add to portal.yaml.`),i}function zp(t,e,s){let n=[],i$1=s.gateConfig?.routes,r=i$1&&!Array.isArray(i$1)&&typeof i$1=="object"?Object.keys(i$1):[];for(let g of t){let y=H.isAbsolute(g)?g:H.join(s.rootDir,g);if(!E.existsSync(y))continue;let f;try{f=E.readFileSync(y,"utf-8");}catch{continue}for(let b of Jp){b.lastIndex=0;let h;for(;(h=b.exec(f))!==null;){let w=h[2]||h[0];w&&w.startsWith("/")&&(!r.some(k=>k.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===w)&&s.gateConfig?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${w}" in ${H.relative(s.rootDir,y)} not in portal.yaml`,file:H.relative(s.rootDir,y),suggestion:"Add route to portal.yaml with ^gates. Use paradigm_gates_for_route for suggestions."}):!s.gateConfig&&w.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${w}" found but no portal.yaml exists`,file:H.relative(s.rootDir,y),suggestion:"Create portal.yaml to declare gates for API routes."}));}}}for(let g of e)j$2(s.index,g).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${g}" 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=Ys(s.gateConfig);for(let g of e)if(g.startsWith("^")){let y=g.slice(1);o.includes(y)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${g}" referenced but not declared in portal.yaml`,suggestion:`Add ${g} to portal.yaml with description and check expression.`});}let a=i(s.index,"aspect");for(let g of a){let y=g.appliesTo||[];if(y.length!==0){for(let f of y){let b=f.includes("*");for(let h of e){let w=false;if(b?w=new RegExp("^"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(h):w=h===f,w){let v=g.anchors||[];if(v.length===0)n.push({type:"stale-aspect",severity:"warning",message:`Aspect "${g.symbol}" applies to "${h}" but has no code anchors`,suggestion:`Add anchors to ${g.symbol} in .purpose file. Run paradigm_aspect_check for details.`});else for(let k of v){let _=H.isAbsolute(k.path)?k.path:H.join(s.rootDir,k.path);E.existsSync(_)||n.push({type:"stale-aspect",severity:"warning",message:`Aspect "${g.symbol}" anchor "${k.raw}" points to missing file`,suggestion:`Update anchors for ${g.symbol} in .purpose file.`});}}}}for(let f of e){if(!f.startsWith("#"))continue;(g.data||{}).aspects||[];for(let w of y){if(!w.includes("*"))continue;if(new RegExp("^"+w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(f))break}}}}t.length>=5&&e.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${t.length} files, ${e.length} symbols) \u2014 consider recording decisions`,suggestion:"Use paradigm_wisdom_record to capture architectural decisions or antipatterns."});for(let g of e){let y=j$2(s.index,g);if(y.length===0)continue;let f=y[0];f.parentSymbol&&j$2(s.index,f.parentSymbol).length===0&&n.push({type:"broken-reference",severity:"warning",message:`Symbol "${g}" references parent "${f.parentSymbol}" which does not exist`,suggestion:"Create the parent symbol or update the parent reference in the .purpose file."});}let c=n.filter(g=>g.severity==="error").length,l=n.filter(g=>g.severity==="warning").length,d="pass";c>0?d="violations":l>0&&(d="warnings");let p=null;try{let g=re(s.rootDir),f=j$1().getStats(),b=[...new Set(f.toolCalls.map(x=>x.toolName))],h=b.includes("paradigm_lore_record"),w;try{w=execSync("git status --porcelain",{cwd:s.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let v=qt({toolsCalled:b,filesModified:t,symbolsTouched:e,loreRecorded:h,hasPortalRoutes:s.gateConfig!==null&&s.gateConfig.routes!=null,taskAddsRoutes:!1,gitClean:w}),k=Ht(g,"postflight",v,void 0,s.rootDir);p={trigger:"postflight",total:k.summary.total,followed:k.summary.followed,skipped:k.summary.skipped,partial:k.summary.partial,blockingViolations:k.summary.blockingViolations,results:k.evaluations.map(x=>({id:x.habit.id,name:x.habit.name,severity:x.habit.severity,result:x.result,reason:x.reason}))};let _=H.join(s.rootDir,".paradigm",".habits-blocking");if(k.blocksCompletion){let x=k.evaluations.filter(C=>C.result==="skipped"&&C.habit.severity==="block").map(C=>`${C.habit.name}: ${C.reason}`);E.writeFileSync(_,x.join(`
443
- `),"utf8");}else E.existsSync(_)&&E.unlinkSync(_);}catch{}let u=n.map(g=>({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"}[g.type]??"missing-description",target:g.file||g.message.slice(0,80),severity:g.severity==="error"?"blocking":"improvement"})),m=u.length>0?Ga(u):null;return {status:d,violations:n,summary:{totalChecks:7,passed:7-(c>0?1:0)-(l>0?1:0),warnings:l,errors:c},blocksCompletion:c>0,habitsEvaluation:p,...m?{narrations:m}:{}}}function za(){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 Ya(t,e,s){switch(t){case "paradigm_habits_list":{let n=Vp(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_check":{let n=await Kp(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_status":{let n=await tu(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_practice_context":{let n=await nu(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_add":{let n=Xp(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_edit":{let n=Zp(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_remove":{let n=eu(e,s);return o(n.length,t),{text:n,handled:true}}default:return {text:"",handled:false}}}function Vp(t,e){let s=t.trigger,n=t.category,i=t.enabled,r=re(e.rootDir);s&&(r=r.filter(a=>a.trigger===s)),n&&(r=r.filter(a=>a.category===n)),i!==void 0&&(r=r.filter(a=>a.enabled===i));let o={};for(let a of r)o[a.trigger]||(o[a.trigger]=[]),o[a.trigger].push(a);return JSON.stringify({total:r.length,filters:Object.fromEntries(Object.entries({trigger:s,category:n,enabled:i}).filter(([,a])=>a!==void 0)),byTrigger:Object.fromEntries(Object.entries(o).map(([a,c])=>[a,c.map(l=>({id:l.id,name:l.name,description:l.description,category:l.category,severity:l.severity,enabled:l.enabled,check:{type:l.check.type,params:l.check.params},platforms:l.platforms||null}))]))},null,2)}async function Kp(t,e){let s=t.trigger,n=t.filesModified||[],i=t.symbolsTouched||[],r=t.taskDescription,o=t.record!==false,a=re(e.rootDir),c=j$1(),l=c.getStats(),d=[...new Set(l.toolCalls.map(k=>k.toolName))],p=d.includes("paradigm_lore_record"),u=(r||"").toLowerCase(),m=["endpoint","route","api","handler","get","post","put","patch","delete"].some(k=>u.includes(k)),g;try{g=execSync("git status --porcelain",{cwd:e.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let y=qt({toolsCalled:d,filesModified:n,symbolsTouched:i,loreRecorded:p,hasPortalRoutes:e.gateConfig!==null&&e.gateConfig.routes!=null,taskAddsRoutes:m,taskDescription:r,gitClean:g}),b=Ht(a,s,y,"claude",e.rootDir),h=[];if(o&&b.evaluations.length>0)try{let k=c.getLastLoreEntryId()??void 0;h=await ta(e.rootDir,b.evaluations.map(_=>({habitId:_.habit.id,habitCategory:_.habit.category,result:_.result,notes:_.reason})),{engineer:"agent",sessionId:l.sessionId,loreEntryId:k,taskDescription:r,symbolsTouched:i,filesModified:n});}catch{}let w=H.join(e.rootDir,".paradigm",".habits-blocking");try{if(s==="on-stop"&&b.blocksCompletion){let k=b.evaluations.filter(_=>_.result==="skipped"&&_.habit.severity==="block").map(_=>`${_.habit.name}: ${_.reason}`);E.writeFileSync(w,k.join(`
444
- `),"utf8");}else s==="on-stop"&&E.existsSync(w)&&E.unlinkSync(w);}catch{}let v=zs;return JSON.stringify({trigger:s,evaluation:{total:b.summary.total,followed:b.summary.followed,skipped:b.summary.skipped,partial:b.summary.partial,blockingViolations:b.summary.blockingViolations,blocksCompletion:b.blocksCompletion},...v>0?{graduatedToHooks:v,graduatedNote:`${v} habit(s) enforced by hooks (zero context cost). Not re-evaluated here.`}:{},habits:b.evaluations.map(k=>({id:k.habit.id,name:k.habit.name,category:k.habit.category,severity:k.habit.severity,result:k.result,reason:k.reason,evidence:k.evidence})),recorded:o?h.length:0,recommendations:Qp(b)},null,2)}function Qp(t){let e=[];for(let s of t.evaluations)if(s.result==="skipped")switch(s.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(`${s.habit.name}: ${s.reason}`);}return [...new Set(e)]}function Xp(t,e){let s=t.id,n=t.scope||"project";if(Ln(s))return JSON.stringify({error:true,message:`Cannot create habit "${s}" \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(re(e.rootDir).find(l=>l.id===s))return JSON.stringify({error:true,message:`Habit "${s}" already exists. Use paradigm_habits_edit to update it, or choose a different ID.`},null,2);let o={id:s,name:t.name,description:t.description,category:t.category,trigger:t.trigger,severity:t.severity,check:t.check,enabled:t.enabled!==void 0?t.enabled:true};t.platforms&&(o.platforms=t.platforms);let a=Us(o);if(!a.valid)return JSON.stringify({error:true,message:"Validation failed",errors:a.errors},null,2);let c=Bs(e.rootDir,o,n);return JSON.stringify({created:true,id:o.id,filePath:c,scope:n,message:`Habit "${o.name}" created at ${c}`},null,2)}function Zp(t,e){let s=t.id;if(Ln(s))return JSON.stringify({error:true,message:`Cannot edit "${s}" \u2014 it is a seed habit. To customize it, add an override in .paradigm/habits.yaml under the "overrides:" key.`},null,2);let n=H.join(e.rootDir,".paradigm","habits",`${s}.habit`),i=process.env.HOME||process.env.USERPROFILE||"~",r=H.join(i,".paradigm","habits",`${s}.habit`),o=null,a="project";if(E.existsSync(n)?(o=n,a="project"):E.existsSync(r)&&(o=r,a="global"),!o)return JSON.stringify({error:true,message:`No .habit file found for "${s}". It may be defined in habits.yaml \u2014 edit that file directly.`},null,2);let c;try{let p=E.readFileSync(o,"utf8");c=Te.load(p);}catch{return JSON.stringify({error:true,message:`Failed to read ${o}`},null,2)}let l={...c};t.name!==void 0&&(l.name=t.name),t.description!==void 0&&(l.description=t.description),t.category!==void 0&&(l.category=t.category),t.trigger!==void 0&&(l.trigger=t.trigger),t.severity!==void 0&&(l.severity=t.severity),t.check!==void 0&&(l.check=t.check),t.enabled!==void 0&&(l.enabled=t.enabled),t.platforms!==void 0&&(l.platforms=t.platforms);let d=Us(l);return d.valid?(Bs(e.rootDir,l,a),JSON.stringify({updated:true,id:l.id,filePath:o,message:`Habit "${l.name}" updated`},null,2)):JSON.stringify({error:true,message:"Validation failed after merge",errors:d.errors},null,2)}function eu(t,e){let s=t.id,n=Ma(e.rootDir,s);return n.removed?JSON.stringify({removed:true,id:s,message:`Habit "${s}" removed`},null,2):JSON.stringify({error:true,message:n.reason},null,2)}async function tu(t,e){let s=t.engineer,n=t.period||"30d",i=new Date,r;if(n!=="all"){let h=parseInt(n.replace("d",""),10)||30;r=new Date(i.getTime()-h*24*60*60*1e3).toISOString();}let o={engineer:s,dateFrom:r},a=await le(e.rootDir,o),c=await Rt(e.rootDir,o),l=await ea(e.rootDir,{...o,limit:200}),d=new Map;for(let h of l){let w=d.get(h.habitId)||{followed:0,skipped:0,partial:0},v=h.result;w[v]++,d.set(h.habitId,w);}let p=null,u=null,m=-1,g=101;for(let h of c)h.rate>m&&(m=h.rate,p=h.category),h.rate<g&&(g=h.rate,u=h.category);let y=re(e.rootDir),f=new Map(y.map(h=>[h.id,h.name])),b=Array.from(d.entries()).map(([h,w])=>{let v=w.followed+w.skipped+w.partial,k=v>0?Math.round((w.followed+w.partial*.5)/v*100):100;return {habitId:h,habitName:f.get(h)||h,...w,total:v,rate:k}}).sort((h,w)=>h.rate-w.rate);return JSON.stringify({period:n,engineer:s||"all",overall:{totalEvents:a.total,complianceRate:a.rate,followed:a.followed,skipped:a.skipped,partial:a.partial,strongestCategory:p,weakestCategory:u},byCategory:c.map(h=>({category:h.category,rate:h.rate,total:h.total,followed:h.followed,skipped:h.skipped,partial:h.partial})),byHabit:b,activeHabits:y.filter(h=>h.enabled).length,totalHabits:y.length},null,2)}async function nu(t,e){let s=t.symbols||[],n=t.task,r=re(e.rootDir).filter(g=>g.enabled&&g.trigger==="preflight"),a=j$1().getStats(),c=[...new Set(a.toolCalls.map(g=>g.toolName))],l=[];for(let g of r)if(g.check.type==="tool-called"){let y=g.check.params.tools||[];!y.some(b=>c.includes(b))&&s.length>0&&l.push({habitId:g.id,habitName:g.name,category:g.category,severity:g.severity,message:`${g.name}: ${g.description}`,suggestion:`Call one of: ${y.join(", ")}`});}let d=new Date(Date.now()-720*60*60*1e3).toISOString(),p=await le(e.rootDir,{dateFrom:d}),m=(await Rt(e.rootDir,{dateFrom:d})).filter(g=>g.rate<60).map(g=>g.category);return JSON.stringify({symbols:s,task:n||null,warnings:l,recentCompliance:{rate:p.rate,totalEvents:p.total,weakAreas:m},preflightReminders:l.length>0?`${l.length} habit(s) not yet followed this session. See warnings above.`:"All preflight habits satisfied."},null,2)}qn();Ls();async function Va(t){let e=at(t);if(!e.enabled)return [];let s=re(t),n=[];for(let i of s){if(!i.enabled)continue;let r=await su(t,i,e);n.push(r);}return n}async function su(t,e,s){let n=Hn(t,e.id),i={habitId:e.id,habitName:e.name,currentTier:n.tier,neverGraduate:false,inCooldown:false};if(n.tier==="hook")return {...i,eligible:false,reason:"Already graduated to hook"};if(n.neverGraduate||s.neverGraduate.includes(e.id))return {...i,eligible:false,reason:"Marked as never-graduate (requires agent cognition)",neverGraduate:true};if(qs.has(e.check.type))return {...i,eligible:false,reason:`Check type "${e.check.type}" cannot graduate \u2014 requires MCP tool output`,neverGraduate:true};if(n.cooldownUntil&&new Date(n.cooldownUntil)>new Date)return {...i,eligible:false,reason:`In cooldown until ${n.cooldownUntil.split("T")[0]} (demoted recently)`,inCooldown:true};let{thresholds:r}=s,o=new Date;o.setDate(o.getDate()-r.timeWindowDays);try{let a=await le(t,{habitId:e.id,dateFrom:o.toISOString()});if(a.total<r.minEvents)return {...i,eligible:!1,reason:`Insufficient data: ${a.total}/${r.minEvents} events in ${r.timeWindowDays}d window`,complianceRate:a.rate,eventCount:a.total};if(a.rate<r.minComplianceRate)return {...i,eligible:!1,reason:`Compliance ${a.rate.toFixed(0)}% < ${r.minComplianceRate}% threshold`,complianceRate:a.rate,eventCount:a.total};let c=new Date;return c.setDate(c.getDate()-r.recencyDays),(await le(t,{habitId:e.id,dateFrom:c.toISOString()})).total===0?{...i,eligible:!1,reason:`No events in last ${r.recencyDays} days \u2014 habit may be dormant`,complianceRate:a.rate,eventCount:a.total}:{...i,eligible:!0,reason:`Ready: ${a.rate.toFixed(0)}% compliance over ${a.total} events in ${r.timeWindowDays}d`,complianceRate:a.rate,eventCount:a.total}}catch{return {...i,eligible:false,reason:"Unable to query practice events (Sentinel DB unavailable)"}}}function Ka(t){let e=re(t),s=at(t),n=Ws(t),i=0,r=0,o=0,a=0;for(let c of e){if(!c.enabled)continue;let l=n[c.id],d=l?.tier||"habit",p=l?.neverGraduate||s.neverGraduate.includes(c.id)||qs.has(c.check.type);d==="hook"?i++:d==="mcp"?o++:r++,p&&a++;}return {hookCount:i,habitCount:r,mcpCount:o,neverGraduateCount:a,states:n}}qn();var iu=[{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 ru(t,e){let s=await Va(t.rootDir),n=s;if(e.habitId&&(n=s.filter(a=>a.habitId===e.habitId),n.length===0))return JSON.stringify({error:`No habit found with ID "${e.habitId}"`});let i=n.filter(a=>a.eligible),r=n.filter(a=>!a.eligible&&!a.neverGraduate),o=n.filter(a=>a.neverGraduate);return JSON.stringify({summary:{checked:n.length,eligible:i.length,ineligible:r.length,neverGraduate:o.length},...i.length>0?{eligible:i.map(Qa),action:"Run `paradigm graduate promote <id>` to graduate eligible habits."}:{},...r.length>0?{ineligible:r.map(Qa)}:{},...o.length>0?{neverGraduate:o.map(a=>({id:a.habitId,name:a.habitName,reason:a.reason}))}:{}},null,2)}async function ou(t){let e=Ka(t.rootDir),s=at(t.rootDir),n={hook:[],habit:[],mcp:[]};for(let[i,r]of Object.entries(e.states)){let o=r.tier||"habit";n[o]||(n[o]=[]),n[o].push({id:i,...r.graduatedAt?{graduatedAt:r.graduatedAt}:{},...r.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:n,thresholds:s.thresholds},null,2)}function Xa(){return iu}async function Za(t,e,s){switch(t){case "paradigm_graduate_check":return {handled:true,text:await ru(s,e)};case "paradigm_graduate_status":return {handled:true,text:await ou(s)};default:return {handled:false,text:""}}}function Qa(t){return {id:t.habitId,name:t.habitName,tier:t.currentTier,reason:t.reason,...t.complianceRate!==void 0?{complianceRate:t.complianceRate}:{},...t.eventCount!==void 0?{eventCount:t.eventCount}:{},...t.inCooldown?{inCooldown:true}:{}}}var ec=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"]),au=.95,cu=.3,lu=10;function du(t,e){let s=t.length,n=e.length;if(s===0)return n;if(n===0)return s;let i=Array.from({length:s+1},()=>Array.from({length:n+1},()=>0));for(let r=0;r<=s;r++)i[r][0]=r;for(let r=0;r<=n;r++)i[0][r]=r;for(let r=1;r<=s;r++)for(let o=1;o<=n;o++){let a=t[r-1]===e[o-1]?0:1;i[r][o]=Math.min(i[r-1][o]+1,i[r][o-1]+1,i[r-1][o-1]+a);}return i[s][n]}function tc(t){let e=t.toLowerCase().split(/\s+/).filter(s=>s.length>0&&!ec.has(s));return e.sort(),e.join(" ")}function pu(t){try{let e=t.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 nc(t,e,s){let n=s?.limit??lu,i=tc(e);if(i.length===0)return [];let r=uu(t,i,s);if(r.length>0)return r.slice(0,n);if(pu(t)){let a=gu(t,i,s);if(a.length>0)return a.slice(0,n)}return mu(t,i,s).slice(0,n)}function uu(t,e,s){try{let n=`
526
+ 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 Xa(t,e,s){switch(t){case "paradigm_pm_preflight":{let{task:n}=e,i=await au(n,s),r=JSON.stringify(i,null,2);return o(r.length,t),{text:r,handled:true}}case "paradigm_pm_postflight":{let{filesModified:n,symbolsTouched:i}=e,r=lu(n,i,s),o$1=JSON.stringify(r,null,2);return o(o$1.length,t),{text:o$1,handled:true}}default:return {text:"",handled:false}}}async function au(t,e){let s=t.toLowerCase(),n=t.match(iu)||[],i=[...new Set(n)],r=i.map(u=>{let g=j$2(e.index,u),m=g.length>0?g[0]:null;return {symbol:u,exists:!!m,type:m?.type,description:m?.description}}),o=r.filter(u=>u.exists).map(u=>{let g=k(e.index,u.symbol),m=new Set;for(let b of g){let h=k(e.index,b.symbol);for(let w of h)w.symbol!==u.symbol&&!g.find(v=>v.symbol===w.symbol)&&m.add(w.symbol);}let y=g.length+m.size,f="low";return y>10?f="high":y>3&&(f="medium"),{symbol:u.symbol,directDependents:g.length,indirectDependents:m.size,impact:f}}),a={exists:e.gateConfig!==null,gateCount:0,gates:[],routeCount:0};if(e.gateConfig){let u=Zs(e.gateConfig);a.gateCount=u.length,a.gates=u.map(m=>`^${m}`);let g=e.gateConfig.routes;a.routeCount=g&&!Array.isArray(g)&&typeof g=="object"?Object.keys(g).length:0;}let c=ru.some(u=>s.includes(u)),l=[];r.some(u=>u.exists)&&l.push("ripple-analysis"),c&&l.push("portal-compliance"),i.some(u=>u.startsWith("^"))&&l.push("gate-validation"),i.some(u=>u.startsWith("!"))&&l.push("signal-registration"),l.push("purpose-coverage");let d=null,p=null;try{let u=re(e.rootDir),m=j$1().getStats(),y=[...new Set(m.toolCalls.map(w=>w.toolName))],f=Mt({toolsCalled:y,filesModified:[],symbolsTouched:i,loreRecorded:!1,hasPortalRoutes:a.exists&&a.routeCount>0,taskAddsRoutes:c,taskDescription:t}),b=Lt(u,"preflight",f,void 0,e.rootDir);d={total:b.summary.total,followed:b.summary.followed,skipped:b.summary.skipped,partial:b.summary.partial,results:b.evaluations.map(w=>({id:w.habit.id,name:w.habit.name,severity:w.habit.severity,result:w.result,reason:w.reason}))};let h=new Date(Date.now()-720*60*60*1e3).toISOString();p=await le(e.rootDir,{dateFrom:h});}catch{}return {task:t.slice(0,100)+(t.length>100?"...":""),affectedSymbols:r,rippleAnalysis:o,portalStatus:a,taskAddsRoutes:c,requiredChecks:l,recommendations:cu(r,o,a,c),habits:{evaluation:d,recentCompliance:p?{rate:p.rate,totalEvents:p.total}:null}}}function cu(t,e,s,n){let i=[],r=t.filter(c=>!c.exists);r.length>0&&i.push(`New symbols detected: ${r.map(c=>c.symbol).join(", ")}. Register in .purpose files after implementation.`);let o=e.filter(c=>c.impact==="high");o.length>0&&i.push(`HIGH IMPACT: ${o.map(c=>c.symbol).join(", ")} \u2014 review all dependents before modifying.`),n&&!s.exists?i.push("Task adds routes but no portal.yaml exists. Create one with appropriate ^gates."):n&&i.push("Task adds routes. Update portal.yaml with gate entries after implementation.");let a=t.filter(c=>c.symbol.startsWith("^")&&!c.exists);return a.length>0&&i.push(`New gates referenced: ${a.map(c=>c.symbol).join(", ")}. Add to portal.yaml.`),i}function lu(t,e,s){let n=[],i$1=s.gateConfig?.routes,r=i$1&&!Array.isArray(i$1)&&typeof i$1=="object"?Object.keys(i$1):[];for(let m of t){let y=H.isAbsolute(m)?m:H.join(s.rootDir,m);if(!E.existsSync(y))continue;let f;try{f=E.readFileSync(y,"utf-8");}catch{continue}for(let b of ou){b.lastIndex=0;let h;for(;(h=b.exec(f))!==null;){let w=h[2]||h[0];w&&w.startsWith("/")&&(!r.some(k=>k.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===w)&&s.gateConfig?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${w}" in ${H.relative(s.rootDir,y)} not in portal.yaml`,file:H.relative(s.rootDir,y),suggestion:"Add route to portal.yaml with ^gates. Use paradigm_gates_for_route for suggestions."}):!s.gateConfig&&w.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${w}" found but no portal.yaml exists`,file:H.relative(s.rootDir,y),suggestion:"Create portal.yaml to declare gates for API routes."}));}}}for(let m of e)j$2(s.index,m).length===0&&n.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=Zs(s.gateConfig);for(let m of e)if(m.startsWith("^")){let y=m.slice(1);o.includes(y)||n.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.`});}let a=i(s.index,"aspect");for(let m of a){let y=m.appliesTo||[];if(y.length!==0){for(let f of y){let b=f.includes("*");for(let h of e){let w=false;if(b?w=new RegExp("^"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(h):w=h===f,w){let v=m.anchors||[];if(v.length===0)n.push({type:"stale-aspect",severity:"warning",message:`Aspect "${m.symbol}" applies to "${h}" but has no code anchors`,suggestion:`Add anchors to ${m.symbol} in .purpose file. Run paradigm_aspect_check for details.`});else for(let k of v){let S=H.isAbsolute(k.path)?k.path:H.join(s.rootDir,k.path);E.existsSync(S)||n.push({type:"stale-aspect",severity:"warning",message:`Aspect "${m.symbol}" anchor "${k.raw}" points to missing file`,suggestion:`Update anchors for ${m.symbol} in .purpose file.`});}}}}for(let f of e){if(!f.startsWith("#"))continue;(m.data||{}).aspects||[];for(let w of y){if(!w.includes("*"))continue;if(new RegExp("^"+w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(f))break}}}}t.length>=5&&e.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${t.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=j$2(s.index,m);if(y.length===0)continue;let f=y[0];f.parentSymbol&&j$2(s.index,f.parentSymbol).length===0&&n.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 c=n.filter(m=>m.severity==="error").length,l=n.filter(m=>m.severity==="warning").length,d="pass";c>0?d="violations":l>0&&(d="warnings");let p=null;try{let m=re(s.rootDir),f=j$1().getStats(),b=[...new Set(f.toolCalls.map(x=>x.toolName))],h=b.includes("paradigm_lore_record"),w;try{w=execSync("git status --porcelain",{cwd:s.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let v=Mt({toolsCalled:b,filesModified:t,symbolsTouched:e,loreRecorded:h,hasPortalRoutes:s.gateConfig!==null&&s.gateConfig.routes!=null,taskAddsRoutes:!1,gitClean:w}),k=Lt(m,"postflight",v,void 0,s.rootDir);p={trigger:"postflight",total:k.summary.total,followed:k.summary.followed,skipped:k.summary.skipped,partial:k.summary.partial,blockingViolations:k.summary.blockingViolations,results:k.evaluations.map(x=>({id:x.habit.id,name:x.habit.name,severity:x.habit.severity,result:x.result,reason:x.reason}))};let S=H.join(s.rootDir,".paradigm",".habits-blocking");if(k.blocksCompletion){let x=k.evaluations.filter(C=>C.result==="skipped"&&C.habit.severity==="block").map(C=>`${C.habit.name}: ${C.reason}`);E.writeFileSync(S,x.join(`
527
+ `),"utf8");}else E.existsSync(S)&&E.unlinkSync(S);}catch{}let u=n.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"})),g=u.length>0?Ka(u):null;return {status:d,violations:n,summary:{totalChecks:7,passed:7-(c>0?1:0)-(l>0?1:0),warnings:l,errors:c},blocksCompletion:c>0,habitsEvaluation:p,...g?{narrations:g}:{}}}function ec(){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 tc(t,e,s){switch(t){case "paradigm_habits_list":{let n=pu(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_check":{let n=await uu(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_status":{let n=await hu(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_practice_context":{let n=await bu(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_add":{let n=mu(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_edit":{let n=fu(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_remove":{let n=yu(e,s);return o(n.length,t),{text:n,handled:true}}default:return {text:"",handled:false}}}function pu(t,e){let s=t.trigger,n=t.category,i=t.enabled,r=re(e.rootDir);s&&(r=r.filter(a=>a.trigger===s)),n&&(r=r.filter(a=>a.category===n)),i!==void 0&&(r=r.filter(a=>a.enabled===i));let o={};for(let a of r)o[a.trigger]||(o[a.trigger]=[]),o[a.trigger].push(a);return JSON.stringify({total:r.length,filters:Object.fromEntries(Object.entries({trigger:s,category:n,enabled:i}).filter(([,a])=>a!==void 0)),byTrigger:Object.fromEntries(Object.entries(o).map(([a,c])=>[a,c.map(l=>({id:l.id,name:l.name,description:l.description,category:l.category,severity:l.severity,enabled:l.enabled,check:{type:l.check.type,params:l.check.params},platforms:l.platforms||null}))]))},null,2)}async function uu(t,e){let s=t.trigger,n=t.filesModified||[],i=t.symbolsTouched||[],r=t.taskDescription,o=t.record!==false,a=re(e.rootDir),c=j$1(),l=c.getStats(),d=[...new Set(l.toolCalls.map(k=>k.toolName))],p=d.includes("paradigm_lore_record"),u=(r||"").toLowerCase(),g=["endpoint","route","api","handler","get","post","put","patch","delete"].some(k=>u.includes(k)),m;try{m=execSync("git status --porcelain",{cwd:e.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let y=Mt({toolsCalled:d,filesModified:n,symbolsTouched:i,loreRecorded:p,hasPortalRoutes:e.gateConfig!==null&&e.gateConfig.routes!=null,taskAddsRoutes:g,taskDescription:r,gitClean:m}),b=Lt(a,s,y,"claude",e.rootDir),h=[];if(o&&b.evaluations.length>0)try{let k=c.getLastLoreEntryId()??void 0;h=await ca(e.rootDir,b.evaluations.map(S=>({habitId:S.habit.id,habitCategory:S.habit.category,result:S.result,notes:S.reason})),{engineer:"agent",sessionId:l.sessionId,loreEntryId:k,taskDescription:r,symbolsTouched:i,filesModified:n});}catch{}let w=H.join(e.rootDir,".paradigm",".habits-blocking");try{if(s==="on-stop"&&b.blocksCompletion){let k=b.evaluations.filter(S=>S.result==="skipped"&&S.habit.severity==="block").map(S=>`${S.habit.name}: ${S.reason}`);E.writeFileSync(w,k.join(`
528
+ `),"utf8");}else s==="on-stop"&&E.existsSync(w)&&E.unlinkSync(w);}catch{}let v=Xs;return JSON.stringify({trigger:s,evaluation:{total:b.summary.total,followed:b.summary.followed,skipped:b.summary.skipped,partial:b.summary.partial,blockingViolations:b.summary.blockingViolations,blocksCompletion:b.blocksCompletion},...v>0?{graduatedToHooks:v,graduatedNote:`${v} habit(s) enforced by hooks (zero context cost). Not re-evaluated here.`}:{},habits:b.evaluations.map(k=>({id:k.habit.id,name:k.habit.name,category:k.habit.category,severity:k.habit.severity,result:k.result,reason:k.reason,evidence:k.evidence})),recorded:o?h.length:0,recommendations:gu(b)},null,2)}function gu(t){let e=[];for(let s of t.evaluations)if(s.result==="skipped")switch(s.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(`${s.habit.name}: ${s.reason}`);}return [...new Set(e)]}function mu(t,e){let s=t.id,n=t.scope||"project";if(Gn(s))return JSON.stringify({error:true,message:`Cannot create habit "${s}" \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(re(e.rootDir).find(l=>l.id===s))return JSON.stringify({error:true,message:`Habit "${s}" already exists. Use paradigm_habits_edit to update it, or choose a different ID.`},null,2);let o={id:s,name:t.name,description:t.description,category:t.category,trigger:t.trigger,severity:t.severity,check:t.check,enabled:t.enabled!==void 0?t.enabled:true};t.platforms&&(o.platforms=t.platforms);let a=Ks(o);if(!a.valid)return JSON.stringify({error:true,message:"Validation failed",errors:a.errors},null,2);let c=Qs(e.rootDir,o,n);return JSON.stringify({created:true,id:o.id,filePath:c,scope:n,message:`Habit "${o.name}" created at ${c}`},null,2)}function fu(t,e){let s=t.id;if(Gn(s))return JSON.stringify({error:true,message:`Cannot edit "${s}" \u2014 it is a seed habit. To customize it, add an override in .paradigm/habits.yaml under the "overrides:" key.`},null,2);let n=H.join(e.rootDir,".paradigm","habits",`${s}.habit`),i=process.env.HOME||process.env.USERPROFILE||"~",r=H.join(i,".paradigm","habits",`${s}.habit`),o=null,a="project";if(E.existsSync(n)?(o=n,a="project"):E.existsSync(r)&&(o=r,a="global"),!o)return JSON.stringify({error:true,message:`No .habit file found for "${s}". It may be defined in habits.yaml \u2014 edit that file directly.`},null,2);let c;try{let p=E.readFileSync(o,"utf8");c=Ae.load(p);}catch{return JSON.stringify({error:true,message:`Failed to read ${o}`},null,2)}let l={...c};t.name!==void 0&&(l.name=t.name),t.description!==void 0&&(l.description=t.description),t.category!==void 0&&(l.category=t.category),t.trigger!==void 0&&(l.trigger=t.trigger),t.severity!==void 0&&(l.severity=t.severity),t.check!==void 0&&(l.check=t.check),t.enabled!==void 0&&(l.enabled=t.enabled),t.platforms!==void 0&&(l.platforms=t.platforms);let d=Ks(l);return d.valid?(Qs(e.rootDir,l,a),JSON.stringify({updated:true,id:l.id,filePath:o,message:`Habit "${l.name}" updated`},null,2)):JSON.stringify({error:true,message:"Validation failed after merge",errors:d.errors},null,2)}function yu(t,e){let s=t.id,n=Ya(e.rootDir,s);return n.removed?JSON.stringify({removed:true,id:s,message:`Habit "${s}" removed`},null,2):JSON.stringify({error:true,message:n.reason},null,2)}async function hu(t,e){let s=t.engineer,n=t.period||"30d",i=new Date,r;if(n!=="all"){let h=parseInt(n.replace("d",""),10)||30;r=new Date(i.getTime()-h*24*60*60*1e3).toISOString();}let o={engineer:s,dateFrom:r},a=await le(e.rootDir,o),c=await jt(e.rootDir,o),l=await aa(e.rootDir,{...o,limit:200}),d=new Map;for(let h of l){let w=d.get(h.habitId)||{followed:0,skipped:0,partial:0},v=h.result;w[v]++,d.set(h.habitId,w);}let p=null,u=null,g=-1,m=101;for(let h of c)h.rate>g&&(g=h.rate,p=h.category),h.rate<m&&(m=h.rate,u=h.category);let y=re(e.rootDir),f=new Map(y.map(h=>[h.id,h.name])),b=Array.from(d.entries()).map(([h,w])=>{let v=w.followed+w.skipped+w.partial,k=v>0?Math.round((w.followed+w.partial*.5)/v*100):100;return {habitId:h,habitName:f.get(h)||h,...w,total:v,rate:k}}).sort((h,w)=>h.rate-w.rate);return JSON.stringify({period:n,engineer:s||"all",overall:{totalEvents:a.total,complianceRate:a.rate,followed:a.followed,skipped:a.skipped,partial:a.partial,strongestCategory:p,weakestCategory:u},byCategory:c.map(h=>({category:h.category,rate:h.rate,total:h.total,followed:h.followed,skipped:h.skipped,partial:h.partial})),byHabit:b,activeHabits:y.filter(h=>h.enabled).length,totalHabits:y.length},null,2)}async function bu(t,e){let s=t.symbols||[],n=t.task,r=re(e.rootDir).filter(m=>m.enabled&&m.trigger==="preflight"),a=j$1().getStats(),c=[...new Set(a.toolCalls.map(m=>m.toolName))],l=[];for(let m of r)if(m.check.type==="tool-called"){let y=m.check.params.tools||[];!y.some(b=>c.includes(b))&&s.length>0&&l.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 d=new Date(Date.now()-720*60*60*1e3).toISOString(),p=await le(e.rootDir,{dateFrom:d}),g=(await jt(e.rootDir,{dateFrom:d})).filter(m=>m.rate<60).map(m=>m.category);return JSON.stringify({symbols:s,task:n||null,warnings:l,recentCompliance:{rate:p.rate,totalEvents:p.total,weakAreas:g},preflightReminders:l.length>0?`${l.length} habit(s) not yet followed this session. See warnings above.`:"All preflight habits satisfied."},null,2)}Wn();Us();async function nc(t){let e=at(t);if(!e.enabled)return [];let s=re(t),n=[];for(let i of s){if(!i.enabled)continue;let r=await wu(t,i,e);n.push(r);}return n}async function wu(t,e,s){let n=Mn(t,e.id),i={habitId:e.id,habitName:e.name,currentTier:n.tier,neverGraduate:false,inCooldown:false};if(n.tier==="hook")return {...i,eligible:false,reason:"Already graduated to hook"};if(n.neverGraduate||s.neverGraduate.includes(e.id))return {...i,eligible:false,reason:"Marked as never-graduate (requires agent cognition)",neverGraduate:true};if(Js.has(e.check.type))return {...i,eligible:false,reason:`Check type "${e.check.type}" cannot graduate \u2014 requires MCP tool output`,neverGraduate:true};if(n.cooldownUntil&&new Date(n.cooldownUntil)>new Date)return {...i,eligible:false,reason:`In cooldown until ${n.cooldownUntil.split("T")[0]} (demoted recently)`,inCooldown:true};let{thresholds:r}=s,o=new Date;o.setDate(o.getDate()-r.timeWindowDays);try{let a=await le(t,{habitId:e.id,dateFrom:o.toISOString()});if(a.total<r.minEvents)return {...i,eligible:!1,reason:`Insufficient data: ${a.total}/${r.minEvents} events in ${r.timeWindowDays}d window`,complianceRate:a.rate,eventCount:a.total};if(a.rate<r.minComplianceRate)return {...i,eligible:!1,reason:`Compliance ${a.rate.toFixed(0)}% < ${r.minComplianceRate}% threshold`,complianceRate:a.rate,eventCount:a.total};let c=new Date;return c.setDate(c.getDate()-r.recencyDays),(await le(t,{habitId:e.id,dateFrom:c.toISOString()})).total===0?{...i,eligible:!1,reason:`No events in last ${r.recencyDays} days \u2014 habit may be dormant`,complianceRate:a.rate,eventCount:a.total}:{...i,eligible:!0,reason:`Ready: ${a.rate.toFixed(0)}% compliance over ${a.total} events in ${r.timeWindowDays}d`,complianceRate:a.rate,eventCount:a.total}}catch{return {...i,eligible:false,reason:"Unable to query practice events (Sentinel DB unavailable)"}}}function sc(t){let e=re(t),s=at(t),n=zs(t),i=0,r=0,o=0,a=0;for(let c of e){if(!c.enabled)continue;let l=n[c.id],d=l?.tier||"habit",p=l?.neverGraduate||s.neverGraduate.includes(c.id)||Js.has(c.check.type);d==="hook"?i++:d==="mcp"?o++:r++,p&&a++;}return {hookCount:i,habitCount:r,mcpCount:o,neverGraduateCount:a,states:n}}Wn();var vu=[{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 ku(t,e){let s=await nc(t.rootDir),n=s;if(e.habitId&&(n=s.filter(a=>a.habitId===e.habitId),n.length===0))return JSON.stringify({error:`No habit found with ID "${e.habitId}"`});let i=n.filter(a=>a.eligible),r=n.filter(a=>!a.eligible&&!a.neverGraduate),o=n.filter(a=>a.neverGraduate);return JSON.stringify({summary:{checked:n.length,eligible:i.length,ineligible:r.length,neverGraduate:o.length},...i.length>0?{eligible:i.map(ic),action:"Run `paradigm graduate promote <id>` to graduate eligible habits."}:{},...r.length>0?{ineligible:r.map(ic)}:{},...o.length>0?{neverGraduate:o.map(a=>({id:a.habitId,name:a.habitName,reason:a.reason}))}:{}},null,2)}async function Su(t){let e=sc(t.rootDir),s=at(t.rootDir),n={hook:[],habit:[],mcp:[]};for(let[i,r]of Object.entries(e.states)){let o=r.tier||"habit";n[o]||(n[o]=[]),n[o].push({id:i,...r.graduatedAt?{graduatedAt:r.graduatedAt}:{},...r.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:n,thresholds:s.thresholds},null,2)}function rc(){return vu}async function oc(t,e,s){switch(t){case "paradigm_graduate_check":return {handled:true,text:await ku(s,e)};case "paradigm_graduate_status":return {handled:true,text:await Su(s)};default:return {handled:false,text:""}}}function ic(t){return {id:t.habitId,name:t.habitName,tier:t.currentTier,reason:t.reason,...t.complianceRate!==void 0?{complianceRate:t.complianceRate}:{},...t.eventCount!==void 0?{eventCount:t.eventCount}:{},...t.inCooldown?{inCooldown:true}:{}}}var ac=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"]),_u=.95,xu=.3,Cu=10;function Ru(t,e){let s=t.length,n=e.length;if(s===0)return n;if(n===0)return s;let i=Array.from({length:s+1},()=>Array.from({length:n+1},()=>0));for(let r=0;r<=s;r++)i[r][0]=r;for(let r=0;r<=n;r++)i[0][r]=r;for(let r=1;r<=s;r++)for(let o=1;o<=n;o++){let a=t[r-1]===e[o-1]?0:1;i[r][o]=Math.min(i[r-1][o]+1,i[r][o-1]+1,i[r-1][o-1]+a);}return i[s][n]}function cc(t){let e=t.toLowerCase().split(/\s+/).filter(s=>s.length>0&&!ac.has(s));return e.sort(),e.join(" ")}function Pu(t){try{let e=t.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 lc(t,e,s){let n=s?.limit??Cu,i=cc(e);if(i.length===0)return [];let r=ju(t,i,s);if(r.length>0)return r.slice(0,n);if(Pu(t)){let a=Tu(t,i,s);if(a.length>0)return a.slice(0,n)}return Au(t,i,s).slice(0,n)}function ju(t,e,s){try{let n=`
445
529
  SELECT
446
530
  a.id, a.description, a.category, a.severity, a.tags,
447
531
  sw.weight,
@@ -449,7 +533,7 @@ Runs pre-flight compliance checks: extracts affected symbols, runs ripple analys
449
533
  FROM search_weights sw
450
534
  JOIN aspects a ON sw.aspect_id = a.id
451
535
  WHERE sw.query_normalized LIKE ? || '%'
452
- `,i=[e];s?.category&&(n+=" AND a.category = ?",i.push(s.category)),s?.severity&&(n+=" AND a.severity = ?",i.push(s.severity)),n+=" ORDER BY sw.weight DESC";let r=t.prepare(n);r.bind(i);let o=[];for(;r.step();){let a=r.getAsObject();o.push({id:a.id,description:a.description,category:a.category||void 0,severity:a.severity||void 0,score:a.weight,tier:1,tags:a.tags?Vs(a.tags):void 0,anchorCount:a.anchor_count});}return r.free(),o}catch{return []}}function gu(t,e,s){try{let n=e.split(/\s+/).filter(c=>c.length>0).map(c=>`"${c}"*`).join(" ");if(n.length===0)return [];let i=`
536
+ `,i=[e];s?.category&&(n+=" AND a.category = ?",i.push(s.category)),s?.severity&&(n+=" AND a.severity = ?",i.push(s.severity)),n+=" ORDER BY sw.weight DESC";let r=t.prepare(n);r.bind(i);let o=[];for(;r.step();){let a=r.getAsObject();o.push({id:a.id,description:a.description,category:a.category||void 0,severity:a.severity||void 0,score:a.weight,tier:1,tags:a.tags?ei(a.tags):void 0,anchorCount:a.anchor_count});}return r.free(),o}catch{return []}}function Tu(t,e,s){try{let n=e.split(/\s+/).filter(c=>c.length>0).map(c=>`"${c}"*`).join(" ");if(n.length===0)return [];let i=`
453
537
  SELECT
454
538
  a.id, a.description, a.category, a.severity, a.tags,
455
539
  rank AS fts_rank,
@@ -457,13 +541,13 @@ Runs pre-flight compliance checks: extracts affected symbols, runs ripple analys
457
541
  FROM aspects_fts fts
458
542
  JOIN aspects a ON fts.rowid = a.rowid
459
543
  WHERE aspects_fts MATCH ?
460
- `,r=[n];s?.category&&(i+=" AND a.category = ?",r.push(s.category)),s?.severity&&(i+=" AND a.severity = ?",r.push(s.severity)),i+=" ORDER BY rank";let o=t.prepare(i);o.bind(r);let a=[];for(;o.step();){let c=o.getAsObject(),l=Math.abs(c.fts_rank);a.push({id:c.id,description:c.description,category:c.category||void 0,severity:c.severity||void 0,score:l,tier:2,tags:c.tags?Vs(c.tags):void 0,anchorCount:c.anchor_count});}return o.free(),a}catch{return []}}function mu(t,e,s){try{let n=`
544
+ `,r=[n];s?.category&&(i+=" AND a.category = ?",r.push(s.category)),s?.severity&&(i+=" AND a.severity = ?",r.push(s.severity)),i+=" ORDER BY rank";let o=t.prepare(i);o.bind(r);let a=[];for(;o.step();){let c=o.getAsObject(),l=Math.abs(c.fts_rank);a.push({id:c.id,description:c.description,category:c.category||void 0,severity:c.severity||void 0,score:l,tier:2,tags:c.tags?ei(c.tags):void 0,anchorCount:c.anchor_count});}return o.free(),a}catch{return []}}function Au(t,e,s){try{let n=`
461
545
  SELECT
462
546
  a.id, a.description, a.category, a.severity, a.tags,
463
547
  (SELECT COUNT(*) FROM anchors anc WHERE anc.aspect_id = a.id) AS anchor_count
464
548
  FROM aspects a
465
549
  WHERE 1=1
466
- `,i=[];s?.category&&(n+=" AND a.category = ?",i.push(s.category)),s?.severity&&(n+=" AND a.severity = ?",i.push(s.severity));let r=t.prepare(n);r.bind(i);let o=[];for(;r.step();){let c=r.getAsObject();o.push({id:c.id,description:c.description,category:c.category,severity:c.severity,tags:c.tags,anchorCount:c.anchor_count});}r.free();let a=[];for(let c of o){let l=fu(e,c.id,c.description);l>cu&&a.push({id:c.id,description:c.description,category:c.category||void 0,severity:c.severity||void 0,score:l,tier:3,tags:c.tags?Vs(c.tags):void 0,anchorCount:c.anchorCount});}return a.sort((c,l)=>l.score-c.score),a}catch{return []}}function fu(t,e,s){let i=[(e.startsWith("~")?e.slice(1):e).toLowerCase()],r=s.toLowerCase().split(/\s+/).filter(c=>c.length>0&&!ec.has(c));i.push(...r);let o=t.split(/\s+/).filter(c=>c.length>0);if(o.length===0)return 0;let a=0;for(let c of o){let l=0;for(let d of i){let u=1/(1+du(c,d));u>l&&(l=u);}a+=l;}return a/o.length}function sc(t,e,s){let n=tc(e),i=new Date().toISOString();try{t.run(`INSERT INTO search_log (query, results, selected, timestamp)
550
+ `,i=[];s?.category&&(n+=" AND a.category = ?",i.push(s.category)),s?.severity&&(n+=" AND a.severity = ?",i.push(s.severity));let r=t.prepare(n);r.bind(i);let o=[];for(;r.step();){let c=r.getAsObject();o.push({id:c.id,description:c.description,category:c.category,severity:c.severity,tags:c.tags,anchorCount:c.anchor_count});}r.free();let a=[];for(let c of o){let l=Du(e,c.id,c.description);l>xu&&a.push({id:c.id,description:c.description,category:c.category||void 0,severity:c.severity||void 0,score:l,tier:3,tags:c.tags?ei(c.tags):void 0,anchorCount:c.anchorCount});}return a.sort((c,l)=>l.score-c.score),a}catch{return []}}function Du(t,e,s){let i=[(e.startsWith("~")?e.slice(1):e).toLowerCase()],r=s.toLowerCase().split(/\s+/).filter(c=>c.length>0&&!ac.has(c));i.push(...r);let o=t.split(/\s+/).filter(c=>c.length>0);if(o.length===0)return 0;let a=0;for(let c of o){let l=0;for(let d of i){let u=1/(1+Ru(c,d));u>l&&(l=u);}a+=l;}return a/o.length}function dc(t,e,s){let n=cc(e),i=new Date().toISOString();try{t.run(`INSERT INTO search_log (query, results, selected, timestamp)
467
551
  VALUES (?, ?, ?, ?)`,[e,JSON.stringify([s]),s,i]);}catch{}try{t.run(`INSERT INTO search_weights (query_normalized, aspect_id, weight, hit_count, last_hit)
468
552
  VALUES (?, ?, 1.0, 1, ?)
469
553
  ON CONFLICT(query_normalized, aspect_id) DO UPDATE SET
@@ -471,51 +555,51 @@ Runs pre-flight compliance checks: extracts affected symbols, runs ripple analys
471
555
  hit_count = hit_count + 1,
472
556
  last_hit = ?`,[n,s,i,i]);}catch{return}try{t.run(`UPDATE search_weights
473
557
  SET weight = weight * ?
474
- WHERE query_normalized = ? AND aspect_id != ?`,[au,n,s]);}catch{}}function Vs(t){try{let e=JSON.parse(t);return Array.isArray(e)&&e.length>0?e:void 0}catch{let e=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);return e.length>0?e:void 0}}function rc(){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 oc(t,e,s){switch(t){case "paradigm_aspect_search":return yu(e,s);case "paradigm_aspect_get":return hu(e,s);case "paradigm_aspect_graph":return bu(e,s);case "paradigm_aspect_heatmap":return wu(e,s);case "paradigm_aspect_suggest_scan":return vu(e,s);case "paradigm_aspect_drift":return ku(e,s);case "paradigm_aspect_confirm":return _u(e,s);default:return {handled:false,text:""}}}async function yu(t,e){let{query:s,limit:n=10}=t,i=null;try{i=await fa$1(e.rootDir);let r=nc(i,s,{limit:n});for(let c of r)try{ma$1(i,c.id,"search");}catch{}let o$1={query:s,count:r.length,results:r.map(c=>({id:c.id,description:c.description,category:c.category,severity:c.severity,score:Math.round(c.score*1e3)/1e3,tier:c.tier,tags:c.tags,anchorCount:c.anchorCount})),tip:r.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."},a=JSON.stringify(o$1,null,2);return ga$1(i,e.rootDir),i=null,o(a.length,"paradigm_aspect_search"),{handled:!0,text:a}}catch(r){if(i)try{ga$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to search aspects",details:String(r),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(o$1.length,"paradigm_aspect_search"),{handled:true,text:o$1}}}async function hu(t,e){let{aspectId:s}=t,n=s.startsWith("~")?s.slice(1):s,i=null;try{i=await fa$1(e.rootDir);let r=ha$1(i,n);if(r||(r=ha$1(i,`~${n}`)),!r){ga$1(i),i=null;let f=JSON.stringify({error:"Aspect not found",aspectId:n,suggestion:"Use paradigm_aspect_search to find aspects by keyword."},null,2);return o(f.length,"paradigm_aspect_get"),{handled:!0,text:f}}let o$1=r.id,c=ia$1(i,o$1).map(f=>{let b=Su(e.rootDir,f);return {filePath:f.file_path,startLine:f.start_line,endLine:f.end_line,drifted:f.drifted===1,snippet:b}}),l=ja$1(i,o$1),d=ka(i,o$1),p=[...l.map(f=>({direction:"outgoing",source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin})),...d.map(f=>({direction:"incoming",source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin}))],u=[];try{u=await pa(i,e.rootDir,o$1);}catch{}try{ma$1(i,o$1,"direct");}catch{}let m;if(r.tags)try{let f=JSON.parse(r.tags);Array.isArray(f)&&(m=f);}catch{m=r.tags.split(",").map(f=>f.trim()).filter(f=>f.length>0);}let g={id:o$1,description:r.description,category:r.category,severity:r.severity,value:r.value,enforcement:r.enforcement,definedIn:r.defined_in,tags:m,createdAt:r.created_at,updatedAt:r.updated_at,anchors:c,edges:p,lore:u},y=JSON.stringify(g,null,2);return ga$1(i,e.rootDir),i=null,o(y.length,"paradigm_aspect_get"),{handled:!0,text:y}}catch(r){if(i)try{ga$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to get aspect",details:String(r),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(o$1.length,"paradigm_aspect_get"),{handled:true,text:o$1}}}async function bu(t,e){let{symbol:s,hops:n=2}=t,i=Math.min(Math.max(n,1),5),r=null;try{r=await fa$1(e.rootDir);let o$1=new Set,a=new Map,c=[],l=[{symbol:s,depth:0}];o$1.add(s);let d=ha$1(r,s);for(a.set(s,{aspectId:s,category:d?.category,severity:d?.severity,depth:0});l.length>0;){let g=l.shift();if(g.depth>=i)continue;let y=la$1(r,g.symbol);for(let f of y){let b=f.source===g.symbol?f.target:f.source;if(c.some(w=>w.source===f.source&&w.target===f.target&&w.relation===f.relation)||c.push({source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin,inferred:f.origin==="inferred"}),!o$1.has(b)){o$1.add(b);let w=ha$1(r,b);a.set(b,{aspectId:b,category:w?.category,severity:w?.severity,depth:g.depth+1}),l.push({symbol:b,depth:g.depth+1});}}}let p=Array.from(a.values()),u={startSymbol:s,maxHops:i,nodeCount:p.length,edgeCount:c.length,nodes:p,edges:c},m=JSON.stringify(u,null,2);return ga$1(r),r=null,o(m.length,"paradigm_aspect_graph"),{handled:!0,text:m}}catch(o$1){if(r)try{ga$1(r);}catch{}let a=JSON.stringify({error:"Failed to traverse aspect graph",details:String(o$1),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(a.length,"paradigm_aspect_graph"),{handled:true,text:a}}}async function wu(t,e){let{limit:s=20,accessType:n}=t,i=null;try{i=await fa$1(e.rootDir);let r=na$1(i,s*4,n),o$1=new Map;for(let d of r){let p=o$1.get(d.aspect_id);if(!p){let u=ha$1(i,d.aspect_id);p={aspectId:d.aspect_id,description:u?.description,totalCount:0,byType:{},lastAccessed:d.last_accessed},o$1.set(d.aspect_id,p);}p.totalCount+=d.count,p.byType[d.access_type]=d.count,d.last_accessed>p.lastAccessed&&(p.lastAccessed=d.last_accessed);}let a=Array.from(o$1.values()).sort((d,p)=>p.totalCount-d.totalCount).slice(0,s),c={count:a.length,...n?{filteredBy:n}:{},entries:a},l=JSON.stringify(c,null,2);return ga$1(i),i=null,o(l.length,"paradigm_aspect_heatmap"),{handled:!0,text:l}}catch(r){if(i)try{ga$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to get aspect heatmap",details:String(r),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(o$1.length,"paradigm_aspect_heatmap"),{handled:true,text:o$1}}}async function vu(t,e){let{filePath:s}=t,n=H.isAbsolute(s)?s:H.join(e.rootDir,s);if(!E.existsSync(n)){let i=JSON.stringify({error:"File not found",filePath:n,suggestion:"Provide a valid relative or absolute file path."},null,2);return o(i.length,"paradigm_aspect_suggest_scan"),{handled:true,text:i}}try{let o$1=(await import('../utils/aspect-suggest.js')).suggestAspects(n),a={filePath:n,count:o$1.length,suggestions:o$1.map(l=>({line:l.line,code:l.code,suggestedName:l.suggestedName,category:l.suggestedCategory,description:l.suggestedDescription,confidence:l.confidence,reason:l.reason,inferred:!0})),tip:o$1.length>0?"Review suggestions and add confirmed aspects to your .purpose files with ~ prefix and code anchors.":"No implicit aspects detected in this file."},c=JSON.stringify(a,null,2);return o(c.length,"paradigm_aspect_suggest_scan"),{handled:!0,text:c}}catch(i){let r=String(i);if(r.includes("Cannot find module")||r.includes("MODULE_NOT_FOUND")){let a=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 o(a.length,"paradigm_aspect_suggest_scan"),{handled:true,text:a}}let o$1=JSON.stringify({error:"Failed to scan for aspect suggestions",details:r},null,2);return o(o$1.length,"paradigm_aspect_suggest_scan"),{handled:true,text:o$1}}}async function ku(t,e){let{aspectId:s,autoHeal:n}=t,i=n!==false,r=s?s.startsWith("~")?s.slice(1):s:void 0,o$1=.7,a=.85;try{let l=H.join(e.rootDir,".paradigm","config.yaml");if(E.existsSync(l)){let p=Te.load(E.readFileSync(l,"utf-8"))?.drift;typeof p?.["suggest-threshold"]=="number"&&(o$1=p["suggest-threshold"]),typeof p?.["auto-heal-threshold"]=="number"&&(a=p["auto-heal-threshold"]);}}catch{}let c=null;try{c=await fa$1(e.rootDir);let l=oa$1(c,e.rootDir,r,i,o$1,a),d=l.filter(v=>v.status==="clean").length,p=l.filter(v=>v.status==="cosmetic").length,u=l.filter(v=>v.status==="shifted").length,m=l.filter(v=>v.status==="modified").length,g=l.filter(v=>v.status==="missing").length,y=m>0||g>0,f=p>0||u>0,b=y?"drift-detected":f?"clean-with-heals":"clean",h={...r?{aspectId:r}:{scope:"all"},totalAnchors:l.length,clean:d,cosmetic:p,shifted:u,modified:m,missing:g,status:b,results:l.map(v=>({aspectId:v.aspectId,path:v.path,startLine:v.startLine,endLine:v.endLine,status:v.status,resolvedBy:v.resolvedBy,exists:v.exists,...v.status==="shifted"?{suggestedStart:v.suggestedStart,suggestedEnd:v.suggestedEnd,autoHealed:v.autoHealed}:{},...v.status==="modified"&&v.currentContent?{currentContent:v.currentContent.slice(0,500)}:{}})),...p>0||u>0?{healed:[p>0?`${p} cosmetic (whitespace/formatting \u2014 hashes updated)`:"",u>0?`${u} shifted (line numbers updated via git diff${i?" \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."}:{}},w=JSON.stringify(h,null,2);return ga$1(c,e.rootDir),c=null,o(w.length,"paradigm_aspect_drift"),{handled:!0,text:w}}catch(l){if(c)try{ga$1(c);}catch{}let d=JSON.stringify({error:"Failed to check aspect drift",details:String(l),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(d.length,"paradigm_aspect_drift"),{handled:true,text:d}}}async function _u(t,e){let{query:s,aspectId:n}=t,i=null;try{i=await fa$1(e.rootDir),sc(i,s,n);let r={confirmed:!0,query:s,aspectId:n,message:`Search mapping reinforced: "${s}" -> ${n}. Future searches for similar queries will rank this aspect higher.`},o$1=JSON.stringify(r,null,2);return ga$1(i,e.rootDir),i=null,o(o$1.length,"paradigm_aspect_confirm"),{handled:!0,text:o$1}}catch(r){if(i)try{ga$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to confirm search",details:String(r)},null,2);return o(o$1.length,"paradigm_aspect_confirm"),{handled:true,text:o$1}}}function Su(t,e){let s=H.isAbsolute(e.file_path)?e.file_path:H.join(t,e.file_path);if(!E.existsSync(s))return null;try{let i=E.readFileSync(s,"utf8").split(`
558
+ WHERE query_normalized = ? AND aspect_id != ?`,[_u,n,s]);}catch{}}function ei(t){try{let e=JSON.parse(t);return Array.isArray(e)&&e.length>0?e:void 0}catch{let e=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);return e.length>0?e:void 0}}function uc(){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 gc(t,e,s){switch(t){case "paradigm_aspect_search":return Ou(e,s);case "paradigm_aspect_get":return Iu(e,s);case "paradigm_aspect_graph":return $u(e,s);case "paradigm_aspect_heatmap":return Fu(e,s);case "paradigm_aspect_suggest_scan":return Nu(e,s);case "paradigm_aspect_drift":return Eu(e,s);case "paradigm_aspect_confirm":return Hu(e,s);default:return {handled:false,text:""}}}async function Ou(t,e){let{query:s,limit:n=10}=t,i=null;try{i=await ha$1(e.rootDir);let r=lc(i,s,{limit:n});for(let c of r)try{oa(i,c.id,"search");}catch{}let o$1={query:s,count:r.length,results:r.map(c=>({id:c.id,description:c.description,category:c.category,severity:c.severity,score:Math.round(c.score*1e3)/1e3,tier:c.tier,tags:c.tags,anchorCount:c.anchorCount})),tip:r.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."},a=JSON.stringify(o$1,null,2);return ia$1(i,e.rootDir),i=null,o(a.length,"paradigm_aspect_search"),{handled:!0,text:a}}catch(r){if(i)try{ia$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to search aspects",details:String(r),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(o$1.length,"paradigm_aspect_search"),{handled:true,text:o$1}}}async function Iu(t,e){let{aspectId:s}=t,n=s.startsWith("~")?s.slice(1):s,i=null;try{i=await ha$1(e.rootDir);let r=ja(i,n);if(r||(r=ja(i,`~${n}`)),!r){ia$1(i),i=null;let f=JSON.stringify({error:"Aspect not found",aspectId:n,suggestion:"Use paradigm_aspect_search to find aspects by keyword."},null,2);return o(f.length,"paradigm_aspect_get"),{handled:!0,text:f}}let o$1=r.id,c=ka$1(i,o$1).map(f=>{let b=qu(e.rootDir,f);return {filePath:f.file_path,startLine:f.start_line,endLine:f.end_line,drifted:f.drifted===1,snippet:b}}),l=la$1(i,o$1),d=ma$1(i,o$1),p=[...l.map(f=>({direction:"outgoing",source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin})),...d.map(f=>({direction:"incoming",source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin}))],u=[];try{u=await ra$1(i,e.rootDir,o$1);}catch{}try{oa(i,o$1,"direct");}catch{}let g;if(r.tags)try{let f=JSON.parse(r.tags);Array.isArray(f)&&(g=f);}catch{g=r.tags.split(",").map(f=>f.trim()).filter(f=>f.length>0);}let m={id:o$1,description:r.description,category:r.category,severity:r.severity,value:r.value,enforcement:r.enforcement,definedIn:r.defined_in,tags:g,createdAt:r.created_at,updatedAt:r.updated_at,anchors:c,edges:p,lore:u},y=JSON.stringify(m,null,2);return ia$1(i,e.rootDir),i=null,o(y.length,"paradigm_aspect_get"),{handled:!0,text:y}}catch(r){if(i)try{ia$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to get aspect",details:String(r),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(o$1.length,"paradigm_aspect_get"),{handled:true,text:o$1}}}async function $u(t,e){let{symbol:s,hops:n=2}=t,i=Math.min(Math.max(n,1),5),r=null;try{r=await ha$1(e.rootDir);let o$1=new Set,a=new Map,c=[],l=[{symbol:s,depth:0}];o$1.add(s);let d=ja(r,s);for(a.set(s,{aspectId:s,category:d?.category,severity:d?.severity,depth:0});l.length>0;){let m=l.shift();if(m.depth>=i)continue;let y=na$1(r,m.symbol);for(let f of y){let b=f.source===m.symbol?f.target:f.source;if(c.some(w=>w.source===f.source&&w.target===f.target&&w.relation===f.relation)||c.push({source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin,inferred:f.origin==="inferred"}),!o$1.has(b)){o$1.add(b);let w=ja(r,b);a.set(b,{aspectId:b,category:w?.category,severity:w?.severity,depth:m.depth+1}),l.push({symbol:b,depth:m.depth+1});}}}let p=Array.from(a.values()),u={startSymbol:s,maxHops:i,nodeCount:p.length,edgeCount:c.length,nodes:p,edges:c},g=JSON.stringify(u,null,2);return ia$1(r),r=null,o(g.length,"paradigm_aspect_graph"),{handled:!0,text:g}}catch(o$1){if(r)try{ia$1(r);}catch{}let a=JSON.stringify({error:"Failed to traverse aspect graph",details:String(o$1),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(a.length,"paradigm_aspect_graph"),{handled:true,text:a}}}async function Fu(t,e){let{limit:s=20,accessType:n}=t,i=null;try{i=await ha$1(e.rootDir);let r=pa$1(i,s*4,n),o$1=new Map;for(let d of r){let p=o$1.get(d.aspect_id);if(!p){let u=ja(i,d.aspect_id);p={aspectId:d.aspect_id,description:u?.description,totalCount:0,byType:{},lastAccessed:d.last_accessed},o$1.set(d.aspect_id,p);}p.totalCount+=d.count,p.byType[d.access_type]=d.count,d.last_accessed>p.lastAccessed&&(p.lastAccessed=d.last_accessed);}let a=Array.from(o$1.values()).sort((d,p)=>p.totalCount-d.totalCount).slice(0,s),c={count:a.length,...n?{filteredBy:n}:{},entries:a},l=JSON.stringify(c,null,2);return ia$1(i),i=null,o(l.length,"paradigm_aspect_heatmap"),{handled:!0,text:l}}catch(r){if(i)try{ia$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to get aspect heatmap",details:String(r),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(o$1.length,"paradigm_aspect_heatmap"),{handled:true,text:o$1}}}async function Nu(t,e){let{filePath:s}=t,n=H.isAbsolute(s)?s:H.join(e.rootDir,s);if(!E.existsSync(n)){let i=JSON.stringify({error:"File not found",filePath:n,suggestion:"Provide a valid relative or absolute file path."},null,2);return o(i.length,"paradigm_aspect_suggest_scan"),{handled:true,text:i}}try{let o$1=(await import('../utils/aspect-suggest.js')).suggestAspects(n),a={filePath:n,count:o$1.length,suggestions:o$1.map(l=>({line:l.line,code:l.code,suggestedName:l.suggestedName,category:l.suggestedCategory,description:l.suggestedDescription,confidence:l.confidence,reason:l.reason,inferred:!0})),tip:o$1.length>0?"Review suggestions and add confirmed aspects to your .purpose files with ~ prefix and code anchors.":"No implicit aspects detected in this file."},c=JSON.stringify(a,null,2);return o(c.length,"paradigm_aspect_suggest_scan"),{handled:!0,text:c}}catch(i){let r=String(i);if(r.includes("Cannot find module")||r.includes("MODULE_NOT_FOUND")){let a=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 o(a.length,"paradigm_aspect_suggest_scan"),{handled:true,text:a}}let o$1=JSON.stringify({error:"Failed to scan for aspect suggestions",details:r},null,2);return o(o$1.length,"paradigm_aspect_suggest_scan"),{handled:true,text:o$1}}}async function Eu(t,e){let{aspectId:s,autoHeal:n}=t,i=n!==false,r=s?s.startsWith("~")?s.slice(1):s:void 0,o$1=.7,a=.85;try{let l=H.join(e.rootDir,".paradigm","config.yaml");if(E.existsSync(l)){let p=Ae.load(E.readFileSync(l,"utf-8"))?.drift;typeof p?.["suggest-threshold"]=="number"&&(o$1=p["suggest-threshold"]),typeof p?.["auto-heal-threshold"]=="number"&&(a=p["auto-heal-threshold"]);}}catch{}let c=null;try{c=await ha$1(e.rootDir);let l=qa$1(c,e.rootDir,r,i,o$1,a),d=l.filter(v=>v.status==="clean").length,p=l.filter(v=>v.status==="cosmetic").length,u=l.filter(v=>v.status==="shifted").length,g=l.filter(v=>v.status==="modified").length,m=l.filter(v=>v.status==="missing").length,y=g>0||m>0,f=p>0||u>0,b=y?"drift-detected":f?"clean-with-heals":"clean",h={...r?{aspectId:r}:{scope:"all"},totalAnchors:l.length,clean:d,cosmetic:p,shifted:u,modified:g,missing:m,status:b,results:l.map(v=>({aspectId:v.aspectId,path:v.path,startLine:v.startLine,endLine:v.endLine,status:v.status,resolvedBy:v.resolvedBy,exists:v.exists,...v.status==="shifted"?{suggestedStart:v.suggestedStart,suggestedEnd:v.suggestedEnd,autoHealed:v.autoHealed}:{},...v.status==="modified"&&v.currentContent?{currentContent:v.currentContent.slice(0,500)}:{}})),...p>0||u>0?{healed:[p>0?`${p} cosmetic (whitespace/formatting \u2014 hashes updated)`:"",u>0?`${u} shifted (line numbers updated via git diff${i?" \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."}:{}},w=JSON.stringify(h,null,2);return ia$1(c,e.rootDir),c=null,o(w.length,"paradigm_aspect_drift"),{handled:!0,text:w}}catch(l){if(c)try{ia$1(c);}catch{}let d=JSON.stringify({error:"Failed to check aspect drift",details:String(l),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(d.length,"paradigm_aspect_drift"),{handled:true,text:d}}}async function Hu(t,e){let{query:s,aspectId:n}=t,i=null;try{i=await ha$1(e.rootDir),dc(i,s,n);let r={confirmed:!0,query:s,aspectId:n,message:`Search mapping reinforced: "${s}" -> ${n}. Future searches for similar queries will rank this aspect higher.`},o$1=JSON.stringify(r,null,2);return ia$1(i,e.rootDir),i=null,o(o$1.length,"paradigm_aspect_confirm"),{handled:!0,text:o$1}}catch(r){if(i)try{ia$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to confirm search",details:String(r)},null,2);return o(o$1.length,"paradigm_aspect_confirm"),{handled:true,text:o$1}}}function qu(t,e){let s=H.isAbsolute(e.file_path)?e.file_path:H.join(t,e.file_path);if(!E.existsSync(s))return null;try{let i=E.readFileSync(s,"utf8").split(`
475
559
  `),r=Math.max(0,e.start_line-1),o=Math.min(i.length,e.end_line),a=i.slice(r,o).join(`
476
560
  `);return a.length>1e3?a.slice(0,1e3)+`
477
- ... (truncated)`:a}catch{return null}}function ac(){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"}},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","done","shelved","all"],description:"Filter by status (default: open)"},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","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"}},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 cc(t,e,s){switch(t){case "paradigm_task_create":{let n=await c$3(s.rootDir,{blurb:e.blurb,priority:e.priority,tags:e.tags,related_lore:e.related_lore}),i=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({created:n,task:i},null,2)}}case "paradigm_task_list":{let n=await a$7(s.rootDir,{status:e.status||"open",priority:e.priority,tag:e.tag,limit:e.limit||20}),i=e.status||"open",r=[`${n.length} ${i} task(s):`];for(let o of n){let a=o.tags.length>0?` [${o.tags.join(", ")}]`:"";r.push(` [${o.priority}] ${o.id}: ${o.blurb}${a}`);}return {handled:true,text:r.join(`
478
- `)}}case "paradigm_task_update":{let n=e.id,i={};if(e.blurb!==void 0&&(i.blurb=e.blurb),e.priority!==void 0&&(i.priority=e.priority),e.status!==void 0&&(i.status=e.status),e.tags!==void 0&&(i.tags=e.tags),e.related_lore!==void 0&&(i.related_lore=e.related_lore),e.related_assessments!==void 0&&(i.related_assessments=e.related_assessments),!await d$6(s.rootDir,n,i))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let o=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({updated:n,task:o},null,2)}}case "paradigm_task_done":{let n=e.id;if(!await e$5(s.rootDir,n))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let r=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({completed:n,task:r,hint:"Consider recording a lore entry with arc:* tags if this was a significant milestone."},null,2)}}case "paradigm_task_shelve":{let n=e.id;if(!await f$3(s.rootDir,n))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let r=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({shelved:n,task:r},null,2)}}default:return {handled:false,text:""}}}var lc=0;function dc(){let t=new Date().toISOString().slice(0,10);return lc++,`run_${t}_${String(lc).padStart(3,"0")}`}var pc=/\{\{([^}]+)\}\}/g;function ct(t,e){if(typeof t=="string")return t.replace(pc,(s,n)=>{let i=xu(n.trim(),e);return i!==void 0?String(i):s});if(Array.isArray(t))return t.map(s=>ct(s,e));if(t&&typeof t=="object"){let s={};for(let[n,i]of Object.entries(t))s[n]=ct(i,e);return s}return t}function xu(t,e){let[s,...n]=t.split("."),i=n.join(".");switch(s){case "fixtures":return e.fixtures[i];case "produces":return Ks(e.produces,i);case "context":case "parent":return e.context[i];case "env":return e.env[i]??process.env[i];default:return}}function Ks(t,e){let s=e.split(/[.\[\]]+/).filter(Boolean),n=t;for(let i of s){if(n==null||typeof n!="object")return;n=n[i];}return n}function Cu(t,e){let s={};for(let[n,i]of Object.entries(t)){let r=i.match(/\{\{response\.(.+)\}\}/);if(r){let o=r[1],a=Ks(e,o);a!==void 0&&(s[n]=a);}}return s}function Ru(t,e){if(e.status!==t.status)return {pass:false,failure:`Status mismatch: expected ${t.status}, got ${e.status}`};if(t.body){let s=e.body;if(t.body.has){for(let n of t.body.has)if(s===null||typeof s!="object"||!(n in s))return {pass:false,failure:`Expected body to have key "${n}"`}}if(t.body.match)for(let[n,i]of Object.entries(t.body.match)){let r=Ks(s,n);if(JSON.stringify(r)!==JSON.stringify(i))return {pass:false,failure:`Body mismatch at "${n}": expected ${JSON.stringify(i)}, got ${JSON.stringify(r)}`}}}return {pass:true}}async function Pu(t,e,s){let n=Date.now(),i=t.route.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(.*)/);if(!i)return {id:t.id,status:"fail",route:t.route,gates:t.gates,failure:`Invalid route format: ${t.route}`,duration_ms:Date.now()-n};let r=i[1],o=i[2],a=ct(o,s),c=`${e.baseUrl.replace(/\/$/,"")}${a}`,l={"Content-Type":"application/json",...t.headers?ct(t.headers,s):{}},d=t.payload?ct(t.payload,s):void 0,p={url:c,method:r,headers:t.headers?l:void 0,payload:d};if(e.dryRun)return {id:t.id,status:"pass",route:t.route,gates:t.gates,request:p,produced:t.produces?Object.fromEntries(Object.keys(t.produces).map(u=>[u,`<dry-run:${u}>`])):void 0,duration_ms:Date.now()-n};try{let u={method:r,headers:l};d&&["POST","PUT","PATCH"].includes(r)&&(u.body=JSON.stringify(d));let m=await fetch(c,u),g;(m.headers.get("content-type")||"").includes("application/json")?g=await m.json():g=await m.text();let f={status:m.status,body:g},b=Ru(t.expect,f),h;t.produces&&b.pass&&(h=Cu(t.produces,g));let w;return (m.status===401||m.status===403)&&(w=t.gates[t.gates.length-1]),{id:t.id,status:b.pass?"pass":"fail",route:t.route,gates:t.gates,request:p,response:f,produced:h,expected_status:b.pass?void 0:t.expect.status,failure:b.failure,gate_that_blocked:w,duration_ms:Date.now()-n}}catch(u){return {id:t.id,status:"fail",route:t.route,gates:t.gates,request:p,failure:`Request failed: ${u.message}`,duration_ms:Date.now()-n}}}async function uc(t,e,s){let n=Date.now(),i=await x$1(t,e);return i?gc(t,i,s):{persona:e,run_id:dc(),status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${e} not found`,duration_ms:Date.now()-n}}async function gc(t,e,s){let n=Date.now(),i=s.stopOnFailure!==false,r={fixtures:e.fixtures||{},produces:{},context:s.context||{},env:process.env},o=[],a=[],c=[],l=false;for(let y of e.journey){if(l&&i){if(o.push({id:y.id,status:"skip",route:y.route,gates:y.gates,duration_ms:0}),y.spawns)for(let b of y.spawns)c.push(b.persona);continue}let f=await Pu(y,s,r);if(o.push(f),f.status==="pass"){if(f.produced&&Object.assign(r.produces,f.produced),y.spawns)for(let b of y.spawns)a.push(b.persona);}else if(l=true,y.spawns)for(let b of y.spawns)c.push(b.persona);}let d=o.filter(y=>y.status==="pass").length,p=o.filter(y=>y.status==="fail").length,u=e.journey.length,m=o.find(y=>y.status==="fail"),g;return p===0?g=`${d}/${u} passed. All steps succeeded.`:g=`${d}/${u} passed. Failed at step ${o.indexOf(m)+1} (${m.id}): ${m.failure}`,{persona:e.id,run_id:dc(),status:p>0?"fail":"pass",steps:o,spawns_triggered:a,spawns_blocked:c,summary:g,duration_ms:Date.now()-n}}async function mc(t,e,s){let n=Date.now(),i=await import('fs'),r=await import('path'),o=await import('js-yaml'),a=r.join(t,".paradigm","personas","chains",`${e}.yaml`);if(!i.existsSync(a))return {chain_id:e,status:"error",persona_results:[],summary:`Chain ${e} not found`,duration_ms:Date.now()-n};let c=o.load(i.readFileSync(a,"utf8")),l;if(s.permutation&&c.permutations&&(l=c.permutations.find(y=>y.id===s.permutation),!l))return {chain_id:e,status:"error",persona_results:[],summary:`Permutation ${s.permutation} not found in chain ${e}`,duration_ms:Date.now()-n};let d=[],p={},u=s.stopOnFailure!==false;for(let y of c.order){let f=await x$1(t,y.persona);if(!f){if(d.push({persona:y.persona,status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${y.persona} not found`,duration_ms:0}),u)break;continue}if(l&&l.overrides[y.persona]){let v=l.overrides[y.persona];if(v.traits&&(f.traits={...f.traits,...v.traits}),v.journey)for(let[k,_]of Object.entries(v.journey)){let x=f.journey.find(C=>C.id===k);x&&(_.payload&&(x.payload={...x.payload,..._.payload}),_.expect&&(x.expect={...x.expect,..._.expect}));}}let b={};if(y.wait_for){let[v,k]=y.wait_for.split("."),_=d.find(C=>C.persona===v);if(_){let C=_.steps.find(S=>S.id===k);C?.produced&&(b=Object.fromEntries(Object.entries(C.produced).map(([S,R])=>[S,String(R)])));}let x=await x$1(t,v);if(x){let C=x.journey.find(S=>S.id===k);if(C?.spawns){let S=C.spawns.find(R=>R.persona===y.persona);if(S?.context){let R=p[v]||{};for(let[I,P]of Object.entries(S.context))b[I]=String(ct(P,{fixtures:{},produces:R,context:{},env:process.env}));}}}}let h=await gc(t,f,{...s,context:b});d.push(h);let w={};for(let v of h.steps)v.produced&&Object.assign(w,v.produced);if(p[y.persona]=w,h.status==="fail"&&u)break}let m=d.filter(y=>y.status==="pass").length,g=c.order.length;return {chain_id:e,status:d.some(y=>y.status!=="pass")?"fail":"pass",persona_results:d,summary:`${m}/${g} personas passed.`,duration_ms:Date.now()-n}}function fc(t){let e=[],s=new Set;for(let n of t.journey){let r=JSON.stringify(n).match(pc)||[];for(let o of r){let a=o.replace("{{","").replace("}}","").trim(),[c,...l]=a.split("."),d=l.join(".");switch(c){case "fixtures":!t.fixtures||d in t.fixtures;break;case "produces":s.has(d)||e.push({step:n.id,template:o,error:`{{produces.${d}}} used but not produced by a prior step`});break;case "context":case "parent":break;case "env":break;case "response":break;default:e.push({step:n.id,template:o,error:`Unknown namespace "${c}" in ${o}`});}}if(n.produces)for(let o of Object.keys(n.produces))s.add(o);}return {valid:e.length===0,errors:e}}var hc="paradigm-personas",ju={id:hc,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"}}},Qs=false;async function yc(t){try{let{SentinelStorage:e}=await import('./dist-W3XCATBJ.js'),s=new e;if(!Qs)try{s.registerSchema(ju),Qs=!0;}catch{Qs=!0;}let n=[];if("persona"in t){let i=t;n.push({type:"persona.run.start",timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,total_steps:i.steps.length}});for(let r of i.steps){let o=r.status==="pass"?"persona.step.complete":`persona.step.${r.status}`;n.push({type:o,timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,step_id:r.id,route:r.route,gates:r.gates,gates_traversed:r.gates,status:r.response?.status,body:r.response?.body,signals_fired:[],duration_ms:r.duration_ms,failure:r.failure,gate_that_blocked:r.gate_that_blocked,produced_keys:r.produced?Object.keys(r.produced):[]}});}n.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,status:i.status,total_steps:i.steps.length,passed:i.steps.filter(r=>r.status==="pass").length,failed:i.steps.filter(r=>r.status==="fail").length,skipped:i.steps.filter(r=>r.status==="skip").length,duration_ms:i.duration_ms,spawns_triggered:i.spawns_triggered,spawns_blocked:i.spawns_blocked}});}else {let i=t;for(let r of i.persona_results)n.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:r.persona,data:{persona_id:r.persona,run_id:r.run_id,chain_id:i.chain_id,status:r.status,total_steps:r.steps.length,passed:r.steps.filter(o=>o.status==="pass").length,failed:r.steps.filter(o=>o.status==="fail").length,duration_ms:r.duration_ms}});n.push({type:"persona.chain.complete",timestamp:new Date().toISOString(),data:{chain_id:i.chain_id,status:i.status,personas_run:i.persona_results.length,personas_passed:i.persona_results.filter(r=>r.status==="pass").length,duration_ms:i.duration_ms}});}n.length>0&&s.insertEventBatch(hc,"paradigm-personas",n);}catch{}}function bc(){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 wc(t,e,s){switch(t){case "paradigm_persona_create":try{let n=await y$1(s.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}),i=await x$1(s.rootDir,n);return {handled:!0,text:JSON.stringify({created:n,persona:i},null,2)}}catch(n){return {handled:true,text:JSON.stringify({error:n.message})}}case "paradigm_persona_get":{let n=e.id,i=await x$1(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Persona ${n} not found`})};let r=await D(s.rootDir,i);return {handled:true,text:JSON.stringify({persona:i,validation:r},null,2)}}case "paradigm_persona_list":{let n=await w(s.rootDir,{tag:e.tag,trigger_type:e.trigger_type,gate:e.gate,flow:e.flow,limit:e.limit||50}),i=n.map(r=>({id:r.id,name:r.name,trigger:r.trigger.type,steps:r.journey.length,gates:[...new Set(r.journey.flatMap(o=>o.gates))],tags:r.tags||[]}));return {handled:true,text:JSON.stringify({count:n.length,personas:i},null,2)}}case "paradigm_persona_update":{let n=e.id,i={};if(e.name!==void 0&&(i.name=e.name),e.description!==void 0&&(i.description=e.description),e.traits!==void 0&&(i.traits=e.traits),e.trigger!==void 0&&(i.trigger=e.trigger),e.fixtures!==void 0&&(i.fixtures=e.fixtures),e.tags!==void 0&&(i.tags=e.tags),e.journey!==void 0&&(i.journey=e.journey),!await z$1(s.rootDir,n,i))return {handled:true,text:JSON.stringify({error:`Persona ${n} not found`})};let o=await x$1(s.rootDir,n);return {handled:true,text:JSON.stringify({updated:n,persona:o},null,2)}}case "paradigm_persona_delete":{let n=e.id,i=await A$1(s.rootDir,n);return i.deleted?{handled:true,text:JSON.stringify({deleted:n,warnings:i.warnings,hint:i.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 ${n} not found`})}}case "paradigm_persona_add_step":try{if(!await B(s.rootDir,e.persona_id,e.step,e.after))return {handled:!0,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let i=await x$1(s.rootDir,e.persona_id);return {handled:!0,text:JSON.stringify({added:e.step.id,persona_id:e.persona_id,total_steps:i?.journey.length},null,2)}}catch(n){return {handled:true,text:JSON.stringify({error:n.message})}}case "paradigm_persona_remove_step":{let n=await C(s.rootDir,e.persona_id,e.step_id);return n.removed?{handled:true,text:JSON.stringify({removed:e.step_id,persona_id:e.persona_id,warnings:n.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 n=e.deep??false,i=e.sentinel??true,r={run_id:e.run_id,chain_id:e.chain_id,environment:e.environment};if(e.persona_id){let d=await x$1(s.rootDir,e.persona_id);if(!d)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let p=await D(s.rootDir,d,n);if(i)try{let u=await G(d,r);p.sentinel_assertions=u,(u.summary.failed>0||u.summary.unmatched>0)&&(p.valid=!1);}catch{}return {handled:true,text:JSON.stringify(p,null,2)}}let o=await w(s.rootDir),a=await Promise.all(o.map(async d=>{let p=await D(s.rootDir,d,n);if(i)try{let u=await G(d,r);p.sentinel_assertions=u,(u.summary.failed>0||u.summary.unmatched>0)&&(p.valid=!1);}catch{}return p})),c=a.filter(d=>d.valid).length,l=a.filter(d=>!d.valid).length;return {handled:true,text:JSON.stringify({total:a.length,valid:c,invalid:l,results:a.filter(d=>!d.valid||d.warnings.length>0||d.sentinel_assertions)},null,2)}}case "paradigm_persona_coverage":{let n=await E$1(s.rootDir);return {handled:true,text:JSON.stringify(n,null,2)}}case "paradigm_persona_affected":{let n=e.symbol,i=await F(s.rootDir,n);return i.length===0?{handled:true,text:JSON.stringify({symbol:n,affected:[],note:"No personas reference this symbol."})}:{handled:true,text:JSON.stringify({symbol:n,affected:i},null,2)}}case "paradigm_persona_run":{let n=e.base_url,i=e.dry_run??false,r=e.stop_on_failure??true;if(e.chain_id){let o=await mc(s.rootDir,e.chain_id,{baseUrl:n,dryRun:i,stopOnFailure:r,permutation:e.permutation});return i||await yc(o),{handled:true,text:JSON.stringify(o,null,2)}}if(e.persona_id){let o=await x$1(s.rootDir,e.persona_id);if(!o)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let a=fc(o);if(!a.valid&&!i)return {handled:true,text:JSON.stringify({error:"Template interpolation errors \u2014 fix before running",errors:a.errors,hint:"Use dry_run: true to see interpolated values without executing requests"},null,2)};let c=await uc(s.rootDir,e.persona_id,{baseUrl:n,dryRun:i,stopOnFailure:r});return i||await yc(c),{handled:true,text:JSON.stringify(c,null,2)}}return {handled:true,text:JSON.stringify({error:"Either persona_id or chain_id is required"})}}default:return {handled:false,text:""}}}var Tu=".paradigm/graphs",ei={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},Xs=200,Zs=60,lt=20,Wn=40,vc=50,Du=60;function _c(){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 Sc(t,e,s){if(t!=="paradigm_graph_generate")return {handled:false,text:""};try{let n=e.name||"untitled",i=n.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),r=Iu(s.rootDir,e.symbols,e.groups,e.links,n),o$1=JSON.stringify(r,null,2),a=H.join(s.rootDir,Tu);E.existsSync(a)||E.mkdirSync(a,{recursive:!0});let c=H.join(a,`${i}.graph.json`);E.writeFileSync(c,o$1,"utf8");let l=JSON.stringify({file:c,name:n,slug:i,nodes:r.nodes.length,edges:r.edges.length,size:`${(o$1.length/1024).toFixed(1)} KB`,hint:"Graph saved. Run `paradigm graph` to view in browser."},null,2);return o(l.length,t),{handled:!0,text:l}}catch(n){let i=JSON.stringify({error:n.message},null,2);return o(i.length,t),{handled:true,text:i}}}var Au={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"};function Ou(t){let e=H.join(t,".paradigm","scan-index.json");if(!E.existsSync(e))return [];let s=JSON.parse(E.readFileSync(e,"utf8")),n=[];for(let[i,r]of Object.entries(Au)){let o=s[i];if(!(!o||typeof o!="object"))for(let[a,c]of Object.entries(o)){let l=c;n.push({id:a,name:a,category:r,prefix:ei[r]||"#",description:l.description,path:l.path,tags:l.tags});}}return n}function kc(t,e){let s=t.replace(/^[#$^!~]/,"");return e.find(n=>n.id===s||n.name===s||n.id===t||n.name===t)}function Iu(t,e,s,n,i="Generated Graph"){let r=Ou(t),o;e&&e.length>0?o=e.map(m=>kc(m,r)).filter(Boolean):o=r;let a=[],c=[],l=new Map,d=new Set,p=0;if(s&&s.length>0)for(let m of s){let g=`group-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;l.set(m.label,g);let y=m.symbols.map(_=>kc(_,o)).filter(Boolean),f=Math.ceil(Math.sqrt(y.length)),b=Math.ceil(y.length/f);for(let _=0;_<y.length;_++){let x=y[_],C=_%f,S=Math.floor(_/f),R=ei[x.category]||"#";a.push({id:`sym-${x.id}`,type:"symbolNode",position:{x:Wn+C*(Xs+lt),y:vc+Wn+S*(Zs+lt)},parentId:g,data:{type:"symbol",symbol:x,label:`${R}${x.name}`}}),d.add(x.id);}let h=Math.max(f,1),w=Math.max(b,1),v=Wn*2+h*Xs+(h-1)*lt,k=vc+Wn*2+w*Zs+(w-1)*lt;a.unshift({id:g,type:"groupNode",position:{x:p,y:0},style:{width:v,height:k},data:{type:"group",label:m.label}}),p+=v+Du;}let u=o.filter(m=>!d.has(m.id));if(u.length>0){let m=s&&s.length>0?400:0,g=Math.ceil(Math.sqrt(u.length));for(let y=0;y<u.length;y++){let f=u[y],b=y%g,h=Math.floor(y/g),w=ei[f.category]||"#";a.push({id:`sym-${f.id}`,type:"symbolNode",position:{x:b*(Xs+lt),y:m+h*(Zs+lt)},data:{type:"symbol",symbol:f,label:`${w}${f.name}`}});}}if(n&&n.length>0)for(let m of n){let g=l.get(m.source),y=l.get(m.target);g&&y&&c.push({id:`e-${g}-${y}`,source:g,target:y,type:"default",label:m.label,data:{label:m.label}});}return {version:"1.0",name:i,projectId:H.basename(t),lastModified:new Date().toISOString(),nodes:a,edges:c}}var ge=["specify","plan","task","implement","validate"],Wt=".paradigm/pipeline",xc={"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 Gn(t){return t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Lt(t,e){let s=Gn(e),n=H.join(t,Wt,`${s}.yaml`);return E.existsSync(n)?Te.load(E.readFileSync(n,"utf8")):null}function Mt(t,e){let s=Gn(e.feature),n=H.join(t,Wt);E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=H.join(n,`${s}.yaml`);return E.writeFileSync(i,Te.dump(e,{lineWidth:120}),"utf8"),i}function Cc(t){let e=H.join(t,Wt);return E.existsSync(e)?E.readdirSync(e).filter(s=>s.endsWith(".yaml")&&!s.startsWith("completed")).map(s=>{try{return Te.load(E.readFileSync(H.join(e,s),"utf8"))}catch{return null}}).filter(Boolean):[]}function $u(t,e,s){let n={specify:{status:"pending"},plan:{status:"pending"},task:{status:"pending"},implement:{status:"pending"},validate:{status:"pending"}};return n.specify.status="in-progress",{version:"1.0",feature:Gn(t),created:new Date().toISOString(),current_stage:"specify",gate_config:e,template:s,stages:n}}function Fu(t){let e=ge.indexOf(t);return e<ge.length-1?ge[e+1]:null}function Rc(t,e){let s=Gn(e.feature),n=H.join(t,Wt,"completed");E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=H.join(n,`${s}.yaml`);E.writeFileSync(i,Te.dump(e,{lineWidth:120}),"utf8");let r=H.join(t,Wt,`${s}.yaml`);E.existsSync(r)&&E.unlinkSync(r);}function Pc(){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 jc(t,e,s){switch(t){case "paradigm_pipeline_start":{let n=e.feature,i=e.template||"add-feature",r=e.gates,o;if(r)o={specify:r.specify||"manual",plan:r.plan||"manual",task:r.task||"auto",implement:r.implement||"sentinel",validate:r.validate||"sentinel"};else {let l=xc[i];if(!l)return {handled:true,text:JSON.stringify({error:`Unknown template: ${i}`,available:Object.keys(xc)})};o=l.gates;}let a=$u(n,o,i),c=Mt(s.rootDir,a);return {handled:true,text:JSON.stringify({created:true,feature:a.feature,template:i,file:c,current_stage:a.current_stage,gate_config:a.gate_config,stages:a.stages,hint:`Pipeline '${a.feature}' started at 'specify' stage. Create your spec, then call paradigm_pipeline_advance to move to 'plan'.`},null,2)}}case "paradigm_pipeline_status":{let n=e.feature;if(n){let r=Lt(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let o=ge.filter(a=>r.stages[a].status==="approved").length;return {handled:true,text:JSON.stringify({feature:r.feature,created:r.created,template:r.template,current_stage:r.current_stage,progress:`${o}/${ge.length}`,gate_config:r.gate_config,stages:r.stages},null,2)}}let i=Cc(s.rootDir);return i.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:i.length,pipelines:i.map(r=>{let o=ge.filter(a=>r.stages[a].status==="approved").length;return {feature:r.feature,current_stage:r.current_stage,progress:`${o}/${ge.length}`,template:r.template,created:r.created}})},null,2)}}case "paradigm_pipeline_advance":{let n=e.feature,i=e.approved_by||"agent",r=Lt(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let o=r.current_stage,a=r.gate_config[o],c=Fu(o);return r.stages[o].status="approved",r.stages[o].approved_by=i,r.stages[o].approved_at=new Date().toISOString(),a==="auto"&&(r.stages[o].auto_passed_at=new Date().toISOString()),c?(r.current_stage=c,r.stages[c].status="in-progress",Mt(s.rootDir,r),{handled:true,text:JSON.stringify({advanced:true,from:o,to:c,gate_mode:a,approved_by:i,pipeline:{feature:r.feature,current_stage:r.current_stage,stages:r.stages}},null,2)}):(Mt(s.rootDir,r),Rc(s.rootDir,r),{handled:true,text:JSON.stringify({completed:true,feature:r.feature,message:`Pipeline '${r.feature}' completed and archived.`,stages:r.stages},null,2)})}case "paradigm_pipeline_configure":{let n=e.feature,i=e.updates,r=e.reason,o=Lt(s.rootDir,n);if(!o)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let a=[];for(let[c,l]of Object.entries(i))if(ge.includes(c)&&["auto","manual","sentinel"].includes(l)){let d=o.gate_config[c];o.gate_config[c]=l,a.push({stage:c,from:d,to:l});}return a.length===0?{handled:true,text:JSON.stringify({error:"No valid gate updates provided",valid_stages:ge,valid_modes:["auto","manual","sentinel"]})}:(Mt(s.rootDir,o),{handled:true,text:JSON.stringify({configured:true,feature:o.feature,changes:a,reason:r,gate_config:o.gate_config},null,2)})}case "paradigm_pipeline_escalate":{let n=e.feature,i=e.stage,r=e.question,o=e.options,a=e.context,c=Lt(s.rootDir,n);return c?(c.stages[i].status="blocked",c.stages[i].block_reason=r,Mt(s.rootDir,c),{handled:true,text:JSON.stringify({escalated:true,feature:c.feature,stage:i,question:r,options:o,context:a||{},current_gate:c.gate_config[i],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: ${n}`})}}case "paradigm_pipeline_abort":{let n=e.feature,i=Lt(s.rootDir,n);return i?(Rc(s.rootDir,i),{handled:true,text:JSON.stringify({aborted:true,feature:i.feature,message:`Pipeline '${i.feature}' aborted and archived.`})}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})}}case "paradigm_pipeline_list":{let n=Cc(s.rootDir);return n.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines."})}:{handled:true,text:JSON.stringify({count:n.length,pipelines:n.map(i=>{let r=ge.filter(o=>i.stages[o].status==="approved").length;return {feature:i.feature,current_stage:i.current_stage,progress:`${r}/${ge.length}`,template:i.template,created:i.created}})},null,2)}}default:return {handled:false,text:""}}}b$1();var Nu=H.join(ra.homedir(),".conductor"),ut=H.join(Nu,"sessions");function Dc(){E.existsSync(ut)||E.mkdirSync(ut,{recursive:true});}function ni(t){Dc();let e={...t,registeredAt:new Date().toISOString()},s=H.join(ut,`${t.pid}.json`);return E.writeFileSync(s,JSON.stringify(e,null,2),"utf-8"),e}function Jn(t){let e=H.join(ut,`${t}.json`);return E.existsSync(e)?(E.unlinkSync(e),true):false}function si(){Dc();let t=E.readdirSync(ut).filter(s=>s.endsWith(".json")),e=[];for(let s of t)try{let n=E.readFileSync(H.join(ut,s),"utf-8"),i=JSON.parse(n);e.push(i);}catch{}return e}function Ac(){let t=si(),e=0;for(let s of t)Eu(s.pid)||(Jn(s.pid),e++);return e}function Eu(t){try{return process.kill(t,0),!0}catch{return false}}function ii(){try{return execSync(`osascript -e '
561
+ ... (truncated)`:a}catch{return null}}function mc(){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"}},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","done","shelved","all"],description:"Filter by status (default: open)"},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","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"}},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 fc(t,e,s){switch(t){case "paradigm_task_create":{let n=await c$3(s.rootDir,{blurb:e.blurb,priority:e.priority,tags:e.tags,related_lore:e.related_lore}),i=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({created:n,task:i},null,2)}}case "paradigm_task_list":{let n=await a$7(s.rootDir,{status:e.status||"open",priority:e.priority,tag:e.tag,limit:e.limit||20}),i=e.status||"open",r=[`${n.length} ${i} task(s):`];for(let o of n){let a=o.tags.length>0?` [${o.tags.join(", ")}]`:"";r.push(` [${o.priority}] ${o.id}: ${o.blurb}${a}`);}return {handled:true,text:r.join(`
562
+ `)}}case "paradigm_task_update":{let n=e.id,i={};if(e.blurb!==void 0&&(i.blurb=e.blurb),e.priority!==void 0&&(i.priority=e.priority),e.status!==void 0&&(i.status=e.status),e.tags!==void 0&&(i.tags=e.tags),e.related_lore!==void 0&&(i.related_lore=e.related_lore),e.related_assessments!==void 0&&(i.related_assessments=e.related_assessments),!await d$6(s.rootDir,n,i))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let o=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({updated:n,task:o},null,2)}}case "paradigm_task_done":{let n=e.id;if(!await e$5(s.rootDir,n))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let r=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({completed:n,task:r,hint:"Consider recording a lore entry with arc:* tags if this was a significant milestone."},null,2)}}case "paradigm_task_shelve":{let n=e.id;if(!await f$3(s.rootDir,n))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let r=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({shelved:n,task:r},null,2)}}default:return {handled:false,text:""}}}var yc=0;function hc(){let t=new Date().toISOString().slice(0,10);return yc++,`run_${t}_${String(yc).padStart(3,"0")}`}var bc=/\{\{([^}]+)\}\}/g;function ct(t,e){if(typeof t=="string")return t.replace(bc,(s,n)=>{let i=Lu(n.trim(),e);return i!==void 0?String(i):s});if(Array.isArray(t))return t.map(s=>ct(s,e));if(t&&typeof t=="object"){let s={};for(let[n,i]of Object.entries(t))s[n]=ct(i,e);return s}return t}function Lu(t,e){let[s,...n]=t.split("."),i=n.join(".");switch(s){case "fixtures":return e.fixtures[i];case "produces":return ti(e.produces,i);case "context":case "parent":return e.context[i];case "env":return e.env[i]??process.env[i];default:return}}function ti(t,e){let s=e.split(/[.\[\]]+/).filter(Boolean),n=t;for(let i of s){if(n==null||typeof n!="object")return;n=n[i];}return n}function Mu(t,e){let s={};for(let[n,i]of Object.entries(t)){let r=i.match(/\{\{response\.(.+)\}\}/);if(r){let o=r[1],a=ti(e,o);a!==void 0&&(s[n]=a);}}return s}function Wu(t,e){if(e.status!==t.status)return {pass:false,failure:`Status mismatch: expected ${t.status}, got ${e.status}`};if(t.body){let s=e.body;if(t.body.has){for(let n of t.body.has)if(s===null||typeof s!="object"||!(n in s))return {pass:false,failure:`Expected body to have key "${n}"`}}if(t.body.match)for(let[n,i]of Object.entries(t.body.match)){let r=ti(s,n);if(JSON.stringify(r)!==JSON.stringify(i))return {pass:false,failure:`Body mismatch at "${n}": expected ${JSON.stringify(i)}, got ${JSON.stringify(r)}`}}}return {pass:true}}async function Gu(t,e,s){let n=Date.now(),i=t.route.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(.*)/);if(!i)return {id:t.id,status:"fail",route:t.route,gates:t.gates,failure:`Invalid route format: ${t.route}`,duration_ms:Date.now()-n};let r=i[1],o=i[2],a=ct(o,s),c=`${e.baseUrl.replace(/\/$/,"")}${a}`,l={"Content-Type":"application/json",...t.headers?ct(t.headers,s):{}},d=t.payload?ct(t.payload,s):void 0,p={url:c,method:r,headers:t.headers?l:void 0,payload:d};if(e.dryRun)return {id:t.id,status:"pass",route:t.route,gates:t.gates,request:p,produced:t.produces?Object.fromEntries(Object.keys(t.produces).map(u=>[u,`<dry-run:${u}>`])):void 0,duration_ms:Date.now()-n};try{let u={method:r,headers:l};d&&["POST","PUT","PATCH"].includes(r)&&(u.body=JSON.stringify(d));let g=await fetch(c,u),m;(g.headers.get("content-type")||"").includes("application/json")?m=await g.json():m=await g.text();let f={status:g.status,body:m},b=Wu(t.expect,f),h;t.produces&&b.pass&&(h=Mu(t.produces,m));let w;return (g.status===401||g.status===403)&&(w=t.gates[t.gates.length-1]),{id:t.id,status:b.pass?"pass":"fail",route:t.route,gates:t.gates,request:p,response:f,produced:h,expected_status:b.pass?void 0:t.expect.status,failure:b.failure,gate_that_blocked:w,duration_ms:Date.now()-n}}catch(u){return {id:t.id,status:"fail",route:t.route,gates:t.gates,request:p,failure:`Request failed: ${u.message}`,duration_ms:Date.now()-n}}}async function wc(t,e,s){let n=Date.now(),i=await x$1(t,e);return i?vc(t,i,s):{persona:e,run_id:hc(),status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${e} not found`,duration_ms:Date.now()-n}}async function vc(t,e,s){let n=Date.now(),i=s.stopOnFailure!==false,r={fixtures:e.fixtures||{},produces:{},context:s.context||{},env:process.env},o=[],a=[],c=[],l=false;for(let y of e.journey){if(l&&i){if(o.push({id:y.id,status:"skip",route:y.route,gates:y.gates,duration_ms:0}),y.spawns)for(let b of y.spawns)c.push(b.persona);continue}let f=await Gu(y,s,r);if(o.push(f),f.status==="pass"){if(f.produced&&Object.assign(r.produces,f.produced),y.spawns)for(let b of y.spawns)a.push(b.persona);}else if(l=true,y.spawns)for(let b of y.spawns)c.push(b.persona);}let d=o.filter(y=>y.status==="pass").length,p=o.filter(y=>y.status==="fail").length,u=e.journey.length,g=o.find(y=>y.status==="fail"),m;return p===0?m=`${d}/${u} passed. All steps succeeded.`:m=`${d}/${u} passed. Failed at step ${o.indexOf(g)+1} (${g.id}): ${g.failure}`,{persona:e.id,run_id:hc(),status:p>0?"fail":"pass",steps:o,spawns_triggered:a,spawns_blocked:c,summary:m,duration_ms:Date.now()-n}}async function kc(t,e,s){let n=Date.now(),i=await import('fs'),r=await import('path'),o=await import('js-yaml'),a=r.join(t,".paradigm","personas","chains",`${e}.yaml`);if(!i.existsSync(a))return {chain_id:e,status:"error",persona_results:[],summary:`Chain ${e} not found`,duration_ms:Date.now()-n};let c=o.load(i.readFileSync(a,"utf8")),l;if(s.permutation&&c.permutations&&(l=c.permutations.find(y=>y.id===s.permutation),!l))return {chain_id:e,status:"error",persona_results:[],summary:`Permutation ${s.permutation} not found in chain ${e}`,duration_ms:Date.now()-n};let d=[],p={},u=s.stopOnFailure!==false;for(let y of c.order){let f=await x$1(t,y.persona);if(!f){if(d.push({persona:y.persona,status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${y.persona} not found`,duration_ms:0}),u)break;continue}if(l&&l.overrides[y.persona]){let v=l.overrides[y.persona];if(v.traits&&(f.traits={...f.traits,...v.traits}),v.journey)for(let[k,S]of Object.entries(v.journey)){let x=f.journey.find(C=>C.id===k);x&&(S.payload&&(x.payload={...x.payload,...S.payload}),S.expect&&(x.expect={...x.expect,...S.expect}));}}let b={};if(y.wait_for){let[v,k]=y.wait_for.split("."),S=d.find(C=>C.persona===v);if(S){let C=S.steps.find(_=>_.id===k);C?.produced&&(b=Object.fromEntries(Object.entries(C.produced).map(([_,R])=>[_,String(R)])));}let x=await x$1(t,v);if(x){let C=x.journey.find(_=>_.id===k);if(C?.spawns){let _=C.spawns.find(R=>R.persona===y.persona);if(_?.context){let R=p[v]||{};for(let[I,P]of Object.entries(_.context))b[I]=String(ct(P,{fixtures:{},produces:R,context:{},env:process.env}));}}}}let h=await vc(t,f,{...s,context:b});d.push(h);let w={};for(let v of h.steps)v.produced&&Object.assign(w,v.produced);if(p[y.persona]=w,h.status==="fail"&&u)break}let g=d.filter(y=>y.status==="pass").length,m=c.order.length;return {chain_id:e,status:d.some(y=>y.status!=="pass")?"fail":"pass",persona_results:d,summary:`${g}/${m} personas passed.`,duration_ms:Date.now()-n}}function Sc(t){let e=[],s=new Set;for(let n of t.journey){let r=JSON.stringify(n).match(bc)||[];for(let o of r){let a=o.replace("{{","").replace("}}","").trim(),[c,...l]=a.split("."),d=l.join(".");switch(c){case "fixtures":!t.fixtures||d in t.fixtures;break;case "produces":s.has(d)||e.push({step:n.id,template:o,error:`{{produces.${d}}} used but not produced by a prior step`});break;case "context":case "parent":break;case "env":break;case "response":break;default:e.push({step:n.id,template:o,error:`Unknown namespace "${c}" in ${o}`});}}if(n.produces)for(let o of Object.keys(n.produces))s.add(o);}return {valid:e.length===0,errors:e}}var xc="paradigm-personas",Ju={id:xc,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"}}},ni=false;async function _c(t){try{let{SentinelStorage:e}=await import('./dist-W3XCATBJ.js'),s=new e;if(!ni)try{s.registerSchema(Ju),ni=!0;}catch{ni=!0;}let n=[];if("persona"in t){let i=t;n.push({type:"persona.run.start",timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,total_steps:i.steps.length}});for(let r of i.steps){let o=r.status==="pass"?"persona.step.complete":`persona.step.${r.status}`;n.push({type:o,timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,step_id:r.id,route:r.route,gates:r.gates,gates_traversed:r.gates,status:r.response?.status,body:r.response?.body,signals_fired:[],duration_ms:r.duration_ms,failure:r.failure,gate_that_blocked:r.gate_that_blocked,produced_keys:r.produced?Object.keys(r.produced):[]}});}n.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,status:i.status,total_steps:i.steps.length,passed:i.steps.filter(r=>r.status==="pass").length,failed:i.steps.filter(r=>r.status==="fail").length,skipped:i.steps.filter(r=>r.status==="skip").length,duration_ms:i.duration_ms,spawns_triggered:i.spawns_triggered,spawns_blocked:i.spawns_blocked}});}else {let i=t;for(let r of i.persona_results)n.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:r.persona,data:{persona_id:r.persona,run_id:r.run_id,chain_id:i.chain_id,status:r.status,total_steps:r.steps.length,passed:r.steps.filter(o=>o.status==="pass").length,failed:r.steps.filter(o=>o.status==="fail").length,duration_ms:r.duration_ms}});n.push({type:"persona.chain.complete",timestamp:new Date().toISOString(),data:{chain_id:i.chain_id,status:i.status,personas_run:i.persona_results.length,personas_passed:i.persona_results.filter(r=>r.status==="pass").length,duration_ms:i.duration_ms}});}n.length>0&&s.insertEventBatch(xc,"paradigm-personas",n);}catch{}}function Cc(){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 Rc(t,e,s){switch(t){case "paradigm_persona_create":try{let n=await y$1(s.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}),i=await x$1(s.rootDir,n);return {handled:!0,text:JSON.stringify({created:n,persona:i},null,2)}}catch(n){return {handled:true,text:JSON.stringify({error:n.message})}}case "paradigm_persona_get":{let n=e.id,i=await x$1(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Persona ${n} not found`})};let r=await D(s.rootDir,i);return {handled:true,text:JSON.stringify({persona:i,validation:r},null,2)}}case "paradigm_persona_list":{let n=await w(s.rootDir,{tag:e.tag,trigger_type:e.trigger_type,gate:e.gate,flow:e.flow,limit:e.limit||50}),i=n.map(r=>({id:r.id,name:r.name,trigger:r.trigger.type,steps:r.journey.length,gates:[...new Set(r.journey.flatMap(o=>o.gates))],tags:r.tags||[]}));return {handled:true,text:JSON.stringify({count:n.length,personas:i},null,2)}}case "paradigm_persona_update":{let n=e.id,i={};if(e.name!==void 0&&(i.name=e.name),e.description!==void 0&&(i.description=e.description),e.traits!==void 0&&(i.traits=e.traits),e.trigger!==void 0&&(i.trigger=e.trigger),e.fixtures!==void 0&&(i.fixtures=e.fixtures),e.tags!==void 0&&(i.tags=e.tags),e.journey!==void 0&&(i.journey=e.journey),!await z$1(s.rootDir,n,i))return {handled:true,text:JSON.stringify({error:`Persona ${n} not found`})};let o=await x$1(s.rootDir,n);return {handled:true,text:JSON.stringify({updated:n,persona:o},null,2)}}case "paradigm_persona_delete":{let n=e.id,i=await A$1(s.rootDir,n);return i.deleted?{handled:true,text:JSON.stringify({deleted:n,warnings:i.warnings,hint:i.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 ${n} not found`})}}case "paradigm_persona_add_step":try{if(!await B(s.rootDir,e.persona_id,e.step,e.after))return {handled:!0,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let i=await x$1(s.rootDir,e.persona_id);return {handled:!0,text:JSON.stringify({added:e.step.id,persona_id:e.persona_id,total_steps:i?.journey.length},null,2)}}catch(n){return {handled:true,text:JSON.stringify({error:n.message})}}case "paradigm_persona_remove_step":{let n=await C(s.rootDir,e.persona_id,e.step_id);return n.removed?{handled:true,text:JSON.stringify({removed:e.step_id,persona_id:e.persona_id,warnings:n.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 n=e.deep??false,i=e.sentinel??true,r={run_id:e.run_id,chain_id:e.chain_id,environment:e.environment};if(e.persona_id){let d=await x$1(s.rootDir,e.persona_id);if(!d)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let p=await D(s.rootDir,d,n);if(i)try{let u=await G(d,r);p.sentinel_assertions=u,(u.summary.failed>0||u.summary.unmatched>0)&&(p.valid=!1);}catch{}return {handled:true,text:JSON.stringify(p,null,2)}}let o=await w(s.rootDir),a=await Promise.all(o.map(async d=>{let p=await D(s.rootDir,d,n);if(i)try{let u=await G(d,r);p.sentinel_assertions=u,(u.summary.failed>0||u.summary.unmatched>0)&&(p.valid=!1);}catch{}return p})),c=a.filter(d=>d.valid).length,l=a.filter(d=>!d.valid).length;return {handled:true,text:JSON.stringify({total:a.length,valid:c,invalid:l,results:a.filter(d=>!d.valid||d.warnings.length>0||d.sentinel_assertions)},null,2)}}case "paradigm_persona_coverage":{let n=await E$1(s.rootDir);return {handled:true,text:JSON.stringify(n,null,2)}}case "paradigm_persona_affected":{let n=e.symbol,i=await F(s.rootDir,n);return i.length===0?{handled:true,text:JSON.stringify({symbol:n,affected:[],note:"No personas reference this symbol."})}:{handled:true,text:JSON.stringify({symbol:n,affected:i},null,2)}}case "paradigm_persona_run":{let n=e.base_url,i=e.dry_run??false,r=e.stop_on_failure??true;if(e.chain_id){let o=await kc(s.rootDir,e.chain_id,{baseUrl:n,dryRun:i,stopOnFailure:r,permutation:e.permutation});return i||await _c(o),{handled:true,text:JSON.stringify(o,null,2)}}if(e.persona_id){let o=await x$1(s.rootDir,e.persona_id);if(!o)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let a=Sc(o);if(!a.valid&&!i)return {handled:true,text:JSON.stringify({error:"Template interpolation errors \u2014 fix before running",errors:a.errors,hint:"Use dry_run: true to see interpolated values without executing requests"},null,2)};let c=await wc(s.rootDir,e.persona_id,{baseUrl:n,dryRun:i,stopOnFailure:r});return i||await _c(c),{handled:true,text:JSON.stringify(c,null,2)}}return {handled:true,text:JSON.stringify({error:"Either persona_id or chain_id is required"})}}default:return {handled:false,text:""}}}var Uu=".paradigm/graphs",ri={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},si=200,ii=60,lt=20,Un=40,Pc=50,Bu=60;function Tc(){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 Ac(t,e,s){if(t!=="paradigm_graph_generate")return {handled:false,text:""};try{let n=e.name||"untitled",i=n.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),r=Vu(s.rootDir,e.symbols,e.groups,e.links,n),o$1=JSON.stringify(r,null,2),a=H.join(s.rootDir,Uu);E.existsSync(a)||E.mkdirSync(a,{recursive:!0});let c=H.join(a,`${i}.graph.json`);E.writeFileSync(c,o$1,"utf8");let l=JSON.stringify({file:c,name:n,slug:i,nodes:r.nodes.length,edges:r.edges.length,size:`${(o$1.length/1024).toFixed(1)} KB`,hint:"Graph saved. Run `paradigm graph` to view in browser."},null,2);return o(l.length,t),{handled:!0,text:l}}catch(n){let i=JSON.stringify({error:n.message},null,2);return o(i.length,t),{handled:true,text:i}}}var zu={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"};function Yu(t){let e=H.join(t,".paradigm","scan-index.json");if(!E.existsSync(e))return [];let s=JSON.parse(E.readFileSync(e,"utf8")),n=[];for(let[i,r]of Object.entries(zu)){let o=s[i];if(!(!o||typeof o!="object"))for(let[a,c]of Object.entries(o)){let l=c;n.push({id:a,name:a,category:r,prefix:ri[r]||"#",description:l.description,path:l.path,tags:l.tags});}}return n}function jc(t,e){let s=t.replace(/^[#$^!~]/,"");return e.find(n=>n.id===s||n.name===s||n.id===t||n.name===t)}function Vu(t,e,s,n,i="Generated Graph"){let r=Yu(t),o;e&&e.length>0?o=e.map(g=>jc(g,r)).filter(Boolean):o=r;let a=[],c=[],l=new Map,d=new Set,p=0;if(s&&s.length>0)for(let g of s){let m=`group-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;l.set(g.label,m);let y=g.symbols.map(S=>jc(S,o)).filter(Boolean),f=Math.ceil(Math.sqrt(y.length)),b=Math.ceil(y.length/f);for(let S=0;S<y.length;S++){let x=y[S],C=S%f,_=Math.floor(S/f),R=ri[x.category]||"#";a.push({id:`sym-${x.id}`,type:"symbolNode",position:{x:Un+C*(si+lt),y:Pc+Un+_*(ii+lt)},parentId:m,data:{type:"symbol",symbol:x,label:`${R}${x.name}`}}),d.add(x.id);}let h=Math.max(f,1),w=Math.max(b,1),v=Un*2+h*si+(h-1)*lt,k=Pc+Un*2+w*ii+(w-1)*lt;a.unshift({id:m,type:"groupNode",position:{x:p,y:0},style:{width:v,height:k},data:{type:"group",label:g.label}}),p+=v+Bu;}let u=o.filter(g=>!d.has(g.id));if(u.length>0){let g=s&&s.length>0?400:0,m=Math.ceil(Math.sqrt(u.length));for(let y=0;y<u.length;y++){let f=u[y],b=y%m,h=Math.floor(y/m),w=ri[f.category]||"#";a.push({id:`sym-${f.id}`,type:"symbolNode",position:{x:b*(si+lt),y:g+h*(ii+lt)},data:{type:"symbol",symbol:f,label:`${w}${f.name}`}});}}if(n&&n.length>0)for(let g of n){let m=l.get(g.source),y=l.get(g.target);m&&y&&c.push({id:`e-${m}-${y}`,source:m,target:y,type:"default",label:g.label,data:{label:g.label}});}return {version:"1.0",name:i,projectId:H.basename(t),lastModified:new Date().toISOString(),nodes:a,edges:c}}var ge=["specify","plan","task","implement","validate"],Jt=".paradigm/pipeline",Dc={"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 Bn(t){return t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Wt(t,e){let s=Bn(e),n=H.join(t,Jt,`${s}.yaml`);return E.existsSync(n)?Ae.load(E.readFileSync(n,"utf8")):null}function Gt(t,e){let s=Bn(e.feature),n=H.join(t,Jt);E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=H.join(n,`${s}.yaml`);return E.writeFileSync(i,Ae.dump(e,{lineWidth:120}),"utf8"),i}function Oc(t){let e=H.join(t,Jt);return E.existsSync(e)?E.readdirSync(e).filter(s=>s.endsWith(".yaml")&&!s.startsWith("completed")).map(s=>{try{return Ae.load(E.readFileSync(H.join(e,s),"utf8"))}catch{return null}}).filter(Boolean):[]}function Ku(t,e,s){let n={specify:{status:"pending"},plan:{status:"pending"},task:{status:"pending"},implement:{status:"pending"},validate:{status:"pending"}};return n.specify.status="in-progress",{version:"1.0",feature:Bn(t),created:new Date().toISOString(),current_stage:"specify",gate_config:e,template:s,stages:n}}function Qu(t){let e=ge.indexOf(t);return e<ge.length-1?ge[e+1]:null}function Ic(t,e){let s=Bn(e.feature),n=H.join(t,Jt,"completed");E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=H.join(n,`${s}.yaml`);E.writeFileSync(i,Ae.dump(e,{lineWidth:120}),"utf8");let r=H.join(t,Jt,`${s}.yaml`);E.existsSync(r)&&E.unlinkSync(r);}function $c(){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 Fc(t,e,s){switch(t){case "paradigm_pipeline_start":{let n=e.feature,i=e.template||"add-feature",r=e.gates,o;if(r)o={specify:r.specify||"manual",plan:r.plan||"manual",task:r.task||"auto",implement:r.implement||"sentinel",validate:r.validate||"sentinel"};else {let l=Dc[i];if(!l)return {handled:true,text:JSON.stringify({error:`Unknown template: ${i}`,available:Object.keys(Dc)})};o=l.gates;}let a=Ku(n,o,i),c=Gt(s.rootDir,a);return {handled:true,text:JSON.stringify({created:true,feature:a.feature,template:i,file:c,current_stage:a.current_stage,gate_config:a.gate_config,stages:a.stages,hint:`Pipeline '${a.feature}' started at 'specify' stage. Create your spec, then call paradigm_pipeline_advance to move to 'plan'.`},null,2)}}case "paradigm_pipeline_status":{let n=e.feature;if(n){let r=Wt(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let o=ge.filter(a=>r.stages[a].status==="approved").length;return {handled:true,text:JSON.stringify({feature:r.feature,created:r.created,template:r.template,current_stage:r.current_stage,progress:`${o}/${ge.length}`,gate_config:r.gate_config,stages:r.stages},null,2)}}let i=Oc(s.rootDir);return i.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:i.length,pipelines:i.map(r=>{let o=ge.filter(a=>r.stages[a].status==="approved").length;return {feature:r.feature,current_stage:r.current_stage,progress:`${o}/${ge.length}`,template:r.template,created:r.created}})},null,2)}}case "paradigm_pipeline_advance":{let n=e.feature,i=e.approved_by||"agent",r=Wt(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let o=r.current_stage,a=r.gate_config[o],c=Qu(o);return r.stages[o].status="approved",r.stages[o].approved_by=i,r.stages[o].approved_at=new Date().toISOString(),a==="auto"&&(r.stages[o].auto_passed_at=new Date().toISOString()),c?(r.current_stage=c,r.stages[c].status="in-progress",Gt(s.rootDir,r),{handled:true,text:JSON.stringify({advanced:true,from:o,to:c,gate_mode:a,approved_by:i,pipeline:{feature:r.feature,current_stage:r.current_stage,stages:r.stages}},null,2)}):(Gt(s.rootDir,r),Ic(s.rootDir,r),{handled:true,text:JSON.stringify({completed:true,feature:r.feature,message:`Pipeline '${r.feature}' completed and archived.`,stages:r.stages},null,2)})}case "paradigm_pipeline_configure":{let n=e.feature,i=e.updates,r=e.reason,o=Wt(s.rootDir,n);if(!o)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let a=[];for(let[c,l]of Object.entries(i))if(ge.includes(c)&&["auto","manual","sentinel"].includes(l)){let d=o.gate_config[c];o.gate_config[c]=l,a.push({stage:c,from:d,to:l});}return a.length===0?{handled:true,text:JSON.stringify({error:"No valid gate updates provided",valid_stages:ge,valid_modes:["auto","manual","sentinel"]})}:(Gt(s.rootDir,o),{handled:true,text:JSON.stringify({configured:true,feature:o.feature,changes:a,reason:r,gate_config:o.gate_config},null,2)})}case "paradigm_pipeline_escalate":{let n=e.feature,i=e.stage,r=e.question,o=e.options,a=e.context,c=Wt(s.rootDir,n);return c?(c.stages[i].status="blocked",c.stages[i].block_reason=r,Gt(s.rootDir,c),{handled:true,text:JSON.stringify({escalated:true,feature:c.feature,stage:i,question:r,options:o,context:a||{},current_gate:c.gate_config[i],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: ${n}`})}}case "paradigm_pipeline_abort":{let n=e.feature,i=Wt(s.rootDir,n);return i?(Ic(s.rootDir,i),{handled:true,text:JSON.stringify({aborted:true,feature:i.feature,message:`Pipeline '${i.feature}' aborted and archived.`})}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})}}case "paradigm_pipeline_list":{let n=Oc(s.rootDir);return n.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines."})}:{handled:true,text:JSON.stringify({count:n.length,pipelines:n.map(i=>{let r=ge.filter(o=>i.stages[o].status==="approved").length;return {feature:i.feature,current_stage:i.current_stage,progress:`${r}/${ge.length}`,template:i.template,created:i.created}})},null,2)}}default:return {handled:false,text:""}}}b$1();var Xu=H.join(ua.homedir(),".conductor"),ut=H.join(Xu,"sessions");function Ec(){E.existsSync(ut)||E.mkdirSync(ut,{recursive:true});}function ai(t){Ec();let e={...t,registeredAt:new Date().toISOString()},s=H.join(ut,`${t.pid}.json`);return E.writeFileSync(s,JSON.stringify(e,null,2),"utf-8"),e}function zn(t){let e=H.join(ut,`${t}.json`);return E.existsSync(e)?(E.unlinkSync(e),true):false}function ci(){Ec();let t=E.readdirSync(ut).filter(s=>s.endsWith(".json")),e=[];for(let s of t)try{let n=E.readFileSync(H.join(ut,s),"utf-8"),i=JSON.parse(n);e.push(i);}catch{}return e}function Hc(){let t=ci(),e=0;for(let s of t)Zu(s.pid)||(zn(s.pid),e++);return e}function Zu(t){try{return process.kill(t,0),!0}catch{return false}}function li(){try{return execSync(`osascript -e '
479
563
  tell application "System Events"
480
564
  set frontApp to first application process whose frontmost is true
481
565
  return bundle identifier of frontApp
482
566
  end tell
483
- '`,{encoding:"utf-8",timeout:3e3}).trim()||void 0}catch{return}}function ri(t){try{return execSync("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf-8",timeout:3e3}).trim()||void 0}catch{return}}function gy(t){try{let e=process.pid,s=ii(),n=ri(t),i;try{let o=execSync(`ps -o ppid= -p ${e}`,{encoding:"utf-8",timeout:3e3}).trim();i=parseInt(o,10),isNaN(i)&&(i=void 0);}catch{}ni({pid:e,parentPid:i,projectDir:t,terminal:s,branch:n});let r=()=>{try{Jn(e);}catch{}};process.on("exit",r),process.on("SIGTERM",()=>{r(),process.exit(0);}),a.component("#conductor-loader").info("Auto-registered with Conductor",{pid:e});}catch{a.component("#conductor-loader").warn("Auto-registration with Conductor skipped (non-fatal)");}}function Oc(){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 Ic(t,e,s){switch(t){case "paradigm_conductor_register":{let n=process.pid,i=s.rootDir,r=e.terminal||ii(),o=ri(i),a;try{let d=execSync(`ps -o ppid= -p ${n}`,{encoding:"utf-8",timeout:3e3}).trim();a=parseInt(d,10),isNaN(a)&&(a=void 0);}catch{}let c=ni({pid:n,parentPid:a,projectDir:i,terminal:r,label:e.label,branch:o}),l=["\u2713 Registered with Conductor","",` PID: ${c.pid}`,` Project: ${c.projectDir}`];return c.branch&&l.push(` Branch: ${c.branch}`),c.label&&l.push(` Label: ${c.label}`),c.terminal&&l.push(` Terminal: ${c.terminal}`),l.push(` File: ~/.conductor/sessions/${c.pid}.json`),l.push(""),l.push("This session is now visible in Paradigm Conductor."),l.push("Conductor will auto-discover it via the registration file."),{text:l.join(`
484
- `),handled:true}}case "paradigm_conductor_unregister":{let n=process.pid;return Jn(n)?{text:`\u2713 Unregistered from Conductor (PID ${n}).
485
- This session is no longer visible in the Conductor overlay.`,handled:true}:{text:`Session (PID ${n}) was not registered with Conductor.`,handled:true}}case "paradigm_conductor_list":{e.clean&&Ac()>0;let n=si();if(n.length===0)return {text:`No sessions registered with Conductor.
567
+ '`,{encoding:"utf-8",timeout:3e3}).trim()||void 0}catch{return}}function di(t){try{return execSync("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf-8",timeout:3e3}).trim()||void 0}catch{return}}function Dy(t){try{let e=process.pid,s=li(),n=di(t),i;try{let o=execSync(`ps -o ppid= -p ${e}`,{encoding:"utf-8",timeout:3e3}).trim();i=parseInt(o,10),isNaN(i)&&(i=void 0);}catch{}ai({pid:e,parentPid:i,projectDir:t,terminal:s,branch:n});let r=()=>{try{zn(e);}catch{}};process.on("exit",r),process.on("SIGTERM",()=>{r(),process.exit(0);}),a.component("#conductor-loader").info("Auto-registered with Conductor",{pid:e});}catch{a.component("#conductor-loader").warn("Auto-registration with Conductor skipped (non-fatal)");}}function qc(){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 Lc(t,e,s){switch(t){case "paradigm_conductor_register":{let n=process.pid,i=s.rootDir,r=e.terminal||li(),o=di(i),a;try{let d=execSync(`ps -o ppid= -p ${n}`,{encoding:"utf-8",timeout:3e3}).trim();a=parseInt(d,10),isNaN(a)&&(a=void 0);}catch{}let c=ai({pid:n,parentPid:a,projectDir:i,terminal:r,label:e.label,branch:o}),l=["\u2713 Registered with Conductor","",` PID: ${c.pid}`,` Project: ${c.projectDir}`];return c.branch&&l.push(` Branch: ${c.branch}`),c.label&&l.push(` Label: ${c.label}`),c.terminal&&l.push(` Terminal: ${c.terminal}`),l.push(` File: ~/.conductor/sessions/${c.pid}.json`),l.push(""),l.push("This session is now visible in Paradigm Conductor."),l.push("Conductor will auto-discover it via the registration file."),{text:l.join(`
568
+ `),handled:true}}case "paradigm_conductor_unregister":{let n=process.pid;return zn(n)?{text:`\u2713 Unregistered from Conductor (PID ${n}).
569
+ This session is no longer visible in the Conductor overlay.`,handled:true}:{text:`Session (PID ${n}) was not registered with Conductor.`,handled:true}}case "paradigm_conductor_list":{e.clean&&Hc()>0;let n=ci();if(n.length===0)return {text:`No sessions registered with Conductor.
486
570
  Use paradigm_conductor_register or /conduct to register.`,handled:true};let i=[`${n.length} session(s) registered with Conductor:
487
571
  `];for(let r of n){let o=[` PID ${r.pid}`];r.label&&o.push(`"${r.label}"`),o.push(`\u2014 ${r.projectDir}`),r.branch&&o.push(`(${r.branch})`),i.push(o.join(" "));}return e.clean&&i.push(`
488
572
  (Stale sessions cleaned)`),{text:i.join(`
489
- `),handled:true}}default:return {text:"",handled:false}}}function Fc(){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 Nc(t,e,s){let n=n$2(s.rootDir);switch(n||(n=j$4(s.rootDir)),t){case "paradigm_symphony_peek":{let i=e.status;o$3(n.id,i);let{hasNew:r}=s$2(n.id),o=r?N("pending").length:0;return {handled:true,text:JSON.stringify(r?{hasNew:true,pendingFileRequests:o,action:"call paradigm_symphony_poll to read"}:{hasNew:false})}}case "paradigm_symphony_poll":{m$2(),S();let i=e.status;o$3(n.id,i);let r=v$2(n.id);if(r.length>0){let c=r[r.length-1].id;z$2(n.id,c),t$2(n.id);}B$1(n.id);let o=N("pending");return r.length===0&&o.length===0?{handled:true,text:JSON.stringify({messages:0,note:"No new notes. Score is quiet.",identity:n.id})}:{handled:true,text:qu(r,o)}}case "paradigm_symphony_send":{let i=e.intent,r=e.text,o=e.parentId,a=e.threadRoot,c=e.recipients,l=e.symbols,d=e.diff,p=e.decision,u=false;if(!a&&!o){let f=r.length>60?r.slice(0,60)+"...":r;a=C$1(f,Gt(n)).id,u=true;}let m;if(c&&c.length>0){let f=l$2();m=c.map(b=>{let h=f.find(w=>w.id===b);return h?Gt(h):{id:b,name:b,type:"agent"}});}let g=I({sender:Gt(n),recipients:m,intent:i,text:r,parentId:o,threadRoot:a,symbols:l,diff:d,decision:p}),y=J(g);if(Ju(g).catch(()=>{}),u&&a){({timestamp:g.timestamp,sender:g.sender,content:{text:`Thread created: ${g.content.text.slice(0,60)}`}});fetch(`${oi}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:"thread:created",category:"lifecycle",timestamp:g.timestamp,scopeValue:a,service:g.sender.project||"symphony",severity:"info",data:{topic:g.content.text.slice(0,60),initiator:g.sender.name,threadId:a}})}).catch(()=>{});}return {handled:true,text:JSON.stringify({sent:true,messageId:g.id,threadId:a,threadCreated:u,deliveredTo:y,intent:i})}}case "paradigm_symphony_status":{m$2();let i=l$2(),r=E$2("active"),o=v$2(n.id),a=N("pending"),c=[];try{let{loadPeers:l}=await import('./symphony-peers-U4KHMKGI.js');c=l().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:n.id,project:n.project,role:n.role},agents:i.map(l=>({id:l.id,name:l.name,project:l.project,role:l.role,status:q$3(l)?"asleep":"awake",lastPoll:l.lastPoll,statusBlurb:l.statusBlurb})),peers:c,activeThreads:r.map(l=>({id:l.id,topic:l.topic,participants:l.participants.length,messageCount:l.messageCount,lastActivity:l.lastActivity})),unreadCount:o.length,pendingFileRequests:a.length},null,2)}}case "paradigm_symphony_thread":{let i=e.threadId,r=e.depth||50,o=D$1(i);if(!o)return {handled:true,text:JSON.stringify({error:`Thread not found: ${i}`})};let a=H$1(i).slice(0,r),c=[],l=new Set,d=new Set;for(let p of a){p.content.decision&&c.push(p.content.decision),p.intent==="decision"&&p.content.text&&c.push(p.content.text);for(let u of p.symbols)l.add(u);if(p.attachments)for(let u of p.attachments)u.type==="file"&&d.add(u.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:a.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:c,symbolsDiscussed:[...l],filesReferenced:[...d]},null,2)}}case "paradigm_symphony_request_file":{let i=e.filePath,r=e.from,o=e.reason,a=e.snippet,c=K();if(Q(i,c))return {handled:true,text:JSON.stringify({error:`File path "${i}" is on the hard-deny list and cannot be requested.`,deniedPatterns:c.defaults.neverApprove})};let l=L$1({filePath:i,requester:Gt(n),reason:o,snippet:a,threadRoot:void 0}),d=I({sender:Gt(n),recipients:[{id:r,name:r,type:"agent"}],intent:"fileRequest",text:`Requesting file: ${i}
573
+ `),handled:true}}default:return {text:"",handled:false}}}function Wc(){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 Gc(t,e,s){let n=n$2(s.rootDir);switch(n||(n=j$4(s.rootDir)),t){case "paradigm_symphony_peek":{let i=e.status;o$3(n.id,i);let{hasNew:r}=s$2(n.id),o=r?N("pending").length:0;return {handled:true,text:JSON.stringify(r?{hasNew:true,pendingFileRequests:o,action:"call paradigm_symphony_poll to read"}:{hasNew:false})}}case "paradigm_symphony_poll":{m$2(),S();let i=e.status;o$3(n.id,i);let r=v$2(n.id);if(r.length>0){let c=r[r.length-1].id;z$2(n.id,c),t$2(n.id);}B$1(n.id);let o=N("pending");return r.length===0&&o.length===0?{handled:true,text:JSON.stringify({messages:0,note:"No new notes. Score is quiet.",identity:n.id})}:{handled:true,text:tg(r,o)}}case "paradigm_symphony_send":{let i=e.intent,r=e.text,o=e.parentId,a=e.threadRoot,c=e.recipients,l=e.symbols,d=e.diff,p=e.decision,u=false;if(!a&&!o){let f=r.length>60?r.slice(0,60)+"...":r;a=C$1(f,Ut(n)).id,u=true;}let g;if(c&&c.length>0){let f=l$2();g=c.map(b=>{let h=f.find(w=>w.id===b);return h?Ut(h):{id:b,name:b,type:"agent"}});}let m=I({sender:Ut(n),recipients:g,intent:i,text:r,parentId:o,threadRoot:a,symbols:l,diff:d,decision:p}),y=J(m);if(og(m).catch(()=>{}),u&&a){({timestamp:m.timestamp,sender:m.sender,content:{text:`Thread created: ${m.content.text.slice(0,60)}`}});fetch(`${pi}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:"thread:created",category:"lifecycle",timestamp:m.timestamp,scopeValue:a,service:m.sender.project||"symphony",severity:"info",data:{topic:m.content.text.slice(0,60),initiator:m.sender.name,threadId:a}})}).catch(()=>{});}return {handled:true,text:JSON.stringify({sent:true,messageId:m.id,threadId:a,threadCreated:u,deliveredTo:y,intent:i})}}case "paradigm_symphony_status":{m$2();let i=l$2(),r=E$2("active"),o=v$2(n.id),a=N("pending"),c=[];try{let{loadPeers:l}=await import('./symphony-peers-U4KHMKGI.js');c=l().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:n.id,project:n.project,role:n.role},agents:i.map(l=>({id:l.id,name:l.name,project:l.project,role:l.role,status:q$3(l)?"asleep":"awake",lastPoll:l.lastPoll,statusBlurb:l.statusBlurb})),peers:c,activeThreads:r.map(l=>({id:l.id,topic:l.topic,participants:l.participants.length,messageCount:l.messageCount,lastActivity:l.lastActivity})),unreadCount:o.length,pendingFileRequests:a.length},null,2)}}case "paradigm_symphony_thread":{let i=e.threadId,r=e.depth||50,o=D$1(i);if(!o)return {handled:true,text:JSON.stringify({error:`Thread not found: ${i}`})};let a=H$1(i).slice(0,r),c=[],l=new Set,d=new Set;for(let p of a){p.content.decision&&c.push(p.content.decision),p.intent==="decision"&&p.content.text&&c.push(p.content.text);for(let u of p.symbols)l.add(u);if(p.attachments)for(let u of p.attachments)u.type==="file"&&d.add(u.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:a.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:c,symbolsDiscussed:[...l],filesReferenced:[...d]},null,2)}}case "paradigm_symphony_request_file":{let i=e.filePath,r=e.from,o=e.reason,a=e.snippet,c=K();if(Q(i,c))return {handled:true,text:JSON.stringify({error:`File path "${i}" is on the hard-deny list and cannot be requested.`,deniedPatterns:c.defaults.neverApprove})};let l=L$1({filePath:i,requester:Ut(n),reason:o,snippet:a,threadRoot:void 0}),d=I({sender:Ut(n),recipients:[{id:r,name:r,type:"agent"}],intent:"fileRequest",text:`Requesting file: ${i}
490
574
  Reason: ${o}${a?`
491
- Snippet: ${a}`:""}`,symbols:[]});return J(d),{handled:true,text:JSON.stringify({requestId:l.request.requestId,status:"pending",filePath:i,from:r,message:`File request created. The owning agent's human must approve via "paradigm symphony approve ${l.request.requestId}" or "paradigm_symphony_approve_file".`})}}case "paradigm_symphony_approve_file":{let i=e.requestId,r=e.action,o=e.reason;if(r==="deny"){let l=P(i,o);return {handled:true,text:JSON.stringify({success:l,requestId:i,action:"denied",reason:o||"No reason provided"})}}let a=r==="approve-redacted",c=O(i,s.rootDir,a);return c.success?{handled:true,text:JSON.stringify({success:true,requestId:i,action:a?"approved-redacted":"approved",filePath:c.delivery?.filePath,size:c.delivery?.size,hash:c.delivery?.hash})}:{handled:true,text:JSON.stringify({success:false,requestId:i,error:c.error})}}default:return {handled:false,text:""}}}function Gt(t){return {id:t.id,name:t.name,type:t.type||"agent",project:t.project,role:t.role}}function qu(t,e){let s=[],n=new Map;for(let i of t){let r=i.threadRoot||"direct";n.has(r)||n.set(r,[]),n.get(r).push(i);}for(let[i,r]of n){let o=i;if(i!=="direct"){let a=D$1(i);a&&(o=a.topic);}s.push(`## Symphony: ${r.length} new note${r.length!==1?"s":""} in "${o}"
492
- `);for(let a=0;a<r.length;a++){let c=r[a],l=new Date(c.timestamp).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),d=`${c.sender.name}${c.sender.project?` (${c.sender.project})`:""}`;s.push(`### ${a+1}. ${d} \u2014 ${Mu(c.intent)} (${l})`),s.push(`> ${c.content.text.split(`
575
+ Snippet: ${a}`:""}`,symbols:[]});return J(d),{handled:true,text:JSON.stringify({requestId:l.request.requestId,status:"pending",filePath:i,from:r,message:`File request created. The owning agent's human must approve via "paradigm symphony approve ${l.request.requestId}" or "paradigm_symphony_approve_file".`})}}case "paradigm_symphony_approve_file":{let i=e.requestId,r=e.action,o=e.reason;if(r==="deny"){let l=P(i,o);return {handled:true,text:JSON.stringify({success:l,requestId:i,action:"denied",reason:o||"No reason provided"})}}let a=r==="approve-redacted",c=O(i,s.rootDir,a);return c.success?{handled:true,text:JSON.stringify({success:true,requestId:i,action:a?"approved-redacted":"approved",filePath:c.delivery?.filePath,size:c.delivery?.size,hash:c.delivery?.hash})}:{handled:true,text:JSON.stringify({success:false,requestId:i,error:c.error})}}default:return {handled:false,text:""}}}function Ut(t){return {id:t.id,name:t.name,type:t.type||"agent",project:t.project,role:t.role}}function tg(t,e){let s=[],n=new Map;for(let i of t){let r=i.threadRoot||"direct";n.has(r)||n.set(r,[]),n.get(r).push(i);}for(let[i,r]of n){let o=i;if(i!=="direct"){let a=D$1(i);a&&(o=a.topic);}s.push(`## Symphony: ${r.length} new note${r.length!==1?"s":""} in "${o}"
576
+ `);for(let a=0;a<r.length;a++){let c=r[a],l=new Date(c.timestamp).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),d=`${c.sender.name}${c.sender.project?` (${c.sender.project})`:""}`;s.push(`### ${a+1}. ${d} \u2014 ${sg(c.intent)} (${l})`),s.push(`> ${c.content.text.split(`
493
577
  `).join(`
494
578
  > `)}`),c.symbols.length>0&&s.push(`> Symbols: ${c.symbols.join(", ")}`),c.content.diff&&s.push(`
495
579
  \`\`\`diff
496
580
  ${c.content.diff}
497
581
  \`\`\``),c.content.decision&&s.push(`
498
- **Decision:** ${c.content.decision}`);let p=Lu(c);p&&s.push(`
582
+ **Decision:** ${c.content.decision}`);let p=ng(c);p&&s.push(`
499
583
  **Suggested action:** ${p}`),s.push("");}}if(e.length>0){s.push(`## Pending File Requests (${e.length})
500
584
  `);for(let i of e)s.push(`- **${i.request.filePath}** from ${i.request.requester.name}: ${i.request.reason}`),s.push(` Approve: \`paradigm_symphony_approve_file({ requestId: "${i.request.requestId}", action: "approve" })\``);s.push("");}return s.join(`
501
- `)}function Lu(t){switch(t.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 Mu(t){return t.charAt(0).toUpperCase()+t.slice(1)}var oi="http://localhost:3838",$c=false;function Wu(t){switch(t){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 Gu(t){if(t.startsWith("note:")){let e=t.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 t.startsWith("thread:")||t.startsWith("participant:")?"lifecycle":t.startsWith("file:")?"transfer":"dialogue"}async function Ju(t){try{$c||(await fetch(`${oi}/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(()=>{}),$c=!0);let e=Wu(t.intent),s=Gu(e);await fetch(`${oi}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:e,category:s,timestamp:t.timestamp,scopeValue:t.threadRoot||t.id,service:t.sender.project||"symphony",severity:s==="system"?"error":s==="outcome"?"warn":"info",parentEventId:t.parentId,data:{sender:t.sender.name,senderRole:t.sender.role||"core",text:t.content.text,symbols:t.symbols,diff:t.content.diff,decision:t.content.decision,parentId:t.parentId,threadId:t.threadRoot}})});}catch{}}function Ec(){let t=process.env.PARADIGM_AUTHOR;if(t)return ai(t);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return ai(e)}catch{}try{let e=ra.userInfo().username;if(e)return ai(e)}catch{}return "unknown"}function ai(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function Hc(){return new Date().toISOString().slice(0,10)}function mt(t,e){let s=[];try{s=J$1(t);}catch{}if(e){let c=s.find(l=>l.manifest.id===e);if(c)return {packId:c.manifest.id,packRoot:c.rootDir,packs:s}}let n=s.find(c=>c.manifest.tenant_kind==="project");if(n)return {packId:n.manifest.id,packRoot:n.rootDir,packs:s};let i=s.find(c=>c.manifest.tenant_kind==="first-party");if(i)return {packId:i.manifest.id,packRoot:i.rootDir,packs:s};let r=L$2(t);return {packId:M$1(r)?.id??"project",packRoot:r,packs:s}}function Bu(t){let e=["notes","policies","quizzes","paths"];for(let s of ["content","src/content"]){let n=H.join(t,s);if(!E.existsSync(n))continue;let i=0;for(let r of e){let o=H.join(n,r);if(E.existsSync(o))try{i+=E.readdirSync(o).filter(a=>a.endsWith(".md")||a.endsWith(".yaml")).length;}catch{}}if(i>0)return i}return 0}function Lc(){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)"},discipline:{type:"string",description:"v6.0: filter by discipline sub-pack name"},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 Mc(t,e,s){if(t==="paradigm_university_pack_list"){let n=e.tenant_kind,i=[];try{i=J$1(s.rootDir);}catch{i=[];}let o$1={packs:(n?i.filter(c=>c.manifest.tenant_kind===n):i).map(c=>({id:c.manifest.id,name:c.manifest.name,version:c.manifest.version,tenant_kind:c.manifest.tenant_kind,...c.manifest.disciplines&&c.manifest.disciplines.length>0?{discipline:c.manifest.disciplines[0]}:{},entry_count:Bu(c.rootDir),path:c.rootDir}))},a=JSON.stringify(o$1,null,2);return o(a.length,t),{handled:true,text:a}}if(t==="paradigm_university_search"){let n=e.pack,{packId:i}=mt(s.rootDir,n),r=U(s.rootDir,{type:e.type,tag:e.tag,difficulty:e.difficulty,symbol:e.symbol,query:e.query,category:e.category,track:e.track,limit:e.limit}),o$1=JSON.stringify({count:r.length,pack:i,results:r.map(a=>({id:`${i}:${a.id}`,title:a.title,type:a.type,difficulty:a.difficulty,tags:a.tags,symbols:a.symbols}))},null,2);return o(o$1.length,t),{handled:true,text:o$1}}if(t==="paradigm_university_get"){let n=e.id;if(!n)return {handled:true,text:JSON.stringify({error:"id is required"})};let i=e.pack,{packId:r,packRoot:o$1}=mt(s.rootDir,i),a;try{a=K$1(n,{activePack:r}).entryId;}catch{a=n;}let c=O$1(s.rootDir,a,o$1);if(c){let u=JSON.stringify({id:c.frontmatter.id,title:c.frontmatter.title,type:c.frontmatter.type,author:c.frontmatter.author,created:c.frontmatter.created,updated:c.frontmatter.updated,tags:c.frontmatter.tags,symbols:c.frontmatter.symbols,difficulty:c.frontmatter.difficulty,prerequisites:c.frontmatter.prerequisites,body:c.body},null,2);return o(u.length,t),{handled:true,text:u}}let l=Q$1(s.rootDir,a,o$1);if(l){let u=JSON.stringify(l,null,2);return o(u.length,t),{handled:true,text:u}}let d=S$1(s.rootDir,a,o$1);if(d){let u=JSON.stringify(d,null,2);return o(u.length,t),{handled:true,text:u}}let p=JSON.stringify({error:`Content "${n}" not found`});return o(p.length,t),{handled:true,text:p}}if(t==="paradigm_university_create"){let n=e.type,i=e.title;if(!n||!i)return {handled:true,text:JSON.stringify({error:"type and title are required"})};let r=e.pack,{packRoot:o$1}=mt(s.rootDir,r),a=Ec(),c=Hc(),l=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40);if(n==="quiz"){let y=`Q-${l}`,f={id:y,title:i,description:e.body||"",author:a,created:c,updated:c,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}:{}};R(s.rootDir,f,o$1),V(s.rootDir);let b=JSON.stringify({created:y,type:"quiz",file:`content/quizzes/${y}.yaml`},null,2);return o(b.length,t),{handled:true,text:b}}if(n==="path"){let y=`LP-${l}`,f={id:y,title:i,description:e.body||"",author:a,created:c,updated:c,tags:e.tags||[],ordered:e.ordered??true,steps:e.steps||[],...e.category?{category:e.category}:{}};T(s.rootDir,f,o$1),V(s.rootDir);let b=JSON.stringify({created:y,type:"path",file:`content/paths/${y}.yaml`},null,2);return o(b.length,t),{handled:true,text:b}}let p=`${n==="policy"?"P":"N"}-${l}`,u={id:p,title:i,type:n,author:a,created:c,updated:c,tags:e.tags||[],symbols:e.symbols||[],difficulty:e.difficulty||"beginner",estimatedMinutes:e.estimatedMinutes,prerequisites:e.prerequisites||[],...e.category?{category:e.category}:{}};P$1(s.rootDir,u,e.body||"",o$1),V(s.rootDir);let g=JSON.stringify({created:p,type:n,file:`content/${n==="policy"?"policies":"notes"}/${p}.md`},null,2);return o(g.length,t),{handled:true,text:g}}if(t==="paradigm_university_update"){let n=e.id;if(!n)return {handled:true,text:JSON.stringify({error:"id is required"})};let i=e.pack,{packId:r,packRoot:o$1}=mt(s.rootDir,i),a;try{a=K$1(n,{activePack:r}).entryId;}catch{a=n;}let c=Hc(),l=O$1(s.rootDir,a,o$1);if(l){let m={...l.frontmatter};e.title&&(m.title=e.title),e.tags&&(m.tags=e.tags),e.symbols&&(m.symbols=e.symbols),e.difficulty&&(m.difficulty=e.difficulty),e.estimatedMinutes!==void 0&&(m.estimatedMinutes=e.estimatedMinutes),e.category!==void 0&&(m.category=e.category),m.updated=c;let g=e.body??l.body;P$1(s.rootDir,m,g,o$1),V(s.rootDir);let y=JSON.stringify({updated:a,type:m.type},null,2);return o(y.length,t),{handled:true,text:y}}let d=Q$1(s.rootDir,a,o$1);if(d){e.title&&(d.title=e.title),e.tags&&(d.tags=e.tags),e.symbols&&(d.symbols=e.symbols),e.difficulty&&(d.difficulty=e.difficulty),e.category!==void 0&&(d.category=e.category),d.updated=c,R(s.rootDir,d,o$1),V(s.rootDir);let m=JSON.stringify({updated:a,type:"quiz"},null,2);return o(m.length,t),{handled:true,text:m}}let p=S$1(s.rootDir,a,o$1);if(p){e.title&&(p.title=e.title),e.tags&&(p.tags=e.tags),e.category!==void 0&&(p.category=e.category),p.updated=c,T(s.rootDir,p,o$1),V(s.rootDir);let m=JSON.stringify({updated:a,type:"path"},null,2);return o(m.length,t),{handled:true,text:m}}let u=JSON.stringify({error:`Content "${n}" not found`});return o(u.length,t),{handled:true,text:u}}if(t==="paradigm_university_onboard"){let n=e.student||Ec(),i=e.pack,{packId:r}=mt(s.rootDir,i),o$1=N$1(s.rootDir),a=Y$1(s.rootDir,n),c=JSON.stringify({university:o$1.branding.name,pack:r,student:n,...a},null,2);return o(c.length,t),{handled:true,text:c}}if(t==="paradigm_university_validate"){let n=e.pack,{packId:i}=mt(s.rootDir,n),r=e.id,o$1=r;if(r)try{o$1=K$1(r,{activePack:i}).entryId;}catch{}let a=W(s.rootDir,{id:o$1,deep:e.deep}),c=JSON.stringify({pack:i,...a},null,2);return o(c.length,t),{handled:true,text:c}}return {handled:false,text:""}}function zu(t){try{let e=H.join(t,".paradigm","config.yaml");if(E.existsSync(e)){let n=Te.load(E.readFileSync(e,"utf-8")).platform;if(n?.port&&typeof n.port=="number")return n.port}}catch{}return 3850}function Yu(t){try{let e=H.join(t,".paradigm","config.yaml");if(E.existsSync(e)){let s=Te.load(E.readFileSync(e,"utf-8")),n=s.project||H.basename(t),i=s.role||"core";return `${n}/${i}`}}catch{}return `${H.basename(t)}/core`}async function ht(t,e,s){let n=zu(t),i=Yu(t),r=`http://localhost:${n}/api/platform/agent-command`;try{let o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:e,agentId:i,payload:s}),signal:AbortSignal.timeout(5e3)});if(!o.ok){let c=await o.text();return {ok:!1,error:`HTTP ${o.status}: ${c}`}}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 Wc(){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 Gc(t,e,s){switch(t){case "paradigm_platform_navigate":{let n=await ht(s.projectDir,"navigate",{section:e.section,symbol:e.symbol,loreId:e.loreId});if(!n.ok)return {handled:true,text:`**Navigate failed:** ${n.error}`};let i=n.data;if(i.navigated){let r=[];i.section&&r.push(`section: **${i.section}**`),i.symbol&&r.push(`symbol: **${i.symbol}**`);let o=i.userActive?" (user was active \u2014 shown as prompt)":"";return {handled:true,text:`Navigated to ${r.join(", ")}${o}`}}return {handled:true,text:`Navigation skipped: ${i.reason}`}}case "paradigm_platform_highlight":{let n=await ht(s.projectDir,"highlight",{symbols:e.symbols,color:e.color,duration:e.duration,pulse:e.pulse,label:e.label});if(!n.ok)return {handled:true,text:`**Highlight failed:** ${n.error}`};let i=n.data;return i.highlighted?{handled:true,text:`Highlighted **${i.count}** symbol(s)${e.label?` with label "${e.label}"`:""}`}:{handled:true,text:`Highlight skipped: ${i.reason}`}}case "paradigm_platform_annotate":{let n=await ht(s.projectDir,"annotate",{type:e.type,message:e.message,symbol:e.symbol,severity:e.severity,duration:e.duration});if(!n.ok)return {handled:true,text:`**Annotate failed:** ${n.error}`};let i=n.data;return i.annotated?{handled:true,text:`Created ${e.type} annotation: "${e.message}"`}:{handled:true,text:`Annotation skipped: ${i.reason}`}}case "paradigm_platform_observe":{let n=await ht(s.projectDir,"observe",{detail:e.detail});if(!n.ok)return {handled:true,text:`**Observe failed:** ${n.error}`};let i=n.data,r=i.state,o=[`## Platform UI State
585
+ `)}function ng(t){switch(t.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 sg(t){return t.charAt(0).toUpperCase()+t.slice(1)}var pi="http://localhost:3838",Mc=false;function ig(t){switch(t){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 rg(t){if(t.startsWith("note:")){let e=t.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 t.startsWith("thread:")||t.startsWith("participant:")?"lifecycle":t.startsWith("file:")?"transfer":"dialogue"}async function og(t){try{Mc||(await fetch(`${pi}/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(()=>{}),Mc=!0);let e=ig(t.intent),s=rg(e);await fetch(`${pi}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:e,category:s,timestamp:t.timestamp,scopeValue:t.threadRoot||t.id,service:t.sender.project||"symphony",severity:s==="system"?"error":s==="outcome"?"warn":"info",parentEventId:t.parentId,data:{sender:t.sender.name,senderRole:t.sender.role||"core",text:t.content.text,symbols:t.symbols,diff:t.content.diff,decision:t.content.decision,parentId:t.parentId,threadId:t.threadRoot}})});}catch{}}function Jc(){let t=process.env.PARADIGM_AUTHOR;if(t)return ui(t);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return ui(e)}catch{}try{let e=ua.userInfo().username;if(e)return ui(e)}catch{}return "unknown"}function ui(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function Uc(){return new Date().toISOString().slice(0,10)}function mt(t,e){let s=[];try{s=J$1(t);}catch{}if(e){let c=s.find(l=>l.manifest.id===e);if(c)return {packId:c.manifest.id,packRoot:c.rootDir,packs:s}}let n=s.find(c=>c.manifest.tenant_kind==="project");if(n)return {packId:n.manifest.id,packRoot:n.rootDir,packs:s};let i=s.find(c=>c.manifest.tenant_kind==="first-party");if(i)return {packId:i.manifest.id,packRoot:i.rootDir,packs:s};let r=L$2(t);return {packId:M$1(r)?.id??"project",packRoot:r,packs:s}}function cg(t){let e=["notes","policies","quizzes","paths"];for(let s of ["content","src/content"]){let n=H.join(t,s);if(!E.existsSync(n))continue;let i=0;for(let r of e){let o=H.join(n,r);if(E.existsSync(o))try{i+=E.readdirSync(o).filter(a=>a.endsWith(".md")||a.endsWith(".yaml")).length;}catch{}}if(i>0)return i}return 0}function zc(){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)"},discipline:{type:"string",description:"v6.0: filter by discipline sub-pack name"},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 Yc(t,e,s){if(t==="paradigm_university_pack_list"){let n=e.tenant_kind,i=[];try{i=J$1(s.rootDir);}catch{i=[];}let o$1={packs:(n?i.filter(c=>c.manifest.tenant_kind===n):i).map(c=>({id:c.manifest.id,name:c.manifest.name,version:c.manifest.version,tenant_kind:c.manifest.tenant_kind,...c.manifest.disciplines&&c.manifest.disciplines.length>0?{discipline:c.manifest.disciplines[0]}:{},entry_count:cg(c.rootDir),path:c.rootDir}))},a=JSON.stringify(o$1,null,2);return o(a.length,t),{handled:true,text:a}}if(t==="paradigm_university_search"){let n=e.pack,{packId:i}=mt(s.rootDir,n),r=U(s.rootDir,{type:e.type,tag:e.tag,difficulty:e.difficulty,symbol:e.symbol,query:e.query,category:e.category,track:e.track,limit:e.limit}),o$1=JSON.stringify({count:r.length,pack:i,results:r.map(a=>({id:`${i}:${a.id}`,title:a.title,type:a.type,difficulty:a.difficulty,tags:a.tags,symbols:a.symbols}))},null,2);return o(o$1.length,t),{handled:true,text:o$1}}if(t==="paradigm_university_get"){let n=e.id;if(!n)return {handled:true,text:JSON.stringify({error:"id is required"})};let i=e.pack,{packId:r,packRoot:o$1}=mt(s.rootDir,i),a;try{a=K$1(n,{activePack:r}).entryId;}catch{a=n;}let c=O$1(s.rootDir,a,o$1);if(c){let u=JSON.stringify({id:c.frontmatter.id,title:c.frontmatter.title,type:c.frontmatter.type,author:c.frontmatter.author,created:c.frontmatter.created,updated:c.frontmatter.updated,tags:c.frontmatter.tags,symbols:c.frontmatter.symbols,difficulty:c.frontmatter.difficulty,prerequisites:c.frontmatter.prerequisites,body:c.body},null,2);return o(u.length,t),{handled:true,text:u}}let l=Q$1(s.rootDir,a,o$1);if(l){let u=JSON.stringify(l,null,2);return o(u.length,t),{handled:true,text:u}}let d=S$1(s.rootDir,a,o$1);if(d){let u=JSON.stringify(d,null,2);return o(u.length,t),{handled:true,text:u}}let p=JSON.stringify({error:`Content "${n}" not found`});return o(p.length,t),{handled:true,text:p}}if(t==="paradigm_university_create"){let n=e.type,i=e.title;if(!n||!i)return {handled:true,text:JSON.stringify({error:"type and title are required"})};let r=e.pack,{packRoot:o$1}=mt(s.rootDir,r),a=Jc(),c=Uc(),l=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40);if(n==="quiz"){let y=`Q-${l}`,f={id:y,title:i,description:e.body||"",author:a,created:c,updated:c,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}:{}};R(s.rootDir,f,o$1),V(s.rootDir);let b=JSON.stringify({created:y,type:"quiz",file:`content/quizzes/${y}.yaml`},null,2);return o(b.length,t),{handled:true,text:b}}if(n==="path"){let y=`LP-${l}`,f={id:y,title:i,description:e.body||"",author:a,created:c,updated:c,tags:e.tags||[],ordered:e.ordered??true,steps:e.steps||[],...e.category?{category:e.category}:{}};T(s.rootDir,f,o$1),V(s.rootDir);let b=JSON.stringify({created:y,type:"path",file:`content/paths/${y}.yaml`},null,2);return o(b.length,t),{handled:true,text:b}}let p=`${n==="policy"?"P":"N"}-${l}`,u={id:p,title:i,type:n,author:a,created:c,updated:c,tags:e.tags||[],symbols:e.symbols||[],difficulty:e.difficulty||"beginner",estimatedMinutes:e.estimatedMinutes,prerequisites:e.prerequisites||[],...e.category?{category:e.category}:{}};P$1(s.rootDir,u,e.body||"",o$1),V(s.rootDir);let m=JSON.stringify({created:p,type:n,file:`content/${n==="policy"?"policies":"notes"}/${p}.md`},null,2);return o(m.length,t),{handled:true,text:m}}if(t==="paradigm_university_update"){let n=e.id;if(!n)return {handled:true,text:JSON.stringify({error:"id is required"})};let i=e.pack,{packId:r,packRoot:o$1}=mt(s.rootDir,i),a;try{a=K$1(n,{activePack:r}).entryId;}catch{a=n;}let c=Uc(),l=O$1(s.rootDir,a,o$1);if(l){let g={...l.frontmatter};e.title&&(g.title=e.title),e.tags&&(g.tags=e.tags),e.symbols&&(g.symbols=e.symbols),e.difficulty&&(g.difficulty=e.difficulty),e.estimatedMinutes!==void 0&&(g.estimatedMinutes=e.estimatedMinutes),e.category!==void 0&&(g.category=e.category),g.updated=c;let m=e.body??l.body;P$1(s.rootDir,g,m,o$1),V(s.rootDir);let y=JSON.stringify({updated:a,type:g.type},null,2);return o(y.length,t),{handled:true,text:y}}let d=Q$1(s.rootDir,a,o$1);if(d){e.title&&(d.title=e.title),e.tags&&(d.tags=e.tags),e.symbols&&(d.symbols=e.symbols),e.difficulty&&(d.difficulty=e.difficulty),e.category!==void 0&&(d.category=e.category),d.updated=c,R(s.rootDir,d,o$1),V(s.rootDir);let g=JSON.stringify({updated:a,type:"quiz"},null,2);return o(g.length,t),{handled:true,text:g}}let p=S$1(s.rootDir,a,o$1);if(p){e.title&&(p.title=e.title),e.tags&&(p.tags=e.tags),e.category!==void 0&&(p.category=e.category),p.updated=c,T(s.rootDir,p,o$1),V(s.rootDir);let g=JSON.stringify({updated:a,type:"path"},null,2);return o(g.length,t),{handled:true,text:g}}let u=JSON.stringify({error:`Content "${n}" not found`});return o(u.length,t),{handled:true,text:u}}if(t==="paradigm_university_onboard"){let n=e.student||Jc(),i=e.pack,{packId:r}=mt(s.rootDir,i),o$1=N$1(s.rootDir),a=Y$1(s.rootDir,n),c=JSON.stringify({university:o$1.branding.name,pack:r,student:n,...a},null,2);return o(c.length,t),{handled:true,text:c}}if(t==="paradigm_university_validate"){let n=e.pack,{packId:i}=mt(s.rootDir,n),r=e.id,o$1=r;if(r)try{o$1=K$1(r,{activePack:i}).entryId;}catch{}let a=W(s.rootDir,{id:o$1,deep:e.deep}),c=JSON.stringify({pack:i,...a},null,2);return o(c.length,t),{handled:true,text:c}}return {handled:false,text:""}}function lg(t){try{let e=H.join(t,".paradigm","config.yaml");if(E.existsSync(e)){let n=Ae.load(E.readFileSync(e,"utf-8")).platform;if(n?.port&&typeof n.port=="number")return n.port}}catch{}return 3850}function dg(t){try{let e=H.join(t,".paradigm","config.yaml");if(E.existsSync(e)){let s=Ae.load(E.readFileSync(e,"utf-8")),n=s.project||H.basename(t),i=s.role||"core";return `${n}/${i}`}}catch{}return `${H.basename(t)}/core`}async function ht(t,e,s){let n=lg(t),i=dg(t),r=`http://localhost:${n}/api/platform/agent-command`;try{let o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:e,agentId:i,payload:s}),signal:AbortSignal.timeout(5e3)});if(!o.ok){let c=await o.text();return {ok:!1,error:`HTTP ${o.status}: ${c}`}}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 Vc(){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 Kc(t,e,s){switch(t){case "paradigm_platform_navigate":{let n=await ht(s.projectDir,"navigate",{section:e.section,symbol:e.symbol,loreId:e.loreId});if(!n.ok)return {handled:true,text:`**Navigate failed:** ${n.error}`};let i=n.data;if(i.navigated){let r=[];i.section&&r.push(`section: **${i.section}**`),i.symbol&&r.push(`symbol: **${i.symbol}**`);let o=i.userActive?" (user was active \u2014 shown as prompt)":"";return {handled:true,text:`Navigated to ${r.join(", ")}${o}`}}return {handled:true,text:`Navigation skipped: ${i.reason}`}}case "paradigm_platform_highlight":{let n=await ht(s.projectDir,"highlight",{symbols:e.symbols,color:e.color,duration:e.duration,pulse:e.pulse,label:e.label});if(!n.ok)return {handled:true,text:`**Highlight failed:** ${n.error}`};let i=n.data;return i.highlighted?{handled:true,text:`Highlighted **${i.count}** symbol(s)${e.label?` with label "${e.label}"`:""}`}:{handled:true,text:`Highlight skipped: ${i.reason}`}}case "paradigm_platform_annotate":{let n=await ht(s.projectDir,"annotate",{type:e.type,message:e.message,symbol:e.symbol,severity:e.severity,duration:e.duration});if(!n.ok)return {handled:true,text:`**Annotate failed:** ${n.error}`};let i=n.data;return i.annotated?{handled:true,text:`Created ${e.type} annotation: "${e.message}"`}:{handled:true,text:`Annotation skipped: ${i.reason}`}}case "paradigm_platform_observe":{let n=await ht(s.projectDir,"observe",{detail:e.detail});if(!n.ok)return {handled:true,text:`**Observe failed:** ${n.error}`};let i=n.data,r=i.state,o=[`## Platform UI State
502
586
  `];o.push(`- **Connected:** ${i.connected?"Yes":"No"} (${i.users} browser client(s))`),o.push(`- **Section:** ${r.section}`),o.push(`- **Selected symbol:** ${r.selectedSymbol||"none"}`),o.push(`- **Theme:** ${r.theme}`),o.push(`- **Muted:** ${r.muted?"Yes \u2014 agent actions silently discarded":"No"}`);let a=i.agents;if(a?.length){o.push(`
503
587
  ### Connected Agents (${a.length})`);for(let c of a)o.push(`- \`${c.agentId}\` (since ${c.connectedAt})`);}if(e.detail==="full"){let c=i.highlights,l=i.annotations;c?.length&&o.push(`
504
588
  ### Active Highlights: ${c.length}`),l?.length&&o.push(`
505
589
  ### Active Annotations: ${l.length}`);}return {handled:true,text:o.join(`
506
- `)}}case "paradigm_platform_clear":{let n=await ht(s.projectDir,"clear",{target:e.target});return n.ok?{handled:true,text:`Cleared ${n.data.target} agent effects`}:{handled:true,text:`**Clear failed:** ${n.error}`}}default:return {handled:false,text:""}}}z();function Jc(){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 Uc(t,e,s){switch(t){case "paradigm_agent_list":{let n=i$3(s.rootDir),i=b$8(s.rootDir);if(n.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 r=i?n.filter(l=>i.includes(l.id)):n,o=i?n.length-r.length:0,a=i$4(s.rootDir),c=new Map(a.map(l=>[l.id,l]));return {handled:true,text:JSON.stringify({count:r.length,totalAvailable:n.length,...i?{rosterActive:true,inactiveCount:o}:{rosterActive:false},agents:r.map(l=>{let d=c.get(l.id);return {id:l.id,role:l.role,nickname:l.nickname,personality:l.personality,...d?{lastSession:d.lastSession?.summary?.slice(0,100),lastSessionAge:d.lastSession?.date,pendingWork:d.pendingWork?.length||0,sessionsOnProject:d.sessionsOnProject||0}:{},topExpertise:(l.expertise||[]).sort((p,u)=>u.confidence-p.confidence).slice(0,5).map(p=>({symbol:p.symbol,confidence:parseFloat(p.confidence.toFixed(2)),sessions:p.sessions})),projectContexts:Object.keys(l.contexts||{}),transferableCount:(l.transferable||[]).length,...l.attention?.threshold!=null?{threshold:l.attention.threshold}:{}}})},null,2)}}case "paradigm_agent_expertise":{let n=e.symbol,i=e.response_format,r=l$3(s.rootDir,n);return i==="concise"?{handled:true,text:JSON.stringify({symbol:n,topAgent:r.length>0?{id:r[0].agentId,confidence:parseFloat(r[0].entry.confidence.toFixed(2))}:null},null,2)}:{handled:true,text:JSON.stringify({symbol:n,agents:r.map(o=>({agentId:o.agentId,confidence:parseFloat(o.entry.confidence.toFixed(2)),sessions:o.entry.sessions,lastTouch:o.entry.lastTouch})),count:r.length,...r.length===0?{note:`No agents have recorded expertise on ${n}. Run \`paradigm agent sync\` to bootstrap from lore history.`}:{}},null,2)}}case "paradigm_agent_get":{let n=e.id,i=h$5(s.rootDir,n);if(!i){let o=i$3(s.rootDir),a=n.toLowerCase(),c=o.filter(l=>l.nickname?.toLowerCase().includes(a)||l.id.includes(a));return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found by ID or nickname`,...c.length>0?{didYouMean:c.map(l=>({id:l.id,nickname:l.nickname}))}:{suggestion:`Create with \`paradigm agent create ${n} --global\``}},null,2)}}let r=y$2(i);return {handled:true,text:JSON.stringify({id:i.id,role:i.role,description:i.description,version:i.version,personality:i.personality,expertise:(i.expertise||[]).sort((o,a)=>a.confidence-o.confidence).map(o=>({symbol:o.symbol,confidence:parseFloat(o.confidence.toFixed(2)),sessions:o.sessions,lastTouch:o.lastTouch})),transferable:(i.transferable||[]).map(o=>({id:o.id,description:o.description,learnedIn:o.learnedIn,appliedIn:o.appliedIn,successRate:o.successRate})),contexts:i.contexts,created:i.created,updated:i.updated,...i.permissions?{permissions:i.permissions}:{},integrity:r},null,2)}}case "paradigm_agent_bench":{let n=e.id,i=h$5(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found`},null,2)};let r=i.id,o=b$8(s.rootDir);return o?o=o.filter(a=>a!==r):o=e$6().filter(a=>a!==r),d$7(s.rootDir,o),{handled:true,text:JSON.stringify({id:r,...i.nickname?{nickname:i.nickname}:{},removedFromRoster:true,rosterCount:o.length,note:`${i.nickname||r} (${r}) removed from this project's roster. Still available globally.`},null,2)}}case "paradigm_agent_activate":{let n=e.id,i=h$5(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found`},null,2)};let r=i.id,o=b$8(s.rootDir);return o&&(o.includes(r)||(o.push(r),d$7(s.rootDir,o))),{handled:true,text:JSON.stringify({id:r,...i.nickname?{nickname:i.nickname}:{},addedToRoster:true,rosterCount:o?.length??"all (no roster)",note:`${i.nickname||r} (${r}) is active on this project's roster.`},null,2)}}default:return {handled:false,text:""}}}h();function Bc(){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 zc(t,e,s){switch(t){case "paradigm_notebook_search":{let n=e.agentId,i=e.query,r=e.concepts,o=e.tags,a=e.response_format,c;return i?c=b$9(n,i,s.rootDir):c=a$8(n,s.rootDir,{concepts:r,tags:o}),a==="concise"?{handled:true,text:JSON.stringify({agentId:n,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,concepts:l.concepts}))},null,2)}:{handled:true,text:JSON.stringify({agentId:n,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,snippet:l.snippet.length>500?l.snippet.slice(0,500)+"...":l.snippet,concepts:l.concepts,tags:l.tags,appliedCount:l.appliedCount,confidence:l.confidence,provenance:l.provenance}))},null,2)}}case "paradigm_notebook_add":{let n=e.agentId,i=e.context,r=e.snippet,o=e.concepts||[],a=e.tags||[],c=e.confidence??.7,l=e.scope||(s.rootDir?"project":"global"),d=e.parentId,p=e.lineageType,u=e.publishable,m=e.scope,g={context:i,snippet:r,provenance:{source:"manual",createdBy:n},confidence:c,concepts:o,tags:a,...m?{scope:m}:{},...u!==void 0?{publishable:u}:{},...d?{parentId:d}:{},...p?{lineageType:p}:{}},y=d$8(n,g,l,s.rootDir);return {handled:true,text:JSON.stringify({action:"notebook_add",id:y.entry.id,agentId:n,scope:l,filePath:y.filePath,concepts:y.entry.concepts,...d?{parentId:d}:{},...p?{lineageType:p}:{}},null,2)}}case "paradigm_notebook_promote":{let n=e.agentId,i=e.loreEntryId,r=e.scope||(s.rootDir?"project":"global"),o=await e$7(n,i,s.rootDir,r);return o?{handled:true,text:JSON.stringify({action:"notebook_promote",id:o.entry.id,agentId:n,loreEntryId:i,scope:r,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 "${i}" not found`,suggestion:"Check the lore entry ID with paradigm_lore_search"},null,2)}}default:return {handled:false,text:""}}}var Vu=".paradigm/scan-index.json",Ku=".paradigm/flow-index.json",Qu=".paradigm/config.yaml",Xu="portal.yaml",Zu=".paradigm/university/index.yaml",oe={enabled:true,title:null,theme:"dark",customCss:null,customContent:"docs/",exclude:{tags:[],patterns:[]},sidebar:{collapsed:[]},output:".paradigm/docs-site"};function wt(t){let e=H.join(t,Qu);if(!E.existsSync(e))return {...oe};try{let s=E.readFileSync(e,"utf8"),n=Te.load(s);if(!n||!n.docs)return {...oe};let i=n.docs;return {enabled:i.enabled??oe.enabled,title:i.title??oe.title,theme:i.theme??oe.theme,customCss:i.customCss??oe.customCss,customContent:i.customContent??oe.customContent,exclude:{tags:i.exclude?.tags??oe.exclude.tags,patterns:i.exclude?.patterns??oe.exclude.patterns},sidebar:{collapsed:i.sidebar?.collapsed??oe.sidebar.collapsed},output:i.output??oe.output}}catch{return {...oe}}}function Un(t){let e=H.join(t,Vu);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function pi(t){let e=H.join(t,Ku);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function Bn(t){let e=H.join(t,Xu);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch{return null}}function Vc(t){let e=H.join(t,Zu);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch{return null}}function Kc(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:Te.load(e[1]),body:e[2].trim()}}catch{return null}}function Qc(t){let e=new Map,s=[t.components,t.features,t.flows,t.state,t.gates,t.signals,t.aspects];for(let n of s)if(n)for(let[i,r]of Object.entries(n))e.set(i,r);return e}function eg(t){return {components:"component",features:"component",flows:"flow",state:"component",gates:"gate",signals:"signal",aspects:"aspect"}[t]||"component"}function bt(t,e){if(e.exclude.tags.length>0&&t.visualTags){for(let s of t.visualTags)if(e.exclude.tags.includes(s))return true}if(e.exclude.patterns.length>0&&t.path){for(let s of e.exclude.patterns)if(s.endsWith("*")){let n=s.slice(0,-1);if(t.path.includes(n))return true}else if(t.path.includes(s))return true}return false}function Xc(t,e){let s=H.join(t,e);if(!E.existsSync(s))return [];let n=[];try{let i=E.readdirSync(s).filter(r=>r.endsWith(".md"));for(let r of i)try{let o=E.readFileSync(H.join(s,r),"utf8"),a=r.replace(/\.md$/,""),c=Kc(o);c?n.push({slug:a,title:c.frontmatter.title||a,body:c.body,order:typeof c.frontmatter.order=="number"?c.frontmatter.order:void 0,description:c.frontmatter.description||void 0}):n.push({slug:a,title:a,body:o.trim()});}catch{}}catch{}return n.sort((i,r)=>i.order!=null&&r.order!=null?i.order-r.order:i.order!=null?-1:r.order!=null?1:i.title.localeCompare(r.title)),n}function Zc(t,e,s){let n=s||wt(t),i=H.join(t,n.customContent),r=H.join(i,`${e}.md`);if(!E.existsSync(r))return null;try{let o=E.readFileSync(r,"utf8"),a=Kc(o);return a?{slug:e,title:a.frontmatter.title||e,body:a.body,order:typeof a.frontmatter.order=="number"?a.frontmatter.order:void 0,description:a.frontmatter.description||void 0}:{slug:e,title:e,body:o.trim()}}catch{return null}}function el(t,e){let s=e||wt(t),n=Un(t),i=pi(t),r=Bn(t),o=Xc(t,s.customContent),a=Vc(t),c=n?.$meta?.project||H.basename(t),l=s.title||`${c} Docs`,d=[],p={},u=0;if(o.length>0&&d.push({id:"custom-pages",label:"Pages",collapsed:s.sidebar.collapsed.includes("custom-pages"),items:o.map(m=>({id:m.slug,label:m.title,kind:"custom",description:m.description}))}),a&&a.entries.length>0){let m=a.entries.filter(g=>(g.type==="note"||g.type==="policy")&&g.symbols.length>0);m.length>0&&d.push({id:"guides",label:"Guides",collapsed:s.sidebar.collapsed.includes("guides"),items:m.map(g=>({id:g.id,label:g.title,kind:"guide",description:void 0,badge:g.symbols.length>0?`${g.symbols.length} symbols`:void 0}))});}if(n){let m=Object.values(n.components||{}).filter(_=>!bt(_,s));if(m.length>0){let _=new Map;for(let S of m){let R=S.componentType||"other";_.has(R)||_.set(R,[]),_.get(R).push(S);}let C=[..._.entries()].sort((S,R)=>R[1].length-S[1].length).map(([S,R])=>({id:`components-${S}`,label:`${S.charAt(0).toUpperCase()+S.slice(1)} (${R.length})`,collapsed:s.sidebar.collapsed.includes(`components-${S}`),items:R.sort((I,P)=>I.name.localeCompare(P.name)).map(I=>({id:I.id,label:I.name,kind:"component",description:I.description,badge:I.componentType}))}));d.push({id:"components",label:`Components (${m.length})`,collapsed:s.sidebar.collapsed.includes("components"),items:[],subgroups:C}),p.components=m.length,u+=m.length;}let g=Object.values(n.features||{}).filter(_=>!bt(_,s));g.length>0&&(d.push({id:"features",label:`Features (${g.length})`,collapsed:s.sidebar.collapsed.includes("features"),items:g.sort((_,x)=>_.name.localeCompare(x.name)).map(_=>({id:_.id,label:_.name,kind:"component",description:_.description}))}),p.features=g.length,u+=g.length);let y=Object.values(n.flows||{}).filter(_=>!bt(_,s)),f=new Set(y.map(_=>_.id)),b=[];if(i)for(let[_,x]of Object.entries(i.flows)){let C=_.replace(/^\$/,"");f.has(C)||b.push({id:C,label:x.name||C,kind:"flow",description:x.description});}let h=[...y.sort((_,x)=>_.name.localeCompare(x.name)).map(_=>({id:_.id,label:_.name,kind:"flow",description:_.description})),...b];h.length>0&&(d.push({id:"flows",label:`Flows (${h.length})`,collapsed:s.sidebar.collapsed.includes("flows"),items:h}),p.flows=h.length,u+=h.length);let w=Object.values(n.gates||{}).filter(_=>!bt(_,s));w.length>0&&(d.push({id:"gates",label:`Gates (${w.length})`,collapsed:s.sidebar.collapsed.includes("gates"),items:w.sort((_,x)=>_.name.localeCompare(x.name)).map(_=>({id:_.id,label:_.name,kind:"gate",description:_.description}))}),p.gates=w.length,u+=w.length);let v=Object.values(n.signals||{}).filter(_=>!bt(_,s));v.length>0&&(d.push({id:"signals",label:`Signals (${v.length})`,collapsed:s.sidebar.collapsed.includes("signals"),items:v.sort((_,x)=>_.name.localeCompare(x.name)).map(_=>({id:_.id,label:_.name,kind:"signal",description:_.description}))}),p.signals=v.length,u+=v.length);let k=Object.values(n.aspects||{}).filter(_=>!bt(_,s));k.length>0&&(d.push({id:"aspects",label:`Aspects (${k.length})`,collapsed:s.sidebar.collapsed.includes("aspects"),items:k.sort((_,x)=>_.name.localeCompare(x.name)).map(_=>({id:_.id,label:_.name,kind:"aspect",description:_.description}))}),p.aspects=k.length,u+=k.length);}if(r){let m=Object.keys(r.routes||{}).length,g=Object.keys(r.gates||{}).length;d.push({id:"portal",label:"Portal",collapsed:s.sidebar.collapsed.includes("portal"),items:[{id:"portal-overview",label:"Authorization Overview",kind:"portal",description:`${g} gates, ${m} routes`,badge:`${m} routes`}]});}return {title:l,project:c,generatedAt:new Date().toISOString(),groups:d,totalSymbols:u,symbolCounts:p}}function tl(t,e){let s=Un(t);if(!s)return null;let n=Qc(s),i=n.get(e);if(!i)return null;let r=[];for(let[f,b]of n)f!==e&&b.related&&b.related.includes(i.symbol)&&r.push(b.symbol);let o=(i.related||[]).slice(),a=[],c=pi(t);if(c)for(let[f,b]of Object.entries(c.flows)){let h=(b.steps||[]).map(w=>w.symbol);(h.includes(i.symbol)||h.includes(`#${e}`))&&a.push({id:f.replace(/^\$/,""),name:b.name||f});}if(s.flows)for(let[f,b]of Object.entries(s.flows)){if(a.some(w=>w.id===f))continue;let h=(b.steps||[]).map(w=>w.symbol).filter(Boolean);(h.includes(i.symbol)||h.includes(`#${e}`))&&a.push({id:f,name:b.name});}let l=[],d=Bn(t);if(d&&i.category==="gates"){let f=Object.keys(d.gates||{}).find(b=>b.replace(/^\^/,"")===e);f&&l.push({id:f.replace(/^\^/,""),description:d.gates[f].description});}else if(d){let f=new Set((i.related||[]).filter(b=>b.startsWith("^")));for(let[b,h]of Object.entries(d.routes||{}))for(let w of h){let v=w.replace(/^\^/,"");if(f.has(w)||f.has(`^${v}`)){let k=d.gates[w]||d.gates[`^${v}`]||d.gates[v];k&&!l.some(_=>_.id===v)&&l.push({id:v,description:k.description});}}}let p=[];if(s.aspects)for(let[f,b]of Object.entries(s.aspects))b.related&&b.related.includes(i.symbol)&&p.push(b.symbol);for(let f of i.related||[])f.startsWith("~")&&!p.includes(f)&&p.push(f);let u=[],m=Vc(t);if(m)for(let f of m.entries)f.symbols.includes(i.symbol)&&u.push({id:f.id,title:f.title});let g=i.parent||void 0,y=[];if(s.components)for(let f of Object.values(s.components))f.parent===i.symbol&&y.push(f.symbol);return {id:i.id,symbol:i.symbol,name:i.name,description:i.description||"",category:i.category||"components",componentType:i.componentType,tags:i.visualTags||[],path:i.path||"",related:i.related||[],referencedBy:r,references:o,flows:a,gates:l,aspects:p,guides:u,parent:g,children:y}}function nl(t,e){let s=pi(t),n=Un(t);if(s){let i=s.flows[`$${e}`]?`$${e}`:e,r=s.flows[i];if(r){let o=(r.steps||[]).map(c=>({type:c.type||"action",symbol:c.symbol||"",description:c.description})),a=n?.flows?.[e.replace(/^\$/,"")];return {id:e.replace(/^\$/,""),symbol:`$${e.replace(/^\$/,"")}`,name:r.name||e,description:r.description,trigger:r.trigger,steps:o,successSignal:r.successSignal,errorSignal:r.errorSignal,tags:a?.visualTags||[],path:a?.path||r.definedIn||""}}}if(n?.flows){let i=e.replace(/^\$/,""),r=n.flows[i];if(r){let o=(r.steps||[]).map(a=>({type:"action",symbol:a.symbol||"",description:a.action||a.name}));return {id:i,symbol:`$${i}`,name:r.name,description:r.description,steps:o,tags:r.visualTags||[],path:r.path||""}}}return null}function sl(t){let e=Bn(t);if(!e)return {version:"0",gates:[],routes:[]};let s=new Map;for(let[r,o]of Object.entries(e.routes||{}))for(let a of o){let c=a.replace(/^\^/,"");s.has(c)||s.set(c,[]),s.get(c).push(r);}let n=Object.entries(e.gates||{}).map(([r,o])=>{let a=r.replace(/^\^/,"");return {symbol:`^${a}`,description:o.description,check:o.check,routes:s.get(a)||[]}}),i=Object.entries(e.routes||{}).map(([r,o])=>{let a=r.indexOf(" "),c=a>0?r.substring(0,a):"GET";return {route:a>0?r.substring(a+1):r,method:c,gates:o.map(d=>{let p=d.replace(/^\^/,""),u=e.gates[d]||e.gates[`^${p}`]||e.gates[p];return {symbol:`^${p}`,description:u?.description}})}});return {version:e.version||"1.0",gates:n,routes:i}}function il(t,e,s){let n=s||20,i=[],r=e.toLowerCase(),o=Un(t);if(o){let d=Qc(o);for(let[p,u]of d){let m=di(u.name,u.description||"",u.visualTags||[],r);m>0&&i.push({id:u.id,kind:eg(u.category),label:u.name,description:u.description||"",matchContext:Yc(u.name,u.description||"",r),score:m});}}let a=wt(t),c=Xc(t,a.customContent);for(let d of c){let p=d.body.substring(0,200),u=di(d.title,p,[],r);u>0&&i.push({id:d.slug,kind:"custom",label:d.title,description:d.description||p.substring(0,100),matchContext:Yc(d.title,d.body,r),score:u});}let l=Bn(t);if(l)for(let[d,p]of Object.entries(l.gates||{})){let u=d.replace(/^\^/,""),m=di(u,p.description,[],r);m>0&&i.push({id:u,kind:"portal",label:`^${u}`,description:p.description,score:m});}return i.sort((d,p)=>p.score-d.score||d.label.localeCompare(p.label)),i.slice(0,n)}function di(t,e,s,n){let i=t.toLowerCase(),r=e.toLowerCase();return i===n?1:i.startsWith(n)?.8:i.includes(n)?.6:r.includes(n)?.5:s.some(o=>o.toLowerCase().includes(n))?.3:0}function Yc(t,e,s){let i=e.toLowerCase().indexOf(s);if(i<0)return t.toLowerCase().includes(s)?t:void 0;let r=Math.max(0,i-40),o=Math.min(e.length,i+s.length+40),a=e.substring(r,o).trim();return r>0&&(a=`...${a}`),o<e.length&&(a=`${a}...`),a}function rl(){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 ol(t,e,s){if(t==="paradigm_docs_manifest"){let n=wt(s.rootDir),i=el(s.rootDir,n),r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}if(t==="paradigm_docs_page"){if(e.portal){let i=sl(s.rootDir),r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}if(e.flow){let i=e.flow,r=nl(s.rootDir,i);if(!r){let a=JSON.stringify({error:`Flow "${i}" not found`});return o(a.length,t),{handled:true,text:a}}let o$1=JSON.stringify(r,null,2);return o(o$1.length,t),{handled:true,text:o$1}}if(e.slug){let i=wt(s.rootDir),r=Zc(s.rootDir,e.slug,i);if(!r){let a=JSON.stringify({error:`Page "${e.slug}" not found`});return o(a.length,t),{handled:true,text:a}}let o$1=JSON.stringify(r,null,2);return o(o$1.length,t),{handled:true,text:o$1}}if(e.symbol){let i=tl(s.rootDir,e.symbol);if(!i){let o$1=JSON.stringify({error:`Symbol "${e.symbol}" not found`});return o(o$1.length,t),{handled:true,text:o$1}}let r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}let n=JSON.stringify({error:"Provide one of: symbol, flow, portal, or slug"});return o(n.length,t),{handled:true,text:n}}if(t==="paradigm_docs_search"){let n=e.query;if(!n)return {handled:true,text:JSON.stringify({error:"query is required"})};let i=il(s.rootDir,n,e.limit),r=JSON.stringify({count:i.length,results:i},null,2);return o(r.length,t),{handled:true,text:r}}return {handled:false,text:""}}g();e();function al(){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 cl(t,e,s){let n=i=>JSON.stringify(i,null,2);switch(t){case "paradigm_work_log_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.summary,i,"work_log"),o=a$5(s.rootDir,{agent:e.agent,summary:r,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:n({recorded:true,id:o.id,timestamp:o.timestamp}),handled:true}}case "paradigm_work_log_search":{if(e.summary){let r=d$5(s.rootDir,7);return {text:n(r),handled:true}}let i=b$6(s.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:n({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,summary:r.summary,outcome:r.outcome,timestamp:r.timestamp,symbols_touched:r.symbols_touched,task_ref:r.task_ref}))}),handled:true}}case "paradigm_journal_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.insight,i,"learning_journal"),o=a$4(e.agent,{trigger:e.trigger,insight:r,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:n({recorded:true,id:o.id,agent:o.agent,timestamp:o.timestamp}),handled:true}}case "paradigm_journal_search":{if(e.stats&&e.agent){let r=e$4(e.agent);return {text:n(r),handled:true}}let i=e.agent?b$5(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$4({trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,trigger:r.trigger,insight:r.insight.slice(0,200),project:r.project,transferable:r.transferable,timestamp:r.timestamp}))}),handled:true}}case "paradigm_decision_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.decision,i,"team_decisions"),{filtered:o}=d$3(e.rationale,i,"team_decisions"),a=a$2(s.rootDir,{title:e.title,decision:r,rationale:o,participants:e.participants,alternatives_considered:e.alternatives_considered,symbols_affected:e.symbols_affected,status:e.status||"active",tags:e.tags}),c=d$1(s.rootDir,a.id);return {text:n({recorded:true,id:a.id,title:a.title,timestamp:a.timestamp,...c?{companion_lore_id:c}:{}}),handled:true}}case "paradigm_decision_search":{if(e.summary){let r=h$4(s.rootDir);return {text:n(r),handled:true}}let i=e$3(s.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:n({count:i.length,entries:i.map(r=>({id:r.id,title:r.title,status:r.status,decision:r.decision.slice(0,200),participants:r.participants.map(o=>`${o.id} (${o.stance})`),symbols_affected:r.symbols_affected,timestamp:r.timestamp}))}),handled:true}}default:return {text:`Unknown streams tool: ${t}`,handled:false}}}v();b$2();z();g();q();function ll(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function tg(t){let e=Date.now(),s=t.match(/^(\d+)(m|h|d)$/);if(s){let n=parseInt(s[1],10),i=s[2],r=i==="m"?n*6e4:i==="h"?n*36e5:n*864e5;return new Date(e-r).toISOString()}return t}async function dl(t,e,s){let n=i=>JSON.stringify(i,null,2);switch(t){case "paradigm_ambient_nominations":{m$1(s.rootDir);let r=e.pending_only!==false,o=e.limit||20,a=i$2(s.rootDir,{agent:e.agent,urgency:e.urgency,pending_only:r,limit:o+20}),c=t$1(s.rootDir);a=u$1(a,c).slice(0,o);let l=H.join(s.rootDir,".paradigm/events/nominations.jsonl");if(E.existsSync(l))try{let p=E.readFileSync(l,"utf8"),u=new Set(a.map(g=>g.id)),m=p.trim().split(`
507
- `).map(g=>{try{let y=JSON.parse(g);return u.has(y.id)?(y.surfaced=!0,JSON.stringify(y)):g}catch{return g}});E.writeFileSync(l,m.join(`
590
+ `)}}case "paradigm_platform_clear":{let n=await ht(s.projectDir,"clear",{target:e.target});return n.ok?{handled:true,text:`Cleared ${n.data.target} agent effects`}:{handled:true,text:`**Clear failed:** ${n.error}`}}default:return {handled:false,text:""}}}z();function Qc(){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 Xc(t,e,s){switch(t){case "paradigm_agent_list":{let n=i$3(s.rootDir),i=b$8(s.rootDir);if(n.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 r=i?n.filter(l=>i.includes(l.id)):n,o=i?n.length-r.length:0,a=i$4(s.rootDir),c=new Map(a.map(l=>[l.id,l]));return {handled:true,text:JSON.stringify({count:r.length,totalAvailable:n.length,...i?{rosterActive:true,inactiveCount:o}:{rosterActive:false},agents:r.map(l=>{let d=c.get(l.id);return {id:l.id,role:l.role,nickname:l.nickname,personality:l.personality,...d?{lastSession:d.lastSession?.summary?.slice(0,100),lastSessionAge:d.lastSession?.date,pendingWork:d.pendingWork?.length||0,sessionsOnProject:d.sessionsOnProject||0}:{},topExpertise:(l.expertise||[]).sort((p,u)=>u.confidence-p.confidence).slice(0,5).map(p=>({symbol:p.symbol,confidence:parseFloat(p.confidence.toFixed(2)),sessions:p.sessions})),projectContexts:Object.keys(l.contexts||{}),transferableCount:(l.transferable||[]).length,...l.attention?.threshold!=null?{threshold:l.attention.threshold}:{}}})},null,2)}}case "paradigm_agent_expertise":{let n=e.symbol,i=e.response_format,r=l$3(s.rootDir,n);return i==="concise"?{handled:true,text:JSON.stringify({symbol:n,topAgent:r.length>0?{id:r[0].agentId,confidence:parseFloat(r[0].entry.confidence.toFixed(2))}:null},null,2)}:{handled:true,text:JSON.stringify({symbol:n,agents:r.map(o=>({agentId:o.agentId,confidence:parseFloat(o.entry.confidence.toFixed(2)),sessions:o.entry.sessions,lastTouch:o.entry.lastTouch})),count:r.length,...r.length===0?{note:`No agents have recorded expertise on ${n}. Run \`paradigm agent sync\` to bootstrap from lore history.`}:{}},null,2)}}case "paradigm_agent_get":{let n=e.id,i=h$5(s.rootDir,n);if(!i){let o=i$3(s.rootDir),a=n.toLowerCase(),c=o.filter(l=>l.nickname?.toLowerCase().includes(a)||l.id.includes(a));return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found by ID or nickname`,...c.length>0?{didYouMean:c.map(l=>({id:l.id,nickname:l.nickname}))}:{suggestion:`Create with \`paradigm agent create ${n} --global\``}},null,2)}}let r=y$2(i);return {handled:true,text:JSON.stringify({id:i.id,role:i.role,description:i.description,version:i.version,personality:i.personality,expertise:(i.expertise||[]).sort((o,a)=>a.confidence-o.confidence).map(o=>({symbol:o.symbol,confidence:parseFloat(o.confidence.toFixed(2)),sessions:o.sessions,lastTouch:o.lastTouch})),transferable:(i.transferable||[]).map(o=>({id:o.id,description:o.description,learnedIn:o.learnedIn,appliedIn:o.appliedIn,successRate:o.successRate})),contexts:i.contexts,created:i.created,updated:i.updated,...i.permissions?{permissions:i.permissions}:{},integrity:r},null,2)}}case "paradigm_agent_bench":{let n=e.id,i=h$5(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found`},null,2)};let r=i.id,o=b$8(s.rootDir);return o?o=o.filter(a=>a!==r):o=e$6().filter(a=>a!==r),d$7(s.rootDir,o),{handled:true,text:JSON.stringify({id:r,...i.nickname?{nickname:i.nickname}:{},removedFromRoster:true,rosterCount:o.length,note:`${i.nickname||r} (${r}) removed from this project's roster. Still available globally.`},null,2)}}case "paradigm_agent_activate":{let n=e.id,i=h$5(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found`},null,2)};let r=i.id,o=b$8(s.rootDir);return o&&(o.includes(r)||(o.push(r),d$7(s.rootDir,o))),{handled:true,text:JSON.stringify({id:r,...i.nickname?{nickname:i.nickname}:{},addedToRoster:true,rosterCount:o?.length??"all (no roster)",note:`${i.nickname||r} (${r}) is active on this project's roster.`},null,2)}}default:return {handled:false,text:""}}}var tl=H.join(".paradigm","authority.yaml");async function Zc(t){let e=H.join(t,tl),s;try{s=await bt.readFile(e,"utf8");}catch(i){if(i.code==="ENOENT")return null;throw i}let n=Ae.load(s);return n==null||typeof n!="object"?{version:"1.0",schema:"v0-experimental",claims:{}}:((!n.claims||typeof n.claims!="object")&&(n.claims={}),n)}async function el(t,e){let s=H.join(t,tl);await bt.mkdir(H.dirname(s),{recursive:true});let n=Ae.dump(e,{lineWidth:100,sortKeys:false});await bt.writeFile(s,n,"utf8");}function nl(){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 sl(t,e,s){if(t==="paradigm_authority_claim"){let n=e.claimant,i=e.scope,r=e.severity??"advise";if(!n||!i)return {handled:true,text:JSON.stringify({error:"Missing required field: claimant, scope"},null,2)};let o=new Date().toISOString(),a={claimant:n,severity:r,since:o,source:"explicit"},c=await Zc(s.rootDir)??{version:"1.0",schema:"v0-experimental",claims:{}};return c.claims[i]=a,await el(s.rootDir,c),{handled:true,text:JSON.stringify({scope:i,claimant:n,severity:r,source:"explicit",since:o},null,2)}}if(t==="paradigm_authority_release"){let n=e.claimant,i=e.scope;if(!n||!i)return {handled:true,text:JSON.stringify({error:"Missing required field: claimant, scope"},null,2)};let r=await Zc(s.rootDir);if(!r||!(i in r.claims))return {handled:true,text:JSON.stringify({scope:i,released:false,note:"no active claim on this scope"},null,2)};let o=r.claims[i].claimant;return delete r.claims[i],await el(s.rootDir,r),{handled:true,text:JSON.stringify({scope:i,released:true,previousClaimant:o},null,2)}}return {handled:false,text:""}}var il=H.join(".paradigm","remediations");function pg(){return "rmd-"+Date.now().toString(36)}function ol(){return [{name:"paradigm_propose_block",description:"Author a soft-block (remediation) that the Stop hook will honor until resolved. Use when your archetype detects a condition the user should resolve before continuing (e.g., coverage drop, missing aspect, broken anchor). User can override via `paradigm override <id>` or PARADIGM_OVERRIDE env var. v6.1: only severity=guard hard-blocks; advise/auto-author are informational. ~150 tokens.",inputSchema:{type:"object",properties:{claimant:{type:"string",description:'Archetype id authoring this block (e.g., "compliance", "security"). REQUIRED \u2014 do not infer.'},severity:{type:"string",enum:["advise","auto-author","guard"],description:"Block intent for this event. v6.1: only `guard` hard-blocks; `advise`/`auto-author` are informational."},reason:{type:"string",description:"Free-text explanation surfaced to the user verbatim. Be specific (component name, file path)."},unblock_hint:{type:"string",description:"Plain-string remediation hint (v6.1; JSONLogic predicates ship v6.2). Tell the user how to resolve."},expires_at:{type:"string",description:"OPTIONAL ISO 8601 UTC timestamp. After this, Check 14 silently skips the remediation. Use for time-bounded conditions."},target:{type:"object",description:"OPTIONAL context: {file, symbol, line}.",properties:{file:{type:"string"},symbol:{type:"string"},line:{type:"number"}}}},required:["claimant","severity","reason","unblock_hint"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function al(t,e,s){if(t!=="paradigm_propose_block")return {handled:false,text:""};let n=e.claimant,i=e.severity,r=e.reason,o=e.unblock_hint,a=e.expires_at,c=e.target;if(!n||!i||!r||!o)return {handled:true,text:JSON.stringify({error:"Missing required field. Required: claimant, severity, reason, unblock_hint."},null,2)};let l=pg(),d=new Date().toISOString(),p={id:l,claimant:n,severity:i,reason:r,unblock_hint:o,created:d};a&&(p.expires_at=a),c&&(c.file||c.symbol||c.line!=null)&&(p.target=c);let u=H.join(s.rootDir,il);await bt.mkdir(u,{recursive:true});let g=H.join(u,`${l}.yaml`),m=Ae.dump(p,{lineWidth:100,sortKeys:false});return await bt.writeFile(g,m,"utf8"),{handled:true,text:JSON.stringify({id:l,path:H.join(il,`${l}.yaml`),claimant:n,severity:i,...a?{expires_at:a}:{},note:`Stop hook will ${i==="guard"?"block":"note"} on next run. User can clear with: paradigm override ${l}`},null,2)}}h();function cl(){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 ll(t,e,s){switch(t){case "paradigm_notebook_search":{let n=e.agentId,i=e.query,r=e.concepts,o=e.tags,a=e.response_format,c;return i?c=b$9(n,i,s.rootDir):c=a$8(n,s.rootDir,{concepts:r,tags:o}),a==="concise"?{handled:true,text:JSON.stringify({agentId:n,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,concepts:l.concepts}))},null,2)}:{handled:true,text:JSON.stringify({agentId:n,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,snippet:l.snippet.length>500?l.snippet.slice(0,500)+"...":l.snippet,concepts:l.concepts,tags:l.tags,appliedCount:l.appliedCount,confidence:l.confidence,provenance:l.provenance}))},null,2)}}case "paradigm_notebook_add":{let n=e.agentId,i=e.context,r=e.snippet,o=e.concepts||[],a=e.tags||[],c=e.confidence??.7,l=e.scope||(s.rootDir?"project":"global"),d=e.parentId,p=e.lineageType,u=e.publishable,g=e.scope,m={context:i,snippet:r,provenance:{source:"manual",createdBy:n},confidence:c,concepts:o,tags:a,...g?{scope:g}:{},...u!==void 0?{publishable:u}:{},...d?{parentId:d}:{},...p?{lineageType:p}:{}},y=d$8(n,m,l,s.rootDir);return {handled:true,text:JSON.stringify({action:"notebook_add",id:y.entry.id,agentId:n,scope:l,filePath:y.filePath,concepts:y.entry.concepts,...d?{parentId:d}:{},...p?{lineageType:p}:{}},null,2)}}case "paradigm_notebook_promote":{let n=e.agentId,i=e.loreEntryId,r=e.scope||(s.rootDir?"project":"global"),o=await e$7(n,i,s.rootDir,r);return o?{handled:true,text:JSON.stringify({action:"notebook_promote",id:o.entry.id,agentId:n,loreEntryId:i,scope:r,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 "${i}" not found`,suggestion:"Check the lore entry ID with paradigm_lore_search"},null,2)}}default:return {handled:false,text:""}}}var ug=".paradigm/scan-index.json",gg=".paradigm/flow-index.json",mg=".paradigm/config.yaml",fg="portal.yaml",yg=".paradigm/university/index.yaml",oe={enabled:true,title:null,theme:"dark",customCss:null,customContent:"docs/",exclude:{tags:[],patterns:[]},sidebar:{collapsed:[]},output:".paradigm/docs-site"};function kt(t){let e=H.join(t,mg);if(!E.existsSync(e))return {...oe};try{let s=E.readFileSync(e,"utf8"),n=Ae.load(s);if(!n||!n.docs)return {...oe};let i=n.docs;return {enabled:i.enabled??oe.enabled,title:i.title??oe.title,theme:i.theme??oe.theme,customCss:i.customCss??oe.customCss,customContent:i.customContent??oe.customContent,exclude:{tags:i.exclude?.tags??oe.exclude.tags,patterns:i.exclude?.patterns??oe.exclude.patterns},sidebar:{collapsed:i.sidebar?.collapsed??oe.sidebar.collapsed},output:i.output??oe.output}}catch{return {...oe}}}function Kn(t){let e=H.join(t,ug);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function yi(t){let e=H.join(t,gg);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function Qn(t){let e=H.join(t,fg);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Ae.load(s)}catch{return null}}function pl(t){let e=H.join(t,yg);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Ae.load(s)}catch{return null}}function ul(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:Ae.load(e[1]),body:e[2].trim()}}catch{return null}}function gl(t){let e=new Map,s=[t.components,t.features,t.flows,t.state,t.gates,t.signals,t.aspects];for(let n of s)if(n)for(let[i,r]of Object.entries(n))e.set(i,r);return e}function hg(t){return {components:"component",features:"component",flows:"flow",state:"component",gates:"gate",signals:"signal",aspects:"aspect"}[t]||"component"}function vt(t,e){if(e.exclude.tags.length>0&&t.visualTags){for(let s of t.visualTags)if(e.exclude.tags.includes(s))return true}if(e.exclude.patterns.length>0&&t.path){for(let s of e.exclude.patterns)if(s.endsWith("*")){let n=s.slice(0,-1);if(t.path.includes(n))return true}else if(t.path.includes(s))return true}return false}function ml(t,e){let s=H.join(t,e);if(!E.existsSync(s))return [];let n=[];try{let i=E.readdirSync(s).filter(r=>r.endsWith(".md"));for(let r of i)try{let o=E.readFileSync(H.join(s,r),"utf8"),a=r.replace(/\.md$/,""),c=ul(o);c?n.push({slug:a,title:c.frontmatter.title||a,body:c.body,order:typeof c.frontmatter.order=="number"?c.frontmatter.order:void 0,description:c.frontmatter.description||void 0}):n.push({slug:a,title:a,body:o.trim()});}catch{}}catch{}return n.sort((i,r)=>i.order!=null&&r.order!=null?i.order-r.order:i.order!=null?-1:r.order!=null?1:i.title.localeCompare(r.title)),n}function fl(t,e,s){let n=s||kt(t),i=H.join(t,n.customContent),r=H.join(i,`${e}.md`);if(!E.existsSync(r))return null;try{let o=E.readFileSync(r,"utf8"),a=ul(o);return a?{slug:e,title:a.frontmatter.title||e,body:a.body,order:typeof a.frontmatter.order=="number"?a.frontmatter.order:void 0,description:a.frontmatter.description||void 0}:{slug:e,title:e,body:o.trim()}}catch{return null}}function yl(t,e){let s=e||kt(t),n=Kn(t),i=yi(t),r=Qn(t),o=ml(t,s.customContent),a=pl(t),c=n?.$meta?.project||H.basename(t),l=s.title||`${c} Docs`,d=[],p={},u=0;if(o.length>0&&d.push({id:"custom-pages",label:"Pages",collapsed:s.sidebar.collapsed.includes("custom-pages"),items:o.map(g=>({id:g.slug,label:g.title,kind:"custom",description:g.description}))}),a&&a.entries.length>0){let g=a.entries.filter(m=>(m.type==="note"||m.type==="policy")&&m.symbols.length>0);g.length>0&&d.push({id:"guides",label:"Guides",collapsed:s.sidebar.collapsed.includes("guides"),items:g.map(m=>({id:m.id,label:m.title,kind:"guide",description:void 0,badge:m.symbols.length>0?`${m.symbols.length} symbols`:void 0}))});}if(n){let g=Object.values(n.components||{}).filter(S=>!vt(S,s));if(g.length>0){let S=new Map;for(let _ of g){let R=_.componentType||"other";S.has(R)||S.set(R,[]),S.get(R).push(_);}let C=[...S.entries()].sort((_,R)=>R[1].length-_[1].length).map(([_,R])=>({id:`components-${_}`,label:`${_.charAt(0).toUpperCase()+_.slice(1)} (${R.length})`,collapsed:s.sidebar.collapsed.includes(`components-${_}`),items:R.sort((I,P)=>I.name.localeCompare(P.name)).map(I=>({id:I.id,label:I.name,kind:"component",description:I.description,badge:I.componentType}))}));d.push({id:"components",label:`Components (${g.length})`,collapsed:s.sidebar.collapsed.includes("components"),items:[],subgroups:C}),p.components=g.length,u+=g.length;}let m=Object.values(n.features||{}).filter(S=>!vt(S,s));m.length>0&&(d.push({id:"features",label:`Features (${m.length})`,collapsed:s.sidebar.collapsed.includes("features"),items:m.sort((S,x)=>S.name.localeCompare(x.name)).map(S=>({id:S.id,label:S.name,kind:"component",description:S.description}))}),p.features=m.length,u+=m.length);let y=Object.values(n.flows||{}).filter(S=>!vt(S,s)),f=new Set(y.map(S=>S.id)),b=[];if(i)for(let[S,x]of Object.entries(i.flows)){let C=S.replace(/^\$/,"");f.has(C)||b.push({id:C,label:x.name||C,kind:"flow",description:x.description});}let h=[...y.sort((S,x)=>S.name.localeCompare(x.name)).map(S=>({id:S.id,label:S.name,kind:"flow",description:S.description})),...b];h.length>0&&(d.push({id:"flows",label:`Flows (${h.length})`,collapsed:s.sidebar.collapsed.includes("flows"),items:h}),p.flows=h.length,u+=h.length);let w=Object.values(n.gates||{}).filter(S=>!vt(S,s));w.length>0&&(d.push({id:"gates",label:`Gates (${w.length})`,collapsed:s.sidebar.collapsed.includes("gates"),items:w.sort((S,x)=>S.name.localeCompare(x.name)).map(S=>({id:S.id,label:S.name,kind:"gate",description:S.description}))}),p.gates=w.length,u+=w.length);let v=Object.values(n.signals||{}).filter(S=>!vt(S,s));v.length>0&&(d.push({id:"signals",label:`Signals (${v.length})`,collapsed:s.sidebar.collapsed.includes("signals"),items:v.sort((S,x)=>S.name.localeCompare(x.name)).map(S=>({id:S.id,label:S.name,kind:"signal",description:S.description}))}),p.signals=v.length,u+=v.length);let k=Object.values(n.aspects||{}).filter(S=>!vt(S,s));k.length>0&&(d.push({id:"aspects",label:`Aspects (${k.length})`,collapsed:s.sidebar.collapsed.includes("aspects"),items:k.sort((S,x)=>S.name.localeCompare(x.name)).map(S=>({id:S.id,label:S.name,kind:"aspect",description:S.description}))}),p.aspects=k.length,u+=k.length);}if(r){let g=Object.keys(r.routes||{}).length,m=Object.keys(r.gates||{}).length;d.push({id:"portal",label:"Portal",collapsed:s.sidebar.collapsed.includes("portal"),items:[{id:"portal-overview",label:"Authorization Overview",kind:"portal",description:`${m} gates, ${g} routes`,badge:`${g} routes`}]});}return {title:l,project:c,generatedAt:new Date().toISOString(),groups:d,totalSymbols:u,symbolCounts:p}}function hl(t,e){let s=Kn(t);if(!s)return null;let n=gl(s),i=n.get(e);if(!i)return null;let r=[];for(let[f,b]of n)f!==e&&b.related&&b.related.includes(i.symbol)&&r.push(b.symbol);let o=(i.related||[]).slice(),a=[],c=yi(t);if(c)for(let[f,b]of Object.entries(c.flows)){let h=(b.steps||[]).map(w=>w.symbol);(h.includes(i.symbol)||h.includes(`#${e}`))&&a.push({id:f.replace(/^\$/,""),name:b.name||f});}if(s.flows)for(let[f,b]of Object.entries(s.flows)){if(a.some(w=>w.id===f))continue;let h=(b.steps||[]).map(w=>w.symbol).filter(Boolean);(h.includes(i.symbol)||h.includes(`#${e}`))&&a.push({id:f,name:b.name});}let l=[],d=Qn(t);if(d&&i.category==="gates"){let f=Object.keys(d.gates||{}).find(b=>b.replace(/^\^/,"")===e);f&&l.push({id:f.replace(/^\^/,""),description:d.gates[f].description});}else if(d){let f=new Set((i.related||[]).filter(b=>b.startsWith("^")));for(let[b,h]of Object.entries(d.routes||{}))for(let w of h){let v=w.replace(/^\^/,"");if(f.has(w)||f.has(`^${v}`)){let k=d.gates[w]||d.gates[`^${v}`]||d.gates[v];k&&!l.some(S=>S.id===v)&&l.push({id:v,description:k.description});}}}let p=[];if(s.aspects)for(let[f,b]of Object.entries(s.aspects))b.related&&b.related.includes(i.symbol)&&p.push(b.symbol);for(let f of i.related||[])f.startsWith("~")&&!p.includes(f)&&p.push(f);let u=[],g=pl(t);if(g)for(let f of g.entries)f.symbols.includes(i.symbol)&&u.push({id:f.id,title:f.title});let m=i.parent||void 0,y=[];if(s.components)for(let f of Object.values(s.components))f.parent===i.symbol&&y.push(f.symbol);return {id:i.id,symbol:i.symbol,name:i.name,description:i.description||"",category:i.category||"components",componentType:i.componentType,tags:i.visualTags||[],path:i.path||"",related:i.related||[],referencedBy:r,references:o,flows:a,gates:l,aspects:p,guides:u,parent:m,children:y}}function bl(t,e){let s=yi(t),n=Kn(t);if(s){let i=s.flows[`$${e}`]?`$${e}`:e,r=s.flows[i];if(r){let o=(r.steps||[]).map(c=>({type:c.type||"action",symbol:c.symbol||"",description:c.description})),a=n?.flows?.[e.replace(/^\$/,"")];return {id:e.replace(/^\$/,""),symbol:`$${e.replace(/^\$/,"")}`,name:r.name||e,description:r.description,trigger:r.trigger,steps:o,successSignal:r.successSignal,errorSignal:r.errorSignal,tags:a?.visualTags||[],path:a?.path||r.definedIn||""}}}if(n?.flows){let i=e.replace(/^\$/,""),r=n.flows[i];if(r){let o=(r.steps||[]).map(a=>({type:"action",symbol:a.symbol||"",description:a.action||a.name}));return {id:i,symbol:`$${i}`,name:r.name,description:r.description,steps:o,tags:r.visualTags||[],path:r.path||""}}}return null}function wl(t){let e=Qn(t);if(!e)return {version:"0",gates:[],routes:[]};let s=new Map;for(let[r,o]of Object.entries(e.routes||{}))for(let a of o){let c=a.replace(/^\^/,"");s.has(c)||s.set(c,[]),s.get(c).push(r);}let n=Object.entries(e.gates||{}).map(([r,o])=>{let a=r.replace(/^\^/,"");return {symbol:`^${a}`,description:o.description,check:o.check,routes:s.get(a)||[]}}),i=Object.entries(e.routes||{}).map(([r,o])=>{let a=r.indexOf(" "),c=a>0?r.substring(0,a):"GET";return {route:a>0?r.substring(a+1):r,method:c,gates:o.map(d=>{let p=d.replace(/^\^/,""),u=e.gates[d]||e.gates[`^${p}`]||e.gates[p];return {symbol:`^${p}`,description:u?.description}})}});return {version:e.version||"1.0",gates:n,routes:i}}function vl(t,e,s){let n=s||20,i=[],r=e.toLowerCase(),o=Kn(t);if(o){let d=gl(o);for(let[p,u]of d){let g=fi(u.name,u.description||"",u.visualTags||[],r);g>0&&i.push({id:u.id,kind:hg(u.category),label:u.name,description:u.description||"",matchContext:dl(u.name,u.description||"",r),score:g});}}let a=kt(t),c=ml(t,a.customContent);for(let d of c){let p=d.body.substring(0,200),u=fi(d.title,p,[],r);u>0&&i.push({id:d.slug,kind:"custom",label:d.title,description:d.description||p.substring(0,100),matchContext:dl(d.title,d.body,r),score:u});}let l=Qn(t);if(l)for(let[d,p]of Object.entries(l.gates||{})){let u=d.replace(/^\^/,""),g=fi(u,p.description,[],r);g>0&&i.push({id:u,kind:"portal",label:`^${u}`,description:p.description,score:g});}return i.sort((d,p)=>p.score-d.score||d.label.localeCompare(p.label)),i.slice(0,n)}function fi(t,e,s,n){let i=t.toLowerCase(),r=e.toLowerCase();return i===n?1:i.startsWith(n)?.8:i.includes(n)?.6:r.includes(n)?.5:s.some(o=>o.toLowerCase().includes(n))?.3:0}function dl(t,e,s){let i=e.toLowerCase().indexOf(s);if(i<0)return t.toLowerCase().includes(s)?t:void 0;let r=Math.max(0,i-40),o=Math.min(e.length,i+s.length+40),a=e.substring(r,o).trim();return r>0&&(a=`...${a}`),o<e.length&&(a=`${a}...`),a}function kl(){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 Sl(t,e,s){if(t==="paradigm_docs_manifest"){let n=kt(s.rootDir),i=yl(s.rootDir,n),r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}if(t==="paradigm_docs_page"){if(e.portal){let i=wl(s.rootDir),r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}if(e.flow){let i=e.flow,r=bl(s.rootDir,i);if(!r){let a=JSON.stringify({error:`Flow "${i}" not found`});return o(a.length,t),{handled:true,text:a}}let o$1=JSON.stringify(r,null,2);return o(o$1.length,t),{handled:true,text:o$1}}if(e.slug){let i=kt(s.rootDir),r=fl(s.rootDir,e.slug,i);if(!r){let a=JSON.stringify({error:`Page "${e.slug}" not found`});return o(a.length,t),{handled:true,text:a}}let o$1=JSON.stringify(r,null,2);return o(o$1.length,t),{handled:true,text:o$1}}if(e.symbol){let i=hl(s.rootDir,e.symbol);if(!i){let o$1=JSON.stringify({error:`Symbol "${e.symbol}" not found`});return o(o$1.length,t),{handled:true,text:o$1}}let r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}let n=JSON.stringify({error:"Provide one of: symbol, flow, portal, or slug"});return o(n.length,t),{handled:true,text:n}}if(t==="paradigm_docs_search"){let n=e.query;if(!n)return {handled:true,text:JSON.stringify({error:"query is required"})};let i=vl(s.rootDir,n,e.limit),r=JSON.stringify({count:i.length,results:i},null,2);return o(r.length,t),{handled:true,text:r}}return {handled:false,text:""}}g();e();function _l(){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 xl(t,e,s){let n=i=>JSON.stringify(i,null,2);switch(t){case "paradigm_work_log_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.summary,i,"work_log"),o=a$5(s.rootDir,{agent:e.agent,summary:r,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:n({recorded:true,id:o.id,timestamp:o.timestamp}),handled:true}}case "paradigm_work_log_search":{if(e.summary){let r=d$5(s.rootDir,7);return {text:n(r),handled:true}}let i=b$6(s.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:n({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,summary:r.summary,outcome:r.outcome,timestamp:r.timestamp,symbols_touched:r.symbols_touched,task_ref:r.task_ref}))}),handled:true}}case "paradigm_journal_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.insight,i,"learning_journal"),o=a$4(e.agent,{trigger:e.trigger,insight:r,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:n({recorded:true,id:o.id,agent:o.agent,timestamp:o.timestamp}),handled:true}}case "paradigm_journal_search":{if(e.stats&&e.agent){let r=e$4(e.agent);return {text:n(r),handled:true}}let i=e.agent?b$5(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$4({trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,trigger:r.trigger,insight:r.insight.slice(0,200),project:r.project,transferable:r.transferable,timestamp:r.timestamp}))}),handled:true}}case "paradigm_decision_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.decision,i,"team_decisions"),{filtered:o}=d$3(e.rationale,i,"team_decisions"),a=a$2(s.rootDir,{title:e.title,decision:r,rationale:o,participants:e.participants,alternatives_considered:e.alternatives_considered,symbols_affected:e.symbols_affected,status:e.status||"active",tags:e.tags}),c=d$1(s.rootDir,a.id);return {text:n({recorded:true,id:a.id,title:a.title,timestamp:a.timestamp,...c?{companion_lore_id:c}:{}}),handled:true}}case "paradigm_decision_search":{if(e.summary){let r=h$4(s.rootDir);return {text:n(r),handled:true}}let i=e$3(s.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:n({count:i.length,entries:i.map(r=>({id:r.id,title:r.title,status:r.status,decision:r.decision.slice(0,200),participants:r.participants.map(o=>`${o.id} (${o.stance})`),symbols_affected:r.symbols_affected,timestamp:r.timestamp}))}),handled:true}}default:return {text:`Unknown streams tool: ${t}`,handled:false}}}v();b$2();z();g();q();function Cl(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function bg(t){let e=Date.now(),s=t.match(/^(\d+)(m|h|d)$/);if(s){let n=parseInt(s[1],10),i=s[2],r=i==="m"?n*6e4:i==="h"?n*36e5:n*864e5;return new Date(e-r).toISOString()}return t}async function Rl(t,e,s){let n=i=>JSON.stringify(i,null,2);switch(t){case "paradigm_ambient_nominations":{m$1(s.rootDir);let r=e.pending_only!==false,o=e.limit||20,a=i$2(s.rootDir,{agent:e.agent,urgency:e.urgency,pending_only:r,limit:o+20}),c=t$1(s.rootDir);a=u$1(a,c).slice(0,o);let l=H.join(s.rootDir,".paradigm/events/nominations.jsonl");if(E.existsSync(l))try{let p=E.readFileSync(l,"utf8"),u=new Set(a.map(m=>m.id)),g=p.trim().split(`
591
+ `).map(m=>{try{let y=JSON.parse(m);return u.has(y.id)?(y.surfaced=!0,JSON.stringify(y)):m}catch{return m}});E.writeFileSync(l,g.join(`
508
592
  `)+`
509
- `,"utf8");}catch{}let d={count:a.length,nominations:a.map(p=>({id:p.id,agent:p.agent,urgency:p.urgency,type:p.type,brief:p.brief,relevance:p.relevance,timestamp:p.timestamp,engaged:p.engaged,response:p.response}))};if(e.include_debates){let u=j$3(s.rootDir).filter(m=>!m.resolution);d.debates=u.map(m=>({id:m.id,topic:m.topic,type:m.type,nominations:m.nominations})),d.debate_count=u.length;}return {text:n(d),handled:true}}case "paradigm_ambient_events":{let i=e.since?tg(e.since):void 0,r=e.limit||50,o=a$6(s.rootDir,{type:e.type,source:e.source,symbol:e.symbol,agent:e.agent,since:i,limit:r});return {text:n({count:o.length,events:o.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i=e.nomination_id,r=e.response,o=e.reason,a=k$1(s.rootDir,i,r,o);if(a)try{let{appendSessionWorkEntry:l,appendVerdictEntry:d}=await import('./session-work-log-EE4UIZ33.js'),u=i$2(s.rootDir,{limit:500}).find(g=>g.id===i),m={timestamp:new Date().toISOString(),type:"user-verdict",agent:u?.agent,nominationId:i,verdict:r,reason:o};l(s.rootDir,m),d(s.rootDir,m);}catch{}let c=false;return e.resolve_debate&&a&&(c=l$1(s.rootDir,e.resolve_debate,i,e.reason)),{text:n({engaged:a,nomination_id:i,response:r,debate_resolved:c||void 0}),handled:true}}case "paradigm_context_compose":{let i=e.agent,r=e.symbols||[],o=e.include_nominations!==false,a=e.include_decisions!==false,c=e.include_journal!==false,l=e.max_decisions||5,d=e.max_journal||5,p=f$2(s.rootDir,i);if(!p)return {text:n({error:`Agent profile not found: ${i}`}),handled:true};let u=[],m=p$1(p,r);if(m.trim()&&u.push(m),a){let g=e$3(s.rootDir,{status:"active",limit:l});if(g.length>0){u.push("## Recent Team Decisions");for(let y of g)u.push(`- **${y.title}**: ${y.decision.slice(0,150)}${y.decision.length>150?"...":""}`);u.push("");}}if(c){let g=b$5(i,{transferable:true,limit:d});if(g.length>0){u.push("## Transferable Insights");for(let y of g)u.push(`- [${y.trigger}] ${y.insight.slice(0,150)}${y.insight.length>150?"...":""}`);u.push("");}}if(o){let g=i$2(s.rootDir,{pending_only:true,limit:10});if(g.length>0){u.push("## Pending Nominations");for(let y of g)u.push(`- [${y.urgency}] ${y.brief}`);u.push("");}}return {text:n({agent:i,context:u.join(`
510
- `),sections_included:{profile:true,decisions:a,journal:c,nominations:o}}),handled:true}}case "paradigm_ambient_promote":{let i=e.agent,r=s$1(s.rootDir,i);return {text:n({agent:i,promoted:r.promoted,entries:r.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e.agent,r=e.dry_run===true,o=p(s.rootDir,i);if(r)return {text:n({agent:i,dry_run:true,stats:o,note:o.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(o.acceptRate*100).toFixed(0)}% \u2014 ${o.acceptRate>.8?"would lower threshold":o.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=o$1(s.rootDir,i);return {text:n({agent:i,...a,stats:o}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let i=q$2(s.rootDir);return {text:n(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:n(await ig(s.rootDir,e)),handled:true};default:return {text:`Unknown ambient tool: ${t}`,handled:false}}}var ng={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function sg(t){try{let e=H.join(t,".paradigm","config.yaml");if(E.existsSync(e)){let n=E.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(n)return n[1].trim()}}catch{}return H.basename(t)}async function ig(t,e={}){let s=e.dry_run===true,n=sg(t),i=e$8(t).filter(g=>g.verdict&&g.agent),r=b$a(t);if(i.length===0)return {sessionEntries:r.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:s,details:[]};let o=new Map;for(let g of i){let y=g.agent;o.has(y)||o.set(y,[]),o.get(y).push(g);}let a=r.filter(g=>g.type==="agent-contribution"),c=new Map;for(let g of a)g.agent&&(c.has(g.agent)||c.set(g.agent,[]),c.get(g.agent).push(g));let l=[],d={},p=0;for(let[g,y]of o){d[g]=0;let f=y.filter(k=>k.verdict==="accepted").length;y.filter(k=>k.verdict==="dismissed").length;y.filter(k=>k.verdict==="revised").length;let w=y.length,v=w>0?f/w:0;for(let k of y){let _=ng[k.verdict];if(!_)continue;let x=c.get(g)?.shift(),C=rg(k,x,{acceptRate:v,total:w,accepted:f}),S=k.verdict==="accepted"?.85:k.verdict==="revised"?.6:.4,R={agent:g,verdict:k.verdict,trigger:_,insight:C,symbols:k.symbols};if(l.push(R),s)d[g]++,p++;else try{a$4(g,{trigger:_,insight:C,confidence_before:k.verdict==="accepted"?.7:.8,confidence_after:S,project:n,transferable:k.verdict==="dismissed",tags:["postflight",`verdict:${k.verdict}`,...(k.symbols||[]).map(I=>`symbol:${I}`)]}),d[g]++,p++;}catch{}}}let u={},m=0;if(!s)for(let g of o.keys())try{let y=s$1(t,g);y.promoted>0&&(u[g]=y.promoted,m+=y.promoted);}catch{}return !s&&i.length>0&&f$4(t,i.map(g=>g.nominationId).filter(Boolean)),{sessionEntries:r.length,agentsProcessed:Array.from(o.keys()),journalsWritten:p,journalsByAgent:d,promoted:m,promotedByAgent:u,dryRun:s,details:l}}function rg(t,e,s){let n=t.symbols?.length?` (symbols: ${t.symbols.join(", ")})`:"",i=t.reason?` Reason: ${t.reason}.`:"";switch(t.verdict){case "accepted":return `Contribution accepted by user${n}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;case "dismissed":return `Contribution dismissed by user${n}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;case "revised":return `Contribution revised by user${n}.${i}`+(t.revisionDelta?` Delta: "${t.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;default:return `Unknown verdict "${t.verdict}"${n}.${i}`}}var zt=["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"],pl={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"}};function zn(t){let e=H.join(t,".paradigm","config.yaml");if(!E.existsSync(e))return {};try{return Te.load(E.readFileSync(e,"utf8"))||{}}catch{return {}}}function ui(t,e){let s=H.join(t,".paradigm","config.yaml");E.writeFileSync(s,Te.dump(e,{lineWidth:120,noRefs:true}),"utf8");}function Yn(t){let e=t.enforcement?.level||"minimal",s=pl[e]||pl.minimal,n=t.enforcement?.checks||{},i=t.enforcement?.orchestration?.threshold??3,r={...s};for(let[o,a]of Object.entries(n))zt.includes(o)&&ul(a)&&(r[o]=a);return r.orchestrationThreshold=i,r}function ul(t){return t==="block"||t==="warn"||t==="off"}function og(t){return t==="strict"||t==="balanced"||t==="minimal"}function ag(t){return zt.includes(t)}var cg=[{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"],description:"Enforcement preset level (for set-level action)."},checkId:{type:"string",description:"Check ID to override (for override action). One of: "+zt.join(", ")},severity:{type:"string",enum:["block","warn","off"],description:"Severity to set for the check (for override action)."}},required:["action"]}}];async function lg(t,e){let{action:s,level:n,checkId:i,severity:r}=e;switch(s){case "status":{let o=zn(t.rootDir),a=Yn(o),c=o.enforcement?.level||"minimal",l=o.enforcement?.checks||{},d=o.enforcement?.orchestration?.threshold??3;return JSON.stringify({level:c,orchestrationThreshold:d,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(l).length>0?l:void 0,effective:a,checkIds:[...zt],presetLevels:["strict","balanced","minimal"]},null,2)}case "set-level":{if(!n||!og(n))return JSON.stringify({error:`Invalid level "${n}". Must be one of: strict, balanced, minimal`});let o=zn(t.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.level=n,o.enforcement.checks={},ui(t.rootDir,o);let a=Yn(o);return JSON.stringify({success:true,level:n,message:`Enforcement level set to "${n}". Per-check overrides cleared.`,effective:a},null,2)}case "override":{if(!i||!ag(i))return JSON.stringify({error:`Invalid checkId "${i}". Must be one of: ${zt.join(", ")}`});if(!r||!ul(r))return JSON.stringify({error:`Invalid severity "${r}". Must be one of: block, warn, off`});let o=zn(t.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.checks||(o.enforcement.checks={}),o.enforcement.checks[i]=r,ui(t.rootDir,o);let a=Yn(o);return JSON.stringify({success:true,checkId:i,severity:r,message:`Override set: ${i} = ${r}`,effective:a},null,2)}case "reset":{let o=zn(t.rootDir);o.enforcement&&(o.enforcement.checks={}),ui(t.rootDir,o);let a=Yn(o),c=o.enforcement?.level||"minimal";return JSON.stringify({success:true,message:`All per-check overrides cleared. Preset "${c}" is now fully in effect.`,effective:a},null,2)}default:return JSON.stringify({error:`Unknown action "${s}". Must be one of: status, set-level, override, reset`})}}function gl(){return cg}async function ml(t,e,s){if(t==="paradigm_enforcement_configure"){let n=await lg(s,e);return o(n.length,"paradigm_enforcement_configure"),{handled:true,text:n}}return {handled:false,text:""}}function dg(t,e){let s=[];for(let n=0;n<=e.length;n++)s[n]=[n];for(let n=0;n<=t.length;n++)s[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=t.length;i++)e.charAt(n-1)===t.charAt(i-1)?s[n][i]=s[n-1][i-1]:s[n][i]=Math.min(s[n-1][i-1]+1,s[n][i-1]+1,s[n-1][i]+1);return s[e.length][t.length]}function fl(t,e,s={}){let{maxDistance:n=3,maxResults:i=5}=s,r=t.toLowerCase(),o=[];for(let a of e){let c=a.toLowerCase();if(c===r){o.push({match:a,distance:0});continue}if(c.includes(r)||r.includes(c)){o.push({match:a,distance:1});continue}let l=dg(r,c);l<=n&&o.push({match:a,distance:l});}return o.sort((a,c)=>a.distance!==c.distance?a.distance-c.distance:a.match.localeCompare(c.match)),o.slice(0,i)}v();function gg(t,e){let s$1=new u(t),n=e||(async()=>{}),i=o=>async(a,c,l)=>o(a,c,l),r$1=o=>async(a,c,l)=>o(a,c,l,n);return s$1.registerAll([{key:"context",tier:"core",getToolsList:r,handleTool:i(s)},{key:"navigate",tier:"core",getToolsList:Ho,handleTool:i(bn)},{key:"tags",tier:"core",getToolsList:wa,handleTool:i(va)},{key:"purpose-portal",tier:"core",getToolsList:Pa,handleTool:r$1(ja)},{key:"pm",tier:"core",getToolsList:Ja,handleTool:i(Ua)},{key:"reindex",tier:"core",getToolsList:qa$1,handleTool:r$1(ra$1)},{key:"docs",tier:"core",getToolsList:rl,handleTool:i(ol)},{key:"ripple",tier:"core",getToolsList:Qo,handleTool:i(Pn)},{key:"captain",tier:"core",getToolsList:ca,handleTool:i(jt)}]),s$1.registerAll([{key:"wisdom",tier:"feature",getToolsList:To,handleTool:i(yn)},{key:"history",tier:"feature",getToolsList:Do,handleTool:i(Ao)},{key:"lore",tier:"feature",getToolsList:oa,handleTool:i(Pt)},{key:"streams",tier:"feature",getToolsList:al,handleTool:i(cl)},{key:"ambient",tier:"feature",getToolsList:ll,handleTool:i(dl)},{key:"sentinel",tier:"feature",getToolsList:qo,handleTool:i(Lo)},{key:"flows",tier:"feature",getToolsList:Wo,handleTool:i(Go)},{key:"fixtures",tier:"feature",getToolsList:Yo,handleTool:i(Vo)},{key:"orchestration",tier:"feature",getToolsList:ga,handleTool:i(ma)},{key:"habits",tier:"feature",getToolsList:za,handleTool:i(Ya)},{key:"tasks",tier:"feature",getToolsList:ac,handleTool:i(cc)},{key:"personas",tier:"feature",getToolsList:bc,handleTool:i(wc)},{key:"protocols",tier:"feature",getToolsList:Xo,handleTool:i(jn)},{key:"symphony",tier:"feature",getToolsList:Fc,handleTool:i(Nc)},{key:"university",tier:"feature",getToolsList:Lc,handleTool:i(Mc)},{key:"agents",tier:"feature",getToolsList:Jc,handleTool:i(Uc)},{key:"notebooks",tier:"feature",getToolsList:Bc,handleTool:i(zc)},{key:"aspect-graph",tier:"feature",getToolsList:rc,handleTool:i(oc)},{key:"enforcement",tier:"feature",getToolsList:gl,handleTool:i(ml),detect:o=>E.existsSync(H.join(o,".paradigm","config.yaml"))},{key:"graph",tier:"feature",getToolsList:_c,handleTool:i(Sc),detect:o=>E.existsSync(H.join(o,".paradigm","aspect-graph.db"))}]),s$1.registerAll([{key:"conductor",tier:"advanced",getToolsList:Oc,handleTool:i(Ic)},{key:"platform",tier:"advanced",getToolsList:Wc,handleTool:i(Gc)},{key:"pipeline",tier:"advanced",getToolsList:Pc,handleTool:i(jc)},{key:"graduation",tier:"advanced",getToolsList:Xa,handleTool:i(Za)}]),s$1}function mg(t,e){let s=m=>m.toLowerCase().replace(/\/+$/,""),n=s(t),i=s(e);if(n===i)return 1;let r=m=>!m.includes("/")&&m.includes("."),o=m=>r(m)?m.split("."):m.split("/").filter(Boolean),a=o(n),c=o(i);if(r(n)||r(i)){let m=r(n)?n.split("."):n.split("/").filter(Boolean),g=r(i)?i.split("."):i.split("/").filter(Boolean),y=0;for(let f=0;f<Math.min(m.length,g.length)&&m[f]===g[f];f++)y++;return y>0?Math.min(1,.5+y/Math.max(m.length,g.length)*.5):0}let l=0,d=Math.max(a.length,c.length);for(let m=0;m<d;m++){let g=a[m]||"",y=c[m]||"";g===y?l++:g.startsWith(":")&&y.startsWith(":")?l+=.9:g.startsWith(":")||y.startsWith(":")?l+=.7:(g.replace(/s$/,"")===y.replace(/s$/,"")||y.replace(/s$/,"")===g.replace(/s$/,""))&&(l+=.8);}let p=l/d,u=a.length===c.length?.1:0;return Math.min(1,p+u)}function fg(){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 - call this at session start for orientation. Shows symbol counts, project health, and available features. Returns symbol counts by type, project health score, and feature flags. ~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 Vh(t$1,e,s){let n$2=e(),i$1=gg(n$2.rootDir,s);t$1.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[...fg(),...i$1.getActiveTools()]})),t$1.setRequestHandler(CallToolRequestSchema,async r=>{let{name:o$1,arguments:a}=r.params;q$1(o$1,a??{});let c=e(),l$1=j$1();l$1.setRootDir(c.rootDir);let d=null,p=null;l$1.hasRecoveredThisSession()||(d=await t(c.rootDir),p=a$1(),b$3(),l$1.markRecovered());let u=await(async()=>{switch(o$1){case "paradigm_search":{let{query:m,type:g,limit:y=10,fuzzy:f=true,includeWorkspace:b=false,componentType:h,response_format:w}=a,v=`search:${m}:${g||""}:${y}:${f}:${b}:${h||""}`,k=await v$1.getOrCompute(v,()=>{let S=j$2(c.index,m);return g&&(S=S.filter(R=>R.type===g)),h&&(S=S.filter(R=>R.componentType===h)),S}),_=[];if(k.length===0&&f){let S=n$1(c.index),R=S.map(I=>I.symbol);_=fl(m,R,{maxDistance:3,maxResults:5}),_.length>0&&(k=_.map(I=>S.find(P=>P.symbol===I.match)).filter(I=>I!=null),g&&(k=k.filter(I=>I.type===g)));}k=k.slice(0,y);let x={query:m,count:k.length,results:k.map(S=>({symbol:S.symbol,type:S.type,description:S.description,filePath:S.filePath,...S.componentType?{componentType:S.componentType}:{},...S.parentSymbol?{parentSymbol:S.parentSymbol}:{}}))};if(_.length>0&&(x.fuzzyMatched=true,x.fuzzyNote=`No exact matches for "${m}". Showing similar symbols.`,x.suggestions=_.map(S=>({symbol:S.match,distance:S.distance}))),b&&c.workspace){let S=xt(c.workspace,m),R=g?S.filter(I=>I.type===g):S;R.length>0&&(x.workspaceResults=R.slice(0,y).map(I=>({symbol:I.symbol,type:I.type,description:I.description,filePath:I.filePath,project:I.project})),x.workspaceCount=R.length);}w==="concise"&&(x.results=k.map(S=>({symbol:S.symbol,type:S.type})),delete x.fuzzyMatched,delete x.fuzzyNote,delete x.suggestions,delete x.workspaceResults,delete x.workspaceCount);let C=JSON.stringify(x,null,2);return o(C.length,o$1),{content:[{type:"text",text:C}]}}case "paradigm_related":{let{symbol:m}=a,g=h$1(c.index,m);if(!g){let h=Rn(c.rootDir,m,{maxResults:20});if(h.length===0){let x=JSON.stringify({error:"Symbol not found",symbol:m,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 o(x.length,o$1),{content:[{type:"text",text:x}]}}let w=[...new Set(h.map(x=>x.filePath))],v=h.filter(x=>x.context==="purpose"),k=h.filter(x=>x.context==="code"),_=JSON.stringify({symbol:m,status:"not-indexed",fallback:"grep-search",note:"Approximate relationships from grep \u2014 run `paradigm scan` for accurate graph data.",usedBy:w.slice(0,10).map(x=>({file:x,references:h.filter(C=>C.filePath===x).length})),uses:[],summary:{totalFiles:w.length,totalReferences:h.length,purposeFileRefs:v.length,codeRefs:k.length},suggestion:"Run `paradigm scan` to enable full relationship tracking"},null,2);return o(_.length,o$1),{content:[{type:"text",text:_}]}}let y=k(c.index,m),f=l(c.index,m),b=JSON.stringify({symbol:g.symbol,type:g.type,description:g.description,usedBy:y.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 o(b.length,o$1),{content:[{type:"text",text:b}]}}case "paradigm_status":{let m$1=a.response_format,g=await v$1.getOrCompute("status",async()=>{let f=m(c.index),b=Object.values(f).reduce((D,j)=>D+j,0),h={};for(let D of Object.keys(f)){let j=i(c.index,D);h[D]=j.slice(0,3).map(T=>T.symbol);}let w=ra.platform(),v=w==="win32",k=v?"PowerShell/CMD":w==="darwin"?"zsh/bash":"bash",_;try{let D=await $(c.rootDir);D&&D.health.total>0&&(_=D.health);}catch{}let x=i(c.index,"component"),C={};for(let D of x)D.componentType&&(C[D.componentType]=(C[D.componentType]||0)+1);let S=x.filter(D=>!D.componentType).length,R;try{let{checkPurposeHealth:D}=await import('./integrity-checker-DHGMZQDG.js');R=D(c.aggregation.purposeFiles,c.rootDir).healthScore;}catch{}let I;try{let{countNotebookReferences:D}=await import('./session-work-log-EE4UIZ33.js'),j=D(c.rootDir);j>0&&(I=j);}catch{}let P;try{let{getComplianceTrend:D,getHealthDot:j}=await import('./compliance-health-JNP3P35P.js'),T=D(c.rootDir);T&&(P={trend:T,dot:j(T,c.rootDir)});}catch{}return JSON.stringify({project:c.projectName,symbolSystem:"v2",counts:{"# components":f.component,"$ flows":f.flow,"^ gates":f.gate,"! signals":f.signal,"~ aspects":f.aspect},total:b,...Object.keys(C).length>0?{componentTypes:{...C,...S>0?{"(untyped)":S}:{}}}:{},examples:h,hasPortalYaml:c.gateConfig!==null,purposeFiles:c.aggregation.purposeFiles.length,...R!==void 0?{purposeHealthScore:R}:{},..._?{protocols:_}:{},...I!==void 0?{notebookReferences:I}:{},...P?{complianceHealth:P}:{},note:"Symbol System v2: Use tags [feature], [state], [integration], [idea] for classification. Use type field for structural role (view, service, tool, etc.)",environment:{os:w,shell:k,terminalNote:v?"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=g;if(m$1==="concise")try{let f=JSON.parse(g);y=JSON.stringify({project:f.project,counts:f.counts,total:f.total},null,2);}catch{}return o(y.length,o$1),{content:[{type:"text",text:y}]}}case "paradigm_gates_for_route":{let{route:m,response_format:g}=a,f=typeof m=="string"&&!m.includes("/")&&m.includes(".")?"POST":a.method||"GET",b=i(c.index,"gate"),h=[],w=[];if(c.gateConfig?.routes)for(let[P,D]of Object.entries(c.gateConfig.routes))D.gates&&w.push({route:P,gates:D.gates,method:D.method});if(c.workspace)for(let[P,D]of c.workspace.siblingIndices){let j=D.gateConfig;if(j?.routes)for(let[T,O]of Object.entries(j.routes)){let $=O,F=Array.isArray($)?$:$?.gates;F&&w.push({route:T,gates:F,method:Array.isArray($)?void 0:$?.method,source:P});}}for(let P of w){let D=mg(m,P.route);if(D>=.6&&(!P.method||P.method===f))for(let j of P.gates){let T=b.find(O=>O.symbol===j||O.symbol===`^${j}`);if(T&&!h.find(O=>O.gate===T.symbol)){let O=P.source?`${P.source}/portal.yaml`:"portal.yaml";h.push({gate:T.symbol,reason:`Similar route "${P.route}" uses this gate`,confidence:D>=.8?"high":"medium",source:O});}}}let _=m.split("/").filter(Boolean).find(P=>!P.startsWith(":")&&P!=="api")?.replace(/s$/,"")||"",x=m.match(/\/:(id|[a-z]+Id)($|\/)/i);if(x&&_){let P=b.find(D=>{let j=D.symbol.toLowerCase(),T=(D.description||"").toLowerCase();return j.includes(`${_}-owner`)||j.includes("owner")||j.includes("ownership")||T.includes("owner")||T.includes("ownership")||T.includes("belongs to")});P?h.push({gate:P.symbol,reason:`Resource ID route (${_}) typically needs ownership verification`,confidence:"high"}):h.push({gate:`^${_}-owner`,reason:`Consider adding ownership gate for ${_} resource`,confidence:"medium"});}if(m.includes("/admin")||m.includes("/settings")){let P=b.find(D=>D.symbol.includes("admin")||D.description?.toLowerCase().includes("admin"));P&&h.push({gate:P.symbol,reason:"Route appears to be admin-related",confidence:"high"});}if(m.startsWith("/api/")||m.includes("/user")||m.includes("/account")){let P=b.find(D=>D.symbol.includes("authenticated")||D.symbol.includes("auth"));P&&h.push({gate:P.symbol,reason:"API/user routes typically require authentication",confidence:"high"});}if(m.includes("/premium")||m.includes("/pro")||m.includes("/export")){let P=b.find(D=>D.symbol.includes("subscription")||D.symbol.includes("premium"));P&&h.push({gate:P.symbol,reason:"Route appears to be a premium feature",confidence:"medium"});}if(f==="DELETE"){let P=b.find(D=>D.symbol.includes("authenticated"));P&&!h.find(D=>D.gate===P.symbol)&&h.push({gate:P.symbol,reason:"DELETE operations require authentication",confidence:"high"});}if(["POST","PUT","PATCH"].includes(f)){let P=b.find(D=>D.symbol.includes("authenticated"));P&&!h.find(D=>D.gate===P.symbol)&&h.push({gate:P.symbol,reason:"Write operations typically require authentication",confidence:"high"});}let C=new Set,S=h.filter(P=>C.has(P.gate)?false:(C.add(P.gate),true)),R=g==="concise"?{suggestions:S.map(P=>({gate:P.gate,confidence:P.confidence}))}:{route:m,method:f,suggestions:S,availableGates:b.map(P=>({symbol:P.symbol,description:P.description})),note:x?"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(R,null,2);o(I.length,o$1);try{n(c.rootDir,{type:"gate-checked",source:"mcp-tool-call",tool:"paradigm_gates_for_route",symbols:S.map(P=>P.gate),context:`Gate check for ${f} ${m}`});}catch{}return {content:[{type:"text",text:I}]}}case "paradigm_plugin_check":{let{runPluginUpdateCheck:m}=await import('./plugin-update-checker-M7PW434O.js'),g=await m(),y=g.filter(w=>w.hasRemoteUpdate||w.hasCacheStale);if(y.length===0){let w=g.length===0?"No Claude Code plugins found in ~/.claude/plugins/marketplaces/.":"All installed plugins are up to date.";return o(w.length,o$1),{content:[{type:"text",text:w}]}}let f=[`Plugin updates available:
593
+ `,"utf8");}catch{}let d={count:a.length,nominations:a.map(p=>({id:p.id,agent:p.agent,urgency:p.urgency,type:p.type,brief:p.brief,relevance:p.relevance,timestamp:p.timestamp,engaged:p.engaged,response:p.response}))};if(e.include_debates){let u=j$3(s.rootDir).filter(g=>!g.resolution);d.debates=u.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),d.debate_count=u.length;}return {text:n(d),handled:true}}case "paradigm_ambient_events":{let i=e.since?bg(e.since):void 0,r=e.limit||50,o=a$6(s.rootDir,{type:e.type,source:e.source,symbol:e.symbol,agent:e.agent,since:i,limit:r});return {text:n({count:o.length,events:o.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i=e.nomination_id,r=e.response,o=e.reason,a=k$1(s.rootDir,i,r,o);if(a)try{let{appendSessionWorkEntry:l,appendVerdictEntry:d}=await import('./session-work-log-MEJ33TYD.js'),u=i$2(s.rootDir,{limit:500}).find(m=>m.id===i),g={timestamp:new Date().toISOString(),type:"user-verdict",agent:u?.agent,nominationId:i,verdict:r,reason:o};l(s.rootDir,g),d(s.rootDir,g);}catch{}let c=false;return e.resolve_debate&&a&&(c=l$1(s.rootDir,e.resolve_debate,i,e.reason)),{text:n({engaged:a,nomination_id:i,response:r,debate_resolved:c||void 0}),handled:true}}case "paradigm_context_compose":{let i=e.agent,r=e.symbols||[],o=e.include_nominations!==false,a=e.include_decisions!==false,c=e.include_journal!==false,l=e.max_decisions||5,d=e.max_journal||5,p=f$2(s.rootDir,i);if(!p)return {text:n({error:`Agent profile not found: ${i}`}),handled:true};let u=[],g=p$1(p,r);if(g.trim()&&u.push(g),a){let m=e$3(s.rootDir,{status:"active",limit:l});if(m.length>0){u.push("## Recent Team Decisions");for(let y of m)u.push(`- **${y.title}**: ${y.decision.slice(0,150)}${y.decision.length>150?"...":""}`);u.push("");}}if(c){let m=b$5(i,{transferable:true,limit:d});if(m.length>0){u.push("## Transferable Insights");for(let y of m)u.push(`- [${y.trigger}] ${y.insight.slice(0,150)}${y.insight.length>150?"...":""}`);u.push("");}}if(o){let m=i$2(s.rootDir,{pending_only:true,limit:10});if(m.length>0){u.push("## Pending Nominations");for(let y of m)u.push(`- [${y.urgency}] ${y.brief}`);u.push("");}}return {text:n({agent:i,context:u.join(`
594
+ `),sections_included:{profile:true,decisions:a,journal:c,nominations:o}}),handled:true}}case "paradigm_ambient_promote":{let i=e.agent,r=s$1(s.rootDir,i);return {text:n({agent:i,promoted:r.promoted,entries:r.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e.agent,r=e.dry_run===true,o=p(s.rootDir,i);if(r)return {text:n({agent:i,dry_run:true,stats:o,note:o.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(o.acceptRate*100).toFixed(0)}% \u2014 ${o.acceptRate>.8?"would lower threshold":o.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=o$1(s.rootDir,i);return {text:n({agent:i,...a,stats:o}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let i=q$2(s.rootDir);return {text:n(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:n(await kg(s.rootDir,e)),handled:true};default:return {text:`Unknown ambient tool: ${t}`,handled:false}}}var wg={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function vg(t){try{let e=H.join(t,".paradigm","config.yaml");if(E.existsSync(e)){let n=E.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(n)return n[1].trim()}}catch{}return H.basename(t)}async function kg(t,e={}){let s=e.dry_run===true,n=vg(t),i=e$8(t).filter(m=>m.verdict&&m.agent),r=b$a(t);if(i.length===0)return {sessionEntries:r.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:s,details:[]};let o=new Map;for(let m of i){let y=m.agent;o.has(y)||o.set(y,[]),o.get(y).push(m);}let a=r.filter(m=>m.type==="agent-contribution"),c=new Map;for(let m of a)m.agent&&(c.has(m.agent)||c.set(m.agent,[]),c.get(m.agent).push(m));let l=[],d={},p=0;for(let[m,y]of o){d[m]=0;let f=y.filter(k=>k.verdict==="accepted").length;y.filter(k=>k.verdict==="dismissed").length;y.filter(k=>k.verdict==="revised").length;let w=y.length,v=w>0?f/w:0;for(let k of y){let S=wg[k.verdict];if(!S)continue;let x=c.get(m)?.shift(),C=Sg(k,x,{acceptRate:v,total:w,accepted:f}),_=k.verdict==="accepted"?.85:k.verdict==="revised"?.6:.4,R={agent:m,verdict:k.verdict,trigger:S,insight:C,symbols:k.symbols};if(l.push(R),s)d[m]++,p++;else try{a$4(m,{trigger:S,insight:C,confidence_before:k.verdict==="accepted"?.7:.8,confidence_after:_,project:n,transferable:k.verdict==="dismissed",tags:["postflight",`verdict:${k.verdict}`,...(k.symbols||[]).map(I=>`symbol:${I}`)]}),d[m]++,p++;}catch{}}}let u={},g=0;if(!s)for(let m of o.keys())try{let y=s$1(t,m);y.promoted>0&&(u[m]=y.promoted,g+=y.promoted);}catch{}return !s&&i.length>0&&f$4(t,i.map(m=>m.nominationId).filter(Boolean)),{sessionEntries:r.length,agentsProcessed:Array.from(o.keys()),journalsWritten:p,journalsByAgent:d,promoted:g,promotedByAgent:u,dryRun:s,details:l}}function Sg(t,e,s){let n=t.symbols?.length?` (symbols: ${t.symbols.join(", ")})`:"",i=t.reason?` Reason: ${t.reason}.`:"";switch(t.verdict){case "accepted":return `Contribution accepted by user${n}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;case "dismissed":return `Contribution dismissed by user${n}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;case "revised":return `Contribution revised by user${n}.${i}`+(t.revisionDelta?` Delta: "${t.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;default:return `Unknown verdict "${t.verdict}"${n}.${i}`}}var Kt=["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"],Pl={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"}};function Xn(t){let e=H.join(t,".paradigm","config.yaml");if(!E.existsSync(e))return {};try{return Ae.load(E.readFileSync(e,"utf8"))||{}}catch{return {}}}function hi(t,e){let s=H.join(t,".paradigm","config.yaml");E.writeFileSync(s,Ae.dump(e,{lineWidth:120,noRefs:true}),"utf8");}function Zn(t){let e=t.enforcement?.level||"minimal",s=Pl[e]||Pl.minimal,n=t.enforcement?.checks||{},i=t.enforcement?.orchestration?.threshold??3,r={...s};for(let[o,a]of Object.entries(n))Kt.includes(o)&&jl(a)&&(r[o]=a);return r.orchestrationThreshold=i,r}function jl(t){return t==="block"||t==="warn"||t==="off"}function _g(t){return t==="strict"||t==="balanced"||t==="minimal"}function xg(t){return Kt.includes(t)}var Cg=[{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"],description:"Enforcement preset level (for set-level action)."},checkId:{type:"string",description:"Check ID to override (for override action). One of: "+Kt.join(", ")},severity:{type:"string",enum:["block","warn","off"],description:"Severity to set for the check (for override action)."}},required:["action"]}}];async function Rg(t,e){let{action:s,level:n,checkId:i,severity:r}=e;switch(s){case "status":{let o=Xn(t.rootDir),a=Zn(o),c=o.enforcement?.level||"minimal",l=o.enforcement?.checks||{},d=o.enforcement?.orchestration?.threshold??3;return JSON.stringify({level:c,orchestrationThreshold:d,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(l).length>0?l:void 0,effective:a,checkIds:[...Kt],presetLevels:["strict","balanced","minimal"]},null,2)}case "set-level":{if(!n||!_g(n))return JSON.stringify({error:`Invalid level "${n}". Must be one of: strict, balanced, minimal`});let o=Xn(t.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.level=n,o.enforcement.checks={},hi(t.rootDir,o);let a=Zn(o);return JSON.stringify({success:true,level:n,message:`Enforcement level set to "${n}". Per-check overrides cleared.`,effective:a},null,2)}case "override":{if(!i||!xg(i))return JSON.stringify({error:`Invalid checkId "${i}". Must be one of: ${Kt.join(", ")}`});if(!r||!jl(r))return JSON.stringify({error:`Invalid severity "${r}". Must be one of: block, warn, off`});let o=Xn(t.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.checks||(o.enforcement.checks={}),o.enforcement.checks[i]=r,hi(t.rootDir,o);let a=Zn(o);return JSON.stringify({success:true,checkId:i,severity:r,message:`Override set: ${i} = ${r}`,effective:a},null,2)}case "reset":{let o=Xn(t.rootDir);o.enforcement&&(o.enforcement.checks={}),hi(t.rootDir,o);let a=Zn(o),c=o.enforcement?.level||"minimal";return JSON.stringify({success:true,message:`All per-check overrides cleared. Preset "${c}" is now fully in effect.`,effective:a},null,2)}default:return JSON.stringify({error:`Unknown action "${s}". Must be one of: status, set-level, override, reset`})}}function Tl(){return Cg}async function Al(t,e,s){if(t==="paradigm_enforcement_configure"){let n=await Rg(s,e);return o(n.length,"paradigm_enforcement_configure"),{handled:true,text:n}}return {handled:false,text:""}}function Pg(t,e){let s=[];for(let n=0;n<=e.length;n++)s[n]=[n];for(let n=0;n<=t.length;n++)s[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=t.length;i++)e.charAt(n-1)===t.charAt(i-1)?s[n][i]=s[n-1][i-1]:s[n][i]=Math.min(s[n-1][i-1]+1,s[n][i-1]+1,s[n-1][i]+1);return s[e.length][t.length]}function Dl(t,e,s={}){let{maxDistance:n=3,maxResults:i=5}=s,r=t.toLowerCase(),o=[];for(let a of e){let c=a.toLowerCase();if(c===r){o.push({match:a,distance:0});continue}if(c.includes(r)||r.includes(c)){o.push({match:a,distance:1});continue}let l=Pg(r,c);l<=n&&o.push({match:a,distance:l});}return o.sort((a,c)=>a.distance!==c.distance?a.distance-c.distance:a.match.localeCompare(c.match)),o.slice(0,i)}v();function Ag(t,e){let s$1=new u(t),n=e||(async()=>{}),i=o=>async(a,c,l)=>o(a,c,l),r$1=o=>async(a,c,l)=>o(a,c,l,n);return s$1.registerAll([{key:"context",tier:"core",getToolsList:r,handleTool:i(s)},{key:"navigate",tier:"core",getToolsList:Uo,handleTool:i(kn)},{key:"tags",tier:"core",getToolsList:Ra,handleTool:i(Pa)},{key:"purpose-portal",tier:"core",getToolsList:$a,handleTool:r$1(Fa)},{key:"pm",tier:"core",getToolsList:Qa,handleTool:i(Xa)},{key:"reindex",tier:"core",getToolsList:sa,handleTool:r$1(ta$1)},{key:"docs",tier:"core",getToolsList:kl,handleTool:i(Sl)},{key:"ripple",tier:"core",getToolsList:ia,handleTool:i(An)},{key:"captain",tier:"core",getToolsList:fa,handleTool:i(At)}]),s$1.registerAll([{key:"wisdom",tier:"feature",getToolsList:No,handleTool:i(wn)},{key:"history",tier:"feature",getToolsList:Eo,handleTool:i(Ho)},{key:"lore",tier:"feature",getToolsList:ga,handleTool:i(Tt)},{key:"streams",tier:"feature",getToolsList:_l,handleTool:i(xl)},{key:"ambient",tier:"feature",getToolsList:Cl,handleTool:i(Rl)},{key:"sentinel",tier:"feature",getToolsList:Bo,handleTool:i(zo)},{key:"flows",tier:"feature",getToolsList:Vo,handleTool:i(Ko)},{key:"fixtures",tier:"feature",getToolsList:ta,handleTool:i(na)},{key:"orchestration",tier:"feature",getToolsList:va,handleTool:i(ka)},{key:"habits",tier:"feature",getToolsList:ec,handleTool:i(tc)},{key:"tasks",tier:"feature",getToolsList:mc,handleTool:i(fc)},{key:"personas",tier:"feature",getToolsList:Cc,handleTool:i(Rc)},{key:"protocols",tier:"feature",getToolsList:ra,handleTool:i(Dn)},{key:"symphony",tier:"feature",getToolsList:Wc,handleTool:i(Gc)},{key:"university",tier:"feature",getToolsList:zc,handleTool:i(Yc)},{key:"agents",tier:"feature",getToolsList:Qc,handleTool:i(Xc)},{key:"authority",tier:"feature",getToolsList:nl,handleTool:i(sl)},{key:"propose-block",tier:"feature",getToolsList:ol,handleTool:i(al)},{key:"notebooks",tier:"feature",getToolsList:cl,handleTool:i(ll)},{key:"aspect-graph",tier:"feature",getToolsList:uc,handleTool:i(gc)},{key:"enforcement",tier:"feature",getToolsList:Tl,handleTool:i(Al),detect:o=>E.existsSync(H.join(o,".paradigm","config.yaml"))},{key:"graph",tier:"feature",getToolsList:Tc,handleTool:i(Ac),detect:o=>E.existsSync(H.join(o,".paradigm","aspect-graph.db"))}]),s$1.registerAll([{key:"conductor",tier:"advanced",getToolsList:qc,handleTool:i(Lc)},{key:"platform",tier:"advanced",getToolsList:Vc,handleTool:i(Kc)},{key:"pipeline",tier:"advanced",getToolsList:$c,handleTool:i(Fc)},{key:"graduation",tier:"advanced",getToolsList:rc,handleTool:i(oc)}]),s$1}function Dg(t,e){let s=g=>g.toLowerCase().replace(/\/+$/,""),n=s(t),i=s(e);if(n===i)return 1;let r=g=>!g.includes("/")&&g.includes("."),o=g=>r(g)?g.split("."):g.split("/").filter(Boolean),a=o(n),c=o(i);if(r(n)||r(i)){let g=r(n)?n.split("."):n.split("/").filter(Boolean),m=r(i)?i.split("."):i.split("/").filter(Boolean),y=0;for(let f=0;f<Math.min(g.length,m.length)&&g[f]===m[f];f++)y++;return y>0?Math.min(1,.5+y/Math.max(g.length,m.length)*.5):0}let l=0,d=Math.max(a.length,c.length);for(let g=0;g<d;g++){let m=a[g]||"",y=c[g]||"";m===y?l++:m.startsWith(":")&&y.startsWith(":")?l+=.9:m.startsWith(":")||y.startsWith(":")?l+=.7:(m.replace(/s$/,"")===y.replace(/s$/,"")||y.replace(/s$/,"")===m.replace(/s$/,""))&&(l+=.8);}let p=l/d,u=a.length===c.length?.1:0;return Math.min(1,p+u)}function Og(){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 - call this at session start for orientation. Shows symbol counts, project health, and available features. Returns symbol counts by type, project health score, and feature flags. ~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 hb(t$1,e,s){let n$2=e(),i$1=Ag(n$2.rootDir,s);t$1.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[...Og(),...i$1.getActiveTools()]})),t$1.setRequestHandler(CallToolRequestSchema,async r=>{let{name:o$1,arguments:a}=r.params;q$1(o$1,a??{});let c=e(),l$1=j$1();l$1.setRootDir(c.rootDir);let d=null,p=null;l$1.hasRecoveredThisSession()||(d=await t(c.rootDir),p=a$1(),b$3(),l$1.markRecovered());let u=await(async()=>{switch(o$1){case "paradigm_search":{let{query:g,type:m,limit:y=10,fuzzy:f=true,includeWorkspace:b=false,componentType:h,response_format:w}=a,v=`search:${g}:${m||""}:${y}:${f}:${b}:${h||""}`,k=await v$1.getOrCompute(v,()=>{let _=j$2(c.index,g);return m&&(_=_.filter(R=>R.type===m)),h&&(_=_.filter(R=>R.componentType===h)),_}),S=[];if(k.length===0&&f){let _=n$1(c.index),R=_.map(I=>I.symbol);S=Dl(g,R,{maxDistance:3,maxResults:5}),S.length>0&&(k=S.map(I=>_.find(P=>P.symbol===I.match)).filter(I=>I!=null),m&&(k=k.filter(I=>I.type===m)));}k=k.slice(0,y);let x={query:g,count:k.length,results:k.map(_=>({symbol:_.symbol,type:_.type,description:_.description,filePath:_.filePath,..._.componentType?{componentType:_.componentType}:{},..._.parentSymbol?{parentSymbol:_.parentSymbol}:{}}))};if(S.length>0&&(x.fuzzyMatched=true,x.fuzzyNote=`No exact matches for "${g}". Showing similar symbols.`,x.suggestions=S.map(_=>({symbol:_.match,distance:_.distance}))),b&&c.workspace){let _=Rt(c.workspace,g),R=m?_.filter(I=>I.type===m):_;R.length>0&&(x.workspaceResults=R.slice(0,y).map(I=>({symbol:I.symbol,type:I.type,description:I.description,filePath:I.filePath,project:I.project})),x.workspaceCount=R.length);}w==="concise"&&(x.results=k.map(_=>({symbol:_.symbol,type:_.type})),delete x.fuzzyMatched,delete x.fuzzyNote,delete x.suggestions,delete x.workspaceResults,delete x.workspaceCount);let C=JSON.stringify(x,null,2);return o(C.length,o$1),{content:[{type:"text",text:C}]}}case "paradigm_related":{let{symbol:g}=a,m=h$1(c.index,g);if(!m){let h=Tn(c.rootDir,g,{maxResults:20});if(h.length===0){let x=JSON.stringify({error:"Symbol not found",symbol:g,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 o(x.length,o$1),{content:[{type:"text",text:x}]}}let w=[...new Set(h.map(x=>x.filePath))],v=h.filter(x=>x.context==="purpose"),k=h.filter(x=>x.context==="code"),S=JSON.stringify({symbol:g,status:"not-indexed",fallback:"grep-search",note:"Approximate relationships from grep \u2014 run `paradigm scan` for accurate graph data.",usedBy:w.slice(0,10).map(x=>({file:x,references:h.filter(C=>C.filePath===x).length})),uses:[],summary:{totalFiles:w.length,totalReferences:h.length,purposeFileRefs:v.length,codeRefs:k.length},suggestion:"Run `paradigm scan` to enable full relationship tracking"},null,2);return o(S.length,o$1),{content:[{type:"text",text:S}]}}let y=k(c.index,g),f=l(c.index,g),b=JSON.stringify({symbol:m.symbol,type:m.type,description:m.description,usedBy:y.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 o(b.length,o$1),{content:[{type:"text",text:b}]}}case "paradigm_status":{let g=a.response_format,m$1=await v$1.getOrCompute("status",async()=>{let f=m(c.index),b=Object.values(f).reduce((A,j)=>A+j,0),h={};for(let A of Object.keys(f)){let j=i(c.index,A);h[A]=j.slice(0,3).map(T=>T.symbol);}let w=ua.platform(),v=w==="win32",k=v?"PowerShell/CMD":w==="darwin"?"zsh/bash":"bash",S;try{let A=await $(c.rootDir);A&&A.health.total>0&&(S=A.health);}catch{}let x=i(c.index,"component"),C={};for(let A of x)A.componentType&&(C[A.componentType]=(C[A.componentType]||0)+1);let _=x.filter(A=>!A.componentType).length,R;try{let{checkPurposeHealth:A}=await import('./integrity-checker-DHGMZQDG.js');R=A(c.aggregation.purposeFiles,c.rootDir).healthScore;}catch{}let I;try{let{countNotebookReferences:A}=await import('./session-work-log-MEJ33TYD.js'),j=A(c.rootDir);j>0&&(I=j);}catch{}let P;try{let{getComplianceTrend:A,getHealthDot:j}=await import('./compliance-health-JNP3P35P.js'),T=A(c.rootDir);T&&(P={trend:T,dot:j(T,c.rootDir)});}catch{}return JSON.stringify({project:c.projectName,symbolSystem:"v2",counts:{"# components":f.component,"$ flows":f.flow,"^ gates":f.gate,"! signals":f.signal,"~ aspects":f.aspect},total:b,...Object.keys(C).length>0?{componentTypes:{...C,..._>0?{"(untyped)":_}:{}}}:{},examples:h,hasPortalYaml:c.gateConfig!==null,purposeFiles:c.aggregation.purposeFiles.length,...R!==void 0?{purposeHealthScore:R}:{},...S?{protocols:S}:{},...I!==void 0?{notebookReferences:I}:{},...P?{complianceHealth:P}:{},note:"Symbol System v2: Use tags [feature], [state], [integration], [idea] for classification. Use type field for structural role (view, service, tool, etc.)",environment:{os:w,shell:k,terminalNote:v?"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$1;if(g==="concise")try{let f=JSON.parse(m$1);y=JSON.stringify({project:f.project,counts:f.counts,total:f.total},null,2);}catch{}return o(y.length,o$1),{content:[{type:"text",text:y}]}}case "paradigm_gates_for_route":{let{route:g,response_format:m}=a,f=typeof g=="string"&&!g.includes("/")&&g.includes(".")?"POST":a.method||"GET",b=i(c.index,"gate"),h=[],w=[];if(c.gateConfig?.routes)for(let[P,A]of Object.entries(c.gateConfig.routes))A.gates&&w.push({route:P,gates:A.gates,method:A.method});if(c.workspace)for(let[P,A]of c.workspace.siblingIndices){let j=A.gateConfig;if(j?.routes)for(let[T,O]of Object.entries(j.routes)){let $=O,F=Array.isArray($)?$:$?.gates;F&&w.push({route:T,gates:F,method:Array.isArray($)?void 0:$?.method,source:P});}}for(let P of w){let A=Dg(g,P.route);if(A>=.6&&(!P.method||P.method===f))for(let j of P.gates){let T=b.find(O=>O.symbol===j||O.symbol===`^${j}`);if(T&&!h.find(O=>O.gate===T.symbol)){let O=P.source?`${P.source}/portal.yaml`:"portal.yaml";h.push({gate:T.symbol,reason:`Similar route "${P.route}" uses this gate`,confidence:A>=.8?"high":"medium",source:O});}}}let S=g.split("/").filter(Boolean).find(P=>!P.startsWith(":")&&P!=="api")?.replace(/s$/,"")||"",x=g.match(/\/:(id|[a-z]+Id)($|\/)/i);if(x&&S){let P=b.find(A=>{let j=A.symbol.toLowerCase(),T=(A.description||"").toLowerCase();return j.includes(`${S}-owner`)||j.includes("owner")||j.includes("ownership")||T.includes("owner")||T.includes("ownership")||T.includes("belongs to")});P?h.push({gate:P.symbol,reason:`Resource ID route (${S}) typically needs ownership verification`,confidence:"high"}):h.push({gate:`^${S}-owner`,reason:`Consider adding ownership gate for ${S} resource`,confidence:"medium"});}if(g.includes("/admin")||g.includes("/settings")){let P=b.find(A=>A.symbol.includes("admin")||A.description?.toLowerCase().includes("admin"));P&&h.push({gate:P.symbol,reason:"Route appears to be admin-related",confidence:"high"});}if(g.startsWith("/api/")||g.includes("/user")||g.includes("/account")){let P=b.find(A=>A.symbol.includes("authenticated")||A.symbol.includes("auth"));P&&h.push({gate:P.symbol,reason:"API/user routes typically require authentication",confidence:"high"});}if(g.includes("/premium")||g.includes("/pro")||g.includes("/export")){let P=b.find(A=>A.symbol.includes("subscription")||A.symbol.includes("premium"));P&&h.push({gate:P.symbol,reason:"Route appears to be a premium feature",confidence:"medium"});}if(f==="DELETE"){let P=b.find(A=>A.symbol.includes("authenticated"));P&&!h.find(A=>A.gate===P.symbol)&&h.push({gate:P.symbol,reason:"DELETE operations require authentication",confidence:"high"});}if(["POST","PUT","PATCH"].includes(f)){let P=b.find(A=>A.symbol.includes("authenticated"));P&&!h.find(A=>A.gate===P.symbol)&&h.push({gate:P.symbol,reason:"Write operations typically require authentication",confidence:"high"});}let C=new Set,_=h.filter(P=>C.has(P.gate)?false:(C.add(P.gate),true)),R=m==="concise"?{suggestions:_.map(P=>({gate:P.gate,confidence:P.confidence}))}:{route:g,method:f,suggestions:_,availableGates:b.map(P=>({symbol:P.symbol,description:P.description})),note:x?"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(R,null,2);o(I.length,o$1);try{n(c.rootDir,{type:"gate-checked",source:"mcp-tool-call",tool:"paradigm_gates_for_route",symbols:_.map(P=>P.gate),context:`Gate check for ${f} ${g}`});}catch{}return {content:[{type:"text",text:I}]}}case "paradigm_plugin_check":{let{runPluginUpdateCheck:g}=await import('./plugin-update-checker-M7PW434O.js'),m=await g(),y=m.filter(w=>w.hasRemoteUpdate||w.hasCacheStale);if(y.length===0){let w=m.length===0?"No Claude Code plugins found in ~/.claude/plugins/marketplaces/.":"All installed plugins are up to date.";return o(w.length,o$1),{content:[{type:"text",text:w}]}}let f=[`Plugin updates available:
511
595
  `],b=[];for(let w of y)w.hasRemoteUpdate?(f.push(` ${w.plugin} (${w.repo}): remote has newer commits`),b.push(`git -C ${w.marketplacePath} pull origin main`)):w.hasCacheStale&&f.push(` ${w.plugin} (${w.repo}): ${w.installedVersion} \u2192 ${w.localVersion} (restart needed)`);b.length>0?(f.push(`
512
596
  Update command:
513
597
  ${b.join(` && \\
514
598
  `)}`),f.push(`
515
599
  After running, restart the session to apply updates.`)):f.push(`
516
600
  Restart the session to apply cached updates.`);let h=f.join(`
517
- `);return o(h.length,o$1),{content:[{type:"text",text:h}]}}case "paradigm_workspace_reindex":{if(!c.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 o(f.length,o$1),{content:[{type:"text",text:f}]}}let{rebuildStaticFiles:m}=await import('./reindex-FWPD2VGM.js'),g=[];for(let f of c.workspace.config.members){let b=H.resolve(H.dirname(c.workspace.workspacePath),f.path);try{let h=await m(b);g.push({name:f.name,symbolCount:h.symbolCount,status:"ok"});}catch(h){g.push({name:f.name,symbolCount:0,status:`error: ${h.message}`});}}let y=JSON.stringify({action:"workspace_reindex",workspace:c.workspace.config.name,members:g,totalSymbols:g.reduce((f,b)=>f+b.symbolCount,0)},null,2);return o(y.length,o$1),v$1.clear(),{content:[{type:"text",text:y}]}}case "paradigm_tool_activate":{let m=a.feature,g=i$1.activateAdvanced(m);if(g){let h=JSON.stringify({action:"tool_activate",feature:m,status:"activated",toolsAdded:g.map(w=>w.name),note:`Advanced module "${m}" activated for this session. ${g.length} tool(s) now available.`},null,2);return o(h.length,o$1),{content:[{type:"text",text:h}]}}let y=i$1.getRegistryInfo(),f=y.activeFeatures.includes(m),b=JSON.stringify({action:"tool_activate",feature:m,status:f?"already_active":"not_found",note:f?`Module "${m}" is already active (auto-detected or core tier).`:`Module "${m}" not found. Available advanced modules: ${y.availableAdvanced.join(", ")||"(none)"}`,availableAdvanced:y.availableAdvanced},null,2);return o(b.length,o$1),{content:[{type:"text",text:b}]}}default:{let m=await i$1.dispatch(o$1,a,c);if(m&&m.handled)return o$1.startsWith("paradigm_context_")||o$1.startsWith("paradigm_session_")||o$1==="paradigm_handoff_prepare"||o(m.text.length,o$1),yg(o$1,a,c.rootDir),{content:[{type:"text",text:m.text}]};throw new Error(`Unknown tool: ${o$1}`)}}})();if(d||p){let m=u.content?.[0];if(m&&typeof m=="object"&&"text"in m&&typeof m.text=="string"){let g=[p,d].filter(Boolean).join(`
601
+ `);return o(h.length,o$1),{content:[{type:"text",text:h}]}}case "paradigm_workspace_reindex":{if(!c.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 o(f.length,o$1),{content:[{type:"text",text:f}]}}let{rebuildStaticFiles:g}=await import('./reindex-GSRV4MQO.js'),m=[];for(let f of c.workspace.config.members){let b=H.resolve(H.dirname(c.workspace.workspacePath),f.path);try{let h=await g(b);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:c.workspace.config.name,members:m,totalSymbols:m.reduce((f,b)=>f+b.symbolCount,0)},null,2);return o(y.length,o$1),v$1.clear(),{content:[{type:"text",text:y}]}}case "paradigm_tool_activate":{let g=a.feature,m=i$1.activateAdvanced(g);if(m){let h=JSON.stringify({action:"tool_activate",feature:g,status:"activated",toolsAdded:m.map(w=>w.name),note:`Advanced module "${g}" activated for this session. ${m.length} tool(s) now available.`},null,2);return o(h.length,o$1),{content:[{type:"text",text:h}]}}let y=i$1.getRegistryInfo(),f=y.activeFeatures.includes(g),b=JSON.stringify({action:"tool_activate",feature:g,status:f?"already_active":"not_found",note:f?`Module "${g}" is already active (auto-detected or core tier).`:`Module "${g}" not found. Available advanced modules: ${y.availableAdvanced.join(", ")||"(none)"}`,availableAdvanced:y.availableAdvanced},null,2);return o(b.length,o$1),{content:[{type:"text",text:b}]}}default:{let g=await i$1.dispatch(o$1,a,c);if(g&&g.handled)return o$1.startsWith("paradigm_context_")||o$1.startsWith("paradigm_session_")||o$1==="paradigm_handoff_prepare"||o(g.text.length,o$1),Ig(o$1,a,c.rootDir),{content:[{type:"text",text:g.text}]};throw new Error(`Unknown tool: ${o$1}`)}}})();if(d||p){let g=u.content?.[0];if(g&&typeof g=="object"&&"text"in g&&typeof g.text=="string"){let m=[p,d].filter(Boolean).join(`
518
602
 
519
- `);m.text=g+`
603
+ `);g.text=m+`
520
604
 
521
- `+m.text;}}return u});}function yg(t,e,s){try{switch(t){case "paradigm_sentinel_record":n(s,{type:"error-encountered",source:"mcp-tool-call",tool:t,severity:e.severity||"warning",context:`Sentinel: ${e.title||e.summary||"incident recorded"}`});break;case "paradigm_lore_record":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,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(s,{type:"work-completed",source:"mcp-tool-call",tool:t,symbols:Array.isArray(e.symbols)?e.symbols.map(String):[],context:`Work logged: ${e.summary||e.title||"entry"}`});break;case "paradigm_decision_record":n(s,{type:"decision-made",source:"mcp-tool-call",tool:t,symbols:Array.isArray(e.symbols)?e.symbols.map(String):[],context:`Decision: ${e.title||e.summary||"recorded"}`});break;case "paradigm_persona_run":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:`Persona run: ${e.persona||"unknown"}`});break;case "paradigm_protocol_record":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:`Protocol recorded: ${e.name||e.id||"unknown"}`});break;case "paradigm_reindex":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:"Index rebuilt"},{skipNominations:!0});break;default:(t.startsWith("paradigm_purpose_")||t.startsWith("paradigm_portal_"))&&(t.includes("_add_")||t.includes("_update_")||t.includes("_remove_"))&&n(s,{type:"file-modified",source:"mcp-tool-call",tool:t,symbols:e.id?[`#${e.id}`]:e.symbol?[String(e.symbol)]:[],context:`Purpose/portal update via ${t}`});break}}catch{}}export{Tl as a,yo as b,Ol as c,Og as d,fn as e,js as f,gy as g,Vh as h};
605
+ `+g.text;}}return u});}function Ig(t,e,s){try{switch(t){case "paradigm_sentinel_record":n(s,{type:"error-encountered",source:"mcp-tool-call",tool:t,severity:e.severity||"warning",context:`Sentinel: ${e.title||e.summary||"incident recorded"}`});break;case "paradigm_lore_record":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,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(s,{type:"work-completed",source:"mcp-tool-call",tool:t,symbols:Array.isArray(e.symbols)?e.symbols.map(String):[],context:`Work logged: ${e.summary||e.title||"entry"}`});break;case "paradigm_decision_record":n(s,{type:"decision-made",source:"mcp-tool-call",tool:t,symbols:Array.isArray(e.symbols)?e.symbols.map(String):[],context:`Decision: ${e.title||e.summary||"recorded"}`});break;case "paradigm_persona_run":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:`Persona run: ${e.persona||"unknown"}`});break;case "paradigm_protocol_record":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:`Protocol recorded: ${e.name||e.id||"unknown"}`});break;case "paradigm_reindex":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:"Index rebuilt"},{skipNominations:!0});break;default:(t.startsWith("paradigm_purpose_")||t.startsWith("paradigm_portal_"))&&(t.includes("_add_")||t.includes("_update_")||t.includes("_remove_"))&&n(s,{type:"file-modified",source:"mcp-tool-call",tool:t,symbols:e.id?[`#${e.id}`]:e.symbol?[String(e.symbol)]:[],context:`Purpose/portal update via ${t}`});break}}catch{}}export{Ul as a,_o as b,Yl as c,Vg as d,bn as e,Is as f,Dy as g,hb as h};