@a-company/paradigm 5.28.0 → 5.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a,b as b$2}from'./chunk-4UJ4NIEQ.js';import {e,v as v$1,b as b$1,n as n$1,c as c$2,d as d$3,q as q$1,p as p$1,o as o$1,s as s$1,i as i$2,k as k$1,l as l$1,a as a$5,m as m$1,t as t$1,u as u$1,j as j$3}from'./chunk-5KSNYRT7.js';import {o as o$2,A,y,x,f as f$4,r as r$2}from'./chunk-KLBH26PA.js';import {g as g$5,d as d$2,a as a$2}from'./chunk-Q2J542ST.js';import {i as i$4}from'./chunk-XROULIQN.js';import {l as l$2,h as h$4,M as M$2,L as L$1,H as H$1,N as N$1,I as I$1,F as F$1,G,A as A$1,E,k as k$2,j as j$4,B,t as t$2,K as K$1,o as o$3,z,P as P$1,m as m$2,w,r as r$1,y as y$1,q as q$2}from'./chunk-VZLGBGU3.js';import {f,g as g$2,e as e$1,m,n,p,h as h$1,i,q,t,o,v as v$2,U,k,l,j as j$2,u,r,ma as ma$1,s,na as na$1,Q,ka as ka$1,Z as Z$1,I,P,O as O$1,R,H,N,M as M$1,L,K,J as J$1,T,Y,S,X as X$1,W,V,ha as ha$1,$,ba as ba$1,da as da$1,ca as ca$1,ia as ia$1,ea as ea$1,aa,ga as ga$1,_,la as la$1,fa as fa$1,ja as ja$1,oa as oa$1,a as a$8,d as d$9,c as c$5,w as w$1,x as x$1,F as F$2,E as E$1,y as y$2,C,z as z$1,A as A$2,B as B$1,G as G$1,D,b as b$a}from'./chunk-VNQGILQU.js';import'./chunk-M4UMM6DC.js';import {d as d$5,b as b$5,a as a$4}from'./chunk-JNSJVCTU.js';import {j,a as a$1,i as i$1,b as b$3,h as h$3,g as g$4,c as c$1,d as d$1}from'./chunk-ODVKPZZ4.js';import {v,f as f$2,p as p$2,h as h$5,b as b$7,d as d$7,e as e$5,i as i$3,u as u$2,l as l$3}from'./chunk-QWL3LERH.js';import {j as j$1,d,e as e$2,f as f$1,g as g$3,h as h$2}from'./chunk-AYYS2AMB.js';import {h,b as b$9}from'./chunk-SL3RZQPW.js';import {f as f$3,b as b$6,e as e$4,d as d$6,a as a$6,c as c$3}from'./chunk-DVZWCXB6.js';import {g as g$1,e as e$3,b as b$4,d as d$4,a as a$3}from'./chunk-QGZRM6ZB.js';import {g,d as d$8,c as c$4,b as b$8,a as a$7}from'./chunk-VG7FN2TU.js';import {b,c,d as d$a}from'./chunk-5TAVYPOV.js';import*as O from'fs';import*as F from'path';import*as Z from'js-yaml';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {ListResourcesRequestSchema,ReadResourceRequestSchema,ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import*as ma from'os';import {execSync}from'child_process';var It,Es,Hs=b(()=>{It={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"]},Es=new Set(["tool-called","context-checked"]);});var Fa={};c(Fa,{getAllStates:()=>Ms,getConfig:()=>ct,getState:()=>Hn,incrementFailure:()=>$a,invalidateGraduationCache:()=>qp,isGraduated:()=>Ep,loadGraduation:()=>Ze,markNeverGraduate:()=>Hp,saveGraduation:()=>En,setTier:()=>Ia});function Oa(n){return F.join(n,".paradigm","graduation.yaml")}function Ze(n){let e=F.resolve(n);if($t&&$n===e&&Date.now()-Fn<Np)return $t;let s=Oa(e),t;if(O.existsSync(s))try{let i=O.readFileSync(s,"utf8");t=Z.load(i);}catch{t={version:"1.0",config:{},states:{}};}else t={version:"1.0",config:{},states:{}};return t.version||(t.version="1.0"),t.config||(t.config={}),t.states||(t.states={}),$t=t,$n=e,Fn=Date.now(),t}function En(n,e){let s=F.resolve(n),t=Oa(s),i=F.dirname(t);O.existsSync(i)||O.mkdirSync(i,{recursive:true});let r=Z.dump(e,{lineWidth:120,noRefs:true,sortKeys:true});O.writeFileSync(t,r,"utf8"),$t=e,$n=s,Fn=Date.now();}function ct(n){let e=Ze(n);return {...It,...e.config,thresholds:{...It.thresholds,...e.config?.thresholds},demotion:{...It.demotion,...e.config?.demotion},neverGraduate:e.config?.neverGraduate??It.neverGraduate}}function qs(n){return {habitId:n,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function Hn(n,e){let t=Ze(n).states[e];return t?{...qs(e),...t,habitId:e}:qs(e)}function Ms(n){let e=Ze(n),s={};for(let[t,i]of Object.entries(e.states))s[t]={...qs(t),...i,habitId:t};return s}function Ep(n,e){return Hn(n,e).tier==="hook"}function Ia(n,e,s,t){let i=Ze(n),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()}:{},...t},En(n,i);}function Hp(n,e){let s=Ze(n);s.states[e]||(s.states[e]={}),s.states[e].neverGraduate=true,s.states[e].tier="habit",En(n,s);}function $a(n,e){let s=Ze(n);s.states[e]||(s.states[e]={});let t=(s.states[e].failureCount||0)+1;return s.states[e].failureCount=t,En(n,s),t}function qp(){$t=null,$n=null,Fn=0;}var $t,$n,Fn,Np,qn=b(()=>{Hs();$t=null,$n=null,Fn=0,Np=3e4;});var Kl=30*1e3,Ss=new Map,xs=".paradigm/wisdom";async function lo(n){let e=F.resolve(n),s=Ss.get(e);if(s&&Date.now()-s.loadedAt<Kl)return s.context;let t=await Ql(e);return Ss.set(e,{context:t,loadedAt:Date.now()}),t}async function Ql(n){let e=F.join(n,xs),s=O.existsSync(e),[t,i,r,o]=s?await Promise.all([Xl(e),Zl(e),ed(e),td(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=t;if(l&&!t)m=l;else if(l&&t){let y={...t.by_symbol};if(l.by_symbol)for(let[f,b]of Object.entries(l.by_symbol))y[f]||(y[f]=b);m={...t,by_symbol:y,global:{...l.global,...t.global}};}return {preferences:m,antipatterns:p,decisions:g,expertise:r}}function Be(n){let e=F.resolve(n);Ss.delete(e);}async function Xl(n){let e=F.join(n,"preferences.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[wisdom-loader] Error parsing preferences.yaml:",s),null}}async function Zl(n){let e=F.join(n,"antipatterns.yaml");if(!O.existsSync(e))return [];try{let s=O.readFileSync(e,"utf8");return Z.load(s).antipatterns||[]}catch(s){return console.error("[wisdom-loader] Error parsing antipatterns.yaml:",s),[]}}async function ed(n){let e=F.join(n,"expertise.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[wisdom-loader] Error parsing expertise.yaml:",s),null}}async function td(n){let e=F.join(n,"decisions");if(!O.existsSync(e))return [];let s=[];try{let t=O.readdirSync(e);for(let i of t){if(!i.endsWith(".yaml")&&!i.endsWith(".yml"))continue;let r=F.join(e,i);try{let o=O.readFileSync(r,"utf8"),a=Z.load(o);s.push(a);}catch(o){console.error(`[wisdom-loader] Error parsing ${i}:`,o);}}}catch(t){console.error("[wisdom-loader] Error reading decisions directory:",t);}return s.sort((t,i)=>t.id.localeCompare(i.id)),s}function po(n,e){return e.map(s=>yn(n,s))}function yn(n,e){let s=n.preferences?.by_symbol?.[e]||null,t=n.antipatterns.filter(o=>o.symbols.some(a=>a===e||fn(e,a))),i=n.decisions.filter(o=>o.symbols.some(a=>a===e||fn(e,a))),r=n.expertise?.experts.filter(o=>o.symbols?.some(a=>a===e||fn(e,a)))||[];return {symbol:e,preferences:s,antipatterns:t,decisions:i,experts:r}}function hn(n,e){return n.expertise?n.expertise.experts.filter(s=>!!(e.symbol&&s.symbols&&s.symbols.some(t=>t===e.symbol||fn(e.symbol,t))||e.area&&s.areas&&s.areas.some(t=>t.toLowerCase().includes(e.area.toLowerCase())))):[]}function fn(n,e){if(e.endsWith("*")){let s=e.slice(0,-1);return n.startsWith(s)}return n===e}async function uo(n,e){let s=F.join(n,xs),t=F.join(s,"antipatterns.yaml");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let i={version:"1.0",antipatterns:[]};if(O.existsSync(t)){let r=O.readFileSync(t,"utf8");i=Z.load(r);}i.antipatterns.push({...e,added:new Date().toISOString()}),O.writeFileSync(t,Z.dump(i,{lineWidth:-1})),Be(n);}async function go(n,e){let s=F.join(n,xs,"decisions");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let t=`${e.id}-${nd(e.title)}.yaml`,i=F.join(s,t);O.writeFileSync(i,Z.dump(e,{lineWidth:-1})),Be(n);}function nd(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var mo=".paradigm/history";async function fo(n){let e=F.join(n,mo);if(!O.existsSync(e))return {index:null,validation:null};let[s,t]=await Promise.all([sd(e),id(e)]);return {index:s,validation:t}}async function sd(n){let e=F.join(n,"index.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[history-loader] Error parsing index.yaml:",s),null}}async function id(n){let e=F.join(n,"validation.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[history-loader] Error parsing validation.yaml:",s),null}}function yo(n,e){return e.map(s=>wn(n,s))}function wn(n,e){let s=n.index?.by_symbol?.[e]||null,t=[];if(n.index?.co_changes){for(let r of n.index.co_changes)if(r.symbols.includes(e))for(let o of r.symbols)o!==e&&!t.includes(o)&&t.push(o);}let i=n.validation?.by_symbol?.[e]||null;return {symbol:e,summary:s,recent:s?.recent||[],co_changes:t,validation:i}}function ho(n,e){let s=[],t=[];if(!n.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=n.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=n.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=n.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&&t.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")),t.length>0&&r.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:s,warnings:t,safe_to_modify:i,recommendations:r}}async function Cs(n,e){let s=F.join(n,mo),t=F.join(s,"log.jsonl");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let i=rd(t),r=new Date().toISOString(),o={id:i,ts:r,...e},a=JSON.stringify(o)+`
2
+ import {a,b as b$2}from'./chunk-4UJ4NIEQ.js';import {e,v as v$1,b as b$1,n as n$1,c as c$2,d as d$3,q as q$1,p as p$1,o as o$1,s as s$1,i as i$2,k as k$1,l as l$1,a as a$5,m as m$1,t as t$1,u as u$1,j as j$3}from'./chunk-5KSNYRT7.js';import {o as o$2,A,y,x,f as f$4,r as r$2}from'./chunk-KLBH26PA.js';import {g as g$5,d as d$2,a as a$2}from'./chunk-Q2J542ST.js';import {i as i$4}from'./chunk-XROULIQN.js';import {l as l$2,h as h$4,M as M$2,L as L$1,H as H$1,N as N$1,I as I$1,F as F$1,G,A as A$1,E,k as k$2,j as j$4,B,t as t$2,K as K$1,o as o$3,z,P as P$1,m as m$2,w,r as r$1,y as y$1,q as q$2}from'./chunk-VZLGBGU3.js';import {f,g as g$2,e as e$1,m,n,p,h as h$1,i,q,t,o,v as v$2,U,k,l,j as j$2,u,r,ma as ma$1,s,na as na$1,Q,ka as ka$1,Z as Z$1,I,P,O as O$1,R,H,N,M as M$1,L,K,J as J$1,T,Y,S,X as X$1,W,V,ha as ha$1,$,ba as ba$1,da as da$1,ca as ca$1,ia as ia$1,ea as ea$1,aa,ga as ga$1,_,la as la$1,fa as fa$1,ja as ja$1,oa as oa$1,a as a$8,d as d$9,c as c$5,w as w$1,x as x$1,F as F$2,E as E$1,y as y$2,C,z as z$1,A as A$2,B as B$1,G as G$1,D,b as b$a}from'./chunk-VNQGILQU.js';import'./chunk-M4UMM6DC.js';import {d as d$5,b as b$5,a as a$4}from'./chunk-JNSJVCTU.js';import {j,a as a$1,i as i$1,b as b$3,h as h$3,g as g$4,c as c$1,d as d$1}from'./chunk-ODVKPZZ4.js';import {v,f as f$2,p as p$2,h as h$5,b as b$7,d as d$7,e as e$5,i as i$3,u as u$2,l as l$3}from'./chunk-QWL3LERH.js';import {j as j$1,d,e as e$2,f as f$1,g as g$3,h as h$2}from'./chunk-AYYS2AMB.js';import {h,b as b$9}from'./chunk-SL3RZQPW.js';import {f as f$3,b as b$6,e as e$4,d as d$6,a as a$6,c as c$3}from'./chunk-DVZWCXB6.js';import {g as g$1,e as e$3,b as b$4,d as d$4,a as a$3}from'./chunk-QGZRM6ZB.js';import {g,d as d$8,c as c$4,b as b$8,a as a$7}from'./chunk-VG7FN2TU.js';import {b,c,d as d$a}from'./chunk-5TAVYPOV.js';import*as O from'fs';import*as F from'path';import*as Z from'js-yaml';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {ListResourcesRequestSchema,ReadResourceRequestSchema,ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import*as ma from'os';import {execSync}from'child_process';var It,Ns,Hs=b(()=>{It={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"]},Ns=new Set(["tool-called","context-checked"]);});var Fa={};c(Fa,{getAllStates:()=>Ms,getConfig:()=>ct,getState:()=>Hn,incrementFailure:()=>$a,invalidateGraduationCache:()=>qp,isGraduated:()=>Np,loadGraduation:()=>Ze,markNeverGraduate:()=>Hp,saveGraduation:()=>Nn,setTier:()=>Ia});function Oa(n){return F.join(n,".paradigm","graduation.yaml")}function Ze(n){let e=F.resolve(n);if($t&&$n===e&&Date.now()-Fn<Ep)return $t;let s=Oa(e),t;if(O.existsSync(s))try{let i=O.readFileSync(s,"utf8");t=Z.load(i);}catch{t={version:"1.0",config:{},states:{}};}else t={version:"1.0",config:{},states:{}};return t.version||(t.version="1.0"),t.config||(t.config={}),t.states||(t.states={}),$t=t,$n=e,Fn=Date.now(),t}function Nn(n,e){let s=F.resolve(n),t=Oa(s),i=F.dirname(t);O.existsSync(i)||O.mkdirSync(i,{recursive:true});let r=Z.dump(e,{lineWidth:120,noRefs:true,sortKeys:true});O.writeFileSync(t,r,"utf8"),$t=e,$n=s,Fn=Date.now();}function ct(n){let e=Ze(n);return {...It,...e.config,thresholds:{...It.thresholds,...e.config?.thresholds},demotion:{...It.demotion,...e.config?.demotion},neverGraduate:e.config?.neverGraduate??It.neverGraduate}}function qs(n){return {habitId:n,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function Hn(n,e){let t=Ze(n).states[e];return t?{...qs(e),...t,habitId:e}:qs(e)}function Ms(n){let e=Ze(n),s={};for(let[t,i]of Object.entries(e.states))s[t]={...qs(t),...i,habitId:t};return s}function Np(n,e){return Hn(n,e).tier==="hook"}function Ia(n,e,s,t){let i=Ze(n),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()}:{},...t},Nn(n,i);}function Hp(n,e){let s=Ze(n);s.states[e]||(s.states[e]={}),s.states[e].neverGraduate=true,s.states[e].tier="habit",Nn(n,s);}function $a(n,e){let s=Ze(n);s.states[e]||(s.states[e]={});let t=(s.states[e].failureCount||0)+1;return s.states[e].failureCount=t,Nn(n,s),t}function qp(){$t=null,$n=null,Fn=0;}var $t,$n,Fn,Ep,qn=b(()=>{Hs();$t=null,$n=null,Fn=0,Ep=3e4;});var Kl=30*1e3,Ss=new Map,xs=".paradigm/wisdom";async function lo(n){let e=F.resolve(n),s=Ss.get(e);if(s&&Date.now()-s.loadedAt<Kl)return s.context;let t=await Ql(e);return Ss.set(e,{context:t,loadedAt:Date.now()}),t}async function Ql(n){let e=F.join(n,xs),s=O.existsSync(e),[t,i,r,o]=s?await Promise.all([Xl(e),Zl(e),ed(e),td(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=t;if(l&&!t)m=l;else if(l&&t){let y={...t.by_symbol};if(l.by_symbol)for(let[f,b]of Object.entries(l.by_symbol))y[f]||(y[f]=b);m={...t,by_symbol:y,global:{...l.global,...t.global}};}return {preferences:m,antipatterns:p,decisions:g,expertise:r}}function Be(n){let e=F.resolve(n);Ss.delete(e);}async function Xl(n){let e=F.join(n,"preferences.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[wisdom-loader] Error parsing preferences.yaml:",s),null}}async function Zl(n){let e=F.join(n,"antipatterns.yaml");if(!O.existsSync(e))return [];try{let s=O.readFileSync(e,"utf8");return Z.load(s).antipatterns||[]}catch(s){return console.error("[wisdom-loader] Error parsing antipatterns.yaml:",s),[]}}async function ed(n){let e=F.join(n,"expertise.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[wisdom-loader] Error parsing expertise.yaml:",s),null}}async function td(n){let e=F.join(n,"decisions");if(!O.existsSync(e))return [];let s=[];try{let t=O.readdirSync(e);for(let i of t){if(!i.endsWith(".yaml")&&!i.endsWith(".yml"))continue;let r=F.join(e,i);try{let o=O.readFileSync(r,"utf8"),a=Z.load(o);s.push(a);}catch(o){console.error(`[wisdom-loader] Error parsing ${i}:`,o);}}}catch(t){console.error("[wisdom-loader] Error reading decisions directory:",t);}return s.sort((t,i)=>t.id.localeCompare(i.id)),s}function po(n,e){return e.map(s=>yn(n,s))}function yn(n,e){let s=n.preferences?.by_symbol?.[e]||null,t=n.antipatterns.filter(o=>o.symbols.some(a=>a===e||fn(e,a))),i=n.decisions.filter(o=>o.symbols.some(a=>a===e||fn(e,a))),r=n.expertise?.experts.filter(o=>o.symbols?.some(a=>a===e||fn(e,a)))||[];return {symbol:e,preferences:s,antipatterns:t,decisions:i,experts:r}}function hn(n,e){return n.expertise?n.expertise.experts.filter(s=>!!(e.symbol&&s.symbols&&s.symbols.some(t=>t===e.symbol||fn(e.symbol,t))||e.area&&s.areas&&s.areas.some(t=>t.toLowerCase().includes(e.area.toLowerCase())))):[]}function fn(n,e){if(e.endsWith("*")){let s=e.slice(0,-1);return n.startsWith(s)}return n===e}async function uo(n,e){let s=F.join(n,xs),t=F.join(s,"antipatterns.yaml");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let i={version:"1.0",antipatterns:[]};if(O.existsSync(t)){let r=O.readFileSync(t,"utf8");i=Z.load(r);}i.antipatterns.push({...e,added:new Date().toISOString()}),O.writeFileSync(t,Z.dump(i,{lineWidth:-1})),Be(n);}async function go(n,e){let s=F.join(n,xs,"decisions");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let t=`${e.id}-${nd(e.title)}.yaml`,i=F.join(s,t);O.writeFileSync(i,Z.dump(e,{lineWidth:-1})),Be(n);}function nd(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var mo=".paradigm/history";async function fo(n){let e=F.join(n,mo);if(!O.existsSync(e))return {index:null,validation:null};let[s,t]=await Promise.all([sd(e),id(e)]);return {index:s,validation:t}}async function sd(n){let e=F.join(n,"index.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[history-loader] Error parsing index.yaml:",s),null}}async function id(n){let e=F.join(n,"validation.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[history-loader] Error parsing validation.yaml:",s),null}}function yo(n,e){return e.map(s=>wn(n,s))}function wn(n,e){let s=n.index?.by_symbol?.[e]||null,t=[];if(n.index?.co_changes){for(let r of n.index.co_changes)if(r.symbols.includes(e))for(let o of r.symbols)o!==e&&!t.includes(o)&&t.push(o);}let i=n.validation?.by_symbol?.[e]||null;return {symbol:e,summary:s,recent:s?.recent||[],co_changes:t,validation:i}}function ho(n,e){let s=[],t=[];if(!n.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=n.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=n.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=n.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&&t.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")),t.length>0&&r.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:s,warnings:t,safe_to_modify:i,recommendations:r}}async function Cs(n,e){let s=F.join(n,mo),t=F.join(s,"log.jsonl");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let i=rd(t),r=new Date().toISOString(),o={id:i,ts:r,...e},a=JSON.stringify(o)+`
3
3
  `;return O.appendFileSync(t,a),i}async function bo(n,e,s,t){return Cs(n,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:s,tests:t})}function rd(n){let e=1;return O.existsSync(n)&&(e=O.readFileSync(n,"utf8").split(`
4
4
  `).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}function od(n){let e=F.resolve(n),s=O.readFileSync(e,"utf8"),t=Z.load(s);if(!t||typeof t!="object")throw new Error(`Invalid workspace file: ${n}`);let i={version:String(t.version||"1.0"),name:String(t.name||"unnamed-workspace"),members:[]};if(Array.isArray(t.members)){for(let r of t.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 vo(n,e){let s=F.resolve(n),t=F.resolve(s,e);if(!O.existsSync(t))return console.error(`Warning: Workspace file not found at ${t}`),null;let i;try{i=od(t);}catch(c){return console.error(`Warning: Could not parse workspace file: ${c.message}`),null}let r=F.dirname(t),o="";for(let c of i.members){let l=F.resolve(r,c.path);if(wo(l)===wo(s)){o=c.name;break}}if(!o)return console.error(`Warning: Current directory is not a member of workspace "${i.name}"`),null;let a=new Map;for(let c of i.members){if(c.name===o)continue;let l=F.resolve(r,c.path),d=F.join(l,".paradigm","scan-index.json");if(!O.existsSync(d)){console.error(`Warning: No scan-index.json for workspace member "${c.name}" at ${d}`);continue}try{let p=JSON.parse(O.readFileSync(d,"utf8")),u=ld(p);c.exports&&c.exports.length>0&&(u=ad(u,c.exports));let g=null,m=F.join(l,"portal.yaml");if(O.existsSync(m))try{let y=O.readFileSync(m,"utf8"),f=Z.load(y);f&&(g=f);}catch{}a.set(c.name,{index:u,gateConfig:g});}catch(p){console.error(`Warning: Could not load index for workspace member "${c.name}": ${p.message}`);}}return {config:i,workspacePath:t,currentMember:o,siblingIndices:a}}function ad(n$1,e){let t=n(n$1).filter(i=>{let r=i.symbol;return e.some(o=>cd(o,r))});return dd(t)}function cd(n,e){let s=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${s}$`,"i").test(e)}function jt(n,e){let s=[];for(let[t,i]of n.siblingIndices){let r=j$2(i.index,e);for(let o of r)s.push({project:t,symbol:`${t}/${o.symbol}`,type:o.type,description:o.description,filePath:o.filePath});}return s}function _o(n$1,e){let s=[],t=e.includes("/")?e.split("/").pop():e;for(let[i,r]of n$1.siblingIndices){let o=[],a=n(r.index);for(let c of a){let l=c.references||[],d=c.description||"",p=l.some(g=>g===t||g===e||g.endsWith(`/${t}`)),u=d.includes(t);(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 wo(n){return F.resolve(n).replace(/\/+$/,"")}function ld(n){let e={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"},s=[];for(let[t,i]of Object.entries(e)){let r=n[t];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$2({symbols:s,purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}function dd(n){return g$2({symbols:n.map(e=>({id:e.id||e.symbol.replace(/^[#$^!~]/,""),symbol:e.symbol,type:e.type,source:"purpose",filePath:e.filePath||"",data:e.data||{},references:e.references||[],referencedBy:e.referencedBy||[],description:e.description,tags:e.tags})),purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}async function Rs(n){let e=F.resolve(n),s=await f(e),t=g$2(s),i=null,r=F.join(e,"portal.yaml");if(O.existsSync(r))try{i=await e$1(r);}catch(d){console.error("Warning: Could not parse portal.yaml:",d.message);}let o=F.basename(e),a=F.join(e,".premise");if(O.existsSync(a))try{let p=O.readFileSync(a,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);p&&(o=p[1].trim());}catch{}let c=null,l=F.join(e,".paradigm","config.yaml");if(O.existsSync(l))try{let d=O.readFileSync(l,"utf8"),p=Z.load(d);p&&typeof p=="object"&&(p.version||console.error('[paradigm] Warning: config.yaml missing "version" field'),p.project||console.error('[paradigm] Warning: config.yaml missing "project" field')),p&&typeof p.workspace=="string"&&(c=vo(e,p.workspace));}catch(d){console.error(`[paradigm] Warning: Failed to load workspace config: ${d.message}`);}return {rootDir:e,index:t,aggregation:s,gateConfig:i,projectName:o,wisdom:null,history:null,workspace:c,_loadedAt:Date.now()}}async function se(n){return n.wisdom||(n.wisdom=await lo(n.rootDir)),n.wisdom}async function ke(n){return n.history||(n.history=await fo(n.rootDir)),n.history}function pd(n){return {id:n.id,symbol:`^${n.id}`,description:n.description,locks:n.locks?.map(e=>({id:e.id,description:e.description,keys:e.keys?.map(s=>s.expression||s),mode:e.mode||"all"})),prizes:n.prizes?.map(e=>({id:e.id,oneTime:e.oneTime}))}}function So(n){let e=n.gateConfig?.gates||[],s=i(n.index,"gate"),t=new Map;for(let i of s){let r=i.symbol.replace(/^\^/,"");t.set(r,{id:r,symbol:i.symbol,description:i.description,source:"purpose",filePath:i.filePath,data:i.data});}for(let i of e)t.set(i.id,{...pd(i),source:"portal.yaml"});return Array.from(t.values())}function xo(n){let e=n.gateConfig?.flows||[],s=i(n.index,"flow"),t=new Map;for(let i of s){let r=i.symbol.replace(/^\$/,"");t.set(r,{id:r,symbol:i.symbol,description:i.description,source:"purpose",filePath:i.filePath,data:i.data});}for(let i of e)t.set(i.id,{id:i.id,symbol:`$${i.id}`,description:i.description,gates:i.gates,source:"portal.yaml"});return Array.from(t.values())}function Co(){return [{uri:"paradigm://wisdom/preferences",name:"Wisdom - Preferences",description:"Team preferences for patterns, testing, and code style",mimeType:"application/json"},{uri:"paradigm://wisdom/antipatterns",name:"Wisdom - Antipatterns",description:"What NOT to do, with reasons and alternatives",mimeType:"application/json"},{uri:"paradigm://wisdom/decisions",name:"Wisdom - Decisions",description:"Architectural Decision Records (ADRs) index",mimeType:"application/json"}]}async function Po(n,e){if(n==="wisdom/preferences"){let s=await se(e);return {handled:true,text:JSON.stringify({version:s.preferences?.version||"1.0",global:s.preferences?.global||{},by_symbol:s.preferences?.by_symbol||{},symbol_count:Object.keys(s.preferences?.by_symbol||{}).length},null,2)}}if(n.startsWith("wisdom/preferences/")){let s=decodeURIComponent(n.replace("wisdom/preferences/","")),t=await se(e),i=yn(t,s);return {handled:true,text:JSON.stringify({symbol:s,preferences:i.preferences,global:t.preferences?.global||{}},null,2)}}if(n==="wisdom/antipatterns"){let s=await se(e);return {handled:true,text:JSON.stringify({count:s.antipatterns.length,antipatterns:s.antipatterns},null,2)}}if(n.startsWith("wisdom/antipatterns/")){let s=decodeURIComponent(n.replace("wisdom/antipatterns/","")),t=await se(e),i=yn(t,s);return {handled:true,text:JSON.stringify({symbol:s,count:i.antipatterns.length,antipatterns:i.antipatterns},null,2)}}if(n==="wisdom/decisions"){let s=await se(e);return {handled:true,text:JSON.stringify({count:s.decisions.length,decisions:s.decisions.map(t=>({id:t.id,title:t.title,status:t.status,date:t.date,symbols:t.symbols}))},null,2)}}if(n.startsWith("wisdom/decision/")){let s=n.replace("wisdom/decision/",""),t=await se(e),i=t.decisions.find(r=>r.id===s);return i?{handled:true,text:JSON.stringify(i,null,2)}:{handled:true,text:JSON.stringify({error:"Decision not found",id:s,available:t.decisions.map(r=>r.id)},null,2)}}if(n.startsWith("wisdom/expertise/")){let s=decodeURIComponent(n.replace("wisdom/expertise/","")),t=await se(e),i=hn(t,{symbol:s});return {handled:true,text:JSON.stringify({symbol:s,count:i.length,experts:i.map(r=>({name:r.name,symbols:r.symbols,areas:r.areas,contact:r.contact}))},null,2)}}return {handled:false,text:""}}function Ro(){return [{uri:"paradigm://history/fragile",name:"History - Fragile Symbols",description:"Symbols with high fragility that need extra care when modifying",mimeType:"application/json"},{uri:"paradigm://history/validation/summary",name:"History - Validation Summary",description:"Overall validation statistics and pass rates",mimeType:"application/json"}]}async function jo(n,e){if(n.startsWith("history/symbol/")&&!n.endsWith("/recent")){let s=decodeURIComponent(n.replace("history/symbol/","")),t=await ke(e),i=wn(t,s);return {handled:true,text:JSON.stringify({symbol:s,summary:i.summary?{total_changes:i.summary.total_changes,last_modified:i.summary.last_modified,stability_score:i.summary.stability_score,fragility:i.summary.fragility,contributors:i.summary.contributors}:null,recent:i.recent,co_changes:i.co_changes,validation:i.validation},null,2)}}if(n.startsWith("history/symbol/")&&n.endsWith("/recent")){let s=decodeURIComponent(n.replace("history/symbol/","").replace("/recent","")),t=await ke(e),i=wn(t,s);return {handled:true,text:JSON.stringify({symbol:s,fragility:i.summary?.fragility||"unknown",stability_score:i.summary?.stability_score,recent:i.recent.slice(0,5)},null,2)}}if(n==="history/fragile"){let s=await ke(e);return {handled:true,text:JSON.stringify({count:s.index?.fragile_symbols?.length||0,fragile_symbols:s.index?.fragile_symbols||[],recommendation:"Consider adding extra test coverage and reviewing recent changes before modifying these symbols"},null,2)}}if(n.startsWith("history/cochanges/")){let s=decodeURIComponent(n.replace("history/cochanges/","")),i=(await ke(e)).index?.co_changes?.filter(r=>r.symbols.includes(s))||[];return {handled:true,text:JSON.stringify({symbol:s,count:i.length,co_changes:i.map(r=>({with:r.symbols.filter(o=>o!==s),frequency:r.frequency,correlation:r.correlation})),recommendation:i.length>0?"These symbols often change together - consider if they need updates too":"No strong co-change patterns detected"},null,2)}}if(n==="history/validation/summary"){let s=await ke(e);return {handled:true,text:JSON.stringify({last_run:s.validation?.last_run,total_validations:s.validation?.total_validations||0,pass_rate:s.validation?.pass_rate||0,by_symbol:s.validation?.by_symbol||{}},null,2)}}return {handled:false,text:""}}function To(){return [{uri:"paradigm://context/agent-protocol",name:"Agent Protocol",description:"IMPORTANT: Read this first. Workflow instructions for using Paradigm MCP tools effectively.",mimeType:"text/markdown"},{uri:"paradigm://context/session",name:"Session Info",description:"Current MCP session statistics and context usage estimate",mimeType:"application/json"},{uri:"paradigm://context/handoff-guide",name:"Handoff Guide",description:"When and how to perform context handoffs",mimeType:"text/markdown"}]}async function Do(n,e){if(n==="context/agent-protocol")return {handled:true,text:`# Agent Protocol for Paradigm MCP Tools
5
5
 
@@ -99,7 +99,7 @@ Call the \`paradigm_context_check\` tool to get:
99
99
  - List specific file paths modified
100
100
  - Include any blockers or decisions needed
101
101
  - Reference relevant symbols (@feature, #component, etc.)
102
- `}:{handled:false,text:""}}var ud={"add-feature":"Pathway for adding a new user-facing feature with proper symbol definitions","add-gate":"Add a new gate (portal) for authorization control","debug-auth":"Debug authentication and authorization issues","implement-ftux":"Implement First-Time User Experience (FTUX) flow","implement-sandbox":"Set up a sandbox environment for testing","read-docs":"Read and understand existing documentation",refactor:"Refactor existing code with proper planning","run-e2e-tests":"Run and debug end-to-end tests","trace-flow":"Trace a flow through the system","validate-portals":"Validate portal.yaml configuration"};function gd(n,e){let s=[F.join(__dirname,"../../../../paradigm/templates/paradigm",n),F.join(e.rootDir,"node_modules/@a-company/paradigm/templates/paradigm",n),F.join(e.rootDir,"../../packages/paradigm/templates/paradigm",n),F.join(process.env.HOME||"",".paradigm/templates",n),F.resolve(__dirname,"../../../paradigm/templates/paradigm",n)];for(let t of s)try{if(O.existsSync(t))return t}catch{}return null}function Ao(n){return gd("prompts",n)}function md(n){return Math.ceil(n.length/3.5)}function Oo(n){let e=Ao(n);if(!e)return [];try{return O.readdirSync(e).filter(t=>t.endsWith(".md")).map(t=>{let i=t.replace(".md",""),r=F.join(e,t),o=O.statSync(r),a=O.readFileSync(r,"utf8");return {name:i,description:ud[i]||`Prompt template: ${i}`,filename:t,size:o.size,tokens:md(a)}})}catch{return []}}function fd(n,e){let s=Ao(e);if(!s)return {found:false,content:"",error:"Prompts directory not found. Ensure @a-company/paradigm is installed."};let t=F.join(s,`${n}.md`);try{if(!O.existsSync(t)){let r=Oo(e).map(o=>o.name);return {found:!1,content:"",error:`Prompt "${n}" not found. Available prompts: ${r.join(", ")}`}}return {content:O.readFileSync(t,"utf8"),found:!0}}catch(i){return {found:false,content:"",error:`Error reading prompt: ${i.message}`}}}function Io(){return [{uri:"paradigm://prompts",name:"Prompts",description:"List all available prompt templates with metadata (name, description, size)",mimeType:"application/json"},{uri:"paradigm://prompts/{name}",name:"Prompt Content",description:"Get a specific prompt template content. Replace {name} with prompt name (e.g., add-feature)",mimeType:"text/markdown"}]}async function $o(n,e){let s=`paradigm://${n}`;if(n==="prompts"){let t=Oo(e),i=t.reduce((a,c)=>a+c.size,0),r=t.reduce((a,c)=>a+c.tokens,0),o=JSON.stringify({count:t.length,totalSize:i,totalTokens:r,prompts:t.map(a=>({name:a.name,description:a.description,size:a.size,tokens:a.tokens,uri:`paradigm://prompts/${a.name}`})),usage:"Read a specific prompt with paradigm://prompts/{name}"},null,2);return p(o.length,s),{handled:true,text:o,mimeType:"application/json"}}if(n.startsWith("prompts/")){let t=decodeURIComponent(n.replace("prompts/","")),{content:i,found:r,error:o}=fd(t,e);if(!r){let a=JSON.stringify({error:o,name:t},null,2);return p(a.length,s),{handled:true,text:a,mimeType:"application/json"}}return p(i.length,s),{handled:true,text:i,mimeType:"text/markdown"}}return {handled:false,text:"",mimeType:"application/json"}}var js={disciplines:"Language and discipline-agnostic symbol mappings for different domains",scan:"Paradigm Probe protocol for visual discovery and UI-to-code mapping","context-tracking":"Context tracking system for session monitoring and handoffs"};function yd(n,e){let s=[F.join(__dirname,"../../../../paradigm/templates/paradigm",n),F.join(e.rootDir,"node_modules/@a-company/paradigm/templates/paradigm",n),F.join(e.rootDir,"../../packages/paradigm/templates/paradigm",n),F.join(process.env.HOME||"",".paradigm/templates",n),F.resolve(__dirname,"../../../paradigm/templates/paradigm",n)];for(let t of s)try{if(O.existsSync(t))return t}catch{}return null}function Fo(n){return yd("specs",n)}function hd(n){return Math.ceil(n.length/3.5)}function bd(n){let e=Fo(n);if(!e)return [];let s=[];for(let[t,i]of Object.entries(js)){let r=`${t}.md`,o=F.join(e,r);try{if(O.existsSync(o)){let a=O.statSync(o),c=O.readFileSync(o,"utf8");s.push({name:t,description:i,filename:r,size:a.size,tokens:hd(c)});}}catch{}}return s}function wd(n,e){if(!js[n]){let i=Object.keys(js);return {found:false,content:"",error:`"${n}" is not a reference spec. Reference specs available via MCP: ${i.join(", ")}. Project-specific specs should be read from .paradigm/specs/ directly.`}}let s=Fo(e);if(!s)return {found:false,content:"",error:"Specs directory not found. Ensure @a-company/paradigm is installed."};let t=F.join(s,`${n}.md`);try{return O.existsSync(t)?{content:O.readFileSync(t,"utf8"),found:!0}:{found:!1,content:"",error:`Spec "${n}" file not found at expected location.`}}catch(i){return {found:false,content:"",error:`Error reading spec: ${i.message}`}}}function No(){return [{uri:"paradigm://specs",name:"Reference Specs",description:"List reference specifications (disciplines, scan, context-tracking)",mimeType:"application/json"},{uri:"paradigm://specs/{name}",name:"Spec Content",description:"Get a reference spec. Available: disciplines, scan, context-tracking",mimeType:"text/markdown"}]}async function Eo(n,e){let s=`paradigm://${n}`;if(n==="specs"){let t=bd(e),i=t.reduce((a,c)=>a+c.size,0),r=t.reduce((a,c)=>a+c.tokens,0),o=JSON.stringify({count:t.length,totalSize:i,totalTokens:r,note:"These are reference specs served via MCP. Project-specific specs (logger, symbols, etc.) should be read from .paradigm/specs/ directly.",specs:t.map(a=>({name:a.name,description:a.description,size:a.size,tokens:a.tokens,uri:`paradigm://specs/${a.name}`}))},null,2);return p(o.length,s),{handled:true,text:o,mimeType:"application/json"}}if(n.startsWith("specs/")&&n!=="specs/"){let t=decodeURIComponent(n.replace("specs/","")),{content:i,found:r,error:o}=wd(t,e);if(!r){let a=JSON.stringify({error:o,name:t},null,2);return p(a.length,s),{handled:true,text:a,mimeType:"application/json"}}return p(i.length,s),{handled:true,text:i,mimeType:"text/markdown"}}return {handled:false,text:"",mimeType:"application/json"}}var Ts={commands:"Complete CLI command reference with examples and usage guidance",queries:"jq query examples for querying the constellation symbol graph"};function vd(n,e){let s=[F.join(__dirname,"../../../../paradigm/templates/paradigm",n),F.join(e.rootDir,"node_modules/@a-company/paradigm/templates/paradigm",n),F.join(e.rootDir,"../../packages/paradigm/templates/paradigm",n),F.join(process.env.HOME||"",".paradigm/templates",n),F.resolve(__dirname,"../../../paradigm/templates/paradigm",n)];for(let t of s)try{if(O.existsSync(t))return t}catch{}return null}function Ho(n){return vd("docs",n)}function _d(n){return Math.ceil(n.length/3.5)}function kd(n){let e=Ho(n);if(!e)return [];let s=[];for(let[t,i]of Object.entries(Ts)){let r=`${t}.md`,o=F.join(e,r);try{if(O.existsSync(o)){let a=O.statSync(o),c=O.readFileSync(o,"utf8");s.push({name:t,description:i,filename:r,size:a.size,tokens:_d(c)});}}catch{}}return s}function Sd(n,e){if(!Ts[n]){let i=Object.keys(Ts);return {found:false,content:"",error:`"${n}" is not a reference doc. Reference docs available via MCP: ${i.join(", ")}. Project-specific docs (patterns, troubleshooting, etc.) should be read from .paradigm/docs/ directly.`}}let s=Ho(e);if(!s)return {found:false,content:"",error:"Docs directory not found. Ensure @a-company/paradigm is installed."};let t=F.join(s,`${n}.md`);try{return O.existsSync(t)?{content:O.readFileSync(t,"utf8"),found:!0}:{found:!1,content:"",error:`Doc "${n}" file not found at expected location.`}}catch(i){return {found:false,content:"",error:`Error reading doc: ${i.message}`}}}function qo(){return [{uri:"paradigm://docs",name:"Reference Docs",description:"List reference documentation (commands, queries)",mimeType:"application/json"},{uri:"paradigm://docs/{name}",name:"Doc Content",description:"Get a reference doc. Available: commands, queries",mimeType:"text/markdown"}]}async function Mo(n,e){let s=`paradigm://${n}`;if(n==="docs"){let t=kd(e),i=t.reduce((a,c)=>a+c.size,0),r=t.reduce((a,c)=>a+c.tokens,0),o=JSON.stringify({count:t.length,totalSize:i,totalTokens:r,note:"These are reference docs served via MCP. Project-specific docs (patterns, troubleshooting, etc.) should be read from .paradigm/docs/ directly.",docs:t.map(a=>({name:a.name,description:a.description,size:a.size,tokens:a.tokens,uri:`paradigm://docs/${a.name}`}))},null,2);return p(o.length,s),{handled:true,text:o,mimeType:"application/json"}}if(n.startsWith("docs/")&&n!=="docs/"){let t=decodeURIComponent(n.replace("docs/","")),{content:i,found:r,error:o}=Sd(t,e);if(!r){let a=JSON.stringify({error:o,name:t},null,2);return p(a.length,s),{handled:true,text:a,mimeType:"application/json"}}return p(i.length,s),{handled:true,text:i,mimeType:"text/markdown"}}return {handled:false,text:"",mimeType:"application/json"}}var vn={logging:{description:"Paradigm logger usage, symbol-to-method mapping by directory",generate:()=>"# Paradigm Logging Guide\n\n**IMPORTANT:** Use the Paradigm logger instead of raw console.log/print.\n\n## Usage Pattern\n\n```typescript\nlog.component('#login-handler').info('Starting login', { email });\nlog.component('#database').debug('Query executed', { duration });\nlog.gate('^authenticated').warn('Access denied', { userId });\nlog.signal('!login-success').info('User authenticated');\nlog.flow('$checkout').info('Flow step reached');\nlog.aspect('~audit-required').info('Audit triggered');\n```\n\n## Symbol Mapping by Directory\n\n| Directory | Symbol | Logger Method |\n|-----------|--------|---------------|\n| `features/**` | `#` | `log.component()` |\n| `routes/**` | `#` | `log.component()` |\n| `api/**` | `#` | `log.component()` |\n| `endpoints/**` | `#` | `log.component()` |\n| `commands/**` | `#` | `log.component()` |\n| `models/**` | `#` | `log.component()` |\n| `components/**` | `#` | `log.component()` |\n| `lib/**` | `#` | `log.component()` |\n| `utils/**` | `#` | `log.component()` |\n| `services/**` | `#` | `log.component()` |\n| `core/**` | `#` | `log.component()` |\n| `drivers/**` | `#` | `log.component()` |\n| `systems/**` | `#` | `log.component()` |\n| `integrations/**` | `#` | `log.component()` |\n| `external/**` | `#` | `log.component()` |\n| `vendors/**` | `#` | `log.component()` |\n| `stores/**` | `#` | `log.component()` |\n| `state/**` | `#` | `log.component()` |\n| `reducers/**` | `#` | `log.component()` |\n| `config/**` | `#` | `log.component()` |\n| `middleware/**` | `^` | `log.gate()` |\n| `auth/**` | `^` | `log.gate()` |\n| `guards/**` | `^` | `log.gate()` |\n| `policies/**` | `^` | `log.gate()` |\n| `events/**` | `!` | `log.signal()` |\n| `handlers/**` | `!` | `log.signal()` |\n| `listeners/**` | `!` | `log.signal()` |\n| `hooks/**` | `!` | `log.signal()` |\n| `flows/**` | `$` | `log.flow()` |\n| `sagas/**` | `$` | `log.flow()` |\n| `workflows/**` | `$` | `log.flow()` |\n| `pipelines/**` | `$` | `log.flow()` |\n| `aspects/**` | `~` | `log.aspect()` |\n| `rules/**` | `~` | `log.aspect()` |\n| `constraints/**` | `~` | `log.aspect()` |\n\nSee `.paradigm/specs/logger.md` for full specification."},portal:{description:"Portal protocol \u2014 authorization, gates, portal.yaml structure and workflow",generate:()=>`# Portal Protocol (Authorization)
102
+ `}:{handled:false,text:""}}var ud={"add-feature":"Pathway for adding a new user-facing feature with proper symbol definitions","add-gate":"Add a new gate (portal) for authorization control","debug-auth":"Debug authentication and authorization issues","implement-ftux":"Implement First-Time User Experience (FTUX) flow","implement-sandbox":"Set up a sandbox environment for testing","read-docs":"Read and understand existing documentation",refactor:"Refactor existing code with proper planning","run-e2e-tests":"Run and debug end-to-end tests","trace-flow":"Trace a flow through the system","validate-portals":"Validate portal.yaml configuration"};function gd(n,e){let s=[F.join(__dirname,"../../../../paradigm/templates/paradigm",n),F.join(e.rootDir,"node_modules/@a-company/paradigm/templates/paradigm",n),F.join(e.rootDir,"../../packages/paradigm/templates/paradigm",n),F.join(process.env.HOME||"",".paradigm/templates",n),F.resolve(__dirname,"../../../paradigm/templates/paradigm",n)];for(let t of s)try{if(O.existsSync(t))return t}catch{}return null}function Ao(n){return gd("prompts",n)}function md(n){return Math.ceil(n.length/3.5)}function Oo(n){let e=Ao(n);if(!e)return [];try{return O.readdirSync(e).filter(t=>t.endsWith(".md")).map(t=>{let i=t.replace(".md",""),r=F.join(e,t),o=O.statSync(r),a=O.readFileSync(r,"utf8");return {name:i,description:ud[i]||`Prompt template: ${i}`,filename:t,size:o.size,tokens:md(a)}})}catch{return []}}function fd(n,e){let s=Ao(e);if(!s)return {found:false,content:"",error:"Prompts directory not found. Ensure @a-company/paradigm is installed."};let t=F.join(s,`${n}.md`);try{if(!O.existsSync(t)){let r=Oo(e).map(o=>o.name);return {found:!1,content:"",error:`Prompt "${n}" not found. Available prompts: ${r.join(", ")}`}}return {content:O.readFileSync(t,"utf8"),found:!0}}catch(i){return {found:false,content:"",error:`Error reading prompt: ${i.message}`}}}function Io(){return [{uri:"paradigm://prompts",name:"Prompts",description:"List all available prompt templates with metadata (name, description, size)",mimeType:"application/json"},{uri:"paradigm://prompts/{name}",name:"Prompt Content",description:"Get a specific prompt template content. Replace {name} with prompt name (e.g., add-feature)",mimeType:"text/markdown"}]}async function $o(n,e){let s=`paradigm://${n}`;if(n==="prompts"){let t=Oo(e),i=t.reduce((a,c)=>a+c.size,0),r=t.reduce((a,c)=>a+c.tokens,0),o=JSON.stringify({count:t.length,totalSize:i,totalTokens:r,prompts:t.map(a=>({name:a.name,description:a.description,size:a.size,tokens:a.tokens,uri:`paradigm://prompts/${a.name}`})),usage:"Read a specific prompt with paradigm://prompts/{name}"},null,2);return p(o.length,s),{handled:true,text:o,mimeType:"application/json"}}if(n.startsWith("prompts/")){let t=decodeURIComponent(n.replace("prompts/","")),{content:i,found:r,error:o}=fd(t,e);if(!r){let a=JSON.stringify({error:o,name:t},null,2);return p(a.length,s),{handled:true,text:a,mimeType:"application/json"}}return p(i.length,s),{handled:true,text:i,mimeType:"text/markdown"}}return {handled:false,text:"",mimeType:"application/json"}}var js={disciplines:"Language and discipline-agnostic symbol mappings for different domains",scan:"Paradigm Probe protocol for visual discovery and UI-to-code mapping","context-tracking":"Context tracking system for session monitoring and handoffs"};function yd(n,e){let s=[F.join(__dirname,"../../../../paradigm/templates/paradigm",n),F.join(e.rootDir,"node_modules/@a-company/paradigm/templates/paradigm",n),F.join(e.rootDir,"../../packages/paradigm/templates/paradigm",n),F.join(process.env.HOME||"",".paradigm/templates",n),F.resolve(__dirname,"../../../paradigm/templates/paradigm",n)];for(let t of s)try{if(O.existsSync(t))return t}catch{}return null}function Fo(n){return yd("specs",n)}function hd(n){return Math.ceil(n.length/3.5)}function bd(n){let e=Fo(n);if(!e)return [];let s=[];for(let[t,i]of Object.entries(js)){let r=`${t}.md`,o=F.join(e,r);try{if(O.existsSync(o)){let a=O.statSync(o),c=O.readFileSync(o,"utf8");s.push({name:t,description:i,filename:r,size:a.size,tokens:hd(c)});}}catch{}}return s}function wd(n,e){if(!js[n]){let i=Object.keys(js);return {found:false,content:"",error:`"${n}" is not a reference spec. Reference specs available via MCP: ${i.join(", ")}. Project-specific specs should be read from .paradigm/specs/ directly.`}}let s=Fo(e);if(!s)return {found:false,content:"",error:"Specs directory not found. Ensure @a-company/paradigm is installed."};let t=F.join(s,`${n}.md`);try{return O.existsSync(t)?{content:O.readFileSync(t,"utf8"),found:!0}:{found:!1,content:"",error:`Spec "${n}" file not found at expected location.`}}catch(i){return {found:false,content:"",error:`Error reading spec: ${i.message}`}}}function Eo(){return [{uri:"paradigm://specs",name:"Reference Specs",description:"List reference specifications (disciplines, scan, context-tracking)",mimeType:"application/json"},{uri:"paradigm://specs/{name}",name:"Spec Content",description:"Get a reference spec. Available: disciplines, scan, context-tracking",mimeType:"text/markdown"}]}async function No(n,e){let s=`paradigm://${n}`;if(n==="specs"){let t=bd(e),i=t.reduce((a,c)=>a+c.size,0),r=t.reduce((a,c)=>a+c.tokens,0),o=JSON.stringify({count:t.length,totalSize:i,totalTokens:r,note:"These are reference specs served via MCP. Project-specific specs (logger, symbols, etc.) should be read from .paradigm/specs/ directly.",specs:t.map(a=>({name:a.name,description:a.description,size:a.size,tokens:a.tokens,uri:`paradigm://specs/${a.name}`}))},null,2);return p(o.length,s),{handled:true,text:o,mimeType:"application/json"}}if(n.startsWith("specs/")&&n!=="specs/"){let t=decodeURIComponent(n.replace("specs/","")),{content:i,found:r,error:o}=wd(t,e);if(!r){let a=JSON.stringify({error:o,name:t},null,2);return p(a.length,s),{handled:true,text:a,mimeType:"application/json"}}return p(i.length,s),{handled:true,text:i,mimeType:"text/markdown"}}return {handled:false,text:"",mimeType:"application/json"}}var Ts={commands:"Complete CLI command reference with examples and usage guidance",queries:"jq query examples for querying the constellation symbol graph"};function vd(n,e){let s=[F.join(__dirname,"../../../../paradigm/templates/paradigm",n),F.join(e.rootDir,"node_modules/@a-company/paradigm/templates/paradigm",n),F.join(e.rootDir,"../../packages/paradigm/templates/paradigm",n),F.join(process.env.HOME||"",".paradigm/templates",n),F.resolve(__dirname,"../../../paradigm/templates/paradigm",n)];for(let t of s)try{if(O.existsSync(t))return t}catch{}return null}function Ho(n){return vd("docs",n)}function _d(n){return Math.ceil(n.length/3.5)}function kd(n){let e=Ho(n);if(!e)return [];let s=[];for(let[t,i]of Object.entries(Ts)){let r=`${t}.md`,o=F.join(e,r);try{if(O.existsSync(o)){let a=O.statSync(o),c=O.readFileSync(o,"utf8");s.push({name:t,description:i,filename:r,size:a.size,tokens:_d(c)});}}catch{}}return s}function Sd(n,e){if(!Ts[n]){let i=Object.keys(Ts);return {found:false,content:"",error:`"${n}" is not a reference doc. Reference docs available via MCP: ${i.join(", ")}. Project-specific docs (patterns, troubleshooting, etc.) should be read from .paradigm/docs/ directly.`}}let s=Ho(e);if(!s)return {found:false,content:"",error:"Docs directory not found. Ensure @a-company/paradigm is installed."};let t=F.join(s,`${n}.md`);try{return O.existsSync(t)?{content:O.readFileSync(t,"utf8"),found:!0}:{found:!1,content:"",error:`Doc "${n}" file not found at expected location.`}}catch(i){return {found:false,content:"",error:`Error reading doc: ${i.message}`}}}function qo(){return [{uri:"paradigm://docs",name:"Reference Docs",description:"List reference documentation (commands, queries)",mimeType:"application/json"},{uri:"paradigm://docs/{name}",name:"Doc Content",description:"Get a reference doc. Available: commands, queries",mimeType:"text/markdown"}]}async function Mo(n,e){let s=`paradigm://${n}`;if(n==="docs"){let t=kd(e),i=t.reduce((a,c)=>a+c.size,0),r=t.reduce((a,c)=>a+c.tokens,0),o=JSON.stringify({count:t.length,totalSize:i,totalTokens:r,note:"These are reference docs served via MCP. Project-specific docs (patterns, troubleshooting, etc.) should be read from .paradigm/docs/ directly.",docs:t.map(a=>({name:a.name,description:a.description,size:a.size,tokens:a.tokens,uri:`paradigm://docs/${a.name}`}))},null,2);return p(o.length,s),{handled:true,text:o,mimeType:"application/json"}}if(n.startsWith("docs/")&&n!=="docs/"){let t=decodeURIComponent(n.replace("docs/","")),{content:i,found:r,error:o}=Sd(t,e);if(!r){let a=JSON.stringify({error:o,name:t},null,2);return p(a.length,s),{handled:true,text:a,mimeType:"application/json"}}return p(i.length,s),{handled:true,text:i,mimeType:"text/markdown"}}return {handled:false,text:"",mimeType:"application/json"}}var vn={logging:{description:"Paradigm logger usage, symbol-to-method mapping by directory",generate:()=>"# Paradigm Logging Guide\n\n**IMPORTANT:** Use the Paradigm logger instead of raw console.log/print.\n\n## Usage Pattern\n\n```typescript\nlog.component('#login-handler').info('Starting login', { email });\nlog.component('#database').debug('Query executed', { duration });\nlog.gate('^authenticated').warn('Access denied', { userId });\nlog.signal('!login-success').info('User authenticated');\nlog.flow('$checkout').info('Flow step reached');\nlog.aspect('~audit-required').info('Audit triggered');\n```\n\n## Symbol Mapping by Directory\n\n| Directory | Symbol | Logger Method |\n|-----------|--------|---------------|\n| `features/**` | `#` | `log.component()` |\n| `routes/**` | `#` | `log.component()` |\n| `api/**` | `#` | `log.component()` |\n| `endpoints/**` | `#` | `log.component()` |\n| `commands/**` | `#` | `log.component()` |\n| `models/**` | `#` | `log.component()` |\n| `components/**` | `#` | `log.component()` |\n| `lib/**` | `#` | `log.component()` |\n| `utils/**` | `#` | `log.component()` |\n| `services/**` | `#` | `log.component()` |\n| `core/**` | `#` | `log.component()` |\n| `drivers/**` | `#` | `log.component()` |\n| `systems/**` | `#` | `log.component()` |\n| `integrations/**` | `#` | `log.component()` |\n| `external/**` | `#` | `log.component()` |\n| `vendors/**` | `#` | `log.component()` |\n| `stores/**` | `#` | `log.component()` |\n| `state/**` | `#` | `log.component()` |\n| `reducers/**` | `#` | `log.component()` |\n| `config/**` | `#` | `log.component()` |\n| `middleware/**` | `^` | `log.gate()` |\n| `auth/**` | `^` | `log.gate()` |\n| `guards/**` | `^` | `log.gate()` |\n| `policies/**` | `^` | `log.gate()` |\n| `events/**` | `!` | `log.signal()` |\n| `handlers/**` | `!` | `log.signal()` |\n| `listeners/**` | `!` | `log.signal()` |\n| `hooks/**` | `!` | `log.signal()` |\n| `flows/**` | `$` | `log.flow()` |\n| `sagas/**` | `$` | `log.flow()` |\n| `workflows/**` | `$` | `log.flow()` |\n| `pipelines/**` | `$` | `log.flow()` |\n| `aspects/**` | `~` | `log.aspect()` |\n| `rules/**` | `~` | `log.aspect()` |\n| `constraints/**` | `~` | `log.aspect()` |\n\nSee `.paradigm/specs/logger.md` for full specification."},portal:{description:"Portal protocol \u2014 authorization, gates, portal.yaml structure and workflow",generate:()=>`# Portal Protocol (Authorization)
103
103
 
104
104
  **Portal.yaml is REQUIRED when the project has protected routes.**
105
105
 
@@ -455,7 +455,7 @@ components:
455
455
  | When | Tool | Purpose |
456
456
  |------|------|---------|
457
457
  | Starting any task | \`paradigm_pm_preflight\` | Get compliance plan |
458
- | Finishing any task | _(handled by stop hook)_ | Auto-checks compliance |`}};function xd(n){return Math.ceil(n.length/3.5)}function Lo(){return [{uri:"paradigm://guidance",name:"Guidance Topics",description:"List all available on-demand guidance topics (logging, portal, flows, orchestration, etc.)",mimeType:"application/json"},{uri:"paradigm://guidance/{topic}",name:"Guidance Content",description:`Get guidance for a topic. Available: ${Object.keys(vn).join(", ")}`,mimeType:"text/markdown"}]}async function Wo(n,e){let s=`paradigm://${n}`;if(n==="guidance"){let t=Object.entries(vn).map(([r,o])=>{let a=o.generate();return {name:r,description:o.description,tokens:xd(a)}}),i=JSON.stringify({count:t.length,totalTokens:t.reduce((r,o)=>r+o.tokens,0),note:"These guidance topics were previously baked into CLAUDE.md. Load on-demand to save context.",topics:t.map(r=>({...r,uri:`paradigm://guidance/${r.name}`}))},null,2);return p(i.length,s),{handled:true,text:i,mimeType:"application/json"}}if(n.startsWith("guidance/")&&n!=="guidance/"){let t=decodeURIComponent(n.replace("guidance/","")),i=vn[t];if(!i){let o=Object.keys(vn),a=JSON.stringify({error:`Unknown guidance topic: "${t}"`,available:o},null,2);return p(a.length,s),{handled:true,text:a,mimeType:"application/json"}}let r=i.generate();return p(r.length,s),{handled:true,text:r,mimeType:"text/markdown"}}return {handled:false,text:"",mimeType:"application/json"}}function Jo(n$1,e){n$1.setRequestHandler(ListResourcesRequestSchema,async()=>({resources:[{uri:"paradigm://symbols",name:"All Symbols",description:"Overview of all Paradigm symbols in the project",mimeType:"application/json"},{uri:"paradigm://symbols/type/feature",name:"Features",description:"All @feature symbols",mimeType:"application/json"},{uri:"paradigm://symbols/type/component",name:"Components",description:"All #component symbols",mimeType:"application/json"},{uri:"paradigm://symbols/type/gate",name:"Gates",description:"All ^gate symbols (authorization)",mimeType:"application/json"},{uri:"paradigm://symbols/type/flow",name:"Flows",description:"All $flow symbols (processes)",mimeType:"application/json"},{uri:"paradigm://symbols/type/signal",name:"Signals",description:"All !signal symbols (events)",mimeType:"application/json"},{uri:"paradigm://symbols/type/state",name:"States",description:"All %state symbols",mimeType:"application/json"},{uri:"paradigm://gates",name:"Gates (Detailed)",description:"All gates with locks, keys, and prizes from portal.yaml",mimeType:"application/json"},{uri:"paradigm://flows",name:"Flows (Detailed)",description:"All flows with gate sequences",mimeType:"application/json"},...Co(),...Ro(),...To(),...Io(),...No(),...qo(),...Lo()]})),n$1.setRequestHandler(ReadResourceRequestSchema,async s=>{let t=s.params.uri;if(!t?.startsWith("paradigm://"))throw new Error(`Unknown URI scheme: ${t}`);let i$1=e(),r=t.replace("paradigm://","");if(r==="symbols"){let o=m(i$1.index),a=n(i$1.index),c=JSON.stringify({project:i$1.projectName,counts:o,total:Object.values(o).reduce((l,d)=>l+d,0),symbols:a.map(l=>({symbol:l.symbol,type:l.type,description:l.description}))},null,2);return p(c.length,t),{contents:[{uri:t,mimeType:"application/json",text:c}]}}if(r.startsWith("symbol/")){let o=decodeURIComponent(r.replace("symbol/","")),a=h$1(i$1.index,o);if(!a){let l=JSON.stringify({error:"Symbol not found",symbol:o,available:n(i$1.index).filter(d=>d.symbol.includes(o.slice(1))).slice(0,5).map(d=>d.symbol)},null,2);return p(l.length,t),{contents:[{uri:t,mimeType:"application/json",text:l}]}}let c=JSON.stringify({symbol:a.symbol,type:a.type,description:a.description,filePath:a.filePath,references:a.references,referencedBy:a.referencedBy,tags:a.tags,data:a.data},null,2);return p(c.length,t),{contents:[{uri:t,mimeType:"application/json",text:c}]}}if(r.startsWith("symbols/type/")){let o=r.replace("symbols/type/",""),a=i(i$1.index,o),c=JSON.stringify({type:o,count:a.length,symbols:a.map(l=>({symbol:l.symbol,description:l.description,filePath:l.filePath,referencesCount:l.references.length,referencedByCount:l.referencedBy.length}))},null,2);return p(c.length,t),{contents:[{uri:t,mimeType:"application/json",text:c}]}}if(r==="gates"){let o=So(i$1),a=JSON.stringify({count:o.length,gates:o},null,2);return p(a.length,t),{contents:[{uri:t,mimeType:"application/json",text:a}]}}if(r==="flows"){let o=xo(i$1),a=JSON.stringify({count:o.length,flows:o},null,2);return p(a.length,t),{contents:[{uri:t,mimeType:"application/json",text:a}]}}if(r.startsWith("wisdom/")){let o=await Po(r,i$1);if(o.handled)return p(o.text.length),{contents:[{uri:t,mimeType:"application/json",text:o.text}]}}if(r.startsWith("history/")){let o=await jo(r,i$1);if(o.handled)return p(o.text.length),{contents:[{uri:t,mimeType:"application/json",text:o.text}]}}if(r.startsWith("context/")){let o=await Do(r);if(o.handled)return p(o.text.length),{contents:[{uri:t,mimeType:o.text.startsWith("#")?"text/markdown":"application/json",text:o.text}]}}if(r==="prompts"||r.startsWith("prompts/")){let o=await $o(r,i$1);if(o.handled)return {contents:[{uri:t,mimeType:o.mimeType,text:o.text}]}}if(r==="specs"||r.startsWith("specs/")){let o=await Eo(r,i$1);if(o.handled)return {contents:[{uri:t,mimeType:o.mimeType,text:o.text}]}}if(r==="docs"||r.startsWith("docs/")){let o=await Mo(r,i$1);if(o.handled)return {contents:[{uri:t,mimeType:o.mimeType,text:o.text}]}}if(r==="guidance"||r.startsWith("guidance/")){let o=await Wo(r);if(o.handled)return {contents:[{uri:t,mimeType:o.mimeType,text:o.text}]}}throw new Error(`Unknown resource: ${r}`)});}j();function Uo(){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 zo(n,e,s){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:i=true}=e,r=await se(s),o=po(r,t),a={symbols:t,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 t){let g=await a$1(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:t,id:i,symbols:r,description:o,reason:a,alternative:c,title:l,status:d,rationale:p,consequences:u,scope:g="project"}=e;if(t==="antipattern"){if(!o||!a||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let m={id:i,symbols:r,description:o,reason:a,alternative:c};return g==="global"?g$3(m):await uo(s.rootDir,m),Be(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:i,scope:g,message:`Antipattern recorded to ${g} scope`})}}if(t==="decision"){if(!l||!o||!p||!u)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};let m={id:i,title:l,status:d||"proposed",date:new Date().toISOString().split("T")[0],symbols:r,context:a||"",decision:o,rationale:p,consequences:u};return g==="global"?h$2(m):await go(s.rootDir,m),Be(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:i,scope:g,message:`Decision recorded to ${g} scope`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_promote":{let{type:t,id:i}=e,r=await se(s),o=F.basename(s.rootDir);if(t==="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$3({...a,learned_from:`promoted from ${o}`}),Be(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(t==="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),Be(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: ${t}`})}}case "paradigm_wisdom_expert":{let{symbol:t,area:i}=e;if(!t&&!i)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let r=await se(s),o=hn(r,{symbol:t,area:i});return {handled:true,text:JSON.stringify({query:{symbol:t,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 Bo(){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 Vo(n,e,s){switch(n){case "paradigm_history_context":{let{symbols:t}=e,i=await ke(s),r=yo(i,t),o={symbols:t,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:t.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:t,symbols:i,intent:r,description:o,commit:a,files:c,reason:l}=e,d=await Cs(s.rootDir,{type:t,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:t,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:t,result:i,tests:r}=e,o=await bo(s.rootDir,t||"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:t}=e,i=await ke(s),r=ho(i,t);return {handled:true,text:JSON.stringify({symbols:t,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:""}}}var Rd=".paradigm/navigator.yaml";async function Qo(n){let e=F.join(n,Rd);if(!O.existsSync(e))return {config:null,configPath:null};try{let s=O.readFileSync(e,"utf8");return {config:Z.load(s),configPath:e}}catch(s){return console.error("[navigator-loader] Error parsing navigator.yaml:",s),{config:null,configPath:e}}}function Xo(n,e,s){switch(e.intent){case "find":return jd(n,e.target||"");case "explore":return Td(n,e.target||"");case "context":return Dd(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function jd(n,e,s){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let i=n.symbols[e];if(i)t.paths.push(i),t.symbols.push(e),t.explanation=`Found symbol ${e} at ${i}`;else {let r=Object.entries(n.symbols).filter(([o])=>o.includes(e.slice(1))).slice(0,5);r.length>0?(t.paths=r.map(([,o])=>o),t.symbols=r.map(([o])=>o),t.explanation=`Found ${r.length} symbols matching "${e}"`):t.explanation=`Symbol ${e} not found in navigator`;}}else {let i=Object.entries(n.symbols).filter(([r])=>r.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(i.length>0)t.paths=i.map(([,r])=>r),t.symbols=i.map(([r])=>r),t.explanation=`Found ${i.length} symbols matching "${e}"`;else {let r=Ad(n,e);r?(t.paths=r.paths,t.explanation=`Found ${e} in structure: ${r.paths.join(", ")}`):t.explanation=`No matches found for "${e}"`;}}return t.suggested_order=Ds(t.paths,n),t}function Td(n,e,s){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},i=e.toLowerCase();for(let[r,o]of Object.entries(n.structure))if(o&&(r.toLowerCase().includes(i)||i.includes(r.toLowerCase()))){t.paths.push(...o.paths);let a=Object.entries(n.symbols).filter(([c])=>c.startsWith(o.symbol)).slice(0,10);t.symbols.push(...a.map(([c])=>c));}for(let[r,o]of Object.entries(n.key_files))r.toLowerCase().includes(i)&&t.paths.push(...o);if(t.paths.length===0){let r=Object.entries(n.symbols).filter(([o,a])=>o.toLowerCase().includes(i)||a.toLowerCase().includes(i)).slice(0,10);t.paths=[...new Set(r.map(([,o])=>o))],t.symbols=r.map(([o])=>o);}return t.explanation=`Exploration paths for "${e}": ${t.paths.length} locations, ${t.symbols.length} symbols`,t.suggested_order=Ds(t.paths,n),t}function Dd(n,e,s){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},i=e.toLowerCase(),r=Od(i);for(let[o,a]of Object.entries(n.structure))a&&r.some(c=>o.toLowerCase().includes(c))&&t.paths.push(...a.paths);for(let[o,a]of Object.entries(n.symbols)){let c=o.slice(1).toLowerCase();r.some(l=>c.includes(l)||l.includes(c))&&(t.paths.push(a),t.symbols.push(o));}return t.paths.push(...n.key_files.config),t.paths=[...new Set(t.paths)],t.symbols=[...new Set(t.symbols)],i.includes("test")?t.skip=n.skip_patterns.always:t.skip=[...n.skip_patterns.always,...n.skip_patterns.unless_testing],!i.includes("doc")&&!i.includes("readme")&&t.skip.push(...n.skip_patterns.unless_docs),t.explanation=`Context for "${e}": ${t.paths.length} relevant files, ${t.symbols.length} symbols`,t.suggested_order=Ds(t.paths,n),t}function Ad(n,e){let s=e.toLowerCase();for(let[t,i]of Object.entries(n.structure))if(i&&(t.toLowerCase().includes(s)||s.includes(t.toLowerCase())))return i;return null}function Od(n){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return n.split(/\s+/).map(s=>s.replace(/[^a-z0-9]/g,"")).filter(s=>s.length>2&&!e.has(s))}function Ds(n,e){let s={};for(let t of n){let i=0;e.key_files.config.some(r=>t.includes(r))&&(i+=100),e.key_files.entry.some(r=>t.includes(r))&&(i+=80),e.key_files.types.some(r=>t.includes(r))&&(i+=60),i-=t.split("/").length*2,s[t]=i;}return [...n].sort((t,i)=>(s[i]||0)-(s[t]||0))}var Id={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}};function Zo(){return [Id]}async function ea(n,e,s){if(n!=="paradigm_navigate")return {handled:false,text:""};let t={intent:e.intent||"find",target:e.target,task:e.task},i=await Qo(s.rootDir);if(i.config||(i={config:$d(s),configPath:null}),false);if(t.intent==="context"&&!t.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((t.intent==="find"||t.intent==="explore")&&!t.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${t.intent} intent`,example:t.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let r=`navigate:${t.intent}:${t.target||""}:${t.task||""}`,o=await v$2.getOrCompute(r,()=>{let c=Xo(i.config,t,s.rootDir),l={intent:t.intent,...t.target&&{target:t.target},...t.task&&{task:t.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(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(t.intent==="find"&&t.target&&c.paths.length===0){let d=jt(s.workspace,t.target);d.length>0&&(l.workspaceResults=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(t.intent==="context"&&t.task){let d=jt(s.workspace,t.task);d.length>0&&(l.workspaceContext=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})));}}return JSON.stringify(l,null,2)}),a=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{}return {handled:true,text:a}}function $d(n$1){let e={},s={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},t=n(n$1.index),i=new Set;for(let a of t)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 n$1.aggregation.purposeFiles)r.push(a.filePath);return r.push(".paradigm/config.yaml"),n$1.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 kn=null,As=false;function Fd(n){if(kn||(kn=new f$4),!As)try{let e=r$2();for(let s of e)try{kn.addPattern(s);}catch{}As=!0;}catch{As=true;}return kn}function ta(){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 na(n,e,s){let t=Fd(),i=new o$2(t);switch(n){case "paradigm_sentinel_triage":{let{symbol:r,status:o="all",environment:a,search:c,limit:l=10}=e,d=t.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=t.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=t.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 t.getIncident(r)?d?(t.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`})}):(t.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=t.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 t.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=t.recordIncident({error:r,symbols:o,environment:a,service:c,version:l,flowPosition:d}),u=t.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(t);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(t);if(r){let l=t.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=t.queryLogs({level:r,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:p,limit:u}),m=t.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=t.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?t.getAppState(r):t.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=t.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=t.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=t.aggregateMetric(r,{service:a,since:c});return {handled:true,text:JSON.stringify(u,null,2)}}let p=t.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=t.getTrace(r);return p?{handled:true,text:JSON.stringify(p,null,2)}:{handled:true,text:JSON.stringify({error:"Trace not found"})}}let d=t.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=t.getSchema(r);return a?{handled:true,text:JSON.stringify(a,null,2)}:{handled:true,text:JSON.stringify({error:`Schema "${r}" not found`})}}let o=t.listSchemas();return o.length===0?{handled:true,text:JSON.stringify({count:0,schemas:[],tip:"No event schemas registered yet. Applications register schemas via POST /api/schemas or SentinelWebClient.registerSchema()."},null,2)}:{handled:true,text:JSON.stringify({count:o.length,schemas:o.map(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=t.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=t.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:""}}}var Nd=30*1e3,sa=new Map;async function Cn(n){let e=F.resolve(n),s=sa.get(e);if(s&&Date.now()-s.loadedAt<Nd)return s.index;let t=await Ed(e);return t&&sa.set(e,{index:t,loadedAt:Date.now()}),t}async function Ed(n){let e=F.join(n,".paradigm","flow-index.json");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return JSON.parse(s)}catch(s){return console.error("[flow-loader] Error parsing flow-index.json:",s),null}}function Hd(n,e){let s=n.symbolToFlows[e]||[],t=[];for(let i of s){let r=n.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);t.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 t}function Pn(n,e){let s=Hd(n,e),t=new Set;for(let o of s)o.validation?.command&&t.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(t),suggestion:s.length>0?`Changes to ${e} may affect ${s.length} flow(s). ${t.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function ia(){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_validate",description:"Validate flow definitions against the codebase. Checks that gates exist in portal.yaml, actions are implemented, and signals are emitted. Returns per-step validation results with issue severity. ~200-400 tokens depending on flow size.",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 ra(n,e,s){switch(n){case "paradigm_flows_affected":{let{symbol:t,includeValidation:i=true}=e,r=await Cn(s.rootDir);if(!r)return {handled:true,text:JSON.stringify({error:"Flow index not found",symbol:t,suggestion:"Run `paradigm scan` to generate the flow index. Ensure .purpose files contain flows definitions.",example:`
458
+ | Finishing any task | _(handled by stop hook)_ | Auto-checks compliance |`}};function xd(n){return Math.ceil(n.length/3.5)}function Lo(){return [{uri:"paradigm://guidance",name:"Guidance Topics",description:"List all available on-demand guidance topics (logging, portal, flows, orchestration, etc.)",mimeType:"application/json"},{uri:"paradigm://guidance/{topic}",name:"Guidance Content",description:`Get guidance for a topic. Available: ${Object.keys(vn).join(", ")}`,mimeType:"text/markdown"}]}async function Wo(n,e){let s=`paradigm://${n}`;if(n==="guidance"){let t=Object.entries(vn).map(([r,o])=>{let a=o.generate();return {name:r,description:o.description,tokens:xd(a)}}),i=JSON.stringify({count:t.length,totalTokens:t.reduce((r,o)=>r+o.tokens,0),note:"These guidance topics were previously baked into CLAUDE.md. Load on-demand to save context.",topics:t.map(r=>({...r,uri:`paradigm://guidance/${r.name}`}))},null,2);return p(i.length,s),{handled:true,text:i,mimeType:"application/json"}}if(n.startsWith("guidance/")&&n!=="guidance/"){let t=decodeURIComponent(n.replace("guidance/","")),i=vn[t];if(!i){let o=Object.keys(vn),a=JSON.stringify({error:`Unknown guidance topic: "${t}"`,available:o},null,2);return p(a.length,s),{handled:true,text:a,mimeType:"application/json"}}let r=i.generate();return p(r.length,s),{handled:true,text:r,mimeType:"text/markdown"}}return {handled:false,text:"",mimeType:"application/json"}}function Jo(n$1,e){n$1.setRequestHandler(ListResourcesRequestSchema,async()=>({resources:[{uri:"paradigm://symbols",name:"All Symbols",description:"Overview of all Paradigm symbols in the project",mimeType:"application/json"},{uri:"paradigm://symbols/type/feature",name:"Features",description:"All @feature symbols",mimeType:"application/json"},{uri:"paradigm://symbols/type/component",name:"Components",description:"All #component symbols",mimeType:"application/json"},{uri:"paradigm://symbols/type/gate",name:"Gates",description:"All ^gate symbols (authorization)",mimeType:"application/json"},{uri:"paradigm://symbols/type/flow",name:"Flows",description:"All $flow symbols (processes)",mimeType:"application/json"},{uri:"paradigm://symbols/type/signal",name:"Signals",description:"All !signal symbols (events)",mimeType:"application/json"},{uri:"paradigm://symbols/type/state",name:"States",description:"All %state symbols",mimeType:"application/json"},{uri:"paradigm://gates",name:"Gates (Detailed)",description:"All gates with locks, keys, and prizes from portal.yaml",mimeType:"application/json"},{uri:"paradigm://flows",name:"Flows (Detailed)",description:"All flows with gate sequences",mimeType:"application/json"},...Co(),...Ro(),...To(),...Io(),...Eo(),...qo(),...Lo()]})),n$1.setRequestHandler(ReadResourceRequestSchema,async s=>{let t=s.params.uri;if(!t?.startsWith("paradigm://"))throw new Error(`Unknown URI scheme: ${t}`);let i$1=e(),r=t.replace("paradigm://","");if(r==="symbols"){let o=m(i$1.index),a=n(i$1.index),c=JSON.stringify({project:i$1.projectName,counts:o,total:Object.values(o).reduce((l,d)=>l+d,0),symbols:a.map(l=>({symbol:l.symbol,type:l.type,description:l.description}))},null,2);return p(c.length,t),{contents:[{uri:t,mimeType:"application/json",text:c}]}}if(r.startsWith("symbol/")){let o=decodeURIComponent(r.replace("symbol/","")),a=h$1(i$1.index,o);if(!a){let l=JSON.stringify({error:"Symbol not found",symbol:o,available:n(i$1.index).filter(d=>d.symbol.includes(o.slice(1))).slice(0,5).map(d=>d.symbol)},null,2);return p(l.length,t),{contents:[{uri:t,mimeType:"application/json",text:l}]}}let c=JSON.stringify({symbol:a.symbol,type:a.type,description:a.description,filePath:a.filePath,references:a.references,referencedBy:a.referencedBy,tags:a.tags,data:a.data},null,2);return p(c.length,t),{contents:[{uri:t,mimeType:"application/json",text:c}]}}if(r.startsWith("symbols/type/")){let o=r.replace("symbols/type/",""),a=i(i$1.index,o),c=JSON.stringify({type:o,count:a.length,symbols:a.map(l=>({symbol:l.symbol,description:l.description,filePath:l.filePath,referencesCount:l.references.length,referencedByCount:l.referencedBy.length}))},null,2);return p(c.length,t),{contents:[{uri:t,mimeType:"application/json",text:c}]}}if(r==="gates"){let o=So(i$1),a=JSON.stringify({count:o.length,gates:o},null,2);return p(a.length,t),{contents:[{uri:t,mimeType:"application/json",text:a}]}}if(r==="flows"){let o=xo(i$1),a=JSON.stringify({count:o.length,flows:o},null,2);return p(a.length,t),{contents:[{uri:t,mimeType:"application/json",text:a}]}}if(r.startsWith("wisdom/")){let o=await Po(r,i$1);if(o.handled)return p(o.text.length),{contents:[{uri:t,mimeType:"application/json",text:o.text}]}}if(r.startsWith("history/")){let o=await jo(r,i$1);if(o.handled)return p(o.text.length),{contents:[{uri:t,mimeType:"application/json",text:o.text}]}}if(r.startsWith("context/")){let o=await Do(r);if(o.handled)return p(o.text.length),{contents:[{uri:t,mimeType:o.text.startsWith("#")?"text/markdown":"application/json",text:o.text}]}}if(r==="prompts"||r.startsWith("prompts/")){let o=await $o(r,i$1);if(o.handled)return {contents:[{uri:t,mimeType:o.mimeType,text:o.text}]}}if(r==="specs"||r.startsWith("specs/")){let o=await No(r,i$1);if(o.handled)return {contents:[{uri:t,mimeType:o.mimeType,text:o.text}]}}if(r==="docs"||r.startsWith("docs/")){let o=await Mo(r,i$1);if(o.handled)return {contents:[{uri:t,mimeType:o.mimeType,text:o.text}]}}if(r==="guidance"||r.startsWith("guidance/")){let o=await Wo(r);if(o.handled)return {contents:[{uri:t,mimeType:o.mimeType,text:o.text}]}}throw new Error(`Unknown resource: ${r}`)});}j();function Uo(){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 zo(n,e,s){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:i=true}=e,r=await se(s),o=po(r,t),a={symbols:t,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 t){let g=await a$1(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:t,id:i,symbols:r,description:o,reason:a,alternative:c,title:l,status:d,rationale:p,consequences:u,scope:g="project"}=e;if(t==="antipattern"){if(!o||!a||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let m={id:i,symbols:r,description:o,reason:a,alternative:c};return g==="global"?g$3(m):await uo(s.rootDir,m),Be(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:i,scope:g,message:`Antipattern recorded to ${g} scope`})}}if(t==="decision"){if(!l||!o||!p||!u)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};let m={id:i,title:l,status:d||"proposed",date:new Date().toISOString().split("T")[0],symbols:r,context:a||"",decision:o,rationale:p,consequences:u};return g==="global"?h$2(m):await go(s.rootDir,m),Be(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:i,scope:g,message:`Decision recorded to ${g} scope`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_promote":{let{type:t,id:i}=e,r=await se(s),o=F.basename(s.rootDir);if(t==="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$3({...a,learned_from:`promoted from ${o}`}),Be(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(t==="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),Be(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: ${t}`})}}case "paradigm_wisdom_expert":{let{symbol:t,area:i}=e;if(!t&&!i)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let r=await se(s),o=hn(r,{symbol:t,area:i});return {handled:true,text:JSON.stringify({query:{symbol:t,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 Bo(){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 Vo(n,e,s){switch(n){case "paradigm_history_context":{let{symbols:t}=e,i=await ke(s),r=yo(i,t),o={symbols:t,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:t.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:t,symbols:i,intent:r,description:o,commit:a,files:c,reason:l}=e,d=await Cs(s.rootDir,{type:t,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:t,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:t,result:i,tests:r}=e,o=await bo(s.rootDir,t||"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:t}=e,i=await ke(s),r=ho(i,t);return {handled:true,text:JSON.stringify({symbols:t,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:""}}}var Rd=".paradigm/navigator.yaml";async function Qo(n){let e=F.join(n,Rd);if(!O.existsSync(e))return {config:null,configPath:null};try{let s=O.readFileSync(e,"utf8");return {config:Z.load(s),configPath:e}}catch(s){return console.error("[navigator-loader] Error parsing navigator.yaml:",s),{config:null,configPath:e}}}function Xo(n,e,s){switch(e.intent){case "find":return jd(n,e.target||"");case "explore":return Td(n,e.target||"");case "context":return Dd(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function jd(n,e,s){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let i=n.symbols[e];if(i)t.paths.push(i),t.symbols.push(e),t.explanation=`Found symbol ${e} at ${i}`;else {let r=Object.entries(n.symbols).filter(([o])=>o.includes(e.slice(1))).slice(0,5);r.length>0?(t.paths=r.map(([,o])=>o),t.symbols=r.map(([o])=>o),t.explanation=`Found ${r.length} symbols matching "${e}"`):t.explanation=`Symbol ${e} not found in navigator`;}}else {let i=Object.entries(n.symbols).filter(([r])=>r.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(i.length>0)t.paths=i.map(([,r])=>r),t.symbols=i.map(([r])=>r),t.explanation=`Found ${i.length} symbols matching "${e}"`;else {let r=Ad(n,e);r?(t.paths=r.paths,t.explanation=`Found ${e} in structure: ${r.paths.join(", ")}`):t.explanation=`No matches found for "${e}"`;}}return t.suggested_order=Ds(t.paths,n),t}function Td(n,e,s){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},i=e.toLowerCase();for(let[r,o]of Object.entries(n.structure))if(o&&(r.toLowerCase().includes(i)||i.includes(r.toLowerCase()))){t.paths.push(...o.paths);let a=Object.entries(n.symbols).filter(([c])=>c.startsWith(o.symbol)).slice(0,10);t.symbols.push(...a.map(([c])=>c));}for(let[r,o]of Object.entries(n.key_files))r.toLowerCase().includes(i)&&t.paths.push(...o);if(t.paths.length===0){let r=Object.entries(n.symbols).filter(([o,a])=>o.toLowerCase().includes(i)||a.toLowerCase().includes(i)).slice(0,10);t.paths=[...new Set(r.map(([,o])=>o))],t.symbols=r.map(([o])=>o);}return t.explanation=`Exploration paths for "${e}": ${t.paths.length} locations, ${t.symbols.length} symbols`,t.suggested_order=Ds(t.paths,n),t}function Dd(n,e,s){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},i=e.toLowerCase(),r=Od(i);for(let[o,a]of Object.entries(n.structure))a&&r.some(c=>o.toLowerCase().includes(c))&&t.paths.push(...a.paths);for(let[o,a]of Object.entries(n.symbols)){let c=o.slice(1).toLowerCase();r.some(l=>c.includes(l)||l.includes(c))&&(t.paths.push(a),t.symbols.push(o));}return t.paths.push(...n.key_files.config),t.paths=[...new Set(t.paths)],t.symbols=[...new Set(t.symbols)],i.includes("test")?t.skip=n.skip_patterns.always:t.skip=[...n.skip_patterns.always,...n.skip_patterns.unless_testing],!i.includes("doc")&&!i.includes("readme")&&t.skip.push(...n.skip_patterns.unless_docs),t.explanation=`Context for "${e}": ${t.paths.length} relevant files, ${t.symbols.length} symbols`,t.suggested_order=Ds(t.paths,n),t}function Ad(n,e){let s=e.toLowerCase();for(let[t,i]of Object.entries(n.structure))if(i&&(t.toLowerCase().includes(s)||s.includes(t.toLowerCase())))return i;return null}function Od(n){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return n.split(/\s+/).map(s=>s.replace(/[^a-z0-9]/g,"")).filter(s=>s.length>2&&!e.has(s))}function Ds(n,e){let s={};for(let t of n){let i=0;e.key_files.config.some(r=>t.includes(r))&&(i+=100),e.key_files.entry.some(r=>t.includes(r))&&(i+=80),e.key_files.types.some(r=>t.includes(r))&&(i+=60),i-=t.split("/").length*2,s[t]=i;}return [...n].sort((t,i)=>(s[i]||0)-(s[t]||0))}var Id={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}};function Zo(){return [Id]}async function ea(n,e,s){if(n!=="paradigm_navigate")return {handled:false,text:""};let t={intent:e.intent||"find",target:e.target,task:e.task},i=await Qo(s.rootDir);if(i.config||(i={config:$d(s),configPath:null}),false);if(t.intent==="context"&&!t.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((t.intent==="find"||t.intent==="explore")&&!t.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${t.intent} intent`,example:t.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let r=`navigate:${t.intent}:${t.target||""}:${t.task||""}`,o=await v$2.getOrCompute(r,()=>{let c=Xo(i.config,t,s.rootDir),l={intent:t.intent,...t.target&&{target:t.target},...t.task&&{task:t.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(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(t.intent==="find"&&t.target&&c.paths.length===0){let d=jt(s.workspace,t.target);d.length>0&&(l.workspaceResults=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(t.intent==="context"&&t.task){let d=jt(s.workspace,t.task);d.length>0&&(l.workspaceContext=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})));}}return JSON.stringify(l,null,2)}),a=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{}return {handled:true,text:a}}function $d(n$1){let e={},s={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},t=n(n$1.index),i=new Set;for(let a of t)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 n$1.aggregation.purposeFiles)r.push(a.filePath);return r.push(".paradigm/config.yaml"),n$1.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 kn=null,As=false;function Fd(n){if(kn||(kn=new f$4),!As)try{let e=r$2();for(let s of e)try{kn.addPattern(s);}catch{}As=!0;}catch{As=true;}return kn}function ta(){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 na(n,e,s){let t=Fd(),i=new o$2(t);switch(n){case "paradigm_sentinel_triage":{let{symbol:r,status:o="all",environment:a,search:c,limit:l=10}=e,d=t.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=t.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=t.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 t.getIncident(r)?d?(t.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`})}):(t.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=t.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 t.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=t.recordIncident({error:r,symbols:o,environment:a,service:c,version:l,flowPosition:d}),u=t.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(t);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(t);if(r){let l=t.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=t.queryLogs({level:r,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:p,limit:u}),m=t.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=t.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?t.getAppState(r):t.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=t.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=t.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=t.aggregateMetric(r,{service:a,since:c});return {handled:true,text:JSON.stringify(u,null,2)}}let p=t.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=t.getTrace(r);return p?{handled:true,text:JSON.stringify(p,null,2)}:{handled:true,text:JSON.stringify({error:"Trace not found"})}}let d=t.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=t.getSchema(r);return a?{handled:true,text:JSON.stringify(a,null,2)}:{handled:true,text:JSON.stringify({error:`Schema "${r}" not found`})}}let o=t.listSchemas();return o.length===0?{handled:true,text:JSON.stringify({count:0,schemas:[],tip:"No event schemas registered yet. Applications register schemas via POST /api/schemas or SentinelWebClient.registerSchema()."},null,2)}:{handled:true,text:JSON.stringify({count:o.length,schemas:o.map(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=t.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=t.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:""}}}var Ed=30*1e3,sa=new Map;async function Cn(n){let e=F.resolve(n),s=sa.get(e);if(s&&Date.now()-s.loadedAt<Ed)return s.index;let t=await Nd(e);return t&&sa.set(e,{index:t,loadedAt:Date.now()}),t}async function Nd(n){let e=F.join(n,".paradigm","flow-index.json");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return JSON.parse(s)}catch(s){return console.error("[flow-loader] Error parsing flow-index.json:",s),null}}function Hd(n,e){let s=n.symbolToFlows[e]||[],t=[];for(let i of s){let r=n.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);t.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 t}function Pn(n,e){let s=Hd(n,e),t=new Set;for(let o of s)o.validation?.command&&t.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(t),suggestion:s.length>0?`Changes to ${e} may affect ${s.length} flow(s). ${t.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function ia(){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_validate",description:"Validate flow definitions against the codebase. Checks that gates exist in portal.yaml, actions are implemented, and signals are emitted. Returns per-step validation results with issue severity. ~200-400 tokens depending on flow size.",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 ra(n,e,s){switch(n){case "paradigm_flows_affected":{let{symbol:t,includeValidation:i=true}=e,r=await Cn(s.rootDir);if(!r)return {handled:true,text:JSON.stringify({error:"Flow index not found",symbol:t,suggestion:"Run `paradigm scan` to generate the flow index. Ensure .purpose files contain flows definitions.",example:`
459
459
  flows:
460
460
  $task-creation:
461
461
  description: "Full task creation flow"
@@ -512,7 +512,7 @@ payloads:
512
512
  createTask:
513
513
  title: "New Task"
514
514
  description: "Task description"
515
- `},null,2)};if(!t){let c=Fs(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&&t!=="all"){let c=la(r,t,i);if(!c){let d=Fs(r);return {handled:true,text:JSON.stringify({error:`Fixture "${i}" not found in category "${t}"`,availableInCategory:d[t]||[]},null,2)}}return {handled:true,text:JSON.stringify(c,null,2)}}let o=$s(r,t);return {handled:true,text:JSON.stringify(o,null,2)}}default:return {handled:false,text:""}}}v();var Wd=/[@#$%^!?&~][a-zA-Z0-9_-]+/g;var Tt={architect:"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",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"},Tn={"tier-1":"opus","tier-2":"sonnet","tier-3":"haiku"};function fa(n,e,s){try{let i=F.join(e,".paradigm","config.yaml");if(O.existsSync(i)){let o=Z.load(O.readFileSync(i,"utf8"))?.["model-resolution"];if(o){let a=s?.modelTier||Tt[n]||"tier-2";if(o[a])return o[a]}}}catch{}if(s?.defaultModel)return s.defaultModel;let t=Tt[n]||"tier-2";return Tn[t]||"sonnet"}var Jd={architect:{min:5e3,max:2e4},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.
515
+ `},null,2)};if(!t){let c=Fs(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&&t!=="all"){let c=la(r,t,i);if(!c){let d=Fs(r);return {handled:true,text:JSON.stringify({error:`Fixture "${i}" not found in category "${t}"`,availableInCategory:d[t]||[]},null,2)}}return {handled:true,text:JSON.stringify(c,null,2)}}let o=$s(r,t);return {handled:true,text:JSON.stringify(o,null,2)}}default:return {handled:false,text:""}}}v();var Wd=/[@#$%^!?&~][a-zA-Z0-9_-]+/g;var Tt={architect:"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"},Tn={"tier-1":"opus","tier-2":"sonnet","tier-3":"haiku"};function fa(n,e,s){try{let i=F.join(e,".paradigm","config.yaml");if(O.existsSync(i)){let o=Z.load(O.readFileSync(i,"utf8"))?.["model-resolution"];if(o){let a=s?.modelTier||Tt[n]||"tier-2";if(o[a])return o[a]}}}catch{}if(s?.defaultModel)return s.defaultModel;let t=Tt[n]||"tier-2";return Tn[t]||"sonnet"}var Jd={architect:{min:5e3,max:2e4},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.
516
516
 
517
517
  ## Your Role
518
518
  You design system architecture, write specifications, and plan features.
@@ -689,7 +689,45 @@ Other agents focus on their domain \u2014 you handle all Paradigm compliance.
689
689
  - Modify source code (.ts, .js, .py, .rs files)
690
690
  - Write implementation code
691
691
  - Change application logic
692
- - Skip .purpose coverage for new code directories`,advocate:`You are the ADVOCATE agent (Jinx).
692
+ - Skip .purpose coverage for new code directories`,compliance:`You are the COMPLIANCE agent (Rune).
693
+
694
+ ## Your Role
695
+ You plan symbols before implementation and validate coverage after.
696
+ You are the Paradigm symbol system expert. You ensure every component has
697
+ aspects, every multi-step process has a flow, every event has a signal,
698
+ and every aspect has a valid anchor.
699
+
700
+ ## When You Run
701
+ 1. BEFORE the builder: create the symbol skeleton from the architect's plan
702
+ 2. AFTER the builder: validate symbol coverage and produce a compliance report
703
+
704
+ ## Key Responsibilities
705
+ 1. Enumerate all symbols needed for the planned work
706
+ 2. Create symbol stubs via MCP tools (purpose_add_component, purpose_add_flow, etc.)
707
+ 3. Enforce 1:1 minimum component-to-aspect ratio
708
+ 4. Create $flows when logic spans 3+ components
709
+ 5. Create !signals for events that trigger side effects
710
+ 6. Validate aspect anchors after implementation
711
+ 7. Produce a Symbol Plan (pre-build) and Compliance Report (post-build)
712
+
713
+ ## What You Produce
714
+ - **Symbol Plan**: list of every #component, $flow, !signal, ~aspect to create
715
+ - **Compliance Report**: coverage ratios, anchor integrity, blocking findings
716
+
717
+ ## What You ONLY Use
718
+ - paradigm_search, paradigm_ripple, paradigm_status
719
+ - paradigm_purpose_init / paradigm_purpose_add_component / paradigm_purpose_add_flow
720
+ - paradigm_purpose_add_signal / paradigm_purpose_add_aspect / paradigm_purpose_add_gate
721
+ - paradigm_purpose_validate / paradigm_purpose_link
722
+ - paradigm_aspect_check / paradigm_aspect_drift / paradigm_aspect_confirm
723
+ - paradigm_flow_validate / paradigm_flows_affected
724
+ - paradigm_reindex
725
+
726
+ ## What You NEVER Do
727
+ - Modify source code (.ts, .swift, .js, .py files)
728
+ - Write implementation code
729
+ - Skip the pre-build symbol plan
730
+ - Approve code with missing aspects (1:1 ratio is mandatory)`,advocate:`You are the ADVOCATE agent (Jinx).
693
731
 
694
732
  ## Your Role
695
733
  You are the devil's advocate \u2014 you stress-test assumptions, find edge cases,
@@ -730,13 +768,13 @@ Examples:
730
768
  - "Fix the login bug" \u2192 quick (greenlight or escalate)
731
769
  - "Add user authentication with JWT" \u2192 plan \u2192 architect + security + builder + tester
732
770
  - "Should I use soft delete or hard delete?" \u2192 plan \u2192 architect only (analysis)
733
- - "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}},{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","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 ha(n,e,s){return n==="paradigm_orchestrate_inline"?Gd(e,s):n==="paradigm_agent_prompt"?zd(e,s):{handled:false,text:""}}async function Gd(n,e){let s=n.task,t=n.mode||"execute",i=n.agents;try{let b=F.join(e.rootDir,".paradigm",".orchestrated");O.writeFileSync(b,new Date().toISOString(),"utf8");}catch{}let r=va(e.rootDir);if(!r){let b=JSON.stringify({error:"No agents.yaml found",suggestion:"Run `paradigm team init` to set up multi-agent orchestration"},null,2);return o(b.length,"paradigm_orchestrate_inline"),{handled:true,text:b}}let o$1=b$7(e.rootDir);if(o$1&&r.agents){let b={};for(let[h,w]of Object.entries(r.agents))o$1.includes(h)&&(b[h]=w);r.agents=b;}let a=Ot(s),c=[];try{let{processPendingEvents:b,loadNominations:h}=await import('./nomination-engine-LMSZ2CAS.js');b(e.rootDir),c=h(e.rootDir,{pending_only:!0,limit:10}).filter(_=>_.urgency==="high"||_.urgency==="critical").map(_=>({agent:_.agent,urgency:_.urgency,brief:_.brief}));}catch{}let l=tp(s);if(t==="quick")return Ud(s,a,l,c,r,e);let d=Vd(s,r.agents,i,l,r.orchestration);if(t==="plan"){let b=sp(s,r.agents),h=np(d,l),w;try{let{loadNotebookEntries:x}=await import('./notebook-loader-CENTDDUJ.js'),C=a.map(P=>P.replace(/^[#$^!~@&%?]/,"").toLowerCase()),T={},j=new Set;for(let P of d.stages)for(let D of P.agents){if(j.has(D.name))continue;j.add(D.name);let I=x(D.name,e.rootDir),A=C.length>0?x(D.name,e.rootDir,{concepts:C}):I;I.length>0&&(T[D.name]={totalEntries:I.length,relevantEntries:A.length});}Object.keys(T).length>0&&(w=T);}catch{}let _=d.stages.flatMap(x=>x.agents.map(C=>C.name)),k=ba(_,r.agents),v=k.length>0?{edges:k,note:"Shows which agents hand off to which based on agents.yaml handoff_to. Stage ordering was derived from this graph."}:void 0,S=JSON.stringify({task:s,mode:"plan",classification:{type:l.type,complexity:l.complexity,securityRequired:l.securityRequired,costMultiplier:l.costMultiplier},plan:d,suggestedAgents:b,costPreview:h,...v?{collaborationGraph:v}:{},...w?{notebookKnowledge:w,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",...v?["Review collaboration graph \u2014 stage ordering was derived from agent handoff_to edges"]:[],...w?["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(S.length,"paradigm_orchestrate_inline"),{handled:true,text:S}}let p=new Map;try{let{loadAgentProfile:b,buildProfileEnrichment:h}=await import('./agent-loader-CZFB5BDP.js'),{loadDecisions:w}=await import('./decision-loader-2XPZE4EZ.js'),{loadJournalEntries:_}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:k}=await import('./nomination-engine-LMSZ2CAS.js'),{loadAgentState:v}=await import('./agent-state-KSQ3S7OB.js'),{loadNotebookEntries:S}=await import('./notebook-loader-CENTDDUJ.js'),x=w(e.rootDir,{status:"active",limit:5}).map(j=>({title:j.title,decision:j.decision.slice(0,150)})),C=k(e.rootDir,{pending_only:!0,limit:10}).map(j=>({urgency:j.urgency,brief:j.brief})),T=a.map(j=>j.replace(/^[#$^!~@&%?]/,"").toLowerCase());for(let j of d.stages)for(let P of j.agents)if(!p.has(P.name)){let D=b(e.rootDir,P.name);if(D){if(D.benched)continue;let I=_(P.name,{transferable:!0,limit:5}).map(q=>({trigger:q.trigger,insight:q.insight.slice(0,150)})),A=v(P.name,e.rootDir),N;try{let q=S(P.name,e.rootDir,T.length>0?{concepts:T}:void 0);q.length>0&&(N=q.sort((et,hi)=>hi.confidence-et.confidence||new Date(hi.updated).getTime()-new Date(et.updated).getTime()).slice(0,5).map(et=>({context:et.context,snippet:et.snippet,concepts:et.concepts})));}catch{}let H=h(D,a,N,{recentDecisions:x,journalInsights:I,pendingNominations:C},A?{lastSession:A.lastSession,pendingWork:A.pendingWork,recentPatterns:A.recentPatterns,sessionsOnProject:A.sessionsOnProject}:void 0);if(D.permissions){let q=[`
771
+ - "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}},{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","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 ha(n,e,s){return n==="paradigm_orchestrate_inline"?Gd(e,s):n==="paradigm_agent_prompt"?zd(e,s):{handled:false,text:""}}async function Gd(n,e){let s=n.task,t=n.mode||"execute",i=n.agents;try{let b=F.join(e.rootDir,".paradigm",".orchestrated");O.writeFileSync(b,new Date().toISOString(),"utf8");}catch{}let r=va(e.rootDir);if(!r){let b=JSON.stringify({error:"No agents.yaml found",suggestion:"Run `paradigm team init` to set up multi-agent orchestration"},null,2);return o(b.length,"paradigm_orchestrate_inline"),{handled:true,text:b}}let o$1=b$7(e.rootDir);if(o$1&&r.agents){let b={};for(let[h,w]of Object.entries(r.agents))o$1.includes(h)&&(b[h]=w);r.agents=b;}let a=Ot(s),c=[];try{let{processPendingEvents:b,loadNominations:h}=await import('./nomination-engine-LMSZ2CAS.js');b(e.rootDir),c=h(e.rootDir,{pending_only:!0,limit:10}).filter(_=>_.urgency==="high"||_.urgency==="critical").map(_=>({agent:_.agent,urgency:_.urgency,brief:_.brief}));}catch{}let l=tp(s);if(t==="quick")return Ud(s,a,l,c,r,e);let d=Vd(s,r.agents,i,l,r.orchestration);if(t==="plan"){let b=sp(s,r.agents),h=np(d,l),w;try{let{loadNotebookEntries:x}=await import('./notebook-loader-CENTDDUJ.js'),C=a.map(P=>P.replace(/^[#$^!~@&%?]/,"").toLowerCase()),T={},j=new Set;for(let P of d.stages)for(let D of P.agents){if(j.has(D.name))continue;j.add(D.name);let I=x(D.name,e.rootDir),A=C.length>0?x(D.name,e.rootDir,{concepts:C}):I;I.length>0&&(T[D.name]={totalEntries:I.length,relevantEntries:A.length});}Object.keys(T).length>0&&(w=T);}catch{}let _=d.stages.flatMap(x=>x.agents.map(C=>C.name)),k=ba(_,r.agents),v=k.length>0?{edges:k,note:"Shows which agents hand off to which based on agents.yaml handoff_to. Stage ordering was derived from this graph."}:void 0,S=JSON.stringify({task:s,mode:"plan",classification:{type:l.type,complexity:l.complexity,securityRequired:l.securityRequired,costMultiplier:l.costMultiplier},plan:d,suggestedAgents:b,costPreview:h,...v?{collaborationGraph:v}:{},...w?{notebookKnowledge:w,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",...v?["Review collaboration graph \u2014 stage ordering was derived from agent handoff_to edges"]:[],...w?["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(S.length,"paradigm_orchestrate_inline"),{handled:true,text:S}}let p=new Map;try{let{loadAgentProfile:b,buildProfileEnrichment:h}=await import('./agent-loader-CZFB5BDP.js'),{loadDecisions:w}=await import('./decision-loader-2XPZE4EZ.js'),{loadJournalEntries:_}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:k}=await import('./nomination-engine-LMSZ2CAS.js'),{loadAgentState:v}=await import('./agent-state-KSQ3S7OB.js'),{loadNotebookEntries:S}=await import('./notebook-loader-CENTDDUJ.js'),x=w(e.rootDir,{status:"active",limit:5}).map(j=>({title:j.title,decision:j.decision.slice(0,150)})),C=k(e.rootDir,{pending_only:!0,limit:10}).map(j=>({urgency:j.urgency,brief:j.brief})),T=a.map(j=>j.replace(/^[#$^!~@&%?]/,"").toLowerCase());for(let j of d.stages)for(let P of j.agents)if(!p.has(P.name)){let D=b(e.rootDir,P.name);if(D){if(D.benched)continue;let I=_(P.name,{transferable:!0,limit:5}).map(q=>({trigger:q.trigger,insight:q.insight.slice(0,150)})),A=v(P.name,e.rootDir),E;try{let q=S(P.name,e.rootDir,T.length>0?{concepts:T}:void 0);q.length>0&&(E=q.sort((et,hi)=>hi.confidence-et.confidence||new Date(hi.updated).getTime()-new Date(et.updated).getTime()).slice(0,5).map(et=>({context:et.context,snippet:et.snippet,concepts:et.concepts})));}catch{}let H=h(D,a,E,{recentDecisions:x,journalInsights:I,pendingNominations:C},A?{lastSession:A.lastSession,pendingWork:A.pendingWork,recentPatterns:A.recentPatterns,sessionsOnProject:A.sessionsOnProject}:void 0);if(D.permissions){let q=[`
734
772
  ## Permission Constraints`];D.permissions.paths?.deny?.length&&q.push(`**Denied paths:** ${D.permissions.paths.deny.join(", ")}`),D.permissions.paths?.write?.length&&q.push(`**Writable paths:** ${D.permissions.paths.write.join(", ")}`),D.permissions.tools?.deny?.length&&q.push(`**Denied tools:** ${D.permissions.tools.deny.join(", ")}`),D.permissions.dangerous_actions?.length&&q.push(`**Requires approval for:** ${D.permissions.dangerous_actions.join(", ")}`),H+=`
735
773
  `+q.join(`
736
- `);}H.trim()&&p.set(P.name,{enrichment:H,nickname:D.nickname});}}}catch{}let u=[];for(let b of d.stages){let h=[];for(let w of b.agents){let _=r.agents[w.name],k={name:_?.name||w.name,role:_?.role||Dt[w.name]||`${w.name} agent`,focus:_?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:fa(w.name,e.rootDir,_),triggers:_?.triggers,handoff_to:_?.handoff_to,context:_?.context,protocol:_?.protocol},v=p.get(w.name),S=wa({agent:k,task:w.task,symbols:a,dependsOn:w.dependsOn,profileEnrichment:v?.enrichment,nickname:v?.nickname});h.push(S);}u.push({stage:b.stage,canRunParallel:b.canRunParallel,agents:h});}let g=`orch-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`;ip(e.rootDir,g,s,d);try{let{appendSessionWorkEntry:b}=await import('./session-work-log-5PHOUEQ6.js');for(let h of u)for(let w of h.agents)b(e.rootDir,{timestamp:new Date().toISOString(),type:"agent-contribution",agent:w.agent,contribution:w.taskDescription?.slice(0,200)||s.slice(0,200),attribution:w.attribution,symbols:a});}catch{}try{let{recordAgentSession:b}=await import('./agent-state-KSQ3S7OB.js'),w=(await import('./session-tracker-FDFL4PZI.js')).default?.session?.sessionId||g;for(let _ of u)for(let k of _.agents)b(k.agent,e.rootDir,{sessionId:w,summary:`${k.attribution||k.agent}: ${(k.taskDescription||s).slice(0,200)}`,symbolsTouched:a});}catch{}let m=`thr-orch-${g}`;try{let b=await import('./symphony-loader-XJT43FOS.js'),h=F.basename(e.rootDir),w=`${h}/maestro`;try{b.getMyIdentity(e.rootDir)||b.registerAgent(e.rootDir,"maestro","Maestro (orchestrator)");}catch{}b.createThread(`Orchestration: ${s.slice(0,80)}`,{id:w,name:"Maestro",type:"agent",project:h,role:"orchestrator"});let _=F.join(ma.homedir(),".paradigm","score","threads"),k=O.readdirSync(_).filter(S=>S.endsWith(".json")).sort(),v=k[k.length-1];if(v){let S=F.join(_,v),x=F.join(_,`${m}.json`),C=JSON.parse(O.readFileSync(S,"utf8"));C.id=m,O.writeFileSync(x,JSON.stringify(C,null,2),"utf8"),S!==x&&O.unlinkSync(S);}for(let S of u)for(let x of S.agents){let C=b.buildMessage({threadRoot:m,sender:{id:w,name:"Maestro",type:"agent",project:h,role:"orchestrator"},intent:"task",text:`[Maestro] Stage ${S.stage}: Assigned to ${x.attribution||x.agent} \u2014 ${x.taskDescription||s}`,symbols:a,metadata:{task:{stage:S.stage,canRunParallel:S.canRunParallel}}});b.routeMessage(C);}}catch{}let y={orchestrationId:g,task:s,mode:"execute",symbols:a,totalAgents:d.estimatedAgents,...c.length>0?{activeNominations:c}:{},stages:u,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"],claudeCode:{method:"Task tool",example:{description:u[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((b,h)=>({stage:h,rolePrompt:`Adopt the ${b.agents[0]?.name} role. Focus ONLY on: ${b.agents.map(w=>w.task).join(", ")}`,constraint:h===0?"Design/plan only \u2014 do NOT write implementation code":h===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:m,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 "${m}" 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="${m}" 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:m,symbols:["#rate-limiter","^authenticated"]}}},f=JSON.stringify(y,null,2);return o(f.length,"paradigm_orchestrate_inline"),{handled:true,text:f}}async function Ud(n,e,s,t,i,r){let o$1=n.toLowerCase(),a=[];s.securityRequired&&a.push("security-adjacent task (auth, gates, permissions detected)"),s.complexity==="high"&&a.push(`high complexity task (type: ${s.type})`),e.length>=4&&a.push(`${e.length} symbols in scope \u2014 cross-cutting change`);let c=t.filter(f=>f.urgency==="critical");c.length>0&&a.push(`${c.length} critical agent nomination(s) pending`);let l={assumptions:[],risks:[],edgeCases:[],questions:[]};(o$1.includes("simple")||o$1.includes("just")||o$1.includes("only"))&&l.assumptions.push("Task framed as simple \u2014 verify no hidden complexity"),(o$1.includes("always")||o$1.includes("never"))&&l.assumptions.push("Absolute language detected \u2014 edge cases likely exist"),!o$1.includes("error")&&!o$1.includes("fail")&&!o$1.includes("invalid")&&l.assumptions.push("No error/failure handling mentioned \u2014 what happens when it fails?"),e.some(f=>f.startsWith("$"))&&l.risks.push("Flow symbols detected \u2014 multi-step changes have ordering/rollback risk"),e.some(f=>f.startsWith("^"))&&(l.risks.push("Gate symbols detected \u2014 authorization changes require security review"),a.some(f=>f.includes("security"))||a.push("gate symbols in scope \u2014 security review recommended")),s.matchedKeywords.some(f=>["migration","database","schema"].includes(f))&&l.risks.push("Data migration risk \u2014 irreversible changes need rollback plan"),s.matchedKeywords.some(f=>["delete","remove","drop"].includes(f))&&l.risks.push("Destructive operation \u2014 verify nothing depends on removed items"),(o$1.includes("add")||o$1.includes("new"))&&l.edgeCases.push("New feature \u2014 how does it interact with existing features?"),(o$1.includes("refactor")||o$1.includes("rename"))&&l.edgeCases.push("Refactor \u2014 all callers updated? Integration tests cover the change?"),(o$1.includes("fix")||o$1.includes("bug"))&&l.edgeCases.push("Bug fix \u2014 does the fix address the root cause or just the symptom?"),o$1.includes("test")||l.questions.push("How will this be tested?"),e.length===0&&l.questions.push("No symbols referenced \u2014 which components are actually affected?");let d={concerns:[],suggestions:[]};for(let f of e){let b=f.replace(/^[#$^!~@&%?]/,"");!i.agents[b]&&f.startsWith("#");}s.costMultiplier.max>1&&d.concerns.push(`Higher-than-average complexity (${s.costMultiplier.min}x-${s.costMultiplier.max}x baseline) \u2014 consider breaking into smaller tasks`);let p=[];try{let{loadNotebookEntries:f}=await import('./notebook-loader-CENTDDUJ.js'),b=e.map(w=>w.replace(/^[#$^!~@&%?]/,"").toLowerCase()),h=f("advocate",r.rootDir,b.length>0?{concepts:b}:void 0);h.length>0&&(p=h.sort((w,_)=>_.confidence-w.confidence).slice(0,3).map(w=>w.snippet));}catch{}let g=a.length>=2||a.some(f=>f.includes("security")||f.includes("critical"))?"escalate":"greenlight",m={mode:"quick",task:n,verdict:g,classification:{type:s.type,complexity:s.complexity,securityRequired:s.securityRequired},advocate:{agent:"Jinx (advocate)",...l.assumptions.length>0?{assumptions:l.assumptions}:{},...l.risks.length>0?{risks:l.risks}:{},...l.edgeCases.length>0?{edgeCases:l.edgeCases}:{},...l.questions.length>0?{questions:l.questions}:{},...p.length>0?{notebookInsights:p}:{}},reviewer:{agent:"reviewer",...d.concerns.length>0?{concerns:d.concerns}:{},...d.suggestions.length>0?{suggestions:d.suggestions}:{}},...a.length>0?{escalationSignals:a}:{},...t.length>0?{activeNominations:t}:{},symbols:e,instructions:g==="greenlight"?["Quick check passed \u2014 proceed with implementation.","Orchestration enforcement is satisfied.",l.questions.length>0?`Address Jinx's questions during implementation: ${l.questions.join("; ")}`:"No open questions from advocate."]:["Quick check recommends full orchestration.",`Escalation reasons: ${a.join("; ")}`,'Call paradigm_orchestrate_inline mode="plan" for full agent planning.',"Orchestration enforcement is satisfied regardless of verdict."]},y=JSON.stringify(m,null,2);return o(y.length,"paradigm_orchestrate_inline"),{handled:true,text:y}}async function zd(n,e){let s=n.agent,t=n.task,i=n.handoffContext,r=n.previousAgent,o$1=va(e.rootDir),a=b$7(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:fa(s,e.rootDir,c),triggers:c?.triggers,handoff_to:c?.handoff_to,context:c?.context,protocol:c?.protocol},d=Ot(t),p,u;try{let{loadAgentProfile:f,buildProfileEnrichment:b}=await import('./agent-loader-CZFB5BDP.js'),{loadDecisions:h}=await import('./decision-loader-2XPZE4EZ.js'),{loadJournalEntries:w}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:_}=await import('./nomination-engine-LMSZ2CAS.js'),{loadNotebookEntries:k}=await import('./notebook-loader-CENTDDUJ.js'),v=f(e.rootDir,s);if(v){u=v.nickname;let S=h(e.rootDir,{status:"active",limit:5}).map(P=>({title:P.title,decision:P.decision.slice(0,150)})),x=w(s,{transferable:!0,limit:5}).map(P=>({trigger:P.trigger,insight:P.insight.slice(0,150)})),C=_(e.rootDir,{pending_only:!0,limit:10}).map(P=>({urgency:P.urgency,brief:P.brief})),T;try{let P=d.map(I=>I.replace(/^[#$^!~@&%?]/,"").toLowerCase()),D=k(s,e.rootDir,P.length>0?{concepts:P}:void 0);D.length>0&&(T=D.sort((A,N)=>N.confidence-A.confidence||new Date(N.updated).getTime()-new Date(A.updated).getTime()).slice(0,5).map(A=>({context:A.context,snippet:A.snippet,concepts:A.concepts})));}catch{}let j=b(v,d,T,{recentDecisions:S,journalInsights:x,pendingNominations:C});if(v.permissions){let P=[`
774
+ `);}H.trim()&&p.set(P.name,{enrichment:H,nickname:D.nickname});}}}catch{}let u=[];for(let b of d.stages){let h=[];for(let w of b.agents){let _=r.agents[w.name],k={name:_?.name||w.name,role:_?.role||Dt[w.name]||`${w.name} agent`,focus:_?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:fa(w.name,e.rootDir,_),triggers:_?.triggers,handoff_to:_?.handoff_to,context:_?.context,protocol:_?.protocol},v=p.get(w.name),S=wa({agent:k,task:w.task,symbols:a,dependsOn:w.dependsOn,profileEnrichment:v?.enrichment,nickname:v?.nickname});h.push(S);}u.push({stage:b.stage,canRunParallel:b.canRunParallel,agents:h});}let g=`orch-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`;ip(e.rootDir,g,s,d);try{let{appendSessionWorkEntry:b}=await import('./session-work-log-5PHOUEQ6.js');for(let h of u)for(let w of h.agents)b(e.rootDir,{timestamp:new Date().toISOString(),type:"agent-contribution",agent:w.agent,contribution:w.taskDescription?.slice(0,200)||s.slice(0,200),attribution:w.attribution,symbols:a});}catch{}try{let{recordAgentSession:b}=await import('./agent-state-KSQ3S7OB.js'),w=(await import('./session-tracker-FDFL4PZI.js')).default?.session?.sessionId||g;for(let _ of u)for(let k of _.agents)b(k.agent,e.rootDir,{sessionId:w,summary:`${k.attribution||k.agent}: ${(k.taskDescription||s).slice(0,200)}`,symbolsTouched:a});}catch{}let m=`thr-orch-${g}`;try{let b=await import('./symphony-loader-XJT43FOS.js'),h=F.basename(e.rootDir),w=`${h}/maestro`;try{b.getMyIdentity(e.rootDir)||b.registerAgent(e.rootDir,"maestro","Maestro (orchestrator)");}catch{}b.createThread(`Orchestration: ${s.slice(0,80)}`,{id:w,name:"Maestro",type:"agent",project:h,role:"orchestrator"});let _=F.join(ma.homedir(),".paradigm","score","threads"),k=O.readdirSync(_).filter(S=>S.endsWith(".json")).sort(),v=k[k.length-1];if(v){let S=F.join(_,v),x=F.join(_,`${m}.json`),C=JSON.parse(O.readFileSync(S,"utf8"));C.id=m,O.writeFileSync(x,JSON.stringify(C,null,2),"utf8"),S!==x&&O.unlinkSync(S);}for(let S of u)for(let x of S.agents){let C=b.buildMessage({threadRoot:m,sender:{id:w,name:"Maestro",type:"agent",project:h,role:"orchestrator"},intent:"task",text:`[Maestro] Stage ${S.stage}: Assigned to ${x.attribution||x.agent} \u2014 ${x.taskDescription||s}`,symbols:a,metadata:{task:{stage:S.stage,canRunParallel:S.canRunParallel}}});b.routeMessage(C);}}catch{}let y={orchestrationId:g,task:s,mode:"execute",symbols:a,totalAgents:d.estimatedAgents,...c.length>0?{activeNominations:c}:{},stages:u,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"],claudeCode:{method:"Task tool",example:{description:u[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((b,h)=>({stage:h,rolePrompt:`Adopt the ${b.agents[0]?.name} role. Focus ONLY on: ${b.agents.map(w=>w.task).join(", ")}`,constraint:h===0?"Design/plan only \u2014 do NOT write implementation code":h===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:m,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 "${m}" 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="${m}" 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:m,symbols:["#rate-limiter","^authenticated"]}}},f=JSON.stringify(y,null,2);return o(f.length,"paradigm_orchestrate_inline"),{handled:true,text:f}}async function Ud(n,e,s,t,i,r){let o$1=n.toLowerCase(),a=[];s.securityRequired&&a.push("security-adjacent task (auth, gates, permissions detected)"),s.complexity==="high"&&a.push(`high complexity task (type: ${s.type})`),e.length>=4&&a.push(`${e.length} symbols in scope \u2014 cross-cutting change`);let c=t.filter(f=>f.urgency==="critical");c.length>0&&a.push(`${c.length} critical agent nomination(s) pending`);let l={assumptions:[],risks:[],edgeCases:[],questions:[]};(o$1.includes("simple")||o$1.includes("just")||o$1.includes("only"))&&l.assumptions.push("Task framed as simple \u2014 verify no hidden complexity"),(o$1.includes("always")||o$1.includes("never"))&&l.assumptions.push("Absolute language detected \u2014 edge cases likely exist"),!o$1.includes("error")&&!o$1.includes("fail")&&!o$1.includes("invalid")&&l.assumptions.push("No error/failure handling mentioned \u2014 what happens when it fails?"),e.some(f=>f.startsWith("$"))&&l.risks.push("Flow symbols detected \u2014 multi-step changes have ordering/rollback risk"),e.some(f=>f.startsWith("^"))&&(l.risks.push("Gate symbols detected \u2014 authorization changes require security review"),a.some(f=>f.includes("security"))||a.push("gate symbols in scope \u2014 security review recommended")),s.matchedKeywords.some(f=>["migration","database","schema"].includes(f))&&l.risks.push("Data migration risk \u2014 irreversible changes need rollback plan"),s.matchedKeywords.some(f=>["delete","remove","drop"].includes(f))&&l.risks.push("Destructive operation \u2014 verify nothing depends on removed items"),(o$1.includes("add")||o$1.includes("new"))&&l.edgeCases.push("New feature \u2014 how does it interact with existing features?"),(o$1.includes("refactor")||o$1.includes("rename"))&&l.edgeCases.push("Refactor \u2014 all callers updated? Integration tests cover the change?"),(o$1.includes("fix")||o$1.includes("bug"))&&l.edgeCases.push("Bug fix \u2014 does the fix address the root cause or just the symptom?"),o$1.includes("test")||l.questions.push("How will this be tested?"),e.length===0&&l.questions.push("No symbols referenced \u2014 which components are actually affected?");let d={concerns:[],suggestions:[]};for(let f of e){let b=f.replace(/^[#$^!~@&%?]/,"");!i.agents[b]&&f.startsWith("#");}s.costMultiplier.max>1&&d.concerns.push(`Higher-than-average complexity (${s.costMultiplier.min}x-${s.costMultiplier.max}x baseline) \u2014 consider breaking into smaller tasks`);let p=[];try{let{loadNotebookEntries:f}=await import('./notebook-loader-CENTDDUJ.js'),b=e.map(w=>w.replace(/^[#$^!~@&%?]/,"").toLowerCase()),h=f("advocate",r.rootDir,b.length>0?{concepts:b}:void 0);h.length>0&&(p=h.sort((w,_)=>_.confidence-w.confidence).slice(0,3).map(w=>w.snippet));}catch{}let g=a.length>=2||a.some(f=>f.includes("security")||f.includes("critical"))?"escalate":"greenlight",m={mode:"quick",task:n,verdict:g,classification:{type:s.type,complexity:s.complexity,securityRequired:s.securityRequired},advocate:{agent:"Jinx (advocate)",...l.assumptions.length>0?{assumptions:l.assumptions}:{},...l.risks.length>0?{risks:l.risks}:{},...l.edgeCases.length>0?{edgeCases:l.edgeCases}:{},...l.questions.length>0?{questions:l.questions}:{},...p.length>0?{notebookInsights:p}:{}},reviewer:{agent:"reviewer",...d.concerns.length>0?{concerns:d.concerns}:{},...d.suggestions.length>0?{suggestions:d.suggestions}:{}},...a.length>0?{escalationSignals:a}:{},...t.length>0?{activeNominations:t}:{},symbols:e,instructions:g==="greenlight"?["Quick check passed \u2014 proceed with implementation.","Orchestration enforcement is satisfied.",l.questions.length>0?`Address Jinx's questions during implementation: ${l.questions.join("; ")}`:"No open questions from advocate."]:["Quick check recommends full orchestration.",`Escalation reasons: ${a.join("; ")}`,'Call paradigm_orchestrate_inline mode="plan" for full agent planning.',"Orchestration enforcement is satisfied regardless of verdict."]},y=JSON.stringify(m,null,2);return o(y.length,"paradigm_orchestrate_inline"),{handled:true,text:y}}async function zd(n,e){let s=n.agent,t=n.task,i=n.handoffContext,r=n.previousAgent,o$1=va(e.rootDir),a=b$7(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:fa(s,e.rootDir,c),triggers:c?.triggers,handoff_to:c?.handoff_to,context:c?.context,protocol:c?.protocol},d=Ot(t),p,u;try{let{loadAgentProfile:f,buildProfileEnrichment:b}=await import('./agent-loader-CZFB5BDP.js'),{loadDecisions:h}=await import('./decision-loader-2XPZE4EZ.js'),{loadJournalEntries:w}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:_}=await import('./nomination-engine-LMSZ2CAS.js'),{loadNotebookEntries:k}=await import('./notebook-loader-CENTDDUJ.js'),v=f(e.rootDir,s);if(v){u=v.nickname;let S=h(e.rootDir,{status:"active",limit:5}).map(P=>({title:P.title,decision:P.decision.slice(0,150)})),x=w(s,{transferable:!0,limit:5}).map(P=>({trigger:P.trigger,insight:P.insight.slice(0,150)})),C=_(e.rootDir,{pending_only:!0,limit:10}).map(P=>({urgency:P.urgency,brief:P.brief})),T;try{let P=d.map(I=>I.replace(/^[#$^!~@&%?]/,"").toLowerCase()),D=k(s,e.rootDir,P.length>0?{concepts:P}:void 0);D.length>0&&(T=D.sort((A,E)=>E.confidence-A.confidence||new Date(E.updated).getTime()-new Date(A.updated).getTime()).slice(0,5).map(A=>({context:A.context,snippet:A.snippet,concepts:A.concepts})));}catch{}let j=b(v,d,T,{recentDecisions:S,journalInsights:x,pendingNominations:C});if(v.permissions){let P=[`
737
775
  ## Permission Constraints`];v.permissions.paths?.deny?.length&&P.push(`**Denied paths:** ${v.permissions.paths.deny.join(", ")}`),v.permissions.paths?.write?.length&&P.push(`**Writable paths:** ${v.permissions.paths.write.join(", ")}`),v.permissions.tools?.deny?.length&&P.push(`**Denied tools:** ${v.permissions.tools.deny.join(", ")}`),v.permissions.dangerous_actions?.length&&P.push(`**Requires approval for:** ${v.permissions.dangerous_actions.join(", ")}`),j+=`
738
776
  `+P.join(`
739
- `);}j.trim()&&(p=j);}}catch{}let g=wa({agent:l,task:t,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 ba(n,e){let s=new Set(n),t=[];for(let i of n){let r=e[i];if(r?.handoff_to)for(let o of r.handoff_to)s.has(o)&&t.push({from:i,to:o});}return t}function Bd(n,e){let s=ba(n,e);if(s.length===0)return null;let t=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(",");t.add(g);}let r=new Map;for(let u of t){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 n)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 n){let g=r.get(u);p.set(u,l.get(g)||0);}return p}function Vd(n,e,s,t,i){let r=Ot(n),o=n.toLowerCase(),a=[],c=[];if(s&&s.length>0)for(let _=0;_<s.length;_++){let k=s[_];e[k]&&c.push({name:k,task:`${k==="architect"?"Design":k==="builder"?"Implement":k==="tester"?"Test":"Process"}: ${n}`,dependsOn:_>0?[s[_-1]]:[],required:true,stage:_});}else {let _=o.includes("design")||o.includes("architect")||o.includes("plan")||o.includes("spec"),k=o.includes("auth")||o.includes("security")||o.includes("gate")||r.some(j=>j.startsWith("^")),v=o.includes("build")||o.includes("implement")||o.includes("create")||o.includes("add")||o.includes("fix"),S=o.includes("review")||o.includes("check"),x=o.includes("test")||o.includes("verify")||o.includes("validate");if(_&&e.architect&&c.push({name:"architect",task:`Design and specify: ${n}`,dependsOn:[],required:true,stage:0}),k&&e.security&&c.push({name:"security",task:`Review security aspects of: ${n}`,dependsOn:[],required:false,stage:0}),v&&e.builder){let j=_&&e.architect?["architect"]:[];c.push({name:"builder",task:`Implement: ${n}`,dependsOn:j,required:true,stage:j.length>0?1:0});}let C=c.some(j=>j.name==="builder"),T=C?2:_?1:0;if(S&&e.reviewer&&c.push({name:"reviewer",task:`Review: ${n}`,dependsOn:C?["builder"]:[],required:false,stage:T}),x&&e.tester&&c.push({name:"tester",task:`Test and validate: ${n}`,dependsOn:C?["builder"]:[],required:false,stage:T}),c.length===0){let j=t?.recommendedAgents||["architect","builder","tester"],P={architect:"Design",security:"Review security of",builder:"Implement",tester:"Test",reviewer:"Review"},D=0,I=null;for(let A of j){if(!e[A])continue;let N=I?[I]:[],H=P[A]||"Process",q=A==="architect"||A==="builder";c.push({name:A,task:`${H}: ${n}`,required:q,stage:D,dependsOn:N}),I=A,D++;}}}let l=c.map(_=>_.name),d=Bd(l,e);if(d)for(let _ of c){_.stage=d.get(_.name)||0;let k=[];for(let v of l){if(v===_.name)continue;e[v]?.handoff_to?.includes(_.name)&&(d.get(v)||0)<_.stage&&k.push(v);}k.length>0&&(_.dependsOn=k);}let p=new Map;for(let _ of c){let k=p.get(_.stage)||[];k.push(_),p.set(_.stage,k);}let u=Array.from(p.keys()).sort((_,k)=>_-k);for(let _ of u){let k=p.get(_)||[];a.push({stage:_,agents:k.map(v=>({name:v.name,task:v.task,dependsOn:v.dependsOn,required:v.required})),canRunParallel:k.length>1});}let g=c.some(_=>_.name==="builder"||_.name==="tester"),y=t?.type==="analysis"||!g,f=false;if(!y){let _=u.length>0?u[u.length-1]+1:0;a.push({stage:_,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 _ of c){let k=Jd[_.name]||{min:5e3,max:2e4};b+=k.min,h+=k.max;}f&&(b+=2e3,h+=8e3);let w=i?.default_mode||"faceted";return {task:n,mode:w,stages:a,symbols:r,estimatedAgents:c.length+(f?1:0),estimatedTokens:{min:b,max:h}}}function wa(n){let{agent:e,task:s,symbols:t,handoffContext:i,previousAgent:r}=n,o=[];n.profileEnrichment&&(o.push(n.profileEnrichment),o.push("---"),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(""),t.length>0){o.push("## Symbols in Scope"),o.push("");for(let p of t){let u=Yd(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
777
+ `);}j.trim()&&(p=j);}}catch{}let g=wa({agent:l,task:t,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 ba(n,e){let s=new Set(n),t=[];for(let i of n){let r=e[i];if(r?.handoff_to)for(let o of r.handoff_to)s.has(o)&&t.push({from:i,to:o});}return t}function Bd(n,e){let s=ba(n,e);if(s.length===0)return null;let t=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(",");t.add(g);}let r=new Map;for(let u of t){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 n)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 n){let g=r.get(u);p.set(u,l.get(g)||0);}return p}function Vd(n,e,s,t,i){let r=Ot(n),o=n.toLowerCase(),a=[],c=[];if(s&&s.length>0)for(let _=0;_<s.length;_++){let k=s[_];e[k]&&c.push({name:k,task:`${k==="architect"?"Design":k==="builder"?"Implement":k==="tester"?"Test":"Process"}: ${n}`,dependsOn:_>0?[s[_-1]]:[],required:true,stage:_});}else {let _=o.includes("design")||o.includes("architect")||o.includes("plan")||o.includes("spec"),k=o.includes("auth")||o.includes("security")||o.includes("gate")||r.some(j=>j.startsWith("^")),v=o.includes("build")||o.includes("implement")||o.includes("create")||o.includes("add")||o.includes("fix"),S=o.includes("review")||o.includes("check"),x=o.includes("test")||o.includes("verify")||o.includes("validate");if(_&&e.architect&&c.push({name:"architect",task:`Design and specify: ${n}`,dependsOn:[],required:true,stage:0}),k&&e.security&&c.push({name:"security",task:`Review security aspects of: ${n}`,dependsOn:[],required:false,stage:0}),v&&e.builder){let j=_&&e.architect?["architect"]:[];c.push({name:"builder",task:`Implement: ${n}`,dependsOn:j,required:true,stage:j.length>0?1:0});}let C=c.some(j=>j.name==="builder"),T=C?2:_?1:0;if(S&&e.reviewer&&c.push({name:"reviewer",task:`Review: ${n}`,dependsOn:C?["builder"]:[],required:false,stage:T}),x&&e.tester&&c.push({name:"tester",task:`Test and validate: ${n}`,dependsOn:C?["builder"]:[],required:false,stage:T}),c.length===0){let j=t?.recommendedAgents||["architect","builder","tester"],P={architect:"Design",security:"Review security of",builder:"Implement",tester:"Test",reviewer:"Review"},D=0,I=null;for(let A of j){if(!e[A])continue;let E=I?[I]:[],H=P[A]||"Process",q=A==="architect"||A==="builder";c.push({name:A,task:`${H}: ${n}`,required:q,stage:D,dependsOn:E}),I=A,D++;}}}let l=c.map(_=>_.name),d=Bd(l,e);if(d)for(let _ of c){_.stage=d.get(_.name)||0;let k=[];for(let v of l){if(v===_.name)continue;e[v]?.handoff_to?.includes(_.name)&&(d.get(v)||0)<_.stage&&k.push(v);}k.length>0&&(_.dependsOn=k);}let p=new Map;for(let _ of c){let k=p.get(_.stage)||[];k.push(_),p.set(_.stage,k);}let u=Array.from(p.keys()).sort((_,k)=>_-k);for(let _ of u){let k=p.get(_)||[];a.push({stage:_,agents:k.map(v=>({name:v.name,task:v.task,dependsOn:v.dependsOn,required:v.required})),canRunParallel:k.length>1});}let g=c.some(_=>_.name==="builder"||_.name==="tester"),y=t?.type==="analysis"||!g,f=false;if(!y){let _=u.length>0?u[u.length-1]+1:0;a.push({stage:_,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 _ of c){let k=Jd[_.name]||{min:5e3,max:2e4};b+=k.min,h+=k.max;}f&&(b+=2e3,h+=8e3);let w=i?.default_mode||"faceted";return {task:n,mode:w,stages:a,symbols:r,estimatedAgents:c.length+(f?1:0),estimatedTokens:{min:b,max:h}}}function wa(n){let{agent:e,task:s,symbols:t,handoffContext:i,previousAgent:r}=n,o=[];n.profileEnrichment&&(o.push(n.profileEnrichment),o.push("---"),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(""),t.length>0){o.push("## Symbols in Scope"),o.push("");for(let p of t){let u=Yd(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
740
778
 
741
779
  When you complete your task, end with a structured summary block:
742
780
 
@@ -762,11 +800,11 @@ This structured output helps track progress and pass context between agents.`);l
762
800
  `)[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(t==="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(`
763
801
  `)[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(`
764
802
  `)[0].trim()||""});return {handled:true,text:JSON.stringify({query:i,count:l.length,matches:l},null,2)}}if(t==="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: ${t}`})}}case "paradigm_tags_suggest":{let{tag:t,description:i,reason:r,appliesTo:o,exampleSymbols:a}=e,c=_a(s.rootDir);if(!c)return {handled:true,text:JSON.stringify({error:"Tag bank not found",suggestion:"Create .paradigm/tags.yaml first"})};if(c.core?.[t]||c.project?.[t])return {handled:true,text:JSON.stringify({error:`Tag "${t}" already exists`,existing:c.core?.[t]?"core":"project"})};if(c.suggested?.some(d=>d.tag===t))return {handled:true,text:JSON.stringify({error:`Tag "${t}" is already in the suggested queue`,status:"pending approval"})};let l={tag:t,"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),rp(s.rootDir,c),{handled:true,text:JSON.stringify({success:true,tag:t,status:"pending approval",message:"Tag suggestion added. Human review required before use.",nextSteps:["Human can approve via Sentinel UI or CLI",'Once approved, tag moves to "project" section',"Then AI can use the tag for classification"]},null,2)}}case "paradigm_aspect_check":{let{aspect:t}=e,i=t.startsWith("~")?t:`~${t}`,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 m of o){let y=F.isAbsolute(m.path)?m.path:F.join(s.rootDir,m.path),f=O.existsSync(y),b;if(f)try{let w=O.readFileSync(y,"utf-8").split(`
765
- `);typeof m.lines=="number"?b=1:Array.isArray(m.lines)&&m.lines.length===2?b=m.lines[1]-m.lines[0]+1:Array.isArray(m.lines)&&(b=m.lines.length);}catch{}a.push({path:m.path,lines:m.raw.split(":")[1]||"full file",exists:f,lineCount:b});}let c=o.length>0&&a.every(m=>m.exists),l=r.appliesTo||[],d=n(s.index),p=[],u=[];for(let m of d)for(let y of l)if(new RegExp("^"+y.replace(/\*/g,".*").replace(/\?/g,".")+"$").test(m.symbol)){p.push(m.symbol),(m.data?.aspects?.includes?.(i)||m.data?.aspects?.includes?.(t))&&u.push(m.symbol);break}let g=p.filter(m=>!u.includes(m));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:g.slice(0,10),missingCount:g.length},warnings:[...o.length===0?["CRITICAL: Aspect has no anchors - aspects MUST have code anchors"]:[],...a.filter(m=>!m.exists).map(m=>`Anchor file not found: ${m.path}`),...g.length>0?[`${g.length} symbols match applies-to but don't have this aspect`]:[]],recommendation:c?g.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:""}}}var op=["#","$","^","!","~"];function J(n){return n.length>1&&op.includes(n[0])?n.slice(1):n}function M(n,e){let s=J(n);return `${e}${s}`}function le(n,e){let s=F.isAbsolute(n)?n:F.resolve(e,n);return s.endsWith(".purpose")?s:F.join(s,".purpose")}function de(n){if(!O.existsSync(n))return {};let e=a$8(n);if(!e.data)throw new Error(`Failed to parse ${n}: ${e.errors.join(", ")}`);return e.data}function pe(n,e){let s=F.dirname(n);O.existsSync(s)||O.mkdirSync(s,{recursive:true});let t=b$a(e);O.writeFileSync(n,t,"utf8");}function Ke(n){if(!n)return {};if(!Array.isArray(n))return n;let e={};for(let s of n){let{id:t,...i}=s;e[t]=i;}return e}function An(n){if(!n)return {};if(!Array.isArray(n))return n;let e={};for(let s of n)e[s.name]={description:s.description,steps:s.steps};return e}function ot(n,e){if(!e||e.length===0)return n;if(!n||n.length===0)return e;let s=new Set(n);for(let t of e)s.add(t);return Array.from(s)}var ap={"#":"#","^":"^","!":"!",$:"$","~":"~"};async function xa(n,e,s,t){let i=ap[t];if(!i)throw new Error(`Invalid symbol type: ${t}. Expected one of: # ^ ! $ ~`);let r=J(e),o=J(s),a=M(r,i),c=M(o,i),l=await c$5(n),d=[];for(let p of l){let u=de(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=Ke(u[f]);for(let[h,w]of Object.entries(b))g=cp(w,a,c)||g;g&&Object.keys(b).length>0&&(u[f]=b);}if(u.flows){let f=An(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&&(pe(p,u),d.push(p));}return d}function cp(n,e,s){let t=false,i=["signals","gates","flows","components","states"];for(let r of i){let o=n[r];if(o){let a=o.indexOf(e);a!==-1&&(o[a]=s,t=true);}}if(n.aspects&&Array.isArray(n.aspects)){let r=n.aspects.indexOf(e);r!==-1&&(n.aspects[r]=s,t=true);}return t}function In(n){let e=F.join(n,"portal.yaml");if(!O.existsSync(e))return {data:{version:"1.0.0",gates:{}},filePath:e};let s=O.readFileSync(e,"utf8");return {data:Z.load(s)||{version:"1.0.0",gates:{}},filePath:e}}function Pa(n,e){let s=Z.dump(e,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});O.writeFileSync(n,s,"utf8");}function Ra(n,e){let{data:s,filePath:t}=In(n);s.gates||(s.gates={});let i=J(e.id),r=s.gates[i]||{};return 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,Pa(t,s),t}function ja(n,e){let{data:s,filePath:t}=In(n);s.routes||(s.routes={});let i=`${e.method} ${e.route}`,r=e.gates.map(o=>`^${J(o)}`);return s.routes[i]=r,Pa(t,s),t}var lp={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}},dp={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}},pp={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}},up={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}},gp={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}},mp={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}},fp={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}},yp={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}},hp={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}},bp={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}},wp={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 enforced (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}},vp={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}},_p={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 Da(){return [lp,dp,pp,up,gp,mp,fp,yp,hp,bp,wp,vp,_p]}async function Aa(n,e,s,t){switch(n){case "paradigm_purpose_init":return kp(e,s,t);case "paradigm_purpose_add_component":return Sp(e,s,t);case "paradigm_purpose_add_aspect":return xp(e,s,t);case "paradigm_purpose_add_signal":return Cp(e,s,t);case "paradigm_purpose_add_flow":return Pp(e,s,t);case "paradigm_purpose_add_gate":return Rp(e,s,t);case "paradigm_purpose_add_state":return jp(e,s,t);case "paradigm_purpose_link":return Tp(e,s,t);case "paradigm_purpose_remove":return Dp(e,s,t);case "paradigm_purpose_rename":return Ap(e,s,t);case "paradigm_portal_add_gate":return Op(e,s,t);case "paradigm_portal_add_route":return Ip(e,s,t);case "paradigm_purpose_validate":return Fp(e,s);default:return {handled:false,text:""}}}function X(n){return {handled:true,text:JSON.stringify(n,null,2)}}function qe(n){return {handled:true,text:JSON.stringify({error:n},null,2)}}async function kp(n,e,s){let{purposeFile:t,name:i,description:r,context:o,version:a}=n,c=le(t,e.rootDir),l=de(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),pe(c,l),await s(),X({action:"purpose_init",file:c,metadata:{name:i,description:l.description,version:l.version}})}async function Sp(n,e,s){let{purposeFile:t,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}=n,h=le(t,e.rootDir),w=de(h),_=J(i),k=o,v=Ke(w[k]),S=v[_]||{description:""};return S.description=r,a!==void 0&&(S.file=a),c!==void 0&&(S.status=c),l!==void 0&&(S.endpoints=l),d!==void 0&&(S.tests=d),p!==void 0&&(S.flows=p.map(x=>M(x,"$"))),u!==void 0&&(S.gates=u.map(x=>M(x,"^"))),g!==void 0&&(S.signals=g.map(x=>M(x,"!"))),m!==void 0&&(S.aspects=m.map(x=>M(x,"~"))),y!==void 0&&(S.components=y.map(x=>M(x,"#"))),f!==void 0&&(S.type=f),b!==void 0&&(S.parent=M(b,"#")),v[_]=S,w[k]=v,pe(h,w),await s(),X({action:"add_component",file:h,section:k,id:_,symbol:`#${_}`})}async function xp(n,e,s){let{purposeFile:t,id:i,description:r,anchors:o,tags:a,appliesTo:c,enforcement:l}=n;if(!o||o.length===0)return qe('Aspects (~) REQUIRE at least one code anchor. Provide anchors like ["src/middleware/audit.ts:15-35"].');let d=/^[^\s:]+:\d+(-\d+)?(,\d+)*$/;for(let y of o)if(!d.test(y))return qe(`Invalid anchor format: "${y}". Expected format: "file.ts:15", "file.ts:15-20", or "file.ts:15,25,30".`);let p=le(t,e.rootDir),u=F.dirname(p);for(let y of o){let f=y.replace(/:.*$/,""),b=F.resolve(u,f);if(!O.existsSync(b)){let h=F.resolve(e.rootDir,f);if(O.existsSync(h)){let w=F.relative(u,h),_=o.indexOf(y);o[_]=y.replace(f,w);}else return qe(`Anchor file not found: "${f}". Anchors must be relative to the .purpose file directory (${u}).`)}}let g=de(p);g.aspects||(g.aspects={});let m=J(i);return g.aspects[m]={description:r,anchors:o,...a&&{tags:a},...c&&{"applies-to":c},...l&&{enforcement:l}},pe(p,g),await s(),X({action:"add_aspect",file:p,id:m,symbol:`~${m}`,anchors:o})}async function Cp(n,e,s){let{purposeFile:t,id:i,description:r,category:o,severity:a,emitters:c,related:l,data:d}=n,p=le(t,e.rootDir),u=de(p);u.signals||(u.signals={});let g=J(i);return u.signals[g]={description:r,...o&&{category:o},...a&&{severity:a},...c&&{emitters:c.map(m=>M(m,"#"))},...l&&{related:l},...d&&{data:d}},pe(p,u),await s(),X({action:"add_signal",file:p,id:g,symbol:`!${g}`})}async function Pp(n,e,s){let{purposeFile:t,id:i,description:r,gates:o,signals:a,components:c,steps:l}=n,d=le(t,e.rootDir),p=de(d),u=An(p.flows),g=J(i),m={description:r,...o&&{gates:o.map(y=>M(y,"^"))},...a&&{signals:a.map(y=>M(y,"!"))},...c&&{components:c.map(y=>M(y,"#"))},...l&&{steps:l}};return u[g]=m,p.flows=u,pe(d,p),await s(),X({action:"add_flow",file:d,id:g,symbol:`$${g}`})}async function Rp(n,e,s){let{purposeFile:t,id:i,description:r,requires:o,keys:a,signals:c}=n,l=le(t,e.rootDir),d=de(l);d.gates||(d.gates={});let p=J(i);return d.gates[p]={description:r,...o&&{requires:o},...a&&{keys:a},...c&&{signals:c.map(u=>M(u,"!"))}},pe(l,d),await s(),X({action:"add_gate",file:l,id:p,symbol:`^${p}`})}async function jp(n,e,s){let{purposeFile:t,id:i,description:r,type:o,default:a,properties:c}=n,l=le(t,e.rootDir),d=de(l);d.states||(d.states={});let p=J(i),u={description:r};return o!==void 0&&(u.type=o),a!==void 0&&(u.default=a),c!==void 0&&(u.properties=c),d.states[p]=u,pe(l,d),await s(),X({action:"add_state",file:l,id:p})}async function Tp(n,e,s){let{purposeFile:t,componentId:i,section:r,signals:o,aspects:a,gates:c,flows:l,components:d}=n,p=le(t,e.rootDir),u=de(p),g=J(i),m=r;if(!m){let h=Ke(u.components),w=Ke(u.features);if(g in h)m="components";else if(g in w)m="features";else return qe(`Component "${g}" not found in components or features. Specify section explicitly.`)}let y=Ke(u[m]);if(!(g in y))return qe(`Component "${g}" not found in ${m} section.`);let f=y[g];o&&(f.signals=ot(f.signals,o.map(h=>M(h,"!")))),c&&(f.gates=ot(f.gates,c.map(h=>M(h,"^")))),l&&(f.flows=ot(f.flows,l.map(h=>M(h,"$")))),d&&(f.components=ot(f.components,d.map(h=>M(h,"#")))),a&&(f.aspects=ot(f.aspects,a.map(h=>M(h,"~")))),y[g]=f,u[m]=y,pe(p,u),await s();let b=[];return o&&b.push(`signals: ${o.join(", ")}`),a&&b.push(`aspects: ${a.join(", ")}`),c&&b.push(`gates: ${c.join(", ")}`),l&&b.push(`flows: ${l.join(", ")}`),d&&b.push(`components: ${d.join(", ")}`),X({action:"link",file:p,componentId:g,section:m,added:b})}async function Dp(n,e,s){let{purposeFile:t,section:i,id:r}=n,o=le(t,e.rootDir),a=de(o),c=J(r);if(i==="flows"){let l=An(a.flows);if(!(c in l))return qe(`Flow "${c}" not found in flows section.`);delete l[c],a.flows=l;}else if(i==="components"||i==="features"){let l=Ke(a[i]);if(!(c in l))return qe(`"${c}" not found in ${i} section.`);delete l[c],a[i]=l;}else {let l=a[i];if(!l||!(c in l))return qe(`"${c}" not found in ${i} section.`);delete l[c];}return pe(o,a),await s(),X({action:"remove",file:o,section:i,id:c})}async function Ap(n,e,s){let{oldId:t,newId:i,symbolType:r}=n,o=await xa(e.rootDir,t,i,r);return await s(),X({action:"rename",oldSymbol:`${r}${J(t)}`,newSymbol:`${r}${J(i)}`,filesModified:o.length,files:o})}async function Op(n,e,s){let{id:t,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:p}=n,u=Ra(e.rootDir,{id:t,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:p});await s();let g=J(t);return X({action:"portal_add_gate",file:u,id:g,symbol:`^${g}`})}async function Ip(n,e,s){let{route:t,method:i,gates:r}=n,o=ja(e.rootDir,{route:t,method:i,gates:r});return await s(),X({action:"portal_add_route",file:o,route:`${i} ${t}`,gates:r})}var $p=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi;function Ta(n,e){let s=[];function t(r,o){if(typeof r=="string"){let a=r.match($p);if(a)for(let c of a)s.push({type:"warning",message:`Clarification needed: ${c}`,path:o});}}t(n.description,"description");let i=[{key:"components",items:n.components},{key:"features",items:n.features},{key:"gates",items:n.gates},{key:"signals",items:n.signals},{key:"aspects",items:n.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"&&t(a.description,`${r.key}.${o}.description`);if(n.flows&&typeof n.flows=="object"){let r=Array.isArray(n.flows)?[]:Object.entries(n.flows);for(let[o,a]of r)a&&typeof a.description=="string"&&t(a.description,`flows.${o}.description`);}return s}async function Fp(n,e){let{purposeFile:s,includePortal:t=true}=n,i=[];if(s){let a=le(s,e.rootDir),c=a$8(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=Ta(c.data);l.issues.push(...d),i.push({file:a,valid:l.valid,issues:l.issues});}}else {let a=await c$5(e.rootDir);for(let c of a){let l=a$8(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=Ta(l.data);d.issues.push(...p),i.push({file:c,valid:d.valid,issues:d.issues});}}if(t){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 X({action:"validate",valid:o,totalFiles:i.length,totalIssues:r,results:i})}var Ja=[{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}],Mp=30*1e3,Ls=new Map;function ie(n){let e=F.resolve(n),s=Ls.get(e);if(s&&Date.now()-s.loadedAt<Mp)return s.habits;let t=Lp(e);return Ls.set(e,{habits:t,loadedAt:Date.now()}),t}function Lp(n){let e=new Map;for(let a of Ja)e.set(a.id,{...a});let s=process.env.HOME||process.env.USERPROFILE||"~",t=Na(F.join(s,".paradigm","habits.yaml"));t&&Ea(e,t);let i=Ha(F.join(s,".paradigm","habits"));for(let a of i)e.set(a.id,a);let r=Na(F.join(n,".paradigm","habits.yaml"));r&&Ea(e,r);let o=Ha(F.join(n,".paradigm","habits"));for(let a of o)e.set(a.id,a);return Array.from(e.values())}function Na(n){if(!O.existsSync(n))return null;try{let e=O.readFileSync(n,"utf8");return Z.load(e)}catch{return null}}function Ea(n,e){if(e.habits)for(let s of e.habits)n.set(s.id,{...s});if(e.overrides)for(let[s,t]of Object.entries(e.overrides)){let i=n.get(s);i&&(t.severity!==void 0&&(i.severity=t.severity),t.enabled!==void 0&&(i.enabled=t.enabled));}}function Wp(n,e){return n.filter(s=>s.enabled&&s.trigger===e)}function Ws(n){Ls.delete(F.resolve(n));}function Ha(n){if(!O.existsSync(n))return [];try{let e=O.readdirSync(n).filter(t=>t.endsWith(".habit")).sort(),s=[];for(let t of e)try{let i=O.readFileSync(F.join(n,t),"utf8"),r=Z.load(i);r?.id&&r?.name&&s.push(r);}catch{}return s}catch{return []}}var qa=["discovery","verification","testing","documentation","collaboration","security"],Ma=["preflight","postflight","on-commit","on-stop"],La=["advisory","warn","block"],Wa=["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"],Jp=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Js(n){let e=[];if(n.id||e.push("Missing required field: id"),n.name||e.push("Missing required field: name"),n.description||e.push("Missing required field: description"),n.category||e.push("Missing required field: category"),n.trigger||e.push("Missing required field: trigger"),n.severity||e.push("Missing required field: severity"),n.check||e.push("Missing required field: check"),(n.enabled===void 0||n.enabled===null)&&e.push("Missing required field: enabled"),n.id&&!Jp.test(n.id)&&e.push(`Invalid id format: "${n.id}" \u2014 must be kebab-case (lowercase, hyphens only)`),n.category&&!qa.includes(n.category)&&e.push(`Invalid category: "${n.category}" \u2014 must be one of: ${qa.join(", ")}`),n.trigger&&!Ma.includes(n.trigger)&&e.push(`Invalid trigger: "${n.trigger}" \u2014 must be one of: ${Ma.join(", ")}`),n.severity&&!La.includes(n.severity)&&e.push(`Invalid severity: "${n.severity}" \u2014 must be one of: ${La.join(", ")}`),n.check){Wa.includes(n.check.type)||e.push(`Invalid check.type: "${n.check.type}" \u2014 must be one of: ${Wa.join(", ")}`);let s=n.check.params||{};switch(n.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 "${n.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 Gp=new Set(Ja.map(n=>n.id));function Mn(n){return Gp.has(n)}function Gs(n,e,s="project"){let t=s==="global"?F.join(process.env.HOME||process.env.USERPROFILE||"~",".paradigm","habits"):F.join(n,".paradigm","habits");O.existsSync(t)||O.mkdirSync(t,{recursive:true});let i=F.join(t,`${e.id}.habit`),r=Z.dump(e,{lineWidth:120,noRefs:true});return O.writeFileSync(i,r,"utf8"),Ws(n),i}function Ga(n,e){if(Mn(e))return {removed:false,reason:`"${e}" is a seed habit and cannot be removed. Use overrides in habits.yaml to disable it.`};let s=F.join(n,".paradigm","habits",`${e}.habit`);if(O.existsSync(s))return O.unlinkSync(s),Ws(n),{removed:true};let t=process.env.HOME||process.env.USERPROFILE||"~",i=F.join(t,".paradigm","habits",`${e}.habit`);return O.existsSync(i)?(O.unlinkSync(i),Ws(n),{removed:true}):{removed:false,reason:`No .habit file found for "${e}". It may be defined in habits.yaml \u2014 edit that file directly.`}}var Us=0;function Nt(n,e,s,t,i){let r=Wp(n,e);t&&(r=r.filter(u=>!u.platforms||u.platforms.includes(t)));let o=0;if(i)try{let{isGraduated:u}=(qn(),d$a(Fa)),g=r.length;r=r.filter(m=>!u(i,m.id)),o=g-r.length;}catch{}Us=o;let a=r.map(u=>Up(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 Et(n){return {toolsCalled:n.toolsCalled||[],filesModified:n.filesModified||[],symbolsTouched:n.symbolsTouched||[],loreRecorded:n.loreRecorded||false,hasPortalRoutes:n.hasPortalRoutes||false,taskAddsRoutes:n.taskAddsRoutes||false,taskDescription:n.taskDescription,gitClean:n.gitClean}}function Up(n,e){switch(n.check.type){case "tool-called":return zp(n,e);case "file-exists":return Bp(n,e);case "file-modified":return Xp(n,e);case "lore-recorded":return Vp(n,e);case "symbols-registered":return Yp(n,e);case "gates-declared":return Kp(n,e);case "tests-exist":return Qp(n,e);case "git-clean":return Zp(n,e);case "commit-message-format":return eu(n,e);case "flow-coverage":return tu(n,e);case "context-checked":return nu(n,e);case "aspect-anchored":return su(n,e);default:return {habit:n,result:"partial",reason:`Unknown check: ${n.check.type}`}}}function zp(n,e){let s=n.check.params.tools||[];if(s.length===0)return {habit:n,result:"followed",reason:"No tools required"};let t=s.filter(i=>e.toolsCalled.includes(i));return t.length>0?{habit:n,result:"followed",reason:`Called: ${t.join(", ")}`,evidence:t}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:n,result:"followed",reason:"No modifications, habit not applicable"}:{habit:n,result:"skipped",reason:`None of [${s.join(", ")}] were called before modifying code`}}function Bp(n,e){if(e.filesModified.length===0)return {habit:n,result:"followed",reason:"No files modified"};if(e.filesModified.some(i=>i.endsWith(".purpose")||i.includes(".paradigm/")))return {habit:n,result:"followed",reason:"Purpose files updated"};let t=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 t.length===0?{habit:n,result:"followed",reason:"Only non-source files modified"}:{habit:n,result:"skipped",reason:`${t.length} source file(s) without .purpose updates`,evidence:t.slice(0,5)}}function Vp(n,e){let s=e.filesModified.filter(t=>!t.endsWith(".md")&&!t.endsWith(".json")&&!t.endsWith(".yaml")&&!t.endsWith(".yml")&&!t.endsWith(".lock")&&!t.endsWith(".purpose")&&!t.includes(".paradigm/"));return s.length<3?{habit:n,result:"followed",reason:"Session not significant (< 3 source files)"}:e.loreRecorded||e.toolsCalled.includes("paradigm_lore_record")?{habit:n,result:"followed",reason:"Lore recorded"}:{habit:n,result:"skipped",reason:`${s.length} source files modified, no lore entry`,evidence:s.slice(0,5)}}function Yp(n,e){if(e.symbolsTouched.length===0)return {habit:n,result:"followed",reason:"No symbols touched"};let t=["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 t.length>0?{habit:n,result:"followed",reason:`Purpose tools called: ${t.join(", ")}`,evidence:t}:{habit:n,result:"partial",reason:`${e.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function Kp(n,e){if(!e.taskAddsRoutes)return {habit:n,result:"followed",reason:"No routes added"};if(e.hasPortalRoutes)return {habit:n,result:"followed",reason:"Portal.yaml has routes"};let t=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(i=>e.toolsCalled.includes(i));return t.length>0?{habit:n,result:"followed",reason:`Gate tools called: ${t.join(", ")}`,evidence:t}:{habit:n,result:"skipped",reason:"Routes added without gate declarations"}}function Qp(n,e){if(e.filesModified.length===0)return {habit:n,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:n,result:"followed",reason:`Test files: ${s.length}`,evidence:s.slice(0,5)};let t=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 t.length===0?{habit:n,result:"followed",reason:"No source files to test"}:{habit:n,result:"partial",reason:`${t.length} source file(s), no test files updated`,evidence:t.slice(0,5)}}function Xp(n,e){if(e.filesModified.length===0)return {habit:n,result:"followed",reason:"No files modified"};let s=n.check.params.patterns||[];if(s.length===0)return {habit:n,result:"followed",reason:"No patterns specified"};if(n.trigger==="on-stop"&&n.severity==="block"){let i=e.filesModified.filter(r=>s.some(o=>r.includes(o)||F.basename(r)===o));return i.length>0?{habit:n,result:"followed",reason:`Matching files: ${i.join(", ")}`,evidence:i}:{habit:n,result:"partial",reason:`None of [${s.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let t=e.filesModified.filter(i=>s.some(r=>i.includes(r)||F.basename(i)===r));return t.length>0?{habit:n,result:"followed",reason:`Matching files: ${t.join(", ")}`,evidence:t}:{habit:n,result:"skipped",reason:`None of [${s.join(", ")}] found in modified files`}}function Zp(n,e){return e.filesModified.length===0?{habit:n,result:"followed",reason:"No files modified"}:n.trigger==="on-stop"?{habit:n,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:e.gitClean===void 0?{habit:n,result:"partial",reason:"Git status not available"}:e.gitClean?{habit:n,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:n,result:"skipped",reason:"Uncommitted changes in working tree"}}function eu(n,e){if(!e.commitMessage)return {habit:n,result:"followed",reason:"No commit message to check (not a commit trigger)"};let s=n.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],t=s.filter(i=>new RegExp(i,"m").test(e.commitMessage));if(t.length===s.length)return {habit:n,result:"followed",reason:"Commit message matches all required patterns",evidence:t};if(t.length>0){let i=s.filter(r=>!new RegExp(r,"m").test(e.commitMessage));return {habit:n,result:"partial",reason:`Matches ${t.length}/${s.length} patterns. Missing: ${i.join(", ")}`}}return {habit:n,result:"skipped",reason:"Commit message does not match required format patterns"}}function tu(n,e){let s=e.symbolsTouched.filter(r=>r.startsWith("#"));if(s.length<3)return {habit:n,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(e.hasFlowCoverage)return {habit:n,result:"followed",reason:"Flow coverage exists for multi-component changes"};let i=["paradigm_flow_validate","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(r=>e.toolsCalled.includes(r));return i.length>0?{habit:n,result:"followed",reason:`Flow tools called: ${i.join(", ")}`,evidence:i}:{habit:n,result:"skipped",reason:`${s.length} components touched without flow coverage`,evidence:s.slice(0,5)}}function nu(n,e){let t=(n.check.params.contextTools||["paradigm_context_check","paradigm_session_recover","paradigm_session_checkpoint"]).filter(i=>e.toolsCalled.includes(i));return t.length>0?{habit:n,result:"followed",reason:`Context tools called: ${t.join(", ")}`,evidence:t}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:n,result:"followed",reason:"No modifications, context check not applicable"}:{habit:n,result:"skipped",reason:"No context/session tools called during session"}}function su(n,e){let s=e.symbolsTouched.filter(t=>t.startsWith("~"));return s.length===0?{habit:n,result:"followed",reason:"No aspects touched"}:e.aspectAnchorsValid===true?{habit:n,result:"followed",reason:"Aspect anchors validated and valid"}:e.toolsCalled.includes("paradigm_aspect_check")?{habit:n,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:n,result:"skipped",reason:`${s.length} aspect(s) touched without anchor validation`,evidence:s.slice(0,5)}}var Ht=null,zs=false;async function Bs(n){if(Ht)zs||(await Ht.ensureReady(),zs=true);else {let e=F.join(n,".paradigm","sentinel","sentinel.db");Ht=new f$4(e),await Ht.ensureReady(),zs=true;}return Ht}async function iu(n,e){return (await Bs(n)).recordPracticeEvent(e)}async function za(n,e){return (await Bs(n)).getPracticeEvents(e)}async function ue(n,e){return (await Bs(n)).getComplianceRate(e)}async function qt(n,e){let s=["discovery","verification","testing","documentation","collaboration","security"],t=[];for(let i of s){let r=await ue(n,{...e,habitCategory:i});r.total>0&&t.push({category:i,...r});}return t}async function Ba(n,e,s){let t=[];for(let i of e){let r=await iu(n,{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});t.push(r);}return t}var ou=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,au=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"],cu=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi];function Va(){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.
803
+ `);typeof m.lines=="number"?b=1:Array.isArray(m.lines)&&m.lines.length===2?b=m.lines[1]-m.lines[0]+1:Array.isArray(m.lines)&&(b=m.lines.length);}catch{}a.push({path:m.path,lines:m.raw.split(":")[1]||"full file",exists:f,lineCount:b});}let c=o.length>0&&a.every(m=>m.exists),l=r.appliesTo||[],d=n(s.index),p=[],u=[];for(let m of d)for(let y of l)if(new RegExp("^"+y.replace(/\*/g,".*").replace(/\?/g,".")+"$").test(m.symbol)){p.push(m.symbol),(m.data?.aspects?.includes?.(i)||m.data?.aspects?.includes?.(t))&&u.push(m.symbol);break}let g=p.filter(m=>!u.includes(m));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:g.slice(0,10),missingCount:g.length},warnings:[...o.length===0?["CRITICAL: Aspect has no anchors - aspects MUST have code anchors"]:[],...a.filter(m=>!m.exists).map(m=>`Anchor file not found: ${m.path}`),...g.length>0?[`${g.length} symbols match applies-to but don't have this aspect`]:[]],recommendation:c?g.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:""}}}var op=["#","$","^","!","~"];function J(n){return n.length>1&&op.includes(n[0])?n.slice(1):n}function M(n,e){let s=J(n);return `${e}${s}`}function le(n,e){let s=F.isAbsolute(n)?n:F.resolve(e,n);return s.endsWith(".purpose")?s:F.join(s,".purpose")}function de(n){if(!O.existsSync(n))return {};let e=a$8(n);if(!e.data)throw new Error(`Failed to parse ${n}: ${e.errors.join(", ")}`);return e.data}function pe(n,e){let s=F.dirname(n);O.existsSync(s)||O.mkdirSync(s,{recursive:true});let t=b$a(e);O.writeFileSync(n,t,"utf8");}function Ke(n){if(!n)return {};if(!Array.isArray(n))return n;let e={};for(let s of n){let{id:t,...i}=s;e[t]=i;}return e}function An(n){if(!n)return {};if(!Array.isArray(n))return n;let e={};for(let s of n)e[s.name]={description:s.description,steps:s.steps};return e}function ot(n,e){if(!e||e.length===0)return n;if(!n||n.length===0)return e;let s=new Set(n);for(let t of e)s.add(t);return Array.from(s)}var ap={"#":"#","^":"^","!":"!",$:"$","~":"~"};async function xa(n,e,s,t){let i=ap[t];if(!i)throw new Error(`Invalid symbol type: ${t}. Expected one of: # ^ ! $ ~`);let r=J(e),o=J(s),a=M(r,i),c=M(o,i),l=await c$5(n),d=[];for(let p of l){let u=de(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=Ke(u[f]);for(let[h,w]of Object.entries(b))g=cp(w,a,c)||g;g&&Object.keys(b).length>0&&(u[f]=b);}if(u.flows){let f=An(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&&(pe(p,u),d.push(p));}return d}function cp(n,e,s){let t=false,i=["signals","gates","flows","components","states"];for(let r of i){let o=n[r];if(o){let a=o.indexOf(e);a!==-1&&(o[a]=s,t=true);}}if(n.aspects&&Array.isArray(n.aspects)){let r=n.aspects.indexOf(e);r!==-1&&(n.aspects[r]=s,t=true);}return t}function In(n){let e=F.join(n,"portal.yaml");if(!O.existsSync(e))return {data:{version:"1.0.0",gates:{}},filePath:e};let s=O.readFileSync(e,"utf8");return {data:Z.load(s)||{version:"1.0.0",gates:{}},filePath:e}}function Pa(n,e){let s=Z.dump(e,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});O.writeFileSync(n,s,"utf8");}function Ra(n,e){let{data:s,filePath:t}=In(n);s.gates||(s.gates={});let i=J(e.id),r=s.gates[i]||{};return 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,Pa(t,s),t}function ja(n,e){let{data:s,filePath:t}=In(n);s.routes||(s.routes={});let i=`${e.method} ${e.route}`,r=e.gates.map(o=>`^${J(o)}`);return s.routes[i]=r,Pa(t,s),t}var lp={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}},dp={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}},pp={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}},up={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}},gp={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}},mp={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}},fp={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}},yp={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}},hp={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}},bp={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}},wp={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 enforced (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}},vp={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}},_p={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 Da(){return [lp,dp,pp,up,gp,mp,fp,yp,hp,bp,wp,vp,_p]}async function Aa(n,e,s,t){switch(n){case "paradigm_purpose_init":return kp(e,s,t);case "paradigm_purpose_add_component":return Sp(e,s,t);case "paradigm_purpose_add_aspect":return xp(e,s,t);case "paradigm_purpose_add_signal":return Cp(e,s,t);case "paradigm_purpose_add_flow":return Pp(e,s,t);case "paradigm_purpose_add_gate":return Rp(e,s,t);case "paradigm_purpose_add_state":return jp(e,s,t);case "paradigm_purpose_link":return Tp(e,s,t);case "paradigm_purpose_remove":return Dp(e,s,t);case "paradigm_purpose_rename":return Ap(e,s,t);case "paradigm_portal_add_gate":return Op(e,s,t);case "paradigm_portal_add_route":return Ip(e,s,t);case "paradigm_purpose_validate":return Fp(e,s);default:return {handled:false,text:""}}}function X(n){return {handled:true,text:JSON.stringify(n,null,2)}}function qe(n){return {handled:true,text:JSON.stringify({error:n},null,2)}}async function kp(n,e,s){let{purposeFile:t,name:i,description:r,context:o,version:a}=n,c=le(t,e.rootDir),l=de(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),pe(c,l),await s(),X({action:"purpose_init",file:c,metadata:{name:i,description:l.description,version:l.version}})}async function Sp(n,e,s){let{purposeFile:t,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}=n,h=le(t,e.rootDir),w=de(h),_=J(i),k=o,v=Ke(w[k]),S=v[_]||{description:""};return S.description=r,a!==void 0&&(S.file=a),c!==void 0&&(S.status=c),l!==void 0&&(S.endpoints=l),d!==void 0&&(S.tests=d),p!==void 0&&(S.flows=p.map(x=>M(x,"$"))),u!==void 0&&(S.gates=u.map(x=>M(x,"^"))),g!==void 0&&(S.signals=g.map(x=>M(x,"!"))),m!==void 0&&(S.aspects=m.map(x=>M(x,"~"))),y!==void 0&&(S.components=y.map(x=>M(x,"#"))),f!==void 0&&(S.type=f),b!==void 0&&(S.parent=M(b,"#")),v[_]=S,w[k]=v,pe(h,w),await s(),X({action:"add_component",file:h,section:k,id:_,symbol:`#${_}`})}async function xp(n,e,s){let{purposeFile:t,id:i,description:r,anchors:o,tags:a,appliesTo:c,enforcement:l}=n;if(!o||o.length===0)return qe('Aspects (~) REQUIRE at least one code anchor. Provide anchors like ["src/middleware/audit.ts:15-35"].');let d=/^[^\s:]+:\d+(-\d+)?(,\d+)*$/;for(let y of o)if(!d.test(y))return qe(`Invalid anchor format: "${y}". Expected format: "file.ts:15", "file.ts:15-20", or "file.ts:15,25,30".`);let p=le(t,e.rootDir),u=F.dirname(p);for(let y of o){let f=y.replace(/:.*$/,""),b=F.resolve(u,f);if(!O.existsSync(b)){let h=F.resolve(e.rootDir,f);if(O.existsSync(h)){let w=F.relative(u,h),_=o.indexOf(y);o[_]=y.replace(f,w);}else return qe(`Anchor file not found: "${f}". Anchors must be relative to the .purpose file directory (${u}).`)}}let g=de(p);g.aspects||(g.aspects={});let m=J(i);return g.aspects[m]={description:r,anchors:o,...a&&{tags:a},...c&&{"applies-to":c},...l&&{enforcement:l}},pe(p,g),await s(),X({action:"add_aspect",file:p,id:m,symbol:`~${m}`,anchors:o})}async function Cp(n,e,s){let{purposeFile:t,id:i,description:r,category:o,severity:a,emitters:c,related:l,data:d}=n,p=le(t,e.rootDir),u=de(p);u.signals||(u.signals={});let g=J(i);return u.signals[g]={description:r,...o&&{category:o},...a&&{severity:a},...c&&{emitters:c.map(m=>M(m,"#"))},...l&&{related:l},...d&&{data:d}},pe(p,u),await s(),X({action:"add_signal",file:p,id:g,symbol:`!${g}`})}async function Pp(n,e,s){let{purposeFile:t,id:i,description:r,gates:o,signals:a,components:c,steps:l}=n,d=le(t,e.rootDir),p=de(d),u=An(p.flows),g=J(i),m={description:r,...o&&{gates:o.map(y=>M(y,"^"))},...a&&{signals:a.map(y=>M(y,"!"))},...c&&{components:c.map(y=>M(y,"#"))},...l&&{steps:l}};return u[g]=m,p.flows=u,pe(d,p),await s(),X({action:"add_flow",file:d,id:g,symbol:`$${g}`})}async function Rp(n,e,s){let{purposeFile:t,id:i,description:r,requires:o,keys:a,signals:c}=n,l=le(t,e.rootDir),d=de(l);d.gates||(d.gates={});let p=J(i);return d.gates[p]={description:r,...o&&{requires:o},...a&&{keys:a},...c&&{signals:c.map(u=>M(u,"!"))}},pe(l,d),await s(),X({action:"add_gate",file:l,id:p,symbol:`^${p}`})}async function jp(n,e,s){let{purposeFile:t,id:i,description:r,type:o,default:a,properties:c}=n,l=le(t,e.rootDir),d=de(l);d.states||(d.states={});let p=J(i),u={description:r};return o!==void 0&&(u.type=o),a!==void 0&&(u.default=a),c!==void 0&&(u.properties=c),d.states[p]=u,pe(l,d),await s(),X({action:"add_state",file:l,id:p})}async function Tp(n,e,s){let{purposeFile:t,componentId:i,section:r,signals:o,aspects:a,gates:c,flows:l,components:d}=n,p=le(t,e.rootDir),u=de(p),g=J(i),m=r;if(!m){let h=Ke(u.components),w=Ke(u.features);if(g in h)m="components";else if(g in w)m="features";else return qe(`Component "${g}" not found in components or features. Specify section explicitly.`)}let y=Ke(u[m]);if(!(g in y))return qe(`Component "${g}" not found in ${m} section.`);let f=y[g];o&&(f.signals=ot(f.signals,o.map(h=>M(h,"!")))),c&&(f.gates=ot(f.gates,c.map(h=>M(h,"^")))),l&&(f.flows=ot(f.flows,l.map(h=>M(h,"$")))),d&&(f.components=ot(f.components,d.map(h=>M(h,"#")))),a&&(f.aspects=ot(f.aspects,a.map(h=>M(h,"~")))),y[g]=f,u[m]=y,pe(p,u),await s();let b=[];return o&&b.push(`signals: ${o.join(", ")}`),a&&b.push(`aspects: ${a.join(", ")}`),c&&b.push(`gates: ${c.join(", ")}`),l&&b.push(`flows: ${l.join(", ")}`),d&&b.push(`components: ${d.join(", ")}`),X({action:"link",file:p,componentId:g,section:m,added:b})}async function Dp(n,e,s){let{purposeFile:t,section:i,id:r}=n,o=le(t,e.rootDir),a=de(o),c=J(r);if(i==="flows"){let l=An(a.flows);if(!(c in l))return qe(`Flow "${c}" not found in flows section.`);delete l[c],a.flows=l;}else if(i==="components"||i==="features"){let l=Ke(a[i]);if(!(c in l))return qe(`"${c}" not found in ${i} section.`);delete l[c],a[i]=l;}else {let l=a[i];if(!l||!(c in l))return qe(`"${c}" not found in ${i} section.`);delete l[c];}return pe(o,a),await s(),X({action:"remove",file:o,section:i,id:c})}async function Ap(n,e,s){let{oldId:t,newId:i,symbolType:r}=n,o=await xa(e.rootDir,t,i,r);return await s(),X({action:"rename",oldSymbol:`${r}${J(t)}`,newSymbol:`${r}${J(i)}`,filesModified:o.length,files:o})}async function Op(n,e,s){let{id:t,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:p}=n,u=Ra(e.rootDir,{id:t,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:p});await s();let g=J(t);return X({action:"portal_add_gate",file:u,id:g,symbol:`^${g}`})}async function Ip(n,e,s){let{route:t,method:i,gates:r}=n,o=ja(e.rootDir,{route:t,method:i,gates:r});return await s(),X({action:"portal_add_route",file:o,route:`${i} ${t}`,gates:r})}var $p=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi;function Ta(n,e){let s=[];function t(r,o){if(typeof r=="string"){let a=r.match($p);if(a)for(let c of a)s.push({type:"warning",message:`Clarification needed: ${c}`,path:o});}}t(n.description,"description");let i=[{key:"components",items:n.components},{key:"features",items:n.features},{key:"gates",items:n.gates},{key:"signals",items:n.signals},{key:"aspects",items:n.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"&&t(a.description,`${r.key}.${o}.description`);if(n.flows&&typeof n.flows=="object"){let r=Array.isArray(n.flows)?[]:Object.entries(n.flows);for(let[o,a]of r)a&&typeof a.description=="string"&&t(a.description,`flows.${o}.description`);}return s}async function Fp(n,e){let{purposeFile:s,includePortal:t=true}=n,i=[];if(s){let a=le(s,e.rootDir),c=a$8(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=Ta(c.data);l.issues.push(...d),i.push({file:a,valid:l.valid,issues:l.issues});}}else {let a=await c$5(e.rootDir);for(let c of a){let l=a$8(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=Ta(l.data);d.issues.push(...p),i.push({file:c,valid:d.valid,issues:d.issues});}}if(t){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 X({action:"validate",valid:o,totalFiles:i.length,totalIssues:r,results:i})}var Ja=[{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}],Mp=30*1e3,Ls=new Map;function ie(n){let e=F.resolve(n),s=Ls.get(e);if(s&&Date.now()-s.loadedAt<Mp)return s.habits;let t=Lp(e);return Ls.set(e,{habits:t,loadedAt:Date.now()}),t}function Lp(n){let e=new Map;for(let a of Ja)e.set(a.id,{...a});let s=process.env.HOME||process.env.USERPROFILE||"~",t=Ea(F.join(s,".paradigm","habits.yaml"));t&&Na(e,t);let i=Ha(F.join(s,".paradigm","habits"));for(let a of i)e.set(a.id,a);let r=Ea(F.join(n,".paradigm","habits.yaml"));r&&Na(e,r);let o=Ha(F.join(n,".paradigm","habits"));for(let a of o)e.set(a.id,a);return Array.from(e.values())}function Ea(n){if(!O.existsSync(n))return null;try{let e=O.readFileSync(n,"utf8");return Z.load(e)}catch{return null}}function Na(n,e){if(e.habits)for(let s of e.habits)n.set(s.id,{...s});if(e.overrides)for(let[s,t]of Object.entries(e.overrides)){let i=n.get(s);i&&(t.severity!==void 0&&(i.severity=t.severity),t.enabled!==void 0&&(i.enabled=t.enabled));}}function Wp(n,e){return n.filter(s=>s.enabled&&s.trigger===e)}function Ws(n){Ls.delete(F.resolve(n));}function Ha(n){if(!O.existsSync(n))return [];try{let e=O.readdirSync(n).filter(t=>t.endsWith(".habit")).sort(),s=[];for(let t of e)try{let i=O.readFileSync(F.join(n,t),"utf8"),r=Z.load(i);r?.id&&r?.name&&s.push(r);}catch{}return s}catch{return []}}var qa=["discovery","verification","testing","documentation","collaboration","security"],Ma=["preflight","postflight","on-commit","on-stop"],La=["advisory","warn","block"],Wa=["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"],Jp=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Js(n){let e=[];if(n.id||e.push("Missing required field: id"),n.name||e.push("Missing required field: name"),n.description||e.push("Missing required field: description"),n.category||e.push("Missing required field: category"),n.trigger||e.push("Missing required field: trigger"),n.severity||e.push("Missing required field: severity"),n.check||e.push("Missing required field: check"),(n.enabled===void 0||n.enabled===null)&&e.push("Missing required field: enabled"),n.id&&!Jp.test(n.id)&&e.push(`Invalid id format: "${n.id}" \u2014 must be kebab-case (lowercase, hyphens only)`),n.category&&!qa.includes(n.category)&&e.push(`Invalid category: "${n.category}" \u2014 must be one of: ${qa.join(", ")}`),n.trigger&&!Ma.includes(n.trigger)&&e.push(`Invalid trigger: "${n.trigger}" \u2014 must be one of: ${Ma.join(", ")}`),n.severity&&!La.includes(n.severity)&&e.push(`Invalid severity: "${n.severity}" \u2014 must be one of: ${La.join(", ")}`),n.check){Wa.includes(n.check.type)||e.push(`Invalid check.type: "${n.check.type}" \u2014 must be one of: ${Wa.join(", ")}`);let s=n.check.params||{};switch(n.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 "${n.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 Gp=new Set(Ja.map(n=>n.id));function Mn(n){return Gp.has(n)}function Gs(n,e,s="project"){let t=s==="global"?F.join(process.env.HOME||process.env.USERPROFILE||"~",".paradigm","habits"):F.join(n,".paradigm","habits");O.existsSync(t)||O.mkdirSync(t,{recursive:true});let i=F.join(t,`${e.id}.habit`),r=Z.dump(e,{lineWidth:120,noRefs:true});return O.writeFileSync(i,r,"utf8"),Ws(n),i}function Ga(n,e){if(Mn(e))return {removed:false,reason:`"${e}" is a seed habit and cannot be removed. Use overrides in habits.yaml to disable it.`};let s=F.join(n,".paradigm","habits",`${e}.habit`);if(O.existsSync(s))return O.unlinkSync(s),Ws(n),{removed:true};let t=process.env.HOME||process.env.USERPROFILE||"~",i=F.join(t,".paradigm","habits",`${e}.habit`);return O.existsSync(i)?(O.unlinkSync(i),Ws(n),{removed:true}):{removed:false,reason:`No .habit file found for "${e}". It may be defined in habits.yaml \u2014 edit that file directly.`}}var Us=0;function Et(n,e,s,t,i){let r=Wp(n,e);t&&(r=r.filter(u=>!u.platforms||u.platforms.includes(t)));let o=0;if(i)try{let{isGraduated:u}=(qn(),d$a(Fa)),g=r.length;r=r.filter(m=>!u(i,m.id)),o=g-r.length;}catch{}Us=o;let a=r.map(u=>Up(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 Nt(n){return {toolsCalled:n.toolsCalled||[],filesModified:n.filesModified||[],symbolsTouched:n.symbolsTouched||[],loreRecorded:n.loreRecorded||false,hasPortalRoutes:n.hasPortalRoutes||false,taskAddsRoutes:n.taskAddsRoutes||false,taskDescription:n.taskDescription,gitClean:n.gitClean}}function Up(n,e){switch(n.check.type){case "tool-called":return zp(n,e);case "file-exists":return Bp(n,e);case "file-modified":return Xp(n,e);case "lore-recorded":return Vp(n,e);case "symbols-registered":return Yp(n,e);case "gates-declared":return Kp(n,e);case "tests-exist":return Qp(n,e);case "git-clean":return Zp(n,e);case "commit-message-format":return eu(n,e);case "flow-coverage":return tu(n,e);case "context-checked":return nu(n,e);case "aspect-anchored":return su(n,e);default:return {habit:n,result:"partial",reason:`Unknown check: ${n.check.type}`}}}function zp(n,e){let s=n.check.params.tools||[];if(s.length===0)return {habit:n,result:"followed",reason:"No tools required"};let t=s.filter(i=>e.toolsCalled.includes(i));return t.length>0?{habit:n,result:"followed",reason:`Called: ${t.join(", ")}`,evidence:t}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:n,result:"followed",reason:"No modifications, habit not applicable"}:{habit:n,result:"skipped",reason:`None of [${s.join(", ")}] were called before modifying code`}}function Bp(n,e){if(e.filesModified.length===0)return {habit:n,result:"followed",reason:"No files modified"};if(e.filesModified.some(i=>i.endsWith(".purpose")||i.includes(".paradigm/")))return {habit:n,result:"followed",reason:"Purpose files updated"};let t=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 t.length===0?{habit:n,result:"followed",reason:"Only non-source files modified"}:{habit:n,result:"skipped",reason:`${t.length} source file(s) without .purpose updates`,evidence:t.slice(0,5)}}function Vp(n,e){let s=e.filesModified.filter(t=>!t.endsWith(".md")&&!t.endsWith(".json")&&!t.endsWith(".yaml")&&!t.endsWith(".yml")&&!t.endsWith(".lock")&&!t.endsWith(".purpose")&&!t.includes(".paradigm/"));return s.length<3?{habit:n,result:"followed",reason:"Session not significant (< 3 source files)"}:e.loreRecorded||e.toolsCalled.includes("paradigm_lore_record")?{habit:n,result:"followed",reason:"Lore recorded"}:{habit:n,result:"skipped",reason:`${s.length} source files modified, no lore entry`,evidence:s.slice(0,5)}}function Yp(n,e){if(e.symbolsTouched.length===0)return {habit:n,result:"followed",reason:"No symbols touched"};let t=["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 t.length>0?{habit:n,result:"followed",reason:`Purpose tools called: ${t.join(", ")}`,evidence:t}:{habit:n,result:"partial",reason:`${e.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function Kp(n,e){if(!e.taskAddsRoutes)return {habit:n,result:"followed",reason:"No routes added"};if(e.hasPortalRoutes)return {habit:n,result:"followed",reason:"Portal.yaml has routes"};let t=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(i=>e.toolsCalled.includes(i));return t.length>0?{habit:n,result:"followed",reason:`Gate tools called: ${t.join(", ")}`,evidence:t}:{habit:n,result:"skipped",reason:"Routes added without gate declarations"}}function Qp(n,e){if(e.filesModified.length===0)return {habit:n,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:n,result:"followed",reason:`Test files: ${s.length}`,evidence:s.slice(0,5)};let t=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 t.length===0?{habit:n,result:"followed",reason:"No source files to test"}:{habit:n,result:"partial",reason:`${t.length} source file(s), no test files updated`,evidence:t.slice(0,5)}}function Xp(n,e){if(e.filesModified.length===0)return {habit:n,result:"followed",reason:"No files modified"};let s=n.check.params.patterns||[];if(s.length===0)return {habit:n,result:"followed",reason:"No patterns specified"};if(n.trigger==="on-stop"&&n.severity==="block"){let i=e.filesModified.filter(r=>s.some(o=>r.includes(o)||F.basename(r)===o));return i.length>0?{habit:n,result:"followed",reason:`Matching files: ${i.join(", ")}`,evidence:i}:{habit:n,result:"partial",reason:`None of [${s.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let t=e.filesModified.filter(i=>s.some(r=>i.includes(r)||F.basename(i)===r));return t.length>0?{habit:n,result:"followed",reason:`Matching files: ${t.join(", ")}`,evidence:t}:{habit:n,result:"skipped",reason:`None of [${s.join(", ")}] found in modified files`}}function Zp(n,e){return e.filesModified.length===0?{habit:n,result:"followed",reason:"No files modified"}:n.trigger==="on-stop"?{habit:n,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:e.gitClean===void 0?{habit:n,result:"partial",reason:"Git status not available"}:e.gitClean?{habit:n,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:n,result:"skipped",reason:"Uncommitted changes in working tree"}}function eu(n,e){if(!e.commitMessage)return {habit:n,result:"followed",reason:"No commit message to check (not a commit trigger)"};let s=n.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],t=s.filter(i=>new RegExp(i,"m").test(e.commitMessage));if(t.length===s.length)return {habit:n,result:"followed",reason:"Commit message matches all required patterns",evidence:t};if(t.length>0){let i=s.filter(r=>!new RegExp(r,"m").test(e.commitMessage));return {habit:n,result:"partial",reason:`Matches ${t.length}/${s.length} patterns. Missing: ${i.join(", ")}`}}return {habit:n,result:"skipped",reason:"Commit message does not match required format patterns"}}function tu(n,e){let s=e.symbolsTouched.filter(r=>r.startsWith("#"));if(s.length<3)return {habit:n,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(e.hasFlowCoverage)return {habit:n,result:"followed",reason:"Flow coverage exists for multi-component changes"};let i=["paradigm_flow_validate","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(r=>e.toolsCalled.includes(r));return i.length>0?{habit:n,result:"followed",reason:`Flow tools called: ${i.join(", ")}`,evidence:i}:{habit:n,result:"skipped",reason:`${s.length} components touched without flow coverage`,evidence:s.slice(0,5)}}function nu(n,e){let t=(n.check.params.contextTools||["paradigm_context_check","paradigm_session_recover","paradigm_session_checkpoint"]).filter(i=>e.toolsCalled.includes(i));return t.length>0?{habit:n,result:"followed",reason:`Context tools called: ${t.join(", ")}`,evidence:t}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:n,result:"followed",reason:"No modifications, context check not applicable"}:{habit:n,result:"skipped",reason:"No context/session tools called during session"}}function su(n,e){let s=e.symbolsTouched.filter(t=>t.startsWith("~"));return s.length===0?{habit:n,result:"followed",reason:"No aspects touched"}:e.aspectAnchorsValid===true?{habit:n,result:"followed",reason:"Aspect anchors validated and valid"}:e.toolsCalled.includes("paradigm_aspect_check")?{habit:n,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:n,result:"skipped",reason:`${s.length} aspect(s) touched without anchor validation`,evidence:s.slice(0,5)}}var Ht=null,zs=false;async function Bs(n){if(Ht)zs||(await Ht.ensureReady(),zs=true);else {let e=F.join(n,".paradigm","sentinel","sentinel.db");Ht=new f$4(e),await Ht.ensureReady(),zs=true;}return Ht}async function iu(n,e){return (await Bs(n)).recordPracticeEvent(e)}async function za(n,e){return (await Bs(n)).getPracticeEvents(e)}async function ue(n,e){return (await Bs(n)).getComplianceRate(e)}async function qt(n,e){let s=["discovery","verification","testing","documentation","collaboration","security"],t=[];for(let i of s){let r=await ue(n,{...e,habitCategory:i});r.total>0&&t.push({category:i,...r});}return t}async function Ba(n,e,s){let t=[];for(let i of e){let r=await iu(n,{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});t.push(r);}return t}var ou=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,au=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"],cu=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi];function Va(){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.
766
804
 
767
- 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 Ya(n,e,s){switch(n){case "paradigm_pm_preflight":{let{task:t}=e,i=await lu(t,s),r=JSON.stringify(i,null,2);return o(r.length,n),{text:r,handled:true}}case "paradigm_pm_postflight":{let{filesModified:t,symbolsTouched:i}=e,r=pu(t,i,s),o$1=JSON.stringify(r,null,2);return o(o$1.length,n),{text:o$1,handled:true}}default:return {text:"",handled:false}}}async function lu(n,e){let s=n.toLowerCase(),t=n.match(ou)||[],i=[...new Set(t)],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(_=>_.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=Object.keys(e.gateConfig.gates||{});a.gateCount=u.length,a.gates=u.map(g=>g.startsWith("^")?g:`^${g}`),a.routeCount=Object.keys(e.gateConfig.routes||{}).length;}let c=au.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=ie(e.rootDir),m=j$1().getStats(),y=[...new Set(m.toolCalls.map(w=>w.toolName))],f=Et({toolsCalled:y,filesModified:[],symbolsTouched:i,loreRecorded:!1,hasPortalRoutes:a.exists&&a.routeCount>0,taskAddsRoutes:c,taskDescription:n}),b=Nt(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 ue(e.rootDir,{dateFrom:h});}catch{}return {task:n.slice(0,100)+(n.length>100?"...":""),affectedSymbols:r,rippleAnalysis:o,portalStatus:a,taskAddsRoutes:c,requiredChecks:l,recommendations:du(r,o,a,c),habits:{evaluation:d,recentCompliance:p?{rate:p.rate,totalEvents:p.total}:null}}}function du(n,e,s,t){let i=[],r=n.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.`),t&&!s.exists?i.push("Task adds routes but no portal.yaml exists. Create one with appropriate ^gates."):t&&i.push("Task adds routes. Update portal.yaml with gate entries after implementation.");let a=n.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 pu(n,e,s){let t=[],i$1=s.gateConfig?.routes?Object.keys(s.gateConfig.routes):[];for(let p of n){let u=F.isAbsolute(p)?p:F.join(s.rootDir,p);if(!O.existsSync(u))continue;let g;try{g=O.readFileSync(u,"utf-8");}catch{continue}for(let m of cu){m.lastIndex=0;let y;for(;(y=m.exec(g))!==null;){let f=y[2]||y[0];f&&f.startsWith("/")&&(!i$1.some(h=>h.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===f)&&s.gateConfig?t.push({type:"missing-portal-gate",severity:"warning",message:`Route "${f}" in ${F.relative(s.rootDir,u)} not in portal.yaml`,file:F.relative(s.rootDir,u),suggestion:"Add route to portal.yaml with ^gates. Use paradigm_gates_for_route for suggestions."}):!s.gateConfig&&f.startsWith("/api/")&&t.push({type:"missing-portal-gate",severity:"warning",message:`API route "${f}" found but no portal.yaml exists`,file:F.relative(s.rootDir,u),suggestion:"Create portal.yaml to declare gates for API routes."}));}}}for(let p of e)j$2(s.index,p).length===0&&t.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${p}" is not registered in any .purpose file`,suggestion:"Add to nearest .purpose file using paradigm_purpose_add_component or paradigm_purpose_add_signal."});let r=s.gateConfig?Object.keys(s.gateConfig.gates||{}).map(p=>p.startsWith("^")?p.slice(1):p):[];for(let p of e)if(p.startsWith("^")){let u=p.slice(1);r.includes(u)||t.push({type:"missing-portal-gate",severity:"error",message:`Gate "${p}" referenced but not declared in portal.yaml`,suggestion:`Add ${p} to portal.yaml with description and check expression.`});}let o=i(s.index,"aspect");for(let p of o){let u=p.appliesTo||[];if(u.length!==0){for(let g of u){let m=g.includes("*");for(let y of e){let f=false;if(m?f=new RegExp("^"+g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(y):f=y===g,f){let b=p.anchors||[];if(b.length===0)t.push({type:"stale-aspect",severity:"warning",message:`Aspect "${p.symbol}" applies to "${y}" but has no code anchors`,suggestion:`Add anchors to ${p.symbol} in .purpose file. Run paradigm_aspect_check for details.`});else for(let h of b){let w=F.isAbsolute(h.path)?h.path:F.join(s.rootDir,h.path);O.existsSync(w)||t.push({type:"stale-aspect",severity:"warning",message:`Aspect "${p.symbol}" anchor "${h.raw}" points to missing file`,suggestion:`Update anchors for ${p.symbol} in .purpose file.`});}}}}for(let g of e){if(!g.startsWith("#"))continue;(p.data||{}).aspects||[];for(let f of u){if(!f.includes("*"))continue;if(new RegExp("^"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(g))break}}}}n.length>=5&&e.length>=3&&t.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${n.length} files, ${e.length} symbols) \u2014 consider recording decisions`,suggestion:"Use paradigm_wisdom_record to capture architectural decisions or antipatterns."});for(let p of e){let u=j$2(s.index,p);if(u.length===0)continue;let g=u[0];g.parentSymbol&&j$2(s.index,g.parentSymbol).length===0&&t.push({type:"broken-reference",severity:"warning",message:`Symbol "${p}" references parent "${g.parentSymbol}" which does not exist`,suggestion:"Create the parent symbol or update the parent reference in the .purpose file."});}let a=t.filter(p=>p.severity==="error").length,c=t.filter(p=>p.severity==="warning").length,l="pass";a>0?l="violations":c>0&&(l="warnings");let d=null;try{let p=ie(s.rootDir),g=j$1().getStats(),m=[...new Set(g.toolCalls.map(_=>_.toolName))],y=m.includes("paradigm_lore_record"),f;try{f=execSync("git status --porcelain",{cwd:s.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let b=Et({toolsCalled:m,filesModified:n,symbolsTouched:e,loreRecorded:y,hasPortalRoutes:s.gateConfig!==null&&s.gateConfig.routes!=null,taskAddsRoutes:!1,gitClean:f}),h=Nt(p,"postflight",b,void 0,s.rootDir);d={trigger:"postflight",total:h.summary.total,followed:h.summary.followed,skipped:h.summary.skipped,partial:h.summary.partial,blockingViolations:h.summary.blockingViolations,results:h.evaluations.map(_=>({id:_.habit.id,name:_.habit.name,severity:_.habit.severity,result:_.result,reason:_.reason}))};let w=F.join(s.rootDir,".paradigm",".habits-blocking");if(h.blocksCompletion){let _=h.evaluations.filter(k=>k.result==="skipped"&&k.habit.severity==="block").map(k=>`${k.habit.name}: ${k.reason}`);O.writeFileSync(w,_.join(`
768
- `),"utf8");}else O.existsSync(w)&&O.unlinkSync(w);}catch{}return {status:l,violations:t,summary:{totalChecks:7,passed:7-(a>0?1:0)-(c>0?1:0),warnings:c,errors:a},blocksCompletion:a>0,habitsEvaluation:d}}j();function Ka(){let n=process.env.PARADIGM_AUTHOR;if(n)return Vs(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Vs(e)}catch{}try{let e=ma.userInfo().username;if(e)return Vs(e)}catch{}return "unknown"}function Vs(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function Za(){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","decision","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}},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, decision, milestone, etc.). Call after completing significant work. Returns the created entry ID and file path. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","decision","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","decision","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 ec(n,e,s){switch(n){case "paradigm_lore_search":{let t={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},i=await a$1(s.rootDir,t);return {handled:true,text:JSON.stringify({count:i.length,filter:Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),entries:i.map(Qa)},null,2)}}case "paradigm_lore_record":{let{type:t,title:i,summary:r,symbols_touched:o,symbols_created:a,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:_,linked_lore:k,linked_tasks:v,linked_commits:S,confidence:x}=e,C;try{let I=new Date(Date.now()-2592e6).toISOString(),A=await ue(s.rootDir,{dateFrom:I});if(A.total>0){let H=(await qt(s.rootDir,{dateFrom:I})).filter(q=>q.rate<60).map(q=>q.category);C={rate:A.rate,followed:A.followed,skipped:A.skipped,partial:A.partial,weakAreas:H.length>0?H:void 0};}}catch{}let T={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:g,author:Ka(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:i,summary:r,symbols_touched:o,symbols_created:a,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:C,body:_,linked_lore:k,linked_tasks:v,linked_commits:S,confidence:x!=null&&x>=0&&x<=1?x:void 0},j=await d$1(s.rootDir,T);j$1().setLastLoreEntryId(j);try{let I=process.env.PARADIGM_AGENT_ID;if(I&&o&&o.length>0){let{updateExpertiseFromLore:A}=await import('./agent-loader-CZFB5BDP.js');A(s.rootDir,I,{symbols_touched:o,confidence:x!=null&&x>=0&&x<=1?x:void 0});}}catch{}let P=null;try{c&&c.length>=2&&(P=Z$1(s.rootDir,c,l||[]));}catch{}let D;if(e.stream){let I=e.stream,A=I==="auto"?gu(e):I;try{if(A==="work-log"){let{recordWorkLog:N}=await import('./work-log-loader-DL5GZ2BQ.js');N(s.rootDir,{agent:T.agent?.model||"unknown",summary:T.summary,outcome:T.verification?.status==="pass"?"pass":T.verification?.status==="fail"?"fail":"partial",files_modified:T.files_modified,symbols_touched:T.symbols_touched,commit:T.commit,linked_lore:T.id||j}),D="work-log";}else if(A==="journal"&&T.learnings?.length){let{recordJournalEntry:N}=await import('./journal-loader-GLH7XFTK.js');for(let H of T.learnings)N(T.agent?.model||"unknown",{trigger:"self_reflection",insight:H,project:s.projectName||"unknown",transferable:!1,linked_work_log:T.id||j});D="journal";}else if(A==="decision"&&T.decisions?.length){let{recordDecision:N}=await import('./decision-loader-2XPZE4EZ.js');for(let H of T.decisions)N(s.rootDir,{title:H.decision.slice(0,100),decision:H.decision,rationale:H.rationale,participants:[{id:`agent/${T.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:T.symbols_touched,status:"active",linked_lore:T.id||j});D="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:j,type:t,title:i,message:"Lore entry recorded successfully",...D?{stream:D}:{},...P?{protocol_suggestion:P}:{}})}}case "paradigm_lore_timeline":{let t=e.limit||10,i=await c$1(s.rootDir),r=await a$1(s.rootDir,{limit:t}),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(Qa),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 t=e.id,i=await b$3(s.rootDir,t);return i?{handled:true,text:JSON.stringify(i,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})}}case "paradigm_lore_update":{let t=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$4(s.rootDir,t,o);return {handled:true,text:JSON.stringify({success:a,id:t,message:a?"Lore entry updated":`Lore entry not found: ${t}`})}}case "paradigm_lore_assess":{let t=e.id,i=e.verdict,r=e.notes,o=await b$3(s.rootDir,t);if(!o)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})};let a={verdict:i,assessed_by:Ka(),assessed_at:new Date().toISOString(),notes:r},c=await h$3(s.rootDir,t,a);try{let u=process.env.PARADIGM_AGENT_ID;if(u&&c&&o.symbols_touched?.length){let{updateExpertiseFromAssessment:g}=await import('./agent-loader-CZFB5BDP.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:t,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: ${t}`})}}case "paradigm_lore_calibration":{let t={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},i=await a$1(s.rootDir,t),r=i.filter(_=>_.confidence!=null),o=i.length,a=r.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,p=0;for(let _ of i){let k=_.assessment.verdict;c[k]++;let v=k==="correct"?1:k==="partial"?.5:0;l+=v,_.confidence!=null&&(d+=_.confidence,p+=Math.abs(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 _=new Map;for(let k of i){let v=[];f==="symbol"?v=k.symbols_touched||[]:f==="tag"?v=k.tags||[]:f==="type"&&(v=[k.type||"agent-session"]);for(let S of v)_.has(S)||_.set(S,[]),_.get(S).push(k);}b=Array.from(_.entries()).map(([k,v])=>{let S=v.filter(P=>P.confidence!=null),x={correct:0,partial:0,incorrect:0},C=0,T=0,j=0;for(let P of v){let D=P.assessment.verdict;x[D]++;let I=D==="correct"?1:D==="partial"?.5:0;C+=I,P.confidence!=null&&(T+=P.confidence,j+=Math.abs(I-P.confidence));}return {key:k,total:v.length,accuracyRate:C/v.length,avgConfidence:S.length>0?T/S.length:null,calibrationScore:S.length>0?1-j/S.length:null,verdictBreakdown:x}}).sort((k,v)=>v.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 t=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,t);return {handled:true,text:JSON.stringify({success:r,id:t,message:r?"Lore entry deleted":`Lore entry not found: ${t}`})}}default:return {handled:false,text:""}}}function gu(n){return n.task_ref||n.files_modified||n.commit?"work-log":n.learnings||n.confidence!==void 0?"journal":n.decisions?.some(s=>s.rationale)?"decision":"work-log"}function Qa(n){return {id:n.id,type:n.type,title:n.title,summary:n.summary,author:n.author,agent:n.agent,timestamp:n.timestamp,duration_minutes:n.duration_minutes,symbols_touched:n.symbols_touched,verification:n.verification?.status,review:n.review?{completeness:n.review.completeness,quality:n.review.quality}:null,confidence:n.confidence??null,assessment:n.assessment?n.assessment.verdict:null,assessment_delta:n.assessment_delta??null,tags:n.tags}}function nc(){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 sc(n,e,s){switch(n){case "paradigm_habits_list":{let t=fu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_check":{let t=await yu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_status":{let t=await _u(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_practice_context":{let t=await ku(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_add":{let t=bu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_edit":{let t=wu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_remove":{let t=vu(e,s);return o(t.length,n),{text:t,handled:true}}default:return {text:"",handled:false}}}function fu(n,e){let s=n.trigger,t=n.category,i=n.enabled,r=ie(e.rootDir);s&&(r=r.filter(a=>a.trigger===s)),t&&(r=r.filter(a=>a.category===t)),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:t,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 yu(n,e){let s=n.trigger,t=n.filesModified||[],i=n.symbolsTouched||[],r=n.taskDescription,o=n.record!==false,a=ie(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=Et({toolsCalled:d,filesModified:t,symbolsTouched:i,loreRecorded:p,hasPortalRoutes:e.gateConfig!==null&&e.gateConfig.routes!=null,taskAddsRoutes:g,taskDescription:r,gitClean:m}),b=Nt(a,s,y,"claude",e.rootDir),h=[];if(o&&b.evaluations.length>0)try{let k=c.getLastLoreEntryId()??void 0;h=await Ba(e.rootDir,b.evaluations.map(v=>({habitId:v.habit.id,habitCategory:v.habit.category,result:v.result,notes:v.reason})),{engineer:"agent",sessionId:l.sessionId,loreEntryId:k,taskDescription:r,symbolsTouched:i,filesModified:t});}catch{}let w=F.join(e.rootDir,".paradigm",".habits-blocking");try{if(s==="on-stop"&&b.blocksCompletion){let k=b.evaluations.filter(v=>v.result==="skipped"&&v.habit.severity==="block").map(v=>`${v.habit.name}: ${v.reason}`);O.writeFileSync(w,k.join(`
769
- `),"utf8");}else s==="on-stop"&&O.existsSync(w)&&O.unlinkSync(w);}catch{}let _=Us;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},..._>0?{graduatedToHooks:_,graduatedNote:`${_} 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:hu(b)},null,2)}function hu(n){let e=[];for(let s of n.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 bu(n,e){let s=n.id,t=n.scope||"project";if(Mn(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(ie(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:n.name,description:n.description,category:n.category,trigger:n.trigger,severity:n.severity,check:n.check,enabled:n.enabled!==void 0?n.enabled:true};n.platforms&&(o.platforms=n.platforms);let a=Js(o);if(!a.valid)return JSON.stringify({error:true,message:"Validation failed",errors:a.errors},null,2);let c=Gs(e.rootDir,o,t);return JSON.stringify({created:true,id:o.id,filePath:c,scope:t,message:`Habit "${o.name}" created at ${c}`},null,2)}function wu(n,e){let s=n.id;if(Mn(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 t=F.join(e.rootDir,".paradigm","habits",`${s}.habit`),i=process.env.HOME||process.env.USERPROFILE||"~",r=F.join(i,".paradigm","habits",`${s}.habit`),o=null,a="project";if(O.existsSync(t)?(o=t,a="project"):O.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=O.readFileSync(o,"utf8");c=Z.load(p);}catch{return JSON.stringify({error:true,message:`Failed to read ${o}`},null,2)}let l={...c};n.name!==void 0&&(l.name=n.name),n.description!==void 0&&(l.description=n.description),n.category!==void 0&&(l.category=n.category),n.trigger!==void 0&&(l.trigger=n.trigger),n.severity!==void 0&&(l.severity=n.severity),n.check!==void 0&&(l.check=n.check),n.enabled!==void 0&&(l.enabled=n.enabled),n.platforms!==void 0&&(l.platforms=n.platforms);let d=Js(l);return d.valid?(Gs(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 vu(n,e){let s=n.id,t=Ga(e.rootDir,s);return t.removed?JSON.stringify({removed:true,id:s,message:`Habit "${s}" removed`},null,2):JSON.stringify({error:true,message:t.reason},null,2)}async function _u(n,e){let s=n.engineer,t=n.period||"30d",i=new Date,r;if(t!=="all"){let h=parseInt(t.replace("d",""),10)||30;r=new Date(i.getTime()-h*24*60*60*1e3).toISOString();}let o={engineer:s,dateFrom:r},a=await ue(e.rootDir,o),c=await qt(e.rootDir,o),l=await za(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},_=h.result;w[_]++,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=ie(e.rootDir),f=new Map(y.map(h=>[h.id,h.name])),b=Array.from(d.entries()).map(([h,w])=>{let _=w.followed+w.skipped+w.partial,k=_>0?Math.round((w.followed+w.partial*.5)/_*100):100;return {habitId:h,habitName:f.get(h)||h,...w,total:_,rate:k}}).sort((h,w)=>h.rate-w.rate);return JSON.stringify({period:t,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 ku(n,e){let s=n.symbols||[],t=n.task,r=ie(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 ue(e.rootDir,{dateFrom:d}),g=(await qt(e.rootDir,{dateFrom:d})).filter(m=>m.rate<60).map(m=>m.category);return JSON.stringify({symbols:s,task:t||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)}qn();Hs();async function ic(n){let e=ct(n);if(!e.enabled)return [];let s=ie(n),t=[];for(let i of s){if(!i.enabled)continue;let r=await Su(n,i,e);t.push(r);}return t}async function Su(n,e,s){let t=Hn(n,e.id),i={habitId:e.id,habitName:e.name,currentTier:t.tier,neverGraduate:false,inCooldown:false};if(t.tier==="hook")return {...i,eligible:false,reason:"Already graduated to hook"};if(t.neverGraduate||s.neverGraduate.includes(e.id))return {...i,eligible:false,reason:"Marked as never-graduate (requires agent cognition)",neverGraduate:true};if(Es.has(e.check.type))return {...i,eligible:false,reason:`Check type "${e.check.type}" cannot graduate \u2014 requires MCP tool output`,neverGraduate:true};if(t.cooldownUntil&&new Date(t.cooldownUntil)>new Date)return {...i,eligible:false,reason:`In cooldown until ${t.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 ue(n,{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 ue(n,{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 rc(n){let e=ie(n),s=ct(n),t=Ms(n),i=0,r=0,o=0,a=0;for(let c of e){if(!c.enabled)continue;let l=t[c.id],d=l?.tier||"habit",p=l?.neverGraduate||s.neverGraduate.includes(c.id)||Es.has(c.check.type);d==="hook"?i++:d==="mcp"?o++:r++,p&&a++;}return {hookCount:i,habitCount:r,mcpCount:o,neverGraduateCount:a,states:t}}qn();var xu=[{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 Cu(n,e){let s=await ic(n.rootDir),t=s;if(e.habitId&&(t=s.filter(a=>a.habitId===e.habitId),t.length===0))return JSON.stringify({error:`No habit found with ID "${e.habitId}"`});let i=t.filter(a=>a.eligible),r=t.filter(a=>!a.eligible&&!a.neverGraduate),o=t.filter(a=>a.neverGraduate);return JSON.stringify({summary:{checked:t.length,eligible:i.length,ineligible:r.length,neverGraduate:o.length},...i.length>0?{eligible:i.map(oc),action:"Run `paradigm graduate promote <id>` to graduate eligible habits."}:{},...r.length>0?{ineligible:r.map(oc)}:{},...o.length>0?{neverGraduate:o.map(a=>({id:a.habitId,name:a.habitName,reason:a.reason}))}:{}},null,2)}async function Pu(n){let e=rc(n.rootDir),s=ct(n.rootDir),t={hook:[],habit:[],mcp:[]};for(let[i,r]of Object.entries(e.states)){let o=r.tier||"habit";t[o]||(t[o]=[]),t[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:t,thresholds:s.thresholds},null,2)}function ac(){return xu}async function cc(n,e,s){switch(n){case "paradigm_graduate_check":return {handled:true,text:await Cu(s,e)};case "paradigm_graduate_status":return {handled:true,text:await Pu(s)};default:return {handled:false,text:""}}}function oc(n){return {id:n.habitId,name:n.habitName,tier:n.currentTier,reason:n.reason,...n.complianceRate!==void 0?{complianceRate:n.complianceRate}:{},...n.eventCount!==void 0?{eventCount:n.eventCount}:{},...n.inCooldown?{inCooldown:true}:{}}}var lc=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"]),Ru=.95,ju=.3,Tu=10;function Du(n,e){let s=n.length,t=e.length;if(s===0)return t;if(t===0)return s;let i=Array.from({length:s+1},()=>Array.from({length:t+1},()=>0));for(let r=0;r<=s;r++)i[r][0]=r;for(let r=0;r<=t;r++)i[0][r]=r;for(let r=1;r<=s;r++)for(let o=1;o<=t;o++){let a=n[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][t]}function dc(n){let e=n.toLowerCase().split(/\s+/).filter(s=>s.length>0&&!lc.has(s));return e.sort(),e.join(" ")}function Au(n){try{let e=n.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 pc(n,e,s){let t=s?.limit??Tu,i=dc(e);if(i.length===0)return [];let r=Ou(n,i,s);if(r.length>0)return r.slice(0,t);if(Au(n)){let a=Iu(n,i,s);if(a.length>0)return a.slice(0,t)}return $u(n,i,s).slice(0,t)}function Ou(n,e,s){try{let t=`
805
+ 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 Ya(n,e,s){switch(n){case "paradigm_pm_preflight":{let{task:t}=e,i=await lu(t,s),r=JSON.stringify(i,null,2);return o(r.length,n),{text:r,handled:true}}case "paradigm_pm_postflight":{let{filesModified:t,symbolsTouched:i}=e,r=pu(t,i,s),o$1=JSON.stringify(r,null,2);return o(o$1.length,n),{text:o$1,handled:true}}default:return {text:"",handled:false}}}async function lu(n,e){let s=n.toLowerCase(),t=n.match(ou)||[],i=[...new Set(t)],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(_=>_.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=Object.keys(e.gateConfig.gates||{});a.gateCount=u.length,a.gates=u.map(g=>g.startsWith("^")?g:`^${g}`),a.routeCount=Object.keys(e.gateConfig.routes||{}).length;}let c=au.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=ie(e.rootDir),m=j$1().getStats(),y=[...new Set(m.toolCalls.map(w=>w.toolName))],f=Nt({toolsCalled:y,filesModified:[],symbolsTouched:i,loreRecorded:!1,hasPortalRoutes:a.exists&&a.routeCount>0,taskAddsRoutes:c,taskDescription:n}),b=Et(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 ue(e.rootDir,{dateFrom:h});}catch{}return {task:n.slice(0,100)+(n.length>100?"...":""),affectedSymbols:r,rippleAnalysis:o,portalStatus:a,taskAddsRoutes:c,requiredChecks:l,recommendations:du(r,o,a,c),habits:{evaluation:d,recentCompliance:p?{rate:p.rate,totalEvents:p.total}:null}}}function du(n,e,s,t){let i=[],r=n.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.`),t&&!s.exists?i.push("Task adds routes but no portal.yaml exists. Create one with appropriate ^gates."):t&&i.push("Task adds routes. Update portal.yaml with gate entries after implementation.");let a=n.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 pu(n,e,s){let t=[],i$1=s.gateConfig?.routes?Object.keys(s.gateConfig.routes):[];for(let p of n){let u=F.isAbsolute(p)?p:F.join(s.rootDir,p);if(!O.existsSync(u))continue;let g;try{g=O.readFileSync(u,"utf-8");}catch{continue}for(let m of cu){m.lastIndex=0;let y;for(;(y=m.exec(g))!==null;){let f=y[2]||y[0];f&&f.startsWith("/")&&(!i$1.some(h=>h.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===f)&&s.gateConfig?t.push({type:"missing-portal-gate",severity:"warning",message:`Route "${f}" in ${F.relative(s.rootDir,u)} not in portal.yaml`,file:F.relative(s.rootDir,u),suggestion:"Add route to portal.yaml with ^gates. Use paradigm_gates_for_route for suggestions."}):!s.gateConfig&&f.startsWith("/api/")&&t.push({type:"missing-portal-gate",severity:"warning",message:`API route "${f}" found but no portal.yaml exists`,file:F.relative(s.rootDir,u),suggestion:"Create portal.yaml to declare gates for API routes."}));}}}for(let p of e)j$2(s.index,p).length===0&&t.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${p}" is not registered in any .purpose file`,suggestion:"Add to nearest .purpose file using paradigm_purpose_add_component or paradigm_purpose_add_signal."});let r=s.gateConfig?Object.keys(s.gateConfig.gates||{}).map(p=>p.startsWith("^")?p.slice(1):p):[];for(let p of e)if(p.startsWith("^")){let u=p.slice(1);r.includes(u)||t.push({type:"missing-portal-gate",severity:"error",message:`Gate "${p}" referenced but not declared in portal.yaml`,suggestion:`Add ${p} to portal.yaml with description and check expression.`});}let o=i(s.index,"aspect");for(let p of o){let u=p.appliesTo||[];if(u.length!==0){for(let g of u){let m=g.includes("*");for(let y of e){let f=false;if(m?f=new RegExp("^"+g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(y):f=y===g,f){let b=p.anchors||[];if(b.length===0)t.push({type:"stale-aspect",severity:"warning",message:`Aspect "${p.symbol}" applies to "${y}" but has no code anchors`,suggestion:`Add anchors to ${p.symbol} in .purpose file. Run paradigm_aspect_check for details.`});else for(let h of b){let w=F.isAbsolute(h.path)?h.path:F.join(s.rootDir,h.path);O.existsSync(w)||t.push({type:"stale-aspect",severity:"warning",message:`Aspect "${p.symbol}" anchor "${h.raw}" points to missing file`,suggestion:`Update anchors for ${p.symbol} in .purpose file.`});}}}}for(let g of e){if(!g.startsWith("#"))continue;(p.data||{}).aspects||[];for(let f of u){if(!f.includes("*"))continue;if(new RegExp("^"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(g))break}}}}n.length>=5&&e.length>=3&&t.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${n.length} files, ${e.length} symbols) \u2014 consider recording decisions`,suggestion:"Use paradigm_wisdom_record to capture architectural decisions or antipatterns."});for(let p of e){let u=j$2(s.index,p);if(u.length===0)continue;let g=u[0];g.parentSymbol&&j$2(s.index,g.parentSymbol).length===0&&t.push({type:"broken-reference",severity:"warning",message:`Symbol "${p}" references parent "${g.parentSymbol}" which does not exist`,suggestion:"Create the parent symbol or update the parent reference in the .purpose file."});}let a=t.filter(p=>p.severity==="error").length,c=t.filter(p=>p.severity==="warning").length,l="pass";a>0?l="violations":c>0&&(l="warnings");let d=null;try{let p=ie(s.rootDir),g=j$1().getStats(),m=[...new Set(g.toolCalls.map(_=>_.toolName))],y=m.includes("paradigm_lore_record"),f;try{f=execSync("git status --porcelain",{cwd:s.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let b=Nt({toolsCalled:m,filesModified:n,symbolsTouched:e,loreRecorded:y,hasPortalRoutes:s.gateConfig!==null&&s.gateConfig.routes!=null,taskAddsRoutes:!1,gitClean:f}),h=Et(p,"postflight",b,void 0,s.rootDir);d={trigger:"postflight",total:h.summary.total,followed:h.summary.followed,skipped:h.summary.skipped,partial:h.summary.partial,blockingViolations:h.summary.blockingViolations,results:h.evaluations.map(_=>({id:_.habit.id,name:_.habit.name,severity:_.habit.severity,result:_.result,reason:_.reason}))};let w=F.join(s.rootDir,".paradigm",".habits-blocking");if(h.blocksCompletion){let _=h.evaluations.filter(k=>k.result==="skipped"&&k.habit.severity==="block").map(k=>`${k.habit.name}: ${k.reason}`);O.writeFileSync(w,_.join(`
806
+ `),"utf8");}else O.existsSync(w)&&O.unlinkSync(w);}catch{}return {status:l,violations:t,summary:{totalChecks:7,passed:7-(a>0?1:0)-(c>0?1:0),warnings:c,errors:a},blocksCompletion:a>0,habitsEvaluation:d}}j();function Ka(){let n=process.env.PARADIGM_AUTHOR;if(n)return Vs(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Vs(e)}catch{}try{let e=ma.userInfo().username;if(e)return Vs(e)}catch{}return "unknown"}function Vs(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function Za(){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","decision","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}},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, decision, milestone, etc.). Call after completing significant work. Returns the created entry ID and file path. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","decision","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","decision","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 ec(n,e,s){switch(n){case "paradigm_lore_search":{let t={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},i=await a$1(s.rootDir,t);return {handled:true,text:JSON.stringify({count:i.length,filter:Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),entries:i.map(Qa)},null,2)}}case "paradigm_lore_record":{let{type:t,title:i,summary:r,symbols_touched:o,symbols_created:a,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:_,linked_lore:k,linked_tasks:v,linked_commits:S,confidence:x}=e,C;try{let I=new Date(Date.now()-2592e6).toISOString(),A=await ue(s.rootDir,{dateFrom:I});if(A.total>0){let H=(await qt(s.rootDir,{dateFrom:I})).filter(q=>q.rate<60).map(q=>q.category);C={rate:A.rate,followed:A.followed,skipped:A.skipped,partial:A.partial,weakAreas:H.length>0?H:void 0};}}catch{}let T={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:g,author:Ka(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:i,summary:r,symbols_touched:o,symbols_created:a,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:C,body:_,linked_lore:k,linked_tasks:v,linked_commits:S,confidence:x!=null&&x>=0&&x<=1?x:void 0},j=await d$1(s.rootDir,T);j$1().setLastLoreEntryId(j);try{let I=process.env.PARADIGM_AGENT_ID;if(I&&o&&o.length>0){let{updateExpertiseFromLore:A}=await import('./agent-loader-CZFB5BDP.js');A(s.rootDir,I,{symbols_touched:o,confidence:x!=null&&x>=0&&x<=1?x:void 0});}}catch{}let P=null;try{c&&c.length>=2&&(P=Z$1(s.rootDir,c,l||[]));}catch{}let D;if(e.stream){let I=e.stream,A=I==="auto"?gu(e):I;try{if(A==="work-log"){let{recordWorkLog:E}=await import('./work-log-loader-DL5GZ2BQ.js');E(s.rootDir,{agent:T.agent?.model||"unknown",summary:T.summary,outcome:T.verification?.status==="pass"?"pass":T.verification?.status==="fail"?"fail":"partial",files_modified:T.files_modified,symbols_touched:T.symbols_touched,commit:T.commit,linked_lore:T.id||j}),D="work-log";}else if(A==="journal"&&T.learnings?.length){let{recordJournalEntry:E}=await import('./journal-loader-GLH7XFTK.js');for(let H of T.learnings)E(T.agent?.model||"unknown",{trigger:"self_reflection",insight:H,project:s.projectName||"unknown",transferable:!1,linked_work_log:T.id||j});D="journal";}else if(A==="decision"&&T.decisions?.length){let{recordDecision:E}=await import('./decision-loader-2XPZE4EZ.js');for(let H of T.decisions)E(s.rootDir,{title:H.decision.slice(0,100),decision:H.decision,rationale:H.rationale,participants:[{id:`agent/${T.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:T.symbols_touched,status:"active",linked_lore:T.id||j});D="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:j,type:t,title:i,message:"Lore entry recorded successfully",...D?{stream:D}:{},...P?{protocol_suggestion:P}:{}})}}case "paradigm_lore_timeline":{let t=e.limit||10,i=await c$1(s.rootDir),r=await a$1(s.rootDir,{limit:t}),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(Qa),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 t=e.id,i=await b$3(s.rootDir,t);return i?{handled:true,text:JSON.stringify(i,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})}}case "paradigm_lore_update":{let t=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$4(s.rootDir,t,o);return {handled:true,text:JSON.stringify({success:a,id:t,message:a?"Lore entry updated":`Lore entry not found: ${t}`})}}case "paradigm_lore_assess":{let t=e.id,i=e.verdict,r=e.notes,o=await b$3(s.rootDir,t);if(!o)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})};let a={verdict:i,assessed_by:Ka(),assessed_at:new Date().toISOString(),notes:r},c=await h$3(s.rootDir,t,a);try{let u=process.env.PARADIGM_AGENT_ID;if(u&&c&&o.symbols_touched?.length){let{updateExpertiseFromAssessment:g}=await import('./agent-loader-CZFB5BDP.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:t,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: ${t}`})}}case "paradigm_lore_calibration":{let t={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},i=await a$1(s.rootDir,t),r=i.filter(_=>_.confidence!=null),o=i.length,a=r.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,p=0;for(let _ of i){let k=_.assessment.verdict;c[k]++;let v=k==="correct"?1:k==="partial"?.5:0;l+=v,_.confidence!=null&&(d+=_.confidence,p+=Math.abs(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 _=new Map;for(let k of i){let v=[];f==="symbol"?v=k.symbols_touched||[]:f==="tag"?v=k.tags||[]:f==="type"&&(v=[k.type||"agent-session"]);for(let S of v)_.has(S)||_.set(S,[]),_.get(S).push(k);}b=Array.from(_.entries()).map(([k,v])=>{let S=v.filter(P=>P.confidence!=null),x={correct:0,partial:0,incorrect:0},C=0,T=0,j=0;for(let P of v){let D=P.assessment.verdict;x[D]++;let I=D==="correct"?1:D==="partial"?.5:0;C+=I,P.confidence!=null&&(T+=P.confidence,j+=Math.abs(I-P.confidence));}return {key:k,total:v.length,accuracyRate:C/v.length,avgConfidence:S.length>0?T/S.length:null,calibrationScore:S.length>0?1-j/S.length:null,verdictBreakdown:x}}).sort((k,v)=>v.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 t=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,t);return {handled:true,text:JSON.stringify({success:r,id:t,message:r?"Lore entry deleted":`Lore entry not found: ${t}`})}}default:return {handled:false,text:""}}}function gu(n){return n.task_ref||n.files_modified||n.commit?"work-log":n.learnings||n.confidence!==void 0?"journal":n.decisions?.some(s=>s.rationale)?"decision":"work-log"}function Qa(n){return {id:n.id,type:n.type,title:n.title,summary:n.summary,author:n.author,agent:n.agent,timestamp:n.timestamp,duration_minutes:n.duration_minutes,symbols_touched:n.symbols_touched,verification:n.verification?.status,review:n.review?{completeness:n.review.completeness,quality:n.review.quality}:null,confidence:n.confidence??null,assessment:n.assessment?n.assessment.verdict:null,assessment_delta:n.assessment_delta??null,tags:n.tags}}function nc(){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 sc(n,e,s){switch(n){case "paradigm_habits_list":{let t=fu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_check":{let t=await yu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_status":{let t=await _u(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_practice_context":{let t=await ku(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_add":{let t=bu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_edit":{let t=wu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_remove":{let t=vu(e,s);return o(t.length,n),{text:t,handled:true}}default:return {text:"",handled:false}}}function fu(n,e){let s=n.trigger,t=n.category,i=n.enabled,r=ie(e.rootDir);s&&(r=r.filter(a=>a.trigger===s)),t&&(r=r.filter(a=>a.category===t)),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:t,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 yu(n,e){let s=n.trigger,t=n.filesModified||[],i=n.symbolsTouched||[],r=n.taskDescription,o=n.record!==false,a=ie(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=Nt({toolsCalled:d,filesModified:t,symbolsTouched:i,loreRecorded:p,hasPortalRoutes:e.gateConfig!==null&&e.gateConfig.routes!=null,taskAddsRoutes:g,taskDescription:r,gitClean:m}),b=Et(a,s,y,"claude",e.rootDir),h=[];if(o&&b.evaluations.length>0)try{let k=c.getLastLoreEntryId()??void 0;h=await Ba(e.rootDir,b.evaluations.map(v=>({habitId:v.habit.id,habitCategory:v.habit.category,result:v.result,notes:v.reason})),{engineer:"agent",sessionId:l.sessionId,loreEntryId:k,taskDescription:r,symbolsTouched:i,filesModified:t});}catch{}let w=F.join(e.rootDir,".paradigm",".habits-blocking");try{if(s==="on-stop"&&b.blocksCompletion){let k=b.evaluations.filter(v=>v.result==="skipped"&&v.habit.severity==="block").map(v=>`${v.habit.name}: ${v.reason}`);O.writeFileSync(w,k.join(`
807
+ `),"utf8");}else s==="on-stop"&&O.existsSync(w)&&O.unlinkSync(w);}catch{}let _=Us;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},..._>0?{graduatedToHooks:_,graduatedNote:`${_} 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:hu(b)},null,2)}function hu(n){let e=[];for(let s of n.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 bu(n,e){let s=n.id,t=n.scope||"project";if(Mn(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(ie(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:n.name,description:n.description,category:n.category,trigger:n.trigger,severity:n.severity,check:n.check,enabled:n.enabled!==void 0?n.enabled:true};n.platforms&&(o.platforms=n.platforms);let a=Js(o);if(!a.valid)return JSON.stringify({error:true,message:"Validation failed",errors:a.errors},null,2);let c=Gs(e.rootDir,o,t);return JSON.stringify({created:true,id:o.id,filePath:c,scope:t,message:`Habit "${o.name}" created at ${c}`},null,2)}function wu(n,e){let s=n.id;if(Mn(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 t=F.join(e.rootDir,".paradigm","habits",`${s}.habit`),i=process.env.HOME||process.env.USERPROFILE||"~",r=F.join(i,".paradigm","habits",`${s}.habit`),o=null,a="project";if(O.existsSync(t)?(o=t,a="project"):O.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=O.readFileSync(o,"utf8");c=Z.load(p);}catch{return JSON.stringify({error:true,message:`Failed to read ${o}`},null,2)}let l={...c};n.name!==void 0&&(l.name=n.name),n.description!==void 0&&(l.description=n.description),n.category!==void 0&&(l.category=n.category),n.trigger!==void 0&&(l.trigger=n.trigger),n.severity!==void 0&&(l.severity=n.severity),n.check!==void 0&&(l.check=n.check),n.enabled!==void 0&&(l.enabled=n.enabled),n.platforms!==void 0&&(l.platforms=n.platforms);let d=Js(l);return d.valid?(Gs(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 vu(n,e){let s=n.id,t=Ga(e.rootDir,s);return t.removed?JSON.stringify({removed:true,id:s,message:`Habit "${s}" removed`},null,2):JSON.stringify({error:true,message:t.reason},null,2)}async function _u(n,e){let s=n.engineer,t=n.period||"30d",i=new Date,r;if(t!=="all"){let h=parseInt(t.replace("d",""),10)||30;r=new Date(i.getTime()-h*24*60*60*1e3).toISOString();}let o={engineer:s,dateFrom:r},a=await ue(e.rootDir,o),c=await qt(e.rootDir,o),l=await za(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},_=h.result;w[_]++,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=ie(e.rootDir),f=new Map(y.map(h=>[h.id,h.name])),b=Array.from(d.entries()).map(([h,w])=>{let _=w.followed+w.skipped+w.partial,k=_>0?Math.round((w.followed+w.partial*.5)/_*100):100;return {habitId:h,habitName:f.get(h)||h,...w,total:_,rate:k}}).sort((h,w)=>h.rate-w.rate);return JSON.stringify({period:t,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 ku(n,e){let s=n.symbols||[],t=n.task,r=ie(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 ue(e.rootDir,{dateFrom:d}),g=(await qt(e.rootDir,{dateFrom:d})).filter(m=>m.rate<60).map(m=>m.category);return JSON.stringify({symbols:s,task:t||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)}qn();Hs();async function ic(n){let e=ct(n);if(!e.enabled)return [];let s=ie(n),t=[];for(let i of s){if(!i.enabled)continue;let r=await Su(n,i,e);t.push(r);}return t}async function Su(n,e,s){let t=Hn(n,e.id),i={habitId:e.id,habitName:e.name,currentTier:t.tier,neverGraduate:false,inCooldown:false};if(t.tier==="hook")return {...i,eligible:false,reason:"Already graduated to hook"};if(t.neverGraduate||s.neverGraduate.includes(e.id))return {...i,eligible:false,reason:"Marked as never-graduate (requires agent cognition)",neverGraduate:true};if(Ns.has(e.check.type))return {...i,eligible:false,reason:`Check type "${e.check.type}" cannot graduate \u2014 requires MCP tool output`,neverGraduate:true};if(t.cooldownUntil&&new Date(t.cooldownUntil)>new Date)return {...i,eligible:false,reason:`In cooldown until ${t.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 ue(n,{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 ue(n,{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 rc(n){let e=ie(n),s=ct(n),t=Ms(n),i=0,r=0,o=0,a=0;for(let c of e){if(!c.enabled)continue;let l=t[c.id],d=l?.tier||"habit",p=l?.neverGraduate||s.neverGraduate.includes(c.id)||Ns.has(c.check.type);d==="hook"?i++:d==="mcp"?o++:r++,p&&a++;}return {hookCount:i,habitCount:r,mcpCount:o,neverGraduateCount:a,states:t}}qn();var xu=[{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 Cu(n,e){let s=await ic(n.rootDir),t=s;if(e.habitId&&(t=s.filter(a=>a.habitId===e.habitId),t.length===0))return JSON.stringify({error:`No habit found with ID "${e.habitId}"`});let i=t.filter(a=>a.eligible),r=t.filter(a=>!a.eligible&&!a.neverGraduate),o=t.filter(a=>a.neverGraduate);return JSON.stringify({summary:{checked:t.length,eligible:i.length,ineligible:r.length,neverGraduate:o.length},...i.length>0?{eligible:i.map(oc),action:"Run `paradigm graduate promote <id>` to graduate eligible habits."}:{},...r.length>0?{ineligible:r.map(oc)}:{},...o.length>0?{neverGraduate:o.map(a=>({id:a.habitId,name:a.habitName,reason:a.reason}))}:{}},null,2)}async function Pu(n){let e=rc(n.rootDir),s=ct(n.rootDir),t={hook:[],habit:[],mcp:[]};for(let[i,r]of Object.entries(e.states)){let o=r.tier||"habit";t[o]||(t[o]=[]),t[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:t,thresholds:s.thresholds},null,2)}function ac(){return xu}async function cc(n,e,s){switch(n){case "paradigm_graduate_check":return {handled:true,text:await Cu(s,e)};case "paradigm_graduate_status":return {handled:true,text:await Pu(s)};default:return {handled:false,text:""}}}function oc(n){return {id:n.habitId,name:n.habitName,tier:n.currentTier,reason:n.reason,...n.complianceRate!==void 0?{complianceRate:n.complianceRate}:{},...n.eventCount!==void 0?{eventCount:n.eventCount}:{},...n.inCooldown?{inCooldown:true}:{}}}var lc=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"]),Ru=.95,ju=.3,Tu=10;function Du(n,e){let s=n.length,t=e.length;if(s===0)return t;if(t===0)return s;let i=Array.from({length:s+1},()=>Array.from({length:t+1},()=>0));for(let r=0;r<=s;r++)i[r][0]=r;for(let r=0;r<=t;r++)i[0][r]=r;for(let r=1;r<=s;r++)for(let o=1;o<=t;o++){let a=n[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][t]}function dc(n){let e=n.toLowerCase().split(/\s+/).filter(s=>s.length>0&&!lc.has(s));return e.sort(),e.join(" ")}function Au(n){try{let e=n.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 pc(n,e,s){let t=s?.limit??Tu,i=dc(e);if(i.length===0)return [];let r=Ou(n,i,s);if(r.length>0)return r.slice(0,t);if(Au(n)){let a=Iu(n,i,s);if(a.length>0)return a.slice(0,t)}return $u(n,i,s).slice(0,t)}function Ou(n,e,s){try{let t=`
770
808
  SELECT
771
809
  a.id, a.description, a.category, a.severity, a.tags,
772
810
  sw.weight,
@@ -796,7 +834,7 @@ Runs pre-flight compliance checks: extracts affected symbols, runs ripple analys
796
834
  hit_count = hit_count + 1,
797
835
  last_hit = ?`,[t,s,i,i]);}catch{return}try{n.run(`UPDATE search_weights
798
836
  SET weight = weight * ?
799
- WHERE query_normalized = ? AND aspect_id != ?`,[Ru,t,s]);}catch{}}function Ys(n){try{let e=JSON.parse(n);return Array.isArray(e)&&e.length>0?e:void 0}catch{let e=n.split(",").map(s=>s.trim()).filter(s=>s.length>0);return e.length>0?e:void 0}}function gc(){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 mc(n,e,s){switch(n){case "paradigm_aspect_search":return Nu(e,s);case "paradigm_aspect_get":return Eu(e,s);case "paradigm_aspect_graph":return Hu(e,s);case "paradigm_aspect_heatmap":return qu(e,s);case "paradigm_aspect_suggest_scan":return Mu(e,s);case "paradigm_aspect_drift":return Lu(e,s);case "paradigm_aspect_confirm":return Wu(e,s);default:return {handled:false,text:""}}}async function Nu(n,e){let{query:s,limit:t=10}=n,i=null;try{i=await w$1(e.rootDir);let r=pc(i,s,{limit:t});for(let c of r)try{D(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 x$1(i,e.rootDir),i=null,o(a.length,"paradigm_aspect_search"),{handled:!0,text:a}}catch(r){if(i)try{x$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 Eu(n,e){let{aspectId:s}=n,t=s.startsWith("~")?s.slice(1):s,i=null;try{i=await w$1(e.rootDir);let r=y$2(i,t);if(r||(r=y$2(i,`~${t}`)),!r){x$1(i),i=null;let f=JSON.stringify({error:"Aspect not found",aspectId:t,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=z$1(i,o$1).map(f=>{let b=Ju(e.rootDir,f);return {filePath:f.file_path,startLine:f.start_line,endLine:f.end_line,drifted:f.drifted===1,snippet:b}}),l=A$2(i,o$1),d=B$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 G$1(i,e.rootDir,o$1);}catch{}try{D(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 x$1(i,e.rootDir),i=null,o(y.length,"paradigm_aspect_get"),{handled:!0,text:y}}catch(r){if(i)try{x$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 Hu(n,e){let{symbol:s,hops:t=2}=n,i=Math.min(Math.max(t,1),5),r=null;try{r=await w$1(e.rootDir);let o$1=new Set,a=new Map,c=[],l=[{symbol:s,depth:0}];o$1.add(s);let d=y$2(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=C(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}),!o$1.has(b)){o$1.add(b);let w=y$2(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 x$1(r),r=null,o(g.length,"paradigm_aspect_graph"),{handled:!0,text:g}}catch(o$1){if(r)try{x$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 qu(n,e){let{limit:s=20,accessType:t}=n,i=null;try{i=await w$1(e.rootDir);let r=E$1(i,s*4,t),o$1=new Map;for(let d of r){let p=o$1.get(d.aspect_id);if(!p){let u=y$2(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,...t?{filteredBy:t}:{},entries:a},l=JSON.stringify(c,null,2);return x$1(i),i=null,o(l.length,"paradigm_aspect_heatmap"),{handled:!0,text:l}}catch(r){if(i)try{x$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 Mu(n,e){let{filePath:s}=n,t=F.isAbsolute(s)?s:F.join(e.rootDir,s);if(!O.existsSync(t)){let i=JSON.stringify({error:"File not found",filePath:t,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(t),a={filePath:t,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})),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 Lu(n,e){let{aspectId:s,autoHeal:t}=n,i=t!==false,r=s?s.startsWith("~")?s.slice(1):s:void 0,o$1=null;try{o$1=await w$1(e.rootDir);let a=F$2(o$1,e.rootDir,r,i),c=a.filter(h=>h.status==="clean").length,l=a.filter(h=>h.status==="cosmetic").length,d=a.filter(h=>h.status==="shifted").length,p=a.filter(h=>h.status==="modified").length,u=a.filter(h=>h.status==="missing").length,g=p>0||u>0,m=l>0||d>0,y=g?"drift-detected":m?"clean-with-heals":"clean",f={...r?{aspectId:r}:{scope:"all"},totalAnchors:a.length,clean:c,cosmetic:l,shifted:d,modified:p,missing:u,status:y,results:a.map(h=>({aspectId:h.aspectId,path:h.path,startLine:h.startLine,endLine:h.endLine,status:h.status,resolvedBy:h.resolvedBy,exists:h.exists,...h.status==="shifted"?{suggestedStart:h.suggestedStart,suggestedEnd:h.suggestedEnd,autoHealed:h.autoHealed}:{},...h.status==="modified"&&h.currentContent?{currentContent:h.currentContent.slice(0,500)}:{}})),...l>0||d>0?{healed:[l>0?`${l} cosmetic (whitespace/formatting \u2014 hashes updated)`:"",d>0?`${d} shifted (line numbers updated via git diff${i?" \u2014 .purpose files patched":""})`:""].filter(Boolean).join(", ")}:{},...g?{suggestion:"Review drifted anchors to ensure aspects still apply. Run `paradigm scan` to re-materialize after fixing."}:{}},b=JSON.stringify(f,null,2);return x$1(o$1,e.rootDir),o$1=null,o(b.length,"paradigm_aspect_drift"),{handled:!0,text:b}}catch(a){if(o$1)try{x$1(o$1);}catch{}let c=JSON.stringify({error:"Failed to check aspect drift",details:String(a),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(c.length,"paradigm_aspect_drift"),{handled:true,text:c}}}async function Wu(n,e){let{query:s,aspectId:t}=n,i=null;try{i=await w$1(e.rootDir),uc(i,s,t);let r={confirmed:!0,query:s,aspectId:t,message:`Search mapping reinforced: "${s}" -> ${t}. Future searches for similar queries will rank this aspect higher.`},o$1=JSON.stringify(r,null,2);return x$1(i,e.rootDir),i=null,o(o$1.length,"paradigm_aspect_confirm"),{handled:!0,text:o$1}}catch(r){if(i)try{x$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 Ju(n,e){let s=F.isAbsolute(e.file_path)?e.file_path:F.join(n,e.file_path);if(!O.existsSync(s))return null;try{let i=O.readFileSync(s,"utf8").split(`
837
+ WHERE query_normalized = ? AND aspect_id != ?`,[Ru,t,s]);}catch{}}function Ys(n){try{let e=JSON.parse(n);return Array.isArray(e)&&e.length>0?e:void 0}catch{let e=n.split(",").map(s=>s.trim()).filter(s=>s.length>0);return e.length>0?e:void 0}}function gc(){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 mc(n,e,s){switch(n){case "paradigm_aspect_search":return Eu(e,s);case "paradigm_aspect_get":return Nu(e,s);case "paradigm_aspect_graph":return Hu(e,s);case "paradigm_aspect_heatmap":return qu(e,s);case "paradigm_aspect_suggest_scan":return Mu(e,s);case "paradigm_aspect_drift":return Lu(e,s);case "paradigm_aspect_confirm":return Wu(e,s);default:return {handled:false,text:""}}}async function Eu(n,e){let{query:s,limit:t=10}=n,i=null;try{i=await w$1(e.rootDir);let r=pc(i,s,{limit:t});for(let c of r)try{D(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 x$1(i,e.rootDir),i=null,o(a.length,"paradigm_aspect_search"),{handled:!0,text:a}}catch(r){if(i)try{x$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 Nu(n,e){let{aspectId:s}=n,t=s.startsWith("~")?s.slice(1):s,i=null;try{i=await w$1(e.rootDir);let r=y$2(i,t);if(r||(r=y$2(i,`~${t}`)),!r){x$1(i),i=null;let f=JSON.stringify({error:"Aspect not found",aspectId:t,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=z$1(i,o$1).map(f=>{let b=Ju(e.rootDir,f);return {filePath:f.file_path,startLine:f.start_line,endLine:f.end_line,drifted:f.drifted===1,snippet:b}}),l=A$2(i,o$1),d=B$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 G$1(i,e.rootDir,o$1);}catch{}try{D(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 x$1(i,e.rootDir),i=null,o(y.length,"paradigm_aspect_get"),{handled:!0,text:y}}catch(r){if(i)try{x$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 Hu(n,e){let{symbol:s,hops:t=2}=n,i=Math.min(Math.max(t,1),5),r=null;try{r=await w$1(e.rootDir);let o$1=new Set,a=new Map,c=[],l=[{symbol:s,depth:0}];o$1.add(s);let d=y$2(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=C(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}),!o$1.has(b)){o$1.add(b);let w=y$2(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 x$1(r),r=null,o(g.length,"paradigm_aspect_graph"),{handled:!0,text:g}}catch(o$1){if(r)try{x$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 qu(n,e){let{limit:s=20,accessType:t}=n,i=null;try{i=await w$1(e.rootDir);let r=E$1(i,s*4,t),o$1=new Map;for(let d of r){let p=o$1.get(d.aspect_id);if(!p){let u=y$2(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,...t?{filteredBy:t}:{},entries:a},l=JSON.stringify(c,null,2);return x$1(i),i=null,o(l.length,"paradigm_aspect_heatmap"),{handled:!0,text:l}}catch(r){if(i)try{x$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 Mu(n,e){let{filePath:s}=n,t=F.isAbsolute(s)?s:F.join(e.rootDir,s);if(!O.existsSync(t)){let i=JSON.stringify({error:"File not found",filePath:t,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(t),a={filePath:t,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})),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 Lu(n,e){let{aspectId:s,autoHeal:t}=n,i=t!==false,r=s?s.startsWith("~")?s.slice(1):s:void 0,o$1=null;try{o$1=await w$1(e.rootDir);let a=F$2(o$1,e.rootDir,r,i),c=a.filter(h=>h.status==="clean").length,l=a.filter(h=>h.status==="cosmetic").length,d=a.filter(h=>h.status==="shifted").length,p=a.filter(h=>h.status==="modified").length,u=a.filter(h=>h.status==="missing").length,g=p>0||u>0,m=l>0||d>0,y=g?"drift-detected":m?"clean-with-heals":"clean",f={...r?{aspectId:r}:{scope:"all"},totalAnchors:a.length,clean:c,cosmetic:l,shifted:d,modified:p,missing:u,status:y,results:a.map(h=>({aspectId:h.aspectId,path:h.path,startLine:h.startLine,endLine:h.endLine,status:h.status,resolvedBy:h.resolvedBy,exists:h.exists,...h.status==="shifted"?{suggestedStart:h.suggestedStart,suggestedEnd:h.suggestedEnd,autoHealed:h.autoHealed}:{},...h.status==="modified"&&h.currentContent?{currentContent:h.currentContent.slice(0,500)}:{}})),...l>0||d>0?{healed:[l>0?`${l} cosmetic (whitespace/formatting \u2014 hashes updated)`:"",d>0?`${d} shifted (line numbers updated via git diff${i?" \u2014 .purpose files patched":""})`:""].filter(Boolean).join(", ")}:{},...g?{suggestion:"Review drifted anchors to ensure aspects still apply. Run `paradigm scan` to re-materialize after fixing."}:{}},b=JSON.stringify(f,null,2);return x$1(o$1,e.rootDir),o$1=null,o(b.length,"paradigm_aspect_drift"),{handled:!0,text:b}}catch(a){if(o$1)try{x$1(o$1);}catch{}let c=JSON.stringify({error:"Failed to check aspect drift",details:String(a),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(c.length,"paradigm_aspect_drift"),{handled:true,text:c}}}async function Wu(n,e){let{query:s,aspectId:t}=n,i=null;try{i=await w$1(e.rootDir),uc(i,s,t);let r={confirmed:!0,query:s,aspectId:t,message:`Search mapping reinforced: "${s}" -> ${t}. Future searches for similar queries will rank this aspect higher.`},o$1=JSON.stringify(r,null,2);return x$1(i,e.rootDir),i=null,o(o$1.length,"paradigm_aspect_confirm"),{handled:!0,text:o$1}}catch(r){if(i)try{x$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 Ju(n,e){let s=F.isAbsolute(e.file_path)?e.file_path:F.join(n,e.file_path);if(!O.existsSync(s))return null;try{let i=O.readFileSync(s,"utf8").split(`
800
838
  `),r=Math.max(0,e.start_line-1),o=Math.min(i.length,e.end_line),a=i.slice(r,o).join(`
801
839
  `);return a.length>1e3?a.slice(0,1e3)+`
802
840
  ... (truncated)`:a}catch{return null}}function fc(){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 yc(n,e,s){switch(n){case "paradigm_task_create":{let t=await c$3(s.rootDir,{blurb:e.blurb,priority:e.priority,tags:e.tags,related_lore:e.related_lore}),i=await b$6(s.rootDir,t);return {handled:true,text:JSON.stringify({created:t,task:i},null,2)}}case "paradigm_task_list":{let t=await a$6(s.rootDir,{status:e.status||"open",priority:e.priority,tag:e.tag,limit:e.limit||20}),i=e.status||"open",r=[`${t.length} ${i} task(s):`];for(let o of t){let a=o.tags.length>0?` [${o.tags.join(", ")}]`:"";r.push(` [${o.priority}] ${o.id}: ${o.blurb}${a}`);}return {handled:true,text:r.join(`
@@ -804,7 +842,7 @@ Runs pre-flight compliance checks: extracts affected symbols, runs ripple analys
804
842
  `)}}try{let i=e.status||"active",o=(await bc(s.rootDir,i)).slice(0,e.limit||20),a=[`${o.length} ${i} arc(s):`];for(let c of o){let l=c.symbols.length>0?` [${c.symbols.slice(0,3).join(", ")}]`:"";a.push(` ${c.id}: ${c.name} (${c.entry_count} entries)${l}`);}return a.push("",'Deprecated: Run "paradigm lore migrate-assessments" then use paradigm_lore_search'),{handled:!0,text:a.join(`
805
843
  `)}}catch{return {handled:true,text:"No assessment arcs found. Assessments are now unified with lore."}}}case "paradigm_assessment_get":{let t=e.id;if(t.startsWith("L-")){let i=await b$3(s.rootDir,t);if(i)return {handled:true,text:JSON.stringify({entry:i,deprecated:"Use paradigm_lore_get instead"},null,2)}}if(t.startsWith("arc-"))try{let i=await wc(s.rootDir,t);if(!i)return {handled:!0,text:JSON.stringify({error:`Arc ${t} not found`})};let r=await _c(s.rootDir,t);return {handled:!0,text:JSON.stringify({arc:i,entries:r.map(o=>({id:o.id,type:o.type,title:o.title,date:o.date.slice(0,10),summary:o.summary})),deprecated:'Run "paradigm lore migrate-assessments" then use paradigm_lore_search with tag: "arc:'+t+'"'},null,2)}}catch{return {handled:true,text:JSON.stringify({error:`Arc ${t} not found`})}}try{let i=await kc(s.rootDir,t);return i?{handled:!0,text:JSON.stringify({entry:i.entry,arc:{id:i.arc.id,name:i.arc.name,status:i.arc.status},deprecated:'Run "paradigm lore migrate-assessments" then use paradigm_lore_get'},null,2)}:{handled:!0,text:JSON.stringify({error:`Entry ${t} not found`})}}catch{return {handled:true,text:JSON.stringify({error:`Entry ${t} not found`})}}}case "paradigm_assessment_search":{let t={limit:e.limit||20};e.symbol&&(t.symbol=e.symbol),e.tag&&(t.tag=e.tag),e.type&&(t.tag=`assessment:${e.type}`),e.dateFrom&&(t.dateFrom=e.dateFrom),e.dateTo&&(t.dateTo=e.dateTo);let r=(await a$1(s.rootDir,t)).filter(o=>o.tags?.some(a=>a.startsWith("arc:")));if(r.length>0){let o=[`${r.length} matching lore entries (with arc tags):`];for(let a of r){let c=a.tags?.find(d=>d.startsWith("arc:"))||"",l=(a.symbols_touched||[]).slice(0,3).join(", ");o.push(` [${a.type||"unknown"}] ${a.id} (${c}): ${a.title} \u2014 ${l}`);}return o.push("","Deprecated: Use paradigm_lore_search with tag filter"),{handled:true,text:o.join(`
806
844
  `)}}try{let o=await Sc(s.rootDir,{symbol:e.symbol,tag:e.tag,type:e.type,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20}),a=[`${o.length} matching entries:`];for(let c of o){let l=(c.symbols||[]).slice(0,3).join(", ");a.push(` [${c.type}] ${c.id} (${c.arc_id}): ${c.title} \u2014 ${l}`);}return a.push("",'Deprecated: Run "paradigm lore migrate-assessments" then use paradigm_lore_search'),{handled:!0,text:a.join(`
807
- `)}}catch{return {handled:true,text:"0 matching entries."}}}case "paradigm_assessment_arc_create":return {handled:true,text:JSON.stringify({message:"Arcs are now tag prefixes on lore entries. No explicit creation needed.",guidance:`To create entries in this arc, use paradigm_lore_record with tags: ["arc:${e.id}"]`,deprecated:true},null,2)};case "paradigm_assessment_arc_close":{let t=e.arc_id,i=e.status||"complete",r=await a$1(s.rootDir,{tag:`arc:${t}`}),o=0;for(let a of r){let c=a.tags||[];c.includes("arc-closed")||(await g$4(s.rootDir,a.id,{tags:[...c,"arc-closed",`arc-status:${i}`]}),o++);}try{await vc(s.rootDir,t,i);}catch{}return {handled:true,text:JSON.stringify({closed:t,status:i,lore_entries_tagged:o,deprecated:"Use paradigm_lore_search + paradigm_lore_update to manage arc lifecycle via tags"},null,2)}}default:return {handled:false,text:""}}}var Rc=0;function jc(){let n=new Date().toISOString().slice(0,10);return Rc++,`run_${n}_${String(Rc).padStart(3,"0")}`}var Tc=/\{\{([^}]+)\}\}/g;function dt(n,e){if(typeof n=="string")return n.replace(Tc,(s,t)=>{let i=Vu(t.trim(),e);return i!==void 0?String(i):s});if(Array.isArray(n))return n.map(s=>dt(s,e));if(n&&typeof n=="object"){let s={};for(let[t,i]of Object.entries(n))s[t]=dt(i,e);return s}return n}function Vu(n,e){let[s,...t]=n.split("."),i=t.join(".");switch(s){case "fixtures":return e.fixtures[i];case "produces":return Qs(e.produces,i);case "context":case "parent":return e.context[i];case "env":return e.env[i]??process.env[i];default:return}}function Qs(n,e){let s=e.split(/[.\[\]]+/).filter(Boolean),t=n;for(let i of s){if(t==null||typeof t!="object")return;t=t[i];}return t}function Yu(n,e){let s={};for(let[t,i]of Object.entries(n)){let r=i.match(/\{\{response\.(.+)\}\}/);if(r){let o=r[1],a=Qs(e,o);a!==void 0&&(s[t]=a);}}return s}function Ku(n,e){if(e.status!==n.status)return {pass:false,failure:`Status mismatch: expected ${n.status}, got ${e.status}`};if(n.body){let s=e.body;if(n.body.has){for(let t of n.body.has)if(s===null||typeof s!="object"||!(t in s))return {pass:false,failure:`Expected body to have key "${t}"`}}if(n.body.match)for(let[t,i]of Object.entries(n.body.match)){let r=Qs(s,t);if(JSON.stringify(r)!==JSON.stringify(i))return {pass:false,failure:`Body mismatch at "${t}": expected ${JSON.stringify(i)}, got ${JSON.stringify(r)}`}}}return {pass:true}}async function Qu(n,e,s){let t=Date.now(),i=n.route.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(.*)/);if(!i)return {id:n.id,status:"fail",route:n.route,gates:n.gates,failure:`Invalid route format: ${n.route}`,duration_ms:Date.now()-t};let r=i[1],o=i[2],a=dt(o,s),c=`${e.baseUrl.replace(/\/$/,"")}${a}`,l={"Content-Type":"application/json",...n.headers?dt(n.headers,s):{}},d=n.payload?dt(n.payload,s):void 0,p={url:c,method:r,headers:n.headers?l:void 0,payload:d};if(e.dryRun)return {id:n.id,status:"pass",route:n.route,gates:n.gates,request:p,produced:n.produces?Object.fromEntries(Object.keys(n.produces).map(u=>[u,`<dry-run:${u}>`])):void 0,duration_ms:Date.now()-t};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=Ku(n.expect,f),h;n.produces&&b.pass&&(h=Yu(n.produces,m));let w;return (g.status===401||g.status===403)&&(w=n.gates[n.gates.length-1]),{id:n.id,status:b.pass?"pass":"fail",route:n.route,gates:n.gates,request:p,response:f,produced:h,expected_status:b.pass?void 0:n.expect.status,failure:b.failure,gate_that_blocked:w,duration_ms:Date.now()-t}}catch(u){return {id:n.id,status:"fail",route:n.route,gates:n.gates,request:p,failure:`Request failed: ${u.message}`,duration_ms:Date.now()-t}}}async function Dc(n,e,s){let t=Date.now(),i=await I(n,e);return i?Ac(n,i,s):{persona:e,run_id:jc(),status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${e} not found`,duration_ms:Date.now()-t}}async function Ac(n,e,s){let t=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 Qu(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:jc(),status:p>0?"fail":"pass",steps:o,spawns_triggered:a,spawns_blocked:c,summary:m,duration_ms:Date.now()-t}}async function Oc(n,e,s){let t=Date.now(),i=await import('fs'),r=await import('path'),o=await import('js-yaml'),a=r.join(n,".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()-t};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()-t};let d=[],p={},u=s.stopOnFailure!==false;for(let y of c.order){let f=await I(n,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 _=l.overrides[y.persona];if(_.traits&&(f.traits={...f.traits,..._.traits}),_.journey)for(let[k,v]of Object.entries(_.journey)){let S=f.journey.find(x=>x.id===k);S&&(v.payload&&(S.payload={...S.payload,...v.payload}),v.expect&&(S.expect={...S.expect,...v.expect}));}}let b={};if(y.wait_for){let[_,k]=y.wait_for.split("."),v=d.find(x=>x.persona===_);if(v){let x=v.steps.find(C=>C.id===k);x?.produced&&(b=Object.fromEntries(Object.entries(x.produced).map(([C,T])=>[C,String(T)])));}let S=await I(n,_);if(S){let x=S.journey.find(C=>C.id===k);if(x?.spawns){let C=x.spawns.find(T=>T.persona===y.persona);if(C?.context){let T=p[_]||{};for(let[j,P]of Object.entries(C.context))b[j]=String(dt(P,{fixtures:{},produces:T,context:{},env:process.env}));}}}}let h=await Ac(n,f,{...s,context:b});d.push(h);let w={};for(let _ of h.steps)_.produced&&Object.assign(w,_.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()-t}}function Ic(n){let e=[],s=new Set;for(let t of n.journey){let r=JSON.stringify(t).match(Tc)||[];for(let o of r){let a=o.replace("{{","").replace("}}","").trim(),[c,...l]=a.split("."),d=l.join(".");switch(c){case "fixtures":!n.fixtures||d in n.fixtures;break;case "produces":s.has(d)||e.push({step:t.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:t.id,template:o,error:`Unknown namespace "${c}" in ${o}`});}}if(t.produces)for(let o of Object.keys(t.produces))s.add(o);}return {valid:e.length===0,errors:e}}var Fc="paradigm-personas",Xu={id:Fc,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"}}},Xs=false;async function $c(n){try{let{SentinelStorage:e}=await import('./dist-W3XCATBJ.js'),s=new e;if(!Xs)try{s.registerSchema(Xu),Xs=!0;}catch{Xs=!0;}let t=[];if("persona"in n){let i=n;t.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}`;t.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):[]}});}t.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=n;for(let r of i.persona_results)t.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}});t.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}});}t.length>0&&s.insertEventBatch(Fc,"paradigm-personas",t);}catch{}}function Nc(){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 Ec(n,e,s){switch(n){case "paradigm_persona_create":try{let t=await J$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 I(s.rootDir,t);return {handled:!0,text:JSON.stringify({created:t,persona:i},null,2)}}catch(t){return {handled:true,text:JSON.stringify({error:t.message})}}case "paradigm_persona_get":{let t=e.id,i=await I(s.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Persona ${t} not found`})};let r=await O$1(s.rootDir,i);return {handled:true,text:JSON.stringify({persona:i,validation:r},null,2)}}case "paradigm_persona_list":{let t=await H(s.rootDir,{tag:e.tag,trigger_type:e.trigger_type,gate:e.gate,flow:e.flow,limit:e.limit||50}),i=t.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:t.length,personas:i},null,2)}}case "paradigm_persona_update":{let t=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 K(s.rootDir,t,i))return {handled:true,text:JSON.stringify({error:`Persona ${t} not found`})};let o=await I(s.rootDir,t);return {handled:true,text:JSON.stringify({updated:t,persona:o},null,2)}}case "paradigm_persona_delete":{let t=e.id,i=await L(s.rootDir,t);return i.deleted?{handled:true,text:JSON.stringify({deleted:t,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 ${t} not found`})}}case "paradigm_persona_add_step":try{if(!await M$1(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 I(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(t){return {handled:true,text:JSON.stringify({error:t.message})}}case "paradigm_persona_remove_step":{let t=await N(s.rootDir,e.persona_id,e.step_id);return t.removed?{handled:true,text:JSON.stringify({removed:e.step_id,persona_id:e.persona_id,warnings:t.warnings},null,2)}:{handled:true,text:JSON.stringify({error:`Step ${e.step_id} not found in persona ${e.persona_id}`})}}case "paradigm_persona_validate":{let t=e.deep??false,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 I(s.rootDir,e.persona_id);if(!d)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let p=await O$1(s.rootDir,d,t);if(i)try{let u=await R(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 H(s.rootDir),a=await Promise.all(o.map(async d=>{let p=await O$1(s.rootDir,d,t);if(i)try{let u=await R(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 t=await P(s.rootDir);return {handled:true,text:JSON.stringify(t,null,2)}}case "paradigm_persona_affected":{let t=e.symbol,i=await Q(s.rootDir,t);return i.length===0?{handled:true,text:JSON.stringify({symbol:t,affected:[],note:"No personas reference this symbol."})}:{handled:true,text:JSON.stringify({symbol:t,affected:i},null,2)}}case "paradigm_persona_run":{let t=e.base_url,i=e.dry_run??false,r=e.stop_on_failure??true;if(e.chain_id){let o=await Oc(s.rootDir,e.chain_id,{baseUrl:t,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 I(s.rootDir,e.persona_id);if(!o)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let a=Ic(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 Dc(s.rootDir,e.persona_id,{baseUrl:t,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:""}}}function Hc(){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 qc(n,e,s){switch(n){case "paradigm_protocol_search":{let t=e.task,i=e.limit||3,r=await V(s.rootDir,t,i);return r.length===0?{handled:true,text:JSON.stringify({count:0,task:t,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:r.length,task:t,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(Zu)}))},null,2)}}case "paradigm_protocol_get":{let t=e.id,i=await T(s.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let r=Y(s.rootDir,i);return {handled:true,text:JSON.stringify({...i,freshness:{status:r.status,issues:r.issues}},null,2)}}case "paradigm_protocol_record":{let t=e.steps||[],i=await W(s.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:t,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:i,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let t=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 X$1(s.rootDir,t,r,i===true);return {handled:true,text:JSON.stringify({success:o,id:t,refreshed:i===true,message:o?i?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${t}`})}}case "paradigm_protocol_validate":{let t=e.id;if(t){let a=await T(s.rootDir,t);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let c=Y(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 S(s.rootDir)).map(a=>{let c=Y(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 Zu(n){let e={action:n.action};return n.target&&(e.target=n.target),n.template_from&&(e.template_from=n.template_from),n.reference&&(e.reference=n.reference),n.command&&(e.command=n.command),n.notes&&(e.notes=n.notes),e}var eg=".paradigm/graphs",ti={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},Zs=200,ei=60,pt=20,Wn=40,Mc=50,tg=60;function Wc(){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 Jc(n,e,s){if(n!=="paradigm_graph_generate")return {handled:false,text:""};try{let t=e.name||"untitled",i=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),r=ig(s.rootDir,e.symbols,e.groups,e.links,t),o$1=JSON.stringify(r,null,2),a=F.join(s.rootDir,eg);O.existsSync(a)||O.mkdirSync(a,{recursive:!0});let c=F.join(a,`${i}.graph.json`);O.writeFileSync(c,o$1,"utf8");let l=JSON.stringify({file:c,name:t,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,n),{handled:!0,text:l}}catch(t){let i=JSON.stringify({error:t.message},null,2);return o(i.length,n),{handled:true,text:i}}}var ng={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"};function sg(n){let e=F.join(n,".paradigm","scan-index.json");if(!O.existsSync(e))return [];let s=JSON.parse(O.readFileSync(e,"utf8")),t=[];for(let[i,r]of Object.entries(ng)){let o=s[i];if(!(!o||typeof o!="object"))for(let[a,c]of Object.entries(o)){let l=c;t.push({id:a,name:a,category:r,prefix:ti[r]||"#",description:l.description,path:l.path,tags:l.tags});}}return t}function Lc(n,e){let s=n.replace(/^[#$^!~]/,"");return e.find(t=>t.id===s||t.name===s||t.id===n||t.name===n)}function ig(n,e,s,t,i="Generated Graph"){let r=sg(n),o;e&&e.length>0?o=e.map(g=>Lc(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(v=>Lc(v,o)).filter(Boolean),f=Math.ceil(Math.sqrt(y.length)),b=Math.ceil(y.length/f);for(let v=0;v<y.length;v++){let S=y[v],x=v%f,C=Math.floor(v/f),T=ti[S.category]||"#";a.push({id:`sym-${S.id}`,type:"symbolNode",position:{x:Wn+x*(Zs+pt),y:Mc+Wn+C*(ei+pt)},parentId:m,data:{type:"symbol",symbol:S,label:`${T}${S.name}`}}),d.add(S.id);}let h=Math.max(f,1),w=Math.max(b,1),_=Wn*2+h*Zs+(h-1)*pt,k=Mc+Wn*2+w*ei+(w-1)*pt;a.unshift({id:m,type:"groupNode",position:{x:p,y:0},style:{width:_,height:k},data:{type:"group",label:g.label}}),p+=_+tg;}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=ti[f.category]||"#";a.push({id:`sym-${f.id}`,type:"symbolNode",position:{x:b*(Zs+pt),y:g+h*(ei+pt)},data:{type:"symbol",symbol:f,label:`${w}${f.name}`}});}}if(t&&t.length>0)for(let g of t){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:F.basename(n),lastModified:new Date().toISOString(),nodes:a,edges:c}}var Gc=".paradigm/heat-map.json",rg=.05;function Uc(){return [{name:"paradigm_heatmap_query",description:"Query the adaptive heat map for historically relevant symbols given keywords. Returns associations sorted by confidence.",inputSchema:{type:"object",properties:{keywords:{type:"array",items:{type:"string"},description:"Keywords to search for in the heat map"}},required:["keywords"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_heatmap_record",description:"Record a query-to-symbol association in the adaptive heat map. Use positive signal to reinforce, negative to correct.",inputSchema:{type:"object",properties:{keywords:{type:"array",items:{type:"string"},description:"Keywords that relate to the symbols"},symbols:{type:"array",items:{type:"string"},description:"Symbol IDs (with prefix) that are relevant"},aspects:{type:"array",items:{type:"string"},description:"Aspect IDs that are relevant (optional)"},context:{type:"string",description:"Why this association exists"},signal:{type:"string",enum:["positive","negative"],description:"Positive reinforces, negative reduces confidence"},correction:{type:"string",description:"Explanation if correcting a wrong association"}},required:["keywords","symbols","signal"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_heatmap_stats",description:"Show heat map statistics \u2014 total associations, hot/cold keywords, top symbols, session count.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}}]}function ni(n){let e=F.join(n,Gc);return O.existsSync(e)?JSON.parse(O.readFileSync(e,"utf8")):{version:"1.0",lastUpdated:new Date().toISOString(),sessionCount:0,associations:[]}}function og(n,e){let s=F.join(n,Gc),t=F.dirname(s);O.existsSync(t)||O.mkdirSync(t,{recursive:true}),e.lastUpdated=new Date().toISOString(),O.writeFileSync(s,JSON.stringify(e,null,2),"utf8");}async function ag(n,e){let s=ni(e),t=Date.now();for(let o of s.associations){let a=(t-new Date(o.lastHit).getTime())/864e5,c=Math.floor(a/30);c>0&&(o.confidence=Math.max(.01,o.confidence*Math.pow(1-rg,c)));}let i=n.keywords.map(o=>o.toLowerCase()),r=s.associations.filter(o=>o.keywords.some(a=>i.some(c=>a.includes(c)||c.includes(a)))).sort((o,a)=>a.confidence-o.confidence).slice(0,10);return JSON.stringify({matches:r,totalAssociations:s.associations.length})}async function cg(n,e){let s=ni(e),t=n.keywords.map(r=>r.toLowerCase()),i=s.associations.find(r=>r.keywords.some(o=>t.includes(o)));if(n.signal==="positive")if(i){i.confidence=Math.min(1,i.confidence+.05),i.hitCount+=1,i.lastHit=new Date().toISOString();for(let r of n.symbols)i.symbols.includes(r)||i.symbols.push(r);if(n.aspects){i.aspects||(i.aspects=[]);for(let r of n.aspects)i.aspects.includes(r)||i.aspects.push(r);}for(let r of t)i.keywords.includes(r)||i.keywords.push(r);}else s.associations.push({keywords:t,symbols:n.symbols,aspects:n.aspects,confidence:.5,hitCount:1,lastHit:new Date().toISOString()});else if(i&&(i.confidence=Math.max(.01,i.confidence-.15),n.correction))for(let r of n.symbols){let o=i.symbols.indexOf(r);o>=0&&i.symbols.splice(o,1);}return og(e,s),JSON.stringify({recorded:true,totalAssociations:s.associations.length})}async function lg(n){let e=ni(n),s=[...e.associations].sort((r,o)=>o.confidence-r.confidence),t=s.filter(r=>r.confidence>.7),i=s.filter(r=>r.confidence<.3);return JSON.stringify({totalAssociations:e.associations.length,sessionCount:e.sessionCount,lastUpdated:e.lastUpdated,hotAssociations:t.slice(0,5).map(r=>({keywords:r.keywords,confidence:r.confidence,hitCount:r.hitCount})),coldAssociations:i.slice(0,5).map(r=>({keywords:r.keywords,confidence:r.confidence,hitCount:r.hitCount})),topSymbols:dg(e)})}function dg(n){let e=new Map;for(let s of n.associations)for(let t of s.symbols)e.set(t,(e.get(t)||0)+s.hitCount);return [...e.entries()].sort((s,t)=>t[1]-s[1]).slice(0,10).map(([s,t])=>({symbol:s,mentions:t}))}async function zc(n,e,s){switch(n){case "paradigm_heatmap_query":{let t=await ag(e,s.rootDir);return o(t.length,n),{handled:true,text:t}}case "paradigm_heatmap_record":{let t=await cg(e,s.rootDir);return o(t.length,n),{handled:true,text:t}}case "paradigm_heatmap_stats":{let t=await lg(s.rootDir);return o(t.length,n),{handled:true,text:t}}default:return {handled:false,text:""}}}var me=["specify","plan","task","implement","validate"],Gt=".paradigm/pipeline",Bc={"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 Jn(n){return n.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Wt(n,e){let s=Jn(e),t=F.join(n,Gt,`${s}.yaml`);return O.existsSync(t)?Z.load(O.readFileSync(t,"utf8")):null}function Jt(n,e){let s=Jn(e.feature),t=F.join(n,Gt);O.existsSync(t)||O.mkdirSync(t,{recursive:true});let i=F.join(t,`${s}.yaml`);return O.writeFileSync(i,Z.dump(e,{lineWidth:120}),"utf8"),i}function Vc(n){let e=F.join(n,Gt);return O.existsSync(e)?O.readdirSync(e).filter(s=>s.endsWith(".yaml")&&!s.startsWith("completed")).map(s=>{try{return Z.load(O.readFileSync(F.join(e,s),"utf8"))}catch{return null}}).filter(Boolean):[]}function pg(n,e,s){let t={specify:{status:"pending"},plan:{status:"pending"},task:{status:"pending"},implement:{status:"pending"},validate:{status:"pending"}};return t.specify.status="in-progress",{version:"1.0",feature:Jn(n),created:new Date().toISOString(),current_stage:"specify",gate_config:e,template:s,stages:t}}function ug(n){let e=me.indexOf(n);return e<me.length-1?me[e+1]:null}function Yc(n,e){let s=Jn(e.feature),t=F.join(n,Gt,"completed");O.existsSync(t)||O.mkdirSync(t,{recursive:true});let i=F.join(t,`${s}.yaml`);O.writeFileSync(i,Z.dump(e,{lineWidth:120}),"utf8");let r=F.join(n,Gt,`${s}.yaml`);O.existsSync(r)&&O.unlinkSync(r);}function Kc(){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 Qc(n,e,s){switch(n){case "paradigm_pipeline_start":{let t=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=Bc[i];if(!l)return {handled:true,text:JSON.stringify({error:`Unknown template: ${i}`,available:Object.keys(Bc)})};o=l.gates;}let a=pg(t,o,i),c=Jt(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 t=e.feature;if(t){let r=Wt(s.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${t}`})};let o=me.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}/${me.length}`,gate_config:r.gate_config,stages:r.stages},null,2)}}let i=Vc(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=me.filter(a=>r.stages[a].status==="approved").length;return {feature:r.feature,current_stage:r.current_stage,progress:`${o}/${me.length}`,template:r.template,created:r.created}})},null,2)}}case "paradigm_pipeline_advance":{let t=e.feature,i=e.approved_by||"agent",r=Wt(s.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${t}`})};let o=r.current_stage,a=r.gate_config[o],c=ug(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",Jt(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)}):(Jt(s.rootDir,r),Yc(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 t=e.feature,i=e.updates,r=e.reason,o=Wt(s.rootDir,t);if(!o)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${t}`})};let a=[];for(let[c,l]of Object.entries(i))if(me.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:me,valid_modes:["auto","manual","sentinel"]})}:(Jt(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 t=e.feature,i=e.stage,r=e.question,o=e.options,a=e.context,c=Wt(s.rootDir,t);return c?(c.stages[i].status="blocked",c.stages[i].block_reason=r,Jt(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: ${t}`})}}case "paradigm_pipeline_abort":{let t=e.feature,i=Wt(s.rootDir,t);return i?(Yc(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: ${t}`})}}case "paradigm_pipeline_list":{let t=Vc(s.rootDir);return t.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines."})}:{handled:true,text:JSON.stringify({count:t.length,pipelines:t.map(i=>{let r=me.filter(o=>i.stages[o].status==="approved").length;return {feature:i.feature,current_stage:i.current_stage,progress:`${r}/${me.length}`,template:i.template,created:i.created}})},null,2)}}default:return {handled:false,text:""}}}var gg=F.join(ma.homedir(),".conductor"),mt=F.join(gg,"sessions");function Zc(){O.existsSync(mt)||O.mkdirSync(mt,{recursive:true});}function ii(n){Zc();let e={...n,registeredAt:new Date().toISOString()},s=F.join(mt,`${n.pid}.json`);return O.writeFileSync(s,JSON.stringify(e,null,2),"utf-8"),e}function Gn(n){let e=F.join(mt,`${n}.json`);return O.existsSync(e)?(O.unlinkSync(e),true):false}function ri(){Zc();let n=O.readdirSync(mt).filter(s=>s.endsWith(".json")),e=[];for(let s of n)try{let t=O.readFileSync(F.join(mt,s),"utf-8"),i=JSON.parse(t);e.push(i);}catch{}return e}function el(){let n=ri(),e=0;for(let s of n)mg(s.pid)||(Gn(s.pid),e++);return e}function mg(n){try{return process.kill(n,0),!0}catch{return false}}function oi(){try{return execSync(`osascript -e '
845
+ `)}}catch{return {handled:true,text:"0 matching entries."}}}case "paradigm_assessment_arc_create":return {handled:true,text:JSON.stringify({message:"Arcs are now tag prefixes on lore entries. No explicit creation needed.",guidance:`To create entries in this arc, use paradigm_lore_record with tags: ["arc:${e.id}"]`,deprecated:true},null,2)};case "paradigm_assessment_arc_close":{let t=e.arc_id,i=e.status||"complete",r=await a$1(s.rootDir,{tag:`arc:${t}`}),o=0;for(let a of r){let c=a.tags||[];c.includes("arc-closed")||(await g$4(s.rootDir,a.id,{tags:[...c,"arc-closed",`arc-status:${i}`]}),o++);}try{await vc(s.rootDir,t,i);}catch{}return {handled:true,text:JSON.stringify({closed:t,status:i,lore_entries_tagged:o,deprecated:"Use paradigm_lore_search + paradigm_lore_update to manage arc lifecycle via tags"},null,2)}}default:return {handled:false,text:""}}}var Rc=0;function jc(){let n=new Date().toISOString().slice(0,10);return Rc++,`run_${n}_${String(Rc).padStart(3,"0")}`}var Tc=/\{\{([^}]+)\}\}/g;function dt(n,e){if(typeof n=="string")return n.replace(Tc,(s,t)=>{let i=Vu(t.trim(),e);return i!==void 0?String(i):s});if(Array.isArray(n))return n.map(s=>dt(s,e));if(n&&typeof n=="object"){let s={};for(let[t,i]of Object.entries(n))s[t]=dt(i,e);return s}return n}function Vu(n,e){let[s,...t]=n.split("."),i=t.join(".");switch(s){case "fixtures":return e.fixtures[i];case "produces":return Qs(e.produces,i);case "context":case "parent":return e.context[i];case "env":return e.env[i]??process.env[i];default:return}}function Qs(n,e){let s=e.split(/[.\[\]]+/).filter(Boolean),t=n;for(let i of s){if(t==null||typeof t!="object")return;t=t[i];}return t}function Yu(n,e){let s={};for(let[t,i]of Object.entries(n)){let r=i.match(/\{\{response\.(.+)\}\}/);if(r){let o=r[1],a=Qs(e,o);a!==void 0&&(s[t]=a);}}return s}function Ku(n,e){if(e.status!==n.status)return {pass:false,failure:`Status mismatch: expected ${n.status}, got ${e.status}`};if(n.body){let s=e.body;if(n.body.has){for(let t of n.body.has)if(s===null||typeof s!="object"||!(t in s))return {pass:false,failure:`Expected body to have key "${t}"`}}if(n.body.match)for(let[t,i]of Object.entries(n.body.match)){let r=Qs(s,t);if(JSON.stringify(r)!==JSON.stringify(i))return {pass:false,failure:`Body mismatch at "${t}": expected ${JSON.stringify(i)}, got ${JSON.stringify(r)}`}}}return {pass:true}}async function Qu(n,e,s){let t=Date.now(),i=n.route.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(.*)/);if(!i)return {id:n.id,status:"fail",route:n.route,gates:n.gates,failure:`Invalid route format: ${n.route}`,duration_ms:Date.now()-t};let r=i[1],o=i[2],a=dt(o,s),c=`${e.baseUrl.replace(/\/$/,"")}${a}`,l={"Content-Type":"application/json",...n.headers?dt(n.headers,s):{}},d=n.payload?dt(n.payload,s):void 0,p={url:c,method:r,headers:n.headers?l:void 0,payload:d};if(e.dryRun)return {id:n.id,status:"pass",route:n.route,gates:n.gates,request:p,produced:n.produces?Object.fromEntries(Object.keys(n.produces).map(u=>[u,`<dry-run:${u}>`])):void 0,duration_ms:Date.now()-t};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=Ku(n.expect,f),h;n.produces&&b.pass&&(h=Yu(n.produces,m));let w;return (g.status===401||g.status===403)&&(w=n.gates[n.gates.length-1]),{id:n.id,status:b.pass?"pass":"fail",route:n.route,gates:n.gates,request:p,response:f,produced:h,expected_status:b.pass?void 0:n.expect.status,failure:b.failure,gate_that_blocked:w,duration_ms:Date.now()-t}}catch(u){return {id:n.id,status:"fail",route:n.route,gates:n.gates,request:p,failure:`Request failed: ${u.message}`,duration_ms:Date.now()-t}}}async function Dc(n,e,s){let t=Date.now(),i=await I(n,e);return i?Ac(n,i,s):{persona:e,run_id:jc(),status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${e} not found`,duration_ms:Date.now()-t}}async function Ac(n,e,s){let t=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 Qu(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:jc(),status:p>0?"fail":"pass",steps:o,spawns_triggered:a,spawns_blocked:c,summary:m,duration_ms:Date.now()-t}}async function Oc(n,e,s){let t=Date.now(),i=await import('fs'),r=await import('path'),o=await import('js-yaml'),a=r.join(n,".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()-t};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()-t};let d=[],p={},u=s.stopOnFailure!==false;for(let y of c.order){let f=await I(n,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 _=l.overrides[y.persona];if(_.traits&&(f.traits={...f.traits,..._.traits}),_.journey)for(let[k,v]of Object.entries(_.journey)){let S=f.journey.find(x=>x.id===k);S&&(v.payload&&(S.payload={...S.payload,...v.payload}),v.expect&&(S.expect={...S.expect,...v.expect}));}}let b={};if(y.wait_for){let[_,k]=y.wait_for.split("."),v=d.find(x=>x.persona===_);if(v){let x=v.steps.find(C=>C.id===k);x?.produced&&(b=Object.fromEntries(Object.entries(x.produced).map(([C,T])=>[C,String(T)])));}let S=await I(n,_);if(S){let x=S.journey.find(C=>C.id===k);if(x?.spawns){let C=x.spawns.find(T=>T.persona===y.persona);if(C?.context){let T=p[_]||{};for(let[j,P]of Object.entries(C.context))b[j]=String(dt(P,{fixtures:{},produces:T,context:{},env:process.env}));}}}}let h=await Ac(n,f,{...s,context:b});d.push(h);let w={};for(let _ of h.steps)_.produced&&Object.assign(w,_.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()-t}}function Ic(n){let e=[],s=new Set;for(let t of n.journey){let r=JSON.stringify(t).match(Tc)||[];for(let o of r){let a=o.replace("{{","").replace("}}","").trim(),[c,...l]=a.split("."),d=l.join(".");switch(c){case "fixtures":!n.fixtures||d in n.fixtures;break;case "produces":s.has(d)||e.push({step:t.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:t.id,template:o,error:`Unknown namespace "${c}" in ${o}`});}}if(t.produces)for(let o of Object.keys(t.produces))s.add(o);}return {valid:e.length===0,errors:e}}var Fc="paradigm-personas",Xu={id:Fc,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"}}},Xs=false;async function $c(n){try{let{SentinelStorage:e}=await import('./dist-W3XCATBJ.js'),s=new e;if(!Xs)try{s.registerSchema(Xu),Xs=!0;}catch{Xs=!0;}let t=[];if("persona"in n){let i=n;t.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}`;t.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):[]}});}t.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=n;for(let r of i.persona_results)t.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}});t.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}});}t.length>0&&s.insertEventBatch(Fc,"paradigm-personas",t);}catch{}}function Ec(){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 Nc(n,e,s){switch(n){case "paradigm_persona_create":try{let t=await J$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 I(s.rootDir,t);return {handled:!0,text:JSON.stringify({created:t,persona:i},null,2)}}catch(t){return {handled:true,text:JSON.stringify({error:t.message})}}case "paradigm_persona_get":{let t=e.id,i=await I(s.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Persona ${t} not found`})};let r=await O$1(s.rootDir,i);return {handled:true,text:JSON.stringify({persona:i,validation:r},null,2)}}case "paradigm_persona_list":{let t=await H(s.rootDir,{tag:e.tag,trigger_type:e.trigger_type,gate:e.gate,flow:e.flow,limit:e.limit||50}),i=t.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:t.length,personas:i},null,2)}}case "paradigm_persona_update":{let t=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 K(s.rootDir,t,i))return {handled:true,text:JSON.stringify({error:`Persona ${t} not found`})};let o=await I(s.rootDir,t);return {handled:true,text:JSON.stringify({updated:t,persona:o},null,2)}}case "paradigm_persona_delete":{let t=e.id,i=await L(s.rootDir,t);return i.deleted?{handled:true,text:JSON.stringify({deleted:t,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 ${t} not found`})}}case "paradigm_persona_add_step":try{if(!await M$1(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 I(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(t){return {handled:true,text:JSON.stringify({error:t.message})}}case "paradigm_persona_remove_step":{let t=await N(s.rootDir,e.persona_id,e.step_id);return t.removed?{handled:true,text:JSON.stringify({removed:e.step_id,persona_id:e.persona_id,warnings:t.warnings},null,2)}:{handled:true,text:JSON.stringify({error:`Step ${e.step_id} not found in persona ${e.persona_id}`})}}case "paradigm_persona_validate":{let t=e.deep??false,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 I(s.rootDir,e.persona_id);if(!d)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let p=await O$1(s.rootDir,d,t);if(i)try{let u=await R(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 H(s.rootDir),a=await Promise.all(o.map(async d=>{let p=await O$1(s.rootDir,d,t);if(i)try{let u=await R(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 t=await P(s.rootDir);return {handled:true,text:JSON.stringify(t,null,2)}}case "paradigm_persona_affected":{let t=e.symbol,i=await Q(s.rootDir,t);return i.length===0?{handled:true,text:JSON.stringify({symbol:t,affected:[],note:"No personas reference this symbol."})}:{handled:true,text:JSON.stringify({symbol:t,affected:i},null,2)}}case "paradigm_persona_run":{let t=e.base_url,i=e.dry_run??false,r=e.stop_on_failure??true;if(e.chain_id){let o=await Oc(s.rootDir,e.chain_id,{baseUrl:t,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 I(s.rootDir,e.persona_id);if(!o)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let a=Ic(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 Dc(s.rootDir,e.persona_id,{baseUrl:t,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:""}}}function Hc(){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 qc(n,e,s){switch(n){case "paradigm_protocol_search":{let t=e.task,i=e.limit||3,r=await V(s.rootDir,t,i);return r.length===0?{handled:true,text:JSON.stringify({count:0,task:t,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:r.length,task:t,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(Zu)}))},null,2)}}case "paradigm_protocol_get":{let t=e.id,i=await T(s.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let r=Y(s.rootDir,i);return {handled:true,text:JSON.stringify({...i,freshness:{status:r.status,issues:r.issues}},null,2)}}case "paradigm_protocol_record":{let t=e.steps||[],i=await W(s.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:t,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:i,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let t=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 X$1(s.rootDir,t,r,i===true);return {handled:true,text:JSON.stringify({success:o,id:t,refreshed:i===true,message:o?i?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${t}`})}}case "paradigm_protocol_validate":{let t=e.id;if(t){let a=await T(s.rootDir,t);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let c=Y(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 S(s.rootDir)).map(a=>{let c=Y(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 Zu(n){let e={action:n.action};return n.target&&(e.target=n.target),n.template_from&&(e.template_from=n.template_from),n.reference&&(e.reference=n.reference),n.command&&(e.command=n.command),n.notes&&(e.notes=n.notes),e}var eg=".paradigm/graphs",ti={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},Zs=200,ei=60,pt=20,Wn=40,Mc=50,tg=60;function Wc(){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 Jc(n,e,s){if(n!=="paradigm_graph_generate")return {handled:false,text:""};try{let t=e.name||"untitled",i=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),r=ig(s.rootDir,e.symbols,e.groups,e.links,t),o$1=JSON.stringify(r,null,2),a=F.join(s.rootDir,eg);O.existsSync(a)||O.mkdirSync(a,{recursive:!0});let c=F.join(a,`${i}.graph.json`);O.writeFileSync(c,o$1,"utf8");let l=JSON.stringify({file:c,name:t,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,n),{handled:!0,text:l}}catch(t){let i=JSON.stringify({error:t.message},null,2);return o(i.length,n),{handled:true,text:i}}}var ng={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"};function sg(n){let e=F.join(n,".paradigm","scan-index.json");if(!O.existsSync(e))return [];let s=JSON.parse(O.readFileSync(e,"utf8")),t=[];for(let[i,r]of Object.entries(ng)){let o=s[i];if(!(!o||typeof o!="object"))for(let[a,c]of Object.entries(o)){let l=c;t.push({id:a,name:a,category:r,prefix:ti[r]||"#",description:l.description,path:l.path,tags:l.tags});}}return t}function Lc(n,e){let s=n.replace(/^[#$^!~]/,"");return e.find(t=>t.id===s||t.name===s||t.id===n||t.name===n)}function ig(n,e,s,t,i="Generated Graph"){let r=sg(n),o;e&&e.length>0?o=e.map(g=>Lc(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(v=>Lc(v,o)).filter(Boolean),f=Math.ceil(Math.sqrt(y.length)),b=Math.ceil(y.length/f);for(let v=0;v<y.length;v++){let S=y[v],x=v%f,C=Math.floor(v/f),T=ti[S.category]||"#";a.push({id:`sym-${S.id}`,type:"symbolNode",position:{x:Wn+x*(Zs+pt),y:Mc+Wn+C*(ei+pt)},parentId:m,data:{type:"symbol",symbol:S,label:`${T}${S.name}`}}),d.add(S.id);}let h=Math.max(f,1),w=Math.max(b,1),_=Wn*2+h*Zs+(h-1)*pt,k=Mc+Wn*2+w*ei+(w-1)*pt;a.unshift({id:m,type:"groupNode",position:{x:p,y:0},style:{width:_,height:k},data:{type:"group",label:g.label}}),p+=_+tg;}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=ti[f.category]||"#";a.push({id:`sym-${f.id}`,type:"symbolNode",position:{x:b*(Zs+pt),y:g+h*(ei+pt)},data:{type:"symbol",symbol:f,label:`${w}${f.name}`}});}}if(t&&t.length>0)for(let g of t){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:F.basename(n),lastModified:new Date().toISOString(),nodes:a,edges:c}}var Gc=".paradigm/heat-map.json",rg=.05;function Uc(){return [{name:"paradigm_heatmap_query",description:"Query the adaptive heat map for historically relevant symbols given keywords. Returns associations sorted by confidence.",inputSchema:{type:"object",properties:{keywords:{type:"array",items:{type:"string"},description:"Keywords to search for in the heat map"}},required:["keywords"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_heatmap_record",description:"Record a query-to-symbol association in the adaptive heat map. Use positive signal to reinforce, negative to correct.",inputSchema:{type:"object",properties:{keywords:{type:"array",items:{type:"string"},description:"Keywords that relate to the symbols"},symbols:{type:"array",items:{type:"string"},description:"Symbol IDs (with prefix) that are relevant"},aspects:{type:"array",items:{type:"string"},description:"Aspect IDs that are relevant (optional)"},context:{type:"string",description:"Why this association exists"},signal:{type:"string",enum:["positive","negative"],description:"Positive reinforces, negative reduces confidence"},correction:{type:"string",description:"Explanation if correcting a wrong association"}},required:["keywords","symbols","signal"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_heatmap_stats",description:"Show heat map statistics \u2014 total associations, hot/cold keywords, top symbols, session count.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}}]}function ni(n){let e=F.join(n,Gc);return O.existsSync(e)?JSON.parse(O.readFileSync(e,"utf8")):{version:"1.0",lastUpdated:new Date().toISOString(),sessionCount:0,associations:[]}}function og(n,e){let s=F.join(n,Gc),t=F.dirname(s);O.existsSync(t)||O.mkdirSync(t,{recursive:true}),e.lastUpdated=new Date().toISOString(),O.writeFileSync(s,JSON.stringify(e,null,2),"utf8");}async function ag(n,e){let s=ni(e),t=Date.now();for(let o of s.associations){let a=(t-new Date(o.lastHit).getTime())/864e5,c=Math.floor(a/30);c>0&&(o.confidence=Math.max(.01,o.confidence*Math.pow(1-rg,c)));}let i=n.keywords.map(o=>o.toLowerCase()),r=s.associations.filter(o=>o.keywords.some(a=>i.some(c=>a.includes(c)||c.includes(a)))).sort((o,a)=>a.confidence-o.confidence).slice(0,10);return JSON.stringify({matches:r,totalAssociations:s.associations.length})}async function cg(n,e){let s=ni(e),t=n.keywords.map(r=>r.toLowerCase()),i=s.associations.find(r=>r.keywords.some(o=>t.includes(o)));if(n.signal==="positive")if(i){i.confidence=Math.min(1,i.confidence+.05),i.hitCount+=1,i.lastHit=new Date().toISOString();for(let r of n.symbols)i.symbols.includes(r)||i.symbols.push(r);if(n.aspects){i.aspects||(i.aspects=[]);for(let r of n.aspects)i.aspects.includes(r)||i.aspects.push(r);}for(let r of t)i.keywords.includes(r)||i.keywords.push(r);}else s.associations.push({keywords:t,symbols:n.symbols,aspects:n.aspects,confidence:.5,hitCount:1,lastHit:new Date().toISOString()});else if(i&&(i.confidence=Math.max(.01,i.confidence-.15),n.correction))for(let r of n.symbols){let o=i.symbols.indexOf(r);o>=0&&i.symbols.splice(o,1);}return og(e,s),JSON.stringify({recorded:true,totalAssociations:s.associations.length})}async function lg(n){let e=ni(n),s=[...e.associations].sort((r,o)=>o.confidence-r.confidence),t=s.filter(r=>r.confidence>.7),i=s.filter(r=>r.confidence<.3);return JSON.stringify({totalAssociations:e.associations.length,sessionCount:e.sessionCount,lastUpdated:e.lastUpdated,hotAssociations:t.slice(0,5).map(r=>({keywords:r.keywords,confidence:r.confidence,hitCount:r.hitCount})),coldAssociations:i.slice(0,5).map(r=>({keywords:r.keywords,confidence:r.confidence,hitCount:r.hitCount})),topSymbols:dg(e)})}function dg(n){let e=new Map;for(let s of n.associations)for(let t of s.symbols)e.set(t,(e.get(t)||0)+s.hitCount);return [...e.entries()].sort((s,t)=>t[1]-s[1]).slice(0,10).map(([s,t])=>({symbol:s,mentions:t}))}async function zc(n,e,s){switch(n){case "paradigm_heatmap_query":{let t=await ag(e,s.rootDir);return o(t.length,n),{handled:true,text:t}}case "paradigm_heatmap_record":{let t=await cg(e,s.rootDir);return o(t.length,n),{handled:true,text:t}}case "paradigm_heatmap_stats":{let t=await lg(s.rootDir);return o(t.length,n),{handled:true,text:t}}default:return {handled:false,text:""}}}var me=["specify","plan","task","implement","validate"],Gt=".paradigm/pipeline",Bc={"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 Jn(n){return n.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Wt(n,e){let s=Jn(e),t=F.join(n,Gt,`${s}.yaml`);return O.existsSync(t)?Z.load(O.readFileSync(t,"utf8")):null}function Jt(n,e){let s=Jn(e.feature),t=F.join(n,Gt);O.existsSync(t)||O.mkdirSync(t,{recursive:true});let i=F.join(t,`${s}.yaml`);return O.writeFileSync(i,Z.dump(e,{lineWidth:120}),"utf8"),i}function Vc(n){let e=F.join(n,Gt);return O.existsSync(e)?O.readdirSync(e).filter(s=>s.endsWith(".yaml")&&!s.startsWith("completed")).map(s=>{try{return Z.load(O.readFileSync(F.join(e,s),"utf8"))}catch{return null}}).filter(Boolean):[]}function pg(n,e,s){let t={specify:{status:"pending"},plan:{status:"pending"},task:{status:"pending"},implement:{status:"pending"},validate:{status:"pending"}};return t.specify.status="in-progress",{version:"1.0",feature:Jn(n),created:new Date().toISOString(),current_stage:"specify",gate_config:e,template:s,stages:t}}function ug(n){let e=me.indexOf(n);return e<me.length-1?me[e+1]:null}function Yc(n,e){let s=Jn(e.feature),t=F.join(n,Gt,"completed");O.existsSync(t)||O.mkdirSync(t,{recursive:true});let i=F.join(t,`${s}.yaml`);O.writeFileSync(i,Z.dump(e,{lineWidth:120}),"utf8");let r=F.join(n,Gt,`${s}.yaml`);O.existsSync(r)&&O.unlinkSync(r);}function Kc(){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 Qc(n,e,s){switch(n){case "paradigm_pipeline_start":{let t=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=Bc[i];if(!l)return {handled:true,text:JSON.stringify({error:`Unknown template: ${i}`,available:Object.keys(Bc)})};o=l.gates;}let a=pg(t,o,i),c=Jt(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 t=e.feature;if(t){let r=Wt(s.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${t}`})};let o=me.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}/${me.length}`,gate_config:r.gate_config,stages:r.stages},null,2)}}let i=Vc(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=me.filter(a=>r.stages[a].status==="approved").length;return {feature:r.feature,current_stage:r.current_stage,progress:`${o}/${me.length}`,template:r.template,created:r.created}})},null,2)}}case "paradigm_pipeline_advance":{let t=e.feature,i=e.approved_by||"agent",r=Wt(s.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${t}`})};let o=r.current_stage,a=r.gate_config[o],c=ug(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",Jt(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)}):(Jt(s.rootDir,r),Yc(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 t=e.feature,i=e.updates,r=e.reason,o=Wt(s.rootDir,t);if(!o)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${t}`})};let a=[];for(let[c,l]of Object.entries(i))if(me.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:me,valid_modes:["auto","manual","sentinel"]})}:(Jt(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 t=e.feature,i=e.stage,r=e.question,o=e.options,a=e.context,c=Wt(s.rootDir,t);return c?(c.stages[i].status="blocked",c.stages[i].block_reason=r,Jt(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: ${t}`})}}case "paradigm_pipeline_abort":{let t=e.feature,i=Wt(s.rootDir,t);return i?(Yc(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: ${t}`})}}case "paradigm_pipeline_list":{let t=Vc(s.rootDir);return t.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines."})}:{handled:true,text:JSON.stringify({count:t.length,pipelines:t.map(i=>{let r=me.filter(o=>i.stages[o].status==="approved").length;return {feature:i.feature,current_stage:i.current_stage,progress:`${r}/${me.length}`,template:i.template,created:i.created}})},null,2)}}default:return {handled:false,text:""}}}var gg=F.join(ma.homedir(),".conductor"),mt=F.join(gg,"sessions");function Zc(){O.existsSync(mt)||O.mkdirSync(mt,{recursive:true});}function ii(n){Zc();let e={...n,registeredAt:new Date().toISOString()},s=F.join(mt,`${n.pid}.json`);return O.writeFileSync(s,JSON.stringify(e,null,2),"utf-8"),e}function Gn(n){let e=F.join(mt,`${n}.json`);return O.existsSync(e)?(O.unlinkSync(e),true):false}function ri(){Zc();let n=O.readdirSync(mt).filter(s=>s.endsWith(".json")),e=[];for(let s of n)try{let t=O.readFileSync(F.join(mt,s),"utf-8"),i=JSON.parse(t);e.push(i);}catch{}return e}function el(){let n=ri(),e=0;for(let s of n)mg(s.pid)||(Gn(s.pid),e++);return e}function mg(n){try{return process.kill(n,0),!0}catch{return false}}function oi(){try{return execSync(`osascript -e '
808
846
  tell application "System Events"
809
847
  set frontApp to first application process whose frontmost is true
810
848
  return bundle identifier of frontApp
@@ -837,7 +875,7 @@ ${c.content.diff}
837
875
  `).map(m=>{try{let y=JSON.parse(m);return u.has(y.id)?(y.surfaced=!0,JSON.stringify(y)):m}catch{return m}});O.writeFileSync(l,g.join(`
838
876
  `)+`
839
877
  `,"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:t(d),handled:true}}case "paradigm_ambient_events":{let i=e.since?Fg(e.since):void 0,r=e.limit||50,o=a$5(s.rootDir,{type:e.type,source:e.source,symbol:e.symbol,agent:e.agent,since:i,limit:r});return {text:t({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}=await import('./session-work-log-5PHOUEQ6.js'),p=i$2(s.rootDir,{limit:500}).find(u=>u.id===i);l(s.rootDir,{timestamp:new Date().toISOString(),type:"user-verdict",agent:p?.agent,nominationId:i,verdict:r,reason:o});}catch{}let c=false;return e.resolve_debate&&a&&(c=l$1(s.rootDir,e.resolve_debate,i,e.reason)),{text:t({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:t({error:`Agent profile not found: ${i}`}),handled:true};let u=[],g=p$2(p,r);if(g.trim()&&u.push(g),a){let m=d$2(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$4(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:t({agent:i,context:u.join(`
840
- `),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:t({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$1(s.rootDir,i);if(r)return {text:t({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:t({agent:i,...a,stats:o}),handled:true}}case "paradigm_ambient_neverland":{let i=q$1(s.rootDir);return {text:t(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:t(await Hg(s.rootDir,e)),handled:true};default:return {text:`Unknown ambient tool: ${n}`,handled:false}}}var Ng={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function Eg(n){try{let e=F.join(n,".paradigm","config.yaml");if(O.existsSync(e)){let t=O.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(t)return t[1].trim()}}catch{}return F.basename(n)}async function Hg(n,e={}){let s=e.dry_run===true,t=Eg(n),i=b$9(n),r=i.filter(m=>m.type==="user-verdict"&&m.verdict&&m.agent);if(r.length===0)return {sessionEntries:i.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:s,details:[]};let o=new Map;for(let m of r){let y=m.agent;o.has(y)||o.set(y,[]),o.get(y).push(m);}let a=i.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,_=w>0?f/w:0;for(let k of y){let v=Ng[k.verdict];if(!v)continue;let S=c.get(m)?.shift(),x=qg(k,S,{acceptRate:_,total:w,accepted:f}),C=k.verdict==="accepted"?.85:k.verdict==="revised"?.6:.4,T={agent:m,verdict:k.verdict,trigger:v,insight:x,symbols:k.symbols};if(l.push(T),s)d[m]++,p++;else try{a$3(m,{trigger:v,insight:x,confidence_before:k.verdict==="accepted"?.7:.8,confidence_after:C,project:t,transferable:k.verdict==="dismissed",tags:["postflight",`verdict:${k.verdict}`,...(k.symbols||[]).map(j=>`symbol:${j}`)]}),d[m]++,p++;}catch{}}}let u={},g=0;if(!s)for(let m of o.keys())try{let y=s$1(n,m);y.promoted>0&&(u[m]=y.promoted,g+=y.promoted);}catch{}return {sessionEntries:i.length,agentsProcessed:Array.from(o.keys()),journalsWritten:p,journalsByAgent:d,promoted:g,promotedByAgent:u,dryRun:s,details:l}}function qg(n,e,s){let t=n.symbols?.length?` (symbols: ${n.symbols.join(", ")})`:"",i=n.reason?` Reason: ${n.reason}.`:"";switch(n.verdict){case "accepted":return `Contribution accepted by user${t}.${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${t}.${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${t}.${i}`+(n.revisionDelta?` Delta: "${n.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 "${n.verdict}"${t}.${i}`}}var Vt=["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"],Nl={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 Vn(n){let e=F.join(n,".paradigm","config.yaml");if(!O.existsSync(e))return {};try{return Z.load(O.readFileSync(e,"utf8"))||{}}catch{return {}}}function fi(n,e){let s=F.join(n,".paradigm","config.yaml");O.writeFileSync(s,Z.dump(e,{lineWidth:120,noRefs:true}),"utf8");}function Yn(n){let e=n.enforcement?.level||"minimal",s=Nl[e]||Nl.minimal,t=n.enforcement?.checks||{},i=n.enforcement?.orchestration?.threshold??3,r={...s};for(let[o,a]of Object.entries(t))Vt.includes(o)&&El(a)&&(r[o]=a);return r.orchestrationThreshold=i,r}function El(n){return n==="block"||n==="warn"||n==="off"}function Mg(n){return n==="strict"||n==="balanced"||n==="minimal"}function Lg(n){return Vt.includes(n)}var Wg=[{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: "+Vt.join(", ")},severity:{type:"string",enum:["block","warn","off"],description:"Severity to set for the check (for override action)."}},required:["action"]}}];async function Jg(n,e){let{action:s,level:t,checkId:i,severity:r}=e;switch(s){case "status":{let o=Vn(n.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:[...Vt],presetLevels:["strict","balanced","minimal"]},null,2)}case "set-level":{if(!t||!Mg(t))return JSON.stringify({error:`Invalid level "${t}". Must be one of: strict, balanced, minimal`});let o=Vn(n.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.level=t,o.enforcement.checks={},fi(n.rootDir,o);let a=Yn(o);return JSON.stringify({success:true,level:t,message:`Enforcement level set to "${t}". Per-check overrides cleared.`,effective:a},null,2)}case "override":{if(!i||!Lg(i))return JSON.stringify({error:`Invalid checkId "${i}". Must be one of: ${Vt.join(", ")}`});if(!r||!El(r))return JSON.stringify({error:`Invalid severity "${r}". Must be one of: block, warn, off`});let o=Vn(n.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.checks||(o.enforcement.checks={}),o.enforcement.checks[i]=r,fi(n.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=Vn(n.rootDir);o.enforcement&&(o.enforcement.checks={}),fi(n.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 Hl(){return Wg}async function ql(n,e,s){if(n==="paradigm_enforcement_configure"){let t=await Jg(s,e);return o(t.length,"paradigm_enforcement_configure"),{handled:true,text:t}}return {handled:false,text:""}}function Gg(n,e){let s=[];for(let t=0;t<=e.length;t++)s[t]=[t];for(let t=0;t<=n.length;t++)s[0][t]=t;for(let t=1;t<=e.length;t++)for(let i=1;i<=n.length;i++)e.charAt(t-1)===n.charAt(i-1)?s[t][i]=s[t-1][i-1]:s[t][i]=Math.min(s[t-1][i-1]+1,s[t][i-1]+1,s[t-1][i]+1);return s[e.length][n.length]}function Ml(n,e,s={}){let{maxDistance:t=3,maxResults:i=5}=s,r=n.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=Gg(r,c);l<=t&&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$1();function Bg(n,e){let s$1=new u(n),t=e||(async()=>{}),i=o=>async(a,c,l)=>o(a,c,l),r$1=o=>async(a,c,l)=>o(a,c,l,t);return s$1.registerAll([{key:"context",tier:"core",getToolsList:r,handleTool:i(s)},{key:"navigate",tier:"core",getToolsList:Zo,handleTool:i(ea)},{key:"tags",tier:"core",getToolsList:ka,handleTool:i(Sa)},{key:"purpose-portal",tier:"core",getToolsList:Da,handleTool:r$1(Aa)},{key:"pm",tier:"core",getToolsList:Va,handleTool:i(Ya)},{key:"reindex",tier:"core",getToolsList:ma$1,handleTool:r$1(na$1)},{key:"docs",tier:"core",getToolsList:Rl,handleTool:i(jl)},{key:"ripple",tier:"core",getToolsList:Dl,handleTool:i(Al)}]),s$1.registerAll([{key:"wisdom",tier:"feature",getToolsList:Uo,handleTool:i(zo)},{key:"history",tier:"feature",getToolsList:Bo,handleTool:i(Vo)},{key:"lore",tier:"feature",getToolsList:Za,handleTool:i(ec)},{key:"streams",tier:"feature",getToolsList:Ol,handleTool:i(Il)},{key:"ambient",tier:"feature",getToolsList:$l,handleTool:i(Fl)},{key:"sentinel",tier:"feature",getToolsList:ta,handleTool:i(na)},{key:"flows",tier:"feature",getToolsList:ia,handleTool:i(ra)},{key:"fixtures",tier:"feature",getToolsList:da,handleTool:i(pa)},{key:"orchestration",tier:"feature",getToolsList:ya,handleTool:i(ha)},{key:"habits",tier:"feature",getToolsList:nc,handleTool:i(sc)},{key:"tasks",tier:"feature",getToolsList:fc,handleTool:i(yc)},{key:"personas",tier:"feature",getToolsList:Nc,handleTool:i(Ec)},{key:"protocols",tier:"feature",getToolsList:Hc,handleTool:i(qc)},{key:"symphony",tier:"feature",getToolsList:rl,handleTool:i(ol)},{key:"university",tier:"feature",getToolsList:cl,handleTool:i(ll)},{key:"agents",tier:"feature",getToolsList:ul,handleTool:i(gl)},{key:"notebooks",tier:"feature",getToolsList:ml,handleTool:i(fl)},{key:"aspect-graph",tier:"feature",getToolsList:gc,handleTool:i(mc)},{key:"enforcement",tier:"feature",getToolsList:Hl,handleTool:i(ql),detect:o=>O.existsSync(F.join(o,".paradigm","config.yaml"))},{key:"graph",tier:"feature",getToolsList:Wc,handleTool:i(Jc),detect:o=>O.existsSync(F.join(o,".paradigm","aspect-graph.db"))},{key:"heatmap",tier:"feature",getToolsList:Uc,handleTool:i(zc),detect:o=>O.existsSync(F.join(o,".paradigm","aspect-graph.db"))}]),s$1.registerAll([{key:"conductor",tier:"advanced",getToolsList:nl,handleTool:i(sl)},{key:"platform",tier:"advanced",getToolsList:dl,handleTool:i(pl)},{key:"pipeline",tier:"advanced",getToolsList:Kc,handleTool:i(Qc)},{key:"graduation",tier:"advanced",getToolsList:ac,handleTool:i(cc)},{key:"assessment",tier:"advanced",getToolsList:Cc,handleTool:i(Pc)}]),s$1}function Vg(n,e){let s=g=>g.toLowerCase().replace(/\/+$/,""),t=s(n),i=s(e);if(t===i)return 1;let r=g=>!g.includes("/")&&g.includes("."),o=g=>r(g)?g.split("."):g.split("/").filter(Boolean),a=o(t),c=o(i);if(r(t)||r(i)){let g=r(t)?t.split("."):t.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 Yg(){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}},{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}},{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}},{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 Wl(n$2,e,s){let t$1=e(),i$1=Bg(t$1.rootDir,s);n$2.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[...Yg(),...i$1.getActiveTools()]})),n$2.setRequestHandler(CallToolRequestSchema,async r=>{let{name:o$1,arguments:a$1}=r.params;q(o$1,a$1??{});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(),b$2(),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$1,_=`search:${g}:${m||""}:${y}:${f}:${b}:${h||""}`,k=await v$2.getOrCompute(_,()=>{let C=j$2(c.index,g);return m&&(C=C.filter(T=>T.type===m)),h&&(C=C.filter(T=>T.componentType===h)),C}),v=[];if(k.length===0&&f){let C=n(c.index),T=C.map(j=>j.symbol);v=Ml(g,T,{maxDistance:3,maxResults:5}),v.length>0&&(k=v.map(j=>C.find(P=>P.symbol===j.match)).filter(j=>j!=null),m&&(k=k.filter(j=>j.type===m)));}k=k.slice(0,y);let S={query:g,count:k.length,results:k.map(C=>({symbol:C.symbol,type:C.type,description:C.description,filePath:C.filePath,...C.componentType?{componentType:C.componentType}:{},...C.parentSymbol?{parentSymbol:C.parentSymbol}:{}}))};if(v.length>0&&(S.fuzzyMatched=true,S.fuzzyNote=`No exact matches for "${g}". Showing similar symbols.`,S.suggestions=v.map(C=>({symbol:C.match,distance:C.distance}))),b&&c.workspace){let C=jt(c.workspace,g),T=m?C.filter(j=>j.type===m):C;T.length>0&&(S.workspaceResults=T.slice(0,y).map(j=>({symbol:j.symbol,type:j.type,description:j.description,filePath:j.filePath,project:j.project})),S.workspaceCount=T.length);}w==="concise"&&(S.results=k.map(C=>({symbol:C.symbol,type:C.type})),delete S.fuzzyMatched,delete S.fuzzyNote,delete S.suggestions,delete S.workspaceResults,delete S.workspaceCount);let x=JSON.stringify(S,null,2);return o(x.length,o$1),{content:[{type:"text",text:x}]}}case "paradigm_related":{let{symbol:g}=a$1,m=h$1(c.index,g);if(!m){let h=Bn(c.rootDir,g,{maxResults:20});if(h.length===0){let S=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(S.length,o$1),{content:[{type:"text",text:S}]}}let w=[...new Set(h.map(S=>S.filePath))],_=h.filter(S=>S.context==="purpose"),k=h.filter(S=>S.context==="code"),v=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(S=>({file:S,references:h.filter(x=>x.filePath===S).length})),uses:[],summary:{totalFiles:w.length,totalReferences:h.length,purposeFileRefs:_.length,codeRefs:k.length},suggestion:"Run `paradigm scan` to enable full relationship tracking"},null,2);return o(v.length,o$1),{content:[{type:"text",text:v}]}}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$1.response_format,m$1=await v$2.getOrCompute("status",async()=>{let f=m(c.index),b=Object.values(f).reduce((j,P)=>j+P,0),h={};for(let j of Object.keys(f)){let P=i(c.index,j);h[j]=P.slice(0,3).map(D=>D.symbol);}let w=ma.platform(),_=w==="win32",k=_?"PowerShell/CMD":w==="darwin"?"zsh/bash":"bash",v;try{let j=await U(c.rootDir);j&&j.health.total>0&&(v=j.health);}catch{}let S=i(c.index,"component"),x={};for(let j of S)j.componentType&&(x[j.componentType]=(x[j.componentType]||0)+1);let C=S.filter(j=>!j.componentType).length,T;try{let{checkPurposeHealth:j}=await import('./integrity-checker-DHGMZQDG.js');T=j(c.aggregation.purposeFiles,c.rootDir).healthScore;}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(x).length>0?{componentTypes:{...x,...C>0?{"(untyped)":C}:{}}}:{},examples:h,hasPortalYaml:c.gateConfig!==null,purposeFiles:c.aggregation.purposeFiles.length,...T!==void 0?{purposeHealthScore:T}:{},...v?{protocols:v}:{},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:_?"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$1,f=typeof g=="string"&&!g.includes("/")&&g.includes(".")?"POST":a$1.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 I=D.gateConfig;if(I?.routes)for(let[A,N]of Object.entries(I.routes)){let H=N,q=Array.isArray(H)?H:H?.gates;q&&w.push({route:A,gates:q,method:Array.isArray(H)?void 0:H?.method,source:P});}}for(let P of w){let D=Vg(g,P.route);if(D>=.6&&(!P.method||P.method===f))for(let I of P.gates){let A=b.find(N=>N.symbol===I||N.symbol===`^${I}`);if(A&&!h.find(N=>N.gate===A.symbol)){let N=P.source?`${P.source}/portal.yaml`:"portal.yaml";h.push({gate:A.symbol,reason:`Similar route "${P.route}" uses this gate`,confidence:D>=.8?"high":"medium",source:N});}}}let v=g.split("/").filter(Boolean).find(P=>!P.startsWith(":")&&P!=="api")?.replace(/s$/,"")||"",S=g.match(/\/:(id|[a-z]+Id)($|\/)/i);if(S&&v){let P=b.find(D=>{let I=D.symbol.toLowerCase(),A=(D.description||"").toLowerCase();return I.includes(`${v}-owner`)||I.includes("owner")||I.includes("ownership")||A.includes("owner")||A.includes("ownership")||A.includes("belongs to")});P?h.push({gate:P.symbol,reason:`Resource ID route (${v}) typically needs ownership verification`,confidence:"high"}):h.push({gate:`^${v}-owner`,reason:`Consider adding ownership gate for ${v} resource`,confidence:"medium"});}if(g.includes("/admin")||g.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(g.startsWith("/api/")||g.includes("/user")||g.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(g.includes("/premium")||g.includes("/pro")||g.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 x=new Set,C=h.filter(P=>x.has(P.gate)?false:(x.add(P.gate),true)),T=m==="concise"?{suggestions:C.map(P=>({gate:P.gate,confidence:P.confidence}))}:{route:g,method:f,suggestions:C,availableGates:b.map(P=>({symbol:P.symbol,description:P.description})),note:S?"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."},j=JSON.stringify(T,null,2);o(j.length,o$1);try{n$1(c.rootDir,{type:"gate-checked",source:"mcp-tool-call",tool:"paradigm_gates_for_route",symbols:C.map(P=>P.gate),context:`Gate check for ${f} ${g}`});}catch{}return {content:[{type:"text",text:j}]}}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:
878
+ `),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:t({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$1(s.rootDir,i);if(r)return {text:t({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:t({agent:i,...a,stats:o}),handled:true}}case "paradigm_ambient_neverland":{let i=q$1(s.rootDir);return {text:t(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:t(await Hg(s.rootDir,e)),handled:true};default:return {text:`Unknown ambient tool: ${n}`,handled:false}}}var Eg={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function Ng(n){try{let e=F.join(n,".paradigm","config.yaml");if(O.existsSync(e)){let t=O.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(t)return t[1].trim()}}catch{}return F.basename(n)}async function Hg(n,e={}){let s=e.dry_run===true,t=Ng(n),i=b$9(n),r=i.filter(m=>m.type==="user-verdict"&&m.verdict&&m.agent);if(r.length===0)return {sessionEntries:i.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:s,details:[]};let o=new Map;for(let m of r){let y=m.agent;o.has(y)||o.set(y,[]),o.get(y).push(m);}let a=i.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,_=w>0?f/w:0;for(let k of y){let v=Eg[k.verdict];if(!v)continue;let S=c.get(m)?.shift(),x=qg(k,S,{acceptRate:_,total:w,accepted:f}),C=k.verdict==="accepted"?.85:k.verdict==="revised"?.6:.4,T={agent:m,verdict:k.verdict,trigger:v,insight:x,symbols:k.symbols};if(l.push(T),s)d[m]++,p++;else try{a$3(m,{trigger:v,insight:x,confidence_before:k.verdict==="accepted"?.7:.8,confidence_after:C,project:t,transferable:k.verdict==="dismissed",tags:["postflight",`verdict:${k.verdict}`,...(k.symbols||[]).map(j=>`symbol:${j}`)]}),d[m]++,p++;}catch{}}}let u={},g=0;if(!s)for(let m of o.keys())try{let y=s$1(n,m);y.promoted>0&&(u[m]=y.promoted,g+=y.promoted);}catch{}return {sessionEntries:i.length,agentsProcessed:Array.from(o.keys()),journalsWritten:p,journalsByAgent:d,promoted:g,promotedByAgent:u,dryRun:s,details:l}}function qg(n,e,s){let t=n.symbols?.length?` (symbols: ${n.symbols.join(", ")})`:"",i=n.reason?` Reason: ${n.reason}.`:"";switch(n.verdict){case "accepted":return `Contribution accepted by user${t}.${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${t}.${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${t}.${i}`+(n.revisionDelta?` Delta: "${n.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 "${n.verdict}"${t}.${i}`}}var Vt=["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"],El={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 Vn(n){let e=F.join(n,".paradigm","config.yaml");if(!O.existsSync(e))return {};try{return Z.load(O.readFileSync(e,"utf8"))||{}}catch{return {}}}function fi(n,e){let s=F.join(n,".paradigm","config.yaml");O.writeFileSync(s,Z.dump(e,{lineWidth:120,noRefs:true}),"utf8");}function Yn(n){let e=n.enforcement?.level||"minimal",s=El[e]||El.minimal,t=n.enforcement?.checks||{},i=n.enforcement?.orchestration?.threshold??3,r={...s};for(let[o,a]of Object.entries(t))Vt.includes(o)&&Nl(a)&&(r[o]=a);return r.orchestrationThreshold=i,r}function Nl(n){return n==="block"||n==="warn"||n==="off"}function Mg(n){return n==="strict"||n==="balanced"||n==="minimal"}function Lg(n){return Vt.includes(n)}var Wg=[{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: "+Vt.join(", ")},severity:{type:"string",enum:["block","warn","off"],description:"Severity to set for the check (for override action)."}},required:["action"]}}];async function Jg(n,e){let{action:s,level:t,checkId:i,severity:r}=e;switch(s){case "status":{let o=Vn(n.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:[...Vt],presetLevels:["strict","balanced","minimal"]},null,2)}case "set-level":{if(!t||!Mg(t))return JSON.stringify({error:`Invalid level "${t}". Must be one of: strict, balanced, minimal`});let o=Vn(n.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.level=t,o.enforcement.checks={},fi(n.rootDir,o);let a=Yn(o);return JSON.stringify({success:true,level:t,message:`Enforcement level set to "${t}". Per-check overrides cleared.`,effective:a},null,2)}case "override":{if(!i||!Lg(i))return JSON.stringify({error:`Invalid checkId "${i}". Must be one of: ${Vt.join(", ")}`});if(!r||!Nl(r))return JSON.stringify({error:`Invalid severity "${r}". Must be one of: block, warn, off`});let o=Vn(n.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.checks||(o.enforcement.checks={}),o.enforcement.checks[i]=r,fi(n.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=Vn(n.rootDir);o.enforcement&&(o.enforcement.checks={}),fi(n.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 Hl(){return Wg}async function ql(n,e,s){if(n==="paradigm_enforcement_configure"){let t=await Jg(s,e);return o(t.length,"paradigm_enforcement_configure"),{handled:true,text:t}}return {handled:false,text:""}}function Gg(n,e){let s=[];for(let t=0;t<=e.length;t++)s[t]=[t];for(let t=0;t<=n.length;t++)s[0][t]=t;for(let t=1;t<=e.length;t++)for(let i=1;i<=n.length;i++)e.charAt(t-1)===n.charAt(i-1)?s[t][i]=s[t-1][i-1]:s[t][i]=Math.min(s[t-1][i-1]+1,s[t][i-1]+1,s[t-1][i]+1);return s[e.length][n.length]}function Ml(n,e,s={}){let{maxDistance:t=3,maxResults:i=5}=s,r=n.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=Gg(r,c);l<=t&&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$1();function Bg(n,e){let s$1=new u(n),t=e||(async()=>{}),i=o=>async(a,c,l)=>o(a,c,l),r$1=o=>async(a,c,l)=>o(a,c,l,t);return s$1.registerAll([{key:"context",tier:"core",getToolsList:r,handleTool:i(s)},{key:"navigate",tier:"core",getToolsList:Zo,handleTool:i(ea)},{key:"tags",tier:"core",getToolsList:ka,handleTool:i(Sa)},{key:"purpose-portal",tier:"core",getToolsList:Da,handleTool:r$1(Aa)},{key:"pm",tier:"core",getToolsList:Va,handleTool:i(Ya)},{key:"reindex",tier:"core",getToolsList:ma$1,handleTool:r$1(na$1)},{key:"docs",tier:"core",getToolsList:Rl,handleTool:i(jl)},{key:"ripple",tier:"core",getToolsList:Dl,handleTool:i(Al)}]),s$1.registerAll([{key:"wisdom",tier:"feature",getToolsList:Uo,handleTool:i(zo)},{key:"history",tier:"feature",getToolsList:Bo,handleTool:i(Vo)},{key:"lore",tier:"feature",getToolsList:Za,handleTool:i(ec)},{key:"streams",tier:"feature",getToolsList:Ol,handleTool:i(Il)},{key:"ambient",tier:"feature",getToolsList:$l,handleTool:i(Fl)},{key:"sentinel",tier:"feature",getToolsList:ta,handleTool:i(na)},{key:"flows",tier:"feature",getToolsList:ia,handleTool:i(ra)},{key:"fixtures",tier:"feature",getToolsList:da,handleTool:i(pa)},{key:"orchestration",tier:"feature",getToolsList:ya,handleTool:i(ha)},{key:"habits",tier:"feature",getToolsList:nc,handleTool:i(sc)},{key:"tasks",tier:"feature",getToolsList:fc,handleTool:i(yc)},{key:"personas",tier:"feature",getToolsList:Ec,handleTool:i(Nc)},{key:"protocols",tier:"feature",getToolsList:Hc,handleTool:i(qc)},{key:"symphony",tier:"feature",getToolsList:rl,handleTool:i(ol)},{key:"university",tier:"feature",getToolsList:cl,handleTool:i(ll)},{key:"agents",tier:"feature",getToolsList:ul,handleTool:i(gl)},{key:"notebooks",tier:"feature",getToolsList:ml,handleTool:i(fl)},{key:"aspect-graph",tier:"feature",getToolsList:gc,handleTool:i(mc)},{key:"enforcement",tier:"feature",getToolsList:Hl,handleTool:i(ql),detect:o=>O.existsSync(F.join(o,".paradigm","config.yaml"))},{key:"graph",tier:"feature",getToolsList:Wc,handleTool:i(Jc),detect:o=>O.existsSync(F.join(o,".paradigm","aspect-graph.db"))},{key:"heatmap",tier:"feature",getToolsList:Uc,handleTool:i(zc),detect:o=>O.existsSync(F.join(o,".paradigm","aspect-graph.db"))}]),s$1.registerAll([{key:"conductor",tier:"advanced",getToolsList:nl,handleTool:i(sl)},{key:"platform",tier:"advanced",getToolsList:dl,handleTool:i(pl)},{key:"pipeline",tier:"advanced",getToolsList:Kc,handleTool:i(Qc)},{key:"graduation",tier:"advanced",getToolsList:ac,handleTool:i(cc)},{key:"assessment",tier:"advanced",getToolsList:Cc,handleTool:i(Pc)}]),s$1}function Vg(n,e){let s=g=>g.toLowerCase().replace(/\/+$/,""),t=s(n),i=s(e);if(t===i)return 1;let r=g=>!g.includes("/")&&g.includes("."),o=g=>r(g)?g.split("."):g.split("/").filter(Boolean),a=o(t),c=o(i);if(r(t)||r(i)){let g=r(t)?t.split("."):t.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 Yg(){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}},{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}},{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}},{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 Wl(n$2,e,s){let t$1=e(),i$1=Bg(t$1.rootDir,s);n$2.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[...Yg(),...i$1.getActiveTools()]})),n$2.setRequestHandler(CallToolRequestSchema,async r=>{let{name:o$1,arguments:a$1}=r.params;q(o$1,a$1??{});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(),b$2(),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$1,_=`search:${g}:${m||""}:${y}:${f}:${b}:${h||""}`,k=await v$2.getOrCompute(_,()=>{let C=j$2(c.index,g);return m&&(C=C.filter(T=>T.type===m)),h&&(C=C.filter(T=>T.componentType===h)),C}),v=[];if(k.length===0&&f){let C=n(c.index),T=C.map(j=>j.symbol);v=Ml(g,T,{maxDistance:3,maxResults:5}),v.length>0&&(k=v.map(j=>C.find(P=>P.symbol===j.match)).filter(j=>j!=null),m&&(k=k.filter(j=>j.type===m)));}k=k.slice(0,y);let S={query:g,count:k.length,results:k.map(C=>({symbol:C.symbol,type:C.type,description:C.description,filePath:C.filePath,...C.componentType?{componentType:C.componentType}:{},...C.parentSymbol?{parentSymbol:C.parentSymbol}:{}}))};if(v.length>0&&(S.fuzzyMatched=true,S.fuzzyNote=`No exact matches for "${g}". Showing similar symbols.`,S.suggestions=v.map(C=>({symbol:C.match,distance:C.distance}))),b&&c.workspace){let C=jt(c.workspace,g),T=m?C.filter(j=>j.type===m):C;T.length>0&&(S.workspaceResults=T.slice(0,y).map(j=>({symbol:j.symbol,type:j.type,description:j.description,filePath:j.filePath,project:j.project})),S.workspaceCount=T.length);}w==="concise"&&(S.results=k.map(C=>({symbol:C.symbol,type:C.type})),delete S.fuzzyMatched,delete S.fuzzyNote,delete S.suggestions,delete S.workspaceResults,delete S.workspaceCount);let x=JSON.stringify(S,null,2);return o(x.length,o$1),{content:[{type:"text",text:x}]}}case "paradigm_related":{let{symbol:g}=a$1,m=h$1(c.index,g);if(!m){let h=Bn(c.rootDir,g,{maxResults:20});if(h.length===0){let S=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(S.length,o$1),{content:[{type:"text",text:S}]}}let w=[...new Set(h.map(S=>S.filePath))],_=h.filter(S=>S.context==="purpose"),k=h.filter(S=>S.context==="code"),v=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(S=>({file:S,references:h.filter(x=>x.filePath===S).length})),uses:[],summary:{totalFiles:w.length,totalReferences:h.length,purposeFileRefs:_.length,codeRefs:k.length},suggestion:"Run `paradigm scan` to enable full relationship tracking"},null,2);return o(v.length,o$1),{content:[{type:"text",text:v}]}}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$1.response_format,m$1=await v$2.getOrCompute("status",async()=>{let f=m(c.index),b=Object.values(f).reduce((j,P)=>j+P,0),h={};for(let j of Object.keys(f)){let P=i(c.index,j);h[j]=P.slice(0,3).map(D=>D.symbol);}let w=ma.platform(),_=w==="win32",k=_?"PowerShell/CMD":w==="darwin"?"zsh/bash":"bash",v;try{let j=await U(c.rootDir);j&&j.health.total>0&&(v=j.health);}catch{}let S=i(c.index,"component"),x={};for(let j of S)j.componentType&&(x[j.componentType]=(x[j.componentType]||0)+1);let C=S.filter(j=>!j.componentType).length,T;try{let{checkPurposeHealth:j}=await import('./integrity-checker-DHGMZQDG.js');T=j(c.aggregation.purposeFiles,c.rootDir).healthScore;}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(x).length>0?{componentTypes:{...x,...C>0?{"(untyped)":C}:{}}}:{},examples:h,hasPortalYaml:c.gateConfig!==null,purposeFiles:c.aggregation.purposeFiles.length,...T!==void 0?{purposeHealthScore:T}:{},...v?{protocols:v}:{},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:_?"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$1,f=typeof g=="string"&&!g.includes("/")&&g.includes(".")?"POST":a$1.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 I=D.gateConfig;if(I?.routes)for(let[A,E]of Object.entries(I.routes)){let H=E,q=Array.isArray(H)?H:H?.gates;q&&w.push({route:A,gates:q,method:Array.isArray(H)?void 0:H?.method,source:P});}}for(let P of w){let D=Vg(g,P.route);if(D>=.6&&(!P.method||P.method===f))for(let I of P.gates){let A=b.find(E=>E.symbol===I||E.symbol===`^${I}`);if(A&&!h.find(E=>E.gate===A.symbol)){let E=P.source?`${P.source}/portal.yaml`:"portal.yaml";h.push({gate:A.symbol,reason:`Similar route "${P.route}" uses this gate`,confidence:D>=.8?"high":"medium",source:E});}}}let v=g.split("/").filter(Boolean).find(P=>!P.startsWith(":")&&P!=="api")?.replace(/s$/,"")||"",S=g.match(/\/:(id|[a-z]+Id)($|\/)/i);if(S&&v){let P=b.find(D=>{let I=D.symbol.toLowerCase(),A=(D.description||"").toLowerCase();return I.includes(`${v}-owner`)||I.includes("owner")||I.includes("ownership")||A.includes("owner")||A.includes("ownership")||A.includes("belongs to")});P?h.push({gate:P.symbol,reason:`Resource ID route (${v}) typically needs ownership verification`,confidence:"high"}):h.push({gate:`^${v}-owner`,reason:`Consider adding ownership gate for ${v} resource`,confidence:"medium"});}if(g.includes("/admin")||g.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(g.startsWith("/api/")||g.includes("/user")||g.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(g.includes("/premium")||g.includes("/pro")||g.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 x=new Set,C=h.filter(P=>x.has(P.gate)?false:(x.add(P.gate),true)),T=m==="concise"?{suggestions:C.map(P=>({gate:P.gate,confidence:P.confidence}))}:{route:g,method:f,suggestions:C,availableGates:b.map(P=>({symbol:P.symbol,description:P.description})),note:S?"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."},j=JSON.stringify(T,null,2);o(j.length,o$1);try{n$1(c.rootDir,{type:"gate-checked",source:"mcp-tool-call",tool:"paradigm_gates_for_route",symbols:C.map(P=>P.gate),context:`Gate check for ${f} ${g}`});}catch{}return {content:[{type:"text",text:j}]}}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:
841
879
  `],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(`
842
880
  Update command:
843
881
  ${b.join(` && \\