@a-company/paradigm 5.22.0 → 5.24.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/{ambient-WEPHBAJD.js → ambient-HYZR42NX.js} +1 -1
- package/dist/chunk-4DVT5IEY.js +2 -0
- package/dist/chunk-73R63P7K.js +2 -0
- package/dist/{chunk-QIGE36CB.js → chunk-FSOI3CCD.js} +79 -21
- package/dist/{compliance-TSXLXADI.js → compliance-NLG7KB73.js} +2 -2
- package/dist/{docs-RXPN6CK7.js → docs-UIYXJ3O3.js} +1 -1
- package/dist/{habits-LX5IWCZM.js → habits-GICVMTJL.js} +1 -1
- package/dist/{hooks-EFM2IK6E.js → hooks-E7HQQ57M.js} +1 -1
- package/dist/index.js +3 -3
- package/dist/mcp.js +64 -41
- package/dist/{migrate-OMR5G5AF.js → migrate-WT56YYAM.js} +1 -1
- package/dist/platform-server-FXYBBH6E.js +25 -0
- package/dist/{project-type-SURTOIG7.js → project-type-4Y6CESWP.js} +1 -1
- package/dist/{roster-FLRZ5J42.js → roster-K2QILE7K.js} +1 -1
- package/dist/{serve-JE6UF5P2.js → serve-5W6KOA4R.js} +1 -1
- package/dist/{shift-ASDLMMK5.js → shift-TDOYQKR4.js} +2 -2
- package/dist/university-FJ7OCOA3.js +2 -0
- package/package.json +1 -1
- package/platform-ui/dist/assets/AmbientSection-BYjt75R1.js +1 -0
- package/platform-ui/dist/assets/{CanvasSection-DLW0s-Bu.js → CanvasSection-rKvA_vZj.js} +2 -2
- package/platform-ui/dist/assets/{DocsSection-BQ9Hi51g.js → DocsSection-CI9K73M-.js} +1 -1
- package/platform-ui/dist/assets/GitSection-DSGj_c6S.js +4 -0
- package/platform-ui/dist/assets/{GraphSection-0c9C-w7K.js → GraphSection-CawN7pC5.js} +2 -2
- package/platform-ui/dist/assets/LoreSection-oO5dCe6O.js +1 -0
- package/platform-ui/dist/assets/{SentinelSection-C4OoME9U.js → SentinelSection-DNgoYMH0.js} +1 -1
- package/platform-ui/dist/assets/SymphonySection-C0zfcqv3.js +1 -0
- package/platform-ui/dist/assets/TeamSection-Bzd3Dt9Q.js +1 -0
- package/platform-ui/dist/assets/UniversitySection-B3ltVfpt.css +1 -0
- package/platform-ui/dist/assets/UniversitySection-tBr62R0S.js +1 -0
- package/platform-ui/dist/assets/{index-DPpOdAtC.js → index-BaOmyn11.js} +12 -12
- package/platform-ui/dist/index.html +1 -1
- package/dist/chunk-AGVAHVUA.js +0 -2
- package/dist/chunk-RMOALQJN.js +0 -2
- package/dist/platform-server-2KXHGHFV.js +0 -25
- package/platform-ui/dist/assets/AmbientSection-DqQ2mfCO.js +0 -1
- package/platform-ui/dist/assets/GitSection-QQeUX6o3.js +0 -4
- package/platform-ui/dist/assets/LoreSection--t56kCj2.js +0 -1
- package/platform-ui/dist/assets/SymphonySection-B-rvsLxq.js +0 -1
- package/platform-ui/dist/assets/TeamSection-CBFmNEEo.js +0 -1
package/dist/mcp.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a,b as b$2}from'./chunk-4UJ4NIEQ.js';import {e,v,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$2,u as u$1,j as j$3}from'./chunk-HXKWL3VK.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$3}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$3,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-6EX37L4Q.js';import {f,g as g$2,e as e$1,m,n,p,h as h$1,i,q,t as t$1,o,v as v$1,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 as aa$1,ga as ga$1,_,la as la$1,fa as fa$1,ja as ja$1,oa,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-V7K6CQVX.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 {t,f as f$2,n as n$2,b as b$7,d as d$7,e as e$5,s as s$2,j as j$5,g as g$6}from'./chunk-XUFYOXOU.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-4ZGGWZ32.js';import {h,b as b$9}from'./chunk-AD5TAD2A.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 ga from'os';import {execSync}from'child_process';var $t,Ns,Es=b(()=>{$t={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 $a={};c($a,{getAllStates:()=>qs,getConfig:()=>lt,getState:()=>Hn,incrementFailure:()=>Ia,invalidateGraduationCache:()=>Ep,isGraduated:()=>Fp,loadGraduation:()=>Ze,markNeverGraduate:()=>Np,saveGraduation:()=>En,setTier:()=>Oa});function Aa(n){return F.join(n,".paradigm","graduation.yaml")}function Ze(n){let e=F.resolve(n);if(Ft&&$n===e&&Date.now()-Fn<$p)return Ft;let s=Aa(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={}),Ft=t,$n=e,Fn=Date.now(),t}function En(n,e){let s=F.resolve(n),t=Aa(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"),Ft=e,$n=s,Fn=Date.now();}function lt(n){let e=Ze(n);return {...$t,...e.config,thresholds:{...$t.thresholds,...e.config?.thresholds},demotion:{...$t.demotion,...e.config?.demotion},neverGraduate:e.config?.neverGraduate??$t.neverGraduate}}function Hs(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?{...Hs(e),...t,habitId:e}:Hs(e)}function qs(n){let e=Ze(n),s={};for(let[t,i]of Object.entries(e.states))s[t]={...Hs(t),...i,habitId:t};return s}function Fp(n,e){return Hn(n,e).tier==="hook"}function Oa(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 Np(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 Ia(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 Ep(){Ft=null,$n=null,Fn=0;}var Ft,$n,Fn,$p,qn=b(()=>{Es();Ft=null,$n=null,Fn=0,$p=3e4;});var Yl=30*1e3,Ss=new Map,ks=".paradigm/wisdom";async function co(n){let e=F.resolve(n),s=Ss.get(e);if(s&&Date.now()-s.loadedAt<Yl)return s.context;let t=await Kl(e);return Ss.set(e,{context:t,loadedAt:Date.now()}),t}async function Kl(n){let e=F.join(n,ks),s=O.existsSync(e),[t,i,r,o]=s?await Promise.all([Ql(e),Xl(e),Zl(e),ed(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 Ql(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 Xl(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 Zl(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 ed(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 lo(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 po(n,e){let s=F.join(n,ks),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 uo(n,e){let s=F.join(n,ks,"decisions");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let t=`${e.id}-${td(e.title)}.yaml`,i=F.join(s,t);O.writeFileSync(i,Z.dump(e,{lineWidth:-1})),Be(n);}function td(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var go=".paradigm/history";async function mo(n){let e=F.join(n,go);if(!O.existsSync(e))return {index:null,validation:null};let[s,t]=await Promise.all([nd(e),sd(e)]);return {index:s,validation:t}}async function nd(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 sd(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 fo(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 yo(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 xs(n,e){let s=F.join(n,go),t=F.join(s,"log.jsonl");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let i=id(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,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$2,u as u$1,j as j$3}from'./chunk-HXKWL3VK.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$3}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$3,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-6EX37L4Q.js';import {f,g as g$2,e as e$1,m,n,p,h as h$1,i,q,t as t$1,o,v as v$1,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 as aa$1,ga as ga$1,_,la as la$1,fa as fa$1,ja as ja$1,oa,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-V7K6CQVX.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 {t,f as f$2,n as n$2,b as b$7,d as d$7,e as e$5,s as s$2,j as j$5,g as g$6}from'./chunk-XUFYOXOU.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-4ZGGWZ32.js';import {h,b as b$9}from'./chunk-AD5TAD2A.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 ga from'os';import {execSync}from'child_process';var $t,Ns,Es=b(()=>{$t={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 $a={};c($a,{getAllStates:()=>qs,getConfig:()=>lt,getState:()=>Hn,incrementFailure:()=>Ia,invalidateGraduationCache:()=>Hp,isGraduated:()=>Np,loadGraduation:()=>Ze,markNeverGraduate:()=>Ep,saveGraduation:()=>En,setTier:()=>Oa});function Aa(n){return F.join(n,".paradigm","graduation.yaml")}function Ze(n){let e=F.resolve(n);if(Ft&&$n===e&&Date.now()-Fn<Fp)return Ft;let s=Aa(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={}),Ft=t,$n=e,Fn=Date.now(),t}function En(n,e){let s=F.resolve(n),t=Aa(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"),Ft=e,$n=s,Fn=Date.now();}function lt(n){let e=Ze(n);return {...$t,...e.config,thresholds:{...$t.thresholds,...e.config?.thresholds},demotion:{...$t.demotion,...e.config?.demotion},neverGraduate:e.config?.neverGraduate??$t.neverGraduate}}function Hs(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?{...Hs(e),...t,habitId:e}:Hs(e)}function qs(n){let e=Ze(n),s={};for(let[t,i]of Object.entries(e.states))s[t]={...Hs(t),...i,habitId:t};return s}function Np(n,e){return Hn(n,e).tier==="hook"}function Oa(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 Ep(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 Ia(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 Hp(){Ft=null,$n=null,Fn=0;}var Ft,$n,Fn,Fp,qn=b(()=>{Es();Ft=null,$n=null,Fn=0,Fp=3e4;});var Yl=30*1e3,ks=new Map,Ss=".paradigm/wisdom";async function co(n){let e=F.resolve(n),s=ks.get(e);if(s&&Date.now()-s.loadedAt<Yl)return s.context;let t=await Kl(e);return ks.set(e,{context:t,loadedAt:Date.now()}),t}async function Kl(n){let e=F.join(n,Ss),s=O.existsSync(e),[t,i,r,o]=s?await Promise.all([Ql(e),Xl(e),Zl(e),ed(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);ks.delete(e);}async function Ql(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 Xl(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 Zl(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 ed(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 lo(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 po(n,e){let s=F.join(n,Ss),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 uo(n,e){let s=F.join(n,Ss,"decisions");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let t=`${e.id}-${td(e.title)}.yaml`,i=F.join(s,t);O.writeFileSync(i,Z.dump(e,{lineWidth:-1})),Be(n);}function td(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var go=".paradigm/history";async function mo(n){let e=F.join(n,go);if(!O.existsSync(e))return {index:null,validation:null};let[s,t]=await Promise.all([nd(e),sd(e)]);return {index:s,validation:t}}async function nd(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 sd(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 fo(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 yo(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 xs(n,e){let s=F.join(n,go),t=F.join(s,"log.jsonl");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let i=id(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 ho(n,e,s,t){return xs(n,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:s,tests:t})}function id(n){let e=1;return O.existsSync(n)&&(e=O.readFileSync(n,"utf8").split(`
|
|
4
|
-
`).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}function rd(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 wo(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=rd(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(bo(l)===bo(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=cd(p);c.exports&&c.exports.length>0&&(u=od(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 od(n$1,e){let t=n(n$1).filter(i=>{let r=i.symbol;return e.some(o=>ad(o,r))});return ld(t)}function ad(n,e){let s=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${s}$`,"i").test(e)}function Tt(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 vo(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 bo(n){return F.resolve(n).replace(/\/+$/,"")}function cd(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 ld(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 Ps(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=wo(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 co(n.rootDir)),n.wisdom}async function Se(n){return n.history||(n.history=await mo(n.rootDir)),n.history}function dd(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,{...dd(i),source:"portal.yaml"});return Array.from(t.values())}function ko(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 xo(){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 Co(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 Po(){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 Ro(n,e){if(n.startsWith("history/symbol/")&&!n.endsWith("/recent")){let s=decodeURIComponent(n.replace("history/symbol/","")),t=await Se(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 Se(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 Se(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 Se(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 Se(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 jo(){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 To(n,e){if(n==="context/agent-protocol")return {handled:true,text:`# Agent Protocol for Paradigm MCP Tools
|
|
4
|
+
`).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}function rd(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 wo(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=rd(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(bo(l)===bo(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=cd(p);c.exports&&c.exports.length>0&&(u=od(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 od(n$1,e){let t=n(n$1).filter(i=>{let r=i.symbol;return e.some(o=>ad(o,r))});return ld(t)}function ad(n,e){let s=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${s}$`,"i").test(e)}function Tt(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 vo(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 bo(n){return F.resolve(n).replace(/\/+$/,"")}function cd(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 ld(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 Ps(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=wo(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 co(n.rootDir)),n.wisdom}async function ke(n){return n.history||(n.history=await mo(n.rootDir)),n.history}function dd(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 ko(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,{...dd(i),source:"portal.yaml"});return Array.from(t.values())}function So(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 xo(){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 Co(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 Po(){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 Ro(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 jo(){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 To(n,e){if(n==="context/agent-protocol")return {handled:true,text:`# Agent Protocol for Paradigm MCP Tools
|
|
5
5
|
|
|
6
6
|
## Query Before Modify
|
|
7
7
|
|
|
@@ -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 pd={"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 ud(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 Do(n){return ud("prompts",n)}function gd(n){return Math.ceil(n.length/3.5)}function Ao(n){let e=Do(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:pd[i]||`Prompt template: ${i}`,filename:t,size:o.size,tokens:gd(a)}})}catch{return []}}function md(n,e){let s=Do(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=Ao(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 Oo(){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 Io(n,e){let s=`paradigm://${n}`;if(n==="prompts"){let t=Ao(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}=md(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 Rs={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 fd(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 $o(n){return fd("specs",n)}function yd(n){return Math.ceil(n.length/3.5)}function hd(n){let e=$o(n);if(!e)return [];let s=[];for(let[t,i]of Object.entries(Rs)){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:yd(c)});}}catch{}}return s}function bd(n,e){if(!Rs[n]){let i=Object.keys(Rs);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=$o(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 Fo(){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=hd(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}=bd(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={commands:"Complete CLI command reference with examples and usage guidance",queries:"jq query examples for querying the constellation symbol graph"};function wd(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 Eo(n){return wd("docs",n)}function vd(n){return Math.ceil(n.length/3.5)}function _d(n){let e=Eo(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:vd(c)});}}catch{}}return s}function Sd(n,e){if(!js[n]){let i=Object.keys(js);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=Eo(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 Ho(){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 qo(n,e){let s=`paradigm://${n}`;if(n==="docs"){let t=_d(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 pd={"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 ud(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 Do(n){return ud("prompts",n)}function gd(n){return Math.ceil(n.length/3.5)}function Ao(n){let e=Do(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:pd[i]||`Prompt template: ${i}`,filename:t,size:o.size,tokens:gd(a)}})}catch{return []}}function md(n,e){let s=Do(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=Ao(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 Oo(){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 Io(n,e){let s=`paradigm://${n}`;if(n==="prompts"){let t=Ao(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}=md(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 Rs={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 fd(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 $o(n){return fd("specs",n)}function yd(n){return Math.ceil(n.length/3.5)}function hd(n){let e=$o(n);if(!e)return [];let s=[];for(let[t,i]of Object.entries(Rs)){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:yd(c)});}}catch{}}return s}function bd(n,e){if(!Rs[n]){let i=Object.keys(Rs);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=$o(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 Fo(){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=hd(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}=bd(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={commands:"Complete CLI command reference with examples and usage guidance",queries:"jq query examples for querying the constellation symbol graph"};function wd(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 Eo(n){return wd("docs",n)}function vd(n){return Math.ceil(n.length/3.5)}function _d(n){let e=Eo(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:vd(c)});}}catch{}}return s}function kd(n,e){if(!js[n]){let i=Object.keys(js);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=Eo(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 Ho(){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 qo(n,e){let s=`paradigm://${n}`;if(n==="docs"){let t=_d(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}=kd(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 kd(n){return Math.ceil(n.length/3.5)}function Mo(){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 Lo(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:kd(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 Wo(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"},...xo(),...Po(),...jo(),...Oo(),...Fo(),...Ho(),...Mo()]})),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=ko(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 Co(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 Ro(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 To(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 Io(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 qo(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 Lo(r);if(o.handled)return {contents:[{uri:t,mimeType:o.mimeType,text:o.text}]}}throw new Error(`Unknown resource: ${r}`)});}j();function Go(){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 Uo(n,e,s){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:i=true}=e,r=await se(s),o=lo(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 po(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 uo(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 zo(){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 Bo(n,e,s){switch(n){case "paradigm_history_context":{let{symbols:t}=e,i=await Se(s),r=fo(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 xs(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 ho(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 Se(s),r=yo(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 Pd=".paradigm/navigator.yaml";async function Ko(n){let e=F.join(n,Pd);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 Qo(n,e,s){switch(e.intent){case "find":return Rd(n,e.target||"");case "explore":return jd(n,e.target||"");case "context":return Td(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Rd(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=Dd(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=Ts(t.paths,n),t}function jd(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=Ts(t.paths,n),t}function Td(n,e,s){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},i=e.toLowerCase(),r=Ad(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=Ts(t.paths,n),t}function Dd(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 Ad(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 Ts(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 Od={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 Xo(){return [Od]}async function Zo(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 Ko(s.rootDir);if(i.config||(i={config:Id(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$1.getOrCompute(r,()=>{let c=Qo(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=Tt(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=Tt(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 Id(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 Sn=null,Ds=false;function $d(n){if(Sn||(Sn=new f$4),!Ds)try{let e=r$2();for(let s of e)try{Sn.addPattern(s);}catch{}Ds=!0;}catch{Ds=true;}return Sn}function ea(){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 ta(n,e,s){let t=$d(),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 Fd=30*1e3,na=new Map;async function Cn(n){let e=F.resolve(n),s=na.get(e);if(s&&Date.now()-s.loadedAt<Fd)return s.index;let t=await Nd(e);return t&&na.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 Ed(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=Ed(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 sa(){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 ia(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 Sd(n){return Math.ceil(n.length/3.5)}function Mo(){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 Lo(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:Sd(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 Wo(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"},...xo(),...Po(),...jo(),...Oo(),...Fo(),...Ho(),...Mo()]})),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=ko(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=So(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 Co(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 Ro(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 To(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 Io(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 qo(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 Lo(r);if(o.handled)return {contents:[{uri:t,mimeType:o.mimeType,text:o.text}]}}throw new Error(`Unknown resource: ${r}`)});}j();function Go(){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 Uo(n,e,s){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:i=true}=e,r=await se(s),o=lo(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 po(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 uo(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 zo(){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 Bo(n,e,s){switch(n){case "paradigm_history_context":{let{symbols:t}=e,i=await ke(s),r=fo(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 xs(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 ho(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=yo(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 Pd=".paradigm/navigator.yaml";async function Ko(n){let e=F.join(n,Pd);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 Qo(n,e,s){switch(e.intent){case "find":return Rd(n,e.target||"");case "explore":return jd(n,e.target||"");case "context":return Td(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Rd(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=Dd(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=Ts(t.paths,n),t}function jd(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=Ts(t.paths,n),t}function Td(n,e,s){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},i=e.toLowerCase(),r=Ad(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=Ts(t.paths,n),t}function Dd(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 Ad(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 Ts(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 Od={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 Xo(){return [Od]}async function Zo(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 Ko(s.rootDir);if(i.config||(i={config:Id(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$1.getOrCompute(r,()=>{let c=Qo(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=Tt(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=Tt(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 Id(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,Ds=false;function $d(n){if(kn||(kn=new f$4),!Ds)try{let e=r$2();for(let s of e)try{kn.addPattern(s);}catch{}Ds=!0;}catch{Ds=true;}return kn}function ea(){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 ta(n,e,s){let t=$d(),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 Fd=30*1e3,na=new Map;async function Cn(n){let e=F.resolve(n),s=na.get(e);if(s&&Date.now()-s.loadedAt<Fd)return s.index;let t=await Nd(e);return t&&na.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 Ed(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=Ed(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 sa(){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 ia(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"
|
|
@@ -486,7 +486,7 @@ flows:
|
|
|
486
486
|
symbol: "!task-created"
|
|
487
487
|
description: Emit success event
|
|
488
488
|
successSignal: "!task-created"
|
|
489
|
-
`},null,2)};let a=F.join(s.rootDir,"portal.yaml"),c=[];if(O.existsSync(a))try{let f=O.readFileSync(a,"utf-8"),b=Z.load(f);b?.gates&&(c=Object.keys(b.gates).map(h=>h.startsWith("^")?h.slice(1):h));}catch{}let l=new Set(c),d=[],p=t?[[t,o.flows[t]]]:Object.entries(o.flows);for(let[f,b]of p){if(!b){if(t)return {handled:true,text:JSON.stringify({error:`Flow not found: ${t}`,availableFlows:Object.keys(o.flows)},null,2)};continue}let h={flowId:f,status:"valid",coverage:{gatesReferenced:[],gatesMissing:[],actionsReferenced:[],actionsMissing:[],signalsEmitted:[],signalsMissing:[]},suggestions:[]},w=b.steps||[];for(let _=0;_<w.length;_++){let
|
|
489
|
+
`},null,2)};let a=F.join(s.rootDir,"portal.yaml"),c=[];if(O.existsSync(a))try{let f=O.readFileSync(a,"utf-8"),b=Z.load(f);b?.gates&&(c=Object.keys(b.gates).map(h=>h.startsWith("^")?h.slice(1):h));}catch{}let l=new Set(c),d=[],p=t?[[t,o.flows[t]]]:Object.entries(o.flows);for(let[f,b]of p){if(!b){if(t)return {handled:true,text:JSON.stringify({error:`Flow not found: ${t}`,availableFlows:Object.keys(o.flows)},null,2)};continue}let h={flowId:f,status:"valid",coverage:{gatesReferenced:[],gatesMissing:[],actionsReferenced:[],actionsMissing:[],signalsEmitted:[],signalsMissing:[]},suggestions:[]},w=b.steps||[];for(let _=0;_<w.length;_++){let k=w[_],v=k.symbol||"",S=Hd(v);if(S)switch(k.type){case "gate":h.coverage.gatesReferenced.push(v),l.has(S.name)||(h.coverage.gatesMissing.push(v),h.status="invalid");break;case "action":h.coverage.actionsReferenced.push(v);break;case "signal":h.coverage.signalsEmitted.push(v);break}}b.successSignal&&h.coverage.signalsEmitted.push(b.successSignal),h.coverage.gatesMissing.length>0&&h.suggestions.push(`Add missing gates to portal.yaml: ${h.coverage.gatesMissing.join(", ")}`),h.status==="valid"&&h.coverage.gatesMissing.length===0&&(h.status="valid"),d.push(h);}let u=d.filter(f=>f.status==="valid").length,g=d.filter(f=>f.status==="invalid").length,m={status:g>0?"invalid":"valid",totalFlows:d.length,validFlows:u,invalidFlows:g,results:d.map(f=>({flowId:f.flowId,status:f.status,gatesReferenced:f.coverage.gatesReferenced,gatesMissing:f.coverage.gatesMissing,actionsReferenced:f.coverage.actionsReferenced,signalsEmitted:f.coverage.signalsEmitted,suggestions:f.suggestions}))};return {handled:true,text:JSON.stringify(m,null,2)}}default:return {handled:false,text:""}}}function Hd(n){let e=n.match(/^([#$^!~])(.+)$/);return e?{prefix:e[1],name:e[2]}:null}var qd=60*1e3,ra=new Map;async function aa(n){let e=F.resolve(n),s=ra.get(e);if(s&&Date.now()-s.loadedAt<qd)return s.fixtures;let t=await Md(e);return t&&ra.set(e,{fixtures:t,loadedAt:Date.now()}),t}async function Md(n){let e=F.join(n,".paradigm","fixtures.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[fixtures-loader] Error parsing fixtures.yaml:",s),null}}function Is(n,e){switch(e){case "users":return n.users||{};case "resources":return n.resources||{};case "payloads":return n.payloads||{};case "all":return {users:n.users||{},resources:n.resources||{},payloads:n.payloads||{}};default:return null}}function ca(n,e,s){return Is(n,e)?.[s]||null}function $s(n){return {users:Object.keys(n.users||{}),resources:Object.keys(n.resources||{}),payloads:Object.keys(n.payloads||{})}}function la(){return [{name:"paradigm_test_fixtures",description:"Get test fixtures for validating flows. Returns users (for auth testing), resources (for entity testing), and sample payloads (for API testing). ~150 tokens.",inputSchema:{type:"object",properties:{category:{type:"string",enum:["users","resources","payloads","all"],description:'Category of fixtures to retrieve. Use "all" to get everything.'},name:{type:"string",description:'Specific fixture name within the category (e.g., "admin", "createTask")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function da(n,e,s){switch(n){case "paradigm_test_fixtures":{let{category:t,name:i}=e,r=await aa(s.rootDir);if(!r)return {handled:true,text:JSON.stringify({error:"Fixtures not found",suggestion:"Create .paradigm/fixtures.yaml with test fixtures. Run `paradigm init` to generate a template.",example:`
|
|
490
490
|
version: "1.0"
|
|
491
491
|
|
|
492
492
|
users:
|
|
@@ -689,31 +689,54 @@ 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
|
|
692
|
+
- Skip .purpose coverage for new code directories`,advocate:`You are the ADVOCATE agent (Jinx).
|
|
693
|
+
|
|
694
|
+
## Your Role
|
|
695
|
+
You are the devil's advocate \u2014 you stress-test assumptions, find edge cases,
|
|
696
|
+
and challenge happy-path thinking before implementation begins. Your job is
|
|
697
|
+
to break plans before code breaks in production.
|
|
698
|
+
|
|
699
|
+
## Key Responsibilities
|
|
700
|
+
1. Identify hidden assumptions in the task description
|
|
701
|
+
2. Surface edge cases and failure modes the team hasn't considered
|
|
702
|
+
3. Challenge "obvious" decisions \u2014 what if the opposite is true?
|
|
703
|
+
4. Flag scale, dependency, and integration risks
|
|
704
|
+
5. Run a mental pre-mortem: imagine the feature failed \u2014 what went wrong?
|
|
705
|
+
|
|
706
|
+
## What You Produce
|
|
707
|
+
- A concise list of risks, assumptions, and edge cases
|
|
708
|
+
- A verdict: GREENLIGHT (proceed) or ESCALATE (needs full orchestration)
|
|
709
|
+
- Specific questions the team should answer before building
|
|
710
|
+
|
|
711
|
+
## What You DON'T Do
|
|
712
|
+
- Write implementation code
|
|
713
|
+
- Block progress without justification \u2014 you challenge, not obstruct
|
|
714
|
+
- Repeat concerns already addressed in the task description
|
|
715
|
+
- Produce lengthy analysis \u2014 be sharp and concise`};function fa(){return [{name:"paradigm_orchestrate_inline",description:`REQUIRED before implementing features. Start with mode="quick" for fast pre-check, or mode="plan" for full orchestration planning.
|
|
693
716
|
|
|
694
717
|
Plans and coordinates multi-agent task execution within the same session.
|
|
718
|
+
- mode: "quick" - Lightweight pre-implementation check (~3-4k tokens). Jinx (advocate) stress-tests assumptions, reviewer checks feasibility. Returns greenlight or escalates to full orchestration. Satisfies enforcement.
|
|
695
719
|
- mode: "plan" - See suggested agents, estimated tokens, and get orchestration plan
|
|
696
720
|
- mode: "execute" - Get full prompts and execution strategy for any IDE
|
|
697
721
|
|
|
698
722
|
After getting prompts, launch agents using the Task tool. Stages marked canRunParallel: true can be launched simultaneously in a single message.
|
|
699
723
|
|
|
700
724
|
When to use this tool:
|
|
701
|
-
-
|
|
702
|
-
- Task involves security
|
|
703
|
-
-
|
|
704
|
-
- Building a new feature end-to-end
|
|
725
|
+
- mode="quick": Before any implementation \u2014 fast sanity check that satisfies orchestration-required enforcement
|
|
726
|
+
- mode="plan": Task affects 3+ files, involves security, or mentions multiple symbols
|
|
727
|
+
- mode="execute": Ready to implement, need full agent prompts
|
|
705
728
|
|
|
706
729
|
Examples:
|
|
707
|
-
- "
|
|
708
|
-
- "
|
|
709
|
-
- "
|
|
710
|
-
- "Refactor the payment module" \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:["plan","execute"],description:'Mode: "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:["architect","builder","tester","reviewer","security"],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 ya(n,e,s){return n==="paradigm_orchestrate_inline"?Jd(e,s):n==="paradigm_agent_prompt"?
|
|
730
|
+
- "Fix the login bug" \u2192 quick (greenlight or escalate)
|
|
731
|
+
- "Add user authentication with JWT" \u2192 plan \u2192 architect + security + builder + tester
|
|
732
|
+
- "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 ya(n,e,s){return n==="paradigm_orchestrate_inline"?Jd(e,s):n==="paradigm_agent_prompt"?Ud(e,s):{handled:false,text:""}}async function Jd(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=wa(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=It(s),c=[];try{let{processPendingEvents:b,loadNominations:h}=await import('./nomination-engine-XF7TWPAP.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=ep(s);if(t==="quick")return Gd(s,a,l,c,r,e);let d=Bd(s,r.agents,i,l,r.orchestration);if(t==="plan"){let b=np(s,r.agents),h=tp(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=ha(_,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-EPXURMO7.js'),{loadDecisions:w}=await import('./decision-loader-2XPZE4EZ.js'),{loadJournalEntries:_}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:k}=await import('./nomination-engine-XF7TWPAP.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,yi)=>yi.confidence-et.confidence||new Date(yi.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=[`
|
|
711
734
|
## 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+=`
|
|
712
735
|
`+q.join(`
|
|
713
|
-
`);}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],S={name:_?.name||w.name,role:_?.role||At[w.name]||`${w.name} agent`,focus:_?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:ma(w.name,e.rootDir,_),triggers:_?.triggers,handoff_to:_?.handoff_to,context:_?.context,protocol:_?.protocol},v=p.get(w.name),k=ba({agent:S,task:w.task,symbols:a,dependsOn:w.dependsOn,profileEnrichment:v?.enrichment,nickname:v?.nickname});h.push(k);}u.push({stage:b.stage,canRunParallel:b.canRunParallel,agents:h});}let g=`orch-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`;np(e.rootDir,g,s,d);try{let{appendSessionWorkEntry:b}=await import('./session-work-log-J2H5OZBR.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-SKOMBDOW.js')).default?.session?.sessionId||g;for(let _ of u)for(let S of _.agents)b(S.agent,e.rootDir,{sessionId:w,summary:`${S.attribution||S.agent}: ${(S.taskDescription||s).slice(0,200)}`,symbolsTouched:a});}catch{}let m=`thr-orch-${g}`;try{let b=await import('./symphony-loader-XACVV2E3.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(ga.homedir(),".paradigm","score","threads"),S=O.readdirSync(_).filter(k=>k.endsWith(".json")).sort(),v=S[S.length-1];if(v){let k=F.join(_,v),x=F.join(_,`${m}.json`),C=JSON.parse(O.readFileSync(k,"utf8"));C.id=m,O.writeFileSync(x,JSON.stringify(C,null,2),"utf8"),k!==x&&O.unlinkSync(k);}for(let k of u)for(let x of k.agents){let C=b.buildMessage({threadRoot:m,sender:{id:w,name:"Maestro",type:"agent",project:h,role:"orchestrator"},intent:"task",text:`[Maestro] Stage ${k.stage}: Assigned to ${x.attribution||x.agent} \u2014 ${x.taskDescription||s}`,symbols:a,metadata:{task:{stage:k.stage,canRunParallel:k.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"],symphony:{orchestrationThread:m,instruction:"After each agent completes, call paradigm_symphony_send to report progress. This makes the work visible in Conductor.",perAgentInstruction:`When each agent finishes, run: paradigm_symphony_send threadId="${m}" intent="task-complete" text="[agentName] Summary of completed work" symbols=[touched symbols]`},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:`thr-${g}`,instructions:["After each agent completes, call paradigm_symphony_send to record the contribution",'Use intent "context" for analysis, "proposal" for recommendations, "decision" for decisions made',`Set threadRoot to "thr-${g}" so all contributions are in one thread`,"Include the symbols array from the agent relay output","This creates a visible team thread that Conductor and other sessions can observe"],exampleCall:{intent:"context",text:"[architect] Rate limiter should be placed before ^authenticated gate to prevent unauthenticated flood",threadRoot:`thr-${g}`,symbols:["#rate-limiter","^authenticated"]}}},f=JSON.stringify(y,null,2);return o(f.length,"paradigm_orchestrate_inline"),{handled:true,text:f}}async function Gd(n,e){let s=n.agent,t=n.task,i=n.handoffContext,r=n.previousAgent,o$1=wa(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||At[s]||At.builder,focus:c?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:ma(s,e.rootDir,c),triggers:c?.triggers,handoff_to:c?.handoff_to,context:c?.context,protocol:c?.protocol},d=It(t),p,u;try{let{loadAgentProfile:f,buildProfileEnrichment:b}=await import('./agent-loader-EPXURMO7.js'),{loadDecisions:h}=await import('./decision-loader-2XPZE4EZ.js'),{loadJournalEntries:w}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:_}=await import('./nomination-engine-XF7TWPAP.js'),{loadNotebookEntries:S}=await import('./notebook-loader-CENTDDUJ.js'),v=f(e.rootDir,s);if(v){u=v.nickname;let k=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=S(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:k,journalInsights:x,pendingNominations:C});if(v.permissions){let P=[`
|
|
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||At[w.name]||`${w.name} agent`,focus:_?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:ma(w.name,e.rootDir,_),triggers:_?.triggers,handoff_to:_?.handoff_to,context:_?.context,protocol:_?.protocol},v=p.get(w.name),S=ba({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)}`;sp(e.rootDir,g,s,d);try{let{appendSessionWorkEntry:b}=await import('./session-work-log-J2H5OZBR.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-SKOMBDOW.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-XACVV2E3.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(ga.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 Gd(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 Ud(n,e){let s=n.agent,t=n.task,i=n.handoffContext,r=n.previousAgent,o$1=wa(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||At[s]||At.builder,focus:c?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:ma(s,e.rootDir,c),triggers:c?.triggers,handoff_to:c?.handoff_to,context:c?.context,protocol:c?.protocol},d=It(t),p,u;try{let{loadAgentProfile:f,buildProfileEnrichment:b}=await import('./agent-loader-EPXURMO7.js'),{loadDecisions:h}=await import('./decision-loader-2XPZE4EZ.js'),{loadJournalEntries:w}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:_}=await import('./nomination-engine-XF7TWPAP.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=[`
|
|
714
737
|
## 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+=`
|
|
715
738
|
`+P.join(`
|
|
716
|
-
`);}j.trim()&&(p=j);}}catch{}let g=ba({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 ha(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
|
|
739
|
+
`);}j.trim()&&(p=j);}}catch{}let g=ba({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 ha(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 zd(n,e){let s=ha(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 Bd(n,e,s,t,i){let r=It(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=zd(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=Wd[_.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 ba(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=At[e.name]||e.role||At.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=Vd(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
|
|
717
740
|
|
|
718
741
|
When you complete your task, end with a structured summary block:
|
|
719
742
|
|
|
@@ -732,18 +755,18 @@ handoff_context: |
|
|
|
732
755
|
\`\`\`
|
|
733
756
|
|
|
734
757
|
This structured output helps track progress and pass context between agents.`);let c=o.join(`
|
|
735
|
-
`),l=e.defaultModel||Tn[Dt[e.name]||"tier-2"]||"sonnet",d=n.nickname?`[${n.nickname} (${e.name})]`:`[${e.name}]`;return {agent:e.name,model:l,prompt:c,taskDescription:`${e.name}: ${s.slice(0,50)}${s.length>50?"...":""}`,subagentType:"general-purpose",attribution:d,focusAreas:e.focus||{reads:["**/*"],writes:["**/*"]}}}function It(n){let e=n.match(Ld)||[];return [...new Set(e)]}function
|
|
758
|
+
`),l=e.defaultModel||Tn[Dt[e.name]||"tier-2"]||"sonnet",d=n.nickname?`[${n.nickname} (${e.name})]`:`[${e.name}]`;return {agent:e.name,model:l,prompt:c,taskDescription:`${e.name}: ${s.slice(0,50)}${s.length>50?"...":""}`,subagentType:"general-purpose",attribution:d,focusAreas:e.focus||{reads:["**/*"],writes:["**/*"]}}}function It(n){let e=n.match(Ld)||[];return [...new Set(e)]}function Vd(n){let e=n.charAt(0);return {"@":"feature","#":"component",$:"flow","%":"state","^":"gate","!":"signal","?":"idea","&":"integration","~":"deprecated"}[e]||"unknown"}var Yd=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","pros and cons"],Kd=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs"],Qd=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","regression","patch"],Xd=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify"],Zd=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","ownership","transfer","privilege","escalation","impersonation","takeover","rbac","acl","role","guard","middleware","session","cookie","csrf","xss","injection","sanitize"];function ep(n){let e=n.toLowerCase(),s=It(n),t=f=>f.filter(b=>e.includes(b.toLowerCase())),i=t(Yd),r=t(Kd),o=t(Qd),a=t(Xd),c=t(Zd),l,d;i.length>0&&o.length===0&&a.length===0?(l="analysis",d=i):r.length>0&&o.length===0?(l="documentation",d=r):o.length>0?(l="bugfix",d=o):a.length>0?(l="refactor",d=a):(l="feature",d=[]);let p="medium",u=n.split(/\s+/).length;s.length>=5||u>=100?p="high":s.length<=1&&u<30&&(p="low");let g=c.length>0||s.some(f=>f.startsWith("^")),m={analysis:["architect"],documentation:["architect"],bugfix:["security","builder"],refactor:["architect","builder"],feature:["architect","security","builder","tester"]},y={analysis:{min:.3,max:.5},documentation:{min:.25,max:.45},bugfix:{min:.5,max:.8},refactor:{min:.6,max:.85},feature:{min:.8,max:1.2}};return {type:l,complexity:p,recommendedAgents:m[l]||["architect","builder"],securityRequired:g,costMultiplier:y[l]||{min:.8,max:1},matchedKeywords:d,symbols:s}}var pa={opus:{input:15,output:75},sonnet:{input:3,output:15},haiku:{input:.25,output:1.25}},ua={architect:{input:8e3,output:4e3},security:{input:6e3,output:3e3},reviewer:{input:5e3,output:2e3},builder:{input:15e3,output:1e4},tester:{input:8e3,output:5e3}};function tp(n,e){let s=[],t=0,i=e.complexity==="high"?1.5:e.complexity==="low"?.6:1;for(let a of n.stages)for(let c of a.agents){let l=ua[c.name]||{input:5e3,output:3e3},d=Tn[Dt[c.name]||"tier-2"]||"sonnet",p=pa[d],u=Math.round(l.input*i),g=Math.round(l.output*i),m=u+g,y=u/1e6*p.input+g/1e6*p.output;s.push({name:c.name,model:d,estimatedTokens:m,estimatedCost:Math.round(y*1e4)/1e4}),t+=y;}let r=0;for(let[a,c]of Object.entries(ua)){let l=Tn[Dt[a]||"tier-2"]||"sonnet",d=pa[l];r+=c.input/1e6*d.input+c.output/1e6*d.output;}let o=r>0?t/r:1;return {agents:s,totalEstimatedCost:Math.round(t*1e4)/1e4,comparisonToBaseline:`${o.toFixed(2)}x`}}function np(n,e){let s=[],t=n.toLowerCase(),i=It(n);for(let[c,l]of Object.entries(e)){let d=[];for(let p of l.triggers||[]){if(p.type==="keyword"&&p.match)for(let u of p.match)t.includes(u.toLowerCase())&&d.push(`keyword:${u}`);if(p.type==="symbol"&&p.match)for(let u of p.match){let g=i.filter(m=>u.endsWith("*")?m.startsWith(u.slice(0,-1)):m===u);for(let m of g)d.push(`symbol:${m}`);}}if(d.length>0){let p=d.filter(b=>b.startsWith("keyword:")).length,u=d.filter(b=>b.startsWith("symbol:")).length,g=p>0&&u>0,m=d.length>=3||g?"high":d.length>=2?"medium":"low",y=l.role.split(`
|
|
736
759
|
`)[0].trim(),f=y.length>50?y.slice(0,47)+"...":y;s.push({name:c,reason:f,confidence:m,triggers_matched:d});}}let r=new Set(s.map(c=>c.name)),o=[];for(let c of s){let l=e[c.name];if(l?.handoff_to)for(let d of l.handoff_to){if(r.has(d)||!e[d])continue;let p=e[d],u=[];for(let g of p.triggers||[]){if(g.type==="keyword"&&g.match)for(let m of g.match)t.includes(m.toLowerCase())&&u.push(`keyword:${m}`);if(g.type==="symbol"&&g.match)for(let m of g.match){let y=i.filter(f=>m.endsWith("*")?f.startsWith(m.slice(0,-1)):f===m);for(let f of y)u.push(`symbol:${f}`);}}if(u.length>0){r.add(d);let g=p.role.split(`
|
|
737
|
-
`)[0].trim(),m=g.length>50?g.slice(0,47)+"...":g;o.push({name:d,reason:m,confidence:u.length>=2?"high":"medium",triggers_matched:[...u,`collaboration:handoff_from:${c.name}`]});}}}s.push(...o);let a={high:3,medium:2,low:1};return s.sort((c,l)=>a[l.confidence]-a[c.confidence])}function wa(n){let e=F.join(n,".paradigm","agents.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf-8");return Z.load(s)}catch{return null}}function
|
|
760
|
+
`)[0].trim(),m=g.length>50?g.slice(0,47)+"...":g;o.push({name:d,reason:m,confidence:u.length>=2?"high":"medium",triggers_matched:[...u,`collaboration:handoff_from:${c.name}`]});}}}s.push(...o);let a={high:3,medium:2,low:1};return s.sort((c,l)=>a[l.confidence]-a[c.confidence])}function wa(n){let e=F.join(n,".paradigm","agents.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf-8");return Z.load(s)}catch{return null}}function sp(n,e,s,t){let i=F.join(n,".paradigm","orchestrations");O.existsSync(i)||O.mkdirSync(i,{recursive:true});let r=F.join(i,`${e}.yaml`),o={id:e,task:s,created:new Date().toISOString(),status:"pending",mode:t.mode,symbols:t.symbols,estimatedAgents:t.estimatedAgents,estimatedTokens:t.estimatedTokens,stages:t.stages};try{O.writeFileSync(r,Z.dump(o));}catch{}}function va(n){let e=F.join(n,".paradigm","tags.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf-8");return Z.load(s)}catch{return null}}function ip(n,e){let s=F.join(n,".paradigm","tags.yaml"),t=Z.dump(e,{lineWidth:-1});O.writeFileSync(s,t,"utf-8");}function _a(){return [{name:"paradigm_tags",description:"List, search, and manage tags in the Tag Bank. Use to find available tags for classification. Returns tags organized by section (core, project, suggested) with usage counts. ~150 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","search","get"],description:"Action: list all tags, search by query, or get specific tag details"},query:{type:"string",description:"For search action: query string to match tag names and descriptions"},tag:{type:"string",description:"For get action: specific tag name to get details for"},category:{type:"string",enum:["core","project","suggested","all"],description:"Filter by tag category (default: all)"}},required:["action"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_tags_suggest",description:"AI proposes a new tag for human review. Tag will be added to the suggested section for approval. Returns confirmation of suggestion with section placement. ~100 tokens.",inputSchema:{type:"object",properties:{tag:{type:"string",description:'Tag name (kebab-case, e.g., "webhook-handler")'},description:{type:"string",description:"What this tag means and when to apply it"},reason:{type:"string",description:'Why this tag would be useful (e.g., "Found 5 components handling webhooks")'},appliesTo:{type:"array",items:{type:"string"},description:'Symbol types this tag applies to (e.g., ["#", "$"])'},exampleSymbols:{type:"array",items:{type:"string"},description:"Example symbols that would use this tag"}},required:["tag","description","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_aspect_check",description:"Verify an aspect has valid anchors and check coverage. Aspects (~) REQUIRE code anchors. Returns anchor validity, coverage stats, and missing anchor warnings. ~150 tokens.",inputSchema:{type:"object",properties:{aspect:{type:"string",description:'Aspect symbol to check (e.g., "~audit-required")'}},required:["aspect"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ka(n$1,e,s){switch(n$1){case "paradigm_tags":{let{action:t,query:i,tag:r,category:o="all"}=e,a=va(s.rootDir);if(!a)return {handled:true,text:JSON.stringify({error:"Tag bank not found",suggestion:"Create .paradigm/tags.yaml or run `paradigm init` to set up tags"})};if(t==="list"){let c={};return (o==="all"||o==="core")&&(c.core=Object.entries(a.core).map(([l,d])=>({tag:l,description:d.description?.split(`
|
|
738
761
|
`)[0].trim(),color:d.color,appliesTo:d["applies-to"]}))),(o==="all"||o==="project")&&(c.project=Object.entries(a.project||{}).map(([l,d])=>({tag:l,description:d.description?.split(`
|
|
739
762
|
`)[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(`
|
|
740
763
|
`)[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(`
|
|
741
|
-
`)[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=va(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),
|
|
742
|
-
`);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 ip=["#","$","^","!","~"];function J(n){return n.length>1&&ip.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 at(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 rp={"#":"#","^":"^","!":"!",$:"$","~":"~"};async function ka(n,e,s,t){let i=rp[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=op(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 op(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 Ca(n,e){let s=Z.dump(e,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});O.writeFileSync(n,s,"utf8");}function Pa(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,Ca(t,s),t}function Ra(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,Ca(t,s),t}var ap={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}},cp={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}},lp={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}},dp={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}},pp={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}},up={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}},gp={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}},mp={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}},fp={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}},yp={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}},hp={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}},bp={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}},wp={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 Ta(){return [ap,cp,lp,dp,pp,up,gp,mp,fp,yp,hp,bp,wp]}async function Da(n,e,s,t){switch(n){case "paradigm_purpose_init":return vp(e,s,t);case "paradigm_purpose_add_component":return _p(e,s,t);case "paradigm_purpose_add_aspect":return Sp(e,s,t);case "paradigm_purpose_add_signal":return kp(e,s,t);case "paradigm_purpose_add_flow":return xp(e,s,t);case "paradigm_purpose_add_gate":return Cp(e,s,t);case "paradigm_purpose_add_state":return Pp(e,s,t);case "paradigm_purpose_link":return Rp(e,s,t);case "paradigm_purpose_remove":return jp(e,s,t);case "paradigm_purpose_rename":return Tp(e,s,t);case "paradigm_portal_add_gate":return Dp(e,s,t);case "paradigm_portal_add_route":return Ap(e,s,t);case "paradigm_purpose_validate":return Ip(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 vp(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 _p(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),S=o,v=Ke(w[S]),k=v[_]||{description:""};return k.description=r,a!==void 0&&(k.file=a),c!==void 0&&(k.status=c),l!==void 0&&(k.endpoints=l),d!==void 0&&(k.tests=d),p!==void 0&&(k.flows=p.map(x=>M(x,"$"))),u!==void 0&&(k.gates=u.map(x=>M(x,"^"))),g!==void 0&&(k.signals=g.map(x=>M(x,"!"))),m!==void 0&&(k.aspects=m.map(x=>M(x,"~"))),y!==void 0&&(k.components=y.map(x=>M(x,"#"))),f!==void 0&&(k.type=f),b!==void 0&&(k.parent=M(b,"#")),v[_]=k,w[S]=v,pe(h,w),await s(),X({action:"add_component",file:h,section:S,id:_,symbol:`#${_}`})}async function Sp(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 kp(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 xp(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 Cp(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 Pp(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 Rp(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=at(f.signals,o.map(h=>M(h,"!")))),c&&(f.gates=at(f.gates,c.map(h=>M(h,"^")))),l&&(f.flows=at(f.flows,l.map(h=>M(h,"$")))),d&&(f.components=at(f.components,d.map(h=>M(h,"#")))),a&&(f.aspects=at(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 jp(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 Tp(n,e,s){let{oldId:t,newId:i,symbolType:r}=n,o=await ka(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 Dp(n,e,s){let{id:t,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:p}=n,u=Pa(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 Ap(n,e,s){let{route:t,method:i,gates:r}=n,o=Ra(e.rootDir,{route:t,method:i,gates:r});return await s(),X({action:"portal_add_route",file:o,route:`${i} ${t}`,gates:r})}var Op=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi;function ja(n,e){let s=[];function t(r,o){if(typeof r=="string"){let a=r.match(Op);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 Ip(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=ja(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=ja(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 Wa=[{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}],Hp=30*1e3,Ms=new Map;function ie(n){let e=F.resolve(n),s=Ms.get(e);if(s&&Date.now()-s.loadedAt<Hp)return s.habits;let t=qp(e);return Ms.set(e,{habits:t,loadedAt:Date.now()}),t}function qp(n){let e=new Map;for(let a of Wa)e.set(a.id,{...a});let s=process.env.HOME||process.env.USERPROFILE||"~",t=Fa(F.join(s,".paradigm","habits.yaml"));t&&Na(e,t);let i=Ea(F.join(s,".paradigm","habits"));for(let a of i)e.set(a.id,a);let r=Fa(F.join(n,".paradigm","habits.yaml"));r&&Na(e,r);let o=Ea(F.join(n,".paradigm","habits"));for(let a of o)e.set(a.id,a);return Array.from(e.values())}function Fa(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 Mp(n,e){return n.filter(s=>s.enabled&&s.trigger===e)}function Ls(n){Ms.delete(F.resolve(n));}function Ea(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 Ha=["discovery","verification","testing","documentation","collaboration","security"],qa=["preflight","postflight","on-commit","on-stop"],Ma=["advisory","warn","block"],La=["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"],Lp=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Ws(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&&!Lp.test(n.id)&&e.push(`Invalid id format: "${n.id}" \u2014 must be kebab-case (lowercase, hyphens only)`),n.category&&!Ha.includes(n.category)&&e.push(`Invalid category: "${n.category}" \u2014 must be one of: ${Ha.join(", ")}`),n.trigger&&!qa.includes(n.trigger)&&e.push(`Invalid trigger: "${n.trigger}" \u2014 must be one of: ${qa.join(", ")}`),n.severity&&!Ma.includes(n.severity)&&e.push(`Invalid severity: "${n.severity}" \u2014 must be one of: ${Ma.join(", ")}`),n.check){La.includes(n.check.type)||e.push(`Invalid check.type: "${n.check.type}" \u2014 must be one of: ${La.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 Wp=new Set(Wa.map(n=>n.id));function Mn(n){return Wp.has(n)}function Js(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"),Ls(n),i}function Ja(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),Ls(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),Ls(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 Gs=0;function Et(n,e,s,t,i){let r=Mp(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($a)),g=r.length;r=r.filter(m=>!u(i,m.id)),o=g-r.length;}catch{}Gs=o;let a=r.map(u=>Jp(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 Ht(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 Jp(n,e){switch(n.check.type){case "tool-called":return Gp(n,e);case "file-exists":return Up(n,e);case "file-modified":return Kp(n,e);case "lore-recorded":return zp(n,e);case "symbols-registered":return Bp(n,e);case "gates-declared":return Vp(n,e);case "tests-exist":return Yp(n,e);case "git-clean":return Qp(n,e);default:return {habit:n,result:"partial",reason:`Unknown check: ${n.check.type}`}}}function Gp(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 Up(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 zp(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 Bp(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 Vp(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 Yp(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 Kp(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 Qp(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"}}var qt=null,Us=false;async function zs(n){if(qt)Us||(await qt.ensureReady(),Us=true);else {let e=F.join(n,".paradigm","sentinel","sentinel.db");qt=new f$4(e),await qt.ensureReady(),Us=true;}return qt}async function Xp(n,e){return (await zs(n)).recordPracticeEvent(e)}async function Ua(n,e){return (await zs(n)).getPracticeEvents(e)}async function ue(n,e){return (await zs(n)).getComplianceRate(e)}async function Mt(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 za(n,e,s){let t=[];for(let i of e){let r=await Xp(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 eu=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,tu=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"],nu=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi];function Ba(){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.
|
|
764
|
+
`)[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=va(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),ip(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 rp=["#","$","^","!","~"];function J(n){return n.length>1&&rp.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 at(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 op={"#":"#","^":"^","!":"!",$:"$","~":"~"};async function Sa(n,e,s,t){let i=op[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=ap(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 ap(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 Ca(n,e){let s=Z.dump(e,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});O.writeFileSync(n,s,"utf8");}function Pa(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,Ca(t,s),t}function Ra(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,Ca(t,s),t}var cp={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}},lp={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}},dp={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}},pp={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}},up={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}},gp={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}},mp={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}},fp={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}},yp={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}},hp={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}},bp={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}},wp={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}},vp={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 Ta(){return [cp,lp,dp,pp,up,gp,mp,fp,yp,hp,bp,wp,vp]}async function Da(n,e,s,t){switch(n){case "paradigm_purpose_init":return _p(e,s,t);case "paradigm_purpose_add_component":return kp(e,s,t);case "paradigm_purpose_add_aspect":return Sp(e,s,t);case "paradigm_purpose_add_signal":return xp(e,s,t);case "paradigm_purpose_add_flow":return Cp(e,s,t);case "paradigm_purpose_add_gate":return Pp(e,s,t);case "paradigm_purpose_add_state":return Rp(e,s,t);case "paradigm_purpose_link":return jp(e,s,t);case "paradigm_purpose_remove":return Tp(e,s,t);case "paradigm_purpose_rename":return Dp(e,s,t);case "paradigm_portal_add_gate":return Ap(e,s,t);case "paradigm_portal_add_route":return Op(e,s,t);case "paradigm_purpose_validate":return $p(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 _p(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 kp(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 Sp(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 xp(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 Cp(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 Pp(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 Rp(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 jp(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=at(f.signals,o.map(h=>M(h,"!")))),c&&(f.gates=at(f.gates,c.map(h=>M(h,"^")))),l&&(f.flows=at(f.flows,l.map(h=>M(h,"$")))),d&&(f.components=at(f.components,d.map(h=>M(h,"#")))),a&&(f.aspects=at(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 Tp(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 Dp(n,e,s){let{oldId:t,newId:i,symbolType:r}=n,o=await Sa(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 Ap(n,e,s){let{id:t,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:p}=n,u=Pa(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 Op(n,e,s){let{route:t,method:i,gates:r}=n,o=Ra(e.rootDir,{route:t,method:i,gates:r});return await s(),X({action:"portal_add_route",file:o,route:`${i} ${t}`,gates:r})}var Ip=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi;function ja(n,e){let s=[];function t(r,o){if(typeof r=="string"){let a=r.match(Ip);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 $p(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=ja(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=ja(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 Wa=[{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}],qp=30*1e3,Ms=new Map;function ie(n){let e=F.resolve(n),s=Ms.get(e);if(s&&Date.now()-s.loadedAt<qp)return s.habits;let t=Mp(e);return Ms.set(e,{habits:t,loadedAt:Date.now()}),t}function Mp(n){let e=new Map;for(let a of Wa)e.set(a.id,{...a});let s=process.env.HOME||process.env.USERPROFILE||"~",t=Fa(F.join(s,".paradigm","habits.yaml"));t&&Na(e,t);let i=Ea(F.join(s,".paradigm","habits"));for(let a of i)e.set(a.id,a);let r=Fa(F.join(n,".paradigm","habits.yaml"));r&&Na(e,r);let o=Ea(F.join(n,".paradigm","habits"));for(let a of o)e.set(a.id,a);return Array.from(e.values())}function Fa(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 Lp(n,e){return n.filter(s=>s.enabled&&s.trigger===e)}function Ls(n){Ms.delete(F.resolve(n));}function Ea(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 Ha=["discovery","verification","testing","documentation","collaboration","security"],qa=["preflight","postflight","on-commit","on-stop"],Ma=["advisory","warn","block"],La=["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"],Wp=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Ws(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&&!Wp.test(n.id)&&e.push(`Invalid id format: "${n.id}" \u2014 must be kebab-case (lowercase, hyphens only)`),n.category&&!Ha.includes(n.category)&&e.push(`Invalid category: "${n.category}" \u2014 must be one of: ${Ha.join(", ")}`),n.trigger&&!qa.includes(n.trigger)&&e.push(`Invalid trigger: "${n.trigger}" \u2014 must be one of: ${qa.join(", ")}`),n.severity&&!Ma.includes(n.severity)&&e.push(`Invalid severity: "${n.severity}" \u2014 must be one of: ${Ma.join(", ")}`),n.check){La.includes(n.check.type)||e.push(`Invalid check.type: "${n.check.type}" \u2014 must be one of: ${La.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 Jp=new Set(Wa.map(n=>n.id));function Mn(n){return Jp.has(n)}function Js(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"),Ls(n),i}function Ja(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),Ls(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),Ls(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 Gs=0;function Et(n,e,s,t,i){let r=Lp(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($a)),g=r.length;r=r.filter(m=>!u(i,m.id)),o=g-r.length;}catch{}Gs=o;let a=r.map(u=>Gp(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 Ht(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 Gp(n,e){switch(n.check.type){case "tool-called":return Up(n,e);case "file-exists":return zp(n,e);case "file-modified":return Qp(n,e);case "lore-recorded":return Bp(n,e);case "symbols-registered":return Vp(n,e);case "gates-declared":return Yp(n,e);case "tests-exist":return Kp(n,e);case "git-clean":return Xp(n,e);case "commit-message-format":return Zp(n,e);case "flow-coverage":return eu(n,e);case "context-checked":return tu(n,e);case "aspect-anchored":return nu(n,e);default:return {habit:n,result:"partial",reason:`Unknown check: ${n.check.type}`}}}function Up(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 zp(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 Bp(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 Vp(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 Yp(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 Kp(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 Qp(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 Xp(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 Zp(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 eu(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 tu(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 nu(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 qt=null,Us=false;async function zs(n){if(qt)Us||(await qt.ensureReady(),Us=true);else {let e=F.join(n,".paradigm","sentinel","sentinel.db");qt=new f$4(e),await qt.ensureReady(),Us=true;}return qt}async function su(n,e){return (await zs(n)).recordPracticeEvent(e)}async function Ua(n,e){return (await zs(n)).getPracticeEvents(e)}async function ue(n,e){return (await zs(n)).getComplianceRate(e)}async function Mt(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 za(n,e,s){let t=[];for(let i of e){let r=await su(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 ru=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,ou=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"],au=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi];function Ba(){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.
|
|
743
766
|
|
|
744
|
-
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 Va(n,e,s){switch(n){case "paradigm_pm_preflight":{let{task:t}=e,i=await
|
|
745
|
-
`),"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 Ya(){let n=process.env.PARADIGM_AUTHOR;if(n)return Bs(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Bs(e)}catch{}try{let e=ga.userInfo().username;if(e)return Bs(e)}catch{}return "unknown"}function Bs(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function Xa(){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 Za(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(Ka)},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:S,linked_tasks:v,linked_commits:k,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 Mt(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:Ya(),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:S,linked_tasks:v,linked_commits:k,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-EPXURMO7.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"?au(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(Ka),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:Ya(),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-EPXURMO7.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 S=_.assessment.verdict;c[S]++;let v=S==="correct"?1:S==="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 S of i){let v=[];f==="symbol"?v=S.symbols_touched||[]:f==="tag"?v=S.tags||[]:f==="type"&&(v=[S.type||"agent-session"]);for(let k of v)_.has(k)||_.set(k,[]),_.get(k).push(S);}b=Array.from(_.entries()).map(([S,v])=>{let k=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:S,total:v.length,accuracyRate:C/v.length,avgConfidence:k.length>0?T/k.length:null,calibrationScore:k.length>0?1-j/k.length:null,verdictBreakdown:x}}).sort((S,v)=>v.total-S.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 au(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 Ka(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 tc(){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 nc(n,e,s){switch(n){case "paradigm_habits_list":{let t=lu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_check":{let t=await du(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_status":{let t=await fu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_practice_context":{let t=await yu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_add":{let t=uu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_edit":{let t=gu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_remove":{let t=mu(e,s);return o(t.length,n),{text:t,handled:true}}default:return {text:"",handled:false}}}function lu(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 du(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(S=>S.toolName))],p=d.includes("paradigm_lore_record"),u=(r||"").toLowerCase(),g=["endpoint","route","api","handler","get","post","put","patch","delete"].some(S=>u.includes(S)),m;try{m=execSync("git status --porcelain",{cwd:e.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let y=Ht({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 S=c.getLastLoreEntryId()??void 0;h=await za(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:S,taskDescription:r,symbolsTouched:i,filesModified:t});}catch{}let w=F.join(e.rootDir,".paradigm",".habits-blocking");try{if(s==="on-stop"&&b.blocksCompletion){let S=b.evaluations.filter(v=>v.result==="skipped"&&v.habit.severity==="block").map(v=>`${v.habit.name}: ${v.reason}`);O.writeFileSync(w,S.join(`
|
|
746
|
-
`),"utf8");}else s==="on-stop"&&O.existsSync(w)&&O.unlinkSync(w);}catch{}let _=Gs;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(S=>({id:S.habit.id,name:S.habit.name,category:S.habit.category,severity:S.habit.severity,result:S.result,reason:S.reason,evidence:S.evidence})),recorded:o?h.length:0,recommendations:pu(b)},null,2)}function pu(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 uu(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=Ws(o);if(!a.valid)return JSON.stringify({error:true,message:"Validation failed",errors:a.errors},null,2);let c=Js(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 gu(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=Ws(l);return d.valid?(Js(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 mu(n,e){let s=n.id,t=Ja(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 fu(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 Mt(e.rootDir,o),l=await Ua(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,S=_>0?Math.round((w.followed+w.partial*.5)/_*100):100;return {habitId:h,habitName:f.get(h)||h,...w,total:_,rate:S}}).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 yu(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 Mt(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();Es();async function sc(n){let e=lt(n);if(!e.enabled)return [];let s=ie(n),t=[];for(let i of s){if(!i.enabled)continue;let r=await hu(n,i,e);t.push(r);}return t}async function hu(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 ic(n){let e=ie(n),s=lt(n),t=qs(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 bu=[{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 wu(n,e){let s=await sc(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(rc),action:"Run `paradigm graduate promote <id>` to graduate eligible habits."}:{},...r.length>0?{ineligible:r.map(rc)}:{},...o.length>0?{neverGraduate:o.map(a=>({id:a.habitId,name:a.habitName,reason:a.reason}))}:{}},null,2)}async function vu(n){let e=ic(n.rootDir),s=lt(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 oc(){return bu}async function ac(n,e,s){switch(n){case "paradigm_graduate_check":return {handled:true,text:await wu(s,e)};case "paradigm_graduate_status":return {handled:true,text:await vu(s)};default:return {handled:false,text:""}}}function rc(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 cc=new Set(["the","a","an","is","how","does","what","why","when","where","do","can","will","should","would","could","are","was","were","been","being","have","has","had","this","that","it","its","of","in","to","for","with","on","at","by","from","or","and","but","not"]),_u=.95,Su=.3,ku=10;function xu(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 lc(n){let e=n.toLowerCase().split(/\s+/).filter(s=>s.length>0&&!cc.has(s));return e.sort(),e.join(" ")}function Cu(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 dc(n,e,s){let t=s?.limit??ku,i=lc(e);if(i.length===0)return [];let r=Pu(n,i,s);if(r.length>0)return r.slice(0,t);if(Cu(n)){let a=Ru(n,i,s);if(a.length>0)return a.slice(0,t)}return ju(n,i,s).slice(0,t)}function Pu(n,e,s){try{let t=`
|
|
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 Va(n,e,s){switch(n){case "paradigm_pm_preflight":{let{task:t}=e,i=await cu(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=du(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 cu(n,e){let s=n.toLowerCase(),t=n.match(ru)||[],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=ou.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=Ht({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:lu(r,o,a,c),habits:{evaluation:d,recentCompliance:p?{rate:p.rate,totalEvents:p.total}:null}}}function lu(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 du(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 au){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=Ht({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(`
|
|
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 Ya(){let n=process.env.PARADIGM_AUTHOR;if(n)return Bs(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Bs(e)}catch{}try{let e=ga.userInfo().username;if(e)return Bs(e)}catch{}return "unknown"}function Bs(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function Xa(){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 Za(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(Ka)},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 Mt(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:Ya(),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-EPXURMO7.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"?uu(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(Ka),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:Ya(),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-EPXURMO7.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 uu(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 Ka(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 tc(){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 nc(n,e,s){switch(n){case "paradigm_habits_list":{let t=mu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_check":{let t=await fu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_status":{let t=await vu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_practice_context":{let t=await _u(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_add":{let t=hu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_edit":{let t=bu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_remove":{let t=wu(e,s);return o(t.length,n),{text:t,handled:true}}default:return {text:"",handled:false}}}function mu(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 fu(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=Ht({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 za(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 _=Gs;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:yu(b)},null,2)}function yu(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 hu(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=Ws(o);if(!a.valid)return JSON.stringify({error:true,message:"Validation failed",errors:a.errors},null,2);let c=Js(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 bu(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=Ws(l);return d.valid?(Js(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 wu(n,e){let s=n.id,t=Ja(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 vu(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 Mt(e.rootDir,o),l=await Ua(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 _u(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 Mt(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();Es();async function sc(n){let e=lt(n);if(!e.enabled)return [];let s=ie(n),t=[];for(let i of s){if(!i.enabled)continue;let r=await ku(n,i,e);t.push(r);}return t}async function ku(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 ic(n){let e=ie(n),s=lt(n),t=qs(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 Su=[{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 xu(n,e){let s=await sc(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(rc),action:"Run `paradigm graduate promote <id>` to graduate eligible habits."}:{},...r.length>0?{ineligible:r.map(rc)}:{},...o.length>0?{neverGraduate:o.map(a=>({id:a.habitId,name:a.habitName,reason:a.reason}))}:{}},null,2)}async function Cu(n){let e=ic(n.rootDir),s=lt(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 oc(){return Su}async function ac(n,e,s){switch(n){case "paradigm_graduate_check":return {handled:true,text:await xu(s,e)};case "paradigm_graduate_status":return {handled:true,text:await Cu(s)};default:return {handled:false,text:""}}}function rc(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 cc=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"]),Pu=.95,Ru=.3,ju=10;function Tu(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 lc(n){let e=n.toLowerCase().split(/\s+/).filter(s=>s.length>0&&!cc.has(s));return e.sort(),e.join(" ")}function Du(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 dc(n,e,s){let t=s?.limit??ju,i=lc(e);if(i.length===0)return [];let r=Au(n,i,s);if(r.length>0)return r.slice(0,t);if(Du(n)){let a=Ou(n,i,s);if(a.length>0)return a.slice(0,t)}return Iu(n,i,s).slice(0,t)}function Au(n,e,s){try{let t=`
|
|
747
770
|
SELECT
|
|
748
771
|
a.id, a.description, a.category, a.severity, a.tags,
|
|
749
772
|
sw.weight,
|
|
@@ -751,7 +774,7 @@ Runs pre-flight compliance checks: extracts affected symbols, runs ripple analys
|
|
|
751
774
|
FROM search_weights sw
|
|
752
775
|
JOIN aspects a ON sw.aspect_id = a.id
|
|
753
776
|
WHERE sw.query_normalized LIKE ? || '%'
|
|
754
|
-
`,i=[e];s?.category&&(t+=" AND a.category = ?",i.push(s.category)),s?.severity&&(t+=" AND a.severity = ?",i.push(s.severity)),t+=" ORDER BY sw.weight DESC";let r=n.prepare(t);r.bind(i);let o=[];for(;r.step();){let a=r.getAsObject();o.push({id:a.id,description:a.description,category:a.category||void 0,severity:a.severity||void 0,score:a.weight,tier:1,tags:a.tags?Vs(a.tags):void 0,anchorCount:a.anchor_count});}return r.free(),o}catch{return []}}function
|
|
777
|
+
`,i=[e];s?.category&&(t+=" AND a.category = ?",i.push(s.category)),s?.severity&&(t+=" AND a.severity = ?",i.push(s.severity)),t+=" ORDER BY sw.weight DESC";let r=n.prepare(t);r.bind(i);let o=[];for(;r.step();){let a=r.getAsObject();o.push({id:a.id,description:a.description,category:a.category||void 0,severity:a.severity||void 0,score:a.weight,tier:1,tags:a.tags?Vs(a.tags):void 0,anchorCount:a.anchor_count});}return r.free(),o}catch{return []}}function Ou(n,e,s){try{let t=e.split(/\s+/).filter(c=>c.length>0).map(c=>`"${c}"*`).join(" ");if(t.length===0)return [];let i=`
|
|
755
778
|
SELECT
|
|
756
779
|
a.id, a.description, a.category, a.severity, a.tags,
|
|
757
780
|
rank AS fts_rank,
|
|
@@ -759,13 +782,13 @@ Runs pre-flight compliance checks: extracts affected symbols, runs ripple analys
|
|
|
759
782
|
FROM aspects_fts fts
|
|
760
783
|
JOIN aspects a ON fts.rowid = a.rowid
|
|
761
784
|
WHERE aspects_fts MATCH ?
|
|
762
|
-
`,r=[t];s?.category&&(i+=" AND a.category = ?",r.push(s.category)),s?.severity&&(i+=" AND a.severity = ?",r.push(s.severity)),i+=" ORDER BY rank";let o=n.prepare(i);o.bind(r);let a=[];for(;o.step();){let c=o.getAsObject(),l=Math.abs(c.fts_rank);a.push({id:c.id,description:c.description,category:c.category||void 0,severity:c.severity||void 0,score:l,tier:2,tags:c.tags?Vs(c.tags):void 0,anchorCount:c.anchor_count});}return o.free(),a}catch{return []}}function
|
|
785
|
+
`,r=[t];s?.category&&(i+=" AND a.category = ?",r.push(s.category)),s?.severity&&(i+=" AND a.severity = ?",r.push(s.severity)),i+=" ORDER BY rank";let o=n.prepare(i);o.bind(r);let a=[];for(;o.step();){let c=o.getAsObject(),l=Math.abs(c.fts_rank);a.push({id:c.id,description:c.description,category:c.category||void 0,severity:c.severity||void 0,score:l,tier:2,tags:c.tags?Vs(c.tags):void 0,anchorCount:c.anchor_count});}return o.free(),a}catch{return []}}function Iu(n,e,s){try{let t=`
|
|
763
786
|
SELECT
|
|
764
787
|
a.id, a.description, a.category, a.severity, a.tags,
|
|
765
788
|
(SELECT COUNT(*) FROM anchors anc WHERE anc.aspect_id = a.id) AS anchor_count
|
|
766
789
|
FROM aspects a
|
|
767
790
|
WHERE 1=1
|
|
768
|
-
`,i=[];s?.category&&(t+=" AND a.category = ?",i.push(s.category)),s?.severity&&(t+=" AND a.severity = ?",i.push(s.severity));let r=n.prepare(t);r.bind(i);let o=[];for(;r.step();){let c=r.getAsObject();o.push({id:c.id,description:c.description,category:c.category,severity:c.severity,tags:c.tags,anchorCount:c.anchor_count});}r.free();let a=[];for(let c of o){let l
|
|
791
|
+
`,i=[];s?.category&&(t+=" AND a.category = ?",i.push(s.category)),s?.severity&&(t+=" AND a.severity = ?",i.push(s.severity));let r=n.prepare(t);r.bind(i);let o=[];for(;r.step();){let c=r.getAsObject();o.push({id:c.id,description:c.description,category:c.category,severity:c.severity,tags:c.tags,anchorCount:c.anchor_count});}r.free();let a=[];for(let c of o){let l=$u(e,c.id,c.description);l>Ru&&a.push({id:c.id,description:c.description,category:c.category||void 0,severity:c.severity||void 0,score:l,tier:3,tags:c.tags?Vs(c.tags):void 0,anchorCount:c.anchorCount});}return a.sort((c,l)=>l.score-c.score),a}catch{return []}}function $u(n,e,s){let i=[(e.startsWith("~")?e.slice(1):e).toLowerCase()],r=s.toLowerCase().split(/\s+/).filter(c=>c.length>0&&!cc.has(c));i.push(...r);let o=n.split(/\s+/).filter(c=>c.length>0);if(o.length===0)return 0;let a=0;for(let c of o){let l=0;for(let d of i){let u=1/(1+Tu(c,d));u>l&&(l=u);}a+=l;}return a/o.length}function pc(n,e,s){let t=lc(e),i=new Date().toISOString();try{n.run(`INSERT INTO search_log (query, results, selected, timestamp)
|
|
769
792
|
VALUES (?, ?, ?, ?)`,[e,JSON.stringify([s]),s,i]);}catch{}try{n.run(`INSERT INTO search_weights (query_normalized, aspect_id, weight, hit_count, last_hit)
|
|
770
793
|
VALUES (?, ?, 1.0, 1, ?)
|
|
771
794
|
ON CONFLICT(query_normalized, aspect_id) DO UPDATE SET
|
|
@@ -773,15 +796,15 @@ Runs pre-flight compliance checks: extracts affected symbols, runs ripple analys
|
|
|
773
796
|
hit_count = hit_count + 1,
|
|
774
797
|
last_hit = ?`,[t,s,i,i]);}catch{return}try{n.run(`UPDATE search_weights
|
|
775
798
|
SET weight = weight * ?
|
|
776
|
-
WHERE query_normalized = ? AND aspect_id != ?`,[_u,t,s]);}catch{}}function Vs(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 uc(){return [{name:"paradigm_aspect_search",description:"Search aspects using three-tier learning search (learned mappings > FTS5 > fuzzy). Returns ranked results. Call paradigm_aspect_confirm after selecting a result to improve future searches. ~200 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:'Search query (natural language or keyword, e.g., "token expiry", "pricing rule")'},limit:{type:"number",description:"Maximum results to return (default: 10)"}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_get",description:"Get full detail for a single aspect: description, category, severity, code anchors with snippets, edges, and linked lore entries. ~300 tokens.",inputSchema:{type:"object",properties:{aspectId:{type:"string",description:'Aspect identifier without ~ prefix (e.g., "token-expiry-24h")'}},required:["aspectId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_graph",description:"Traverse the aspect graph from a symbol to visualize its neighborhood. Returns nodes and edges within N hops (BFS). Useful for understanding how aspects relate to each other. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Starting symbol for graph traversal (e.g., "~token-expiry-24h", "#auth-service")'},hops:{type:"number",description:"Maximum number of hops to traverse (default: 2, max: 5)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_heatmap",description:"View the most frequently accessed aspects, ranked by total access count. Shows which aspects are queried most often. ~150 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Maximum entries to return (default: 20)"},accessType:{type:"string",enum:["search","ripple","navigate","direct"],description:"Optional: filter by access type"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_suggest_scan",description:"Scan a source file for implicit aspects (magic numbers, hardcoded limits, configuration values) and suggest aspect definitions. ~200 tokens.",inputSchema:{type:"object",properties:{filePath:{type:"string",description:"Relative or absolute path to the source file to scan"}},required:["filePath"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_drift",description:"Smart drift detection for code anchors. Layer 1: normalized hash (ignores formatting). Layer 2: git-aware line mapping (detects shifts, auto-heals .purpose files). ~200 tokens.",inputSchema:{type:"object",properties:{aspectId:{type:"string",description:"Optional: check a specific aspect. If omitted, checks all aspects."},autoHeal:{type:"boolean",description:"Auto-update anchors for high-confidence shifts (default: true)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_aspect_confirm",description:"Confirm a search result to improve future search accuracy. Call this after the user selects or uses a result from paradigm_aspect_search. Reinforces the query-to-aspect mapping. ~50 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"The original search query used"},aspectId:{type:"string",description:"The aspect ID that was selected/confirmed"}},required:["query","aspectId"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function gc(n,e,s){switch(n){case "paradigm_aspect_search":return Du(e,s);case "paradigm_aspect_get":return Au(e,s);case "paradigm_aspect_graph":return Ou(e,s);case "paradigm_aspect_heatmap":return Iu(e,s);case "paradigm_aspect_suggest_scan":return $u(e,s);case "paradigm_aspect_drift":return Fu(e,s);case "paradigm_aspect_confirm":return Nu(e,s);default:return {handled:false,text:""}}}async function Du(n,e){let{query:s,limit:t=10}=n,i=null;try{i=await w$1(e.rootDir);let r=dc(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 Au(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=Eu(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 Ou(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 Iu(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 $u(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 Fu(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 Nu(n,e){let{query:s,aspectId:t}=n,i=null;try{i=await w$1(e.rootDir),pc(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 Eu(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(`
|
|
799
|
+
WHERE query_normalized = ? AND aspect_id != ?`,[Pu,t,s]);}catch{}}function Vs(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 uc(){return [{name:"paradigm_aspect_search",description:"Search aspects using three-tier learning search (learned mappings > FTS5 > fuzzy). Returns ranked results. Call paradigm_aspect_confirm after selecting a result to improve future searches. ~200 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:'Search query (natural language or keyword, e.g., "token expiry", "pricing rule")'},limit:{type:"number",description:"Maximum results to return (default: 10)"}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_get",description:"Get full detail for a single aspect: description, category, severity, code anchors with snippets, edges, and linked lore entries. ~300 tokens.",inputSchema:{type:"object",properties:{aspectId:{type:"string",description:'Aspect identifier without ~ prefix (e.g., "token-expiry-24h")'}},required:["aspectId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_graph",description:"Traverse the aspect graph from a symbol to visualize its neighborhood. Returns nodes and edges within N hops (BFS). Useful for understanding how aspects relate to each other. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Starting symbol for graph traversal (e.g., "~token-expiry-24h", "#auth-service")'},hops:{type:"number",description:"Maximum number of hops to traverse (default: 2, max: 5)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_heatmap",description:"View the most frequently accessed aspects, ranked by total access count. Shows which aspects are queried most often. ~150 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Maximum entries to return (default: 20)"},accessType:{type:"string",enum:["search","ripple","navigate","direct"],description:"Optional: filter by access type"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_suggest_scan",description:"Scan a source file for implicit aspects (magic numbers, hardcoded limits, configuration values) and suggest aspect definitions. ~200 tokens.",inputSchema:{type:"object",properties:{filePath:{type:"string",description:"Relative or absolute path to the source file to scan"}},required:["filePath"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_drift",description:"Smart drift detection for code anchors. Layer 1: normalized hash (ignores formatting). Layer 2: git-aware line mapping (detects shifts, auto-heals .purpose files). ~200 tokens.",inputSchema:{type:"object",properties:{aspectId:{type:"string",description:"Optional: check a specific aspect. If omitted, checks all aspects."},autoHeal:{type:"boolean",description:"Auto-update anchors for high-confidence shifts (default: true)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_aspect_confirm",description:"Confirm a search result to improve future search accuracy. Call this after the user selects or uses a result from paradigm_aspect_search. Reinforces the query-to-aspect mapping. ~50 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"The original search query used"},aspectId:{type:"string",description:"The aspect ID that was selected/confirmed"}},required:["query","aspectId"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function gc(n,e,s){switch(n){case "paradigm_aspect_search":return Fu(e,s);case "paradigm_aspect_get":return Nu(e,s);case "paradigm_aspect_graph":return Eu(e,s);case "paradigm_aspect_heatmap":return Hu(e,s);case "paradigm_aspect_suggest_scan":return qu(e,s);case "paradigm_aspect_drift":return Mu(e,s);case "paradigm_aspect_confirm":return Lu(e,s);default:return {handled:false,text:""}}}async function Fu(n,e){let{query:s,limit:t=10}=n,i=null;try{i=await w$1(e.rootDir);let r=dc(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=Wu(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 Eu(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 Hu(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 qu(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 Mu(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 Lu(n,e){let{query:s,aspectId:t}=n,i=null;try{i=await w$1(e.rootDir),pc(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 Wu(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(`
|
|
777
800
|
`),r=Math.max(0,e.start_line-1),o=Math.min(i.length,e.end_line),a=i.slice(r,o).join(`
|
|
778
801
|
`);return a.length>1e3?a.slice(0,1e3)+`
|
|
779
802
|
... (truncated)`:a}catch{return null}}function mc(){return [{name:"paradigm_task_create",description:"Create a task (persistent scratch-pad item that survives context windows). Returns the created task ID. ~100 tokens.",inputSchema:{type:"object",properties:{blurb:{type:"string",description:"One-line task description"},priority:{type:"string",enum:["high","medium","low"],description:"Priority level (default: medium)"},tags:{type:"array",items:{type:"string"},description:"Tags \u2014 symbols (#component), freeform labels, etc."},related_lore:{type:"array",items:{type:"string"},description:"Linked lore entry IDs"}},required:["blurb"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_list",description:"List/filter tasks by status, priority, tags, or symbols. Returns task list sorted by priority then date. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",enum:["open","done","shelved","all"],description:"Filter by status (default: open)"},priority:{type:"string",enum:["high","medium","low"],description:"Filter by priority"},tag:{type:"string",description:"Filter by tag (symbol or freeform)"},limit:{type:"number",description:"Maximum results (default: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_task_update",description:"Update a task (blurb, priority, status, tags). Returns updated task. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Task ID (e.g., "T-2026-02-26-001")'},blurb:{type:"string",description:"New description"},priority:{type:"string",enum:["high","medium","low"]},status:{type:"string",enum:["open","done","shelved"]},tags:{type:"array",items:{type:"string"},description:"Replace tags"},related_lore:{type:"array",items:{type:"string"},description:"Related lore entry IDs (includes former assessment entries)"},related_assessments:{type:"array",items:{type:"string"},description:"(Deprecated \u2014 use related_lore) Alias for related_lore"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_done",description:"Mark a task as done. Shorthand for update with status=done. Returns confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_shelve",description:"Shelve a task (not now, not never). Shorthand for update with status=shelved. Returns confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function fc(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(`
|
|
780
|
-
`)}}case "paradigm_task_update":{let t=e.id,i={};if(e.blurb!==void 0&&(i.blurb=e.blurb),e.priority!==void 0&&(i.priority=e.priority),e.status!==void 0&&(i.status=e.status),e.tags!==void 0&&(i.tags=e.tags),e.related_lore!==void 0&&(i.related_lore=e.related_lore),e.related_assessments!==void 0&&(i.related_assessments=e.related_assessments),!await d$6(s.rootDir,t,i))return {handled:true,text:JSON.stringify({error:`Task ${t} not found`})};let o=await b$6(s.rootDir,t);return {handled:true,text:JSON.stringify({updated:t,task:o},null,2)}}case "paradigm_task_done":{let t=e.id;if(!await e$4(s.rootDir,t))return {handled:true,text:JSON.stringify({error:`Task ${t} not found`})};let r=await b$6(s.rootDir,t);return {handled:true,text:JSON.stringify({completed:t,task:r,hint:"Consider recording a lore entry with arc:* tags if this was a significant milestone."},null,2)}}case "paradigm_task_shelve":{let t=e.id;if(!await f$3(s.rootDir,t))return {handled:true,text:JSON.stringify({error:`Task ${t} not found`})};let r=await b$6(s.rootDir,t);return {handled:true,text:JSON.stringify({shelved:t,task:r},null,2)}}default:return {handled:false,text:""}}}j();var Te=".paradigm/assessments",Me="arcs",
|
|
803
|
+
`)}}case "paradigm_task_update":{let t=e.id,i={};if(e.blurb!==void 0&&(i.blurb=e.blurb),e.priority!==void 0&&(i.priority=e.priority),e.status!==void 0&&(i.status=e.status),e.tags!==void 0&&(i.tags=e.tags),e.related_lore!==void 0&&(i.related_lore=e.related_lore),e.related_assessments!==void 0&&(i.related_assessments=e.related_assessments),!await d$6(s.rootDir,t,i))return {handled:true,text:JSON.stringify({error:`Task ${t} not found`})};let o=await b$6(s.rootDir,t);return {handled:true,text:JSON.stringify({updated:t,task:o},null,2)}}case "paradigm_task_done":{let t=e.id;if(!await e$4(s.rootDir,t))return {handled:true,text:JSON.stringify({error:`Task ${t} not found`})};let r=await b$6(s.rootDir,t);return {handled:true,text:JSON.stringify({completed:t,task:r,hint:"Consider recording a lore entry with arc:* tags if this was a significant milestone."},null,2)}}case "paradigm_task_shelve":{let t=e.id;if(!await f$3(s.rootDir,t))return {handled:true,text:JSON.stringify({error:`Task ${t} not found`})};let r=await b$6(s.rootDir,t);return {handled:true,text:JSON.stringify({shelved:t,task:r},null,2)}}default:return {handled:false,text:""}}}j();var Te=".paradigm/assessments",Me="arcs",Ju="index.yaml";function yc(n,e){let s=F.join(n,Te,Me,e.id,"entries"),t=new Set,i=0,r;if(O.existsSync(s)){let o=O.readdirSync(s).filter(a=>a.endsWith(".yaml"));for(let a of o)try{let c=Z.load(O.readFileSync(F.join(s,a),"utf8"));i++,c.symbols&&c.symbols.forEach(l=>t.add(l)),(!r||c.date>r)&&(r=c.date);}catch{}}return {...e,entry_count:i,symbols:Array.from(t),latest_entry:r}}async function hc(n,e){let s=F.join(n,Te,Me);if(!O.existsSync(s))return [];let t=O.readdirSync(s).filter(r=>{try{return O.statSync(F.join(s,r)).isDirectory()}catch{return false}}),i=[];for(let r of t){let o=F.join(s,r,"arc.yaml");if(O.existsSync(o))try{let a=Z.load(O.readFileSync(o,"utf8"));if(e&&e!=="all"&&a.status!==e)continue;i.push(yc(n,a));}catch{}}return i.sort((r,o)=>{let a=r.latest_entry||r.created;return (o.latest_entry||o.created).localeCompare(a)}),i}async function bc(n,e){let s=F.join(n,Te,Me,e,"arc.yaml");if(!O.existsSync(s))return null;try{let t=Z.load(O.readFileSync(s,"utf8"));return yc(n,t)}catch{return null}}async function wc(n,e,s){let t=F.join(n,Te,Me,e,"arc.yaml");if(!O.existsSync(t))return false;try{let i=Z.load(O.readFileSync(t,"utf8"));return i.status=s,O.writeFileSync(t,Z.dump(i,{lineWidth:-1,noRefs:!0})),await Gu(n),!0}catch{return false}}async function vc(n,e){let s=F.join(n,Te,Me,e,"entries");if(!O.existsSync(s))return [];let t=[],i=O.readdirSync(s).filter(r=>r.endsWith(".yaml")).sort();for(let r of i)try{let o=Z.load(O.readFileSync(F.join(s,r),"utf8"));t.push(o);}catch{}return t.sort((r,o)=>o.date.localeCompare(r.date)),t}async function _c(n,e){let s=F.join(n,Te,Me);if(!O.existsSync(s))return null;let t=O.readdirSync(s).filter(i=>{try{return O.statSync(F.join(s,i)).isDirectory()}catch{return false}});for(let i of t){let r=F.join(s,i,"entries",`${e}.yaml`);if(O.existsSync(r))try{let o=Z.load(O.readFileSync(r,"utf8")),a=F.join(s,i,"arc.yaml"),c=Z.load(O.readFileSync(a,"utf8"));return {entry:o,arc:c}}catch{return null}}return null}async function kc(n,e){let s=F.join(n,Te,Me);if(!O.existsSync(s))return [];let t=e.limit,i=[],r=O.readdirSync(s).filter(o=>{try{return O.statSync(F.join(s,o)).isDirectory()}catch{return false}});for(let o of r){let a=F.join(s,o,"entries");if(!O.existsSync(a))continue;let c=O.readdirSync(a).filter(l=>l.endsWith(".yaml"));for(let l of c)try{let d=Z.load(O.readFileSync(F.join(a,l),"utf8"));if(e.symbol&&!(d.symbols||[]).includes(e.symbol)||e.tag&&!(d.tags||[]).includes(e.tag)||e.type&&d.type!==e.type||e.dateFrom&&d.date<e.dateFrom||e.dateTo&&d.date>e.dateTo)continue;i.push(d);}catch{}}return i.sort((o,a)=>a.date.localeCompare(o.date)),i.slice(0,t)}async function Gu(n){let e=F.join(n,Te,Me),s=F.join(n,Te),t=0,i=0,r=0,o=[];if(O.existsSync(e)){let c=O.readdirSync(e).filter(l=>{try{return O.statSync(F.join(e,l)).isDirectory()}catch{return false}});for(let l of c){let d=F.join(e,l,"arc.yaml");if(O.existsSync(d))try{let p=Z.load(O.readFileSync(d,"utf8")),u=F.join(e,l,"entries"),g=O.existsSync(u)?O.readdirSync(u).filter(m=>m.endsWith(".yaml")).length:0;t++,i+=g,p.status==="active"&&r++,o.push({id:p.id,name:p.name,status:p.status,entries:g});}catch{}}}let a={version:"1.0",total_arcs:t,total_entries:i,active_arcs:r,last_updated:new Date().toISOString(),arcs:o};return O.mkdirSync(s,{recursive:true}),O.writeFileSync(F.join(s,Ju),Z.dump(a,{lineWidth:-1,noRefs:true})),a}function zu(){let n=process.env.PARADIGM_AUTHOR;if(n)return Ys(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Ys(e)}catch{}try{let e=ga.userInfo().username;if(e)return Ys(e)}catch{}return "unknown"}function Ys(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function xc(){return [{name:"paradigm_assessment_record",description:"[DEPRECATED \u2014 use paradigm_lore_record with arc:* tags] Add a reflection entry. Forwards to lore with arc:{arc_id} and assessment:{type} tags. ~150 tokens.",inputSchema:{type:"object",properties:{arc_id:{type:"string",description:"Arc ID (becomes arc:{id} tag on the lore entry)"},arc_name:{type:"string",description:"Human-readable arc name (ignored \u2014 arcs are now just tags)"},arc_description:{type:"string",description:"Arc description (ignored \u2014 arcs are now just tags)"},title:{type:"string",description:"Entry title"},summary:{type:"string",description:"Short summary (1-2 sentences)"},body:{type:"string",description:"Full reflection \u2014 what happened, what was learned, what changed"},symbols:{type:"array",items:{type:"string"},description:"Symbols touched in this entry"},tags:{type:"array",items:{type:"string"}},type:{type:"string",enum:["retro","insight","decision","milestone"],description:"Entry type (default: retro)"},linked_lore:{type:"array",items:{type:"string"},description:"Lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"Task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Commit hashes"}},required:["arc_id","title","summary"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_assessment_list",description:'[DEPRECATED \u2014 use paradigm_lore_search with tag:"arc:{id}"] List assessment arcs or entries within a specific arc. ~200 tokens.',inputSchema:{type:"object",properties:{arc_id:{type:"string",description:"If provided, list entries in this arc. Otherwise, list all arcs."},status:{type:"string",enum:["active","complete","archived","all"],description:"Filter arcs by status (default: active). Ignored when arc_id is provided."},limit:{type:"number",description:"Maximum results (default: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_assessment_get",description:"[DEPRECATED \u2014 use paradigm_lore_get] Get a specific assessment entry or arc detail. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Entry ID (e.g., "A-2026-02-26-001") or arc ID (e.g., "arc-telemetry")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_assessment_search",description:"[DEPRECATED \u2014 use paradigm_lore_search with tag/type filters] Search across assessment entries by symbol, tag, type, or date. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter by symbol"},tag:{type:"string",description:"Filter by tag"},type:{type:"string",enum:["retro","insight","decision","milestone"]},dateFrom:{type:"string",description:"ISO date string (inclusive)"},dateTo:{type:"string",description:"ISO date string (inclusive)"},limit:{type:"number",description:"Max results (default: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_assessment_arc_create",description:"[DEPRECATED \u2014 arcs are now tag prefixes] No-op. Arcs are just arc:* tags on lore entries. No explicit creation needed. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Arc ID (no longer needed \u2014 just use arc:{id} tag on lore entries)"},name:{type:"string",description:"Arc name (ignored)"},description:{type:"string",description:"Arc description (ignored)"},tags:{type:"array",items:{type:"string"}}},required:["id","name"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_assessment_arc_close",description:"[DEPRECATED \u2014 use paradigm_lore_search + paradigm_lore_update] Adds arc-closed tag to all entries in the arc. ~100 tokens.",inputSchema:{type:"object",properties:{arc_id:{type:"string",description:"Arc ID to close"},status:{type:"string",enum:["complete","archived"],description:"New status (default: complete)"}},required:["arc_id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Cc(n,e,s){switch(n){case "paradigm_assessment_record":{let t=e.arc_id,i=e.type||"retro",r=e.tags||[],o=[`arc:${t}`,`assessment:${i}`,...r],a={id:"",type:i,timestamp:new Date().toISOString(),author:zu(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:e.title,summary:e.summary,body:e.body,symbols_touched:e.symbols||[],tags:o,linked_lore:e.linked_lore,linked_tasks:e.linked_tasks,linked_commits:e.linked_commits};try{let c=await d$1(s.rootDir,a);return {handled:!0,text:JSON.stringify({recorded:c,arc_id:t,deprecated:'Use paradigm_lore_record with tags: ["arc:'+t+'"] instead'},null,2)}}catch(c){return {handled:true,text:JSON.stringify({error:c.message})}}}case "paradigm_assessment_list":{let t=e.arc_id;if(t){let i=await a$1(s.rootDir,{tag:`arc:${t}`,limit:e.limit||20}),r=[`${i.length} entries with arc:${t} tag:`];for(let o of i)r.push(` [${o.type||"unknown"}] ${o.id}: ${o.title} (${o.timestamp.slice(0,10)})`);return r.push("",'Deprecated: Use paradigm_lore_search with tag: "arc:'+t+'"'),{handled:true,text:r.join(`
|
|
781
804
|
`)}}try{let i=e.status||"active",o=(await hc(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(`
|
|
782
805
|
`)}}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 bc(s.rootDir,t);if(!i)return {handled:!0,text:JSON.stringify({error:`Arc ${t} not found`})};let r=await vc(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 _c(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(`
|
|
783
|
-
`)}}try{let o=await
|
|
784
|
-
`)}}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 wc(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 Pc=0;function Rc(){let n=new Date().toISOString().slice(0,10);return Pc++,`run_${n}_${String(Pc).padStart(3,"0")}`}var jc=/\{\{([^}]+)\}\}/g;function pt(n,e){if(typeof n=="string")return n.replace(jc,(s,t)=>{let i=Wu(t.trim(),e);return i!==void 0?String(i):s});if(Array.isArray(n))return n.map(s=>pt(s,e));if(n&&typeof n=="object"){let s={};for(let[t,i]of Object.entries(n))s[t]=pt(i,e);return s}return n}function Wu(n,e){let[s,...t]=n.split("."),i=t.join(".");switch(s){case "fixtures":return e.fixtures[i];case "produces":return Ks(e.produces,i);case "context":case "parent":return e.context[i];case "env":return e.env[i]??process.env[i];default:return}}function Ks(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 Ju(n,e){let s={};for(let[t,i]of Object.entries(n)){let r=i.match(/\{\{response\.(.+)\}\}/);if(r){let o=r[1],a=Ks(e,o);a!==void 0&&(s[t]=a);}}return s}function Gu(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=Ks(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 Uu(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=pt(o,s),c=`${e.baseUrl.replace(/\/$/,"")}${a}`,l={"Content-Type":"application/json",...n.headers?pt(n.headers,s):{}},d=n.payload?pt(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=Gu(n.expect,f),h;n.produces&&b.pass&&(h=Ju(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 Tc(n,e,s){let t=Date.now(),i=await I(n,e);return i?Dc(n,i,s):{persona:e,run_id:Rc(),status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${e} not found`,duration_ms:Date.now()-t}}async function Dc(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 Uu(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:Rc(),status:p>0?"fail":"pass",steps:o,spawns_triggered:a,spawns_blocked:c,summary:m,duration_ms:Date.now()-t}}async function Ac(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[S,v]of Object.entries(_.journey)){let k=f.journey.find(x=>x.id===S);k&&(v.payload&&(k.payload={...k.payload,...v.payload}),v.expect&&(k.expect={...k.expect,...v.expect}));}}let b={};if(y.wait_for){let[_,S]=y.wait_for.split("."),v=d.find(x=>x.persona===_);if(v){let x=v.steps.find(C=>C.id===S);x?.produced&&(b=Object.fromEntries(Object.entries(x.produced).map(([C,T])=>[C,String(T)])));}let k=await I(n,_);if(k){let x=k.journey.find(C=>C.id===S);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(pt(P,{fixtures:{},produces:T,context:{},env:process.env}));}}}}let h=await Dc(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 Oc(n){let e=[],s=new Set;for(let t of n.journey){let r=JSON.stringify(t).match(jc)||[];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 $c="paradigm-personas",zu={id:$c,version:"1.0",name:"Paradigm Personas",description:"Events from persona journey and chain execution",scope:{key:"persona_id",label:"Persona"},eventTypes:{"persona.run.start":{category:"lifecycle",severity:"info"},"persona.step.pass":{category:"assertion",severity:"info"},"persona.step.fail":{category:"assertion",severity:"warning"},"persona.step.skip":{category:"lifecycle",severity:"info"},"persona.run.complete":{category:"lifecycle",severity:"info"},"persona.chain.complete":{category:"lifecycle",severity:"info"},"persona.coverage.report":{category:"analysis",severity:"info"}}},Qs=false;async function Ic(n){try{let{SentinelStorage:e}=await import('./dist-W3XCATBJ.js'),s=new e;if(!Qs)try{s.registerSchema(zu),Qs=!0;}catch{Qs=!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($c,"paradigm-personas",t);}catch{}}function Fc(){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 Ac(s.rootDir,e.chain_id,{baseUrl:t,dryRun:i,stopOnFailure:r,permutation:e.permutation});return i||await Ic(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=Oc(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 Tc(s.rootDir,e.persona_id,{baseUrl:t,dryRun:i,stopOnFailure:r});return i||await Ic(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 Ec(){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 Hc(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(Bu)}))},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 Bu(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 Vu=".paradigm/graphs",ei={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},Xs=200,Zs=60,ut=20,Wn=40,qc=50,Yu=60;function Lc(){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 Wc(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=Xu(s.rootDir,e.symbols,e.groups,e.links,t),o$1=JSON.stringify(r,null,2),a=F.join(s.rootDir,Vu);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 Ku={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"};function Qu(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(Ku)){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:ei[r]||"#",description:l.description,path:l.path,tags:l.tags});}}return t}function Mc(n,e){let s=n.replace(/^[#$^!~]/,"");return e.find(t=>t.id===s||t.name===s||t.id===n||t.name===n)}function Xu(n,e,s,t,i="Generated Graph"){let r=Qu(n),o;e&&e.length>0?o=e.map(g=>Mc(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=>Mc(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 k=y[v],x=v%f,C=Math.floor(v/f),T=ei[k.category]||"#";a.push({id:`sym-${k.id}`,type:"symbolNode",position:{x:Wn+x*(Xs+ut),y:qc+Wn+C*(Zs+ut)},parentId:m,data:{type:"symbol",symbol:k,label:`${T}${k.name}`}}),d.add(k.id);}let h=Math.max(f,1),w=Math.max(b,1),_=Wn*2+h*Xs+(h-1)*ut,S=qc+Wn*2+w*Zs+(w-1)*ut;a.unshift({id:m,type:"groupNode",position:{x:p,y:0},style:{width:_,height:S},data:{type:"group",label:g.label}}),p+=_+Yu;}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=ei[f.category]||"#";a.push({id:`sym-${f.id}`,type:"symbolNode",position:{x:b*(Xs+ut),y:g+h*(Zs+ut)},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 Jc=".paradigm/heat-map.json",Zu=.05;function Gc(){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 ti(n){let e=F.join(n,Jc);return O.existsSync(e)?JSON.parse(O.readFileSync(e,"utf8")):{version:"1.0",lastUpdated:new Date().toISOString(),sessionCount:0,associations:[]}}function eg(n,e){let s=F.join(n,Jc),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 tg(n,e){let s=ti(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-Zu,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 ng(n,e){let s=ti(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 eg(e,s),JSON.stringify({recorded:true,totalAssociations:s.associations.length})}async function sg(n){let e=ti(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:ig(e)})}function ig(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 Uc(n,e,s){switch(n){case "paradigm_heatmap_query":{let t=await tg(e,s.rootDir);return o(t.length,n),{handled:true,text:t}}case "paradigm_heatmap_record":{let t=await ng(e,s.rootDir);return o(t.length,n),{handled:true,text:t}}case "paradigm_heatmap_stats":{let t=await sg(s.rootDir);return o(t.length,n),{handled:true,text:t}}default:return {handled:false,text:""}}}var me=["specify","plan","task","implement","validate"],Ut=".paradigm/pipeline",zc={"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 Jt(n,e){let s=Jn(e),t=F.join(n,Ut,`${s}.yaml`);return O.existsSync(t)?Z.load(O.readFileSync(t,"utf8")):null}function Gt(n,e){let s=Jn(e.feature),t=F.join(n,Ut);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 Bc(n){let e=F.join(n,Ut);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 rg(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 og(n){let e=me.indexOf(n);return e<me.length-1?me[e+1]:null}function Vc(n,e){let s=Jn(e.feature),t=F.join(n,Ut,"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,Ut,`${s}.yaml`);O.existsSync(r)&&O.unlinkSync(r);}function Yc(){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 Kc(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=zc[i];if(!l)return {handled:true,text:JSON.stringify({error:`Unknown template: ${i}`,available:Object.keys(zc)})};o=l.gates;}let a=rg(t,o,i),c=Gt(s.rootDir,a);return {handled:true,text:JSON.stringify({created:true,feature:a.feature,template:i,file:c,current_stage:a.current_stage,gate_config:a.gate_config,stages:a.stages,hint:`Pipeline '${a.feature}' started at 'specify' stage. Create your spec, then call paradigm_pipeline_advance to move to 'plan'.`},null,2)}}case "paradigm_pipeline_status":{let t=e.feature;if(t){let r=Jt(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=Bc(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=Jt(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=og(o);return r.stages[o].status="approved",r.stages[o].approved_by=i,r.stages[o].approved_at=new Date().toISOString(),a==="auto"&&(r.stages[o].auto_passed_at=new Date().toISOString()),c?(r.current_stage=c,r.stages[c].status="in-progress",Gt(s.rootDir,r),{handled:true,text:JSON.stringify({advanced:true,from:o,to:c,gate_mode:a,approved_by:i,pipeline:{feature:r.feature,current_stage:r.current_stage,stages:r.stages}},null,2)}):(Gt(s.rootDir,r),Vc(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=Jt(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"]})}:(Gt(s.rootDir,o),{handled:true,text:JSON.stringify({configured:true,feature:o.feature,changes:a,reason:r,gate_config:o.gate_config},null,2)})}case "paradigm_pipeline_escalate":{let t=e.feature,i=e.stage,r=e.question,o=e.options,a=e.context,c=Jt(s.rootDir,t);return c?(c.stages[i].status="blocked",c.stages[i].block_reason=r,Gt(s.rootDir,c),{handled:true,text:JSON.stringify({escalated:true,feature:c.feature,stage:i,question:r,options:o,context:a||{},current_gate:c.gate_config[i],instruction:"This pipeline stage requires user input. Present the question and options to the user, then use paradigm_pipeline_advance or paradigm_pipeline_configure based on their response."},null,2)}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${t}`})}}case "paradigm_pipeline_abort":{let t=e.feature,i=Jt(s.rootDir,t);return i?(Vc(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=Bc(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 ag=F.join(ga.homedir(),".conductor"),ft=F.join(ag,"sessions");function Xc(){O.existsSync(ft)||O.mkdirSync(ft,{recursive:true});}function si(n){Xc();let e={...n,registeredAt:new Date().toISOString()},s=F.join(ft,`${n.pid}.json`);return O.writeFileSync(s,JSON.stringify(e,null,2),"utf-8"),e}function Gn(n){let e=F.join(ft,`${n}.json`);return O.existsSync(e)?(O.unlinkSync(e),true):false}function ii(){Xc();let n=O.readdirSync(ft).filter(s=>s.endsWith(".json")),e=[];for(let s of n)try{let t=O.readFileSync(F.join(ft,s),"utf-8"),i=JSON.parse(t);e.push(i);}catch{}return e}function Zc(){let n=ii(),e=0;for(let s of n)cg(s.pid)||(Gn(s.pid),e++);return e}function cg(n){try{return process.kill(n,0),!0}catch{return false}}function ri(){try{return execSync(`osascript -e '
|
|
806
|
+
`)}}try{let o=await kc(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 wc(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 Pc=0;function Rc(){let n=new Date().toISOString().slice(0,10);return Pc++,`run_${n}_${String(Pc).padStart(3,"0")}`}var jc=/\{\{([^}]+)\}\}/g;function pt(n,e){if(typeof n=="string")return n.replace(jc,(s,t)=>{let i=Bu(t.trim(),e);return i!==void 0?String(i):s});if(Array.isArray(n))return n.map(s=>pt(s,e));if(n&&typeof n=="object"){let s={};for(let[t,i]of Object.entries(n))s[t]=pt(i,e);return s}return n}function Bu(n,e){let[s,...t]=n.split("."),i=t.join(".");switch(s){case "fixtures":return e.fixtures[i];case "produces":return Ks(e.produces,i);case "context":case "parent":return e.context[i];case "env":return e.env[i]??process.env[i];default:return}}function Ks(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 Vu(n,e){let s={};for(let[t,i]of Object.entries(n)){let r=i.match(/\{\{response\.(.+)\}\}/);if(r){let o=r[1],a=Ks(e,o);a!==void 0&&(s[t]=a);}}return s}function Yu(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=Ks(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 Ku(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=pt(o,s),c=`${e.baseUrl.replace(/\/$/,"")}${a}`,l={"Content-Type":"application/json",...n.headers?pt(n.headers,s):{}},d=n.payload?pt(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=Yu(n.expect,f),h;n.produces&&b.pass&&(h=Vu(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 Tc(n,e,s){let t=Date.now(),i=await I(n,e);return i?Dc(n,i,s):{persona:e,run_id:Rc(),status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${e} not found`,duration_ms:Date.now()-t}}async function Dc(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 Ku(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:Rc(),status:p>0?"fail":"pass",steps:o,spawns_triggered:a,spawns_blocked:c,summary:m,duration_ms:Date.now()-t}}async function Ac(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(pt(P,{fixtures:{},produces:T,context:{},env:process.env}));}}}}let h=await Dc(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 Oc(n){let e=[],s=new Set;for(let t of n.journey){let r=JSON.stringify(t).match(jc)||[];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 $c="paradigm-personas",Qu={id:$c,version:"1.0",name:"Paradigm Personas",description:"Events from persona journey and chain execution",scope:{key:"persona_id",label:"Persona"},eventTypes:{"persona.run.start":{category:"lifecycle",severity:"info"},"persona.step.pass":{category:"assertion",severity:"info"},"persona.step.fail":{category:"assertion",severity:"warning"},"persona.step.skip":{category:"lifecycle",severity:"info"},"persona.run.complete":{category:"lifecycle",severity:"info"},"persona.chain.complete":{category:"lifecycle",severity:"info"},"persona.coverage.report":{category:"analysis",severity:"info"}}},Qs=false;async function Ic(n){try{let{SentinelStorage:e}=await import('./dist-W3XCATBJ.js'),s=new e;if(!Qs)try{s.registerSchema(Qu),Qs=!0;}catch{Qs=!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($c,"paradigm-personas",t);}catch{}}function Fc(){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 Ac(s.rootDir,e.chain_id,{baseUrl:t,dryRun:i,stopOnFailure:r,permutation:e.permutation});return i||await Ic(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=Oc(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 Tc(s.rootDir,e.persona_id,{baseUrl:t,dryRun:i,stopOnFailure:r});return i||await Ic(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 Ec(){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 Hc(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(Xu)}))},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 Xu(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 Zu=".paradigm/graphs",ei={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},Xs=200,Zs=60,ut=20,Wn=40,qc=50,eg=60;function Lc(){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 Wc(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=sg(s.rootDir,e.symbols,e.groups,e.links,t),o$1=JSON.stringify(r,null,2),a=F.join(s.rootDir,Zu);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 tg={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"};function ng(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(tg)){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:ei[r]||"#",description:l.description,path:l.path,tags:l.tags});}}return t}function Mc(n,e){let s=n.replace(/^[#$^!~]/,"");return e.find(t=>t.id===s||t.name===s||t.id===n||t.name===n)}function sg(n,e,s,t,i="Generated Graph"){let r=ng(n),o;e&&e.length>0?o=e.map(g=>Mc(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=>Mc(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=ei[S.category]||"#";a.push({id:`sym-${S.id}`,type:"symbolNode",position:{x:Wn+x*(Xs+ut),y:qc+Wn+C*(Zs+ut)},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*Xs+(h-1)*ut,k=qc+Wn*2+w*Zs+(w-1)*ut;a.unshift({id:m,type:"groupNode",position:{x:p,y:0},style:{width:_,height:k},data:{type:"group",label:g.label}}),p+=_+eg;}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=ei[f.category]||"#";a.push({id:`sym-${f.id}`,type:"symbolNode",position:{x:b*(Xs+ut),y:g+h*(Zs+ut)},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 Jc=".paradigm/heat-map.json",ig=.05;function Gc(){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 ti(n){let e=F.join(n,Jc);return O.existsSync(e)?JSON.parse(O.readFileSync(e,"utf8")):{version:"1.0",lastUpdated:new Date().toISOString(),sessionCount:0,associations:[]}}function rg(n,e){let s=F.join(n,Jc),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 og(n,e){let s=ti(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-ig,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 ag(n,e){let s=ti(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 rg(e,s),JSON.stringify({recorded:true,totalAssociations:s.associations.length})}async function cg(n){let e=ti(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:lg(e)})}function lg(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 Uc(n,e,s){switch(n){case "paradigm_heatmap_query":{let t=await og(e,s.rootDir);return o(t.length,n),{handled:true,text:t}}case "paradigm_heatmap_record":{let t=await ag(e,s.rootDir);return o(t.length,n),{handled:true,text:t}}case "paradigm_heatmap_stats":{let t=await cg(s.rootDir);return o(t.length,n),{handled:true,text:t}}default:return {handled:false,text:""}}}var me=["specify","plan","task","implement","validate"],Ut=".paradigm/pipeline",zc={"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 Jt(n,e){let s=Jn(e),t=F.join(n,Ut,`${s}.yaml`);return O.existsSync(t)?Z.load(O.readFileSync(t,"utf8")):null}function Gt(n,e){let s=Jn(e.feature),t=F.join(n,Ut);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 Bc(n){let e=F.join(n,Ut);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 dg(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 pg(n){let e=me.indexOf(n);return e<me.length-1?me[e+1]:null}function Vc(n,e){let s=Jn(e.feature),t=F.join(n,Ut,"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,Ut,`${s}.yaml`);O.existsSync(r)&&O.unlinkSync(r);}function Yc(){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 Kc(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=zc[i];if(!l)return {handled:true,text:JSON.stringify({error:`Unknown template: ${i}`,available:Object.keys(zc)})};o=l.gates;}let a=dg(t,o,i),c=Gt(s.rootDir,a);return {handled:true,text:JSON.stringify({created:true,feature:a.feature,template:i,file:c,current_stage:a.current_stage,gate_config:a.gate_config,stages:a.stages,hint:`Pipeline '${a.feature}' started at 'specify' stage. Create your spec, then call paradigm_pipeline_advance to move to 'plan'.`},null,2)}}case "paradigm_pipeline_status":{let t=e.feature;if(t){let r=Jt(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=Bc(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=Jt(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=pg(o);return r.stages[o].status="approved",r.stages[o].approved_by=i,r.stages[o].approved_at=new Date().toISOString(),a==="auto"&&(r.stages[o].auto_passed_at=new Date().toISOString()),c?(r.current_stage=c,r.stages[c].status="in-progress",Gt(s.rootDir,r),{handled:true,text:JSON.stringify({advanced:true,from:o,to:c,gate_mode:a,approved_by:i,pipeline:{feature:r.feature,current_stage:r.current_stage,stages:r.stages}},null,2)}):(Gt(s.rootDir,r),Vc(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=Jt(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"]})}:(Gt(s.rootDir,o),{handled:true,text:JSON.stringify({configured:true,feature:o.feature,changes:a,reason:r,gate_config:o.gate_config},null,2)})}case "paradigm_pipeline_escalate":{let t=e.feature,i=e.stage,r=e.question,o=e.options,a=e.context,c=Jt(s.rootDir,t);return c?(c.stages[i].status="blocked",c.stages[i].block_reason=r,Gt(s.rootDir,c),{handled:true,text:JSON.stringify({escalated:true,feature:c.feature,stage:i,question:r,options:o,context:a||{},current_gate:c.gate_config[i],instruction:"This pipeline stage requires user input. Present the question and options to the user, then use paradigm_pipeline_advance or paradigm_pipeline_configure based on their response."},null,2)}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${t}`})}}case "paradigm_pipeline_abort":{let t=e.feature,i=Jt(s.rootDir,t);return i?(Vc(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=Bc(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 ug=F.join(ga.homedir(),".conductor"),ft=F.join(ug,"sessions");function Xc(){O.existsSync(ft)||O.mkdirSync(ft,{recursive:true});}function si(n){Xc();let e={...n,registeredAt:new Date().toISOString()},s=F.join(ft,`${n.pid}.json`);return O.writeFileSync(s,JSON.stringify(e,null,2),"utf-8"),e}function Gn(n){let e=F.join(ft,`${n}.json`);return O.existsSync(e)?(O.unlinkSync(e),true):false}function ii(){Xc();let n=O.readdirSync(ft).filter(s=>s.endsWith(".json")),e=[];for(let s of n)try{let t=O.readFileSync(F.join(ft,s),"utf-8"),i=JSON.parse(t);e.push(i);}catch{}return e}function Zc(){let n=ii(),e=0;for(let s of n)gg(s.pid)||(Gn(s.pid),e++);return e}function gg(n){try{return process.kill(n,0),!0}catch{return false}}function ri(){try{return execSync(`osascript -e '
|
|
785
808
|
tell application "System Events"
|
|
786
809
|
set frontApp to first application process whose frontmost is true
|
|
787
810
|
return bundle identifier of frontApp
|
|
@@ -792,37 +815,37 @@ This session is no longer visible in the Conductor overlay.`,handled:true}:{text
|
|
|
792
815
|
Use paradigm_conductor_register or /conduct to register.`,handled:true};let i=[`${t.length} session(s) registered with Conductor:
|
|
793
816
|
`];for(let r of t){let o=[` PID ${r.pid}`];r.label&&o.push(`"${r.label}"`),o.push(`\u2014 ${r.projectDir}`),r.branch&&o.push(`(${r.branch})`),i.push(o.join(" "));}return e.clean&&i.push(`
|
|
794
817
|
(Stale sessions cleaned)`),{text:i.join(`
|
|
795
|
-
`),handled:true}}default:return {text:"",handled:false}}}function il(){return [{name:"paradigm_symphony_peek",description:"Ultra-cheap inbox check \u2014 file stat only, no parsing. Returns { hasNew: true/false }. Use with /loop 10s for near-free monitoring. When hasNew is true, call paradigm_symphony_poll to read messages. ~15 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",description:"Short status blurb (same as poll). Updates heartbeat."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_poll",description:"Read inbox notes and process them. Call when paradigm_symphony_peek returns hasNew: true, or directly via /loop for continuous messaging. Returns unread notes formatted as markdown with thread context and suggested actions. Updates heartbeat and optional status blurb. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",description:'Short status blurb describing what you are currently working on (e.g., "Implementing auth middleware \u2014 3 files modified"). Visible to humans and other agents in the Network view.'}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_send",description:"Send a note to other agents or broadcast. Auto-creates thread if no threadRoot provided. Supports intents: question, context, proposal, decision, action, etc. ~100 tokens.",inputSchema:{type:"object",properties:{intent:{type:"string",enum:["question","context","clarification","proposal","verification","action","decision","alert","approval","rejection","reference","handoff","task","task-ack","progress","approval-request","approval-response","task-complete","task-failed"],description:"Message intent (what kind of message this is). Task protocol intents: task (assignment), task-ack, progress, approval-request, approval-response, task-complete, task-failed."},text:{type:"string",description:"Message text content"},parentId:{type:"string",description:"ID of message being replied to"},threadRoot:{type:"string",description:"Thread ID to post in (auto-created if omitted)"},recipients:{type:"array",items:{type:"string"},description:"Agent IDs to send to (omit for broadcast)"},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols referenced (e.g., ["#auth-service", "$login-flow"])'},diff:{type:"string",description:"Code diff to include with the message"},decision:{type:"string",description:"Decision text to record (for intent=decision)"}},required:["intent","text"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_status",description:"Show Symphony network status: linked agents (with awake/asleep detection), active threads, unread count, pending file requests. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_thread",description:"Get full thread context: all notes in order, participants, extracted decisions, and referenced symbols. ~200 tokens.",inputSchema:{type:"object",properties:{threadId:{type:"string",description:"Thread ID (thr-XXXXXXXX format)"},depth:{type:"number",description:"Maximum messages to return (default: 50)"}},required:["threadId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_request_file",description:"Request a file from another agent's project. Human approval required (unless auto-approved in trust config). Files matching hard-deny patterns (.env, *.key, etc.) are always blocked. ~100 tokens.",inputSchema:{type:"object",properties:{filePath:{type:"string",description:'Relative file path to request (e.g., "src/auth/middleware.ts")'},from:{type:"string",description:'Agent ID to request file from (e.g., "backend/core")'},reason:{type:"string",description:"Why this file is needed"},snippet:{type:"string",description:'Specific function or line range needed (e.g., "validateToken function" or "lines 50-100")'}},required:["filePath","from","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_approve_file",description:'Approve or deny a pending file request. Use action "approve" to send file, "deny" to reject, or "approve-redacted" to send with secrets stripped. ~100 tokens.',inputSchema:{type:"object",properties:{requestId:{type:"string",description:"File request ID (freq-XXXXXXXX format)"},action:{type:"string",enum:["approve","deny","approve-redacted"],description:"Approve, deny, or approve with redaction"},reason:{type:"string",description:"Reason for denial (required for deny action)"}},required:["requestId","action"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function rl(n,e,s){let t=l$2(s.rootDir);switch(t||(t=h$4(s.rootDir)),n){case "paradigm_symphony_peek":{let i=e.status;m$2(t.id,i);let{hasNew:r}=q$2(t.id),o=r?K$1("pending").length:0;return {handled:true,text:JSON.stringify(r?{hasNew:true,pendingFileRequests:o,action:"call paradigm_symphony_poll to read"}:{hasNew:false})}}case "paradigm_symphony_poll":{k$2(),P$1();let i=e.status;m$2(t.id,i);let r=t$3(t.id);if(r.length>0){let c=r[r.length-1].id;w(t.id,c),r$1(t.id);}y$1(t.id);let o=K$1("pending");return r.length===0&&o.length===0?{handled:true,text:JSON.stringify({messages:0,note:"No new notes. Score is quiet.",identity:t.id})}:{handled:true,text:
|
|
818
|
+
`),handled:true}}default:return {text:"",handled:false}}}function il(){return [{name:"paradigm_symphony_peek",description:"Ultra-cheap inbox check \u2014 file stat only, no parsing. Returns { hasNew: true/false }. Use with /loop 10s for near-free monitoring. When hasNew is true, call paradigm_symphony_poll to read messages. ~15 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",description:"Short status blurb (same as poll). Updates heartbeat."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_poll",description:"Read inbox notes and process them. Call when paradigm_symphony_peek returns hasNew: true, or directly via /loop for continuous messaging. Returns unread notes formatted as markdown with thread context and suggested actions. Updates heartbeat and optional status blurb. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",description:'Short status blurb describing what you are currently working on (e.g., "Implementing auth middleware \u2014 3 files modified"). Visible to humans and other agents in the Network view.'}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_send",description:"Send a note to other agents or broadcast. Auto-creates thread if no threadRoot provided. Supports intents: question, context, proposal, decision, action, etc. ~100 tokens.",inputSchema:{type:"object",properties:{intent:{type:"string",enum:["question","context","clarification","proposal","verification","action","decision","alert","approval","rejection","reference","handoff","task","task-ack","progress","approval-request","approval-response","task-complete","task-failed"],description:"Message intent (what kind of message this is). Task protocol intents: task (assignment), task-ack, progress, approval-request, approval-response, task-complete, task-failed."},text:{type:"string",description:"Message text content"},parentId:{type:"string",description:"ID of message being replied to"},threadRoot:{type:"string",description:"Thread ID to post in (auto-created if omitted)"},recipients:{type:"array",items:{type:"string"},description:"Agent IDs to send to (omit for broadcast)"},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols referenced (e.g., ["#auth-service", "$login-flow"])'},diff:{type:"string",description:"Code diff to include with the message"},decision:{type:"string",description:"Decision text to record (for intent=decision)"}},required:["intent","text"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_status",description:"Show Symphony network status: linked agents (with awake/asleep detection), active threads, unread count, pending file requests. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_thread",description:"Get full thread context: all notes in order, participants, extracted decisions, and referenced symbols. ~200 tokens.",inputSchema:{type:"object",properties:{threadId:{type:"string",description:"Thread ID (thr-XXXXXXXX format)"},depth:{type:"number",description:"Maximum messages to return (default: 50)"}},required:["threadId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_request_file",description:"Request a file from another agent's project. Human approval required (unless auto-approved in trust config). Files matching hard-deny patterns (.env, *.key, etc.) are always blocked. ~100 tokens.",inputSchema:{type:"object",properties:{filePath:{type:"string",description:'Relative file path to request (e.g., "src/auth/middleware.ts")'},from:{type:"string",description:'Agent ID to request file from (e.g., "backend/core")'},reason:{type:"string",description:"Why this file is needed"},snippet:{type:"string",description:'Specific function or line range needed (e.g., "validateToken function" or "lines 50-100")'}},required:["filePath","from","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_approve_file",description:'Approve or deny a pending file request. Use action "approve" to send file, "deny" to reject, or "approve-redacted" to send with secrets stripped. ~100 tokens.',inputSchema:{type:"object",properties:{requestId:{type:"string",description:"File request ID (freq-XXXXXXXX format)"},action:{type:"string",enum:["approve","deny","approve-redacted"],description:"Approve, deny, or approve with redaction"},reason:{type:"string",description:"Reason for denial (required for deny action)"}},required:["requestId","action"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function rl(n,e,s){let t=l$2(s.rootDir);switch(t||(t=h$4(s.rootDir)),n){case "paradigm_symphony_peek":{let i=e.status;m$2(t.id,i);let{hasNew:r}=q$2(t.id),o=r?K$1("pending").length:0;return {handled:true,text:JSON.stringify(r?{hasNew:true,pendingFileRequests:o,action:"call paradigm_symphony_poll to read"}:{hasNew:false})}}case "paradigm_symphony_poll":{k$2(),P$1();let i=e.status;m$2(t.id,i);let r=t$3(t.id);if(r.length>0){let c=r[r.length-1].id;w(t.id,c),r$1(t.id);}y$1(t.id);let o=K$1("pending");return r.length===0&&o.length===0?{handled:true,text:JSON.stringify({messages:0,note:"No new notes. Score is quiet.",identity:t.id})}:{handled:true,text:fg(r,o)}}case "paradigm_symphony_send":{let i=e.intent,r=e.text,o=e.parentId,a=e.threadRoot,c=e.recipients,l=e.symbols,d=e.diff,p=e.decision,u=false;if(!a&&!o){let f=r.length>60?r.slice(0,60)+"...":r;a=z(f,zt(t)).id,u=true;}let g;if(c&&c.length>0){let f=j$4();g=c.map(b=>{let h=f.find(w=>w.id===b);return h?zt(h):{id:b,name:b,type:"agent"}});}let m=F$1({sender:zt(t),recipients:g,intent:i,text:r,parentId:o,threadRoot:a,symbols:l,diff:d,decision:p}),y=G(m);if(vg(m).catch(()=>{}),u&&a){({timestamp:m.timestamp,sender:m.sender,content:{text:`Thread created: ${m.content.text.slice(0,60)}`}});fetch(`${ai}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:"thread:created",category:"lifecycle",timestamp:m.timestamp,scopeValue:a,service:m.sender.project||"symphony",severity:"info",data:{topic:m.content.text.slice(0,60),initiator:m.sender.name,threadId:a}})}).catch(()=>{});}return {handled:true,text:JSON.stringify({sent:true,messageId:m.id,threadId:a,threadCreated:u,deliveredTo:y,intent:i})}}case "paradigm_symphony_status":{k$2();let i=j$4(),r=B("active"),o=t$3(t.id),a=K$1("pending"),c=[];try{let{loadPeers:l}=await import('./symphony-peers-U4KHMKGI.js');c=l().filter(p=>!p.revoked).map(p=>({id:p.id,address:p.address,agents:p.agents?.length??0,lastSeen:p.lastSeen}));}catch{}return {handled:true,text:JSON.stringify({identity:{id:t.id,project:t.project,role:t.role},agents:i.map(l=>({id:l.id,name:l.name,project:l.project,role:l.role,status:o$3(l)?"asleep":"awake",lastPoll:l.lastPoll,statusBlurb:l.statusBlurb})),peers:c,activeThreads:r.map(l=>({id:l.id,topic:l.topic,participants:l.participants.length,messageCount:l.messageCount,lastActivity:l.lastActivity})),unreadCount:o.length,pendingFileRequests:a.length},null,2)}}case "paradigm_symphony_thread":{let i=e.threadId,r=e.depth||50,o=A$1(i);if(!o)return {handled:true,text:JSON.stringify({error:`Thread not found: ${i}`})};let a=E(i).slice(0,r),c=[],l=new Set,d=new Set;for(let p of a){p.content.decision&&c.push(p.content.decision),p.intent==="decision"&&p.content.text&&c.push(p.content.text);for(let u of p.symbols)l.add(u);if(p.attachments)for(let u of p.attachments)u.type==="file"&&d.add(u.name);}return {handled:true,text:JSON.stringify({thread:{id:o.id,topic:o.topic,status:o.status,createdAt:o.createdAt,decision:o.decision},participants:o.participants,messages:a.map(p=>({id:p.id,sender:p.sender.name,intent:p.intent,text:p.content.text,timestamp:p.timestamp,symbols:p.symbols,hasDiff:!!p.content.diff,hasDecision:!!p.content.decision})),decisions:c,symbolsDiscussed:[...l],filesReferenced:[...d]},null,2)}}case "paradigm_symphony_request_file":{let i=e.filePath,r=e.from,o=e.reason,a=e.snippet,c=H$1();if(N$1(i,c))return {handled:true,text:JSON.stringify({error:`File path "${i}" is on the hard-deny list and cannot be requested.`,deniedPatterns:c.defaults.neverApprove})};let l=I$1({filePath:i,requester:zt(t),reason:o,snippet:a,threadRoot:void 0}),d=F$1({sender:zt(t),recipients:[{id:r,name:r,type:"agent"}],intent:"fileRequest",text:`Requesting file: ${i}
|
|
796
819
|
Reason: ${o}${a?`
|
|
797
|
-
Snippet: ${a}`:""}`,symbols:[]});return G(d),{handled:true,text:JSON.stringify({requestId:l.request.requestId,status:"pending",filePath:i,from:r,message:`File request created. The owning agent's human must approve via "paradigm symphony approve ${l.request.requestId}" or "paradigm_symphony_approve_file".`})}}case "paradigm_symphony_approve_file":{let i=e.requestId,r=e.action,o=e.reason;if(r==="deny"){let l=M$2(i,o);return {handled:true,text:JSON.stringify({success:l,requestId:i,action:"denied",reason:o||"No reason provided"})}}let a=r==="approve-redacted",c=L$1(i,s.rootDir,a);return c.success?{handled:true,text:JSON.stringify({success:true,requestId:i,action:a?"approved-redacted":"approved",filePath:c.delivery?.filePath,size:c.delivery?.size,hash:c.delivery?.hash})}:{handled:true,text:JSON.stringify({success:false,requestId:i,error:c.error})}}default:return {handled:false,text:""}}}function zt(n){return {id:n.id,name:n.name,type:n.type||"agent",project:n.project,role:n.role}}function
|
|
798
|
-
`);for(let a=0;a<r.length;a++){let c=r[a],l=new Date(c.timestamp).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),d=`${c.sender.name}${c.sender.project?` (${c.sender.project})`:""}`;s.push(`### ${a+1}. ${d} \u2014 ${
|
|
820
|
+
Snippet: ${a}`:""}`,symbols:[]});return G(d),{handled:true,text:JSON.stringify({requestId:l.request.requestId,status:"pending",filePath:i,from:r,message:`File request created. The owning agent's human must approve via "paradigm symphony approve ${l.request.requestId}" or "paradigm_symphony_approve_file".`})}}case "paradigm_symphony_approve_file":{let i=e.requestId,r=e.action,o=e.reason;if(r==="deny"){let l=M$2(i,o);return {handled:true,text:JSON.stringify({success:l,requestId:i,action:"denied",reason:o||"No reason provided"})}}let a=r==="approve-redacted",c=L$1(i,s.rootDir,a);return c.success?{handled:true,text:JSON.stringify({success:true,requestId:i,action:a?"approved-redacted":"approved",filePath:c.delivery?.filePath,size:c.delivery?.size,hash:c.delivery?.hash})}:{handled:true,text:JSON.stringify({success:false,requestId:i,error:c.error})}}default:return {handled:false,text:""}}}function zt(n){return {id:n.id,name:n.name,type:n.type||"agent",project:n.project,role:n.role}}function fg(n,e){let s=[],t=new Map;for(let i of n){let r=i.threadRoot||"direct";t.has(r)||t.set(r,[]),t.get(r).push(i);}for(let[i,r]of t){let o=i;if(i!=="direct"){let a=A$1(i);a&&(o=a.topic);}s.push(`## Symphony: ${r.length} new note${r.length!==1?"s":""} in "${o}"
|
|
821
|
+
`);for(let a=0;a<r.length;a++){let c=r[a],l=new Date(c.timestamp).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),d=`${c.sender.name}${c.sender.project?` (${c.sender.project})`:""}`;s.push(`### ${a+1}. ${d} \u2014 ${hg(c.intent)} (${l})`),s.push(`> ${c.content.text.split(`
|
|
799
822
|
`).join(`
|
|
800
823
|
> `)}`),c.symbols.length>0&&s.push(`> Symbols: ${c.symbols.join(", ")}`),c.content.diff&&s.push(`
|
|
801
824
|
\`\`\`diff
|
|
802
825
|
${c.content.diff}
|
|
803
826
|
\`\`\``),c.content.decision&&s.push(`
|
|
804
|
-
**Decision:** ${c.content.decision}`);let p=
|
|
827
|
+
**Decision:** ${c.content.decision}`);let p=yg(c);p&&s.push(`
|
|
805
828
|
**Suggested action:** ${p}`),s.push("");}}if(e.length>0){s.push(`## Pending File Requests (${e.length})
|
|
806
829
|
`);for(let i of e)s.push(`- **${i.request.filePath}** from ${i.request.requester.name}: ${i.request.reason}`),s.push(` Approve: \`paradigm_symphony_approve_file({ requestId: "${i.request.requestId}", action: "approve" })\``);s.push("");}return s.join(`
|
|
807
|
-
`)}function pg(n){switch(n.intent){case "question":return 'Reply with paradigm_symphony_send using intent "context" or "clarification"';case "proposal":return 'Reply with intent "approval" or "rejection"';case "fileRequest":return "Use paradigm_symphony_approve_file to approve or deny";case "handoff":return "Review handoff context and continue the work";case "alert":return 'Investigate the alert and reply with intent "action"';case "verification":return 'Confirm with intent "approval" or clarify with "clarification"';default:return null}}function ug(n){return n.charAt(0).toUpperCase()+n.slice(1)}var ai="http://localhost:3838",sl=false;function gg(n){switch(n){case "question":return "note:question";case "context":return "note:context";case "clarification":return "note:clarification";case "proposal":return "note:proposal";case "verification":return "note:verification";case "action":return "note:action";case "decision":return "note:decision";case "alert":return "note:alert";case "approval":return "note:approval";case "rejection":return "note:rejection";case "reference":return "note:reference";case "handoff":return "note:handoff";case "fileRequest":return "file:requested";case "fileApproved":return "file:approved";case "fileDenied":return "file:denied";case "fileDelivery":return "file:delivered";default:return "note:context"}}function mg(n){if(n.startsWith("note:")){let e=n.split(":")[1];if(["question","context","clarification","verification","reference"].includes(e))return "dialogue";if(["proposal","action"].includes(e))return "action";if(["decision","approval","rejection"].includes(e))return "outcome";if(e==="alert")return "system";if(e==="handoff")return "lifecycle"}return n.startsWith("thread:")||n.startsWith("participant:")?"lifecycle":n.startsWith("file:")?"transfer":"dialogue"}async function fg(n){try{sl||(await fetch(`${ai}/api/schemas`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:"paradigm-symphony",version:"1.0.0",name:"Symphony Conversations",description:"Agent-to-agent messaging events from The Score protocol"})}).catch(()=>{}),sl=!0);let e=gg(n.intent),s=mg(e);await fetch(`${ai}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:e,category:s,timestamp:n.timestamp,scopeValue:n.threadRoot||n.id,service:n.sender.project||"symphony",severity:s==="system"?"error":s==="outcome"?"warn":"info",parentEventId:n.parentId,data:{sender:n.sender.name,senderRole:n.sender.role||"core",text:n.content.text,symbols:n.symbols,diff:n.content.diff,decision:n.content.decision,parentId:n.parentId,threadId:n.threadRoot}})});}catch{}}function ci(){let n=process.env.PARADIGM_AUTHOR;if(n)return li(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return li(e)}catch{}try{let e=ga.userInfo().username;if(e)return li(e)}catch{}return "unknown"}function li(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function di(){return new Date().toISOString().slice(0,10)}function al(){return [{name:"paradigm_university_search",description:"Search project university content by type, tag, difficulty, or symbol. Returns matching content items. ~150 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["note","policy","guide","runbook","quiz","path"],description:"Filter by content type"},tag:{type:"string",description:"Filter by tag prefix"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"],description:"Filter by difficulty level"},symbol:{type:"string",description:'Filter by Paradigm symbol (e.g., "#api-gateway")'},query:{type:"string",description:"Free-text search in title and tags"},category:{type:"string",description:'Filter by category ID (e.g., "paradigm-core", "extracurricular")'},track:{type:"string",enum:["core","extracurricular"],description:"Filter by track"},limit:{type:"number",description:"Maximum results (default: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_get",description:"Fetch a university content item by ID. Returns full content including body for notes/policies and questions for quizzes. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Content ID (e.g., "N-architecture-overview", "Q-onboarding-basics", "LP-new-engineer")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_create",description:"Create a new university content item (note, policy, quiz, or learning path). Auto-generates timestamps and resolves author. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["note","policy","guide","runbook","quiz","path"],description:"Content type to create"},title:{type:"string",description:"Content title"},body:{type:"string",description:"Markdown body for notes/policies. Quiz/path YAML content for those types."},tags:{type:"array",items:{type:"string"},description:"Tags for classification"},symbols:{type:"array",items:{type:"string"},description:"Paradigm symbols referenced by this content"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"],description:"Difficulty level (default: beginner)"},estimatedMinutes:{type:"number",description:"Estimated reading/completion time in minutes"},prerequisites:{type:"array",items:{type:"string"},description:"IDs of prerequisite content items"},category:{type:"string",description:"Category ID for the content (default: project defaultCategory)"},passThreshold:{type:"number",description:"For quizzes: pass threshold 0.0-1.0 (default: 0.7)"},questions:{type:"array",description:"For quizzes: array of {id, question, choices: {A:..., B:...}, correct, explanation?}"},ordered:{type:"boolean",description:"For learning paths: whether steps must be completed in order"},steps:{type:"array",description:"For learning paths: array of {content, required, passRequired?, note?}"}},required:["type","title"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_university_update",description:"Update an existing university content item. Specify only the fields to change. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID to update"},title:{type:"string",description:"New title"},body:{type:"string",description:"New body content"},tags:{type:"array",items:{type:"string"},description:"New tags"},symbols:{type:"array",items:{type:"string"},description:"New symbols"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"]},estimatedMinutes:{type:"number"},category:{type:"string",description:"Category ID for the content"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_university_quiz",description:"Get a quiz for taking \u2014 returns questions WITHOUT answers. Use paradigm_university_submit to submit answers. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Quiz ID (e.g., "Q-onboarding-basics")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_submit",description:"Submit quiz answers for grading. Returns score and saves diploma if passed. ~150 tokens.",inputSchema:{type:"object",properties:{quizId:{type:"string",description:"Quiz ID"},answers:{type:"object",description:'Map of question ID to answer key (e.g., {"q1": "B", "q2": "A"})'},student:{type:"string",description:"Student name (auto-resolved if omitted)"}},required:["quizId","answers"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_university_onboard",description:"Get recommended onboarding sequence for the project university. Shows learning paths, suggested content, and completion status. ~200 tokens.",inputSchema:{type:"object",properties:{student:{type:"string",description:"Student name to check completion (auto-resolved if omitted)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_diplomas",description:"List earned diplomas (PLSAT, quiz completions, path completions). ~100 tokens.",inputSchema:{type:"object",properties:{student:{type:"string",description:"Filter by student name"},type:{type:"string",enum:["plsat","quiz","path"],description:"Filter by diploma type"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_validate",description:"Validate university content integrity: schema, symbol refs, prerequisites, quiz structure. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID to validate (validates all if omitted)"},deep:{type:"boolean",description:"Enable deep cross-reference checks against scan-index (default: false)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function cl(n,e,s){if(n==="paradigm_university_search"){let t=ha$1(s.rootDir,{type:e.type,tag:e.tag,difficulty:e.difficulty,symbol:e.symbol,query:e.query,category:e.category,track:e.track,limit:e.limit}),i=JSON.stringify({count:t.length,results:t.map(r=>({id:r.id,title:r.title,type:r.type,difficulty:r.difficulty,tags:r.tags,symbols:r.symbols}))},null,2);return o(i.length,n),{handled:true,text:i}}if(n==="paradigm_university_get"){let t=e.id;if(!t)return {handled:true,text:JSON.stringify({error:"id is required"})};let i=$(s.rootDir,t);if(i){let c=JSON.stringify({id:i.frontmatter.id,title:i.frontmatter.title,type:i.frontmatter.type,author:i.frontmatter.author,created:i.frontmatter.created,updated:i.frontmatter.updated,tags:i.frontmatter.tags,symbols:i.frontmatter.symbols,difficulty:i.frontmatter.difficulty,prerequisites:i.frontmatter.prerequisites,body:i.body},null,2);return o(c.length,n),{handled:true,text:c}}let r=ba$1(s.rootDir,t);if(r){let c=JSON.stringify(r,null,2);return o(c.length,n),{handled:true,text:c}}let o$1=da$1(s.rootDir,t);if(o$1){let c=JSON.stringify(o$1,null,2);return o(c.length,n),{handled:true,text:c}}let a=JSON.stringify({error:`Content "${t}" not found`});return o(a.length,n),{handled:true,text:a}}if(n==="paradigm_university_create"){let t=e.type,i=e.title;if(!t||!i)return {handled:true,text:JSON.stringify({error:"type and title are required"})};let r=ci(),o$1=di(),a=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40);if(t==="quiz"){let g=`Q-${a}`,m={id:g,title:i,description:e.body||"",author:r,created:o$1,updated:o$1,tags:e.tags||[],symbols:e.symbols||[],difficulty:e.difficulty||"beginner",estimatedMinutes:e.estimatedMinutes,passThreshold:e.passThreshold??.7,questions:e.questions||[],...e.category?{category:e.category}:{}};ca$1(s.rootDir,m),ia$1(s.rootDir);let y=JSON.stringify({created:g,type:"quiz",file:`content/quizzes/${g}.yaml`},null,2);return o(y.length,n),{handled:true,text:y}}if(t==="path"){let g=`LP-${a}`,m={id:g,title:i,description:e.body||"",author:r,created:o$1,updated:o$1,tags:e.tags||[],ordered:e.ordered??true,steps:e.steps||[],...e.category?{category:e.category}:{}};ea$1(s.rootDir,m),ia$1(s.rootDir);let y=JSON.stringify({created:g,type:"path",file:`content/paths/${g}.yaml`},null,2);return o(y.length,n),{handled:true,text:y}}let l=`${t==="policy"?"P":"N"}-${a}`,d={id:l,title:i,type:t,author:r,created:o$1,updated:o$1,tags:e.tags||[],symbols:e.symbols||[],difficulty:e.difficulty||"beginner",estimatedMinutes:e.estimatedMinutes,prerequisites:e.prerequisites||[],...e.category?{category:e.category}:{}};aa$1(s.rootDir,d,e.body||""),ia$1(s.rootDir);let u=JSON.stringify({created:l,type:t,file:`content/${t==="policy"?"policies":"notes"}/${l}.md`},null,2);return o(u.length,n),{handled:true,text:u}}if(n==="paradigm_university_update"){let t=e.id;if(!t)return {handled:true,text:JSON.stringify({error:"id is required"})};let i=di(),r=$(s.rootDir,t);if(r){let l={...r.frontmatter};e.title&&(l.title=e.title),e.tags&&(l.tags=e.tags),e.symbols&&(l.symbols=e.symbols),e.difficulty&&(l.difficulty=e.difficulty),e.estimatedMinutes!==void 0&&(l.estimatedMinutes=e.estimatedMinutes),e.category!==void 0&&(l.category=e.category),l.updated=i;let d=e.body??r.body;aa$1(s.rootDir,l,d),ia$1(s.rootDir);let p=JSON.stringify({updated:t,type:l.type},null,2);return o(p.length,n),{handled:true,text:p}}let o$1=ba$1(s.rootDir,t);if(o$1){e.title&&(o$1.title=e.title),e.tags&&(o$1.tags=e.tags),e.symbols&&(o$1.symbols=e.symbols),e.difficulty&&(o$1.difficulty=e.difficulty),e.category!==void 0&&(o$1.category=e.category),o$1.updated=i,ca$1(s.rootDir,o$1),ia$1(s.rootDir);let l=JSON.stringify({updated:t,type:"quiz"},null,2);return o(l.length,n),{handled:true,text:l}}let a=da$1(s.rootDir,t);if(a){e.title&&(a.title=e.title),e.tags&&(a.tags=e.tags),e.category!==void 0&&(a.category=e.category),a.updated=i,ea$1(s.rootDir,a),ia$1(s.rootDir);let l=JSON.stringify({updated:t,type:"path"},null,2);return o(l.length,n),{handled:true,text:l}}let c=JSON.stringify({error:`Content "${t}" not found`});return o(c.length,n),{handled:true,text:c}}if(n==="paradigm_university_quiz"){let t=e.id,i=ba$1(s.rootDir,t);if(!i){let a=JSON.stringify({error:`Quiz "${t}" not found`});return o(a.length,n),{handled:true,text:a}}let r={id:i.id,title:i.title,description:i.description,difficulty:i.difficulty,passThreshold:i.passThreshold,questionCount:i.questions.length,questions:i.questions.map(a=>({id:a.id,question:a.question,choices:a.choices}))},o$1=JSON.stringify(r,null,2);return o(o$1.length,n),{handled:true,text:o$1}}if(n==="paradigm_university_submit"){let t=e.quizId,i=e.answers,r=e.student||ci(),o$1=ba$1(s.rootDir,t);if(!o$1){let y=JSON.stringify({error:`Quiz "${t}" not found`});return o(y.length,n),{handled:true,text:y}}let a=0,c=o$1.questions.length,l=[];for(let y of o$1.questions){let b=i[y.id]===y.correct;b&&a++,l.push({id:y.id,correct:b,...b?{}:{expected:y.correct},...y.explanation?{explanation:y.explanation}:{}});}let d=c>0?Math.round(a/c*1e4)/100:0,p=d/100>=o$1.passThreshold,u=`D-${di()}-${r}-${t.replace(/^Q-/,"")}`,g={id:u,type:"quiz",student:r,earnedAt:new Date().toISOString(),source:t,score:a,total:c,percentage:d,passed:p};ga$1(s.rootDir,g);let m=JSON.stringify({quizId:t,student:r,score:a,total:c,percentage:d,passThreshold:o$1.passThreshold*100,passed:p,diplomaId:u,feedback:l},null,2);return o(m.length,n),{handled:true,text:m}}if(n==="paradigm_university_onboard"){let t=e.student||ci(),i=_(s.rootDir),r=la$1(s.rootDir,t),o$1=JSON.stringify({university:i.branding.name,student:t,...r},null,2);return o(o$1.length,n),{handled:true,text:o$1}}if(n==="paradigm_university_diplomas"){let t=fa$1(s.rootDir,{student:e.student,type:e.type}),i=JSON.stringify({count:t.length,diplomas:t.map(r=>({id:r.id,type:r.type,student:r.student,source:r.source,score:r.score,total:r.total,percentage:r.percentage,passed:r.passed,earnedAt:r.earnedAt}))},null,2);return o(i.length,n),{handled:true,text:i}}if(n==="paradigm_university_validate"){let t=ja$1(s.rootDir,{id:e.id,deep:e.deep}),i=JSON.stringify(t,null,2);return o(i.length,n),{handled:true,text:i}}return {handled:false,text:""}}function hg(n){try{let e=F.join(n,".paradigm","config.yaml");if(O.existsSync(e)){let t=Z.load(O.readFileSync(e,"utf-8")).platform;if(t?.port&&typeof t.port=="number")return t.port}}catch{}return 3850}function bg(n){try{let e=F.join(n,".paradigm","config.yaml");if(O.existsSync(e)){let s=Z.load(O.readFileSync(e,"utf-8")),t=s.project||F.basename(n),i=s.role||"core";return `${t}/${i}`}}catch{}return `${F.basename(n)}/core`}async function wt(n,e,s){let t=hg(n),i=bg(n),r=`http://localhost:${t}/api/platform/agent-command`;try{let o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:e,agentId:i,payload:s}),signal:AbortSignal.timeout(5e3)});if(!o.ok){let c=await o.text();return {ok:!1,error:`HTTP ${o.status}: ${c}`}}return {ok:!0,data:await o.json()}}catch(o){return {ok:false,error:`Platform server unreachable (${o instanceof Error?o.message:String(o)}). Is \`paradigm serve\` running?`}}}function ll(){return [{name:"paradigm_platform_navigate",description:"Navigate the Platform UI to a section, select a symbol, or open a lore entry. The browser updates in real-time. If the user is actively interacting, shows a prompt instead of auto-navigating. ~100 tokens.",inputSchema:{type:"object",properties:{section:{type:"string",enum:["overview","lore","graph","sentinel","university","symphony"],description:"Section to navigate to"},symbol:{type:"string",description:'Symbol to select (e.g., "#payment-service")'},loreId:{type:"string",description:"Lore entry ID to open in lore section"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_highlight",description:"Temporarily highlight symbols in the Platform UI with a pulsing glow. Auto-expires after duration. Use to draw attention to specific components during explanations. ~100 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbol IDs to highlight (e.g., ["#payment-service", "#api-gateway"])'},color:{type:"string",description:"Highlight color (CSS color, defaults to agent color)"},duration:{type:"number",description:"Duration in milliseconds (default: 5000)"},pulse:{type:"boolean",description:"Whether to pulse the highlight (default: true)"},label:{type:"string",description:"Optional label shown near highlighted symbols"}},required:["symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_annotate",description:"Show a toast notification, callout on a graph node, or badge in the Platform UI. Use for communicating decisions, warnings, or context to the user visually. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["toast","callout","badge"],description:"Annotation type: toast (notification), callout (floating note on graph node), badge (icon on symbol)"},message:{type:"string",description:"Annotation message text"},symbol:{type:"string",description:"Symbol to attach callout/badge to (required for callout/badge)"},severity:{type:"string",enum:["info","warning","error","success"],description:"Visual severity (default: info)"},duration:{type:"number",description:"Auto-dismiss duration in milliseconds (default: 6000, 0 = persistent)"}},required:["type","message"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_observe",description:"Read the current Platform UI state: what section the user is viewing, what symbol is selected, theme, connected agents, and active highlights/annotations. ~150 tokens.",inputSchema:{type:"object",properties:{detail:{type:"string",enum:["summary","full"],description:"Level of detail (default: summary)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_platform_clear",description:"Remove agent highlights, annotations, or all agent effects from the Platform UI. ~50 tokens.",inputSchema:{type:"object",properties:{target:{type:"string",enum:["highlights","annotations","all"],description:"What to clear (default: all)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function dl(n,e,s){switch(n){case "paradigm_platform_navigate":{let t=await wt(s.projectDir,"navigate",{section:e.section,symbol:e.symbol,loreId:e.loreId});if(!t.ok)return {handled:true,text:`**Navigate failed:** ${t.error}`};let i=t.data;if(i.navigated){let r=[];i.section&&r.push(`section: **${i.section}**`),i.symbol&&r.push(`symbol: **${i.symbol}**`);let o=i.userActive?" (user was active \u2014 shown as prompt)":"";return {handled:true,text:`Navigated to ${r.join(", ")}${o}`}}return {handled:true,text:`Navigation skipped: ${i.reason}`}}case "paradigm_platform_highlight":{let t=await wt(s.projectDir,"highlight",{symbols:e.symbols,color:e.color,duration:e.duration,pulse:e.pulse,label:e.label});if(!t.ok)return {handled:true,text:`**Highlight failed:** ${t.error}`};let i=t.data;return i.highlighted?{handled:true,text:`Highlighted **${i.count}** symbol(s)${e.label?` with label "${e.label}"`:""}`}:{handled:true,text:`Highlight skipped: ${i.reason}`}}case "paradigm_platform_annotate":{let t=await wt(s.projectDir,"annotate",{type:e.type,message:e.message,symbol:e.symbol,severity:e.severity,duration:e.duration});if(!t.ok)return {handled:true,text:`**Annotate failed:** ${t.error}`};let i=t.data;return i.annotated?{handled:true,text:`Created ${e.type} annotation: "${e.message}"`}:{handled:true,text:`Annotation skipped: ${i.reason}`}}case "paradigm_platform_observe":{let t=await wt(s.projectDir,"observe",{detail:e.detail});if(!t.ok)return {handled:true,text:`**Observe failed:** ${t.error}`};let i=t.data,r=i.state,o=[`## Platform UI State
|
|
830
|
+
`)}function yg(n){switch(n.intent){case "question":return 'Reply with paradigm_symphony_send using intent "context" or "clarification"';case "proposal":return 'Reply with intent "approval" or "rejection"';case "fileRequest":return "Use paradigm_symphony_approve_file to approve or deny";case "handoff":return "Review handoff context and continue the work";case "alert":return 'Investigate the alert and reply with intent "action"';case "verification":return 'Confirm with intent "approval" or clarify with "clarification"';default:return null}}function hg(n){return n.charAt(0).toUpperCase()+n.slice(1)}var ai="http://localhost:3838",sl=false;function bg(n){switch(n){case "question":return "note:question";case "context":return "note:context";case "clarification":return "note:clarification";case "proposal":return "note:proposal";case "verification":return "note:verification";case "action":return "note:action";case "decision":return "note:decision";case "alert":return "note:alert";case "approval":return "note:approval";case "rejection":return "note:rejection";case "reference":return "note:reference";case "handoff":return "note:handoff";case "fileRequest":return "file:requested";case "fileApproved":return "file:approved";case "fileDenied":return "file:denied";case "fileDelivery":return "file:delivered";default:return "note:context"}}function wg(n){if(n.startsWith("note:")){let e=n.split(":")[1];if(["question","context","clarification","verification","reference"].includes(e))return "dialogue";if(["proposal","action"].includes(e))return "action";if(["decision","approval","rejection"].includes(e))return "outcome";if(e==="alert")return "system";if(e==="handoff")return "lifecycle"}return n.startsWith("thread:")||n.startsWith("participant:")?"lifecycle":n.startsWith("file:")?"transfer":"dialogue"}async function vg(n){try{sl||(await fetch(`${ai}/api/schemas`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:"paradigm-symphony",version:"1.0.0",name:"Symphony Conversations",description:"Agent-to-agent messaging events from The Score protocol"})}).catch(()=>{}),sl=!0);let e=bg(n.intent),s=wg(e);await fetch(`${ai}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:e,category:s,timestamp:n.timestamp,scopeValue:n.threadRoot||n.id,service:n.sender.project||"symphony",severity:s==="system"?"error":s==="outcome"?"warn":"info",parentEventId:n.parentId,data:{sender:n.sender.name,senderRole:n.sender.role||"core",text:n.content.text,symbols:n.symbols,diff:n.content.diff,decision:n.content.decision,parentId:n.parentId,threadId:n.threadRoot}})});}catch{}}function ci(){let n=process.env.PARADIGM_AUTHOR;if(n)return li(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return li(e)}catch{}try{let e=ga.userInfo().username;if(e)return li(e)}catch{}return "unknown"}function li(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function di(){return new Date().toISOString().slice(0,10)}function al(){return [{name:"paradigm_university_search",description:"Search project university content by type, tag, difficulty, or symbol. Returns matching content items. ~150 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["note","policy","guide","runbook","quiz","path"],description:"Filter by content type"},tag:{type:"string",description:"Filter by tag prefix"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"],description:"Filter by difficulty level"},symbol:{type:"string",description:'Filter by Paradigm symbol (e.g., "#api-gateway")'},query:{type:"string",description:"Free-text search in title and tags"},category:{type:"string",description:'Filter by category ID (e.g., "paradigm-core", "extracurricular")'},track:{type:"string",enum:["core","extracurricular"],description:"Filter by track"},limit:{type:"number",description:"Maximum results (default: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_get",description:"Fetch a university content item by ID. Returns full content including body for notes/policies and questions for quizzes. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Content ID (e.g., "N-architecture-overview", "Q-onboarding-basics", "LP-new-engineer")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_create",description:"Create a new university content item (note, policy, quiz, or learning path). Auto-generates timestamps and resolves author. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["note","policy","guide","runbook","quiz","path"],description:"Content type to create"},title:{type:"string",description:"Content title"},body:{type:"string",description:"Markdown body for notes/policies. Quiz/path YAML content for those types."},tags:{type:"array",items:{type:"string"},description:"Tags for classification"},symbols:{type:"array",items:{type:"string"},description:"Paradigm symbols referenced by this content"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"],description:"Difficulty level (default: beginner)"},estimatedMinutes:{type:"number",description:"Estimated reading/completion time in minutes"},prerequisites:{type:"array",items:{type:"string"},description:"IDs of prerequisite content items"},category:{type:"string",description:"Category ID for the content (default: project defaultCategory)"},passThreshold:{type:"number",description:"For quizzes: pass threshold 0.0-1.0 (default: 0.7)"},questions:{type:"array",description:"For quizzes: array of {id, question, choices: {A:..., B:...}, correct, explanation?}"},ordered:{type:"boolean",description:"For learning paths: whether steps must be completed in order"},steps:{type:"array",description:"For learning paths: array of {content, required, passRequired?, note?}"}},required:["type","title"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_university_update",description:"Update an existing university content item. Specify only the fields to change. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID to update"},title:{type:"string",description:"New title"},body:{type:"string",description:"New body content"},tags:{type:"array",items:{type:"string"},description:"New tags"},symbols:{type:"array",items:{type:"string"},description:"New symbols"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"]},estimatedMinutes:{type:"number"},category:{type:"string",description:"Category ID for the content"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_university_quiz",description:"Get a quiz for taking \u2014 returns questions WITHOUT answers. Use paradigm_university_submit to submit answers. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Quiz ID (e.g., "Q-onboarding-basics")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_submit",description:"Submit quiz answers for grading. Returns score and saves diploma if passed. ~150 tokens.",inputSchema:{type:"object",properties:{quizId:{type:"string",description:"Quiz ID"},answers:{type:"object",description:'Map of question ID to answer key (e.g., {"q1": "B", "q2": "A"})'},student:{type:"string",description:"Student name (auto-resolved if omitted)"}},required:["quizId","answers"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_university_onboard",description:"Get recommended onboarding sequence for the project university. Shows learning paths, suggested content, and completion status. ~200 tokens.",inputSchema:{type:"object",properties:{student:{type:"string",description:"Student name to check completion (auto-resolved if omitted)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_diplomas",description:"List earned diplomas (PLSAT, quiz completions, path completions). ~100 tokens.",inputSchema:{type:"object",properties:{student:{type:"string",description:"Filter by student name"},type:{type:"string",enum:["plsat","quiz","path"],description:"Filter by diploma type"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_validate",description:"Validate university content integrity: schema, symbol refs, prerequisites, quiz structure. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID to validate (validates all if omitted)"},deep:{type:"boolean",description:"Enable deep cross-reference checks against scan-index (default: false)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function cl(n,e,s){if(n==="paradigm_university_search"){let t=ha$1(s.rootDir,{type:e.type,tag:e.tag,difficulty:e.difficulty,symbol:e.symbol,query:e.query,category:e.category,track:e.track,limit:e.limit}),i=JSON.stringify({count:t.length,results:t.map(r=>({id:r.id,title:r.title,type:r.type,difficulty:r.difficulty,tags:r.tags,symbols:r.symbols}))},null,2);return o(i.length,n),{handled:true,text:i}}if(n==="paradigm_university_get"){let t=e.id;if(!t)return {handled:true,text:JSON.stringify({error:"id is required"})};let i=$(s.rootDir,t);if(i){let c=JSON.stringify({id:i.frontmatter.id,title:i.frontmatter.title,type:i.frontmatter.type,author:i.frontmatter.author,created:i.frontmatter.created,updated:i.frontmatter.updated,tags:i.frontmatter.tags,symbols:i.frontmatter.symbols,difficulty:i.frontmatter.difficulty,prerequisites:i.frontmatter.prerequisites,body:i.body},null,2);return o(c.length,n),{handled:true,text:c}}let r=ba$1(s.rootDir,t);if(r){let c=JSON.stringify(r,null,2);return o(c.length,n),{handled:true,text:c}}let o$1=da$1(s.rootDir,t);if(o$1){let c=JSON.stringify(o$1,null,2);return o(c.length,n),{handled:true,text:c}}let a=JSON.stringify({error:`Content "${t}" not found`});return o(a.length,n),{handled:true,text:a}}if(n==="paradigm_university_create"){let t=e.type,i=e.title;if(!t||!i)return {handled:true,text:JSON.stringify({error:"type and title are required"})};let r=ci(),o$1=di(),a=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40);if(t==="quiz"){let g=`Q-${a}`,m={id:g,title:i,description:e.body||"",author:r,created:o$1,updated:o$1,tags:e.tags||[],symbols:e.symbols||[],difficulty:e.difficulty||"beginner",estimatedMinutes:e.estimatedMinutes,passThreshold:e.passThreshold??.7,questions:e.questions||[],...e.category?{category:e.category}:{}};ca$1(s.rootDir,m),ia$1(s.rootDir);let y=JSON.stringify({created:g,type:"quiz",file:`content/quizzes/${g}.yaml`},null,2);return o(y.length,n),{handled:true,text:y}}if(t==="path"){let g=`LP-${a}`,m={id:g,title:i,description:e.body||"",author:r,created:o$1,updated:o$1,tags:e.tags||[],ordered:e.ordered??true,steps:e.steps||[],...e.category?{category:e.category}:{}};ea$1(s.rootDir,m),ia$1(s.rootDir);let y=JSON.stringify({created:g,type:"path",file:`content/paths/${g}.yaml`},null,2);return o(y.length,n),{handled:true,text:y}}let l=`${t==="policy"?"P":"N"}-${a}`,d={id:l,title:i,type:t,author:r,created:o$1,updated:o$1,tags:e.tags||[],symbols:e.symbols||[],difficulty:e.difficulty||"beginner",estimatedMinutes:e.estimatedMinutes,prerequisites:e.prerequisites||[],...e.category?{category:e.category}:{}};aa$1(s.rootDir,d,e.body||""),ia$1(s.rootDir);let u=JSON.stringify({created:l,type:t,file:`content/${t==="policy"?"policies":"notes"}/${l}.md`},null,2);return o(u.length,n),{handled:true,text:u}}if(n==="paradigm_university_update"){let t=e.id;if(!t)return {handled:true,text:JSON.stringify({error:"id is required"})};let i=di(),r=$(s.rootDir,t);if(r){let l={...r.frontmatter};e.title&&(l.title=e.title),e.tags&&(l.tags=e.tags),e.symbols&&(l.symbols=e.symbols),e.difficulty&&(l.difficulty=e.difficulty),e.estimatedMinutes!==void 0&&(l.estimatedMinutes=e.estimatedMinutes),e.category!==void 0&&(l.category=e.category),l.updated=i;let d=e.body??r.body;aa$1(s.rootDir,l,d),ia$1(s.rootDir);let p=JSON.stringify({updated:t,type:l.type},null,2);return o(p.length,n),{handled:true,text:p}}let o$1=ba$1(s.rootDir,t);if(o$1){e.title&&(o$1.title=e.title),e.tags&&(o$1.tags=e.tags),e.symbols&&(o$1.symbols=e.symbols),e.difficulty&&(o$1.difficulty=e.difficulty),e.category!==void 0&&(o$1.category=e.category),o$1.updated=i,ca$1(s.rootDir,o$1),ia$1(s.rootDir);let l=JSON.stringify({updated:t,type:"quiz"},null,2);return o(l.length,n),{handled:true,text:l}}let a=da$1(s.rootDir,t);if(a){e.title&&(a.title=e.title),e.tags&&(a.tags=e.tags),e.category!==void 0&&(a.category=e.category),a.updated=i,ea$1(s.rootDir,a),ia$1(s.rootDir);let l=JSON.stringify({updated:t,type:"path"},null,2);return o(l.length,n),{handled:true,text:l}}let c=JSON.stringify({error:`Content "${t}" not found`});return o(c.length,n),{handled:true,text:c}}if(n==="paradigm_university_quiz"){let t=e.id,i=ba$1(s.rootDir,t);if(!i){let a=JSON.stringify({error:`Quiz "${t}" not found`});return o(a.length,n),{handled:true,text:a}}let r={id:i.id,title:i.title,description:i.description,difficulty:i.difficulty,passThreshold:i.passThreshold,questionCount:i.questions.length,questions:i.questions.map(a=>({id:a.id,question:a.question,choices:a.choices}))},o$1=JSON.stringify(r,null,2);return o(o$1.length,n),{handled:true,text:o$1}}if(n==="paradigm_university_submit"){let t=e.quizId,i=e.answers,r=e.student||ci(),o$1=ba$1(s.rootDir,t);if(!o$1){let y=JSON.stringify({error:`Quiz "${t}" not found`});return o(y.length,n),{handled:true,text:y}}let a=0,c=o$1.questions.length,l=[];for(let y of o$1.questions){let b=i[y.id]===y.correct;b&&a++,l.push({id:y.id,correct:b,...b?{}:{expected:y.correct},...y.explanation?{explanation:y.explanation}:{}});}let d=c>0?Math.round(a/c*1e4)/100:0,p=d/100>=o$1.passThreshold,u=`D-${di()}-${r}-${t.replace(/^Q-/,"")}`,g={id:u,type:"quiz",student:r,earnedAt:new Date().toISOString(),source:t,score:a,total:c,percentage:d,passed:p};ga$1(s.rootDir,g);let m=JSON.stringify({quizId:t,student:r,score:a,total:c,percentage:d,passThreshold:o$1.passThreshold*100,passed:p,diplomaId:u,feedback:l},null,2);return o(m.length,n),{handled:true,text:m}}if(n==="paradigm_university_onboard"){let t=e.student||ci(),i=_(s.rootDir),r=la$1(s.rootDir,t),o$1=JSON.stringify({university:i.branding.name,student:t,...r},null,2);return o(o$1.length,n),{handled:true,text:o$1}}if(n==="paradigm_university_diplomas"){let t=fa$1(s.rootDir,{student:e.student,type:e.type}),i=JSON.stringify({count:t.length,diplomas:t.map(r=>({id:r.id,type:r.type,student:r.student,source:r.source,score:r.score,total:r.total,percentage:r.percentage,passed:r.passed,earnedAt:r.earnedAt}))},null,2);return o(i.length,n),{handled:true,text:i}}if(n==="paradigm_university_validate"){let t=ja$1(s.rootDir,{id:e.id,deep:e.deep}),i=JSON.stringify(t,null,2);return o(i.length,n),{handled:true,text:i}}return {handled:false,text:""}}function kg(n){try{let e=F.join(n,".paradigm","config.yaml");if(O.existsSync(e)){let t=Z.load(O.readFileSync(e,"utf-8")).platform;if(t?.port&&typeof t.port=="number")return t.port}}catch{}return 3850}function Sg(n){try{let e=F.join(n,".paradigm","config.yaml");if(O.existsSync(e)){let s=Z.load(O.readFileSync(e,"utf-8")),t=s.project||F.basename(n),i=s.role||"core";return `${t}/${i}`}}catch{}return `${F.basename(n)}/core`}async function wt(n,e,s){let t=kg(n),i=Sg(n),r=`http://localhost:${t}/api/platform/agent-command`;try{let o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:e,agentId:i,payload:s}),signal:AbortSignal.timeout(5e3)});if(!o.ok){let c=await o.text();return {ok:!1,error:`HTTP ${o.status}: ${c}`}}return {ok:!0,data:await o.json()}}catch(o){return {ok:false,error:`Platform server unreachable (${o instanceof Error?o.message:String(o)}). Is \`paradigm serve\` running?`}}}function ll(){return [{name:"paradigm_platform_navigate",description:"Navigate the Platform UI to a section, select a symbol, or open a lore entry. The browser updates in real-time. If the user is actively interacting, shows a prompt instead of auto-navigating. ~100 tokens.",inputSchema:{type:"object",properties:{section:{type:"string",enum:["overview","lore","graph","sentinel","university","symphony"],description:"Section to navigate to"},symbol:{type:"string",description:'Symbol to select (e.g., "#payment-service")'},loreId:{type:"string",description:"Lore entry ID to open in lore section"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_highlight",description:"Temporarily highlight symbols in the Platform UI with a pulsing glow. Auto-expires after duration. Use to draw attention to specific components during explanations. ~100 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbol IDs to highlight (e.g., ["#payment-service", "#api-gateway"])'},color:{type:"string",description:"Highlight color (CSS color, defaults to agent color)"},duration:{type:"number",description:"Duration in milliseconds (default: 5000)"},pulse:{type:"boolean",description:"Whether to pulse the highlight (default: true)"},label:{type:"string",description:"Optional label shown near highlighted symbols"}},required:["symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_annotate",description:"Show a toast notification, callout on a graph node, or badge in the Platform UI. Use for communicating decisions, warnings, or context to the user visually. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["toast","callout","badge"],description:"Annotation type: toast (notification), callout (floating note on graph node), badge (icon on symbol)"},message:{type:"string",description:"Annotation message text"},symbol:{type:"string",description:"Symbol to attach callout/badge to (required for callout/badge)"},severity:{type:"string",enum:["info","warning","error","success"],description:"Visual severity (default: info)"},duration:{type:"number",description:"Auto-dismiss duration in milliseconds (default: 6000, 0 = persistent)"}},required:["type","message"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_observe",description:"Read the current Platform UI state: what section the user is viewing, what symbol is selected, theme, connected agents, and active highlights/annotations. ~150 tokens.",inputSchema:{type:"object",properties:{detail:{type:"string",enum:["summary","full"],description:"Level of detail (default: summary)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_platform_clear",description:"Remove agent highlights, annotations, or all agent effects from the Platform UI. ~50 tokens.",inputSchema:{type:"object",properties:{target:{type:"string",enum:["highlights","annotations","all"],description:"What to clear (default: all)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function dl(n,e,s){switch(n){case "paradigm_platform_navigate":{let t=await wt(s.projectDir,"navigate",{section:e.section,symbol:e.symbol,loreId:e.loreId});if(!t.ok)return {handled:true,text:`**Navigate failed:** ${t.error}`};let i=t.data;if(i.navigated){let r=[];i.section&&r.push(`section: **${i.section}**`),i.symbol&&r.push(`symbol: **${i.symbol}**`);let o=i.userActive?" (user was active \u2014 shown as prompt)":"";return {handled:true,text:`Navigated to ${r.join(", ")}${o}`}}return {handled:true,text:`Navigation skipped: ${i.reason}`}}case "paradigm_platform_highlight":{let t=await wt(s.projectDir,"highlight",{symbols:e.symbols,color:e.color,duration:e.duration,pulse:e.pulse,label:e.label});if(!t.ok)return {handled:true,text:`**Highlight failed:** ${t.error}`};let i=t.data;return i.highlighted?{handled:true,text:`Highlighted **${i.count}** symbol(s)${e.label?` with label "${e.label}"`:""}`}:{handled:true,text:`Highlight skipped: ${i.reason}`}}case "paradigm_platform_annotate":{let t=await wt(s.projectDir,"annotate",{type:e.type,message:e.message,symbol:e.symbol,severity:e.severity,duration:e.duration});if(!t.ok)return {handled:true,text:`**Annotate failed:** ${t.error}`};let i=t.data;return i.annotated?{handled:true,text:`Created ${e.type} annotation: "${e.message}"`}:{handled:true,text:`Annotation skipped: ${i.reason}`}}case "paradigm_platform_observe":{let t=await wt(s.projectDir,"observe",{detail:e.detail});if(!t.ok)return {handled:true,text:`**Observe failed:** ${t.error}`};let i=t.data,r=i.state,o=[`## Platform UI State
|
|
808
831
|
`];o.push(`- **Connected:** ${i.connected?"Yes":"No"} (${i.users} browser client(s))`),o.push(`- **Section:** ${r.section}`),o.push(`- **Selected symbol:** ${r.selectedSymbol||"none"}`),o.push(`- **Theme:** ${r.theme}`),o.push(`- **Muted:** ${r.muted?"Yes \u2014 agent actions silently discarded":"No"}`);let a=i.agents;if(a?.length){o.push(`
|
|
809
832
|
### Connected Agents (${a.length})`);for(let c of a)o.push(`- \`${c.agentId}\` (since ${c.connectedAt})`);}if(e.detail==="full"){let c=i.highlights,l=i.annotations;c?.length&&o.push(`
|
|
810
833
|
### Active Highlights: ${c.length}`),l?.length&&o.push(`
|
|
811
834
|
### Active Annotations: ${l.length}`);}return {handled:true,text:o.join(`
|
|
812
|
-
`)}}case "paradigm_platform_clear":{let t=await wt(s.projectDir,"clear",{target:e.target});return t.ok?{handled:true,text:`Cleared ${t.data.target} agent effects`}:{handled:true,text:`**Clear failed:** ${t.error}`}}default:return {handled:false,text:""}}}t();function pl(){return [{name:"paradigm_agent_list",description:"List all agent identity profiles with top expertise areas. Shows agents from both global (~/.paradigm/agents/) and project (.paradigm/agents/) scopes. Returns profile summaries with personality and top symbols. ~150 tokens.",inputSchema:{type:"object",properties:{scope:{type:"string",enum:["all","global","project"],description:"Filter by scope (default: all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_expertise",description:"Find which agents are best qualified to work on a specific symbol. Returns agents ranked by confidence score from their expertise history. Use for symbol-to-agent routing. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to query (e.g., "#auth-middleware", "$checkout-flow")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns only top agent (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_get",description:"Get full agent profile including personality, expertise table, transferable patterns, and per-project contexts. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID (e.g., "architect", "builder")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_bench",description:"Bench an agent \u2014 Maestro will skip this agent during orchestration and nomination scoring. Use when an agent is noisy or unhelpful. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to bench (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_agent_activate",description:"Activate a benched agent \u2014 restore it to active Maestro orchestration. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to activate (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function ul(n,e,s){switch(n){case "paradigm_agent_list":{let t=g$6(s.rootDir),i=b$7(s.rootDir);if(t.length===0)return {handled:true,text:JSON.stringify({count:0,agents:[],note:"No .agent profiles found. Create one with `paradigm agent create <id> --global` or via paradigm_agent_create."},null,2)};let r=i?t.filter(l=>i.includes(l.id)):t,o=i?t.length-r.length:0,a=i$3(s.rootDir),c=new Map(a.map(l=>[l.id,l]));return {handled:true,text:JSON.stringify({count:r.length,totalAvailable:t.length,...i?{rosterActive:true,inactiveCount:o}:{rosterActive:false},agents:r.map(l=>{let d=c.get(l.id);return {id:l.id,role:l.role,nickname:l.nickname,personality:l.personality,...d?{lastSession:d.lastSession?.summary?.slice(0,100),lastSessionAge:d.lastSession?.date,pendingWork:d.pendingWork?.length||0,sessionsOnProject:d.sessionsOnProject||0}:{},topExpertise:(l.expertise||[]).sort((p,u)=>u.confidence-p.confidence).slice(0,5).map(p=>({symbol:p.symbol,confidence:parseFloat(p.confidence.toFixed(2)),sessions:p.sessions})),projectContexts:Object.keys(l.contexts||{}),transferableCount:(l.transferable||[]).length,...l.attention?.threshold!=null?{threshold:l.attention.threshold}:{}}})},null,2)}}case "paradigm_agent_expertise":{let t=e.symbol,i=e.response_format,r=j$5(s.rootDir,t);return i==="concise"?{handled:true,text:JSON.stringify({symbol:t,topAgent:r.length>0?{id:r[0].agentId,confidence:parseFloat(r[0].entry.confidence.toFixed(2))}:null},null,2)}:{handled:true,text:JSON.stringify({symbol:t,agents:r.map(o=>({agentId:o.agentId,confidence:parseFloat(o.entry.confidence.toFixed(2)),sessions:o.entry.sessions,lastTouch:o.entry.lastTouch})),count:r.length,...r.length===0?{note:`No agents have recorded expertise on ${t}. Run \`paradigm agent sync\` to bootstrap from lore history.`}:{}},null,2)}}case "paradigm_agent_get":{let t=e.id,i=f$2(s.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Agent profile "${t}" not found`,suggestion:`Create with \`paradigm agent create ${t} --global\``},null,2)};let r=s$2(i);return {handled:true,text:JSON.stringify({id:i.id,role:i.role,description:i.description,version:i.version,personality:i.personality,expertise:(i.expertise||[]).sort((o,a)=>a.confidence-o.confidence).map(o=>({symbol:o.symbol,confidence:parseFloat(o.confidence.toFixed(2)),sessions:o.sessions,lastTouch:o.lastTouch})),transferable:(i.transferable||[]).map(o=>({id:o.id,description:o.description,learnedIn:o.learnedIn,appliedIn:o.appliedIn,successRate:o.successRate})),contexts:i.contexts,created:i.created,updated:i.updated,...i.permissions?{permissions:i.permissions}:{},integrity:r},null,2)}}case "paradigm_agent_bench":{let t=e.id;if(!f$2(s.rootDir,t))return {handled:true,text:JSON.stringify({error:`Agent "${t}" not found`},null,2)};let r=b$7(s.rootDir);return r?r=r.filter(o=>o!==t):r=e$5().filter(o=>o!==t),d$7(s.rootDir,r),{handled:true,text:JSON.stringify({id:t,removedFromRoster:true,rosterCount:r.length,note:`${t} removed from this project's roster. Still available globally.`},null,2)}}case "paradigm_agent_activate":{let t=e.id;if(!f$2(s.rootDir,t))return {handled:true,text:JSON.stringify({error:`Agent "${t}" not found`},null,2)};let r=b$7(s.rootDir);return r&&(r.includes(t)||(r.push(t),d$7(s.rootDir,r))),{handled:true,text:JSON.stringify({id:t,addedToRoster:true,rosterCount:r?.length??"all (no roster)",note:`${t} is active on this project's roster.`},null,2)}}default:return {handled:false,text:""}}}g();function gl(){return [{name:"paradigm_notebook_search",description:"Search agent notebook entries by concept, tag, or keyword. Notebooks are curated snippet libraries distilled from lore for reuse in orchestration. ~150 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:'Agent ID to search notebooks for (e.g., "architect", "builder")'},query:{type:"string",description:"Search query \u2014 matches concepts, tags, context, and snippet content"},concepts:{type:"array",items:{type:"string"},description:'Filter by concept tags (e.g., ["auth", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Filter by classification tags"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level (default: "detailed")'}},required:["agentId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_notebook_add",description:"Add a new entry to an agent's notebook. Use for curated, reusable snippets that should be available across sessions. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add notebook entry for"},context:{type:"string",description:"When to apply this snippet \u2014 the retrieval context"},snippet:{type:"string",description:"The reusable code/knowledge snippet"},concepts:{type:"array",items:{type:"string"},description:'Concept tags for retrieval (e.g., ["auth", "jwt", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Classification tags"},confidence:{type:"number",description:"Confidence score 0.0-1.0 (default: 0.7)"},scope:{type:"string",enum:["global","project"],description:'Where to store: global travels across projects (default: "global")'}},required:["agentId","context","snippet","concepts"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_notebook_promote",description:"Extract a lore entry into a notebook entry. Distills the lore into a reusable snippet with provenance linking. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add the promoted entry to"},loreEntryId:{type:"string",description:'Lore entry ID to promote (e.g., "L-2026-03-15-...")'},scope:{type:"string",enum:["global","project"],description:'Where to store (default: "global")'}},required:["agentId","loreEntryId"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function ml(n,e,s){switch(n){case "paradigm_notebook_search":{let t=e.agentId,i=e.query,r=e.concepts,o=e.tags,a=e.response_format,c;return i?c=b$8(t,i,s.rootDir):c=a$7(t,s.rootDir,{concepts:r,tags:o}),a==="concise"?{handled:true,text:JSON.stringify({agentId:t,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,concepts:l.concepts}))},null,2)}:{handled:true,text:JSON.stringify({agentId:t,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,snippet:l.snippet.length>500?l.snippet.slice(0,500)+"...":l.snippet,concepts:l.concepts,tags:l.tags,appliedCount:l.appliedCount,confidence:l.confidence,provenance:l.provenance}))},null,2)}}case "paradigm_notebook_add":{let t=e.agentId,i=e.context,r=e.snippet,o=e.concepts||[],a=e.tags||[],c=e.confidence??.7,l=e.scope||(s.rootDir?"project":"global"),d=c$4(t,{context:i,snippet:r,provenance:{source:"manual",createdBy:t},confidence:c,concepts:o,tags:a},l,s.rootDir);return {handled:true,text:JSON.stringify({action:"notebook_add",id:d.entry.id,agentId:t,scope:l,filePath:d.filePath,concepts:d.entry.concepts},null,2)}}case "paradigm_notebook_promote":{let t=e.agentId,i=e.loreEntryId,r=e.scope||(s.rootDir?"project":"global"),o=await d$8(t,i,s.rootDir,r);return o?{handled:true,text:JSON.stringify({action:"notebook_promote",id:o.entry.id,agentId:t,loreEntryId:i,scope:r,filePath:o.filePath,concepts:o.entry.concepts,confidence:o.entry.confidence},null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry "${i}" not found`,suggestion:"Check the lore entry ID with paradigm_lore_search"},null,2)}}default:return {handled:false,text:""}}}var wg=".paradigm/scan-index.json",vg=".paradigm/flow-index.json",_g=".paradigm/config.yaml",Sg="portal.yaml",kg=".paradigm/university/index.yaml",re={enabled:true,title:null,theme:"dark",customCss:null,customContent:"docs/",exclude:{tags:[],patterns:[]},sidebar:{collapsed:[]},output:".paradigm/docs-site"};function _t(n){let e=F.join(n,_g);if(!O.existsSync(e))return {...re};try{let s=O.readFileSync(e,"utf8"),t=Z.load(s);if(!t||!t.docs)return {...re};let i=t.docs;return {enabled:i.enabled??re.enabled,title:i.title??re.title,theme:i.theme??re.theme,customCss:i.customCss??re.customCss,customContent:i.customContent??re.customContent,exclude:{tags:i.exclude?.tags??re.exclude.tags,patterns:i.exclude?.patterns??re.exclude.patterns},sidebar:{collapsed:i.sidebar?.collapsed??re.sidebar.collapsed},output:i.output??re.output}}catch{return {...re}}}function Un(n){let e=F.join(n,wg);if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function gi(n){let e=F.join(n,vg);if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function zn(n){let e=F.join(n,Sg);if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch{return null}}function yl(n){let e=F.join(n,kg);if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch{return null}}function hl(n){let e=n.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:Z.load(e[1]),body:e[2].trim()}}catch{return null}}function bl(n){let e=new Map,s=[n.components,n.features,n.flows,n.state,n.gates,n.signals,n.aspects];for(let t of s)if(t)for(let[i,r]of Object.entries(t))e.set(i,r);return e}function xg(n){return {components:"component",features:"component",flows:"flow",state:"component",gates:"gate",signals:"signal",aspects:"aspect"}[n]||"component"}function vt(n,e){if(e.exclude.tags.length>0&&n.visualTags){for(let s of n.visualTags)if(e.exclude.tags.includes(s))return true}if(e.exclude.patterns.length>0&&n.path){for(let s of e.exclude.patterns)if(s.endsWith("*")){let t=s.slice(0,-1);if(n.path.includes(t))return true}else if(n.path.includes(s))return true}return false}function wl(n,e){let s=F.join(n,e);if(!O.existsSync(s))return [];let t=[];try{let i=O.readdirSync(s).filter(r=>r.endsWith(".md"));for(let r of i)try{let o=O.readFileSync(F.join(s,r),"utf8"),a=r.replace(/\.md$/,""),c=hl(o);c?t.push({slug:a,title:c.frontmatter.title||a,body:c.body,order:typeof c.frontmatter.order=="number"?c.frontmatter.order:void 0,description:c.frontmatter.description||void 0}):t.push({slug:a,title:a,body:o.trim()});}catch{}}catch{}return t.sort((i,r)=>i.order!=null&&r.order!=null?i.order-r.order:i.order!=null?-1:r.order!=null?1:i.title.localeCompare(r.title)),t}function vl(n,e,s){let t=s||_t(n),i=F.join(n,t.customContent),r=F.join(i,`${e}.md`);if(!O.existsSync(r))return null;try{let o=O.readFileSync(r,"utf8"),a=hl(o);return a?{slug:e,title:a.frontmatter.title||e,body:a.body,order:typeof a.frontmatter.order=="number"?a.frontmatter.order:void 0,description:a.frontmatter.description||void 0}:{slug:e,title:e,body:o.trim()}}catch{return null}}function _l(n,e){let s=e||_t(n),t=Un(n),i=gi(n),r=zn(n),o=wl(n,s.customContent),a=yl(n),c=t?.$meta?.project||F.basename(n),l=s.title||`${c} Docs`,d=[],p={},u=0;if(o.length>0&&d.push({id:"custom-pages",label:"Pages",collapsed:s.sidebar.collapsed.includes("custom-pages"),items:o.map(g=>({id:g.slug,label:g.title,kind:"custom",description:g.description}))}),a&&a.entries.length>0){let g=a.entries.filter(m=>(m.type==="note"||m.type==="policy")&&m.symbols.length>0);g.length>0&&d.push({id:"guides",label:"Guides",collapsed:s.sidebar.collapsed.includes("guides"),items:g.map(m=>({id:m.id,label:m.title,kind:"guide",description:void 0,badge:m.symbols.length>0?`${m.symbols.length} symbols`:void 0}))});}if(t){let g=Object.values(t.components||{}).filter(v=>!vt(v,s));if(g.length>0){let v=new Map;for(let C of g){let T=C.componentType||"other";v.has(T)||v.set(T,[]),v.get(T).push(C);}let x=[...v.entries()].sort((C,T)=>T[1].length-C[1].length).map(([C,T])=>({id:`components-${C}`,label:`${C.charAt(0).toUpperCase()+C.slice(1)} (${T.length})`,collapsed:s.sidebar.collapsed.includes(`components-${C}`),items:T.sort((j,P)=>j.name.localeCompare(P.name)).map(j=>({id:j.id,label:j.name,kind:"component",description:j.description,badge:j.componentType}))}));d.push({id:"components",label:`Components (${g.length})`,collapsed:s.sidebar.collapsed.includes("components"),items:[],subgroups:x}),p.components=g.length,u+=g.length;}let m=Object.values(t.features||{}).filter(v=>!vt(v,s));m.length>0&&(d.push({id:"features",label:`Features (${m.length})`,collapsed:s.sidebar.collapsed.includes("features"),items:m.sort((v,k)=>v.name.localeCompare(k.name)).map(v=>({id:v.id,label:v.name,kind:"component",description:v.description}))}),p.features=m.length,u+=m.length);let y=Object.values(t.flows||{}).filter(v=>!vt(v,s)),f=new Set(y.map(v=>v.id)),b=[];if(i)for(let[v,k]of Object.entries(i.flows)){let x=v.replace(/^\$/,"");f.has(x)||b.push({id:x,label:k.name||x,kind:"flow",description:k.description});}let h=[...y.sort((v,k)=>v.name.localeCompare(k.name)).map(v=>({id:v.id,label:v.name,kind:"flow",description:v.description})),...b];h.length>0&&(d.push({id:"flows",label:`Flows (${h.length})`,collapsed:s.sidebar.collapsed.includes("flows"),items:h}),p.flows=h.length,u+=h.length);let w=Object.values(t.gates||{}).filter(v=>!vt(v,s));w.length>0&&(d.push({id:"gates",label:`Gates (${w.length})`,collapsed:s.sidebar.collapsed.includes("gates"),items:w.sort((v,k)=>v.name.localeCompare(k.name)).map(v=>({id:v.id,label:v.name,kind:"gate",description:v.description}))}),p.gates=w.length,u+=w.length);let _=Object.values(t.signals||{}).filter(v=>!vt(v,s));_.length>0&&(d.push({id:"signals",label:`Signals (${_.length})`,collapsed:s.sidebar.collapsed.includes("signals"),items:_.sort((v,k)=>v.name.localeCompare(k.name)).map(v=>({id:v.id,label:v.name,kind:"signal",description:v.description}))}),p.signals=_.length,u+=_.length);let S=Object.values(t.aspects||{}).filter(v=>!vt(v,s));S.length>0&&(d.push({id:"aspects",label:`Aspects (${S.length})`,collapsed:s.sidebar.collapsed.includes("aspects"),items:S.sort((v,k)=>v.name.localeCompare(k.name)).map(v=>({id:v.id,label:v.name,kind:"aspect",description:v.description}))}),p.aspects=S.length,u+=S.length);}if(r){let g=Object.keys(r.routes||{}).length,m=Object.keys(r.gates||{}).length;d.push({id:"portal",label:"Portal",collapsed:s.sidebar.collapsed.includes("portal"),items:[{id:"portal-overview",label:"Authorization Overview",kind:"portal",description:`${m} gates, ${g} routes`,badge:`${g} routes`}]});}return {title:l,project:c,generatedAt:new Date().toISOString(),groups:d,totalSymbols:u,symbolCounts:p}}function Sl(n,e){let s=Un(n);if(!s)return null;let t=bl(s),i=t.get(e);if(!i)return null;let r=[];for(let[f,b]of t)f!==e&&b.related&&b.related.includes(i.symbol)&&r.push(b.symbol);let o=(i.related||[]).slice(),a=[],c=gi(n);if(c)for(let[f,b]of Object.entries(c.flows)){let h=(b.steps||[]).map(w=>w.symbol);(h.includes(i.symbol)||h.includes(`#${e}`))&&a.push({id:f.replace(/^\$/,""),name:b.name||f});}if(s.flows)for(let[f,b]of Object.entries(s.flows)){if(a.some(w=>w.id===f))continue;let h=(b.steps||[]).map(w=>w.symbol).filter(Boolean);(h.includes(i.symbol)||h.includes(`#${e}`))&&a.push({id:f,name:b.name});}let l=[],d=zn(n);if(d&&i.category==="gates"){let f=Object.keys(d.gates||{}).find(b=>b.replace(/^\^/,"")===e);f&&l.push({id:f.replace(/^\^/,""),description:d.gates[f].description});}else if(d){let f=new Set((i.related||[]).filter(b=>b.startsWith("^")));for(let[b,h]of Object.entries(d.routes||{}))for(let w of h){let _=w.replace(/^\^/,"");if(f.has(w)||f.has(`^${_}`)){let S=d.gates[w]||d.gates[`^${_}`]||d.gates[_];S&&!l.some(v=>v.id===_)&&l.push({id:_,description:S.description});}}}let p=[];if(s.aspects)for(let[f,b]of Object.entries(s.aspects))b.related&&b.related.includes(i.symbol)&&p.push(b.symbol);for(let f of i.related||[])f.startsWith("~")&&!p.includes(f)&&p.push(f);let u=[],g=yl(n);if(g)for(let f of g.entries)f.symbols.includes(i.symbol)&&u.push({id:f.id,title:f.title});let m=i.parent||void 0,y=[];if(s.components)for(let f of Object.values(s.components))f.parent===i.symbol&&y.push(f.symbol);return {id:i.id,symbol:i.symbol,name:i.name,description:i.description||"",category:i.category||"components",componentType:i.componentType,tags:i.visualTags||[],path:i.path||"",related:i.related||[],referencedBy:r,references:o,flows:a,gates:l,aspects:p,guides:u,parent:m,children:y}}function kl(n,e){let s=gi(n),t=Un(n);if(s){let i=s.flows[`$${e}`]?`$${e}`:e,r=s.flows[i];if(r){let o=(r.steps||[]).map(c=>({type:c.type||"action",symbol:c.symbol||"",description:c.description})),a=t?.flows?.[e.replace(/^\$/,"")];return {id:e.replace(/^\$/,""),symbol:`$${e.replace(/^\$/,"")}`,name:r.name||e,description:r.description,trigger:r.trigger,steps:o,successSignal:r.successSignal,errorSignal:r.errorSignal,tags:a?.visualTags||[],path:a?.path||r.definedIn||""}}}if(t?.flows){let i=e.replace(/^\$/,""),r=t.flows[i];if(r){let o=(r.steps||[]).map(a=>({type:"action",symbol:a.symbol||"",description:a.action||a.name}));return {id:i,symbol:`$${i}`,name:r.name,description:r.description,steps:o,tags:r.visualTags||[],path:r.path||""}}}return null}function xl(n){let e=zn(n);if(!e)return {version:"0",gates:[],routes:[]};let s=new Map;for(let[r,o]of Object.entries(e.routes||{}))for(let a of o){let c=a.replace(/^\^/,"");s.has(c)||s.set(c,[]),s.get(c).push(r);}let t=Object.entries(e.gates||{}).map(([r,o])=>{let a=r.replace(/^\^/,"");return {symbol:`^${a}`,description:o.description,check:o.check,routes:s.get(a)||[]}}),i=Object.entries(e.routes||{}).map(([r,o])=>{let a=r.indexOf(" "),c=a>0?r.substring(0,a):"GET";return {route:a>0?r.substring(a+1):r,method:c,gates:o.map(d=>{let p=d.replace(/^\^/,""),u=e.gates[d]||e.gates[`^${p}`]||e.gates[p];return {symbol:`^${p}`,description:u?.description}})}});return {version:e.version||"1.0",gates:t,routes:i}}function Cl(n,e,s){let t=s||20,i=[],r=e.toLowerCase(),o=Un(n);if(o){let d=bl(o);for(let[p,u]of d){let g=ui(u.name,u.description||"",u.visualTags||[],r);g>0&&i.push({id:u.id,kind:xg(u.category),label:u.name,description:u.description||"",matchContext:fl(u.name,u.description||"",r),score:g});}}let a=_t(n),c=wl(n,a.customContent);for(let d of c){let p=d.body.substring(0,200),u=ui(d.title,p,[],r);u>0&&i.push({id:d.slug,kind:"custom",label:d.title,description:d.description||p.substring(0,100),matchContext:fl(d.title,d.body,r),score:u});}let l=zn(n);if(l)for(let[d,p]of Object.entries(l.gates||{})){let u=d.replace(/^\^/,""),g=ui(u,p.description,[],r);g>0&&i.push({id:u,kind:"portal",label:`^${u}`,description:p.description,score:g});}return i.sort((d,p)=>p.score-d.score||d.label.localeCompare(p.label)),i.slice(0,t)}function ui(n,e,s,t){let i=n.toLowerCase(),r=e.toLowerCase();return i===t?1:i.startsWith(t)?.8:i.includes(t)?.6:r.includes(t)?.5:s.some(o=>o.toLowerCase().includes(t))?.3:0}function fl(n,e,s){let i=e.toLowerCase().indexOf(s);if(i<0)return n.toLowerCase().includes(s)?n:void 0;let r=Math.max(0,i-40),o=Math.min(e.length,i+s.length+40),a=e.substring(r,o).trim();return r>0&&(a=`...${a}`),o<e.length&&(a=`${a}...`),a}function Pl(){return [{name:"paradigm_docs_manifest",description:"Get the documentation sidebar manifest \u2014 all symbols grouped by type with counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_docs_page",description:"Get page data for a symbol, flow, portal, or custom docs page. Returns structured data for rendering. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol ID (e.g., "cli-commands", "checkout-flow", "authenticated"). Do not include the prefix (#, $, ^, !, ~).'},flow:{type:"string",description:'Flow ID (e.g., "$init-flow"). Include the $ prefix.'},portal:{type:"boolean",description:"Set to true to get the portal overview page (gates + routes)."},slug:{type:"string",description:'Custom page slug (e.g., "getting-started").'}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_docs_search",description:"Search across all documentation content \u2014 symbols, descriptions, tags, custom pages. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query string"},limit:{type:"number",description:"Maximum results (default: 20)"}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Rl(n,e,s){if(n==="paradigm_docs_manifest"){let t=_t(s.rootDir),i=_l(s.rootDir,t),r=JSON.stringify(i,null,2);return o(r.length,n),{handled:true,text:r}}if(n==="paradigm_docs_page"){if(e.portal){let i=xl(s.rootDir),r=JSON.stringify(i,null,2);return o(r.length,n),{handled:true,text:r}}if(e.flow){let i=e.flow,r=kl(s.rootDir,i);if(!r){let a=JSON.stringify({error:`Flow "${i}" not found`});return o(a.length,n),{handled:true,text:a}}let o$1=JSON.stringify(r,null,2);return o(o$1.length,n),{handled:true,text:o$1}}if(e.slug){let i=_t(s.rootDir),r=vl(s.rootDir,e.slug,i);if(!r){let a=JSON.stringify({error:`Page "${e.slug}" not found`});return o(a.length,n),{handled:true,text:a}}let o$1=JSON.stringify(r,null,2);return o(o$1.length,n),{handled:true,text:o$1}}if(e.symbol){let i=Sl(s.rootDir,e.symbol);if(!i){let o$1=JSON.stringify({error:`Symbol "${e.symbol}" not found`});return o(o$1.length,n),{handled:true,text:o$1}}let r=JSON.stringify(i,null,2);return o(r.length,n),{handled:true,text:r}}let t=JSON.stringify({error:"Provide one of: symbol, flow, portal, or slug"});return o(t.length,n),{handled:true,text:t}}if(n==="paradigm_docs_search"){let t=e.query;if(!t)return {handled:true,text:JSON.stringify({error:"query is required"})};let i=Cl(s.rootDir,t,e.limit),r=JSON.stringify({count:i.length,results:i},null,2);return o(r.length,n),{handled:true,text:r}}return {handled:false,text:""}}function Bn(n,e,s={}){let{maxResults:t=20}=s,i=[],r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=[`rg -n --no-heading "${r}" "${n}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${r}" "${n}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of o)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return i;let c=a.trim().split(`
|
|
813
|
-
`);for(let l of c.slice(0,t)){let d=l.match(/^(.+?):(\d+):(.*)$/);if(d){let[,p,u,g]=d,m=F.relative(n,p),y="unknown";m.includes(".purpose")||m.includes("portal.yaml")?y="purpose":g.includes("//")||g.includes("#")||g.includes("*")?y="comment":y="code",i.push({filePath:m,line:parseInt(u,10),content:g.trim().slice(0,200),context:y});}}return i}function Tl(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Dl(n,e,s){if(n!=="paradigm_ripple")return {handled:false,text:""};let{symbol:t,depth:i$1=3,includeWorkspace:r=false,response_format:o$1}=e,a=h$1(s.index,t);if(!a){let x=Pg(s.rootDir,t);return o(x.length,n),{handled:true,text:x}}let c=Math.min(Math.max(i$1||3,1),5),l$1=k(s.index,t),d=new Set([t]),p=new Map;function u(x,C){if(C>=c)return;let T=[];for(let j of x){if(d.has(j))continue;d.add(j);let P=k(s.index,j);for(let D of P)d.has(D.symbol)||T.push(D.symbol);}T.length>0&&(p.set(C+1,T),u(T,C+1));}u(l$1.map(x=>x.symbol),1);let g=new Set;for(let[,x]of p)for(let C of x)C!==t&&!l$1.find(T=>T.symbol===C)&&g.add(C);let m=l(s.index,t),y=l$1.length+g.size,f="low";y>10?f="high":y>3&&(f="medium");let b=await Cn(s.rootDir),h=null;if(b){let x=Pn(b,t);x.totalFlows>0&&(x.impactLevel==="high"&&f==="low"?f="medium":x.impactLevel==="high"&&(f="high"),h={totalFlows:x.totalFlows,affectedFlows:x.affectedFlows.map(C=>({flowId:C.flowId,impactLevel:C.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${C.stepAffected.position}, affects ${C.downstreamSteps.length} downstream steps`})),validationSuggestion:x.validationCommands.length>0?`Run: ${x.validationCommands[0]}`:void 0});}let w=new Set([t,...l$1.map(x=>x.symbol),...g]),_=[];try{let x=i(s.index,"gate");for(let C of x)w.has(C.symbol)&&_.push({gate:C.symbol,description:C.description});for(let C of l$1)C.type==="gate"&&!_.find(T=>T.gate===C.symbol)&&_.push({gate:C.symbol,description:C.description});}catch{}let S={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:f,analysis:{directlyAffected:l$1.map(x=>({symbol:x.symbol,type:x.type,description:x.description})),indirectlyAffected:Array.from(g),indirectByLevel:Object.fromEntries(p),dependsOn:m.map(x=>({symbol:x.symbol,type:x.type}))},summary:{directCount:l$1.length,indirectCount:g.size,totalAffected:y,dependsOnCount:m.length,levelsAnalyzed:c},recommendation:Rg(f)};h&&(S.affectedFlows=h),_.length>0&&(S.affectedGates=_),S.suggestedReviewScope=jg(f,l$1.length,g.size,_.length,h?.totalFlows??0);try{let x=await Q(s.rootDir,t);x.length>0&&(S.personas_affected=x,x.length>2&&f==="low"&&(S.impact="medium"));}catch{}try{let x=ka$1(s.rootDir,t);x.length>0&&(S.university_content_affected=x.map(C=>({id:C.id,title:C.title,type:C.type,stale:C.stale})));}catch{}if(r&&s.workspace){let x=vo(s.workspace,t);if(x.length>0){S.workspaceImpact={siblings:x.map(T=>({project:T.project,references:T.references.map(j=>({symbol:j.symbol,type:j.type,description:j.description}))}))};let C=x.reduce((T,j)=>T+j.references.length,0);C>0&&f==="low"&&(S.impact="medium"),C>5&&(S.impact="high");}}let v=o$1==="concise"?{symbol:S.symbol,impact:S.impact,summary:S.summary}:S,k$1=JSON.stringify(v,null,2);return o(k$1.length,n),{handled:true,text:k$1}}function Pg(n,e){let s=Bn(n,e,{maxResults:20});if(s.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let t=[...new Set(s.map(o=>o.filePath))],i={};for(let o of s)i[o.context]=(i[o.context]||0)+1;let r="low";return t.length>10||s.length>20?r="high":(t.length>3||s.length>5)&&(r="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:r,analysis:{filesAffected:t.slice(0,10),totalFilesAffected:t.length,totalReferences:s.length,contextBreakdown:i,sampleReferences:s.slice(0,5).map(o=>({file:o.filePath,line:o.line,preview:o.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function Rg(n){switch(n){case "high":return "High impact change - review all affected symbols carefully before modifying";case "medium":return "Moderate impact - check direct dependencies for breaking changes";case "low":return "Low impact - safe to modify with standard review"}}function jg(n,e,s,t,i){let r=[];return e>0&&r.push(`Review ${e} direct dependent(s) for breaking changes`),s>0&&r.push(`Scan ${s} indirect dependent(s) for cascading effects`),t>0&&r.push(`Verify ${t} affected gate(s) still enforce correct auth/access`),i>0&&r.push(`Validate ${i} affected flow(s) end-to-end`),n==="high"?r.push("Consider running full test suite before merging"):n==="medium"&&r.push("Run targeted tests for affected components"),r.length===0&&r.push("No downstream dependents detected - safe to proceed"),r}g$1();e();function Al(){return [{name:"paradigm_work_log_record",description:"Record a work log entry \u2014 what got done. Auto-attached to sprint boards and standup summaries. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent that did the work (e.g., "builder")'},summary:{type:"string",description:"What was done"},outcome:{type:"string",enum:["pass","fail","partial","blocked"],description:"How it went"},task_ref:{type:"string",description:'Ticket/issue reference (e.g., "ENG-142")'},files_modified:{type:"array",items:{type:"string"},description:"Files that were modified"},symbols_touched:{type:"array",items:{type:"string"},description:"Paradigm symbols touched"},next_steps:{type:"array",items:{type:"string"},description:"What's left to do"},blockers:{type:"array",items:{type:"string"},description:"What's blocking progress"},duration_minutes:{type:"number",description:"How long it took"},commit:{type:"string",description:"Git commit hash"}},required:["agent","summary","outcome"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_work_log_search",description:"Search work log entries \u2014 what got done. Returns recent work, filterable by agent, outcome, symbol, date. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent"},outcome:{type:"string",enum:["pass","fail","partial","blocked"]},task_ref:{type:"string",description:"Filter by ticket reference"},symbol:{type:"string",description:"Filter by symbol touched"},dateFrom:{type:"string",description:"Start date (YYYY-MM-DD)"},dateTo:{type:"string",description:"End date (YYYY-MM-DD)"},limit:{type:"number",description:"Max entries to return (default 20)"},summary:{type:"boolean",description:"Return aggregate summary instead of entries"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_journal_record",description:"Record a learning journal entry \u2014 what an agent learned. Agent-private, travels across projects. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent who learned this (e.g., "security")'},trigger:{type:"string",enum:["correction_received","confidence_miss","pattern_discovered","debate_loss","failure_analysis","human_feedback","self_reflection"],description:"What triggered this learning moment"},insight:{type:"string",description:"The insight itself"},project:{type:"string",description:"Project where this happened"},transferable:{type:"boolean",description:"Whether this applies to other projects"},confidence_before:{type:"number",description:"Confidence before (0.0-1.0)"},confidence_after:{type:"number",description:"Confidence after (0.0-1.0)"},pattern:{type:"object",properties:{id:{type:"string"},applies_when:{type:"string"},correct_approach:{type:"string"}}},linked_work_log:{type:"string",description:"Work log entry that prompted this"},tags:{type:"array",items:{type:"string"}}},required:["agent","trigger","insight","project","transferable"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_journal_search",description:"Search learning journal entries \u2014 what agents learned. Can search across all agents or a specific one. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent (omit for all agents)"},trigger:{type:"string",description:"Filter by trigger type"},project:{type:"string",description:"Filter by project"},transferable:{type:"boolean",description:"Only show transferable insights"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},stats:{type:"boolean",description:"Return stats instead of entries (requires agent)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_decision_record",description:"Record a team decision \u2014 what we decided and why. Institutional memory with rationale and alternatives. ~100 tokens.",inputSchema:{type:"object",properties:{title:{type:"string",description:"Decision title"},decision:{type:"string",description:"The decision itself"},rationale:{type:"string",description:"Why this was chosen"},participants:{type:"array",items:{type:"object",properties:{id:{type:"string"},role:{type:"string",enum:["human","agent"]},stance:{type:"string",enum:["proposed","supported","dissented","abstained","neutral"]}},required:["id","role","stance"]}},alternatives_considered:{type:"array",items:{type:"object",properties:{option:{type:"string"},rejected_because:{type:"string"}}}},symbols_affected:{type:"array",items:{type:"string"}},status:{type:"string",enum:["active","proposed"],description:"Decision status (default: active)"},tags:{type:"array",items:{type:"string"}}},required:["title","decision","rationale","participants"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_decision_search",description:"Search team decisions \u2014 what we decided. Find active decisions by symbol, participant, status. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",enum:["active","superseded","deprecated","proposed","rejected"]},participant:{type:"string",description:"Filter by participant ID"},symbol:{type:"string",description:"Filter by affected symbol"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},summary:{type:"boolean",description:"Return aggregate summary"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Ol(n,e,s){let t=i=>JSON.stringify(i,null,2);switch(n){case "paradigm_work_log_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.summary,i,"work_log"),o=a$4(s.rootDir,{agent:e.agent,summary:r,outcome:e.outcome,task_ref:e.task_ref,files_modified:e.files_modified,symbols_touched:e.symbols_touched,next_steps:e.next_steps,blockers:e.blockers,duration_minutes:e.duration_minutes,commit:e.commit});return {text:t({recorded:true,id:o.id,timestamp:o.timestamp}),handled:true}}case "paradigm_work_log_search":{if(e.summary){let r=d$5(s.rootDir,7);return {text:t(r),handled:true}}let i=b$5(s.rootDir,{agent:e.agent,outcome:e.outcome,task_ref:e.task_ref,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:t({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,summary:r.summary,outcome:r.outcome,timestamp:r.timestamp,symbols_touched:r.symbols_touched,task_ref:r.task_ref}))}),handled:true}}case "paradigm_journal_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.insight,i,"learning_journal"),o=a$3(e.agent,{trigger:e.trigger,insight:r,project:e.project,transferable:e.transferable,confidence_before:e.confidence_before,confidence_after:e.confidence_after,pattern:e.pattern,linked_work_log:e.linked_work_log,tags:e.tags});return {text:t({recorded:true,id:o.id,agent:o.agent,timestamp:o.timestamp}),handled:true}}case "paradigm_journal_search":{if(e.stats&&e.agent){let r=e$3(e.agent);return {text:t(r),handled:true}}let i=e.agent?b$4(e.agent,{trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20}):d$4({trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:t({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,trigger:r.trigger,insight:r.insight.slice(0,200),project:r.project,transferable:r.transferable,timestamp:r.timestamp}))}),handled:true}}case "paradigm_decision_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.decision,i,"team_decisions"),{filtered:o}=d$3(e.rationale,i,"team_decisions"),a=a$2(s.rootDir,{title:e.title,decision:r,rationale:o,participants:e.participants,alternatives_considered:e.alternatives_considered,symbols_affected:e.symbols_affected,status:e.status||"active",tags:e.tags});return {text:t({recorded:true,id:a.id,title:a.title,timestamp:a.timestamp}),handled:true}}case "paradigm_decision_search":{if(e.summary){let r=g$5(s.rootDir);return {text:t(r),handled:true}}let i=d$2(s.rootDir,{status:e.status,participant:e.participant,symbol:e.symbol,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:t({count:i.length,entries:i.map(r=>({id:r.id,title:r.title,status:r.status,decision:r.decision.slice(0,200),participants:r.participants.map(o=>`${o.id} (${o.stance})`),symbols_affected:r.symbols_affected,timestamp:r.timestamp}))}),handled:true}}default:return {text:`Unknown streams tool: ${n}`,handled:false}}}v();b$1();t();g$1();h();function Il(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_neverland",description:"Neverland Validation \u2014 aggregate learning metrics across all agents. Shows acceptance rates, threshold drift, expertise growth, notebook counts, cross-project transfer, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature). ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function Tg(n){let e=Date.now(),s=n.match(/^(\d+)(m|h|d)$/);if(s){let t=parseInt(s[1],10),i=s[2],r=i==="m"?t*6e4:i==="h"?t*36e5:t*864e5;return new Date(e-r).toISOString()}return n}async function $l(n,e,s){let t=i=>JSON.stringify(i,null,2);switch(n){case "paradigm_ambient_nominations":{m$1(s.rootDir);let r=e.pending_only!==false,o=e.limit||20,a=i$2(s.rootDir,{agent:e.agent,urgency:e.urgency,pending_only:r,limit:o+20}),c=t$2(s.rootDir);a=u$1(a,c).slice(0,o);let l=F.join(s.rootDir,".paradigm/events/nominations.jsonl");if(O.existsSync(l))try{let p=O.readFileSync(l,"utf8"),u=new Set(a.map(m=>m.id)),g=p.trim().split(`
|
|
835
|
+
`)}}case "paradigm_platform_clear":{let t=await wt(s.projectDir,"clear",{target:e.target});return t.ok?{handled:true,text:`Cleared ${t.data.target} agent effects`}:{handled:true,text:`**Clear failed:** ${t.error}`}}default:return {handled:false,text:""}}}t();function pl(){return [{name:"paradigm_agent_list",description:"List all agent identity profiles with top expertise areas. Shows agents from both global (~/.paradigm/agents/) and project (.paradigm/agents/) scopes. Returns profile summaries with personality and top symbols. ~150 tokens.",inputSchema:{type:"object",properties:{scope:{type:"string",enum:["all","global","project"],description:"Filter by scope (default: all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_expertise",description:"Find which agents are best qualified to work on a specific symbol. Returns agents ranked by confidence score from their expertise history. Use for symbol-to-agent routing. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to query (e.g., "#auth-middleware", "$checkout-flow")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns only top agent (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_get",description:"Get full agent profile including personality, expertise table, transferable patterns, and per-project contexts. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID (e.g., "architect", "builder")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_bench",description:"Bench an agent \u2014 Maestro will skip this agent during orchestration and nomination scoring. Use when an agent is noisy or unhelpful. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to bench (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_agent_activate",description:"Activate a benched agent \u2014 restore it to active Maestro orchestration. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to activate (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function ul(n,e,s){switch(n){case "paradigm_agent_list":{let t=g$6(s.rootDir),i=b$7(s.rootDir);if(t.length===0)return {handled:true,text:JSON.stringify({count:0,agents:[],note:"No .agent profiles found. Create one with `paradigm agent create <id> --global` or via paradigm_agent_create."},null,2)};let r=i?t.filter(l=>i.includes(l.id)):t,o=i?t.length-r.length:0,a=i$3(s.rootDir),c=new Map(a.map(l=>[l.id,l]));return {handled:true,text:JSON.stringify({count:r.length,totalAvailable:t.length,...i?{rosterActive:true,inactiveCount:o}:{rosterActive:false},agents:r.map(l=>{let d=c.get(l.id);return {id:l.id,role:l.role,nickname:l.nickname,personality:l.personality,...d?{lastSession:d.lastSession?.summary?.slice(0,100),lastSessionAge:d.lastSession?.date,pendingWork:d.pendingWork?.length||0,sessionsOnProject:d.sessionsOnProject||0}:{},topExpertise:(l.expertise||[]).sort((p,u)=>u.confidence-p.confidence).slice(0,5).map(p=>({symbol:p.symbol,confidence:parseFloat(p.confidence.toFixed(2)),sessions:p.sessions})),projectContexts:Object.keys(l.contexts||{}),transferableCount:(l.transferable||[]).length,...l.attention?.threshold!=null?{threshold:l.attention.threshold}:{}}})},null,2)}}case "paradigm_agent_expertise":{let t=e.symbol,i=e.response_format,r=j$5(s.rootDir,t);return i==="concise"?{handled:true,text:JSON.stringify({symbol:t,topAgent:r.length>0?{id:r[0].agentId,confidence:parseFloat(r[0].entry.confidence.toFixed(2))}:null},null,2)}:{handled:true,text:JSON.stringify({symbol:t,agents:r.map(o=>({agentId:o.agentId,confidence:parseFloat(o.entry.confidence.toFixed(2)),sessions:o.entry.sessions,lastTouch:o.entry.lastTouch})),count:r.length,...r.length===0?{note:`No agents have recorded expertise on ${t}. Run \`paradigm agent sync\` to bootstrap from lore history.`}:{}},null,2)}}case "paradigm_agent_get":{let t=e.id,i=f$2(s.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Agent profile "${t}" not found`,suggestion:`Create with \`paradigm agent create ${t} --global\``},null,2)};let r=s$2(i);return {handled:true,text:JSON.stringify({id:i.id,role:i.role,description:i.description,version:i.version,personality:i.personality,expertise:(i.expertise||[]).sort((o,a)=>a.confidence-o.confidence).map(o=>({symbol:o.symbol,confidence:parseFloat(o.confidence.toFixed(2)),sessions:o.sessions,lastTouch:o.lastTouch})),transferable:(i.transferable||[]).map(o=>({id:o.id,description:o.description,learnedIn:o.learnedIn,appliedIn:o.appliedIn,successRate:o.successRate})),contexts:i.contexts,created:i.created,updated:i.updated,...i.permissions?{permissions:i.permissions}:{},integrity:r},null,2)}}case "paradigm_agent_bench":{let t=e.id;if(!f$2(s.rootDir,t))return {handled:true,text:JSON.stringify({error:`Agent "${t}" not found`},null,2)};let r=b$7(s.rootDir);return r?r=r.filter(o=>o!==t):r=e$5().filter(o=>o!==t),d$7(s.rootDir,r),{handled:true,text:JSON.stringify({id:t,removedFromRoster:true,rosterCount:r.length,note:`${t} removed from this project's roster. Still available globally.`},null,2)}}case "paradigm_agent_activate":{let t=e.id;if(!f$2(s.rootDir,t))return {handled:true,text:JSON.stringify({error:`Agent "${t}" not found`},null,2)};let r=b$7(s.rootDir);return r&&(r.includes(t)||(r.push(t),d$7(s.rootDir,r))),{handled:true,text:JSON.stringify({id:t,addedToRoster:true,rosterCount:r?.length??"all (no roster)",note:`${t} is active on this project's roster.`},null,2)}}default:return {handled:false,text:""}}}g();function gl(){return [{name:"paradigm_notebook_search",description:"Search agent notebook entries by concept, tag, or keyword. Notebooks are curated snippet libraries distilled from lore for reuse in orchestration. ~150 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:'Agent ID to search notebooks for (e.g., "architect", "builder")'},query:{type:"string",description:"Search query \u2014 matches concepts, tags, context, and snippet content"},concepts:{type:"array",items:{type:"string"},description:'Filter by concept tags (e.g., ["auth", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Filter by classification tags"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level (default: "detailed")'}},required:["agentId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_notebook_add",description:"Add a new entry to an agent's notebook. Use for curated, reusable snippets that should be available across sessions. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add notebook entry for"},context:{type:"string",description:"When to apply this snippet \u2014 the retrieval context"},snippet:{type:"string",description:"The reusable code/knowledge snippet"},concepts:{type:"array",items:{type:"string"},description:'Concept tags for retrieval (e.g., ["auth", "jwt", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Classification tags"},confidence:{type:"number",description:"Confidence score 0.0-1.0 (default: 0.7)"},scope:{type:"string",enum:["global","project"],description:'Where to store: global travels across projects (default: "global")'}},required:["agentId","context","snippet","concepts"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_notebook_promote",description:"Extract a lore entry into a notebook entry. Distills the lore into a reusable snippet with provenance linking. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add the promoted entry to"},loreEntryId:{type:"string",description:'Lore entry ID to promote (e.g., "L-2026-03-15-...")'},scope:{type:"string",enum:["global","project"],description:'Where to store (default: "global")'}},required:["agentId","loreEntryId"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function ml(n,e,s){switch(n){case "paradigm_notebook_search":{let t=e.agentId,i=e.query,r=e.concepts,o=e.tags,a=e.response_format,c;return i?c=b$8(t,i,s.rootDir):c=a$7(t,s.rootDir,{concepts:r,tags:o}),a==="concise"?{handled:true,text:JSON.stringify({agentId:t,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,concepts:l.concepts}))},null,2)}:{handled:true,text:JSON.stringify({agentId:t,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,snippet:l.snippet.length>500?l.snippet.slice(0,500)+"...":l.snippet,concepts:l.concepts,tags:l.tags,appliedCount:l.appliedCount,confidence:l.confidence,provenance:l.provenance}))},null,2)}}case "paradigm_notebook_add":{let t=e.agentId,i=e.context,r=e.snippet,o=e.concepts||[],a=e.tags||[],c=e.confidence??.7,l=e.scope||(s.rootDir?"project":"global"),d=c$4(t,{context:i,snippet:r,provenance:{source:"manual",createdBy:t},confidence:c,concepts:o,tags:a},l,s.rootDir);return {handled:true,text:JSON.stringify({action:"notebook_add",id:d.entry.id,agentId:t,scope:l,filePath:d.filePath,concepts:d.entry.concepts},null,2)}}case "paradigm_notebook_promote":{let t=e.agentId,i=e.loreEntryId,r=e.scope||(s.rootDir?"project":"global"),o=await d$8(t,i,s.rootDir,r);return o?{handled:true,text:JSON.stringify({action:"notebook_promote",id:o.entry.id,agentId:t,loreEntryId:i,scope:r,filePath:o.filePath,concepts:o.entry.concepts,confidence:o.entry.confidence},null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry "${i}" not found`,suggestion:"Check the lore entry ID with paradigm_lore_search"},null,2)}}default:return {handled:false,text:""}}}var xg=".paradigm/scan-index.json",Cg=".paradigm/flow-index.json",Pg=".paradigm/config.yaml",Rg="portal.yaml",jg=".paradigm/university/index.yaml",re={enabled:true,title:null,theme:"dark",customCss:null,customContent:"docs/",exclude:{tags:[],patterns:[]},sidebar:{collapsed:[]},output:".paradigm/docs-site"};function _t(n){let e=F.join(n,Pg);if(!O.existsSync(e))return {...re};try{let s=O.readFileSync(e,"utf8"),t=Z.load(s);if(!t||!t.docs)return {...re};let i=t.docs;return {enabled:i.enabled??re.enabled,title:i.title??re.title,theme:i.theme??re.theme,customCss:i.customCss??re.customCss,customContent:i.customContent??re.customContent,exclude:{tags:i.exclude?.tags??re.exclude.tags,patterns:i.exclude?.patterns??re.exclude.patterns},sidebar:{collapsed:i.sidebar?.collapsed??re.sidebar.collapsed},output:i.output??re.output}}catch{return {...re}}}function Un(n){let e=F.join(n,xg);if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function gi(n){let e=F.join(n,Cg);if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function zn(n){let e=F.join(n,Rg);if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch{return null}}function yl(n){let e=F.join(n,jg);if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch{return null}}function hl(n){let e=n.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:Z.load(e[1]),body:e[2].trim()}}catch{return null}}function bl(n){let e=new Map,s=[n.components,n.features,n.flows,n.state,n.gates,n.signals,n.aspects];for(let t of s)if(t)for(let[i,r]of Object.entries(t))e.set(i,r);return e}function Tg(n){return {components:"component",features:"component",flows:"flow",state:"component",gates:"gate",signals:"signal",aspects:"aspect"}[n]||"component"}function vt(n,e){if(e.exclude.tags.length>0&&n.visualTags){for(let s of n.visualTags)if(e.exclude.tags.includes(s))return true}if(e.exclude.patterns.length>0&&n.path){for(let s of e.exclude.patterns)if(s.endsWith("*")){let t=s.slice(0,-1);if(n.path.includes(t))return true}else if(n.path.includes(s))return true}return false}function wl(n,e){let s=F.join(n,e);if(!O.existsSync(s))return [];let t=[];try{let i=O.readdirSync(s).filter(r=>r.endsWith(".md"));for(let r of i)try{let o=O.readFileSync(F.join(s,r),"utf8"),a=r.replace(/\.md$/,""),c=hl(o);c?t.push({slug:a,title:c.frontmatter.title||a,body:c.body,order:typeof c.frontmatter.order=="number"?c.frontmatter.order:void 0,description:c.frontmatter.description||void 0}):t.push({slug:a,title:a,body:o.trim()});}catch{}}catch{}return t.sort((i,r)=>i.order!=null&&r.order!=null?i.order-r.order:i.order!=null?-1:r.order!=null?1:i.title.localeCompare(r.title)),t}function vl(n,e,s){let t=s||_t(n),i=F.join(n,t.customContent),r=F.join(i,`${e}.md`);if(!O.existsSync(r))return null;try{let o=O.readFileSync(r,"utf8"),a=hl(o);return a?{slug:e,title:a.frontmatter.title||e,body:a.body,order:typeof a.frontmatter.order=="number"?a.frontmatter.order:void 0,description:a.frontmatter.description||void 0}:{slug:e,title:e,body:o.trim()}}catch{return null}}function _l(n,e){let s=e||_t(n),t=Un(n),i=gi(n),r=zn(n),o=wl(n,s.customContent),a=yl(n),c=t?.$meta?.project||F.basename(n),l=s.title||`${c} Docs`,d=[],p={},u=0;if(o.length>0&&d.push({id:"custom-pages",label:"Pages",collapsed:s.sidebar.collapsed.includes("custom-pages"),items:o.map(g=>({id:g.slug,label:g.title,kind:"custom",description:g.description}))}),a&&a.entries.length>0){let g=a.entries.filter(m=>(m.type==="note"||m.type==="policy")&&m.symbols.length>0);g.length>0&&d.push({id:"guides",label:"Guides",collapsed:s.sidebar.collapsed.includes("guides"),items:g.map(m=>({id:m.id,label:m.title,kind:"guide",description:void 0,badge:m.symbols.length>0?`${m.symbols.length} symbols`:void 0}))});}if(t){let g=Object.values(t.components||{}).filter(v=>!vt(v,s));if(g.length>0){let v=new Map;for(let C of g){let T=C.componentType||"other";v.has(T)||v.set(T,[]),v.get(T).push(C);}let x=[...v.entries()].sort((C,T)=>T[1].length-C[1].length).map(([C,T])=>({id:`components-${C}`,label:`${C.charAt(0).toUpperCase()+C.slice(1)} (${T.length})`,collapsed:s.sidebar.collapsed.includes(`components-${C}`),items:T.sort((j,P)=>j.name.localeCompare(P.name)).map(j=>({id:j.id,label:j.name,kind:"component",description:j.description,badge:j.componentType}))}));d.push({id:"components",label:`Components (${g.length})`,collapsed:s.sidebar.collapsed.includes("components"),items:[],subgroups:x}),p.components=g.length,u+=g.length;}let m=Object.values(t.features||{}).filter(v=>!vt(v,s));m.length>0&&(d.push({id:"features",label:`Features (${m.length})`,collapsed:s.sidebar.collapsed.includes("features"),items:m.sort((v,S)=>v.name.localeCompare(S.name)).map(v=>({id:v.id,label:v.name,kind:"component",description:v.description}))}),p.features=m.length,u+=m.length);let y=Object.values(t.flows||{}).filter(v=>!vt(v,s)),f=new Set(y.map(v=>v.id)),b=[];if(i)for(let[v,S]of Object.entries(i.flows)){let x=v.replace(/^\$/,"");f.has(x)||b.push({id:x,label:S.name||x,kind:"flow",description:S.description});}let h=[...y.sort((v,S)=>v.name.localeCompare(S.name)).map(v=>({id:v.id,label:v.name,kind:"flow",description:v.description})),...b];h.length>0&&(d.push({id:"flows",label:`Flows (${h.length})`,collapsed:s.sidebar.collapsed.includes("flows"),items:h}),p.flows=h.length,u+=h.length);let w=Object.values(t.gates||{}).filter(v=>!vt(v,s));w.length>0&&(d.push({id:"gates",label:`Gates (${w.length})`,collapsed:s.sidebar.collapsed.includes("gates"),items:w.sort((v,S)=>v.name.localeCompare(S.name)).map(v=>({id:v.id,label:v.name,kind:"gate",description:v.description}))}),p.gates=w.length,u+=w.length);let _=Object.values(t.signals||{}).filter(v=>!vt(v,s));_.length>0&&(d.push({id:"signals",label:`Signals (${_.length})`,collapsed:s.sidebar.collapsed.includes("signals"),items:_.sort((v,S)=>v.name.localeCompare(S.name)).map(v=>({id:v.id,label:v.name,kind:"signal",description:v.description}))}),p.signals=_.length,u+=_.length);let k=Object.values(t.aspects||{}).filter(v=>!vt(v,s));k.length>0&&(d.push({id:"aspects",label:`Aspects (${k.length})`,collapsed:s.sidebar.collapsed.includes("aspects"),items:k.sort((v,S)=>v.name.localeCompare(S.name)).map(v=>({id:v.id,label:v.name,kind:"aspect",description:v.description}))}),p.aspects=k.length,u+=k.length);}if(r){let g=Object.keys(r.routes||{}).length,m=Object.keys(r.gates||{}).length;d.push({id:"portal",label:"Portal",collapsed:s.sidebar.collapsed.includes("portal"),items:[{id:"portal-overview",label:"Authorization Overview",kind:"portal",description:`${m} gates, ${g} routes`,badge:`${g} routes`}]});}return {title:l,project:c,generatedAt:new Date().toISOString(),groups:d,totalSymbols:u,symbolCounts:p}}function kl(n,e){let s=Un(n);if(!s)return null;let t=bl(s),i=t.get(e);if(!i)return null;let r=[];for(let[f,b]of t)f!==e&&b.related&&b.related.includes(i.symbol)&&r.push(b.symbol);let o=(i.related||[]).slice(),a=[],c=gi(n);if(c)for(let[f,b]of Object.entries(c.flows)){let h=(b.steps||[]).map(w=>w.symbol);(h.includes(i.symbol)||h.includes(`#${e}`))&&a.push({id:f.replace(/^\$/,""),name:b.name||f});}if(s.flows)for(let[f,b]of Object.entries(s.flows)){if(a.some(w=>w.id===f))continue;let h=(b.steps||[]).map(w=>w.symbol).filter(Boolean);(h.includes(i.symbol)||h.includes(`#${e}`))&&a.push({id:f,name:b.name});}let l=[],d=zn(n);if(d&&i.category==="gates"){let f=Object.keys(d.gates||{}).find(b=>b.replace(/^\^/,"")===e);f&&l.push({id:f.replace(/^\^/,""),description:d.gates[f].description});}else if(d){let f=new Set((i.related||[]).filter(b=>b.startsWith("^")));for(let[b,h]of Object.entries(d.routes||{}))for(let w of h){let _=w.replace(/^\^/,"");if(f.has(w)||f.has(`^${_}`)){let k=d.gates[w]||d.gates[`^${_}`]||d.gates[_];k&&!l.some(v=>v.id===_)&&l.push({id:_,description:k.description});}}}let p=[];if(s.aspects)for(let[f,b]of Object.entries(s.aspects))b.related&&b.related.includes(i.symbol)&&p.push(b.symbol);for(let f of i.related||[])f.startsWith("~")&&!p.includes(f)&&p.push(f);let u=[],g=yl(n);if(g)for(let f of g.entries)f.symbols.includes(i.symbol)&&u.push({id:f.id,title:f.title});let m=i.parent||void 0,y=[];if(s.components)for(let f of Object.values(s.components))f.parent===i.symbol&&y.push(f.symbol);return {id:i.id,symbol:i.symbol,name:i.name,description:i.description||"",category:i.category||"components",componentType:i.componentType,tags:i.visualTags||[],path:i.path||"",related:i.related||[],referencedBy:r,references:o,flows:a,gates:l,aspects:p,guides:u,parent:m,children:y}}function Sl(n,e){let s=gi(n),t=Un(n);if(s){let i=s.flows[`$${e}`]?`$${e}`:e,r=s.flows[i];if(r){let o=(r.steps||[]).map(c=>({type:c.type||"action",symbol:c.symbol||"",description:c.description})),a=t?.flows?.[e.replace(/^\$/,"")];return {id:e.replace(/^\$/,""),symbol:`$${e.replace(/^\$/,"")}`,name:r.name||e,description:r.description,trigger:r.trigger,steps:o,successSignal:r.successSignal,errorSignal:r.errorSignal,tags:a?.visualTags||[],path:a?.path||r.definedIn||""}}}if(t?.flows){let i=e.replace(/^\$/,""),r=t.flows[i];if(r){let o=(r.steps||[]).map(a=>({type:"action",symbol:a.symbol||"",description:a.action||a.name}));return {id:i,symbol:`$${i}`,name:r.name,description:r.description,steps:o,tags:r.visualTags||[],path:r.path||""}}}return null}function xl(n){let e=zn(n);if(!e)return {version:"0",gates:[],routes:[]};let s=new Map;for(let[r,o]of Object.entries(e.routes||{}))for(let a of o){let c=a.replace(/^\^/,"");s.has(c)||s.set(c,[]),s.get(c).push(r);}let t=Object.entries(e.gates||{}).map(([r,o])=>{let a=r.replace(/^\^/,"");return {symbol:`^${a}`,description:o.description,check:o.check,routes:s.get(a)||[]}}),i=Object.entries(e.routes||{}).map(([r,o])=>{let a=r.indexOf(" "),c=a>0?r.substring(0,a):"GET";return {route:a>0?r.substring(a+1):r,method:c,gates:o.map(d=>{let p=d.replace(/^\^/,""),u=e.gates[d]||e.gates[`^${p}`]||e.gates[p];return {symbol:`^${p}`,description:u?.description}})}});return {version:e.version||"1.0",gates:t,routes:i}}function Cl(n,e,s){let t=s||20,i=[],r=e.toLowerCase(),o=Un(n);if(o){let d=bl(o);for(let[p,u]of d){let g=ui(u.name,u.description||"",u.visualTags||[],r);g>0&&i.push({id:u.id,kind:Tg(u.category),label:u.name,description:u.description||"",matchContext:fl(u.name,u.description||"",r),score:g});}}let a=_t(n),c=wl(n,a.customContent);for(let d of c){let p=d.body.substring(0,200),u=ui(d.title,p,[],r);u>0&&i.push({id:d.slug,kind:"custom",label:d.title,description:d.description||p.substring(0,100),matchContext:fl(d.title,d.body,r),score:u});}let l=zn(n);if(l)for(let[d,p]of Object.entries(l.gates||{})){let u=d.replace(/^\^/,""),g=ui(u,p.description,[],r);g>0&&i.push({id:u,kind:"portal",label:`^${u}`,description:p.description,score:g});}return i.sort((d,p)=>p.score-d.score||d.label.localeCompare(p.label)),i.slice(0,t)}function ui(n,e,s,t){let i=n.toLowerCase(),r=e.toLowerCase();return i===t?1:i.startsWith(t)?.8:i.includes(t)?.6:r.includes(t)?.5:s.some(o=>o.toLowerCase().includes(t))?.3:0}function fl(n,e,s){let i=e.toLowerCase().indexOf(s);if(i<0)return n.toLowerCase().includes(s)?n:void 0;let r=Math.max(0,i-40),o=Math.min(e.length,i+s.length+40),a=e.substring(r,o).trim();return r>0&&(a=`...${a}`),o<e.length&&(a=`${a}...`),a}function Pl(){return [{name:"paradigm_docs_manifest",description:"Get the documentation sidebar manifest \u2014 all symbols grouped by type with counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_docs_page",description:"Get page data for a symbol, flow, portal, or custom docs page. Returns structured data for rendering. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol ID (e.g., "cli-commands", "checkout-flow", "authenticated"). Do not include the prefix (#, $, ^, !, ~).'},flow:{type:"string",description:'Flow ID (e.g., "$init-flow"). Include the $ prefix.'},portal:{type:"boolean",description:"Set to true to get the portal overview page (gates + routes)."},slug:{type:"string",description:'Custom page slug (e.g., "getting-started").'}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_docs_search",description:"Search across all documentation content \u2014 symbols, descriptions, tags, custom pages. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query string"},limit:{type:"number",description:"Maximum results (default: 20)"}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Rl(n,e,s){if(n==="paradigm_docs_manifest"){let t=_t(s.rootDir),i=_l(s.rootDir,t),r=JSON.stringify(i,null,2);return o(r.length,n),{handled:true,text:r}}if(n==="paradigm_docs_page"){if(e.portal){let i=xl(s.rootDir),r=JSON.stringify(i,null,2);return o(r.length,n),{handled:true,text:r}}if(e.flow){let i=e.flow,r=Sl(s.rootDir,i);if(!r){let a=JSON.stringify({error:`Flow "${i}" not found`});return o(a.length,n),{handled:true,text:a}}let o$1=JSON.stringify(r,null,2);return o(o$1.length,n),{handled:true,text:o$1}}if(e.slug){let i=_t(s.rootDir),r=vl(s.rootDir,e.slug,i);if(!r){let a=JSON.stringify({error:`Page "${e.slug}" not found`});return o(a.length,n),{handled:true,text:a}}let o$1=JSON.stringify(r,null,2);return o(o$1.length,n),{handled:true,text:o$1}}if(e.symbol){let i=kl(s.rootDir,e.symbol);if(!i){let o$1=JSON.stringify({error:`Symbol "${e.symbol}" not found`});return o(o$1.length,n),{handled:true,text:o$1}}let r=JSON.stringify(i,null,2);return o(r.length,n),{handled:true,text:r}}let t=JSON.stringify({error:"Provide one of: symbol, flow, portal, or slug"});return o(t.length,n),{handled:true,text:t}}if(n==="paradigm_docs_search"){let t=e.query;if(!t)return {handled:true,text:JSON.stringify({error:"query is required"})};let i=Cl(s.rootDir,t,e.limit),r=JSON.stringify({count:i.length,results:i},null,2);return o(r.length,n),{handled:true,text:r}}return {handled:false,text:""}}function Bn(n,e,s={}){let{maxResults:t=20}=s,i=[],r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=[`rg -n --no-heading "${r}" "${n}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${r}" "${n}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of o)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return i;let c=a.trim().split(`
|
|
836
|
+
`);for(let l of c.slice(0,t)){let d=l.match(/^(.+?):(\d+):(.*)$/);if(d){let[,p,u,g]=d,m=F.relative(n,p),y="unknown";m.includes(".purpose")||m.includes("portal.yaml")?y="purpose":g.includes("//")||g.includes("#")||g.includes("*")?y="comment":y="code",i.push({filePath:m,line:parseInt(u,10),content:g.trim().slice(0,200),context:y});}}return i}function Tl(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Dl(n,e,s){if(n!=="paradigm_ripple")return {handled:false,text:""};let{symbol:t,depth:i$1=3,includeWorkspace:r=false,response_format:o$1}=e,a=h$1(s.index,t);if(!a){let x=Ag(s.rootDir,t);return o(x.length,n),{handled:true,text:x}}let c=Math.min(Math.max(i$1||3,1),5),l$1=k(s.index,t),d=new Set([t]),p=new Map;function u(x,C){if(C>=c)return;let T=[];for(let j of x){if(d.has(j))continue;d.add(j);let P=k(s.index,j);for(let D of P)d.has(D.symbol)||T.push(D.symbol);}T.length>0&&(p.set(C+1,T),u(T,C+1));}u(l$1.map(x=>x.symbol),1);let g=new Set;for(let[,x]of p)for(let C of x)C!==t&&!l$1.find(T=>T.symbol===C)&&g.add(C);let m=l(s.index,t),y=l$1.length+g.size,f="low";y>10?f="high":y>3&&(f="medium");let b=await Cn(s.rootDir),h=null;if(b){let x=Pn(b,t);x.totalFlows>0&&(x.impactLevel==="high"&&f==="low"?f="medium":x.impactLevel==="high"&&(f="high"),h={totalFlows:x.totalFlows,affectedFlows:x.affectedFlows.map(C=>({flowId:C.flowId,impactLevel:C.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${C.stepAffected.position}, affects ${C.downstreamSteps.length} downstream steps`})),validationSuggestion:x.validationCommands.length>0?`Run: ${x.validationCommands[0]}`:void 0});}let w=new Set([t,...l$1.map(x=>x.symbol),...g]),_=[];try{let x=i(s.index,"gate");for(let C of x)w.has(C.symbol)&&_.push({gate:C.symbol,description:C.description});for(let C of l$1)C.type==="gate"&&!_.find(T=>T.gate===C.symbol)&&_.push({gate:C.symbol,description:C.description});}catch{}let k$1={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:f,analysis:{directlyAffected:l$1.map(x=>({symbol:x.symbol,type:x.type,description:x.description})),indirectlyAffected:Array.from(g),indirectByLevel:Object.fromEntries(p),dependsOn:m.map(x=>({symbol:x.symbol,type:x.type}))},summary:{directCount:l$1.length,indirectCount:g.size,totalAffected:y,dependsOnCount:m.length,levelsAnalyzed:c},recommendation:Og(f)};h&&(k$1.affectedFlows=h),_.length>0&&(k$1.affectedGates=_),k$1.suggestedReviewScope=Ig(f,l$1.length,g.size,_.length,h?.totalFlows??0);try{let x=await Q(s.rootDir,t);x.length>0&&(k$1.personas_affected=x,x.length>2&&f==="low"&&(k$1.impact="medium"));}catch{}try{let x=ka$1(s.rootDir,t);x.length>0&&(k$1.university_content_affected=x.map(C=>({id:C.id,title:C.title,type:C.type,stale:C.stale})));}catch{}if(r&&s.workspace){let x=vo(s.workspace,t);if(x.length>0){k$1.workspaceImpact={siblings:x.map(T=>({project:T.project,references:T.references.map(j=>({symbol:j.symbol,type:j.type,description:j.description}))}))};let C=x.reduce((T,j)=>T+j.references.length,0);C>0&&f==="low"&&(k$1.impact="medium"),C>5&&(k$1.impact="high");}}let v=o$1==="concise"?{symbol:k$1.symbol,impact:k$1.impact,summary:k$1.summary}:k$1,S=JSON.stringify(v,null,2);return o(S.length,n),{handled:true,text:S}}function Ag(n,e){let s=Bn(n,e,{maxResults:20});if(s.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let t=[...new Set(s.map(o=>o.filePath))],i={};for(let o of s)i[o.context]=(i[o.context]||0)+1;let r="low";return t.length>10||s.length>20?r="high":(t.length>3||s.length>5)&&(r="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:r,analysis:{filesAffected:t.slice(0,10),totalFilesAffected:t.length,totalReferences:s.length,contextBreakdown:i,sampleReferences:s.slice(0,5).map(o=>({file:o.filePath,line:o.line,preview:o.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function Og(n){switch(n){case "high":return "High impact change - review all affected symbols carefully before modifying";case "medium":return "Moderate impact - check direct dependencies for breaking changes";case "low":return "Low impact - safe to modify with standard review"}}function Ig(n,e,s,t,i){let r=[];return e>0&&r.push(`Review ${e} direct dependent(s) for breaking changes`),s>0&&r.push(`Scan ${s} indirect dependent(s) for cascading effects`),t>0&&r.push(`Verify ${t} affected gate(s) still enforce correct auth/access`),i>0&&r.push(`Validate ${i} affected flow(s) end-to-end`),n==="high"?r.push("Consider running full test suite before merging"):n==="medium"&&r.push("Run targeted tests for affected components"),r.length===0&&r.push("No downstream dependents detected - safe to proceed"),r}g$1();e();function Al(){return [{name:"paradigm_work_log_record",description:"Record a work log entry \u2014 what got done. Auto-attached to sprint boards and standup summaries. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent that did the work (e.g., "builder")'},summary:{type:"string",description:"What was done"},outcome:{type:"string",enum:["pass","fail","partial","blocked"],description:"How it went"},task_ref:{type:"string",description:'Ticket/issue reference (e.g., "ENG-142")'},files_modified:{type:"array",items:{type:"string"},description:"Files that were modified"},symbols_touched:{type:"array",items:{type:"string"},description:"Paradigm symbols touched"},next_steps:{type:"array",items:{type:"string"},description:"What's left to do"},blockers:{type:"array",items:{type:"string"},description:"What's blocking progress"},duration_minutes:{type:"number",description:"How long it took"},commit:{type:"string",description:"Git commit hash"}},required:["agent","summary","outcome"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_work_log_search",description:"Search work log entries \u2014 what got done. Returns recent work, filterable by agent, outcome, symbol, date. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent"},outcome:{type:"string",enum:["pass","fail","partial","blocked"]},task_ref:{type:"string",description:"Filter by ticket reference"},symbol:{type:"string",description:"Filter by symbol touched"},dateFrom:{type:"string",description:"Start date (YYYY-MM-DD)"},dateTo:{type:"string",description:"End date (YYYY-MM-DD)"},limit:{type:"number",description:"Max entries to return (default 20)"},summary:{type:"boolean",description:"Return aggregate summary instead of entries"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_journal_record",description:"Record a learning journal entry \u2014 what an agent learned. Agent-private, travels across projects. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent who learned this (e.g., "security")'},trigger:{type:"string",enum:["correction_received","confidence_miss","pattern_discovered","debate_loss","failure_analysis","human_feedback","self_reflection"],description:"What triggered this learning moment"},insight:{type:"string",description:"The insight itself"},project:{type:"string",description:"Project where this happened"},transferable:{type:"boolean",description:"Whether this applies to other projects"},confidence_before:{type:"number",description:"Confidence before (0.0-1.0)"},confidence_after:{type:"number",description:"Confidence after (0.0-1.0)"},pattern:{type:"object",properties:{id:{type:"string"},applies_when:{type:"string"},correct_approach:{type:"string"}}},linked_work_log:{type:"string",description:"Work log entry that prompted this"},tags:{type:"array",items:{type:"string"}}},required:["agent","trigger","insight","project","transferable"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_journal_search",description:"Search learning journal entries \u2014 what agents learned. Can search across all agents or a specific one. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent (omit for all agents)"},trigger:{type:"string",description:"Filter by trigger type"},project:{type:"string",description:"Filter by project"},transferable:{type:"boolean",description:"Only show transferable insights"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},stats:{type:"boolean",description:"Return stats instead of entries (requires agent)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_decision_record",description:"Record a team decision \u2014 what we decided and why. Institutional memory with rationale and alternatives. ~100 tokens.",inputSchema:{type:"object",properties:{title:{type:"string",description:"Decision title"},decision:{type:"string",description:"The decision itself"},rationale:{type:"string",description:"Why this was chosen"},participants:{type:"array",items:{type:"object",properties:{id:{type:"string"},role:{type:"string",enum:["human","agent"]},stance:{type:"string",enum:["proposed","supported","dissented","abstained","neutral"]}},required:["id","role","stance"]}},alternatives_considered:{type:"array",items:{type:"object",properties:{option:{type:"string"},rejected_because:{type:"string"}}}},symbols_affected:{type:"array",items:{type:"string"}},status:{type:"string",enum:["active","proposed"],description:"Decision status (default: active)"},tags:{type:"array",items:{type:"string"}}},required:["title","decision","rationale","participants"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_decision_search",description:"Search team decisions \u2014 what we decided. Find active decisions by symbol, participant, status. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",enum:["active","superseded","deprecated","proposed","rejected"]},participant:{type:"string",description:"Filter by participant ID"},symbol:{type:"string",description:"Filter by affected symbol"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},summary:{type:"boolean",description:"Return aggregate summary"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Ol(n,e,s){let t=i=>JSON.stringify(i,null,2);switch(n){case "paradigm_work_log_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.summary,i,"work_log"),o=a$4(s.rootDir,{agent:e.agent,summary:r,outcome:e.outcome,task_ref:e.task_ref,files_modified:e.files_modified,symbols_touched:e.symbols_touched,next_steps:e.next_steps,blockers:e.blockers,duration_minutes:e.duration_minutes,commit:e.commit});return {text:t({recorded:true,id:o.id,timestamp:o.timestamp}),handled:true}}case "paradigm_work_log_search":{if(e.summary){let r=d$5(s.rootDir,7);return {text:t(r),handled:true}}let i=b$5(s.rootDir,{agent:e.agent,outcome:e.outcome,task_ref:e.task_ref,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:t({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,summary:r.summary,outcome:r.outcome,timestamp:r.timestamp,symbols_touched:r.symbols_touched,task_ref:r.task_ref}))}),handled:true}}case "paradigm_journal_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.insight,i,"learning_journal"),o=a$3(e.agent,{trigger:e.trigger,insight:r,project:e.project,transferable:e.transferable,confidence_before:e.confidence_before,confidence_after:e.confidence_after,pattern:e.pattern,linked_work_log:e.linked_work_log,tags:e.tags});return {text:t({recorded:true,id:o.id,agent:o.agent,timestamp:o.timestamp}),handled:true}}case "paradigm_journal_search":{if(e.stats&&e.agent){let r=e$3(e.agent);return {text:t(r),handled:true}}let i=e.agent?b$4(e.agent,{trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20}):d$4({trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:t({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,trigger:r.trigger,insight:r.insight.slice(0,200),project:r.project,transferable:r.transferable,timestamp:r.timestamp}))}),handled:true}}case "paradigm_decision_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.decision,i,"team_decisions"),{filtered:o}=d$3(e.rationale,i,"team_decisions"),a=a$2(s.rootDir,{title:e.title,decision:r,rationale:o,participants:e.participants,alternatives_considered:e.alternatives_considered,symbols_affected:e.symbols_affected,status:e.status||"active",tags:e.tags});return {text:t({recorded:true,id:a.id,title:a.title,timestamp:a.timestamp}),handled:true}}case "paradigm_decision_search":{if(e.summary){let r=g$5(s.rootDir);return {text:t(r),handled:true}}let i=d$2(s.rootDir,{status:e.status,participant:e.participant,symbol:e.symbol,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:t({count:i.length,entries:i.map(r=>({id:r.id,title:r.title,status:r.status,decision:r.decision.slice(0,200),participants:r.participants.map(o=>`${o.id} (${o.stance})`),symbols_affected:r.symbols_affected,timestamp:r.timestamp}))}),handled:true}}default:return {text:`Unknown streams tool: ${n}`,handled:false}}}v();b$1();t();g$1();h();function Il(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_neverland",description:"Neverland Validation \u2014 aggregate learning metrics across all agents. Shows acceptance rates, threshold drift, expertise growth, notebook counts, cross-project transfer, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature). ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function $g(n){let e=Date.now(),s=n.match(/^(\d+)(m|h|d)$/);if(s){let t=parseInt(s[1],10),i=s[2],r=i==="m"?t*6e4:i==="h"?t*36e5:t*864e5;return new Date(e-r).toISOString()}return n}async function $l(n,e,s){let t=i=>JSON.stringify(i,null,2);switch(n){case "paradigm_ambient_nominations":{m$1(s.rootDir);let r=e.pending_only!==false,o=e.limit||20,a=i$2(s.rootDir,{agent:e.agent,urgency:e.urgency,pending_only:r,limit:o+20}),c=t$2(s.rootDir);a=u$1(a,c).slice(0,o);let l=F.join(s.rootDir,".paradigm/events/nominations.jsonl");if(O.existsSync(l))try{let p=O.readFileSync(l,"utf8"),u=new Set(a.map(m=>m.id)),g=p.trim().split(`
|
|
814
837
|
`).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(`
|
|
815
838
|
`)+`
|
|
816
|
-
`,"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
|
|
817
|
-
`),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 Og(s.rootDir,e)),handled:true};default:return {text:`Unknown ambient tool: ${n}`,handled:false}}}var Dg={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function Ag(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 Og(n,e={}){let s=e.dry_run===true,t=Ag(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(S=>S.verdict==="accepted").length;y.filter(S=>S.verdict==="dismissed").length;y.filter(S=>S.verdict==="revised").length;let w=y.length,_=w>0?f/w:0;for(let S of y){let v=Dg[S.verdict];if(!v)continue;let k=c.get(m)?.shift(),x=Ig(S,k,{acceptRate:_,total:w,accepted:f}),C=S.verdict==="accepted"?.85:S.verdict==="revised"?.6:.4,T={agent:m,verdict:S.verdict,trigger:v,insight:x,symbols:S.symbols};if(l.push(T),s)d[m]++,p++;else try{a$3(m,{trigger:v,insight:x,confidence_before:S.verdict==="accepted"?.7:.8,confidence_after:C,project:t,transferable:S.verdict==="dismissed",tags:["postflight",`verdict:${S.verdict}`,...(S.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 Ig(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 Yt=["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"],Fl={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 mi(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||"balanced",s=Fl[e]||Fl.balanced,t=n.enforcement?.checks||{},i=n.enforcement?.orchestration?.threshold??3,r={...s};for(let[o,a]of Object.entries(t))Yt.includes(o)&&Nl(a)&&(r[o]=a);return r.orchestrationThreshold=i,r}function Nl(n){return n==="block"||n==="warn"||n==="off"}function $g(n){return n==="strict"||n==="balanced"||n==="minimal"}function Fg(n){return Yt.includes(n)}var Ng=[{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: "+Yt.join(", ")},severity:{type:"string",enum:["block","warn","off"],description:"Severity to set for the check (for override action)."}},required:["action"]}}];async function Eg(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||"balanced",l=o.enforcement?.checks||{},d=o.enforcement?.orchestration?.threshold??3;return JSON.stringify({level:c,orchestrationThreshold:d,overrides:Object.keys(l).length>0?l:void 0,effective:a,checkIds:[...Yt],presetLevels:["strict","balanced","minimal"]},null,2)}case "set-level":{if(!t||!$g(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={},mi(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||!Fg(i))return JSON.stringify({error:`Invalid checkId "${i}". Must be one of: ${Yt.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,mi(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={}),mi(n.rootDir,o);let a=Yn(o),c=o.enforcement?.level||"balanced";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 El(){return Ng}async function Hl(n,e,s){if(n==="paradigm_enforcement_configure"){let t=await Eg(s,e);return o(t.length,"paradigm_enforcement_configure"),{handled:true,text:t}}return {handled:false,text:""}}function Hg(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 ql(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=Hg(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();function Lg(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:Xo,handleTool:i(Zo)},{key:"tags",tier:"core",getToolsList:_a,handleTool:i(Sa)},{key:"purpose-portal",tier:"core",getToolsList:Ta,handleTool:r$1(Da)},{key:"pm",tier:"core",getToolsList:Ba,handleTool:i(Va)},{key:"reindex",tier:"core",getToolsList:ma$1,handleTool:r$1(na$1)},{key:"docs",tier:"core",getToolsList:Pl,handleTool:i(Rl)},{key:"ripple",tier:"core",getToolsList:Tl,handleTool:i(Dl)}]),s$1.registerAll([{key:"wisdom",tier:"feature",getToolsList:Go,handleTool:i(Uo)},{key:"history",tier:"feature",getToolsList:zo,handleTool:i(Bo)},{key:"lore",tier:"feature",getToolsList:Xa,handleTool:i(Za)},{key:"streams",tier:"feature",getToolsList:Al,handleTool:i(Ol)},{key:"ambient",tier:"feature",getToolsList:Il,handleTool:i($l)},{key:"sentinel",tier:"feature",getToolsList:ea,handleTool:i(ta)},{key:"flows",tier:"feature",getToolsList:sa,handleTool:i(ia)},{key:"fixtures",tier:"feature",getToolsList:la,handleTool:i(da)},{key:"orchestration",tier:"feature",getToolsList:fa,handleTool:i(ya)},{key:"habits",tier:"feature",getToolsList:tc,handleTool:i(nc)},{key:"tasks",tier:"feature",getToolsList:mc,handleTool:i(fc)},{key:"personas",tier:"feature",getToolsList:Fc,handleTool:i(Nc)},{key:"protocols",tier:"feature",getToolsList:Ec,handleTool:i(Hc)},{key:"symphony",tier:"feature",getToolsList:il,handleTool:i(rl)},{key:"university",tier:"feature",getToolsList:al,handleTool:i(cl)},{key:"agents",tier:"feature",getToolsList:pl,handleTool:i(ul)},{key:"notebooks",tier:"feature",getToolsList:gl,handleTool:i(ml)},{key:"aspect-graph",tier:"feature",getToolsList:uc,handleTool:i(gc)},{key:"enforcement",tier:"feature",getToolsList:El,handleTool:i(Hl),detect:o=>O.existsSync(F.join(o,".paradigm","config.yaml"))},{key:"graph",tier:"feature",getToolsList:Lc,handleTool:i(Wc),detect:o=>O.existsSync(F.join(o,".paradigm","aspect-graph.db"))},{key:"heatmap",tier:"feature",getToolsList:Gc,handleTool:i(Uc),detect:o=>O.existsSync(F.join(o,".paradigm","aspect-graph.db"))}]),s$1.registerAll([{key:"conductor",tier:"advanced",getToolsList:tl,handleTool:i(nl)},{key:"platform",tier:"advanced",getToolsList:ll,handleTool:i(dl)},{key:"pipeline",tier:"advanced",getToolsList:Yc,handleTool:i(Kc)},{key:"graduation",tier:"advanced",getToolsList:oc,handleTool:i(ac)},{key:"assessment",tier:"advanced",getToolsList:xc,handleTool:i(Cc)}]),s$1}function Wg(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 Jg(){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 Ll(n$2,e,s){let t=e(),i$1=Lg(t.rootDir,s);n$2.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[...Jg(),...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$1(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||""}`,S=await v$1.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(S.length===0&&f){let C=n(c.index),T=C.map(j=>j.symbol);v=ql(g,T,{maxDistance:3,maxResults:5}),v.length>0&&(S=v.map(j=>C.find(P=>P.symbol===j.match)).filter(j=>j!=null),m&&(S=S.filter(j=>j.type===m)));}S=S.slice(0,y);let k={query:g,count:S.length,results:S.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&&(k.fuzzyMatched=true,k.fuzzyNote=`No exact matches for "${g}". Showing similar symbols.`,k.suggestions=v.map(C=>({symbol:C.match,distance:C.distance}))),b&&c.workspace){let C=Tt(c.workspace,g),T=m?C.filter(j=>j.type===m):C;T.length>0&&(k.workspaceResults=T.slice(0,y).map(j=>({symbol:j.symbol,type:j.type,description:j.description,filePath:j.filePath,project:j.project})),k.workspaceCount=T.length);}w==="concise"&&(k.results=S.map(C=>({symbol:C.symbol,type:C.type})),delete k.fuzzyMatched,delete k.fuzzyNote,delete k.suggestions,delete k.workspaceResults,delete k.workspaceCount);let x=JSON.stringify(k,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 k=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(k.length,o$1),{content:[{type:"text",text:k}]}}let w=[...new Set(h.map(k=>k.filePath))],_=h.filter(k=>k.context==="purpose"),S=h.filter(k=>k.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(k=>({file:k,references:h.filter(x=>x.filePath===k).length})),uses:[],summary:{totalFiles:w.length,totalReferences:h.length,purposeFileRefs:_.length,codeRefs:S.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$1.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=ga.platform(),_=w==="win32",S=_?"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 k=i(c.index,"component"),x={};for(let j of k)j.componentType&&(x[j.componentType]=(x[j.componentType]||0)+1);let C=k.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:S,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=Wg(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$/,"")||"",k=g.match(/\/:(id|[a-z]+Id)($|\/)/i);if(k&&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:k?"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:
|
|
839
|
+
`,"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?$g(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-J2H5OZBR.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=n$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 Eg(s.rootDir,e)),handled:true};default:return {text:`Unknown ambient tool: ${n}`,handled:false}}}var Fg={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 Eg(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=Fg[k.verdict];if(!v)continue;let S=c.get(m)?.shift(),x=Hg(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 Hg(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 Yt=["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"],Fl={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 mi(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||"balanced",s=Fl[e]||Fl.balanced,t=n.enforcement?.checks||{},i=n.enforcement?.orchestration?.threshold??3,r={...s};for(let[o,a]of Object.entries(t))Yt.includes(o)&&Nl(a)&&(r[o]=a);return r.orchestrationThreshold=i,r}function Nl(n){return n==="block"||n==="warn"||n==="off"}function qg(n){return n==="strict"||n==="balanced"||n==="minimal"}function Mg(n){return Yt.includes(n)}var Lg=[{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: "+Yt.join(", ")},severity:{type:"string",enum:["block","warn","off"],description:"Severity to set for the check (for override action)."}},required:["action"]}}];async function Wg(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||"balanced",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:[...Yt],presetLevels:["strict","balanced","minimal"]},null,2)}case "set-level":{if(!t||!qg(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={},mi(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||!Mg(i))return JSON.stringify({error:`Invalid checkId "${i}". Must be one of: ${Yt.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,mi(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={}),mi(n.rootDir,o);let a=Yn(o),c=o.enforcement?.level||"balanced";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 El(){return Lg}async function Hl(n,e,s){if(n==="paradigm_enforcement_configure"){let t=await Wg(s,e);return o(t.length,"paradigm_enforcement_configure"),{handled:true,text:t}}return {handled:false,text:""}}function Jg(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 ql(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=Jg(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();function zg(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:Xo,handleTool:i(Zo)},{key:"tags",tier:"core",getToolsList:_a,handleTool:i(ka)},{key:"purpose-portal",tier:"core",getToolsList:Ta,handleTool:r$1(Da)},{key:"pm",tier:"core",getToolsList:Ba,handleTool:i(Va)},{key:"reindex",tier:"core",getToolsList:ma$1,handleTool:r$1(na$1)},{key:"docs",tier:"core",getToolsList:Pl,handleTool:i(Rl)},{key:"ripple",tier:"core",getToolsList:Tl,handleTool:i(Dl)}]),s$1.registerAll([{key:"wisdom",tier:"feature",getToolsList:Go,handleTool:i(Uo)},{key:"history",tier:"feature",getToolsList:zo,handleTool:i(Bo)},{key:"lore",tier:"feature",getToolsList:Xa,handleTool:i(Za)},{key:"streams",tier:"feature",getToolsList:Al,handleTool:i(Ol)},{key:"ambient",tier:"feature",getToolsList:Il,handleTool:i($l)},{key:"sentinel",tier:"feature",getToolsList:ea,handleTool:i(ta)},{key:"flows",tier:"feature",getToolsList:sa,handleTool:i(ia)},{key:"fixtures",tier:"feature",getToolsList:la,handleTool:i(da)},{key:"orchestration",tier:"feature",getToolsList:fa,handleTool:i(ya)},{key:"habits",tier:"feature",getToolsList:tc,handleTool:i(nc)},{key:"tasks",tier:"feature",getToolsList:mc,handleTool:i(fc)},{key:"personas",tier:"feature",getToolsList:Fc,handleTool:i(Nc)},{key:"protocols",tier:"feature",getToolsList:Ec,handleTool:i(Hc)},{key:"symphony",tier:"feature",getToolsList:il,handleTool:i(rl)},{key:"university",tier:"feature",getToolsList:al,handleTool:i(cl)},{key:"agents",tier:"feature",getToolsList:pl,handleTool:i(ul)},{key:"notebooks",tier:"feature",getToolsList:gl,handleTool:i(ml)},{key:"aspect-graph",tier:"feature",getToolsList:uc,handleTool:i(gc)},{key:"enforcement",tier:"feature",getToolsList:El,handleTool:i(Hl),detect:o=>O.existsSync(F.join(o,".paradigm","config.yaml"))},{key:"graph",tier:"feature",getToolsList:Lc,handleTool:i(Wc),detect:o=>O.existsSync(F.join(o,".paradigm","aspect-graph.db"))},{key:"heatmap",tier:"feature",getToolsList:Gc,handleTool:i(Uc),detect:o=>O.existsSync(F.join(o,".paradigm","aspect-graph.db"))}]),s$1.registerAll([{key:"conductor",tier:"advanced",getToolsList:tl,handleTool:i(nl)},{key:"platform",tier:"advanced",getToolsList:ll,handleTool:i(dl)},{key:"pipeline",tier:"advanced",getToolsList:Yc,handleTool:i(Kc)},{key:"graduation",tier:"advanced",getToolsList:oc,handleTool:i(ac)},{key:"assessment",tier:"advanced",getToolsList:xc,handleTool:i(Cc)}]),s$1}function Bg(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 Vg(){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 Ll(n$2,e,s){let t=e(),i$1=zg(t.rootDir,s);n$2.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[...Vg(),...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$1(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$1.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=ql(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=Tt(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$1.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=ga.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=Bg(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:
|
|
818
841
|
`],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(`
|
|
819
842
|
Update command:
|
|
820
843
|
${b.join(` && \\
|
|
821
844
|
`)}`),f.push(`
|
|
822
845
|
After running, restart the session to apply updates.`)):f.push(`
|
|
823
846
|
Restart the session to apply cached updates.`);let h=f.join(`
|
|
824
|
-
`);return o(h.length,o$1),{content:[{type:"text",text:h}]}}case "paradigm_workspace_reindex":{if(!c.workspace){let f=JSON.stringify({error:"No workspace configured",suggestion:'Add a "workspace" field to .paradigm/config.yaml pointing to your .paradigm-workspace file, then run `paradigm workspace init` to create one.'},null,2);return o(f.length,o$1),{content:[{type:"text",text:f}]}}let{rebuildStaticFiles:g}=await import('./reindex-PGDQSM42.js'),m=[];for(let f of c.workspace.config.members){let b=F.resolve(F.dirname(c.workspace.workspacePath),f.path);try{let h=await g(b);m.push({name:f.name,symbolCount:h.symbolCount,status:"ok"});}catch(h){m.push({name:f.name,symbolCount:0,status:`error: ${h.message}`});}}let y=JSON.stringify({action:"workspace_reindex",workspace:c.workspace.config.name,members:m,totalSymbols:m.reduce((f,b)=>f+b.symbolCount,0)},null,2);return o(y.length,o$1),v$1.clear(),{content:[{type:"text",text:y}]}}case "paradigm_tool_activate":{let g=a$1.feature,m=i$1.activateAdvanced(g);if(m){let h=JSON.stringify({action:"tool_activate",feature:g,status:"activated",toolsAdded:m.map(w=>w.name),note:`Advanced module "${g}" activated for this session. ${m.length} tool(s) now available.`},null,2);return o(h.length,o$1),{content:[{type:"text",text:h}]}}let y=i$1.getRegistryInfo(),f=y.activeFeatures.includes(g),b=JSON.stringify({action:"tool_activate",feature:g,status:f?"already_active":"not_found",note:f?`Module "${g}" is already active (auto-detected or core tier).`:`Module "${g}" not found. Available advanced modules: ${y.availableAdvanced.join(", ")||"(none)"}`,availableAdvanced:y.availableAdvanced},null,2);return o(b.length,o$1),{content:[{type:"text",text:b}]}}default:{let g=await i$1.dispatch(o$1,a$1,c);if(g&&g.handled)return o$1.startsWith("paradigm_context_")||o$1.startsWith("paradigm_session_")||o$1==="paradigm_handoff_prepare"||o(g.text.length,o$1),
|
|
847
|
+
`);return o(h.length,o$1),{content:[{type:"text",text:h}]}}case "paradigm_workspace_reindex":{if(!c.workspace){let f=JSON.stringify({error:"No workspace configured",suggestion:'Add a "workspace" field to .paradigm/config.yaml pointing to your .paradigm-workspace file, then run `paradigm workspace init` to create one.'},null,2);return o(f.length,o$1),{content:[{type:"text",text:f}]}}let{rebuildStaticFiles:g}=await import('./reindex-PGDQSM42.js'),m=[];for(let f of c.workspace.config.members){let b=F.resolve(F.dirname(c.workspace.workspacePath),f.path);try{let h=await g(b);m.push({name:f.name,symbolCount:h.symbolCount,status:"ok"});}catch(h){m.push({name:f.name,symbolCount:0,status:`error: ${h.message}`});}}let y=JSON.stringify({action:"workspace_reindex",workspace:c.workspace.config.name,members:m,totalSymbols:m.reduce((f,b)=>f+b.symbolCount,0)},null,2);return o(y.length,o$1),v$1.clear(),{content:[{type:"text",text:y}]}}case "paradigm_tool_activate":{let g=a$1.feature,m=i$1.activateAdvanced(g);if(m){let h=JSON.stringify({action:"tool_activate",feature:g,status:"activated",toolsAdded:m.map(w=>w.name),note:`Advanced module "${g}" activated for this session. ${m.length} tool(s) now available.`},null,2);return o(h.length,o$1),{content:[{type:"text",text:h}]}}let y=i$1.getRegistryInfo(),f=y.activeFeatures.includes(g),b=JSON.stringify({action:"tool_activate",feature:g,status:f?"already_active":"not_found",note:f?`Module "${g}" is already active (auto-detected or core tier).`:`Module "${g}" not found. Available advanced modules: ${y.availableAdvanced.join(", ")||"(none)"}`,availableAdvanced:y.availableAdvanced},null,2);return o(b.length,o$1),{content:[{type:"text",text:b}]}}default:{let g=await i$1.dispatch(o$1,a$1,c);if(g&&g.handled)return o$1.startsWith("paradigm_context_")||o$1.startsWith("paradigm_session_")||o$1==="paradigm_handoff_prepare"||o(g.text.length,o$1),Yg(o$1,a$1,c.rootDir),{content:[{type:"text",text:g.text}]};throw new Error(`Unknown tool: ${o$1}`)}}})();if(d||p){let g=u.content?.[0];if(g&&typeof g=="object"&&"text"in g&&typeof g.text=="string"){let m=[p,d].filter(Boolean).join(`
|
|
825
848
|
|
|
826
849
|
`);g.text=m+`
|
|
827
850
|
|
|
828
|
-
`+g.text;}}return u});}function
|
|
851
|
+
`+g.text;}}return u});}function Yg(n,e,s){try{switch(n){case "paradigm_sentinel_record":n$1(s,{type:"error-encountered",source:"mcp-tool-call",tool:n,severity:e.severity||"warning",context:`Sentinel: ${e.title||e.summary||"incident recorded"}`});break;case "paradigm_lore_record":n$1(s,{type:"work-completed",source:"mcp-tool-call",tool:n,symbols:Array.isArray(e.symbols_touched)?e.symbols_touched.map(String):[],context:`Lore recorded: ${e.title||"untitled"}`});break;case "paradigm_work_log_record":case "paradigm_journal_record":n$1(s,{type:"work-completed",source:"mcp-tool-call",tool:n,symbols:Array.isArray(e.symbols)?e.symbols.map(String):[],context:`Work logged: ${e.summary||e.title||"entry"}`});break;case "paradigm_decision_record":n$1(s,{type:"decision-made",source:"mcp-tool-call",tool:n,symbols:Array.isArray(e.symbols)?e.symbols.map(String):[],context:`Decision: ${e.title||e.summary||"recorded"}`});break;case "paradigm_persona_run":n$1(s,{type:"work-completed",source:"mcp-tool-call",tool:n,context:`Persona run: ${e.persona||"unknown"}`});break;case "paradigm_protocol_record":n$1(s,{type:"work-completed",source:"mcp-tool-call",tool:n,context:`Protocol recorded: ${e.name||e.id||"unknown"}`});break;case "paradigm_reindex":n$1(s,{type:"work-completed",source:"mcp-tool-call",tool:n,context:"Index rebuilt"},{skipNominations:!0});break;default:(n.startsWith("paradigm_purpose_")||n.startsWith("paradigm_portal_"))&&(n.includes("_add_")||n.includes("_update_")||n.includes("_remove_"))&&n$1(s,{type:"file-modified",source:"mcp-tool-call",tool:n,symbols:e.id?[`#${e.id}`]:e.symbol?[String(e.symbol)]:[],context:`Purpose/portal update via ${n}`});break}}catch{}}var Kt=process.argv[2]||process.cwd(),Je=null;function Wl(){if(!Je)throw new Error("Project context not loaded");return Je}async function Xg(){Je=await Ps(Kt),oa(Kt,Je).catch(n=>{console.error("[paradigm-mcp] Background reindex:",n.message);});}async function Zg(){console.error(`[paradigm-mcp] Loading project from: ${Kt}`);try{Je=await Ps(Kt),j$1().setRootDir(Je.rootDir),console.error(`[paradigm-mcp] Loaded ${Je.aggregation.symbols.length} symbols from ${Je.projectName}`);}catch(s){console.error("[paradigm-mcp] Error loading project:",s),process.exit(1);}el(Kt);let n=new Server({name:"paradigm",version:"0.1.0"},{capabilities:{resources:{},tools:{}}});Wo(n,Wl),Ll(n,Wl,Xg),n.onerror=s=>{console.error("[paradigm-mcp] Server error:",s);};let e=new StdioServerTransport;await n.connect(e),console.error("[paradigm-mcp] Server running on stdio");}Zg().catch(n=>{console.error("[paradigm-mcp] Fatal error:",n),process.exit(1);});
|