@a-company/paradigm 6.2.0 → 6.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/arch-loader-T3TARMSO.js +2 -0
  2. package/dist/chunk-32XL3FIQ.js +2 -0
  3. package/dist/chunk-ARLB6YYW.js +3 -0
  4. package/dist/chunk-EMGJWT7D.js +111 -0
  5. package/dist/chunk-SRWROALW.js +666 -0
  6. package/dist/chunk-SU5F5D4I.js +3 -0
  7. package/dist/{enforcement-46XWPNSA.js → enforcement-FXO6IYYE.js} +1 -1
  8. package/dist/{enforcement-BEGPQIUN.js → enforcement-VRE3WZOI.js} +1 -1
  9. package/dist/index.js +2 -2
  10. package/dist/mcp.js +3 -52
  11. package/dist/reindex-PJVOMN57.js +2 -0
  12. package/dist/rune-promotion-3JQ5LMWK.js +3 -0
  13. package/dist/{shift-3ATE2ONQ.js → shift-6Y3KQP62.js} +2 -2
  14. package/dist/tools-2XPMZZBT.js +2 -0
  15. package/dist/university-content/notes/N-para-001-shift-setup.md +2 -2
  16. package/dist/university-content/notes/N-para-301-enforcement-levels.md +18 -11
  17. package/dist/university-content/notes/N-para-301-paradigm-shift.md +2 -2
  18. package/dist/university-content/notes/N-para-301-rune-promotion.md +69 -0
  19. package/dist/university-content/notes/N-para-501-hook-enforcement.md +3 -1
  20. package/dist/university-content/notes/N-para-701-orchestration-enforcement.md +10 -1
  21. package/dist/university-content/quizzes/Q-para-301-enforcement-levels.yaml +21 -1
  22. package/dist/university-content/quizzes/Q-para-701-orchestration-enforcement.yaml +11 -1
  23. package/dist/university-ui/assets/{index-CkgaxOXi.js → index-SNyIB61M.js} +2 -2
  24. package/dist/university-ui/assets/{index-CkgaxOXi.js.map → index-SNyIB61M.js.map} +1 -1
  25. package/dist/university-ui/index.html +1 -1
  26. package/package.json +1 -1
  27. package/dist/chunk-K7EQHFZP.js +0 -111
  28. package/dist/chunk-KYA4TP26.js +0 -2
  29. package/dist/chunk-UMC4RC66.js +0 -636
  30. package/dist/reindex-GSRV4MQO.js +0 -2
  31. package/dist/tools-F34P22PW.js +0 -2
@@ -1,636 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a as a$1,b as b$3}from'./chunk-4UJ4NIEQ.js';import {e,v,b as b$2,n,c as c$2,d as d$3,q as q$2,p,o as o$1,s as s$1,i as i$2,k as k$1,l as l$1,a as a$6,m as m$1,t as t$1,u as u$1,j as j$3}from'./chunk-4N56FRNE.js';import {a as a$2,d as d$1,h as h$4,e as e$3}from'./chunk-Q527BPUF.js';import {o as o$2,A,y,x,f as f$5,r as r$1}from'./chunk-KLBH26PA.js';import {d as d$5,b as b$6,a as a$5}from'./chunk-JNSJVCTU.js';import {i as i$4}from'./chunk-XROULIQN.js';import {n as n$2,j as j$4,P,O,K,Q,L,I,J,D as D$1,H as H$1,m as m$2,l as l$2,E as E$2,v as v$2,N,q as q$3,C as C$1,S,o as o$3,z as z$2,t as t$2,B as B$1,s as s$2}from'./chunk-ZUAUFZRJ.js';import {f,g as g$1,e as e$1,q as q$1,t,o,v as v$1,i,m,$,h as h$1,k,l,j as j$2,n as n$1,u,r,sa,s,ta as ta$1,fa as fa$1,ga,F,X as X$1,ea as ea$1,x as x$1,E as E$1,D,G,w,C,B,A as A$1,z as z$1,y as y$1,_,da,Z as Z$1,ca as ca$1,ba as ba$1,aa as aa$1,J as J$1,U,K as K$1,O as O$1,Q as Q$1,S as S$1,R,V,T,P as P$1,N as N$1,Y as Y$1,W as W$1,a as a$9,d as d$9,c as c$4,L as L$1,M as M$1,ha as ha$1,ia as ia$1,qa as qa$1,pa as pa$1,ja as ja$1,na as na$1,ka as ka$1,la as la$1,ma as ma$1,ra as ra$1,oa as oa$1,I as I$1,b as b$b,H as H$2}from'./chunk-K7EQHFZP.js';import {j,a as a$3,i as i$1,b as b$4,h as h$3,g as g$3,c as c$1,d as d$2}from'./chunk-GRZQIKST.js';import {z,f as f$2,p as p$1,h as h$5,b as b$8,d as d$7,e as e$6,i as i$3,y as y$2,l as l$3,c as c$5}from'./chunk-KAFQA7HV.js';import {j as j$1,d,e as e$2,f as f$1,g as g$2,h as h$2}from'./chunk-6QXBXZF6.js';import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import {q,e as e$8,b as b$a,f as f$4}from'./chunk-LAYBUKMB.js';import {f as f$3,b as b$7,e as e$5,d as d$6,a as a$7,c as c$3}from'./chunk-DVZWCXB6.js';import {g,e as e$4,b as b$5,d as d$4,a as a$4}from'./chunk-QGZRM6ZB.js';import {h,e as e$7,d as d$8,b as b$9,a as a$8}from'./chunk-K7X3Z3GL.js';import {b,c,d as d$a}from'./chunk-5TAVYPOV.js';import*as E from'fs';import*as H from'path';import*as Te from'js-yaml';import*as wa from'os';import {ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import {execSync}from'child_process';import*as Et from'crypto';import*as vt from'fs/promises';var qt,Ks,Qs=b(()=>{qt={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"]},Ks=new Set(["tool-called","context-checked"]);});var Ba={};c(Ba,{getAllStates:()=>Zs,getConfig:()=>lt,getState:()=>Gn,incrementFailure:()=>Ua,invalidateGraduationCache:()=>Jp,isGraduated:()=>Wp,loadGraduation:()=>ze,markNeverGraduate:()=>Gp,saveGraduation:()=>Wn,setTier:()=>Ja});function Ga(t){return H.join(t,".paradigm","graduation.yaml")}function ze(t){let e=H.resolve(t);if(Lt&&qn===e&&Date.now()-Ln<Mp)return Lt;let s=Ga(e),n;if(E.existsSync(s))try{let i=E.readFileSync(s,"utf8");n=Te.load(i);}catch{n={version:"1.0",config:{},states:{}};}else n={version:"1.0",config:{},states:{}};return n.version||(n.version="1.0"),n.config||(n.config={}),n.states||(n.states={}),Lt=n,qn=e,Ln=Date.now(),n}function Wn(t,e){let s=H.resolve(t),n=Ga(s),i=H.dirname(n);E.existsSync(i)||E.mkdirSync(i,{recursive:true});let r=Te.dump(e,{lineWidth:120,noRefs:true,sortKeys:true});E.writeFileSync(n,r,"utf8"),Lt=e,qn=s,Ln=Date.now();}function lt(t){let e=ze(t);return {...qt,...e.config,thresholds:{...qt.thresholds,...e.config?.thresholds},demotion:{...qt.demotion,...e.config?.demotion},neverGraduate:e.config?.neverGraduate??qt.neverGraduate}}function Xs(t){return {habitId:t,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function Gn(t,e){let n=ze(t).states[e];return n?{...Xs(e),...n,habitId:e}:Xs(e)}function Zs(t){let e=ze(t),s={};for(let[n,i]of Object.entries(e.states))s[n]={...Xs(n),...i,habitId:n};return s}function Wp(t,e){return Gn(t,e).tier==="hook"}function Ja(t,e,s,n){let i=ze(t),r=i.states[e]||{};i.states[e]={...r,tier:s,previousTier:r.tier||"habit",...s==="hook"?{graduatedAt:new Date().toISOString(),failureCount:0}:{},...s==="habit"&&r.tier==="hook"?{demotedAt:new Date().toISOString()}:{},...n},Wn(t,i);}function Gp(t,e){let s=ze(t);s.states[e]||(s.states[e]={}),s.states[e].neverGraduate=true,s.states[e].tier="habit",Wn(t,s);}function Ua(t,e){let s=ze(t);s.states[e]||(s.states[e]={});let n=(s.states[e].failureCount||0)+1;return s.states[e].failureCount=n,Wn(t,s),n}function Jp(){Lt=null,qn=null,Ln=0;}var Lt,qn,Ln,Mp,Jn=b(()=>{Qs();Lt=null,qn=null,Ln=0,Mp=3e4;});b$1();b$1();var Yl=30*1e3,Is=new Map,Co=".paradigm/wisdom";async function Ro(t){let e=H.resolve(t),s=Is.get(e);if(s&&Date.now()-s.loadedAt<Yl)return s.context;let n=await Vl(e);return Is.set(e,{context:n,loadedAt:Date.now()}),n}async function Vl(t){let e=H.join(t,Co),s=E.existsSync(e),[n,i,r,o]=s?await Promise.all([Kl(e),Ql(e),Xl(e),Zl(e)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e$2(),l=f$1();}catch{}let d$1=new Set(i.map(y=>y.id)),p=i.map(y=>({...y,scope:"project"}));for(let y of a)d$1.has(y.id)||p.push({...y,scope:"global"});let u=new Set(o.map(y=>y.id)),g=o.map(y=>({...y,scope:"project"}));for(let y of c)u.has(y.id)||g.push({...y,scope:"global"});let m=n;if(l&&!n)m=l;else if(l&&n){let y={...n.by_symbol};if(l.by_symbol)for(let[f,b]of Object.entries(l.by_symbol))y[f]||(y[f]=b);m={...n,by_symbol:y,global:{...l.global,...n.global}};}return {preferences:m,antipatterns:p,decisions:g,expertise:r}}function Le(t){let e=H.resolve(t);Is.delete(e);}async function Kl(t){let e=H.join(t,"preferences.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch(s){return a.component("#wisdom-loader").error("Error parsing preferences.yaml",{error:s}),null}}async function Ql(t){let e=H.join(t,"antipatterns.yaml");if(!E.existsSync(e))return [];try{let s=E.readFileSync(e,"utf8");return Te.load(s).antipatterns||[]}catch(s){return a.component("#wisdom-loader").error("Error parsing antipatterns.yaml",{error:s}),[]}}async function Xl(t){let e=H.join(t,"expertise.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch(s){return a.component("#wisdom-loader").error("Error parsing expertise.yaml",{error:s}),null}}var xo=new Set;async function Zl(t){let e=H.join(t,"decisions");if(!E.existsSync(e))return [];let s=[];try{let n=E.readdirSync(e);n.some(r=>r.endsWith(".yaml")||r.endsWith(".yml"))&&!xo.has(e)&&(xo.add(e),a.component("#wisdom-loader").warn("wisdom-decisions found; run `paradigm migrate decisions` in v6.0. In v5.39.0 wisdom-decisions are still read but will be migrated to TD-streams in v6.0."));for(let r of n){if(!r.endsWith(".yaml")&&!r.endsWith(".yml"))continue;let o=H.join(e,r);try{let a=E.readFileSync(o,"utf8"),c=Te.load(a);s.push(c);}catch(a$1){a.component("#wisdom-loader").error(`Error parsing ${r}`,{error:a$1});}}}catch(n){a.component("#wisdom-loader").error("Error reading decisions directory",{error:n});}return s.sort((n,i)=>n.id.localeCompare(i.id)),s}function Po(t,e){return e.map(s=>ed(t,s))}function ed(t,e){let s=t.preferences?.by_symbol?.[e]||null,n=t.antipatterns.filter(o=>o.symbols.some(a=>a===e||bn(e,a))),i=t.decisions.filter(o=>o.symbols.some(a=>a===e||bn(e,a))),r=t.expertise?.experts.filter(o=>o.symbols?.some(a=>a===e||bn(e,a)))||[];return {symbol:e,preferences:s,antipatterns:n,decisions:i,experts:r}}function jo(t,e){return t.expertise?t.expertise.experts.filter(s=>!!(e.symbol&&s.symbols&&s.symbols.some(n=>n===e.symbol||bn(e.symbol,n))||e.area&&s.areas&&s.areas.some(n=>n.toLowerCase().includes(e.area.toLowerCase())))):[]}function bn(t,e){if(e.endsWith("*")){let s=e.slice(0,-1);return t.startsWith(s)}return t===e}async function Ao(t,e){let s=H.join(t,Co),n=H.join(s,"antipatterns.yaml");E.existsSync(s)||E.mkdirSync(s,{recursive:true});let i={version:"1.0",antipatterns:[]};if(E.existsSync(n)){let r=E.readFileSync(n,"utf8");i=Te.load(r);}i.antipatterns.push({...e,added:new Date().toISOString()}),E.writeFileSync(n,Te.dump(i,{lineWidth:-1})),Le(t);}b$1();var To=".paradigm/history";async function Do(t){let e=H.join(t,To);if(!E.existsSync(e))return {index:null,validation:null};let[s,n]=await Promise.all([td(e),nd(e)]);return {index:s,validation:n}}async function td(t){let e=H.join(t,"index.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch(s){return a.component("#history-loader").error("Error parsing index.yaml",{error:s.message}),null}}async function nd(t){let e=H.join(t,"validation.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch(s){return a.component("#history-loader").error("Error parsing validation.yaml",{error:s.message}),null}}function Oo(t,e){return e.map(s=>sd(t,s))}function sd(t,e){let s=t.index?.by_symbol?.[e]||null,n=[];if(t.index?.co_changes){for(let r of t.index.co_changes)if(r.symbols.includes(e))for(let o of r.symbols)o!==e&&!n.includes(o)&&n.push(o);}let i=t.validation?.by_symbol?.[e]||null;return {symbol:e,summary:s,recent:s?.recent||[],co_changes:n,validation:i}}function Io(t,e){let s=[],n=[];if(!t.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let o of e){let a=t.index.by_symbol?.[o];a&&(a.fragility==="high"||a.fragility==="critical")&&s.push({symbol:o,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=t.index.fragile_symbols?.find(l=>l.symbol===o);c&&!s.find(l=>l.symbol===o)&&s.push(c);}for(let o of e){let a=t.index.co_changes?.filter(c=>c.symbols.includes(o));if(a?.length)for(let c of a){let l=c.symbols.filter(d=>d!==o&&!e.includes(d));l.length>0&&c.correlation>.7&&n.push(`${o} often changes with ${l.join(", ")} (${Math.round(c.correlation*100)}% correlation)`);}}let i=s.filter(o=>o.fragility==="critical").length===0,r=[];return s.length>0&&(r.push("Consider adding extra test coverage before modifying fragile symbols"),r.push("Review recent rollbacks and failures for these symbols")),n.length>0&&r.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:s,warnings:n,safe_to_modify:i,recommendations:r}}async function $s(t,e){let s=H.join(t,To),n=H.join(s,"log.jsonl");E.existsSync(s)||E.mkdirSync(s,{recursive:true});let i=id(n),r=new Date().toISOString(),o={id:i,ts:r,...e},a=JSON.stringify(o)+`
3
- `;return E.appendFileSync(n,a),i}async function $o(t,e,s,n){return $s(t,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:s,tests:n})}function id(t){let e=1;return E.existsSync(t)&&(e=E.readFileSync(t,"utf8").split(`
4
- `).filter(n=>n.trim()).length+1),`h${String(e).padStart(4,"0")}`}b$1();function rd(t){let e=H.resolve(t),s=E.readFileSync(e,"utf8"),n=Te.load(s);if(!n||typeof n!="object")throw new Error(`Invalid workspace file: ${t}`);let i={version:String(n.version||"1.0"),name:String(n.name||"unnamed-workspace"),members:[]};if(Array.isArray(n.members)){for(let r of n.members)if(typeof r=="object"&&r!==null){let o=r;i.members.push({name:String(o.name||""),path:String(o.path||""),role:o.role,exports:Array.isArray(o.exports)?o.exports.map(String):void 0});}}return i}function No(t,e){let s=H.resolve(t),n=H.resolve(s,e);if(!E.existsSync(n))return a.component("#workspace-loader").warn("Workspace file not found",{workspacePath:n}),null;let i;try{i=rd(n);}catch(c){return a.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let r=H.dirname(n),o="";for(let c of i.members){let l=H.resolve(r,c.path);if(Fo(l)===Fo(s)){o=c.name;break}}if(!o)return a.component("#workspace-loader").warn("Current directory is not a member of workspace",{workspace:i.name}),null;let a$1=new Map;for(let c of i.members){if(c.name===o)continue;let l=H.resolve(r,c.path),d=H.join(l,".paradigm","scan-index.json");if(!E.existsSync(d)){a.component("#workspace-loader").warn("No scan-index.json for workspace member",{member:c.name,scanIndexPath:d});continue}try{let p=JSON.parse(E.readFileSync(d,"utf8")),u=cd(p);c.exports&&c.exports.length>0&&(u=od(u,c.exports));let g=null,m=H.join(l,"portal.yaml");if(E.existsSync(m))try{let y=E.readFileSync(m,"utf8"),f=Te.load(y);f&&(g=f);}catch{}a$1.set(c.name,{index:u,gateConfig:g});}catch(p){a.component("#workspace-loader").warn("Could not load index for workspace member",{member:c.name,error:p.message});}}return {config:i,workspacePath:n,currentMember:o,siblingIndices:a$1}}function od(t,e){let n=n$1(t).filter(i=>{let r=i.symbol;return e.some(o=>ad(o,r))});return ld(n)}function ad(t,e){let s=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${s}$`,"i").test(e)}function jt(t,e){let s=[];for(let[n,i]of t.siblingIndices){let r=j$2(i.index,e);for(let o of r)s.push({project:n,symbol:`${n}/${o.symbol}`,type:o.type,description:o.description,filePath:o.filePath});}return s}function Eo(t,e){let s=[],n=e.includes("/")?e.split("/").pop():e;for(let[i,r]of t.siblingIndices){let o=[],a=n$1(r.index);for(let c of a){let l=c.references||[],d=c.description||"",p=l.some(g=>g===n||g===e||g.endsWith(`/${n}`)),u=d.includes(n);(p||u)&&o.push({symbol:c.symbol,type:c.type,description:c.description});}o.length>0&&s.push({project:i,references:o});}return s}function Fo(t){return H.resolve(t).replace(/\/+$/,"")}function cd(t){let e={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"},s=[];for(let[n,i]of Object.entries(e)){let r=t[n];if(!(!r||typeof r!="object"))for(let[o,a]of Object.entries(r)){let c={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"}[i]||"#";s.push({id:o,symbol:a.symbol||`${c}${o}`,type:i,source:"purpose",filePath:a.path||"",data:{},references:a.related||[],referencedBy:[],description:a.description,tags:a.visualTags||[]});}}return g$1({symbols:s,purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}function ld(t){return g$1({symbols:t.map(e=>({id:e.id||e.symbol.replace(/^[#$^!~]/,""),symbol:e.symbol,type:e.type,source:"purpose",filePath:e.filePath||"",data:e.data||{},references:e.references||[],referencedBy:e.referencedBy||[],description:e.description,tags:e.tags})),purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}async function im(t){let e=H.resolve(t),s=await f(e),n=g$1(s),i=null,r=H.join(e,"portal.yaml");if(E.existsSync(r))try{i=await e$1(r);}catch(d){let p=d?.name??"Error";a.component("#index-loader").warn("Could not parse portal.yaml",{errorClass:p});}let o=H.basename(e),a$1=H.join(e,".premise");if(E.existsSync(a$1))try{let p=E.readFileSync(a$1,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);p&&(o=p[1].trim());}catch{}let c=null,l=H.join(e,".paradigm","config.yaml");if(E.existsSync(l))try{let d=E.readFileSync(l,"utf8"),p=Te.load(d);p&&typeof p=="object"&&(p.version||a.component("#index-loader").warn('config.yaml missing "version" field'),p.project||a.component("#index-loader").warn('config.yaml missing "project" field')),p&&typeof p.workspace=="string"&&(c=No(e,p.workspace));}catch(d){a.component("#index-loader").warn("Failed to load workspace config",{error:d.message});}return {rootDir:e,index:n,aggregation:s,gateConfig:i,projectName:o,wisdom:null,history:null,workspace:c,_loadedAt:Date.now()}}async function vn(t){return t.wisdom||(t.wisdom=await Ro(t.rootDir)),t.wisdom}async function Ns(t){return t.history||(t.history=await Do(t.rootDir)),t.history}j();b$1();var qo=false;function Mo(){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 kn(t,e,s){switch(t){case "paradigm_wisdom_context":{let{symbols:n,include_global:i=true}=e,r=await vn(s),o=Po(r,n),a={symbols:n,wisdom:o.map(d=>({symbol:d.symbol,preferences:d.preferences,antipatterns:d.antipatterns.map(p=>({id:p.id,description:p.description,reason:p.reason,alternative:p.alternative,scope:p.scope||"project"})),decisions:d.decisions.map(p=>({id:p.id,title:p.title,status:p.status,decision:p.decision,scope:p.scope||"project"})),experts:d.experts.map(p=>p.name)}))};i&&r.preferences?.global&&(a.global_preferences=r.preferences.global);let c=o.reduce((d,p)=>d+p.antipatterns.length,0),l=o.reduce((d,p)=>d+p.decisions.length,0);a.summary={symbols_with_preferences:o.filter(d=>d.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:o.some(d=>d.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let d={},p=[];for(let u of n){let g=await a$3(s.rootDir,{symbol:u,hasAssessment:!0,limit:100});if(g.length===0)continue;let m={correct:0,partial:0,incorrect:0},y=0,f=0;for(let h of g){let w=h.assessment.verdict;m[w]++,h.confidence!=null&&(y+=h.confidence,f++);}d[u]={total:g.length,...m,avgConfidence:f>0?Math.round(y/f*1e3)/1e3:null};let b=(m.correct+m.partial*.5)/g.length;b<.6&&g.length>=3&&p.push(`Low historical accuracy for ${u}: ${Math.round(b*100)}% across ${g.length} entries. Proceed with extra caution.`);}Object.keys(d).length>0&&(a.calibration=d),p.length>0&&(a.calibration_warnings=p);}catch{}return {handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_wisdom_record":{let{type:n,id:i,symbols:r,description:o,reason:a$1,alternative:c,title:l,status:d,rationale:p,consequences:u,scope:g="project"}=e;if(n==="antipattern"){if(!o||!a$1||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let m={id:i,symbols:r,description:o,reason:a$1,alternative:c};return g==="global"?g$2(m):await Ao(s.rootDir,m),Le(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:i,scope:g,message:`Antipattern recorded to ${g} scope`})}}if(n==="decision"){if(!l||!o||!p||!u)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};if(qo||(qo=true,a.component("#wisdom").warn('paradigm_wisdom_record({type:"decision"}) is deprecated. Use paradigm_decision_record instead.',{deprecation:"v6.0",canonical_tool:"paradigm_decision_record"})),g==="global"){let f={id:i,title:l,status:d||"proposed",date:new Date().toISOString().split("T")[0],symbols:r,context:a$1||"",decision:o,rationale:p,consequences:u};return h$2(f),Le(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:i,scope:"global",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record for project-scoped decisions.',message:"Decision recorded to global scope"})}}let m=a$2(s.rootDir,{title:l,decision:o,rationale:{factors:p.factors,conclusion:p.conclusion},participants:[{id:"wisdom-record",role:"agent",stance:"proposed"}],symbols_affected:r,status:d==="accepted"?"active":d==="proposed"?"proposed":"active",context:a$1||void 0,consequences:u,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),y=d$1(s.rootDir,m.id);return Le(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:m.id,legacy_id:i,scope:"project",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record going forward.',message:`Decision recorded (routed to decisions stream as ${m.id})`,...y?{companion_lore_id:y}:{}})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${n}`})}}case "paradigm_wisdom_promote":{let{type:n,id:i}=e,r=await vn(s),o=H.basename(s.rootDir);if(n==="antipattern"){let a=r.antipatterns.find(l=>l.id===i);return a?d().some(l=>l.id===i)?{handled:true,text:JSON.stringify({error:`Antipattern "${i}" already exists in global scope`})}:(g$2({...a,learned_from:`promoted from ${o}`}),Le(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:i,promoted_from:o,message:`Antipattern "${i}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${i}" not found in project`})}}if(n==="decision"){let a=r.decisions.find(l=>l.id===i);return a?e$2().some(l=>l.id===i)?{handled:true,text:JSON.stringify({error:`Decision "${i}" already exists in global scope`})}:(h$2(a),Le(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:i,promoted_from:o,message:`Decision "${i}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${i}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${n}`})}}case "paradigm_wisdom_expert":{let{symbol:n,area:i}=e;if(!n&&!i)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let r=await vn(s),o=jo(r,{symbol:n,area:i});return {handled:true,text:JSON.stringify({query:{symbol:n,area:i},count:o.length,experts:o.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:o.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function Wo(){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 Go(t,e,s){switch(t){case "paradigm_history_context":{let{symbols:n}=e,i=await Ns(s),r=Oo(i,n),o={symbols:n,history:r.map(a=>({symbol:a.symbol,summary:a.summary?{total_changes:a.summary.total_changes,last_modified:a.summary.last_modified,stability_score:a.summary.stability_score,fragility:a.summary.fragility,contributors:a.summary.contributors}:null,recent:a.recent.slice(0,3).map(c=>({type:c.type,description:c.description,author:c.author,ts:c.ts})),co_changes:a.co_changes.slice(0,5)})),summary:{total_symbols:n.length,with_history:r.filter(a=>a.summary).length,fragile_count:r.filter(a=>a.summary?.fragility==="high"||a.summary?.fragility==="critical").length}};return {handled:true,text:JSON.stringify(o,null,2)}}case "paradigm_history_record":{let{type:n,symbols:i,intent:r,description:o,commit:a,files:c,reason:l}=e,d=await $s(s.rootDir,{type:n,symbols:i,author:{type:"agent",id:"claude"},intent:r,description:o,commit:a,files:c,reason:l});return {handled:true,text:JSON.stringify({success:true,id:d,type:n,symbols:i,message:"History entry recorded successfully",note:"Run paradigm history reindex to update the index after multiple entries"})}}case "paradigm_history_validate":{let{implementation_id:n,result:i,tests:r}=e,o=await $o(s.rootDir,n||"unknown",i,r);return {handled:true,text:JSON.stringify({success:true,id:o,result:i,tests:r,message:"Validation recorded successfully"})}}case "paradigm_history_fragility":{let{symbols:n}=e,i=await Ns(s),r=Io(i,n);return {handled:true,text:JSON.stringify({symbols:n,safe_to_modify:r.safe_to_modify,fragile:r.fragile.map(o=>({symbol:o.symbol,fragility:o.fragility,reason:o.reason})),warnings:r.warnings,recommendations:r.recommendations,summary:r.fragile.length===0?"All symbols are stable - safe to proceed":r.safe_to_modify?"Some fragile symbols detected - proceed with extra testing":"Critical fragility detected - consider deferring changes or adding extensive tests"})}}default:return {handled:false,text:""}}}b$1();var dd=".paradigm/navigator.yaml";async function Bo(t){let e=H.join(t,dd);if(!E.existsSync(e))return {config:null,configPath:null};try{let s=E.readFileSync(e,"utf8");return {config:Te.load(s),configPath:e}}catch(s){return a.component("#navigator-loader").error("Error parsing navigator.yaml",{error:s}),{config:null,configPath:e}}}function zo(t,e,s){switch(e.intent){case "find":return pd(t,e.target||"");case "explore":return ud(t,e.target||"");case "context":return gd(t,e.task||"");default:return {paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function pd(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let i=t.symbols[e];if(i)n.paths.push(i),n.symbols.push(e),n.explanation=`Found symbol ${e} at ${i}`;else {let r=Object.entries(t.symbols).filter(([o])=>o.includes(e.slice(1))).slice(0,5);r.length>0?(n.paths=r.map(([,o])=>o),n.symbols=r.map(([o])=>o),n.explanation=`Found ${r.length} symbols matching "${e}"`):n.explanation=`Symbol ${e} not found in navigator`;}}else {let i=Object.entries(t.symbols).filter(([r])=>r.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(i.length>0)n.paths=i.map(([,r])=>r),n.symbols=i.map(([r])=>r),n.explanation=`Found ${i.length} symbols matching "${e}"`;else {let r=md(t,e);r?(n.paths=r.paths,n.explanation=`Found ${e} in structure: ${r.paths.join(", ")}`):n.explanation=`No matches found for "${e}"`;}}return n.suggested_order=Es(n.paths,t),n}function ud(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]},i=e.toLowerCase();for(let[r,o]of Object.entries(t.structure))if(o&&(r.toLowerCase().includes(i)||i.includes(r.toLowerCase()))){n.paths.push(...o.paths);let a=Object.entries(t.symbols).filter(([c])=>c.startsWith(o.symbol)).slice(0,10);n.symbols.push(...a.map(([c])=>c));}for(let[r,o]of Object.entries(t.key_files))r.toLowerCase().includes(i)&&n.paths.push(...o);if(n.paths.length===0){let r=Object.entries(t.symbols).filter(([o,a])=>o.toLowerCase().includes(i)||a.toLowerCase().includes(i)).slice(0,10);n.paths=[...new Set(r.map(([,o])=>o))],n.symbols=r.map(([o])=>o);}return n.explanation=`Exploration paths for "${e}": ${n.paths.length} locations, ${n.symbols.length} symbols`,n.suggested_order=Es(n.paths,t),n}function gd(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]},i=e.toLowerCase(),r=fd(i);for(let[o,a]of Object.entries(t.structure))a&&r.some(c=>o.toLowerCase().includes(c))&&n.paths.push(...a.paths);for(let[o,a]of Object.entries(t.symbols)){let c=o.slice(1).toLowerCase();r.some(l=>c.includes(l)||l.includes(c))&&(n.paths.push(a),n.symbols.push(o));}return n.paths.push(...t.key_files.config),n.paths=[...new Set(n.paths)],n.symbols=[...new Set(n.symbols)],i.includes("test")?n.skip=t.skip_patterns.always:n.skip=[...t.skip_patterns.always,...t.skip_patterns.unless_testing],!i.includes("doc")&&!i.includes("readme")&&n.skip.push(...t.skip_patterns.unless_docs),n.explanation=`Context for "${e}": ${n.paths.length} relevant files, ${n.symbols.length} symbols`,n.suggested_order=Es(n.paths,t),n}function md(t,e){let s=e.toLowerCase();for(let[n,i]of Object.entries(t.structure))if(i&&(n.toLowerCase().includes(s)||s.includes(n.toLowerCase())))return i;return null}function fd(t){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return t.split(/\s+/).map(s=>s.replace(/[^a-z0-9]/g,"")).filter(s=>s.length>2&&!e.has(s))}function Es(t,e){let s={};for(let n of t){let i=0;e.key_files.config.some(r=>n.includes(r))&&(i+=100),e.key_files.entry.some(r=>n.includes(r))&&(i+=80),e.key_files.types.some(r=>n.includes(r))&&(i+=60),i-=n.split("/").length*2,s[n]=i;}return [...t].sort((n,i)=>(s[i]||0)-(s[n]||0))}var yd={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function Ko(){return [yd]}async function _n(t,e,s){if(t!=="paradigm_navigate")return {handled:false,text:""};let n={intent:e.intent||"find",target:e.target,task:e.task},i=await Bo(s.rootDir);if(i.config||(i={config:hd(s),configPath:null}),false);if(n.intent==="context"&&!n.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((n.intent==="find"||n.intent==="explore")&&!n.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${n.intent} intent`,example:n.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let r=`navigate:${n.intent}:${n.target||""}:${n.task||""}`,o=await v$1.getOrCompute(r,()=>{let c=zo(i.config,n,s.rootDir),l={intent:n.intent,...n.target&&{target:n.target},...n.task&&{task:n.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(i.config?.auto_generated&&(l.auto_generated=true,l.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(l.note="No paths found.",l.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(l.tip=l.tip||"Many paths returned. Start with suggested_order for efficient exploration."),s.workspace){if(n.intent==="find"&&n.target&&c.paths.length===0){let d=jt(s.workspace,n.target);d.length>0&&(l.workspaceResults=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(n.intent==="context"&&n.task){let d=jt(s.workspace,n.task);d.length>0&&(l.workspaceContext=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})));}}return JSON.stringify(l,null,2)}),a=o;if(e.response_format==="concise")try{let c=JSON.parse(o);delete c.skip,delete c.tip,delete c.note,delete c.recovery,delete c.workspaceResults,delete c.workspaceContext,delete c.auto_generated,a=JSON.stringify(c,null,2);}catch{}try{let c=H.join(s.rootDir,".paradigm",".nav-called");E.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a}}function hd(t){let e={},s={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},n=n$1(t.index),i=new Set;for(let a of n)if(a.filePath){e[a.symbol]=a.filePath,i.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":s.features.paths.includes(c)||s.features.paths.push(c);break;case "component":s.components.paths.includes(c)||s.components.paths.push(c);break;case "gate":s.gates.paths.includes(c)||s.gates.paths.push(c);break;case "flow":s.flows.paths.includes(c)||s.flows.paths.push(c);break}}let r=[],o=[];for(let a of t.aggregation.purposeFiles)r.push(a.filePath);return r.push(".paradigm/config.yaml"),t.gateConfig&&r.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:s,key_files:{config:r.slice(0,10),entry:o,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}var xn=null,Hs=false;function bd(t){if(xn||(xn=new f$5),!Hs)try{let e=r$1();for(let s of e)try{xn.addPattern(s);}catch{}Hs=!0;}catch{Hs=true;}return xn}function Qo(){return [{name:"paradigm_sentinel_triage",description:"View and filter incidents with pattern matches. Returns recent errors with symbolic context and resolution suggestions. ~200-400 tokens depending on incident count.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter by symbol (e.g., @checkout, ^auth)"},status:{type:"string",enum:["open","investigating","resolved","wont-fix","all"],description:"Filter by status (default: all)"},environment:{type:"string",description:"Filter by environment"},search:{type:"string",description:"Search in error messages"},limit:{type:"number",description:"Max results (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_show",description:"Get full details of a specific incident including timeline and matched patterns. ~200 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Incident ID (e.g., INC-001)"},includeTimeline:{type:"boolean",description:"Include flow timeline"},includeSimilar:{type:"boolean",description:"Include similar incidents"}},required:["incidentId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_resolve",description:"Mark an incident as resolved with optional pattern and commit reference. ~100 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Incident ID"},patternId:{type:"string",description:"Pattern that led to resolution"},commitHash:{type:"string",description:"Fix commit hash"},prUrl:{type:"string",description:"PR URL"},notes:{type:"string",description:"Resolution notes"},wontFix:{type:"boolean",description:"Mark as wont-fix instead of resolved"}},required:["incidentId"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_patterns",description:"List and filter failure patterns with confidence scores. Returns pattern names, match counts, and confidence scores. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter patterns for this symbol"},minConfidence:{type:"number",description:"Minimum confidence score"},source:{type:"string",enum:["manual","suggested","imported","community"],description:"Filter by source"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_add_pattern",description:"Create a new failure pattern. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Pattern ID (kebab-case)"},name:{type:"string",description:"Human-readable name"},description:{type:"string",description:"What this pattern matches"},pattern:{type:"object",properties:{symbols:{type:"object",description:"Symbol criteria"},errorContains:{type:"array",items:{type:"string"},description:"Error keywords"},missingSignals:{type:"array",items:{type:"string"},description:"Expected missing signals"}}},resolution:{type:"object",properties:{description:{type:"string",description:"Resolution steps"},strategy:{type:"string",enum:["retry","fallback","fix-data","fix-code","ignore","escalate"]},priority:{type:"string",enum:["low","medium","high","critical"]},codeHint:{type:"string",description:"Code fix hint"}},required:["description","strategy"]},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"}},required:["id","name","pattern","resolution"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_record",description:"Manually record a new incident. ~100 tokens.",inputSchema:{type:"object",properties:{error:{type:"object",properties:{message:{type:"string",description:"Error message"},stack:{type:"string",description:"Stack trace"},code:{type:"string",description:"Error code"},type:{type:"string",description:"Error type"}},required:["message"]},symbols:{type:"object",properties:{feature:{type:"string"},component:{type:"string"},flow:{type:"string"},gate:{type:"string"},signal:{type:"string"},state:{type:"string"},integration:{type:"string"}}},environment:{type:"string",description:"Environment (required)"},service:{type:"string",description:"Service name"},version:{type:"string",description:"App version"},flowPosition:{type:"object",properties:{flowId:{type:"string"},expected:{type:"array",items:{type:"string"}},actual:{type:"array",items:{type:"string"}},missing:{type:"array",items:{type:"string"}},failedAt:{type:"string"}}}},required:["error","symbols","environment"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_stats",description:"Get statistics and health metrics. Returns open/resolved counts, MTTR, and symbol breakdown. ~150 tokens.",inputSchema:{type:"object",properties:{period:{type:"string",description:"Period: 1d, 7d, 30d, 90d (default: 7d)"},symbol:{type:"string",description:"Get health for specific symbol"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_suggest_pattern",description:"Get AI suggestions for patterns based on incidents. ~200 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Suggest from specific incident"},minOccurrences:{type:"number",description:"Min similar incidents for suggestion"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_logs",description:"Query structured logs from connected apps. Filters by level, symbol, service, search text, time range. ~200-400 tokens.",inputSchema:{type:"object",properties:{level:{type:"string",enum:["debug","info","warn","error"],description:"Filter by log level"},symbol:{type:"string",description:"Filter by symbol (partial match)"},service:{type:"string",description:"Filter by service name"},search:{type:"string",description:"Search in log messages"},since:{type:"string",description:"ISO timestamp \u2014 logs after this time"},sessionId:{type:"string",description:"Filter by session ID"},correlationId:{type:"string",description:"Filter by correlation ID"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_services",description:"List all registered services with version, environment, and last-seen time. ~100 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_app_state",description:"Get live app state snapshots. Shows current state, active flows, and held gates for connected services. ~200 tokens.",inputSchema:{type:"object",properties:{service:{type:"string",description:"Filter by service name"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_validate_symbol",description:"Check if a symbol exists in the project index. Returns known/unknown status with suggestions for typos. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to validate (e.g., #checkout, ^auth)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_flow_activity",description:"Get recent flow events \u2014 which flow nodes were hit, in what order, by which service. ~200 tokens.",inputSchema:{type:"object",properties:{flowId:{type:"string",description:"Filter by flow ID (e.g., $checkout-flow)"},service:{type:"string",description:"Filter by service name"},since:{type:"string",description:"ISO timestamp \u2014 events after this time"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_metrics",description:"Query metrics (counters, gauges, histograms) from connected apps. Supports filtering and aggregation. ~200 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Metric name filter"},type:{type:"string",enum:["counter","gauge","histogram"],description:"Metric type filter"},service:{type:"string",description:"Service name filter"},since:{type:"string",description:"ISO timestamp \u2014 metrics after this time"},aggregate:{type:"boolean",description:"If true and name is provided, return aggregation (count/sum/min/max/avg) instead of raw data"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_traces",description:"Query distributed traces across services. Shows span trees with timing, status, and service hops. ~200 tokens.",inputSchema:{type:"object",properties:{traceId:{type:"string",description:"Get a specific trace by ID"},service:{type:"string",description:"Filter by service name"},symbol:{type:"string",description:"Filter by symbol"},since:{type:"string",description:"ISO timestamp \u2014 traces after this time"},limit:{type:"number",description:"Max traces (default: 10, max: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_schemas",description:"List or get registered event schemas. Schemas define event types, scopes, causality, and visualization for application-agnostic observability. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Get a specific schema by ID. Omit to list all."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_events",description:"Query generic events from any registered schema. Filters by schema, event type, category, scope, service, severity, time range. ~200-400 tokens.",inputSchema:{type:"object",properties:{schemaId:{type:"string",description:'Filter by schema ID (e.g., "pretend-engine")'},eventType:{type:"string",description:'Filter by event type (e.g., "rule:fire")'},category:{type:"string",description:'Filter by category (e.g., "rules")'},service:{type:"string",description:"Filter by service name"},scopeValue:{type:"string",description:"Filter by scope value (e.g., frame number)"},severity:{type:"string",enum:["debug","info","warn","error"],description:"Filter by severity"},since:{type:"string",description:"ISO timestamp \u2014 events after this time"},search:{type:"string",description:"Full-text search in event data"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_scopes",description:"Get scope summaries for a schema \u2014 e.g., frame list with event counts, request list with category breakdown. ~200 tokens.",inputSchema:{type:"object",properties:{schemaId:{type:"string",description:"Schema ID (required)"},sessionId:{type:"string",description:"Filter by session ID"},limit:{type:"number",description:"Max scopes (default: 50)"}},required:["schemaId"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Xo(t,e,s){let n=bd(),i=new o$2(n);switch(t){case "paradigm_sentinel_triage":{let{symbol:r,status:o="all",environment:a,search:c,limit:l=10}=e,d=n.getRecentIncidents({limit:l,status:o,symbol:r,environment:a,search:c});if(d.length===0)return {handled:true,text:JSON.stringify({count:0,incidents:[],tip:"No incidents recorded yet. Incidents are created when errors occur in production or via paradigm_sentinel_record.",howToRecord:{description:"Record incidents manually with paradigm_sentinel_record",example:{error:{message:"Connection timeout",code:"ETIMEDOUT"},symbols:{feature:"@checkout",integration:"&stripe"},environment:"production"}}},null,2)};let p=d.map(u=>{let g=i.match(u,{maxResults:3});return {id:u.id,timestamp:u.timestamp,status:u.status,error:u.error.message,symbols:u.symbols,environment:u.environment,matches:g.map(m=>({patternId:m.pattern.id,name:m.pattern.name,confidence:m.confidence,strategy:m.pattern.resolution.strategy,description:m.pattern.resolution.description}))}});return {handled:true,text:JSON.stringify({count:p.length,incidents:p},null,2)}}case "paradigm_sentinel_show":{let{incidentId:r,includeTimeline:o,includeSimilar:a}=e,c=n.getIncident(r);if(!c)return {handled:true,text:JSON.stringify({error:`Incident ${r} not found`})};let l=i.match(c,{maxResults:5}),d={incident:c,matches:l.map(p=>({patternId:p.pattern.id,name:p.pattern.name,confidence:p.confidence,matchedCriteria:p.matchedCriteria,resolution:p.pattern.resolution}))};if(o&&c.flowPosition){let p=new x().build(c);p&&(d.timeline=new x().renderStructured(p));}if(a){let p=n.getRecentIncidents({symbol:Object.values(c.symbols)[0],limit:5}).filter(u=>u.id!==r);d.similar=p.map(u=>({id:u.id,error:u.error.message,status:u.status}));}return {handled:true,text:JSON.stringify(d,null,2)}}case "paradigm_sentinel_resolve":{let{incidentId:r,patternId:o,commitHash:a,prUrl:c,notes:l,wontFix:d}=e;return n.getIncident(r)?d?(n.updateIncident(r,{status:"wont-fix",resolvedAt:new Date().toISOString(),resolvedBy:"manual",resolution:{notes:l}}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${r} marked as won't fix`})}):(n.recordResolution({incidentId:r,patternId:o,commitHash:a,prUrl:c,notes:l}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${r} resolved`,patternId:o,commitHash:a,prUrl:c})}):{handled:true,text:JSON.stringify({error:`Incident ${r} not found`})}}case "paradigm_sentinel_patterns":{let{symbol:r,minConfidence:o,source:a}=e,c=n.getAllPatterns({source:a,minConfidence:o,includePrivate:false}),l=c;return r&&(l=c.filter(d=>{let p=d.pattern.symbols;return Object.values(p).some(u=>u?Array.isArray(u)?u.includes(r)||u.some(g=>r.match(g.replace("*",".*"))):u===r||r.match(u.replace("*",".*")):false)})),{handled:true,text:JSON.stringify({count:l.length,patterns:l.map(d=>({id:d.id,name:d.name,description:d.description,confidence:d.confidence.score,resolution:d.resolution,tags:d.tags}))},null,2)}}case "paradigm_sentinel_add_pattern":{let{id:r,name:o,description:a,pattern:c,resolution:l,tags:d}=e,p={id:r,name:o,description:a||"",pattern:{symbols:c.symbols||{},errorContains:c.errorContains,missingSignals:c.missingSignals},resolution:{description:l.description,strategy:l.strategy,priority:l.priority||"medium",codeHint:l.codeHint},source:"manual",private:false,tags:d||[]};return n.addPattern(p),{handled:true,text:JSON.stringify({success:true,message:`Pattern ${r} created`,pattern:p})}}case "paradigm_sentinel_record":{let{error:r,symbols:o,environment:a,service:c,version:l,flowPosition:d}=e,p=n.recordIncident({error:r,symbols:o,environment:a,service:c,version:l,flowPosition:d}),u=n.getIncident(p),g=u?i.match(u,{maxResults:3}):[];return {handled:true,text:JSON.stringify({success:true,incidentId:p,matches:g.map(m=>({patternId:m.pattern.id,confidence:m.confidence,resolution:m.pattern.resolution.description}))},null,2)}}case "paradigm_sentinel_stats":{let{period:r="7d",symbol:o}=e,a=new y(n);if(o){let p=a.getSymbolHealth(o);return {handled:true,text:JSON.stringify({symbol:o,health:p},null,2)}}let c=r.match(/^(\d+)d$/),l=c?parseInt(c[1],10):7,d=a.getStats(l);return {handled:true,text:JSON.stringify({period:`${l}d`,stats:d},null,2)}}case "paradigm_sentinel_suggest_pattern":{let{incidentId:r,minOccurrences:o}=e,a=new A(n);if(r){let l=n.getIncident(r);if(!l)return {handled:true,text:JSON.stringify({error:`Incident ${r} not found`})};let d=a.suggestFromIncident(l);return {handled:true,text:JSON.stringify({source:"incident",incidentId:r,suggestion:d},null,2)}}let c=a.findPatternCandidates(o||3);return {handled:true,text:JSON.stringify({source:"analysis",candidates:c.slice(0,5).map(l=>({occurrences:l.occurrenceCount,sampleIncidents:l.incidents.slice(0,3).map(d=>d.id),suggestion:l.suggestedPattern}))},null,2)}}case "paradigm_sentinel_logs":{let{level:r,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:p,limit:u=50}=e,g=n.queryLogs({level:r,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:p,limit:u}),m=n.getLogCount({level:r,symbol:o,service:a,since:l});return {handled:true,text:JSON.stringify({count:g.length,total:m,logs:g.map(y=>({timestamp:y.timestamp,level:y.level,symbol:y.symbol,service:y.service,message:y.message,data:y.data,sessionId:y.sessionId,correlationId:y.correlationId,durationMs:y.durationMs}))},null,2)}}case "paradigm_sentinel_services":{let r=n.getServices();return {handled:true,text:JSON.stringify({count:r.length,services:r.map(o=>({name:o.name,version:o.version,environment:o.environment,lastSeen:o.lastSeenAt,startedAt:o.startedAt,pid:o.pid}))},null,2)}}case "paradigm_sentinel_app_state":{let{service:r}=e,o=r?n.getAppState(r):n.getAllAppStates();return {handled:true,text:JSON.stringify({states:o.map(a=>({service:a.service,sessionId:a.sessionId,state:a.state,activeFlows:a.activeFlows,activeGates:a.activeGates,timestamp:a.timestamp}))},null,2)}}case "paradigm_sentinel_validate_symbol":{let{symbol:r}=e,o=n.getLogCount({symbol:r});return {handled:true,text:JSON.stringify({symbol:r,usedInLogs:o>0,logCount:o,tip:o===0?"This symbol has not appeared in any logs. It may be a typo or unused.":`This symbol has been used in ${o} log entries.`},null,2)}}case "paradigm_sentinel_flow_activity":{let{flowId:r,service:o,since:a}=e,l=n.queryLogs({symbol:r,service:o,since:a,limit:100}).filter(d=>["flow","signal","gate"].includes(d.symbolType)).map(d=>({timestamp:d.timestamp,symbol:d.symbol,symbolType:d.symbolType,service:d.service,message:d.message,level:d.level}));return {handled:true,text:JSON.stringify({count:l.length,events:l},null,2)}}case "paradigm_sentinel_metrics":{let{name:r,type:o,service:a,since:c,aggregate:l,limit:d}=e;if(l&&r){let u=n.aggregateMetric(r,{service:a,since:c});return {handled:true,text:JSON.stringify(u,null,2)}}let p=n.queryMetrics({name:r,type:o,service:a,since:c,limit:Math.min(d||50,100)});return {handled:true,text:JSON.stringify({count:p.length,metrics:p.map(u=>({timestamp:u.timestamp,name:u.name,type:u.type,value:u.value,tags:u.tags,service:u.service}))},null,2)}}case "paradigm_sentinel_traces":{let{traceId:r,service:o,symbol:a,since:c,limit:l}=e;if(r){let p=n.getTrace(r);return p?{handled:true,text:JSON.stringify(p,null,2)}:{handled:true,text:JSON.stringify({error:"Trace not found"})}}let d=n.queryTraces({service:o,symbol:a,since:c,limit:Math.min(l||10,20)});return {handled:true,text:JSON.stringify({count:d.length,traces:d.map(p=>({traceId:p.traceId,services:p.services,spanCount:p.spans.length,totalDurationMs:p.totalDurationMs,startTime:p.startTime,endTime:p.endTime}))},null,2)}}case "paradigm_sentinel_schemas":{let{id:r}=e;if(r){let a=n.getSchema(r);return a?{handled:true,text:JSON.stringify(a,null,2)}:{handled:true,text:JSON.stringify({error:`Schema "${r}" not found`})}}let o=n.listSchemas();return o.length===0?{handled:true,text:JSON.stringify({count:0,schemas:[],tip:"No event schemas registered yet. Applications register schemas via POST /api/schemas or SentinelWebClient.registerSchema()."},null,2)}:{handled:true,text:JSON.stringify({count:o.length,schemas:o.map(a=>({id:a.id,version:a.version,name:a.name,description:a.description,eventTypeCount:a.eventTypes.length,scope:a.scope.label,tags:a.tags,registeredAt:a.registeredAt}))},null,2)}}case "paradigm_sentinel_events":{let{schemaId:r,eventType:o,category:a,service:c,scopeValue:l,severity:d,since:p,search:u,limit:g}=e,m=n.queryEvents({schemaId:r,eventType:o,category:a,service:c,scopeValue:l,severity:d,since:p,search:u,limit:Math.min(g||50,100)});return m.length===0?{handled:true,text:JSON.stringify({count:0,events:[],tip:"No events found. Events are ingested via POST /api/events or SentinelWebClient.emit()."},null,2)}:{handled:true,text:JSON.stringify({count:m.length,events:m.map(y=>({id:y.id,schemaId:y.schemaId,eventType:y.eventType,category:y.category,timestamp:y.timestamp,scopeValue:y.scopeValue,service:y.service,severity:y.severity,data:y.data,parentEventId:y.parentEventId,depth:y.depth}))},null,2)}}case "paradigm_sentinel_scopes":{let{schemaId:r,sessionId:o,limit:a}=e,c=n.getEventScopes(r,{limit:Math.min(a||50,200),sessionId:o});return c.length===0?{handled:true,text:JSON.stringify({count:0,scopes:[],tip:`No scopes found for schema "${r}". Events with scope values are required.`},null,2)}:{handled:true,text:JSON.stringify({count:c.length,scopes:c},null,2)}}default:return {handled:false,text:""}}}b$1();var wd=30*1e3,Zo=new Map;async function Pn(t){let e=H.resolve(t),s=Zo.get(e);if(s&&Date.now()-s.loadedAt<wd)return s.index;let n=await vd(e);return n&&Zo.set(e,{index:n,loadedAt:Date.now()}),n}async function vd(t){let e=H.join(t,".paradigm","flow-index.json");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch(s){return a.component("#flow-loader").error("Error parsing flow-index.json",{error:s}),null}}function kd(t,e){let s=t.symbolToFlows[e]||[],n=[];for(let i of s){let r=t.flows[i];if(!r)continue;let o=r.steps.map((a,c)=>({step:a,index:c})).filter(({step:a})=>a.symbol===e);for(let{step:a,index:c}of o){let l=r.steps.slice(c+1).map(d=>d.id);n.push({flowId:r.id,definedIn:r.definedIn,description:r.description,trigger:r.trigger,stepAffected:{id:a.id,action:a.action,position:c+1},downstreamSteps:l,validation:r.validation});}}return n}function jn(t,e){let s=kd(t,e),n=new Set;for(let o of s)o.validation?.command&&n.add(o.validation.command);let i="low",r=s.reduce((o,a)=>o+a.downstreamSteps.length,0);return s.length>3||r>10?i="high":(s.length>1||r>3)&&(i="medium"),{symbol:e,totalFlows:s.length,impactLevel:i,affectedFlows:s,validationCommands:Array.from(n),suggestion:s.length>0?`Changes to ${e} may affect ${s.length} flow(s). ${n.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function ea(){return [{name:"paradigm_flows_affected",description:"Find flows affected by changes to a symbol. Returns flows that include the symbol in their steps, with downstream impact analysis and validation commands. Returns flow IDs, step positions, and validation commands. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol being modified (e.g., @tasks, ^project-member, !task-created)"},includeValidation:{type:"boolean",description:"Include validation commands in response (default: true)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_flow_check",description:"Check flow definition completeness \u2014 verifies that gates referenced in flows.yaml exist in portal.yaml and that required fields are present. Does not trace code execution paths.",inputSchema:{type:"object",properties:{flowId:{type:"string",description:"Specific flow ID to validate (e.g., $task-creation). If not provided, validates all flows."},checkImplementation:{type:"boolean",description:"Deep check: verify actions and signals exist in codebase (default: false)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ta(t,e,s){switch(t){case "paradigm_flows_affected":{let{symbol:n,includeValidation:i=true}=e,r=await Pn(s.rootDir);if(!r)return {handled:true,text:JSON.stringify({error:"Flow index not found",symbol:n,suggestion:"Run `paradigm scan` to generate the flow index. Ensure .purpose files contain flows definitions.",example:`
5
- flows:
6
- $task-creation:
7
- description: "Full task creation flow"
8
- trigger: "POST /api/projects/:id/tasks"
9
- steps:
10
- - id: validate
11
- action: "Check project membership"
12
- symbol: "^project-member"
13
- expect: "403 if not member"
14
- - id: create
15
- action: "Create task record"
16
- symbol: "@tasks"
17
- `},null,2)};let o=jn(r,n),a={symbol:o.symbol,totalFlows:o.totalFlows,impactLevel:o.impactLevel,affectedFlows:o.affectedFlows.map(l=>{let d={flowId:l.flowId,definedIn:l.definedIn,description:l.description,stepAffected:l.stepAffected,downstreamSteps:l.downstreamSteps};return l.trigger&&(d.trigger=l.trigger),i&&l.validation&&(d.validation=l.validation),d}),suggestion:o.suggestion};return i&&o.validationCommands.length>0&&(a.validationCommands=o.validationCommands),{handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_flow_check":case "paradigm_flow_validate":{let{flowId:n,checkImplementation:i=false}=e,r=H.join(s.rootDir,".paradigm","flows.yaml"),o=null;if(E.existsSync(r))try{let f=E.readFileSync(r,"utf-8");o=Te.load(f);}catch(f){return {handled:true,text:JSON.stringify({error:"Failed to parse flows.yaml",details:String(f)},null,2)}}if(!o||!o.flows||Object.keys(o.flows).length===0)return {handled:true,text:JSON.stringify({error:"No flows found",suggestion:"Create .paradigm/flows.yaml with flow definitions",example:`
18
- version: "1.0"
19
- flows:
20
- $task-creation:
21
- name: Task Creation Flow
22
- description: Complete flow for creating a new task
23
- trigger: "POST /api/tasks"
24
- steps:
25
- - type: gate
26
- symbol: ^authenticated
27
- description: User must be logged in
28
- - type: action
29
- symbol: @create-task
30
- description: Create task in database
31
- - type: signal
32
- symbol: "!task-created"
33
- description: Emit success event
34
- successSignal: "!task-created"
35
- `},null,2)};let a=H.join(s.rootDir,"portal.yaml"),c=[];if(E.existsSync(a))try{let f=E.readFileSync(a,"utf-8"),b=Te.load(f);b?.gates&&(c=Object.keys(b.gates).map(h=>h.startsWith("^")?h.slice(1):h));}catch{}let l=new Set(c),d=[],p=n?[[n,o.flows[n]]]:Object.entries(o.flows);for(let[f,b]of p){if(!b){if(n)return {handled:true,text:JSON.stringify({error:`Flow not found: ${n}`,availableFlows:Object.keys(o.flows)},null,2)};continue}let h={flowId:f,status:"valid",coverage:{gatesReferenced:[],gatesMissing:[],actionsReferenced:[],actionsMissing:[],signalsEmitted:[],signalsMissing:[]},suggestions:[]},w=b.steps||[];for(let S=0;S<w.length;S++){let v=w[S],k=v.symbol||"",x=Sd(k);if(x)switch(v.type){case "gate":h.coverage.gatesReferenced.push(k),l.has(x.name)||(h.coverage.gatesMissing.push(k),h.status="invalid");break;case "action":h.coverage.actionsReferenced.push(k);break;case "signal":h.coverage.signalsEmitted.push(k);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 Sd(t){let e=t.match(/^([#$^!~])(.+)$/);return e?{prefix:e[1],name:e[2]}:null}b$1();var _d=60*1e3,na=new Map;async function ia(t){let e=H.resolve(t),s=na.get(e);if(s&&Date.now()-s.loadedAt<_d)return s.fixtures;let n=await xd(e);return n&&na.set(e,{fixtures:n,loadedAt:Date.now()}),n}async function xd(t){let e=H.join(t,".paradigm","fixtures.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch(s){return a.component("#fixtures-loader").error("Error parsing fixtures.yaml",{error:s}),null}}function Ms(t,e){switch(e){case "users":return t.users||{};case "resources":return t.resources||{};case "payloads":return t.payloads||{};case "all":return {users:t.users||{},resources:t.resources||{},payloads:t.payloads||{}};default:return null}}function ra(t,e,s){return Ms(t,e)?.[s]||null}function Ws(t){return {users:Object.keys(t.users||{}),resources:Object.keys(t.resources||{}),payloads:Object.keys(t.payloads||{})}}function oa(){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 aa(t,e,s){switch(t){case "paradigm_test_fixtures":{let{category:n,name:i}=e,r=await ia(s.rootDir);if(!r)return {handled:true,text:JSON.stringify({error:"Fixtures not found",suggestion:"Create .paradigm/fixtures.yaml with test fixtures. Run `paradigm init` to generate a template.",example:`
36
- version: "1.0"
37
-
38
- users:
39
- admin:
40
- id: "user-admin"
41
- email: "admin@test.com"
42
- role: "org-admin"
43
- token: "Bearer admin-token-xxx"
44
- member:
45
- id: "user-alice"
46
- email: "alice@test.com"
47
- role: "member"
48
- token: "Bearer alice-token-xxx"
49
-
50
- resources:
51
- project:
52
- id: "project-1"
53
- name: "Test Project"
54
- members: ["user-alice"]
55
- admins: ["user-admin"]
56
-
57
- payloads:
58
- createTask:
59
- title: "New Task"
60
- description: "Task description"
61
- `},null,2)};if(!n){let c=Ws(r);return {handled:true,text:JSON.stringify({available:c,usage:{getAllUsers:'paradigm_test_fixtures({ category: "users" })',getSpecificUser:'paradigm_test_fixtures({ category: "users", name: "admin" })',getAllPayloads:'paradigm_test_fixtures({ category: "payloads" })',getEverything:'paradigm_test_fixtures({ category: "all" })'}},null,2)}}if(i&&n!=="all"){let c=ra(r,n,i);if(!c){let d=Ws(r);return {handled:true,text:JSON.stringify({error:`Fixture "${i}" not found in category "${n}"`,availableInCategory:d[n]||[]},null,2)}}return {handled:true,text:JSON.stringify(c,null,2)}}let o=Ms(r,n);return {handled:true,text:JSON.stringify(o,null,2)}}default:return {handled:false,text:""}}}z();b$1();var Us=".paradigm/arch.yaml";function rt(t){let e=H.join(t,Us);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch{return null}}function ca(t,e){let s=rt(t);if(!s)return {unassigned:[],missing_purpose:[]};let n=new Set;for(let a of s.tiers)for(let c of a.components)n.add(c);let i$1=new Set;try{let a=i(e.index,"component");for(let c of a)i$1.add(c.symbol);}catch(a$1){a.component("#arch-loader").warn("Could not load symbol index for drift check",{error:String(a$1)});}let r=Array.from(i$1).filter(a=>!n.has(a)),o=Array.from(n).filter(a=>!i$1.has(a));return {unassigned:r,missing_purpose:o}}function la(t){let e=n=>n.replace(/[^a-zA-Z0-9_-]/g,"-"),s=["graph TD"];for(let n of t.tiers){let i=e(n.id);s.push(` ${i}["${n.label}\\n(${n.responsibility})"]`);}for(let n of t.links){let i=e(n.from),r=e(n.to);n.via?s.push(` ${i} -->|"${n.via}"| ${r}`):s.push(` ${i} --> ${r}`);}return s.join(`
62
- `)}function Dn(t,e,s={}){let{maxResults:n=20}=s,i=[],r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=[`rg -n --no-heading "${r}" "${t}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${r}" "${t}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of o)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return i;let c=a.trim().split(`
63
- `);for(let l of c.slice(0,n)){let d=l.match(/^(.+?):(\d+):(.*)$/);if(d){let[,p,u,g]=d,m=H.relative(t,p),y="unknown";m.includes(".purpose")||m.includes("portal.yaml")?y="purpose":g.includes("//")||g.includes("#")||g.includes("*")?y="comment":y="code",i.push({filePath:m,line:parseInt(u,10),content:g.trim().slice(0,200),context:y});}}return i}function pa(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["dependencies","impact","blast radius","what would break","dependents","affects"]}]}async function On(t,e,s){if(t!=="paradigm_ripple")return {handled:false,text:""};let{symbol:n,depth:i$1=3,includeWorkspace:r=false,response_format:o$1}=e,a=h$1(s.index,n);if(!a){let C=Rd(s.rootDir,n);return o(C.length,t),{handled:true,text:C}}let c=Math.min(Math.max(i$1||3,1),5),l$1=k(s.index,n),d=new Set([n]),p=new Map;function u(C,_){if(_>=c)return;let P=[];for(let $ of C){if(d.has($))continue;d.add($);let R=k(s.index,$);for(let T of R)d.has(T.symbol)||P.push(T.symbol);}P.length>0&&(p.set(_+1,P),u(P,_+1));}u(l$1.map(C=>C.symbol),1);let g=new Set;for(let[,C]of p)for(let _ of C)_!==n&&!l$1.find(P=>P.symbol===_)&&g.add(_);let m=l(s.index,n),y=l$1.length+g.size,f="low";y>10?f="high":y>3&&(f="medium");let b=await Pn(s.rootDir),h=null;if(b){let C=jn(b,n);C.totalFlows>0&&(C.impactLevel==="high"&&f==="low"?f="medium":C.impactLevel==="high"&&(f="high"),h={totalFlows:C.totalFlows,affectedFlows:C.affectedFlows.map(_=>({flowId:_.flowId,impactLevel:_.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${_.stepAffected.position}, affects ${_.downstreamSteps.length} downstream steps`})),validationSuggestion:C.validationCommands.length>0?`Run: ${C.validationCommands[0]}`:void 0});}let w=new Set([n,...l$1.map(C=>C.symbol),...g]),S=[];try{let C=i(s.index,"gate");for(let _ of C)w.has(_.symbol)&&S.push({gate:_.symbol,description:_.description});for(let _ of l$1)_.type==="gate"&&!S.find(P=>P.gate===_.symbol)&&S.push({gate:_.symbol,description:_.description});}catch{}let v={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:f,analysis:{directlyAffected:l$1.map(C=>({symbol:C.symbol,type:C.type,description:C.description})),indirectlyAffected:Array.from(g),indirectByLevel:Object.fromEntries(p),dependsOn:m.map(C=>({symbol:C.symbol,type:C.type}))},summary:{directCount:l$1.length,indirectCount:g.size,totalAffected:y,dependsOnCount:m.length,levelsAnalyzed:c},recommendation:Pd(f)};h&&(v.affectedFlows=h),S.length>0&&(v.affectedGates=S),v.suggestedReviewScope=jd(f,l$1.length,g.size,S.length,h?.totalFlows??0);try{let C=await F(s.rootDir,n);C.length>0&&(v.personas_affected=C,C.length>2&&f==="low"&&(v.impact="medium"));}catch{}try{let C=X$1(s.rootDir,n);C.length>0&&(v.university_content_affected=C.map(_=>({id:_.id,title:_.title,type:_.type,stale:_.stale})));}catch{}if(r&&s.workspace){let C=Eo(s.workspace,n);if(C.length>0){v.workspaceImpact={siblings:C.map(P=>({project:P.project,references:P.references.map($=>({symbol:$.symbol,type:$.type,description:$.description}))}))};let _=C.reduce((P,$)=>P+$.references.length,0);_>0&&f==="low"&&(v.impact="medium"),_>5&&(v.impact="high");}}let k$1=o$1==="concise"?{symbol:v.symbol,impact:v.impact,summary:v.summary}:v,x=JSON.stringify(k$1,null,2);return o(x.length,t),{handled:true,text:x}}function Rd(t,e){let s=Dn(t,e,{maxResults:20});if(s.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let n=[...new Set(s.map(o=>o.filePath))],i={};for(let o of s)i[o.context]=(i[o.context]||0)+1;let r="low";return n.length>10||s.length>20?r="high":(n.length>3||s.length>5)&&(r="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:r,analysis:{filesAffected:n.slice(0,10),totalFilesAffected:n.length,totalReferences:s.length,contextBreakdown:i,sampleReferences:s.slice(0,5).map(o=>({file:o.filePath,line:o.line,preview:o.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function Pd(t){switch(t){case "high":return "High impact change - review all affected symbols carefully before modifying";case "medium":return "Moderate impact - check direct dependencies for breaking changes";case "low":return "Low impact - safe to modify with standard review"}}function jd(t,e,s,n,i){let r=[];return e>0&&r.push(`Review ${e} direct dependent(s) for breaking changes`),s>0&&r.push(`Scan ${s} indirect dependent(s) for cascading effects`),n>0&&r.push(`Verify ${n} affected gate(s) still enforce correct auth/access`),i>0&&r.push(`Validate ${i} affected flow(s) end-to-end`),t==="high"?r.push("Consider running full test suite before merging"):t==="medium"&&r.push("Run targeted tests for affected components"),r.length===0&&r.push("No downstream dependents detected - safe to proceed"),r}function ua(){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 In(t,e,s){switch(t){case "paradigm_protocol_search":{let n=e.task,i=e.limit||3,r=await aa$1(s.rootDir,n,i);return r.length===0?{handled:true,text:JSON.stringify({count:0,task:n,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:r.length,task:n,matches:r.map(o=>({id:o.protocol.id,name:o.protocol.name,description:o.protocol.description,score:o.score,status:o.protocol.status,exemplar:o.protocol.exemplar,last_verified:o.protocol.last_verified,steps:o.protocol.steps.map(Ad)}))},null,2)}}case "paradigm_protocol_get":{let n=e.id,i=await _(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${n}`})};let r=da(s.rootDir,i);return {handled:true,text:JSON.stringify({...i,freshness:{status:r.status,issues:r.issues}},null,2)}}case "paradigm_protocol_record":{let n=e.steps||[],i=await ba$1(s.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:n,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:i,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let n=e.id,i=e.refresh,r={};e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),e.trigger!==void 0&&(r.trigger=e.trigger),e.tags!==void 0&&(r.tags=e.tags),e.symbols!==void 0&&(r.symbols=e.symbols),e.exemplar!==void 0&&(r.exemplar=e.exemplar),e.steps!==void 0&&(r.steps=e.steps);let o=await ca$1(s.rootDir,n,r,i===true);return {handled:true,text:JSON.stringify({success:o,id:n,refreshed:i===true,message:o?i?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${n}`})}}case "paradigm_protocol_validate":{let n=e.id;if(n){let a=await _(s.rootDir,n);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${n}`})};let c=da(s.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let r=(await Z$1(s.rootDir)).map(a=>{let c=da(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 Ad(t){let e={action:t.action};return t.target&&(e.target=t.target),t.template_from&&(e.template_from=t.template_from),t.reference&&(e.reference=t.reference),t.command&&(e.command=t.command),t.notes&&(e.notes=t.notes),e}j();var At=null,Bs=false;async function zs(t){if(At)Bs||(await At.ensureReady(),Bs=true);else {let e=H.join(t,".paradigm","sentinel","sentinel.db");At=new f$5(e),await At.ensureReady(),Bs=true;}return At}async function Td(t,e){return (await zs(t)).recordPracticeEvent(e)}async function ma(t,e){return (await zs(t)).getPracticeEvents(e)}async function de(t,e){return (await zs(t)).getComplianceRate(e)}async function Tt(t,e){let s=["discovery","verification","testing","documentation","collaboration","security"],n=[];for(let i of s){let r=await de(t,{...e,habitCategory:i});r.total>0&&n.push({category:i,...r});}return n}async function fa(t,e,s){let n=[];for(let i of e){let r=await Td(t,{habitId:i.habitId,habitCategory:i.habitCategory,result:i.result,engineer:s.engineer,sessionId:s.sessionId,loreEntryId:s.loreEntryId,taskDescription:s.taskDescription,symbolsTouched:s.symbolsTouched,filesModified:s.filesModified,notes:i.notes});n.push(r);}return n}b$1();function ya(t){return {handled:true,text:JSON.stringify({error:t},null,2)}}var $n={code:"lore_type_decision_removed",message:"lore type 'decision' was removed in v6.0. Use paradigm_decision_record instead. The decision will be stored in .paradigm/decisions/ and a companion lore insight entry (type:'insight' with references.decision_id) will be written automatically so the timeline stays complete. For narrative-only references, use paradigm_lore_record({type:'insight', references:{decision_id}}).",successor_tool:"paradigm_decision_record",doc:"docs/private/plans/v6.0-decisions-locked.md",removed_in:"6.0.0"};function ha(){let t=process.env.PARADIGM_AUTHOR;if(t)return Ys(t);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Ys(e)}catch{}try{let e=wa.userInfo().username;if(e)return Ys(e)}catch{}return "unknown"}function Ys(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function va(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, milestone, retro, insight, etc.). Call after completing significant work. Returns the created entry ID and file path. For decisions, use paradigm_decision_record (a companion lore insight is auto-written). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function Dt(t,e,s){switch(t){case "paradigm_lore_search":{let n={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},i=await a$3(s.rootDir,n);return {handled:true,text:JSON.stringify({count:i.length,filter:Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0)),entries:i.map(ba)},null,2)}}case "paradigm_lore_record":{let{type:n,title:i,summary:r,symbols_touched:o,symbols_created:a$1,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:u,duration_minutes:g,decisions:m,errors_encountered:y,learnings:f,verification:b,tags:h,meta:w,body:S,linked_lore:v,linked_tasks:k,linked_commits:x,confidence:C}=e;if(n==="decision")return a.component("#lore").warn("rejected paradigm_lore_record({type:'decision'}) \u2014 removed in v6.0",{removed_in:$n.removed_in,successor_tool:$n.successor_tool}),ya($n);let _;try{let j=new Date(Date.now()-2592e6).toISOString(),A=await de(s.rootDir,{dateFrom:j});if(A.total>0){let I=(await Tt(s.rootDir,{dateFrom:j})).filter(N=>N.rate<60).map(N=>N.category);_={rate:A.rate,followed:A.followed,skipped:A.skipped,partial:A.partial,weakAreas:I.length>0?I:void 0};}}catch{}let P={id:"",type:n||"agent-session",timestamp:new Date().toISOString(),duration_minutes:g,author:ha(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:i,summary:r,symbols_touched:o,symbols_created:a$1,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:u,decisions:m,errors_encountered:y,learnings:f,verification:b,tags:h,meta:w||void 0,habit_compliance:_,body:S,linked_lore:v,linked_tasks:k,linked_commits:x,confidence:C!=null&&C>=0&&C<=1?C:void 0},$=await d$2(s.rootDir,P);j$1().setLastLoreEntryId($);try{let j=process.env.PARADIGM_AGENT_ID;if(j&&o&&o.length>0){let{updateExpertiseFromLore:A}=await import('./agent-loader-W3RQJVW7.js');A(s.rootDir,j,{symbols_touched:o,confidence:C!=null&&C>=0&&C<=1?C:void 0});}}catch{}let R=null;try{c&&c.length>=2&&(R=ea$1(s.rootDir,c,l||[]));}catch{}let T;if(e.stream){let j=e.stream,A=j==="auto"?Od(e):j;try{if(A==="work-log"){let{recordWorkLog:O}=await import('./work-log-loader-DL5GZ2BQ.js');O(s.rootDir,{agent:P.agent?.model||"unknown",summary:P.summary,outcome:P.verification?.status==="pass"?"pass":P.verification?.status==="fail"?"fail":"partial",files_modified:P.files_modified,symbols_touched:P.symbols_touched,commit:P.commit,linked_lore:P.id||$}),T="work-log";}else if(A==="journal"&&P.learnings?.length){let{recordJournalEntry:O}=await import('./journal-loader-GLH7XFTK.js');for(let I of P.learnings)O(P.agent?.model||"unknown",{trigger:"self_reflection",insight:I,project:s.projectName||"unknown",transferable:!1,linked_work_log:P.id||$});T="journal";}else if(A==="decision"&&P.decisions?.length){let{recordDecision:O}=await import('./decision-loader-HELL2AMX.js');for(let I of P.decisions)O(s.rootDir,{title:I.decision.slice(0,100),decision:I.decision,rationale:I.rationale,participants:[{id:`agent/${P.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:P.symbols_touched,status:"active",linked_lore:P.id||$});T="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:$,type:n,title:i,message:"Lore entry recorded successfully",...T?{stream:T}:{},...R?{protocol_suggestion:R}:{}})}}case "paradigm_lore_timeline":{let n=e.limit||10,i=await c$1(s.rootDir),r=await a$3(s.rootDir,{limit:n}),o={};for(let l of r)for(let d of l.symbols_touched)o[d]=(o[d]||0)+1;let a=Object.entries(o).sort(([,l],[,d])=>d-l).slice(0,10).map(([l,d])=>({symbol:l,count:d})),c={};for(let l of r){let d=l.author;c[d]||(c[d]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c[d].count++,l.agent&&(c[d].hasAgent=true),l.timestamp>c[d].lastActive&&(c[d].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:i||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:r.map(ba),hotSymbols:a,authors:Object.entries(c).map(([l,d])=>({id:l,hasAgent:d.hasAgent,entries:d.count,lastActive:d.lastActive}))},null,2)}}case "paradigm_lore_get":{let n=e.id,i=await b$4(s.rootDir,n);return i?{handled:true,text:JSON.stringify(i,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${n}`})}}case "paradigm_lore_update":{let n=e.id,{id:i,...r}=e,o={};for(let[c,l]of Object.entries(r))l!==void 0&&(o[c]=l);let a=await g$3(s.rootDir,n,o);return {handled:true,text:JSON.stringify({success:a,id:n,message:a?"Lore entry updated":`Lore entry not found: ${n}`})}}case "paradigm_lore_assess":{let n=e.id,i=e.verdict,r=e.notes,o=await b$4(s.rootDir,n);if(!o)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${n}`})};let a={verdict:i,assessed_by:ha(),assessed_at:new Date().toISOString(),notes:r},c=await h$3(s.rootDir,n,a);try{let u=process.env.PARADIGM_AGENT_ID;if(u&&c&&o.symbols_touched?.length){let{updateExpertiseFromAssessment:g}=await import('./agent-loader-W3RQJVW7.js');g(s.rootDir,u,{symbols_touched:o.symbols_touched,verdict:i});}}catch{}let l=i==="correct"?1:i==="partial"?.5:0,d=o.confidence!=null?l-o.confidence:null,p=d!=null?d>.1?"Under-confident (actual outcome better than predicted)":d<-0.1?"Over-confident (actual outcome worse than predicted)":"Well-calibrated":"No confidence recorded \u2014 delta not computed";return {handled:true,text:JSON.stringify({success:c,id:n,verdict:i,confidence:o.confidence??null,delta:d,deltaDescription:p,message:c?`Assessment recorded: ${i}${d!=null?` (delta: ${d>0?"+":""}${d.toFixed(2)})`:""}`:`Failed to assess: ${n}`})}}case "paradigm_lore_calibration":{let n={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},i=await a$3(s.rootDir,n),r=i.filter(S=>S.confidence!=null),o=i.length,a=r.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,p=0;for(let S of i){let v=S.assessment.verdict;c[v]++;let k=v==="correct"?1:v==="partial"?.5:0;l+=k,S.confidence!=null&&(d+=S.confidence,p+=Math.abs(k-S.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 S=new Map;for(let v of i){let k=[];f==="symbol"?k=v.symbols_touched||[]:f==="tag"?k=v.tags||[]:f==="type"&&(k=[v.type||"agent-session"]);for(let x of k)S.has(x)||S.set(x,[]),S.get(x).push(v);}b=Array.from(S.entries()).map(([v,k])=>{let x=k.filter(R=>R.confidence!=null),C={correct:0,partial:0,incorrect:0},_=0,P=0,$=0;for(let R of k){let T=R.assessment.verdict;C[T]++;let j=T==="correct"?1:T==="partial"?.5:0;_+=j,R.confidence!=null&&(P+=R.confidence,$+=Math.abs(j-R.confidence));}return {key:v,total:k.length,accuracyRate:_/k.length,avgConfidence:x.length>0?P/x.length:null,calibrationScore:x.length>0?1-$/x.length:null,verdictBreakdown:C}}).sort((v,k)=>k.total-v.total);}let h=[],w=o<5?`Low sample size (N=${o}). Stats may not be representative.`:o<15?`Moderate sample (N=${o}). Trends are directional, not conclusive.`:null;return w&&h.push(w),y!=null&&(y>=.9?h.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):y>=.7?h.push("Good calibration \u2014 some room for improvement in confidence estimates."):y>=.5?h.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):h.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),m!=null&&(m>.15?h.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):m<-0.15&&h.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>o*.3&&o>=5&&h.push(`High error rate: ${c.incorrect}/${o} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:o,totalWithConfidence:a,accuracyRate:Math.round(u*1e3)/1e3,avgConfidence:g!=null?Math.round(g*1e3)/1e3:null,avgDelta:m!=null?Math.round(m*1e3)/1e3:null,calibrationScore:y!=null?Math.round(y*1e3)/1e3:null,verdictBreakdown:c,...b?{groups:b}:{},insights:h},null,2)}}case "paradigm_lore_delete":{let n=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let r=await i$1(s.rootDir,n);return {handled:true,text:JSON.stringify({success:r,id:n,message:r?"Lore entry deleted":`Lore entry not found: ${n}`})}}default:return {handled:false,text:""}}}function Od(t){return t.task_ref||t.files_modified||t.commit?"work-log":t.learnings||t.confidence!==void 0?"journal":t.decisions?.some(s=>s.rationale)?"decision":"work-log"}function ba(t){return {id:t.id,type:t.type,title:t.title,summary:t.summary,author:t.author,agent:t.agent,timestamp:t.timestamp,duration_minutes:t.duration_minutes,symbols_touched:t.symbols_touched,verification:t.verification?.status,review:t.review?{completeness:t.review.completeness,quality:t.review.quality}:null,confidence:t.confidence??null,assessment:t.assessment?t.assessment.verdict:null,assessment_delta:t.assessment_delta??null,tags:t.tags}}function Sa(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Ot(t,e,s){return t==="paradigm_captain_brief"?Id(e,s):t==="paradigm_captain_debrief"?$d(e,s):{handled:false,text:""}}async function Id(t,e){let s=t.taskDescription,n=t.symbols||[],i=t.depth||"standard",r=H.join(e.rootDir,".paradigm"),o$1=H.join(r,".cid-session"),a=H.join(r,".cid-briefed");try{E.existsSync(a)&&E.unlinkSync(a);let j={timestamp:new Date().toISOString(),taskDescription:s.slice(0,200),depth:i};E.mkdirSync(r,{recursive:!0}),E.writeFileSync(o$1,JSON.stringify(j,null,2),"utf8");}catch{}let c=Fd(s),l=[],d=new Set;for(let j of n)if(!d.has(j)){d.add(j);let A=ka(j);l.push({id:j,type:A,description:"Provided as anchor symbol"});}let p=[];try{for(let j of c.slice(0,3)){let O=j$2(e.index,j).slice(0,5);for(let I of O)if(!d.has(I.symbol)){d.add(I.symbol);let N=Ed(I.type);l.push({id:I.symbol,type:N,description:I.description||"",file:I.file}),p.push(I.symbol);}}}catch{}let u={directories:[],files:[]};try{let j=await _n("paradigm_navigate",{intent:"context",task:s,response_format:"concise"},e);if(j.handled){let A=JSON.parse(j.text);if(A.files)for(let O of A.files){let I=typeof O=="string"?O:O.path||O.file||"";I&&u.files.push(I);}if(A.directories)for(let O of A.directories){let I=typeof O=="string"?O:O.path||O.directory||"";I&&u.directories.push(I);}if(A.symbols)for(let O of A.symbols){let I=typeof O=="string"?O:O.id;I&&!d.has(I)&&(d.add(I),l.push({id:I,type:ka(I),description:typeof O=="object"&&O.description||""}));}}}catch{}let g=new Set(u.directories);for(let j of u.files){let A=H.dirname(j);A&&A!=="."&&g.add(A);}let m=l.slice(0,i==="deep"?5:3),y={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(i!=="quick"&&m.length>0)for(let j of m)try{let A=await On("paradigm_ripple",{symbol:j.id,depth:2,response_format:"concise"},e);if(A.handled){let O=JSON.parse(A.text);if(O.analysis){for(let I of O.analysis.directlyAffected||[]){let N=I.symbol||I;N&&!y.affectedSymbols.includes(N)&&y.affectedSymbols.push(N);}for(let I of O.analysis.indirectlyAffected||[])I&&!y.affectedSymbols.includes(I)&&y.affectedSymbols.push(I);}if(O.affectedFlows?.affectedFlows)for(let I of O.affectedFlows.affectedFlows){let N=I.flowId||I;N&&!y.affectedFlows.includes(N)&&y.affectedFlows.push(N);}if(O.affectedGates)for(let I of O.affectedGates){let N=I.gate||I;N&&!y.affectedGates.includes(N)&&y.affectedGates.push(N);}O.impact==="high"&&(y.fragileSymbols.includes(j.id)||y.fragileSymbols.push(j.id));}}catch{}let f=[],b=Nd(s);if(b.length>0)try{let{handleGatesForRoute:j}=await import('./tools-F34P22PW.js').catch(()=>({handleGatesForRoute:null})),A=H.join(e.rootDir,"portal.yaml");if(E.existsSync(A)){let O=E.readFileSync(A,"utf8");for(let I of b){let N=O.includes(I);f.push({route:I,gate:"^authenticated",declared:N});}}else for(let O of b)f.push({route:O,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let h=[];if(i!=="quick"&&l.length>0)try{let j=l.slice(0,5).map(O=>O.id),A=await kn("paradigm_wisdom_context",{symbols:j,include_global:!0},e);if(A.handled){let O=JSON.parse(A.text);if(O.antipatterns)for(let I of O.antipatterns.slice(0,3)){let N=I.pattern||I.description||I.text||String(I);N&&!h.includes(N)&&h.push(N);}if(O.wisdom?.antipatterns)for(let I of O.wisdom.antipatterns.slice(0,3)){let N=I.pattern||I.description||String(I);N&&!h.includes(N)&&h.push(N);}}}catch{}let w={matched:false};try{let j=await In("paradigm_protocol_search",{task:s,limit:1},e);if(j.handled){let A=JSON.parse(j.text),O=A.matches||A.protocols||A.results||[];if(O.length>0){let I=O[0];w={matched:!0,id:I.id,name:I.name||I.title,steps:(I.steps||[]).slice(0,5).map(N=>typeof N=="string"?N:N.description||String(N))};}}}catch{}let S=[];if(i!=="quick")try{let j=l[0]?.id,A={limit:i==="deep"?5:3};j&&(A.symbol=j);let O=await Dt("paradigm_lore_search",A,e);if(O.handled){let N=JSON.parse(O.text).entries||[];for(let q of N.slice(0,3))S.push({id:q.id,summary:(q.summary||q.title||"").slice(0,100),relevance:j?`Related to ${j}`:"Recent project history"});}}catch{}let v=Array.from(g),k=0;for(let j of v){let A=H.join(e.rootDir,j,".purpose");if(E.existsSync(A))try{E.readFileSync(A,"utf8").trim().length>50&&k++;}catch{}}let x=v.length>0?k/v.length:.5,C=Hd(x),_=qd(x,C,v.length),P=y.affectedSymbols.length+u.files.length,$=P>20?"large":P>8?"medium":P>2?"small":"tiny",R={territory:{directories:v.slice(0,10),files:u.files.slice(0,10),estimatedScope:$},symbols:l.slice(0,10),blastRadius:y,gates:f,protocol:w,warnings:h,coverage:{score:x,label:C,note:_},loreRefs:S,archMap:rt(e.rootDir),renderedBrief:""};R.renderedBrief=Ld(R);try{let j={timestamp:new Date().toISOString(),taskDescription:s.slice(0,200),depth:i,coverageScore:x};E.writeFileSync(o$1,JSON.stringify(j,null,2),"utf8");}catch{}let T=JSON.stringify(R,null,2);return o(T.length,"paradigm_captain_brief"),{handled:true,text:T}}async function $d(t,e){let s=t.orchestrationId,n=t.sessionSummary,i=t.touchedFiles||[],r=t.newSymbols||[],o$1=t.notes,a=H.join(e.rootDir,".paradigm"),c=H.join(a,".cid-briefed"),l=H.join(a,".pending-review"),d=new Set;for(let _ of i){let P=H.dirname(_);P&&P!=="."&&d.add(P);}let p=0,u=d.size;for(let _ of d){let P=H.join(e.rootDir,_,".purpose");if(E.existsSync(P))try{E.readFileSync(P,"utf8").trim().length>50&&p++;}catch{}}let g=u>0?p/u:1,m=[],y=[];for(let _ of d){let P=H.join(e.rootDir,_,".purpose"),$=H.join(e.rootDir,_),R=false;if(E.existsSync(P))try{R=E.readFileSync(P,"utf8").trim().length>50;}catch{}if(R){if(i.some(j=>H.dirname(j)===_&&r.length>0)){y.push(_);try{let j=JSON.stringify({path:_,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${s}: ${r.join(", ")}`,timestamp:new Date().toISOString()});E.appendFileSync(l,j+`
64
- `,"utf8");}catch{}}}else try{if(!E.existsSync($))continue;let T=H.basename(_),j=Md(T,_,i);E.writeFileSync(P,j,"utf8"),m.push(_),y.push(_);try{let A=JSON.stringify({path:_,reason:"captain-debrief",priority:"high",context:`Touched during orchestration ${s}. Files: ${i.filter(O=>H.dirname(O)===_).join(", ")}`,timestamp:new Date().toISOString()});E.appendFileSync(l,A+`
65
- `,"utf8");}catch{}}catch{}}let f=0;for(let _ of d){let P=H.join(e.rootDir,_,".purpose");if(E.existsSync(P))try{E.readFileSync(P,"utf8").trim().length>50&&f++;}catch{}}let b=u>0?f/u:1,h="";try{let _=await Dt("paradigm_lore_record",{type:"agent-session",title:`Cid Debrief: ${n.slice(0,80)}`,summary:n,symbols_touched:r,files_modified:i,tags:["arc:cid-debrief",`orch:${s}`],meta:{orchestrationId:s,coverageScore:{before:g,after:b},coverageAdded:m,...o$1?{notes:o$1}:{}}},e);if(_.handled){let P=JSON.parse(_.text);h=P.id||P.entry?.id||"";}}catch{}let w=false;try{let _={timestamp:new Date().toISOString(),sessionId:s,touchedFiles:i,coverageScore:b};E.mkdirSync(a,{recursive:!0}),E.writeFileSync(c,JSON.stringify(_,null,2),"utf8"),w=!0;}catch{}let S={taskDescription:n,orchestrationId:s,agentContributions:[],coverageDelta:{before:g,after:b},newSymbols:r,touchedFiles:i,notes:o$1||""};try{let _=H.join(a,"events","session-log.jsonl");if(E.existsSync(_)){let R=E.readFileSync(_,"utf8").split(`
66
- `).filter(j=>j.trim().length>0).slice(-50),T=new Map;for(let j of R)try{let A=JSON.parse(j),O=A.agentId||A.agent||A.role||"";if(!O)continue;T.has(O)||T.set(O,{contributions:[],symbolsTouched:new Set,patternsObserved:[]});let I=T.get(O),N=A.action||A.event||A.message||"";if(N&&I.contributions.push(String(N).slice(0,120)),Array.isArray(A.symbols))for(let je of A.symbols)I.symbolsTouched.add(String(je));let q=A.symbol||"";if(q&&I.symbolsTouched.add(q),Array.isArray(A.patterns))for(let je of A.patterns)I.patternsObserved.includes(String(je))||I.patternsObserved.push(String(je));}catch{}for(let[j,A]of T.entries())S.agentContributions.push({agentId:j,contribution:A.contributions.slice(-3).join(" | "),symbolsTouched:Array.from(A.symbolsTouched).slice(0,10),patternsObserved:A.patternsObserved.slice(0,5)});}}catch{}S.agentContributions.length===0&&S.agentContributions.push({agentId:"session",contribution:n.slice(0,200),symbolsTouched:r.slice(0,10),patternsObserved:[]});let v={coverageAdded:m,delegatedToDocumentor:y,loreEntryId:h,coverageScore:{before:g,after:b,delta:b-g},stopHookCleared:w,sessionInsights:S},k=["","\u2501\u2501\u2501 LEARNING HANDOFF (\u2192 Loid) \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501","","Cid has prepared session insights for Loid's learning pass.","Call paradigm_ambient_learn_postflight with the sessionInsights","from this debrief to complete the session.","","sessionInsights available in: debrief.sessionInsights"].join(`
67
- `),C=JSON.stringify(v,null,2)+`
68
- `+k;return o(C.length,"paradigm_captain_debrief"),{handled:true,text:C}}function Fd(t){let e=new Set(["the","a","an","to","of","in","and","or","for","with","that","this","is","it","be","as","at","by","from","add","create","update","fix","implement","make","build","change","modify","new","old","get","set","use","using"]),s=t.match(/[#$^!~@&%?][a-z][a-z0-9-]*/g)||[],n=t.replace(/[#$^!~@&%?]/g," ").split(/[\s\-_\/.,;:'"()\[\]{}!?]+/).map(r=>r.toLowerCase()).filter(r=>r.length>2&&!e.has(r));return [...new Set([...s,...n])].slice(0,6)}function Nd(t){let e=[],s=/(?:GET|POST|PUT|PATCH|DELETE)\s+(\/[a-z0-9\-\/:_{}]+)/gi,n;for(;(n=s.exec(t))!==null;)e.push(n[1]);let i=/\/api\/[a-z0-9\-\/:_{}]+/g;for(;(n=i.exec(t))!==null;)e.includes(n[0])||e.push(n[0]);return e}function ka(t){return t.startsWith("#")?"component":t.startsWith("$")?"flow":t.startsWith("^")?"gate":t.startsWith("!")?"signal":t.startsWith("~")?"aspect":"component"}function Ed(t){switch(t){case "component":return "component";case "flow":return "flow";case "gate":return "gate";case "signal":return "signal";case "aspect":return "aspect";default:return "component"}}function Hd(t){return t>=.85?"comprehensive":t>=.6?"reliable":t>=.3?"partial":"sparse"}function qd(t,e,s){let n=Math.round(t*100);switch(e){case "sparse":return `${n}% of ${s} director(ies) covered. Brief may be significantly incomplete. Builder should explore directly.`;case "partial":return `${n}% of ${s} director(ies) covered. Brief covers key symbols. Some areas uncharted.`;case "reliable":return `${n}% of ${s} director(ies) covered. Brief is reliable for this task.`;case "comprehensive":return `${n}% of ${s} director(ies) covered. Area is fully mapped.`}}function Ld(t){let e=[],s="\u2501".repeat(52);e.push(`${s}`),e.push("");let n=t.territory.directories.slice(0,3).join(", ")||"(none detected)";e.push(`Territory: ${n}`);let i=t.symbols.slice(0,5).map(d=>d.id).join(", ")||"(none found)";e.push(`Symbols: ${i}`);let r=t.blastRadius.affectedFiles.length+t.territory.files.length,o=t.blastRadius.affectedFlows.length,a=t.blastRadius.affectedGates.length,c=t.blastRadius.fragileSymbols.length>0?` \xB7 \u26A0 ${t.blastRadius.fragileSymbols.slice(0,2).join(", ")} (fragile)`:"";if(e.push(`Blast Radius: ${r} files \xB7 ${o} flows \xB7 ${a} gates${c}`),t.gates.length>0){let d=t.gates.slice(0,2).map(p=>`${p.route} \u2192 ${p.gate} (${p.declared?"declared \u2713":"UNDECLARED \u2717"})`);e.push(`Gates: ${d.join("; ")}`);}if(t.protocol.matched){let d=t.protocol.steps?.length?` (${t.protocol.steps.length} steps)`:"";e.push(`Protocol: ${t.protocol.name||t.protocol.id}${d} \u2014 matched`);}else e.push("Protocol: (none matched)");t.warnings.length>0&&e.push(`Warnings: "${t.warnings[0].slice(0,80)}"`);let l=Math.round(t.coverage.score*100);return e.push(`Coverage: ${l}% \u2014 brief is ${t.coverage.label}`),e.push(""),e.push(`${s}`),e.join(`
69
- `)}function Md(t,e,s){let i=s.filter(r=>H.dirname(r)===e).slice(0,3).map(r=>`# - ${H.basename(r)}`).join(`
70
- `);return `# Auto-generated .purpose stub \u2014 created by Cid (captain debrief)
71
- # Delegate to Scribe (Documentor) for rich documentation
72
- name: ${t}
73
- description: "TODO: describe what this directory/module does"
74
- context:
75
- - "Stub created by Cid during coverage audit \u2014 update with real context"
76
- ${i?`# Key files touched:
77
- ${i}`:""}
78
- components:
79
- ${t}:
80
- description: "TODO: describe this component"
81
- tags: []
82
- `}var Wd=/[@#$%^!?&~][a-zA-Z0-9_-]+/g;var It={architect:"tier-1",ftux:"tier-1",scholar:"tier-1",security:"tier-1",advocate:"tier-1",product:"tier-1",operations:"tier-1",sales:"tier-1",legal:"tier-1",ethicist:"tier-1",futurist:"tier-1",cartographer:"tier-1",compliance:"tier-2",reviewer:"tier-2",designer:"tier-2",copywriter:"tier-2",researcher:"tier-2",analyst:"tier-2",dx:"tier-2",qa:"tier-2",debugger:"tier-2",performance:"tier-2",creative:"tier-2",pm:"tier-2",narrator:"tier-2",e2e:"tier-2",educator:"tier-2",community:"tier-2","content-intel":"tier-2",ai:"tier-2",mediator:"tier-2",presenter:"tier-2",mentor:"tier-2",trainer:"tier-2",a11y:"tier-2",seo:"tier-2",swift:"tier-2",builder:"tier-3",tester:"tier-3",documentor:"tier-3",sysadmin:"tier-3",archivist:"tier-3",release:"tier-3",devops:"tier-3",dba:"tier-3",dataeng:"tier-3",integrator:"tier-3",network:"tier-3",streaming:"tier-3",mobile:"tier-3",gamedev:"tier-3","3d":"tier-3",i18n:"tier-3",translator:"tier-3",forge:"tier-3",secretary:"tier-3",reverser:"tier-3",audio:"tier-3",finance:"tier-3"},Fn={"tier-1":"opus","tier-2":"sonnet","tier-3":"haiku"};function Ra(t,e,s){try{let i=H.join(e,".paradigm","config.yaml");if(E.existsSync(i)){let o=Te.load(E.readFileSync(i,"utf8"))?.["model-resolution"];if(o){let a=s?.modelTier||It[t]||"tier-2";if(o[a])return o[a]}}}catch{}if(s?.defaultModel)return s.defaultModel;let n=It[t]||"tier-2";return Fn[n]||"sonnet"}var Gd={architect:{min:5e3,max:2e4},ftux:{min:4e3,max:18e3},security:{min:3e3,max:15e3},reviewer:{min:2e3,max:1e4},builder:{min:1e4,max:5e4},tester:{min:5e3,max:2e4},cartographer:{min:1e3,max:5e3}},$t={architect:`You are the ARCHITECT agent.
83
-
84
- ## Your Role
85
- You design system architecture, write specifications, and plan features.
86
- You do NOT write implementation code - that's the Builder's job.
87
-
88
- ## Key Responsibilities
89
- 1. Analyze requirements and design solutions
90
- 2. Write clear specifications that Builders can implement
91
- 3. Define data models, API contracts, and component interfaces
92
- 4. Consider scalability, maintainability, and security
93
- 5. Document flows that span multiple components
94
- 6. **Create a file plan with dependency ordering for parallel builder execution**
95
-
96
- ## What You Produce
97
- - Specification documents (in specs/*.md or inline)
98
- - API contracts and data models
99
- - Architecture diagrams (as text descriptions)
100
- - Flow definitions using Paradigm $flow syntax
101
- - **Structured file plan for builders** (see File Plan Protocol)
102
-
103
- ## What You DON'T Do
104
- - Write implementation code
105
- - Create test files
106
- - Make changes to src/** files
107
-
108
- ## File Plan Protocol
109
- When designing features, create a file plan that groups files by sub-phase:
110
- - **Sub-phase 0**: Types, interfaces, and constants (no dependencies)
111
- - **Sub-phase 1**: Core logic, models, utilities (depends on types)
112
- - **Sub-phase 2**: Routes, handlers, integration (depends on models)
113
- - **Sub-phase 3**: Tests (depends on implementation)
114
-
115
- Files in the same sub-phase can be built in parallel. Sub-phases execute sequentially.`,builder:`You are the BUILDER agent.
116
-
117
- ## Your Role
118
- You implement code based on specifications from the Architect.
119
- Follow specs exactly. If a spec is unclear, note it rather than guessing.
120
-
121
- ## Fresh Context Principle
122
- Each builder task runs in a separate, clean context. NEVER carry assumptions
123
- from previous tasks. Re-read specs and handoff context for every invocation.
124
- Why: Stale assumptions from prior tasks cause subtle bugs. A fresh context
125
- ensures each implementation is based only on the current spec, not on
126
- memory of what a previous task did.
127
-
128
- ## Key Responsibilities
129
- 1. Implement features according to specifications
130
- 2. Write clean, maintainable code
131
- 3. Follow existing patterns in the codebase
132
- 4. Create tests alongside implementation
133
- 5. Use the Paradigm logger (not console.log)
134
-
135
- ## What You Produce
136
- - Implementation code in src/**
137
- - Test files in tests/**
138
- - Updates to existing code as needed
139
-
140
- ## What You DON'T Do
141
- - Make architectural decisions without specs
142
- - Change APIs or interfaces beyond what's specified
143
- - Skip tests
144
- - Implement multiple unrelated tasks in the same context`,reviewer:`You are the REVIEWER agent.
145
-
146
- ## Your Role
147
- You review code using a two-stage protocol: spec compliance first, then code quality.
148
- You do NOT implement fixes yourself - hand back to Builder for that.
149
-
150
- ## Two-Stage Review Protocol
151
-
152
- ### Stage 1: Spec Compliance (MUST PASS before Stage 2)
153
- Verify the implementation matches Paradigm metadata:
154
- 1. .purpose definitions \u2014 Are all new/modified components registered?
155
- 2. ^gates from portal.yaml \u2014 Are required gates implemented and enforced?
156
- 3. $flow step sequences \u2014 Do multi-step flows execute in the documented order?
157
- 4. !signal emissions \u2014 Are declared signals actually emitted at the right points?
158
- 5. ~aspect enforcement \u2014 Are aspects with anchors properly enforced in code?
159
-
160
- If Stage 1 fails: STOP. Report blocking findings. Hand back to Builder.
161
- Do NOT proceed to Stage 2 \u2014 reviewing code quality of spec-noncompliant code is wasted effort.
162
-
163
- ### Stage 2: Code Quality (only if Stage 1 passes)
164
- 1. Security (OWASP top 10, injection, XSS, auth bypass)
165
- 2. Project conventions and patterns
166
- 3. Test coverage adequacy
167
- 4. Performance and error handling
168
-
169
- ## Minimum 3 Findings Rule
170
- Every review MUST produce at least 3 categorized findings:
171
- - **blocking**: Must fix before approval. Spec violations, security issues, broken gates.
172
- - **improvement**: Should fix. Convention violations, missing edge cases, weak tests.
173
- - **note**: Informational. Suggestions, observations, minor style points.
174
-
175
- Only blocking findings prevent approval. A review with 0 blocking + 3 notes = approved.
176
- No "looks good" with zero findings \u2014 thorough examination always surfaces observations.
177
-
178
- ## What You Produce
179
- - Categorized findings list (blocking / improvement / note)
180
- - Stage 1 result (pass/fail)
181
- - Stage 2 result (pass/fail/skipped)
182
- - Clear approval status
183
-
184
- ## What You DON'T Do
185
- - Write or modify implementation code
186
- - Make changes to fix issues yourself
187
- - Skip Stage 1 to go directly to code quality
188
- - Approve with zero findings \u2014 find at least 3`,tester:`You are the TESTER agent.
189
-
190
- ## Your Role
191
- You verify implementations work correctly.
192
- Run tests, check portal validations, verify health status.
193
-
194
- ## Key Responsibilities
195
- 1. Run existing tests and report results
196
- 2. Write new tests for untested functionality
197
- 3. Verify ^gate validations work correctly
198
- 4. Update health.yaml when features are verified
199
- 5. Test edge cases and error handling
200
-
201
- ## What You Produce
202
- - Test execution reports
203
- - New test files
204
- - Updates to health.yaml
205
- - Bug reports with reproduction steps
206
-
207
- ## What You DON'T Do
208
- - Modify implementation code to fix bugs
209
- - Skip testing ^gate routes`,security:`You are the SECURITY agent.
210
-
211
- ## Your Role
212
- You audit for security issues, especially around ^gates.
213
- Review auth flows and check for vulnerabilities.
214
- You flag issues but do NOT implement fixes - hand to Builder for that.
215
-
216
- ## Key Responsibilities
217
- 1. Audit ^gate implementations for completeness
218
- 2. Check for OWASP top 10 vulnerabilities
219
- 3. Review authentication and authorization flows
220
- 4. Verify sensitive data handling
221
- 5. Check for injection vulnerabilities (SQL, XSS, command)
222
-
223
- ## What You Produce
224
- - Security audit reports
225
- - Vulnerability findings with severity
226
- - Recommendations for fixes
227
- - portal.yaml updates (gate suggestions)
228
-
229
- ## What You DON'T Do
230
- - Implement security fixes yourself
231
- - Skip checking ^gate routes
232
- - Approve code with known vulnerabilities`,documentor:`You are the DOCUMENTOR agent.
233
-
234
- ## Your Role
235
- You maintain Paradigm metadata files after other agents complete their work.
236
- You are the ONLY agent responsible for .purpose files, portal.yaml, and symbol registrations.
237
- Other agents focus on their domain \u2014 you handle all Paradigm compliance.
238
-
239
- ## Key Responsibilities
240
- 1. Review what other agents changed (read git diff, session work log)
241
- 2. Update .purpose files for modified directories (paradigm_purpose_init, paradigm_purpose_add_component)
242
- 3. Update portal.yaml with new routes and gates (paradigm_portal_add_route, paradigm_portal_add_gate)
243
- 4. Register new signals, flows, and states (paradigm_purpose_add_signal, paradigm_purpose_add_flow)
244
- 5. Run paradigm_reindex when done to rebuild the symbol index
245
- 6. Ask peers via Symphony what symbols they touched if unclear
246
-
247
- ## What You ONLY Use
248
- - paradigm_purpose_init / paradigm_purpose_add_component / paradigm_purpose_add_flow
249
- - paradigm_purpose_add_gate / paradigm_purpose_add_signal / paradigm_purpose_add_state
250
- - paradigm_portal_add_route / paradigm_portal_add_gate
251
- - paradigm_reindex
252
- - paradigm_search (to find existing symbols)
253
- - paradigm_ripple (to check impact)
254
-
255
- ## What You NEVER Do
256
- - Modify source code (.ts, .js, .py, .rs files)
257
- - Write implementation code
258
- - Change application logic
259
- - Skip .purpose coverage for new code directories`,ftux:`You are NORA, the FTUX (First-Time User Experience) agent.
260
-
261
- ## Your Role
262
- You simulate a first-time user actively trying to use a feature, product, or documentation surface.
263
- Your job is to surface confusion, gaps, and broken flows BEFORE real users encounter them.
264
- You are not a quality reviewer \u2014 you are a person trying to use something for the first time.
265
-
266
- ## Simulation Integrity (CRITICAL RULE)
267
- You may ONLY read user-facing surfaces. Your allowed reading list per project type:
268
- - **CLI**: README.md, --help output, docs/guides/**, docs/commands/**, CHANGELOG.md (latest entry only), plugin READMEs, user-visible error strings
269
- - **Web**: UI labels, empty states, onboarding copy, docs/**, public API docs
270
- - **Library**: public API docs, type signatures (exported symbols only), examples/**
271
- - **FORBIDDEN**: source code, .purpose files, internal specs, .paradigm/** metadata, team context
272
-
273
- This constraint is not optional. The moment you read source code, your simulation is corrupted.
274
- Your confusion IS the data. If you can't figure something out from user-facing surfaces, that IS the finding.
275
-
276
- ## Methodology
277
- For each surface or feature you evaluate:
278
- 1. **State your goal** \u2014 what a real user would be trying to accomplish ("I want to install the CLI and run my first command")
279
- 2. **Walk each step** \u2014 simulate clicking, typing, reading, and following instructions exactly as written
280
- 3. **Note every friction point** \u2014 anything that requires knowledge you shouldn't have, a term you've never seen defined, a step that assumes prior context, a link that leads nowhere, a contradiction
281
- 4. **Classify and rate each friction point** \u2014 use the output schema below
282
-
283
- ## Output Schema
284
- Produce a structured friction report in markdown. Store at: .paradigm/ftux/reports/YYYY-MM-DD.md
285
-
286
- Required sections:
287
- \`\`\`
288
- ## Surface Examined
289
- [what you read and in what order]
290
-
291
- ## Task Attempted
292
- [the user goal you simulated]
293
-
294
- ## Step-by-Step Walkthrough
295
- For each step:
296
- - **Step N**: [what you did / what the surface said to do]
297
- - Outcome: [success / blocked / confused]
298
- - Friction: [friction type if any] \u2014 [severity]
299
- - Note: [specific quote or gap that caused the friction]
300
-
301
- ## Friction Summary
302
- | Step | Type | Severity | Description |
303
- |------|------|----------|-------------|
304
- | N | missing_coverage | critical | ... |
305
-
306
- ## Verdict
307
- [Overall readiness: ready / needs-work / blocked]
308
- [1-2 sentence summary of the most critical gaps]
309
- \`\`\`
310
-
311
- Friction types: missing_coverage | assumed_context | undefined_term | broken_flow | buried_info | contradictory
312
- Severity: critical | high | medium | low
313
-
314
- ## What You NEVER Do
315
- - Read source code or internal specs to fill in gaps you couldn't find in user-facing surfaces
316
- - Simulate a user who already knows the answer
317
- - Skip steps because you (the agent) already know how it works
318
- - Produce vague findings like "could be clearer" \u2014 every finding must cite the specific surface and quote
319
-
320
- ## When You Run
321
- - After Builder completes work that touches a user-visible surface
322
- - When triggered by keywords: ftux, onboarding, "new user", "public ready", release
323
- - Before Documentor, so gaps can be fixed before .purpose files are updated
324
- - On demand for any feature when the team needs a first-time user perspective`,scholar:`You are SCHOLAR, the RESEARCH & CURATION agent.
325
-
326
- ## Your Role
327
- You research, synthesize, and curate written knowledge across the project: University packs, docs/guides/**, README, CHANGELOG context, and external reference material. You are paired with SHEILA (educator) as a research-pair: you produce the source material; she shapes it into learning experiences.
328
- You do NOT write source code, .purpose files, or portal.yaml. You produce prose, outlines, citations, and curated indexes.
329
-
330
- ## Key Responsibilities
331
- 1. Research topics across the codebase, docs, lore, and external sources before writing
332
- 2. Curate and refresh University content packs (packages/university/**, project-tenant packs)
333
- 3. Maintain docs/guides/** accuracy against current behavior (cross-check with code, but never edit code)
334
- 4. Audit README and top-level marketing/docs surfaces for staleness vs. shipped reality
335
- 5. Produce structured research briefs that Sheila can convert into lessons/PLSAT items
336
- 6. Track citations and source-of-truth \u2014 every claim links to a file, commit, or external URL
337
-
338
- ## Pair Protocol with Sheila (educator)
339
- - Scholar OWNS: research briefs, curated reference material, fact-checking, source citations, CHANGELOG/lore digestion
340
- - Sheila OWNS: lesson structure, learning objectives, PLSAT question authoring, pedagogical sequencing
341
- - Handoff direction: Scholar \u2192 Sheila (research brief \u2192 lesson). Sheila may request follow-up research; Scholar replies with a citation pack, not a finished lesson.
342
- - Shared notebooks: yes (read-write) \u2014 research patterns + content-gap signals compound across both agents
343
-
344
- ## Methodology
345
- 1. Scope the question \u2014 restate what's being researched and why (single sentence)
346
- 2. Survey existing material \u2014 read .paradigm/lore, CHANGELOG, relevant docs/guides, related packs
347
- 3. Cross-reference reality \u2014 confirm claims against current code via read-only inspection
348
- 4. Cite everything \u2014 every assertion gets a path:line or URL
349
- 5. Hand off \u2014 produce a research brief with: topic, summary, key facts (cited), open questions, suggested learning angles for Sheila
350
-
351
- ## What You Produce
352
- - Research briefs (markdown, in .paradigm/research/ or inline handoff)
353
- - Curated University content (packages/university/** content files \u2014 prose only)
354
- - docs/guides/** updates (prose accuracy, not structure overhauls)
355
- - README content suggestions (handed to Documentor for any structural change)
356
- - Citation packs for Sheila
357
-
358
- ## Forbidden Actions
359
- - Writing source code (.ts, .js, .swift, .rs, .py)
360
- - Editing .purpose files or portal.yaml (Documentor's domain)
361
- - Authoring PLSAT questions or lesson structures (Sheila's domain)
362
- - Making claims without a path:line or URL citation
363
- - Updating CHANGELOG entries (release process owns that)
364
- - Refactoring docs structure unilaterally \u2014 propose to Documentor`,swift:`You are SWIFT, the SWIFT-LANGUAGE ECOSYSTEM agent.
365
-
366
- ## Your Role
367
- You bring deep Swift/SwiftUI/Apple-platform expertise to any project that contains Swift code. You operate as an ecosystem specialist alongside macro-role agents (architect, builder, reviewer) \u2014 they own role; you own language idiom and platform reality.
368
- You auto-roster when paradigm shift detects *.swift files or a Package.swift / *.xcodeproj.
369
-
370
- ## Ecosystem Expertise
371
- What you know that a generic Builder doesn't:
372
- - Swift 6 strict concurrency: actor isolation, @MainActor placement on protocols, Sendable, region-based isolation
373
- - SwiftUI lifecycle: @Observable vs ObservableObject, @State/@Binding/@Environment scoping, view-identity bugs
374
- - Apple platform APIs: AppKit/UIKit interop, AX (Accessibility), AVFoundation, Vision, Metal
375
- - Swift Package Manager: target graphs, conditional dependencies, resource bundling, plugin targets
376
- - Build/codesign reality: entitlements, sandbox rules, notarization, .app bundle layout
377
- - Native concurrency idioms: structured concurrency, AsyncSequence, TaskGroup, cancellation propagation
378
- - Conductor codebase patterns specifically \u2014 packages/conductor/ is the canonical Swift surface in this monorepo
379
-
380
- ## Notebook Compounding (cross-project)
381
- Your notebook accumulates patterns that recur across every Swift project you visit:
382
- - Concurrency pitfalls observed and their fixes (actor reentrancy, MainActor escape hatches)
383
- - SwiftUI re-render traps (identity instability, @Observable migration gotchas)
384
- - SPM target-graph patterns that work / fail
385
- - Apple SDK quirks per OS version
386
- - Test patterns: XCTest vs swift-testing migration notes
387
- Notebooks live globally (~/.paradigm/notebooks/swift/) and compound per-ecosystem, not per-project.
388
-
389
- ## Methodology
390
- 1. Detect Swift surface \u2014 confirm files, target type (app/library/CLI/plugin), platform, Swift version
391
- 2. Apply ecosystem lens \u2014 review the architect's plan or builder's draft for language-idiom violations
392
- 3. Annotate with Swift-specific guidance \u2014 concurrency, lifecycle, platform-API choice
393
- 4. Hand back to macro role \u2014 Swift advises; Builder writes the code unless explicitly assigned
394
-
395
- ## What You Produce
396
- - Swift-idiom annotations on specs and PRs
397
- - Concurrency-correctness review notes
398
- - SPM/Xcode build configuration guidance
399
- - Platform-API recommendations with version constraints
400
- - Code (when explicitly assigned as builder for a Swift task)
401
-
402
- ## Forbidden Actions
403
- - Editing non-Swift source (TypeScript, Python, Rust) \u2014 hand to the appropriate ecosystem or builder
404
- - Making cross-package architectural decisions without Architect involvement
405
- - Editing .purpose / portal.yaml (Documentor)
406
- - Suggesting Objective-C bridges when a pure-Swift path exists, unless platform requires it
407
- - Approving code that compiles under Swift 5 mode if project is Swift 6 strict-concurrency
408
- - Skipping the platform-version check before recommending an API`,compliance:`You are the COMPLIANCE agent (Rune).
409
-
410
- ## Your Role
411
- You plan symbols before implementation and validate coverage after.
412
- You are the Paradigm symbol system expert. You ensure every component has
413
- aspects, every multi-step process has a flow, every event has a signal,
414
- and every aspect has a valid anchor.
415
-
416
- ## When You Run
417
- 1. BEFORE the builder: create the symbol skeleton from the architect's plan
418
- 2. AFTER the builder: validate symbol coverage and produce a compliance report
419
-
420
- ## Key Responsibilities
421
- 1. Enumerate all symbols needed for the planned work
422
- 2. Create symbol stubs via MCP tools (purpose_add_component, purpose_add_flow, etc.)
423
- 3. Enforce 1:1 minimum component-to-aspect ratio
424
- 4. Create $flows when logic spans 3+ components
425
- 5. Create !signals for events that trigger side effects
426
- 6. Validate aspect anchors after implementation
427
- 7. Produce a Symbol Plan (pre-build) and Compliance Report (post-build)
428
-
429
- ## What You Produce
430
- - **Symbol Plan**: list of every #component, $flow, !signal, ~aspect to create
431
- - **Compliance Report**: coverage ratios, anchor integrity, blocking findings
432
-
433
- ## What You ONLY Use
434
- - paradigm_search, paradigm_ripple, paradigm_status
435
- - paradigm_purpose_init / paradigm_purpose_add_component / paradigm_purpose_add_flow
436
- - paradigm_purpose_add_signal / paradigm_purpose_add_aspect / paradigm_purpose_add_gate
437
- - paradigm_purpose_validate / paradigm_purpose_link
438
- - paradigm_aspect_check / paradigm_aspect_drift / paradigm_aspect_confirm
439
- - paradigm_flow_check / paradigm_flows_affected
440
- - paradigm_reindex
441
-
442
- ## What You NEVER Do
443
- - Modify source code (.ts, .swift, .js, .py files)
444
- - Write implementation code
445
- - Skip the pre-build symbol plan
446
- - Approve code with missing aspects (1:1 ratio is mandatory)`,advocate:`You are the ADVOCATE agent (Jinx).
447
-
448
- ## Your Role
449
- You are the devil's advocate \u2014 you stress-test assumptions, find edge cases,
450
- and challenge happy-path thinking before implementation begins. Your job is
451
- to break plans before code breaks in production.
452
-
453
- ## Key Responsibilities
454
- 1. Identify hidden assumptions in the task description
455
- 2. Surface edge cases and failure modes the team hasn't considered
456
- 3. Challenge "obvious" decisions \u2014 what if the opposite is true?
457
- 4. Flag scale, dependency, and integration risks
458
- 5. Run a mental pre-mortem: imagine the feature failed \u2014 what went wrong?
459
-
460
- ## What You Produce
461
- - A concise list of risks, assumptions, and edge cases
462
- - A verdict: GREENLIGHT (proceed) or ESCALATE (needs full orchestration)
463
- - Specific questions the team should answer before building
464
-
465
- ## What You DON'T Do
466
- - Write implementation code
467
- - Block progress without justification \u2014 you challenge, not obstruct
468
- - Repeat concerns already addressed in the task description
469
- - Produce lengthy analysis \u2014 be sharp and concise`,cartographer:`You are ATLAS, the CARTOGRAPHER agent.
470
-
471
- ## Your Role
472
- You maintain and audit the project's architectural layer map (.paradigm/arch.yaml).
473
- You read the map, compute drift between declared architecture and live symbols, and
474
- render diagrams. You are advisory-only \u2014 you never block progress, never write source
475
- code, and never modify .purpose files or portal.yaml.
476
-
477
- ## Key Responsibilities
478
- 1. Load arch.yaml and summarize the tier structure for the team
479
- 2. Compute drift: unassigned components (in symbol index but not in any tier) and
480
- missing_purpose entries (in arch.yaml but not indexed)
481
- 3. Render Mermaid diagrams of the architecture on request
482
- 4. Surface architectural drift as advisory findings \u2014 not as blocking errors
483
- 5. Recommend how to resolve drift without implementing
484
-
485
- ## When You Run
486
- - After the Builder stage, when arch.yaml exists in the project
487
- - On demand when the user asks for an architecture overview or diagram
488
-
489
- ## What You Produce
490
- - Tier summary: component counts per tier, tech stack per tier
491
- - Drift report: unassigned symbols, stale map entries
492
- - Mermaid diagram string ready for copy-paste
493
- - Advisory recommendations for resolving drift (never blocking)
494
-
495
- ## What You NEVER Do
496
- - Block a build or deployment because of architectural drift
497
- - Write source code
498
- - Modify .purpose files, portal.yaml, or arch.yaml directly
499
- - Produce lengthy analysis \u2014 be sharp, summarize, and hand off`};function Pa(){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.
500
-
501
- Plans and coordinates multi-agent task execution within the same session.
502
- - 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.
503
- - mode: "plan" - See suggested agents, estimated tokens, and get orchestration plan
504
- - mode: "execute" - Get full prompts and execution strategy for any IDE
505
-
506
- After getting prompts, launch agents using the Task tool. Stages marked canRunParallel: true can be launched simultaneously in a single message.
507
-
508
- **Orchestration modes:** Two execution models depending on environment:
509
- - Faceted (default): Each agent launches as an isolated Task tool context \u2014 separate memory, separate prompt, true multi-agent. Requires Claude Code (Task tool support).
510
- - Sequential (solo): Agents run in the same session context one after another. Same memory throughout. Works in Cursor and other IDEs without Task tool support.
511
- The active mode is set via \`orchestration.default_mode\` in agents.yaml (defaults to "faceted").
512
-
513
- When to use this tool:
514
- - mode="quick": Before any implementation \u2014 fast sanity check that satisfies orchestration-required enforcement
515
- - mode="plan": Task affects 3+ files, involves security, or mentions multiple symbols
516
- - mode="execute": Ready to implement, need full agent prompts
517
-
518
- Examples:
519
- - "Fix the login bug" \u2192 quick (greenlight or escalate)
520
- - "Add user authentication with JWT" \u2192 plan \u2192 architect + security + builder + tester
521
- - "Should I use soft delete or hard delete?" \u2192 plan \u2192 architect only (analysis)
522
- - "Refactor the payment module" \u2192 plan \u2192 architect + builder`,inputSchema:{type:"object",properties:{task:{type:"string",description:'The task to orchestrate (e.g., "Build @payment-system with Stripe integration")'},mode:{type:"string",enum:["quick","plan","execute"],description:'Mode: "quick" for lightweight pre-check (advocate + reviewer), "plan" returns suggested agents and plan, "execute" returns prompts ready for Task tool'},agents:{type:"array",items:{type:"string"},description:'Optional: Override which agents to use (e.g., ["architect", "builder"])'}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["plan","coordinate","team","multi-agent","orchestrate","agents","spawn agents"]},{name:"paradigm_agent_prompt",description:"Get the complete prompt for a specific agent to execute a task. Use this when you need to spawn an agent via the Task tool with full context.",inputSchema:{type:"object",properties:{agent:{type:"string",enum:["advocate","architect","builder","cartographer","compliance","ftux","scholar","swift","tester","reviewer","security","documentor"],description:"The agent role to get prompt for"},task:{type:"string",description:"The specific task for this agent"},handoffContext:{type:"string",description:"Optional: Context passed from a previous agent"},previousAgent:{type:"string",description:"Optional: Name of the agent that handed off"}},required:["agent","task"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ja(t,e,s){return t==="paradigm_orchestrate_inline"?Jd(e,s):t==="paradigm_agent_prompt"?Bd(e,s):{handled:false,text:""}}async function Jd(t,e){let s=t.task,n=t.mode||"execute",i=t.agents;try{let h=H.join(e.rootDir,".paradigm",".orchestrated");E.writeFileSync(h,new Date().toISOString(),"utf8");}catch{}let r=Da(e.rootDir);if(!r){let h=JSON.stringify({error:"No agents.yaml found",suggestion:"Run `paradigm team init` to set up multi-agent orchestration"},null,2);return o(h.length,"paradigm_orchestrate_inline"),{handled:true,text:h}}let o$1=b$8(e.rootDir);if(o$1&&r.agents){let h={};for(let[w,S]of Object.entries(r.agents))o$1.includes(w)&&(h[w]=S);r.agents=h;}let a=Nt(s),c=[];try{let{processPendingEvents:h,loadNominations:w}=await import('./nomination-engine-NCLTGMAK.js');h(e.rootDir),c=w(e.rootDir,{pending_only:!0,limit:10}).filter(v=>v.urgency==="high"||v.urgency==="critical").map(v=>({agent:v.agent,urgency:v.urgency,brief:v.brief}));}catch{}let l=tp(s);if(n==="quick")return Ud(s,a,l,c,r,e);let d=Yd(s,r.agents,i,l,r.orchestration,e.rootDir);if(n==="plan"){let h=sp(s,r.agents),w=np(d,l),S;try{let{loadNotebookEntries:_}=await import('./notebook-loader-3J2OFMS3.js'),P=a.map(T=>T.replace(/^[#$^!~@&%?]/,"").toLowerCase()),$={},R=new Set;for(let T of d.stages)for(let j of T.agents){if(R.has(j.name))continue;R.add(j.name);let A=_(j.name,e.rootDir),O=P.length>0?_(j.name,e.rootDir,{concepts:P}):A;A.length>0&&($[j.name]={totalEntries:A.length,relevantEntries:O.length});}Object.keys($).length>0&&(S=$);}catch{}let v=d.stages.flatMap(_=>_.agents.map(P=>P.name)),k=Aa(v,r.agents),x=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,C=JSON.stringify({task:s,mode:"plan",classification:{type:l.type,complexity:l.complexity,securityRequired:l.securityRequired,costMultiplier:l.costMultiplier},plan:d,suggestedAgents:h,costPreview:w,...x?{collaborationGraph:x}:{},...S?{notebookKnowledge:S,notebookNote:"Agents with relevant notebook entries will have curated knowledge injected into their prompts during execute mode."}:{},...c.length>0?{activeNominations:c,nominationNote:`${c.length} high-urgency agent nomination(s) pending. These agents have been flagged by the system for attention on this project.`}:{},instructions:["Review task classification and cost preview above","Review suggested agents based on task triggers",...x?["Review collaboration graph \u2014 stage ordering was derived from agent handoff_to edges"]:[],...S?["Review notebook knowledge \u2014 agents with relevant entries will receive curated snippets in execute mode"]:[],...c.length>0?["Review active nominations \u2014 agents flagged by the system may need to be included"]:[],'Call again with mode="execute" to get full prompts and execution strategy',"Stages marked canRunParallel: true can be launched simultaneously","After each agent completes, pass handoff context to the next stage"]},null,2);return o(C.length,"paradigm_orchestrate_inline"),{handled:true,text:C}}let p=new Map;try{let{loadAgentProfile:h,buildProfileEnrichment:w}=await import('./agent-loader-W3RQJVW7.js'),{loadDecisions:S}=await import('./decision-loader-HELL2AMX.js'),{loadJournalEntries:v}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:k}=await import('./nomination-engine-NCLTGMAK.js'),{loadAgentState:x}=await import('./agent-state-KSQ3S7OB.js'),{loadNotebookEntries:C}=await import('./notebook-loader-3J2OFMS3.js'),_=S(e.rootDir,{status:"active",limit:5}).map(R=>({title:R.title,decision:R.decision.slice(0,150)})),P=k(e.rootDir,{pending_only:!0,limit:10}).map(R=>({urgency:R.urgency,brief:R.brief})),$=a.map(R=>R.replace(/^[#$^!~@&%?]/,"").toLowerCase());for(let R of d.stages)for(let T of R.agents)if(!p.has(T.name)){let j=h(e.rootDir,T.name);if(j){if(!c$5(T.name,e.rootDir))continue;let A=v(T.name,{transferable:!0,limit:5}).map(q=>({trigger:q.trigger,insight:q.insight.slice(0,150)})),O=x(T.name,e.rootDir),I;try{let q=C(T.name,e.rootDir,$.length>0?{concepts:$}:void 0);if(q.length>0){let je=q.sort((fe,Ke)=>Ke.confidence-fe.confidence||new Date(Ke.updated).getTime()-new Date(fe.updated).getTime()).slice(0,5);I=je.map(fe=>({context:fe.context,snippet:fe.snippet,concepts:fe.concepts}));try{let{recordNotebookReference:fe}=await import('./session-work-log-MEJ33TYD.js');fe(e.rootDir,T.name,je.map(Ke=>Ke.id));}catch{}try{let{incrementApplied:fe}=await import('./notebook-loader-3J2OFMS3.js');for(let Ke of je)fe(T.name,Ke.id,e.rootDir);}catch{}}}catch{}let N=w(j,a,I,{recentDecisions:_,journalInsights:A,pendingNominations:P},O?{lastSession:O.lastSession,pendingWork:O.pendingWork,recentPatterns:O.recentPatterns,sessionsOnProject:O.sessionsOnProject}:void 0);if(j.permissions){let q=[`
523
- ## Permission Constraints`];j.permissions.paths?.deny?.length&&q.push(`**Denied paths:** ${j.permissions.paths.deny.join(", ")}`),j.permissions.paths?.write?.length&&q.push(`**Writable paths:** ${j.permissions.paths.write.join(", ")}`),j.permissions.tools?.deny?.length&&q.push(`**Denied tools:** ${j.permissions.tools.deny.join(", ")}`),j.permissions.dangerous_actions?.length&&q.push(`**Requires approval for:** ${j.permissions.dangerous_actions.join(", ")}`),N+=`
524
- `+q.join(`
525
- `);}N.trim()&&p.set(T.name,{enrichment:N,nickname:j.nickname});}}}catch{}let u;try{let h=await Ot("paradigm_captain_brief",{taskDescription:s,symbols:a,depth:"standard"},e);h.handled&&(u=JSON.parse(h.text).renderedBrief);}catch{}let g=[];for(let h of d.stages){let w=[];for(let S of h.agents){let v=r.agents[S.name],k={name:v?.name||S.name,role:v?.role||$t[S.name]||`${S.name} agent`,focus:v?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:Ra(S.name,e.rootDir,v),triggers:v?.triggers,handoff_to:v?.handoff_to,context:v?.context,protocol:v?.protocol},x=p.get(S.name),C=Ta({agent:k,task:S.task,symbols:a,dependsOn:S.dependsOn,profileEnrichment:x?.enrichment,nickname:x?.nickname,captainBrief:u});w.push(C);}g.push({stage:h.stage,canRunParallel:h.canRunParallel,agents:w});}let m=`orch-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`;ip(e.rootDir,m,s,d);try{let{appendSessionWorkEntry:h}=await import('./session-work-log-MEJ33TYD.js');for(let w of g)for(let S of w.agents)h(e.rootDir,{timestamp:new Date().toISOString(),type:"agent-contribution",agent:S.agent,contribution:S.taskDescription?.slice(0,200)||s.slice(0,200),attribution:S.attribution,symbols:a});}catch{}try{let{recordAgentSession:h}=await import('./agent-state-KSQ3S7OB.js'),S=(await import('./session-tracker-HHNY6J4I.js')).default?.session?.sessionId||m;for(let v of g)for(let k of v.agents)h(k.agent,e.rootDir,{sessionId:S,summary:`${k.attribution||k.agent}: ${(k.taskDescription||s).slice(0,200)}`,symbolsTouched:a});}catch{}let y=`thr-orch-${m}`;try{let h=await import('./symphony-loader-VA4UREOM.js'),w=H.basename(e.rootDir),S=`${w}/maestro`;try{h.getMyIdentity(e.rootDir)||h.registerAgent(e.rootDir,"maestro","Maestro (orchestrator)");}catch{}h.createThread(`Orchestration: ${s.slice(0,80)}`,{id:S,name:"Maestro",type:"agent",project:w,role:"orchestrator"});let v=H.join(wa.homedir(),".paradigm","score","threads"),k=E.readdirSync(v).filter(C=>C.endsWith(".json")).sort(),x=k[k.length-1];if(x){let C=H.join(v,x),_=H.join(v,`${y}.json`),P=JSON.parse(E.readFileSync(C,"utf8"));P.id=y,E.writeFileSync(_,JSON.stringify(P,null,2),"utf8"),C!==_&&E.unlinkSync(C);}for(let C of g)for(let _ of C.agents){let P=h.buildMessage({threadRoot:y,sender:{id:S,name:"Maestro",type:"agent",project:w,role:"orchestrator"},intent:"task",text:`[Maestro] Stage ${C.stage}: Assigned to ${_.attribution||_.agent} \u2014 ${_.taskDescription||s}`,symbols:a,metadata:{task:{stage:C.stage,canRunParallel:C.canRunParallel}}});h.routeMessage(P);}}catch{}let f={orchestrationId:m,task:s,mode:"execute",symbols:a,totalAgents:d.estimatedAgents,...c.length>0?{activeNominations:c}:{},stages:g,executionInstructions:["Execute stages in order (stage 0, then stage 1, etc.)","Agents within a stage can be run in parallel if your environment supports it","Pass handoff context between stages",'Present each agent response as an attributed message using the attribution prefix (e.g., "[architect] Rate limiter should go before ^authenticated")',"Do NOT synthesize agent responses \u2014 show them as distinct contributions from each agent","After all agents in a stage complete, reconcile their outputs before proceeding to the next stage"],finalStep:{mandatory:true,description:"FINAL STEPS (mandatory, in order):",steps:[{order:1,action:"Call paradigm_captain_debrief",args:{orchestrationId:`${m} (use the orchestrationId from this response)`,sessionSummary:"(summarize what was accomplished)",touchedFiles:"(list all files modified during this session)",newSymbols:"(optional: list any new symbols registered)"}},{order:2,action:"Take the sessionInsights from the debrief result and call paradigm_ambient_learn_postflight",args:{sessionId:`${m} (use the orchestrationId from this response)`,context:"(pass the sessionInsights object from the debrief result here)"},note:"This is Loid's learning pass \u2014 she processes what the crew learned and ensures it compounds."},{order:3,action:"Session is complete."}],note:"Step 1 closes the session, updates .purpose coverage, records lore, and clears the stop hook. Step 2 runs Loid's learning pass on the session insights. Both steps are required \u2014 the session is NOT complete until both run."},claudeCode:{method:"Task tool",example:{description:g[0]?.agents[0]?.taskDescription||"Agent task",prompt:"(see agent prompts above)",subagent_type:"general-purpose"},parallel:"Launch multiple Task calls in one message for parallel stages"},sequential:{method:"Execute each role in sequence within this session",steps:d.stages.map((h,w)=>({stage:w,rolePrompt:`Adopt the ${h.agents[0]?.name} role. Focus ONLY on: ${h.agents.map(S=>S.task).join(", ")}`,constraint:w===0?"Design/plan only \u2014 do NOT write implementation code":w===d.stages.length-1?"Verify and test \u2014 do NOT change implementation":"Implement following the design from the previous stage"}))},cli:{method:"paradigm team orchestrate",command:`paradigm team orchestrate "${s}"`,note:"Spawns independent agent processes \u2014 works from any terminal"},symphony:{enabled:true,orchestrationThread:y,instructions:["After each agent completes, call paradigm_symphony_send to report progress. This makes the work visible in Conductor.",'Use intent "context" for analysis, "proposal" for recommendations, "decision" for decisions made',`Set threadRoot to "${y}" so all contributions are in one thread`,"Include the symbols array from the agent relay output"],perAgentInstruction:`When each agent finishes, run: paradigm_symphony_send threadId="${y}" intent="task-complete" text="[agentName] Summary of completed work" symbols=[touched symbols]`,exampleCall:{intent:"context",text:"[architect] Rate limiter should be placed before ^authenticated gate to prevent unauthenticated flood",threadRoot:y,symbols:["#rate-limiter","^authenticated"]}}},b=JSON.stringify(f,null,2);return o(b.length,"paradigm_orchestrate_inline"),{handled:true,text:b}}async function Ud(t,e,s,n,i,r){let o$1=t.toLowerCase(),a;try{let b=await Ot("paradigm_captain_brief",{taskDescription:t,symbols:e,depth:"quick"},r);if(b.handled){let h=JSON.parse(b.text);a={coverage:`${h.coverage?.label||"unknown"} (${Math.round((h.coverage?.score||0)*100)}%)`,warnings:h.warnings||[]};}}catch{}let c=[];s.securityRequired&&c.push("security-adjacent task (auth, gates, permissions detected)"),s.complexity==="high"&&c.push(`high complexity task (type: ${s.type})`),e.length>=4&&c.push(`${e.length} symbols in scope \u2014 cross-cutting change`);let l=n.filter(b=>b.urgency==="critical");l.length>0&&c.push(`${l.length} critical agent nomination(s) pending`);let d={assumptions:[],risks:[],edgeCases:[],questions:[]};(o$1.includes("simple")||o$1.includes("just")||o$1.includes("only"))&&d.assumptions.push("Task framed as simple \u2014 verify no hidden complexity"),(o$1.includes("always")||o$1.includes("never"))&&d.assumptions.push("Absolute language detected \u2014 edge cases likely exist"),!o$1.includes("error")&&!o$1.includes("fail")&&!o$1.includes("invalid")&&d.assumptions.push("No error/failure handling mentioned \u2014 what happens when it fails?"),e.some(b=>b.startsWith("$"))&&d.risks.push("Flow symbols detected \u2014 multi-step changes have ordering/rollback risk"),e.some(b=>b.startsWith("^"))&&(d.risks.push("Gate symbols detected \u2014 authorization changes require security review"),c.some(b=>b.includes("security"))||c.push("gate symbols in scope \u2014 security review recommended")),s.matchedKeywords.some(b=>["migration","database","schema"].includes(b))&&d.risks.push("Data migration risk \u2014 irreversible changes need rollback plan"),s.matchedKeywords.some(b=>["delete","remove","drop"].includes(b))&&d.risks.push("Destructive operation \u2014 verify nothing depends on removed items"),(o$1.includes("add")||o$1.includes("new"))&&d.edgeCases.push("New feature \u2014 how does it interact with existing features?"),(o$1.includes("refactor")||o$1.includes("rename"))&&d.edgeCases.push("Refactor \u2014 all callers updated? Integration tests cover the change?"),(o$1.includes("fix")||o$1.includes("bug"))&&d.edgeCases.push("Bug fix \u2014 does the fix address the root cause or just the symptom?"),o$1.includes("test")||d.questions.push("How will this be tested?"),e.length===0&&d.questions.push("No symbols referenced \u2014 which components are actually affected?");let p={concerns:[],suggestions:[]};for(let b of e){let h=b.replace(/^[#$^!~@&%?]/,"");!i.agents[h]&&b.startsWith("#");}s.costMultiplier.max>1&&p.concerns.push(`Higher-than-average complexity (${s.costMultiplier.min}x-${s.costMultiplier.max}x baseline) \u2014 consider breaking into smaller tasks`);let u=[];try{let{loadNotebookEntries:b}=await import('./notebook-loader-3J2OFMS3.js'),h=e.map(S=>S.replace(/^[#$^!~@&%?]/,"").toLowerCase()),w=b("advocate",r.rootDir,h.length>0?{concepts:h}:void 0);w.length>0&&(u=w.sort((S,v)=>v.confidence-S.confidence).slice(0,3).map(S=>S.snippet));}catch{}let m=c.length>=2||c.some(b=>b.includes("security")||b.includes("critical"))?"escalate":"greenlight",y={mode:"quick",task:t,verdict:m,classification:{type:s.type,complexity:s.complexity,securityRequired:s.securityRequired},advocate:{agent:"Jinx (advocate)",...d.assumptions.length>0?{assumptions:d.assumptions}:{},...d.risks.length>0?{risks:d.risks}:{},...d.edgeCases.length>0?{edgeCases:d.edgeCases}:{},...d.questions.length>0?{questions:d.questions}:{},...u.length>0?{notebookInsights:u}:{}},reviewer:{agent:"reviewer",...p.concerns.length>0?{concerns:p.concerns}:{},...p.suggestions.length>0?{suggestions:p.suggestions}:{}},...c.length>0?{escalationSignals:c}:{},...n.length>0?{activeNominations:n}:{},...a?{captainBrief:a}:{},symbols:e,instructions:m==="greenlight"?["Quick check passed \u2014 proceed with implementation.","Orchestration enforcement is satisfied.",d.questions.length>0?`Address Jinx's questions during implementation: ${d.questions.join("; ")}`:"No open questions from advocate."]:["Quick check recommends full orchestration.",`Escalation reasons: ${c.join("; ")}`,'Call paradigm_orchestrate_inline mode="plan" for full agent planning.',"Orchestration enforcement is satisfied regardless of verdict."]},f=JSON.stringify(y,null,2);return o(f.length,"paradigm_orchestrate_inline"),{handled:true,text:f}}async function Bd(t,e){let s=t.agent,n=t.task,i=t.handoffContext,r=t.previousAgent,o$1=Da(e.rootDir),a=b$8(e.rootDir);if(a&&!a.includes(s)){let f=JSON.stringify({warning:`Agent "${s}" is not on this project's roster`,suggestion:`Run paradigm_agent_activate id="${s}" to add it, or check .paradigm/roster.yaml`,activeRoster:a},null,2);return o(f.length,"paradigm_agent_prompt"),{handled:true,text:f}}let c=o$1?.agents[s],l={name:c?.name||s,role:c?.role||$t[s]||$t.builder,focus:c?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:Ra(s,e.rootDir,c),triggers:c?.triggers,handoff_to:c?.handoff_to,context:c?.context,protocol:c?.protocol},d=Nt(n),p,u;try{let{loadAgentProfile:f,buildProfileEnrichment:b}=await import('./agent-loader-W3RQJVW7.js'),{loadDecisions:h}=await import('./decision-loader-HELL2AMX.js'),{loadJournalEntries:w}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:S}=await import('./nomination-engine-NCLTGMAK.js'),{loadNotebookEntries:v}=await import('./notebook-loader-3J2OFMS3.js'),k=f(e.rootDir,s);if(k){u=k.nickname;let x=h(e.rootDir,{status:"active",limit:5}).map(R=>({title:R.title,decision:R.decision.slice(0,150)})),C=w(s,{transferable:!0,limit:5}).map(R=>({trigger:R.trigger,insight:R.insight.slice(0,150)})),_=S(e.rootDir,{pending_only:!0,limit:10}).map(R=>({urgency:R.urgency,brief:R.brief})),P;try{let R=d.map(j=>j.replace(/^[#$^!~@&%?]/,"").toLowerCase()),T=v(s,e.rootDir,R.length>0?{concepts:R}:void 0);if(T.length>0){let j=T.sort((A,O)=>O.confidence-A.confidence||new Date(O.updated).getTime()-new Date(A.updated).getTime()).slice(0,5);P=j.map(A=>({context:A.context,snippet:A.snippet,concepts:A.concepts}));try{let{recordNotebookReference:A}=await import('./session-work-log-MEJ33TYD.js');A(e.rootDir,s,j.map(O=>O.id));}catch{}}}catch{}let $=b(k,d,P,{recentDecisions:x,journalInsights:C,pendingNominations:_});if(k.permissions){let R=[`
526
- ## Permission Constraints`];k.permissions.paths?.deny?.length&&R.push(`**Denied paths:** ${k.permissions.paths.deny.join(", ")}`),k.permissions.paths?.write?.length&&R.push(`**Writable paths:** ${k.permissions.paths.write.join(", ")}`),k.permissions.tools?.deny?.length&&R.push(`**Denied tools:** ${k.permissions.tools.deny.join(", ")}`),k.permissions.dangerous_actions?.length&&R.push(`**Requires approval for:** ${k.permissions.dangerous_actions.join(", ")}`),$+=`
527
- `+R.join(`
528
- `);}$.trim()&&(p=$);}}catch{}let g=Ta({agent:l,task:n,symbols:d,handoffContext:i,previousAgent:r,profileEnrichment:p,nickname:u}),m={agent:s,model:g.model,prompt:g.prompt,attribution:g.attribution,taskToolParams:{description:g.taskDescription,prompt:g.prompt,subagent_type:g.subagentType,model:g.model},focusAreas:g.focusAreas,usage:"Use the Task tool with the taskToolParams to spawn this agent. Present the response with the attribution prefix."},y=JSON.stringify(m,null,2);return o(y.length,"paradigm_agent_prompt"),{handled:true,text:y}}function Aa(t,e){let s=new Set(t),n=[];for(let i of t){let r=e[i];if(r?.handoff_to)for(let o of r.handoff_to)s.has(o)&&n.push({from:i,to:o});}return n}function zd(t,e){let s=Aa(t,e);if(s.length===0)return null;let n=new Set,i=new Set(s.map(u=>`${u.from}->${u.to}`));for(let u of s)if(i.has(`${u.to}->${u.from}`)){let g=[u.from,u.to].sort().join(",");n.add(g);}let r=new Map;for(let u of n){let[g,m]=u.split(","),y=r.get(g)||g,f=r.get(m)||m,b=y<f?y:f;for(let[h,w]of r)(w===y||w===f)&&r.set(h,b);r.set(g,b),r.set(m,b);}for(let u of t)r.has(u)||r.set(u,u);let o=[...new Set(r.values())],a=new Map,c=new Map;for(let u of o)a.set(u,0),c.set(u,new Set);for(let u of s){let g=r.get(u.from),m=r.get(u.to);g!==m&&(c.get(g).has(m)||(c.get(g).add(m),a.set(m,(a.get(m)||0)+1)));}let l=new Map,d=[];for(let u of o)(a.get(u)||0)===0&&(d.push(u),l.set(u,0));for(;d.length>0;){let u=d.shift(),g=l.get(u)||0;for(let m of c.get(u)||[]){let y=(a.get(m)||1)-1;a.set(m,y);let f=g+1;l.set(m,Math.max(l.get(m)||0,f)),y===0&&d.push(m);}}if(l.size<o.length)return null;let p=new Map;for(let u of t){let g=r.get(u);p.set(u,l.get(g)||0);}return p}function Yd(t,e,s,n,i,r){let o=Nt(t),a=t.toLowerCase(),c=[],l=[];if(s&&s.length>0)for(let v=0;v<s.length;v++){let k=s[v];e[k]&&l.push({name:k,task:`${k==="architect"?"Design":k==="builder"?"Implement":k==="tester"?"Test":"Process"}: ${t}`,dependsOn:v>0?[s[v-1]]:[],required:true,stage:v});}else {let v=a.includes("design")||a.includes("architect")||a.includes("plan")||a.includes("spec"),k=a.includes("auth")||a.includes("security")||a.includes("gate")||o.some(R=>R.startsWith("^")),x=a.includes("build")||a.includes("implement")||a.includes("create")||a.includes("add")||a.includes("fix"),C=a.includes("review")||a.includes("check"),_=a.includes("test")||a.includes("verify")||a.includes("validate");if(v&&e.architect&&l.push({name:"architect",task:`Design and specify: ${t}`,dependsOn:[],required:true,stage:0}),k&&e.security&&l.push({name:"security",task:`Review security aspects of: ${t}`,dependsOn:[],required:false,stage:0}),x&&e.builder){let R=v&&e.architect?["architect"]:[];l.push({name:"builder",task:`Implement: ${t}`,dependsOn:R,required:true,stage:R.length>0?1:0});}let P=l.some(R=>R.name==="builder"),$=P?2:v?1:0;if(C&&e.reviewer&&l.push({name:"reviewer",task:`Review: ${t}`,dependsOn:P?["builder"]:[],required:false,stage:$}),_&&e.tester&&l.push({name:"tester",task:`Test and validate: ${t}`,dependsOn:P?["builder"]:[],required:false,stage:$}),l.length===0){let R=n?.recommendedAgents||["architect","builder","tester"],T={architect:"Design",security:"Review security of",builder:"Implement",tester:"Test",reviewer:"Review"},j=0,A=null;for(let O of R){if(!e[O])continue;let I=A?[A]:[],N=T[O]||"Process",q=O==="architect"||O==="builder";l.push({name:O,task:`${N}: ${t}`,required:q,stage:j,dependsOn:I}),A=O,j++;}}}let d=l.map(v=>v.name),p=zd(d,e);if(p)for(let v of l){v.stage=p.get(v.name)||0;let k=[];for(let x of d){if(x===v.name)continue;e[x]?.handoff_to?.includes(v.name)&&(p.get(x)||0)<v.stage&&k.push(x);}k.length>0&&(v.dependsOn=k);}let u=new Map;for(let v of l){let k=u.get(v.stage)||[];k.push(v),u.set(v.stage,k);}let g=Array.from(u.keys()).sort((v,k)=>v-k);for(let v of g){let k=u.get(v)||[];c.push({stage:v,agents:k.map(x=>({name:x.name,task:x.task,dependsOn:x.dependsOn,required:x.required})),canRunParallel:k.length>1});}let m=l.some(v=>v.name==="builder"||v.name==="tester"),f=n?.type==="analysis"||!m,b=false;if(!f){let v=g.length>0?g[g.length-1]+1:0;c.push({stage:v,agents:[{name:"documentor",task:"Review all changes made by previous agents. Update .purpose files, portal.yaml, and symbol registrations using only paradigm_purpose_* and paradigm_portal_* MCP tools. Run paradigm_reindex when done. Do NOT modify source code.",dependsOn:l.map(k=>k.name),required:true}],canRunParallel:false}),b=true;}let h=0,w=0;for(let v of l){let k=Gd[v.name]||{min:5e3,max:2e4};h+=k.min,w+=k.max;}b&&(h+=2e3,w+=8e3);let S=i?.default_mode||"faceted";return {task:t,mode:S,stages:c,symbols:o,estimatedAgents:l.length+(b?1:0),estimatedTokens:{min:h,max:w}}}function Ta(t){let{agent:e,task:s,symbols:n,handoffContext:i,previousAgent:r}=t,o=[];t.profileEnrichment&&(o.push(t.profileEnrichment),o.push("---"),o.push("")),t.captainBrief&&(o.push(t.captainBrief),o.push(""));let a=$t[e.name]||e.role||$t.builder;if(o.push(a),o.push(""),o.push("---"),o.push(""),o.push("## Your Task"),o.push(""),o.push(s),o.push(""),n.length>0){o.push("## Symbols in Scope"),o.push("");for(let p of n){let u=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
529
-
530
- When you complete your task, end with a structured summary block:
531
-
532
- \`\`\`yaml
533
- # Agent Relay
534
- status: success | partial | failed | blocked
535
- summary: |
536
- Brief summary of what was accomplished
537
- artifacts:
538
- - path/to/file1.ts # created or modified
539
- decisions:
540
- - Key decision 1
541
- handoff_to: builder | reviewer | tester | architect | security # optional
542
- handoff_context: |
543
- Context the next agent needs to know
544
- \`\`\`
545
-
546
- This structured output helps track progress and pass context between agents.`);let c=o.join(`
547
- `),l=e.defaultModel||Fn[It[e.name]||"tier-2"]||"sonnet",d=t.nickname?`[${t.nickname} (${e.name})]`:`[${e.name}]`;return {agent:e.name,model:l,prompt:c,taskDescription:`${e.name}: ${s.slice(0,50)}${s.length>50?"...":""}`,subagentType:"general-purpose",attribution:d,focusAreas:e.focus||{reads:["**/*"],writes:["**/*"]}}}function Nt(t){let e=t.match(Wd)||[];return [...new Set(e)]}function Vd(t){let e=t.charAt(0);return {"@":"feature","#":"component",$:"flow","%":"state","^":"gate","!":"signal","?":"idea","&":"integration","~":"deprecated"}[e]||"unknown"}var Kd=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","pros and cons"],Qd=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs"],Xd=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","regression","patch"],Zd=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify"],ep=["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 tp(t){let e=t.toLowerCase(),s=Nt(t),n=f=>f.filter(b=>e.includes(b.toLowerCase())),i=n(Kd),r=n(Qd),o=n(Xd),a=n(Zd),c=n(ep),l,d;i.length>0&&o.length===0&&a.length===0?(l="analysis",d=i):r.length>0&&o.length===0?(l="documentation",d=r):o.length>0?(l="bugfix",d=o):a.length>0?(l="refactor",d=a):(l="feature",d=[]);let p="medium",u=t.split(/\s+/).length;s.length>=5||u>=100?p="high":s.length<=1&&u<30&&(p="low");let g=c.length>0||s.some(f=>f.startsWith("^")),m={analysis:["architect"],documentation:["architect"],bugfix:["security","builder"],refactor:["architect","builder"],feature:["architect","security","builder","tester"]},y={analysis:{min:.3,max:.5},documentation:{min:.25,max:.45},bugfix:{min:.5,max:.8},refactor:{min:.6,max:.85},feature:{min:.8,max:1.2}};return {type:l,complexity:p,recommendedAgents:m[l]||["architect","builder"],securityRequired:g,costMultiplier:y[l]||{min:.8,max:1},matchedKeywords:d,symbols:s}}var _a={opus:{input:15,output:75},sonnet:{input:3,output:15},haiku:{input:.25,output:1.25}},xa={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 np(t,e){let s=[],n=0,i=e.complexity==="high"?1.5:e.complexity==="low"?.6:1;for(let a of t.stages)for(let c of a.agents){let l=xa[c.name]||{input:5e3,output:3e3},d=Fn[It[c.name]||"tier-2"]||"sonnet",p=_a[d],u=Math.round(l.input*i),g=Math.round(l.output*i),m=u+g,y=u/1e6*p.input+g/1e6*p.output;s.push({name:c.name,model:d,estimatedTokens:m,estimatedCost:Math.round(y*1e4)/1e4}),n+=y;}let r=0;for(let[a,c]of Object.entries(xa)){let l=Fn[It[a]||"tier-2"]||"sonnet",d=_a[l];r+=c.input/1e6*d.input+c.output/1e6*d.output;}let o=r>0?n/r:1;return {agents:s,totalEstimatedCost:Math.round(n*1e4)/1e4,comparisonToBaseline:`${o.toFixed(2)}x`}}function sp(t,e){let s=[],n=t.toLowerCase(),i=Nt(t);for(let[c,l]of Object.entries(e)){let d=[];for(let p of l.triggers||[]){if(p.type==="keyword"&&p.match)for(let u of p.match)n.includes(u.toLowerCase())&&d.push(`keyword:${u}`);if(p.type==="symbol"&&p.match)for(let u of p.match){let g=i.filter(m=>u.endsWith("*")?m.startsWith(u.slice(0,-1)):m===u);for(let m of g)d.push(`symbol:${m}`);}}if(d.length>0){let p=d.filter(b=>b.startsWith("keyword:")).length,u=d.filter(b=>b.startsWith("symbol:")).length,g=p>0&&u>0,m=d.length>=3||g?"high":d.length>=2?"medium":"low",y=l.role.split(`
548
- `)[0].trim(),f=y.length>50?y.slice(0,47)+"...":y;s.push({name:c,reason:f,confidence:m,triggers_matched:d});}}let r=new Set(s.map(c=>c.name)),o=[];for(let c of s){let l=e[c.name];if(l?.handoff_to)for(let d of l.handoff_to){if(r.has(d)||!e[d])continue;let p=e[d],u=[];for(let g of p.triggers||[]){if(g.type==="keyword"&&g.match)for(let m of g.match)n.includes(m.toLowerCase())&&u.push(`keyword:${m}`);if(g.type==="symbol"&&g.match)for(let m of g.match){let y=i.filter(f=>m.endsWith("*")?f.startsWith(m.slice(0,-1)):f===m);for(let f of y)u.push(`symbol:${f}`);}}if(u.length>0){r.add(d);let g=p.role.split(`
549
- `)[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 Da(t){let e=H.join(t,".paradigm","agents.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf-8");return Te.load(s)}catch{return null}}function ip(t,e,s,n){let i=H.join(t,".paradigm","orchestrations");E.existsSync(i)||E.mkdirSync(i,{recursive:true});let r=H.join(i,`${e}.yaml`),o={id:e,task:s,created:new Date().toISOString(),status:"pending",mode:n.mode,symbols:n.symbols,estimatedAgents:n.estimatedAgents,estimatedTokens:n.estimatedTokens,stages:n.stages};try{E.writeFileSync(r,Te.dump(o));}catch{}}function Oa(t){let e=H.join(t,".paradigm","tags.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf-8");return Te.load(s)}catch{return null}}function rp(t,e){let s=H.join(t,".paradigm","tags.yaml"),n=Te.dump(e,{lineWidth:-1});E.writeFileSync(s,n,"utf-8");}function Ia(){return [{name:"paradigm_tags",description:"List, search, and manage tags in the Tag Bank. Use to find available tags for classification. Returns tags organized by section (core, project, suggested) with usage counts. ~150 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","search","get"],description:"Action: list all tags, search by query, or get specific tag details"},query:{type:"string",description:"For search action: query string to match tag names and descriptions"},tag:{type:"string",description:"For get action: specific tag name to get details for"},category:{type:"string",enum:["core","project","suggested","all"],description:"Filter by tag category (default: all)"}},required:["action"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_tags_suggest",description:"AI proposes a new tag for human review. Tag will be added to the suggested section for approval. Returns confirmation of suggestion with section placement. ~100 tokens.",inputSchema:{type:"object",properties:{tag:{type:"string",description:'Tag name (kebab-case, e.g., "webhook-handler")'},description:{type:"string",description:"What this tag means and when to apply it"},reason:{type:"string",description:'Why this tag would be useful (e.g., "Found 5 components handling webhooks")'},appliesTo:{type:"array",items:{type:"string"},description:'Symbol types this tag applies to (e.g., ["#", "$"])'},exampleSymbols:{type:"array",items:{type:"string"},description:"Example symbols that would use this tag"}},required:["tag","description","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_aspect_check",description:"Verify an aspect has valid anchors and check coverage. Aspects (~) REQUIRE code anchors. Returns anchor validity, coverage stats, and missing anchor warnings. ~150 tokens.",inputSchema:{type:"object",properties:{aspect:{type:"string",description:'Aspect symbol to check (e.g., "~audit-required")'}},required:["aspect"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["cross-cutting","aspect enforcement","policy check","verify aspect"]}]}async function $a(t,e,s){switch(t){case "paradigm_tags":{let{action:n,query:i,tag:r,category:o="all"}=e,a=Oa(s.rootDir);if(!a)return {handled:true,text:JSON.stringify({error:"Tag bank not found",suggestion:"Create .paradigm/tags.yaml or run `paradigm init` to set up tags"})};if(n==="list"){let c={};return (o==="all"||o==="core")&&(c.core=Object.entries(a.core).map(([l,d])=>({tag:l,description:d.description?.split(`
550
- `)[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(`
551
- `)[0].trim(),color:d.color,appliesTo:d["applies-to"]}))),(o==="all"||o==="suggested")&&(c.suggested=(a.suggested||[]).map(l=>({tag:l.tag,reason:l.reason,proposedBy:l["proposed-by"],proposedAt:l["proposed-at"]}))),c.summary={coreCount:Object.keys(a.core||{}).length,projectCount:Object.keys(a.project||{}).length,suggestedCount:(a.suggested||[]).length},{handled:true,text:JSON.stringify(c,null,2)}}if(n==="search"){if(!i)return {handled:true,text:JSON.stringify({error:"Query required for search action"})};let c=i.toLowerCase(),l=[];for(let[d,p]of Object.entries(a.core||{}))(d.toLowerCase().includes(c)||p.description?.toLowerCase().includes(c)||p.aliases?.some(u=>u.toLowerCase().includes(c)))&&l.push({tag:d,category:"core",description:p.description?.split(`
552
- `)[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(`
553
- `)[0].trim()||""});return {handled:true,text:JSON.stringify({query:i,count:l.length,matches:l},null,2)}}if(n==="get"){if(!r)return {handled:true,text:JSON.stringify({error:"Tag name required for get action"})};if(a.core?.[r]){let l=a.core[r];return {handled:true,text:JSON.stringify({tag:r,category:"core",description:l.description,color:l.color,appliesTo:l["applies-to"],aliases:l.aliases,requiresAspect:l["requires-aspect"]},null,2)}}if(a.project?.[r]){let l=a.project[r];return {handled:true,text:JSON.stringify({tag:r,category:"project",description:l.description,color:l.color,appliesTo:l["applies-to"],aliases:l.aliases,requiresAspect:l["requires-aspect"]},null,2)}}let c=a.suggested?.find(l=>l.tag===r);return c?{handled:true,text:JSON.stringify({tag:r,category:"suggested",reason:c.reason,proposedBy:c["proposed-by"],proposedAt:c["proposed-at"],appliesTo:c["applies-to"],exampleSymbols:c["example-symbols"],status:"pending approval"},null,2)}:{handled:true,text:JSON.stringify({error:`Tag "${r}" not found`,suggestion:'Use paradigm_tags with action "list" to see available tags'})}}return {handled:true,text:JSON.stringify({error:`Unknown action: ${n}`})}}case "paradigm_tags_suggest":{let{tag:n,description:i,reason:r,appliesTo:o,exampleSymbols:a}=e,c=Oa(s.rootDir);if(!c)return {handled:true,text:JSON.stringify({error:"Tag bank not found",suggestion:"Create .paradigm/tags.yaml first"})};if(c.core?.[n]||c.project?.[n])return {handled:true,text:JSON.stringify({error:`Tag "${n}" already exists`,existing:c.core?.[n]?"core":"project"})};if(c.suggested?.some(d=>d.tag===n))return {handled:true,text:JSON.stringify({error:`Tag "${n}" is already in the suggested queue`,status:"pending approval"})};let l={tag:n,"proposed-by":"claude","proposed-at":new Date().toISOString(),reason:r,"applies-to":o||["#"],"example-symbols":a};return c.suggested||(c.suggested=[]),c.suggested.push(l),rp(s.rootDir,c),{handled:true,text:JSON.stringify({success:true,tag:n,status:"pending approval",message:"Tag suggestion added. Human review required before use.",nextSteps:["Human can approve via Sentinel UI or CLI",'Once approved, tag moves to "project" section',"Then AI can use the tag for classification"]},null,2)}}case "paradigm_aspect_check":{let{aspect:n}=e,i=n.startsWith("~")?n:`~${n}`,r=h$1(s.index,i);if(!r)return {handled:true,text:JSON.stringify({error:`Aspect "${i}" not found`,suggestion:"Use paradigm_search to find available aspects"})};if(r.type!=="aspect")return {handled:true,text:JSON.stringify({error:`Symbol "${i}" is not an aspect (type: ${r.type})`,note:"Only ~ symbols are aspects"})};let o=r.anchors||[],a=r.filePath?H.isAbsolute(r.filePath)?r.filePath:H.resolve(s.rootDir,r.filePath):s.rootDir,c=r.filePath?H.dirname(a):s.rootDir,l=[];for(let f of o){let b=fa$1(f.path,c,s.rootDir),h=b.resolvedPath,w=b.exists,S;if(w)try{let x=E.readFileSync(h,"utf-8").split(`
554
- `);typeof f.lines=="number"?S=1:Array.isArray(f.lines)&&f.lines.length===2?S=f.lines[1]-f.lines[0]+1:Array.isArray(f.lines)&&(S=f.lines.length);}catch{}let v;w||ga(f.path,c,s.rootDir).mismatch&&(v="Anchor resolves under .purpose-dir base but not project-root base (or vice versa). This indicates a framework path-resolution bug; do NOT hand-edit. Run `paradigm_aspect_drift` for full audit, or file framework-bug task per protocol."),l.push({path:f.path,lines:f.raw.split(":")[1]||"full file",exists:w,lineCount:S,...v?{resolution_hint:v}:{}});}let d=o.length>0&&l.every(f=>f.exists),p=r.appliesTo||[],u=n$1(s.index),g=[],m=[];for(let f of u)for(let b of p)if(new RegExp("^"+b.replace(/\*/g,".*").replace(/\?/g,".")+"$").test(f.symbol)){g.push(f.symbol),(f.data?.aspects?.includes?.(i)||f.data?.aspects?.includes?.(n))&&m.push(f.symbol);break}let y=g.filter(f=>!m.includes(f));return {handled:true,text:JSON.stringify({aspect:i,valid:d,description:r.description,enforcement:r.enforcement,anchors:l,coverage:{appliesTo:p,matchingSymbols:g.length,symbolsWithAspect:m.length,missing:y.slice(0,10),missingCount:y.length},warnings:[...o.length===0?["CRITICAL: Aspect has no anchors - aspects MUST have code anchors"]:[],...l.filter(f=>!f.exists).map(f=>`Anchor file not found: ${f.path}`),...y.length>0?[`${y.length} symbols match applies-to but don't have this aspect`]:[]],recommendation:d?y.length>0?"Aspect is valid but has coverage gaps - consider applying to matching symbols":"Aspect is valid and fully applied":"INVALID: Add code anchors to this aspect"},null,2)}}default:return {handled:false,text:""}}}b$1();var be=class extends Error{code="WRITE_VERIFICATION_FAILED";constructor(e="write verification failed"){super(e),this.name="WriteVerificationError";}},op=".paradigm-install-key",ap="paradigm-v5.38.0-hmac-fallback-key",Ie=null;function cp(){if(Ie)return Ie;try{let t=wa.homedir(),e=H.join(t,op);if(E.existsSync(e)){let n=E.readFileSync(e,"utf-8").trim();if(/^[0-9a-f]{64}$/i.test(n))return Ie=Buffer.from(n,"hex"),Ie}let s=Et.randomBytes(32);try{E.writeFileSync(e,s.toString("hex"),{encoding:"utf-8",mode:384});}catch{}return Ie=s,Ie}catch{return Ie=Buffer.from(ap),Ie}}function lp(t){let e=Et.createHmac("sha256",cp());return e.update(t),e.digest("hex").slice(0,12)}function dp(t,e){let s=H.dirname(t),n=`.${H.basename(t)}.${process.pid}.${Date.now()}.${Et.randomBytes(4).toString("hex")}.tmp`,i=H.join(s,n);try{E.writeFileSync(i,e,{encoding:"utf-8"}),E.renameSync(i,t);}catch(r){try{E.unlinkSync(i);}catch{}throw r}}async function Ht(t,e,s){dp(t,e);let n;try{n=E.readFileSync(t,"utf-8");}catch{throw a.component("#write-and-confirm").error("read-back failed after atomic write",{stage:"read-back"}),new be("write verification failed (read-back error)")}let i=false;try{i=s(n);}catch{throw a.component("#write-and-confirm").error("verify callback threw",{stage:"verify-callback",strict:H$2()}),new be("write verification failed (verify callback error)")}if(!i)throw a.component("#write-and-confirm").error("verify callback returned false",{stage:"verify-callback-false",strict:H$2()}),new be("write verification failed");let r=Buffer.byteLength(n,"utf-8"),o=lp(n);return {written:true,path:t,hashHint:o,bytes:r}}b$1();var pp=["#","$","^","!","~"];function M(t){return t.length>1&&pp.includes(t[0])?t.slice(1):t}function W(t,e){let s=M(t);return `${e}${s}`}function ue(t,e){let s=H.isAbsolute(t)?t:H.resolve(e,t);return s.endsWith(".purpose")?s:H.join(s,".purpose")}function Y(t){if(!E.existsSync(t))return {};let e=a$9(t);if(!e.data)throw new Error(`Failed to parse ${t}: ${e.errors.join(", ")}`);return e.data}function $e(t,e){let s=H.dirname(t);E.existsSync(s)||E.mkdirSync(s,{recursive:true});let n=b$b(e);E.writeFileSync(t,n,"utf8");}async function En(t,e,s,n="purpose.yaml"){let i=H.dirname(t);E.existsSync(i)||E.mkdirSync(i,{recursive:true});let r=b$b(e);try{return await Ht(t,r,o=>{let a=a$9(t);if(!a.data)return !1;try{return s(a.data)}catch{return !1}})}catch(o){throw o instanceof be?(a.component("#purpose-writer").error("purpose write verification failed",{surface:n,stage:"writeAndConfirm"}),new Error(`purpose write verification failed (${n})`)):o}}function Je(t){if(!t)return {};if(!Array.isArray(t))return t;let e={};for(let s of t){let{id:n,...i}=s;e[n]=i;}return e}function ot(t){if(!t)return {};if(!Array.isArray(t))return t;let e={};for(let s of t)e[s.name]={description:s.description,steps:s.steps};return e}function at(t,e){if(!e||e.length===0)return t;if(!t||t.length===0)return e;let s=new Set(t);for(let n of e)s.add(n);return Array.from(s)}var up={"#":"#","^":"^","!":"!",$:"$","~":"~"};async function Na(t,e,s,n){let i=up[n];if(!i)throw new Error(`Invalid symbol type: ${n}. Expected one of: # ^ ! $ ~`);let r=M(e),o=M(s),a=W(r,i),c=W(o,i),l=await c$4(t),d=[];for(let p of l){let u=Y(p),g=false,y={"#":"components","^":"gates","!":"signals",$:"flows","~":"aspects"}[i];if(y&&y!=="flows"){let f=u[y];f&&!Array.isArray(f)&&r in f&&(f[o]=f[r],delete f[r],g=true);}if(i==="#")for(let f of ["features","components"]){let b=u[f];b&&!Array.isArray(b)&&r in b&&(b[o]=b[r],delete b[r],g=true);}i==="$"&&u.flows&&!Array.isArray(u.flows)&&r in u.flows&&(u.flows[o]=u.flows[r],delete u.flows[r],g=true);for(let f of ["features","components"]){let b=Je(u[f]);for(let[h,w]of Object.entries(b))g=gp(w,a,c)||g;g&&Object.keys(b).length>0&&(u[f]=b);}if(u.flows){let f=ot(u.flows);for(let[b,h]of Object.entries(f)){if(h.gates){let w=h.gates.indexOf(a);w!==-1&&(h.gates[w]=c,g=true);}if(h.signals){let w=h.signals.indexOf(a);w!==-1&&(h.signals[w]=c,g=true);}if(h.components){let w=h.components.indexOf(a);w!==-1&&(h.components[w]=c,g=true);}if(h.steps)for(let w of h.steps)typeof w=="object"&&"component"in w&&(w.component===a||w.component===r)&&(w.component=i==="#"?o:c,g=true);}g&&(u.flows=f);}if(u.gates){for(let[f,b]of Object.entries(u.gates))if(b.signals){let h=b.signals.indexOf(a);h!==-1&&(b.signals[h]=c,g=true);}}if(u.aspects){for(let[f,b]of Object.entries(u.aspects))if(b["applies-to"]){let h=b["applies-to"].indexOf(a);h!==-1&&(b["applies-to"][h]=c,g=true);}}g&&($e(p,u),d.push(p));}return d}function gp(t,e,s){let n=false,i=["signals","gates","flows","components","states"];for(let r of i){let o=t[r];if(o){let a=o.indexOf(e);a!==-1&&(o[a]=s,n=true);}}if(t.aspects&&Array.isArray(t.aspects)){let r=t.aspects.indexOf(e);r!==-1&&(t.aspects[r]=s,n=true);}return n}b$1();function Hn(t){let e=H.join(t,"portal.yaml"),s=I$1(e);if(s.status==="missing")return {data:{version:"1.0.0",gates:{}},filePath:e};if(s.status==="unparseable"||s.status==="invalid")throw a.component("#portal-writer").error("portal.yaml unparseable on read",{errorClass:s.errorClass}),new Error(`portal.yaml unparseable (${s.errorClass}). Refusing to overwrite. Run 'paradigm doctor' for line-specific details.`);return {data:s.data||{version:"1.0.0",gates:{}},filePath:e}}async function Ha(t,e){let{data:s,filePath:n}=Hn(t);if(!s.gates||Array.isArray(s.gates)){let a=s.gates;if(s.gates={},Array.isArray(a)&&a.length>0){for(let c of a)if(c&&typeof c=="object"&&"id"in c){let l=M(c.id);s.gates[l]=c;}}}let i=M(e.id),r=s.gates[i]||{};r.description=e.description,e.type!==void 0&&(r.type=e.type),e.location!==void 0&&(r.location=e.location),e.requires!==void 0&&(r.requires=e.requires),e.check!==void 0&&(r.check=e.check),e.grants!==void 0&&(r.grants=e.grants),e.emits!==void 0&&(r.emits=e.emits),e.prizes!==void 0&&(r.prizes=e.prizes),r.prizes||(r.prizes=[]),s.gates[i]=r;let o=Te.dump(s,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});try{return await Ht(n,o,a=>{let c;try{c=Te.load(a);}catch{return !1}let l=c?.gates;return !l||Array.isArray(l)?!1:!!l[i]})}catch(a$1){throw a$1 instanceof be?(a.component("#portal-writer").error("portal_add_gate write verification failed",{stage:"writeAndConfirm"}),new Error("portal_add_gate write verification failed")):a$1}}async function qa(t,e){let{data:s,filePath:n}=Hn(t);(!s.routes||Array.isArray(s.routes))&&(s.routes={});let i=`${e.method} ${e.route}`,r=e.gates.map(a=>`^${M(a)}`);s.routes[i]=r;let o=Te.dump(s,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});try{return await Ht(n,o,a=>{let c;try{c=Te.load(a);}catch{return !1}let l=c?.routes;return !l||Array.isArray(l)?!1:!!l[i]})}catch(a$1){throw a$1 instanceof be?(a.component("#portal-writer").error("portal_add_route write verification failed",{stage:"writeAndConfirm"}),new Error("portal_add_route write verification failed")):a$1}}var mp={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}},fp={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}},yp={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}},hp={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}},bp={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}},wp={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}},vp={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}},kp={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}},Sp={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}},_p={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}},xp={name:"paradigm_portal_add_gate",description:"Add or update a gate (^) in portal.yaml. Creates portal.yaml if it doesn't exist. Strips ^ prefix. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Gate ID (e.g. "authenticated" or "^authenticated")'},description:{type:"string",description:"What this gate checks"},type:{type:"string",description:'Gate type (e.g. "auth", "role", "ownership")'},location:{type:"string",description:'Where the gate is checked in your code (e.g. "middleware", "route-handler")'},requires:{type:"array",items:{type:"string"},description:"Prerequisite gates"},check:{type:"string",description:'Expression to evaluate (e.g. "req.user != null")'},grants:{type:"array",items:{type:"string"},description:"What passing this gate grants access to"},emits:{type:"array",items:{type:"string"},description:"Signals emitted when gate is checked"},prizes:{type:"array",items:{type:"object",properties:{id:{type:"string"},oneTime:{type:"boolean"}},required:["id"]},description:"Side effects triggered on pass"}},required:["id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},Cp={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}},Rp={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 Ma(){return [mp,fp,yp,hp,bp,wp,vp,kp,Sp,_p,xp,Cp,Rp]}async function Wa(t,e,s,n){switch(t){case "paradigm_purpose_init":return Pp(e,s,n);case "paradigm_purpose_add_component":return jp(e,s,n);case "paradigm_purpose_add_aspect":return Ap(e,s,n);case "paradigm_purpose_add_signal":return Tp(e,s,n);case "paradigm_purpose_add_flow":return Dp(e,s,n);case "paradigm_purpose_add_gate":return Op(e,s,n);case "paradigm_purpose_add_state":return Ip(e,s,n);case "paradigm_purpose_link":return $p(e,s,n);case "paradigm_purpose_remove":return Fp(e,s,n);case "paradigm_purpose_rename":return Np(e,s,n);case "paradigm_portal_add_gate":return Ep(e,s,n);case "paradigm_portal_add_route":return Hp(e,s,n);case "paradigm_purpose_validate":return Lp(e,s);default:return {handled:false,text:""}}}function Z(t){return {handled:true,text:JSON.stringify(t,null,2)}}function X(t){return {handled:true,text:JSON.stringify({error:t},null,2)}}async function Pp(t,e,s){let{purposeFile:n,name:i,description:r,context:o,version:a}=t,c=ue(n,e.rootDir),l=Y(c);return a!==void 0?l.version=a:l.version||(l.version="1.0.0"),r!==void 0?l.description=r:l.description||(l.description=i),o!==void 0&&(l.context=o),$e(c,l),await s(),Z({action:"purpose_init",file:c,metadata:{name:i,description:l.description,version:l.version}})}async function jp(t,e,s){let{purposeFile:n,id:i,description:r,section:o="components",file:a,status:c,endpoints:l,tests:d,flows:p,gates:u,signals:g,aspects:m,components:y,type:f,parent:b}=t,h=ue(n,e.rootDir),w=Y(h),S=M(i),v=o,k=Je(w[v]),x=k[S]||{description:""};x.description=r,a!==void 0&&(x.file=a),c!==void 0&&(x.status=c),l!==void 0&&(x.endpoints=l),d!==void 0&&(x.tests=d),p!==void 0&&(x.flows=p.map(_=>W(_,"$"))),u!==void 0&&(x.gates=u.map(_=>W(_,"^"))),g!==void 0&&(x.signals=g.map(_=>W(_,"!"))),m!==void 0&&(x.aspects=m.map(_=>W(_,"~"))),y!==void 0&&(x.components=y.map(_=>W(_,"#"))),f!==void 0&&(x.type=f),b!==void 0&&(x.parent=W(b,"#")),k[S]=x,w[v]=k;let C=await En(h,w,_=>{let P=_[v];return !P||typeof P!="object"||Array.isArray(P)?!1:S in P},v);return await s(),Z({action:"add_component",file:C.path,section:v,id:S,symbol:`#${S}`,written:C.written,hashHint:C.hashHint,bytes:C.bytes})}async function Ap(t,e,s){let{purposeFile:n,id:i,description:r,anchors:o,tags:a,appliesTo:c,enforcement:l}=t;if(!o||o.length===0)return X('Aspects (~) REQUIRE at least one code anchor. Provide anchors like ["src/middleware/audit.ts:15-35"].');let d=/^[^\s:]+:\d+(-\d+)?(,\d+)*$/;for(let f of o)if(!d.test(f))return X(`Invalid anchor format: "${f}". Expected format: "file.ts:15", "file.ts:15-20", or "file.ts:15,25,30".`);let p=ue(n,e.rootDir),u=H.dirname(p);for(let f of o){let b=f.replace(/:.*$/,""),h=H.resolve(u,b);if(!E.existsSync(h)){let w=H.resolve(e.rootDir,b);if(E.existsSync(w)){let S=H.relative(u,w),v=o.indexOf(f);o[v]=f.replace(b,S);}else return X(`Anchor file not found: "${b}". Anchors must be relative to the .purpose file directory (${u}).`)}}let g=Y(p);(!g.aspects||Array.isArray(g.aspects))&&(g.aspects={});let m=M(i);g.aspects[m]={description:r,anchors:o,...a&&{tags:a},...c&&{"applies-to":c},...l&&{enforcement:l}},$e(p,g);let y=Y(p).aspects;return !y||Array.isArray(y)||!y[m]?X(`add_aspect write verification failed: aspect "${m}" not found in ${p} after write.`):(await s(),Z({action:"add_aspect",file:p,id:m,symbol:`~${m}`,anchors:o}))}async function Tp(t,e,s){let{purposeFile:n,id:i,description:r,category:o,severity:a,emitters:c,related:l,data:d}=t,p=ue(n,e.rootDir),u=Y(p);(!u.signals||Array.isArray(u.signals))&&(u.signals={});let g=M(i);u.signals[g]={description:r,...o&&{category:o},...a&&{severity:a},...c&&{emitters:c.map(y=>W(y,"#"))},...l&&{related:l},...d&&{data:d}},$e(p,u);let m=Y(p).signals;return !m||Array.isArray(m)||!m[g]?X(`add_signal write verification failed: signal "${g}" not found in ${p} after write.`):(await s(),Z({action:"add_signal",file:p,id:g,symbol:`!${g}`}))}async function Dp(t,e,s){let{purposeFile:n,id:i,description:r,gates:o,signals:a,components:c,steps:l}=t,d=ue(n,e.rootDir),p=Y(d),u=ot(p.flows),g=M(i),m={description:r,...o&&{gates:o.map(f=>W(f,"^"))},...a&&{signals:a.map(f=>W(f,"!"))},...c&&{components:c.map(f=>W(f,"#"))},...l&&{steps:l}};return u[g]=m,p.flows=u,$e(d,p),ot(Y(d).flows)[g]?(await s(),Z({action:"add_flow",file:d,id:g,symbol:`$${g}`})):X(`add_flow write verification failed: flow "${g}" not found in ${d} after write.`)}async function Op(t,e,s){let{purposeFile:n,id:i,description:r,requires:o,keys:a,signals:c}=t,l=ue(n,e.rootDir),d=Y(l);(!d.gates||Array.isArray(d.gates))&&(d.gates={});let p=M(i);d.gates[p]={description:r,...o&&{requires:o},...a&&{keys:a},...c&&{signals:c.map(g=>W(g,"!"))}},$e(l,d);let u=Y(l).gates;return !u||Array.isArray(u)||!u[p]?X(`add_gate write verification failed: gate "${p}" not found in ${l} after write.`):(await s(),Z({action:"add_gate",file:l,id:p,symbol:`^${p}`}))}async function Ip(t,e,s){let{purposeFile:n,id:i,description:r,type:o,default:a,properties:c}=t,l=ue(n,e.rootDir),d=Y(l);(!d.states||Array.isArray(d.states))&&(d.states={});let p=M(i),u={description:r};o!==void 0&&(u.type=o),a!==void 0&&(u.default=a),c!==void 0&&(u.properties=c),d.states[p]=u,$e(l,d);let g=Y(l).states;return !g||Array.isArray(g)||!g[p]?X(`add_state write verification failed: state "${p}" not found in ${l} after write.`):(await s(),Z({action:"add_state",file:l,id:p}))}async function $p(t,e,s){let{purposeFile:n,componentId:i,section:r,signals:o,aspects:a,gates:c,flows:l,components:d}=t,p=ue(n,e.rootDir),u=Y(p),g=M(i),m=r;if(!m){let w=Je(u.components),S=Je(u.features);if(g in w)m="components";else if(g in S)m="features";else return X(`Component "${g}" not found in components or features. Specify section explicitly.`)}let y=Je(u[m]);if(!(g in y))return X(`Component "${g}" not found in ${m} section.`);let f=y[g];o&&(f.signals=at(f.signals,o.map(w=>W(w,"!")))),c&&(f.gates=at(f.gates,c.map(w=>W(w,"^")))),l&&(f.flows=at(f.flows,l.map(w=>W(w,"$")))),d&&(f.components=at(f.components,d.map(w=>W(w,"#")))),a&&(f.aspects=at(f.aspects,a.map(w=>W(w,"~")))),y[g]=f,u[m]=y;let b=await En(p,u,w=>{let S=w[m];return !S||typeof S!="object"||Array.isArray(S)?!1:g in S},m);await s();let h=[];return o&&h.push(`signals: ${o.join(", ")}`),a&&h.push(`aspects: ${a.join(", ")}`),c&&h.push(`gates: ${c.join(", ")}`),l&&h.push(`flows: ${l.join(", ")}`),d&&h.push(`components: ${d.join(", ")}`),Z({action:"link",file:b.path,componentId:g,section:m,added:h,written:b.written,hashHint:b.hashHint,bytes:b.bytes})}async function Fp(t,e,s){let{purposeFile:n,section:i,id:r}=t,o=ue(n,e.rootDir),a=Y(o),c=M(r);if(i==="flows"){let d=ot(a.flows);if(!(c in d))return X(`Flow "${c}" not found in flows section.`);delete d[c],a.flows=d;}else if(i==="components"||i==="features"){let d=Je(a[i]);if(!(c in d))return X(`"${c}" not found in ${i} section.`);delete d[c],a[i]=d;}else {let d=a[i];if(!d||!(c in d))return X(`"${c}" not found in ${i} section.`);delete d[c];}let l=await En(o,a,d=>{if(i==="flows"){let u=ot(d.flows);return !(c in u)}let p=d[i];return !p||typeof p!="object"||Array.isArray(p)?!0:!(c in p)},i);return await s(),Z({action:"remove",file:l.path,section:i,id:c,written:l.written,hashHint:l.hashHint,bytes:l.bytes})}async function Np(t,e,s){let{oldId:n,newId:i,symbolType:r}=t,o=await Na(e.rootDir,n,i,r);return await s(),Z({action:"rename",oldSymbol:`${r}${M(n)}`,newSymbol:`${r}${M(i)}`,filesModified:o.length,files:o})}async function Ep(t,e,s){let{id:n,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:p}=t,u=await Ha(e.rootDir,{id:n,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:p});await s();let g=M(n);return Z({action:"portal_add_gate",file:u.path,id:g,symbol:`^${g}`,written:u.written,hashHint:u.hashHint,bytes:u.bytes})}async function Hp(t,e,s){let{route:n,method:i,gates:r}=t,o=await qa(e.rootDir,{route:n,method:i,gates:r});return await s(),Z({action:"portal_add_route",file:o.path,route:`${i} ${n}`,gates:r,written:o.written,hashHint:o.hashHint,bytes:o.bytes})}var qp=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi;function La(t,e){let s=[];function n(r,o){if(typeof r=="string"){let a=r.match(qp);if(a)for(let c of a)s.push({type:"warning",message:`Clarification needed: ${c}`,path:o});}}n(t.description,"description");let i=[{key:"components",items:t.components},{key:"features",items:t.features},{key:"gates",items:t.gates},{key:"signals",items:t.signals},{key:"aspects",items:t.aspects}];for(let r of i)if(r.items&&typeof r.items=="object")for(let[o,a]of Object.entries(r.items))a&&typeof a.description=="string"&&n(a.description,`${r.key}.${o}.description`);if(t.flows&&typeof t.flows=="object"){let r=Array.isArray(t.flows)?[]:Object.entries(t.flows);for(let[o,a]of r)a&&typeof a.description=="string"&&n(a.description,`flows.${o}.description`);}return s}async function Lp(t,e){let{purposeFile:s,includePortal:n=true}=t,i=[];if(s){let a=ue(s,e.rootDir),c=a$9(a);if(!c.data)i.push({file:a,valid:false,issues:c.errors.map(l=>({type:"error",message:l}))});else {let l=d$9(c.data,a);if(c.data.aspects)for(let[p,u]of Object.entries(c.data.aspects))(!u.anchors||u.anchors.length===0)&&(l.issues.push({type:"error",message:`Aspect "${p}" is missing required anchors`,path:`aspects.${p}`}),l.valid=false);let d=La(c.data);l.issues.push(...d),i.push({file:a,valid:l.valid,issues:l.issues});}}else {let a=await c$4(e.rootDir);for(let c of a){let l=a$9(c);if(!l.data){i.push({file:c,valid:false,issues:l.errors.map(u=>({type:"error",message:u}))});continue}let d=d$9(l.data,c);if(l.data.aspects)for(let[u,g]of Object.entries(l.data.aspects))(!g.anchors||g.anchors.length===0)&&(d.issues.push({type:"error",message:`Aspect "${u}" is missing required anchors`,path:`aspects.${u}`}),d.valid=false);let p=La(l.data);d.issues.push(...p),i.push({file:c,valid:d.valid,issues:d.issues});}}if(n){let{data:a,filePath:c}=Hn(e.rootDir),l=[];if(a.gates)for(let[d,p]of Object.entries(a.gates))p.description||l.push({type:"warning",message:`Gate "${d}" has no description`,path:`gates.${d}`}),p.prizes||l.push({type:"warning",message:`Gate "${d}" is missing prizes array (v2 requirement)`,path:`gates.${d}`});l.length>0&&i.push({file:c,valid:l.every(d=>d.type!=="error"),issues:l});}let r=i.reduce((a,c)=>a+c.issues.length,0),o=i.every(a=>a.valid);return Z({action:"validate",valid:o,totalFiles:i.length,totalIssues:r,results:i})}var ec=[{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}],Up=30*1e3,ei=new Map;function re(t){let e=H.resolve(t),s=ei.get(e);if(s&&Date.now()-s.loadedAt<Up)return s.habits;let n=Bp(e);return ei.set(e,{habits:n,loadedAt:Date.now()}),n}function Bp(t){let e=new Map;for(let a of ec)e.set(a.id,{...a});let s=process.env.HOME||process.env.USERPROFILE||"~",n=za(H.join(s,".paradigm","habits.yaml"));n&&Ya(e,n);let i=Va(H.join(s,".paradigm","habits"));for(let a of i)e.set(a.id,a);let r=za(H.join(t,".paradigm","habits.yaml"));r&&Ya(e,r);let o=Va(H.join(t,".paradigm","habits"));for(let a of o)e.set(a.id,a);return Array.from(e.values())}function za(t){if(!E.existsSync(t))return null;try{let e=E.readFileSync(t,"utf8");return Te.load(e)}catch{return null}}function Ya(t,e){if(e.habits)for(let s of e.habits)t.set(s.id,{...s});if(e.overrides)for(let[s,n]of Object.entries(e.overrides)){let i=t.get(s);i&&(n.severity!==void 0&&(i.severity=n.severity),n.enabled!==void 0&&(i.enabled=n.enabled));}}function zp(t,e){return t.filter(s=>s.enabled&&s.trigger===e)}function ti(t){ei.delete(H.resolve(t));}function Va(t){if(!E.existsSync(t))return [];try{let e=E.readdirSync(t).filter(n=>n.endsWith(".habit")).sort(),s=[];for(let n of e)try{let i=E.readFileSync(H.join(t,n),"utf8"),r=Te.load(i);r?.id&&r?.name&&s.push(r);}catch{}return s}catch{return []}}var Ka=["discovery","verification","testing","documentation","collaboration","security"],Qa=["preflight","postflight","on-commit","on-stop"],Xa=["advisory","warn","block"],Za=["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"],Yp=/^[a-z0-9]+(-[a-z0-9]+)*$/;function ni(t){let e=[];if(t.id||e.push("Missing required field: id"),t.name||e.push("Missing required field: name"),t.description||e.push("Missing required field: description"),t.category||e.push("Missing required field: category"),t.trigger||e.push("Missing required field: trigger"),t.severity||e.push("Missing required field: severity"),t.check||e.push("Missing required field: check"),(t.enabled===void 0||t.enabled===null)&&e.push("Missing required field: enabled"),t.id&&!Yp.test(t.id)&&e.push(`Invalid id format: "${t.id}" \u2014 must be kebab-case (lowercase, hyphens only)`),t.category&&!Ka.includes(t.category)&&e.push(`Invalid category: "${t.category}" \u2014 must be one of: ${Ka.join(", ")}`),t.trigger&&!Qa.includes(t.trigger)&&e.push(`Invalid trigger: "${t.trigger}" \u2014 must be one of: ${Qa.join(", ")}`),t.severity&&!Xa.includes(t.severity)&&e.push(`Invalid severity: "${t.severity}" \u2014 must be one of: ${Xa.join(", ")}`),t.check){Za.includes(t.check.type)||e.push(`Invalid check.type: "${t.check.type}" \u2014 must be one of: ${Za.join(", ")}`);let s=t.check.params||{};switch(t.check.type){case "tool-called":(!s.tools||!Array.isArray(s.tools)||s.tools.length===0)&&e.push('check.type "tool-called" requires check.params.tools[] (non-empty array)');break;case "file-exists":case "file-modified":(!s.patterns||!Array.isArray(s.patterns)||s.patterns.length===0)&&e.push(`check.type "${t.check.type}" requires check.params.patterns[] (non-empty array)`);break;case "commit-message-format":(!s.messagePatterns||!Array.isArray(s.messagePatterns)||s.messagePatterns.length===0)&&e.push('check.type "commit-message-format" requires check.params.messagePatterns[] (non-empty array)');break}}return {valid:e.length===0,errors:e}}var Vp=new Set(ec.map(t=>t.id));function Un(t){return Vp.has(t)}function si(t,e,s="project"){let n=s==="global"?H.join(process.env.HOME||process.env.USERPROFILE||"~",".paradigm","habits"):H.join(t,".paradigm","habits");E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=H.join(n,`${e.id}.habit`),r=Te.dump(e,{lineWidth:120,noRefs:true});return E.writeFileSync(i,r,"utf8"),ti(t),i}function tc(t,e){if(Un(e))return {removed:false,reason:`"${e}" is a seed habit and cannot be removed. Use overrides in habits.yaml to disable it.`};let s=H.join(t,".paradigm","habits",`${e}.habit`);if(E.existsSync(s))return E.unlinkSync(s),ti(t),{removed:true};let n=process.env.HOME||process.env.USERPROFILE||"~",i=H.join(n,".paradigm","habits",`${e}.habit`);return E.existsSync(i)?(E.unlinkSync(i),ti(t),{removed:true}):{removed:false,reason:`No .habit file found for "${e}". It may be defined in habits.yaml \u2014 edit that file directly.`}}var ii=0;function Wt(t,e,s,n,i){let r=zp(t,e);n&&(r=r.filter(u=>!u.platforms||u.platforms.includes(n)));let o=0;if(i)try{let{isGraduated:u}=(Jn(),d$a(Ba)),g=r.length;r=r.filter(m=>!u(i,m.id)),o=g-r.length;}catch{}ii=o;let a=r.map(u=>Kp(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 Gt(t){return {toolsCalled:t.toolsCalled||[],filesModified:t.filesModified||[],symbolsTouched:t.symbolsTouched||[],loreRecorded:t.loreRecorded||false,hasPortalRoutes:t.hasPortalRoutes||false,taskAddsRoutes:t.taskAddsRoutes||false,taskDescription:t.taskDescription,gitClean:t.gitClean}}function Kp(t,e){switch(t.check.type){case "tool-called":return Qp(t,e);case "file-exists":return Xp(t,e);case "file-modified":return su(t,e);case "lore-recorded":return Zp(t,e);case "symbols-registered":return eu(t,e);case "gates-declared":return tu(t,e);case "tests-exist":return nu(t,e);case "git-clean":return iu(t,e);case "commit-message-format":return ru(t,e);case "flow-coverage":return ou(t,e);case "context-checked":return au(t,e);case "aspect-anchored":return cu(t,e);default:return {habit:t,result:"partial",reason:`Unknown check: ${t.check.type}`}}}function Qp(t,e){let s=t.check.params.tools||[];if(s.length===0)return {habit:t,result:"followed",reason:"No tools required"};let n=s.filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Called: ${n.join(", ")}`,evidence:n}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:t,result:"followed",reason:"No modifications, habit not applicable"}:{habit:t,result:"skipped",reason:`None of [${s.join(", ")}] were called before modifying code`}}function Xp(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};if(e.filesModified.some(i=>i.endsWith(".purpose")||i.includes(".paradigm/")))return {habit:t,result:"followed",reason:"Purpose files updated"};let n=e.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".yml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/"));return n.length===0?{habit:t,result:"followed",reason:"Only non-source files modified"}:{habit:t,result:"skipped",reason:`${n.length} source file(s) without .purpose updates`,evidence:n.slice(0,5)}}function Zp(t,e){let s=e.filesModified.filter(n=>!n.endsWith(".md")&&!n.endsWith(".json")&&!n.endsWith(".yaml")&&!n.endsWith(".yml")&&!n.endsWith(".lock")&&!n.endsWith(".purpose")&&!n.includes(".paradigm/"));return s.length<3?{habit:t,result:"followed",reason:"Session not significant (< 3 source files)"}:e.loreRecorded||e.toolsCalled.includes("paradigm_lore_record")?{habit:t,result:"followed",reason:"Lore recorded"}:{habit:t,result:"skipped",reason:`${s.length} source files modified, no lore entry`,evidence:s.slice(0,5)}}function eu(t,e){if(e.symbolsTouched.length===0)return {habit:t,result:"followed",reason:"No symbols touched"};let n=["paradigm_purpose_add_component","paradigm_purpose_add_signal","paradigm_purpose_add_flow","paradigm_purpose_add_gate","paradigm_purpose_add_aspect","paradigm_purpose_init"].filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Purpose tools called: ${n.join(", ")}`,evidence:n}:{habit:t,result:"partial",reason:`${e.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function tu(t,e){if(!e.taskAddsRoutes)return {habit:t,result:"followed",reason:"No routes added"};if(e.hasPortalRoutes)return {habit:t,result:"followed",reason:"Portal.yaml has routes"};let n=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Gate tools called: ${n.join(", ")}`,evidence:n}:{habit:t,result:"skipped",reason:"Routes added without gate declarations"}}function nu(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};let s=e.filesModified.filter(i=>i.includes(".test.")||i.includes(".spec.")||i.includes("/tests/")||i.includes("/test/")||i.includes("__tests__"));if(s.length>0)return {habit:t,result:"followed",reason:`Test files: ${s.length}`,evidence:s.slice(0,5)};let n=e.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/")&&!i.includes("node_modules/"));return n.length===0?{habit:t,result:"followed",reason:"No source files to test"}:{habit:t,result:"partial",reason:`${n.length} source file(s), no test files updated`,evidence:n.slice(0,5)}}function su(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};let s=t.check.params.patterns||[];if(s.length===0)return {habit:t,result:"followed",reason:"No patterns specified"};if(t.trigger==="on-stop"&&t.severity==="block"){let i=e.filesModified.filter(r=>s.some(o=>r.includes(o)||H.basename(r)===o));return i.length>0?{habit:t,result:"followed",reason:`Matching files: ${i.join(", ")}`,evidence:i}:{habit:t,result:"partial",reason:`None of [${s.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let n=e.filesModified.filter(i=>s.some(r=>i.includes(r)||H.basename(i)===r));return n.length>0?{habit:t,result:"followed",reason:`Matching files: ${n.join(", ")}`,evidence:n}:{habit:t,result:"skipped",reason:`None of [${s.join(", ")}] found in modified files`}}function iu(t,e){return e.filesModified.length===0?{habit:t,result:"followed",reason:"No files modified"}:t.trigger==="on-stop"?{habit:t,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:e.gitClean===void 0?{habit:t,result:"partial",reason:"Git status not available"}:e.gitClean?{habit:t,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:t,result:"skipped",reason:"Uncommitted changes in working tree"}}function ru(t,e){if(!e.commitMessage)return {habit:t,result:"followed",reason:"No commit message to check (not a commit trigger)"};let s=t.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],n=s.filter(i=>new RegExp(i,"m").test(e.commitMessage));if(n.length===s.length)return {habit:t,result:"followed",reason:"Commit message matches all required patterns",evidence:n};if(n.length>0){let i=s.filter(r=>!new RegExp(r,"m").test(e.commitMessage));return {habit:t,result:"partial",reason:`Matches ${n.length}/${s.length} patterns. Missing: ${i.join(", ")}`}}return {habit:t,result:"skipped",reason:"Commit message does not match required format patterns"}}function ou(t,e){let s=e.symbolsTouched.filter(r=>r.startsWith("#"));if(s.length<3)return {habit:t,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(e.hasFlowCoverage)return {habit:t,result:"followed",reason:"Flow coverage exists for multi-component changes"};let i=["paradigm_flow_check","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(r=>e.toolsCalled.includes(r));return i.length>0?{habit:t,result:"followed",reason:`Flow tools called: ${i.join(", ")}`,evidence:i}:{habit:t,result:"skipped",reason:`${s.length} components touched without flow coverage`,evidence:s.slice(0,5)}}function au(t,e){let n=(t.check.params.contextTools||["paradigm_session_health","paradigm_session_recover","paradigm_session_checkpoint"]).filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Context tools called: ${n.join(", ")}`,evidence:n}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:t,result:"followed",reason:"No modifications, context check not applicable"}:{habit:t,result:"skipped",reason:"No context/session tools called during session"}}function cu(t,e){let s=e.symbolsTouched.filter(n=>n.startsWith("~"));return s.length===0?{habit:t,result:"followed",reason:"No aspects touched"}:e.aspectAnchorsValid===true?{habit:t,result:"followed",reason:"Aspect anchors validated and valid"}:e.toolsCalled.includes("paradigm_aspect_check")?{habit:t,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:t,result:"skipped",reason:`${s.length} aspect(s) touched without anchor validation`,evidence:s.slice(0,5)}}var lu={"missing-purpose":t=>`${t.target?`"${t.target}"`:"a directory"} is missing a .purpose file. Without it, agents cannot discover what this directory contains or which components live here. The stop hook will block if source files were modified in a directory with no .purpose. Fix: run paradigm_purpose_init for this directory, then add components with paradigm_purpose_add_component.`,"stale-purpose":t=>{let e=t.target?`"${t.target}"`:"a .purpose file",s=t.context?.ageHours!=null?` (${t.context.ageHours}h old)`:"";return `The .purpose file at ${e}${s} has not been updated since the last code change in its directory. Stale purposes mislead agents about what components exist, causing incorrect context injection. Fix: update the .purpose to reflect any added, removed, or changed components, then run paradigm_reindex.`},"missing-gate":t=>`${t.target?`"${t.target}"`:"a route or endpoint"} appears to require authentication or authorization but has no gate declared in portal.yaml. Gates are how Paradigm tracks security enforcement \u2014 missing gates mean agents cannot verify that the route is protected. Fix: add the gate to portal.yaml using paradigm_portal_add_route or paradigm_purpose_add_component with the appropriate gates array.`,"orphan-signal":t=>`${t.target?`"${t.target}"`:"a signal"} is emitted in code but not declared in any .purpose file. Undeclared signals cannot be traced by agents during ripple analysis, meaning downstream effects may be missed when the signal's emitter changes. Fix: add the signal to the nearest .purpose file under its component's signals array (e.g., signals: ["!${t.target||"event-name"}"]). `,"undocumented-flow":t=>`${t.target?`"${t.target}"`:"a multi-step flow"} spans multiple components but has no $flow declaration. Flows with 3 or more steps should be documented so agents can reason about the sequence end-to-end. Without a flow record, agents may implement duplicate logic or miss ordering constraints. Fix: add a flow entry to .paradigm/flows.yaml with the steps and participants.`,"aspect-drift":t=>`${t.target?`"${t.target}"`:"an aspect anchor"} has drifted \u2014 the code at the anchored location no longer matches the fingerprint recorded when the aspect was first applied. This means the aspect may no longer be enforced correctly at that site. Drift is common after refactors that move or rewrite anchored code. Fix: re-anchor the aspect at its new location using paradigm_aspect_anchor, then delete the stale anchor.`,"portal-mismatch":t=>`${t.target?`"${t.target}"`:"a portal.yaml entry"} has a mismatch between what portal.yaml declares and what the code enforces. This could mean a gate is declared but never applied in middleware, or code enforces a check that is not tracked in portal.yaml. Both directions create audit gaps. Fix: reconcile portal.yaml with actual middleware usage \u2014 run paradigm portal check to see specifics.`,"missing-test":t=>`${t.target?`"${t.target}"`:"a component"} has no associated test file. Agents are expected to write tests alongside every implementation. Missing tests increase regression risk and reduce confidence scores for the affected component. Fix: create a test file alongside the implementation (e.g., ${t.target?t.target.replace(/\.[^.]+$/,".test$&"):"component.test.ts"}).`,"uncovered-route":t=>`${t.target?`"${t.target}"`:"a route"} appears in the codebase but is not listed in portal.yaml. All routes \u2014 protected or public \u2014 should be tracked in portal.yaml so the full API surface is visible to agents and reviewers. Uncovered routes are invisible to ripple analysis and gate audits. Fix: add the route to portal.yaml with paradigm_portal_add_route.`,"broken-reference":t=>`${t.target?`"${t.target}"`:"a symbol reference"} references a symbol or file that no longer exists. Broken references in .purpose files cause agents to load stale context and may indicate a renamed or deleted component. Fix: update the reference to the new symbol name, or remove it if the component was deleted. Run paradigm_reindex after fixing to regenerate the scan index.`,"missing-description":t=>`${t.target?`"${t.target}"`:"a component or gate"} has no description. Descriptions are required for agents to understand purpose and context during context injection. Without descriptions, agents may misapply the component or skip it when it would have been relevant. Fix: add a description field to the component or gate entry in its .purpose or portal.yaml file.`,"enforcement-level-violation":t=>{let e=t.target?`"${t.target}"`:"a data category",s=t.context?.ring,n=t.context?.boundary;return `${e} is being transmitted across a boundary (${n||"unknown boundary"}) that exceeds its trust ring${s?` (Ring: ${s})`:""}. Data policy requires project-locked content to never leave the project boundary. This gap could expose internal compliance data externally. Fix: check the data-policy.yaml configuration and ensure the content category is listed in the deny_content for the relevant stream.`},"index-stale":t=>{let e=t.target?`"${t.target}"`:"the scan index",s=t.context?.ageHours,n=s!=null?` (${s} hours old)`:"";return `${e}${n} is stale. The scan index drives context injection, navigator, and ripple analysis. When the index is out of date, agents work from stale symbol maps and may miss recently added components or references. Fix: run paradigm_reindex (or "paradigm index") to regenerate the index.`}};function du(t,e){let s=lu[t];return s?s({...e,type:t}):`Unknown check type "${t}" \u2014 no narration template available.`}function sc(t){let e=[],s=[],n=[];for(let o of t){let a=du(o.type,o),c=o.severity??"improvement",l={type:o.type,target:o.target,narration:a,severity:c};c==="blocking"?e.push(l):c==="note"?n.push(l):s.push(l);}let i=e.length+s.length+n.length,r=pu(e,s,n);return {gapCount:i,blocking:e,improvement:s,note:n,narrative:r}}function pu(t,e,s){let n=[],i=t.length+e.length+s.length;if(i===0)return "No gaps found. All enforcement checks passed.";if(n.push(`Found ${i} gap${i!==1?"s":""} across ${nc(t,e,s)} check type${nc(t,e,s)!==1?"s":""}.`),n.push(""),t.length>0){n.push(`BLOCKING (${t.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of t)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}if(e.length>0){n.push(`IMPROVEMENTS (${e.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of e)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}if(s.length>0){n.push(`NOTES (${s.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of s)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}return n.join(`
555
- `).trimEnd()}function nc(t,e,s){let n=new Set;for(let i of [...t,...e,...s])n.add(i.type);return n.size}function ri(t){if(!t)return [];let e=t.gates;if(e==null)return [];if(Array.isArray(e))return e.map(s=>{if(s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"){let n=s.id;return n.startsWith("^")?n.slice(1):n}return null}).filter(s=>s!==null);if(typeof e=="object")return Object.keys(e).map(s=>s.startsWith("^")?s.slice(1):s);throw new Error(`Invalid gateConfig.gates shape: expected Array or Record, got ${typeof e}`)}var gu=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,mu=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"],fu=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi];function ic(){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.
556
-
557
- 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 rc(t,e,s){switch(t){case "paradigm_pm_preflight":{let{task:n}=e,i=await yu(n,s),r=JSON.stringify(i,null,2);return o(r.length,t),{text:r,handled:true}}case "paradigm_pm_postflight":{let{filesModified:n,symbolsTouched:i}=e,r=bu(n,i,s),o$1=JSON.stringify(r,null,2);return o(o$1.length,t),{text:o$1,handled:true}}default:return {text:"",handled:false}}}async function yu(t,e){let s=t.toLowerCase(),n=t.match(gu)||[],i=[...new Set(n)],r=i.map(u=>{let g=j$2(e.index,u),m=g.length>0?g[0]:null;return {symbol:u,exists:!!m,type:m?.type,description:m?.description}}),o=r.filter(u=>u.exists).map(u=>{let g=k(e.index,u.symbol),m=new Set;for(let b of g){let h=k(e.index,b.symbol);for(let w of h)w.symbol!==u.symbol&&!g.find(S=>S.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=ri(e.gateConfig);a.gateCount=u.length,a.gates=u.map(m=>`^${m}`);let g=e.gateConfig.routes;a.routeCount=g&&!Array.isArray(g)&&typeof g=="object"?Object.keys(g).length:0;}let c=mu.some(u=>s.includes(u)),l=[];r.some(u=>u.exists)&&l.push("ripple-analysis"),c&&l.push("portal-compliance"),i.some(u=>u.startsWith("^"))&&l.push("gate-validation"),i.some(u=>u.startsWith("!"))&&l.push("signal-registration"),l.push("purpose-coverage");let d=null,p=null;try{let u=re(e.rootDir),m=j$1().getStats(),y=[...new Set(m.toolCalls.map(w=>w.toolName))],f=Gt({toolsCalled:y,filesModified:[],symbolsTouched:i,loreRecorded:!1,hasPortalRoutes:a.exists&&a.routeCount>0,taskAddsRoutes:c,taskDescription:t}),b=Wt(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 de(e.rootDir,{dateFrom:h});}catch{}return {task:t.slice(0,100)+(t.length>100?"...":""),affectedSymbols:r,rippleAnalysis:o,portalStatus:a,taskAddsRoutes:c,requiredChecks:l,recommendations:hu(r,o,a,c),habits:{evaluation:d,recentCompliance:p?{rate:p.rate,totalEvents:p.total}:null}}}function hu(t,e,s,n){let i=[],r=t.filter(c=>!c.exists);r.length>0&&i.push(`New symbols detected: ${r.map(c=>c.symbol).join(", ")}. Register in .purpose files after implementation.`);let o=e.filter(c=>c.impact==="high");o.length>0&&i.push(`HIGH IMPACT: ${o.map(c=>c.symbol).join(", ")} \u2014 review all dependents before modifying.`),n&&!s.exists?i.push("Task adds routes but no portal.yaml exists. Create one with appropriate ^gates."):n&&i.push("Task adds routes. Update portal.yaml with gate entries after implementation.");let a=t.filter(c=>c.symbol.startsWith("^")&&!c.exists);return a.length>0&&i.push(`New gates referenced: ${a.map(c=>c.symbol).join(", ")}. Add to portal.yaml.`),i}function bu(t,e,s){let n=[],i$1=s.gateConfig?.routes,r=i$1&&!Array.isArray(i$1)&&typeof i$1=="object"?Object.keys(i$1):[];for(let m of t){let y=H.isAbsolute(m)?m:H.join(s.rootDir,m);if(!E.existsSync(y))continue;let f;try{f=E.readFileSync(y,"utf-8");}catch{continue}for(let b of fu){b.lastIndex=0;let h;for(;(h=b.exec(f))!==null;){let w=h[2]||h[0];w&&w.startsWith("/")&&(!r.some(v=>v.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===w)&&s.gateConfig?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${w}" in ${H.relative(s.rootDir,y)} not in portal.yaml`,file:H.relative(s.rootDir,y),suggestion:"Add route to portal.yaml with ^gates. Use paradigm_gates_for_route for suggestions."}):!s.gateConfig&&w.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${w}" found but no portal.yaml exists`,file:H.relative(s.rootDir,y),suggestion:"Create portal.yaml to declare gates for API routes."}));}}}for(let m of e)j$2(s.index,m).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${m}" is not registered in any .purpose file`,suggestion:"Add to nearest .purpose file using paradigm_purpose_add_component or paradigm_purpose_add_signal."});let o=ri(s.gateConfig);for(let m of e)if(m.startsWith("^")){let y=m.slice(1);o.includes(y)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${m}" referenced but not declared in portal.yaml`,suggestion:`Add ${m} to portal.yaml with description and check expression.`});}let a=i(s.index,"aspect");for(let m of a){let y=m.appliesTo||[];if(y.length!==0){for(let f of y){let b=f.includes("*");for(let h of e){let w=false;if(b?w=new RegExp("^"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(h):w=h===f,w){let S=m.anchors||[];if(S.length===0)n.push({type:"stale-aspect",severity:"warning",message:`Aspect "${m.symbol}" applies to "${h}" but has no code anchors`,suggestion:`Add anchors to ${m.symbol} in .purpose file. Run paradigm_aspect_check for details.`});else for(let v of S){let k=H.isAbsolute(v.path)?v.path:H.join(s.rootDir,v.path);E.existsSync(k)||n.push({type:"stale-aspect",severity:"warning",message:`Aspect "${m.symbol}" anchor "${v.raw}" points to missing file`,suggestion:`Update anchors for ${m.symbol} in .purpose file.`});}}}}for(let f of e){if(!f.startsWith("#"))continue;(m.data||{}).aspects||[];for(let w of y){if(!w.includes("*"))continue;if(new RegExp("^"+w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(f))break}}}}t.length>=5&&e.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${t.length} files, ${e.length} symbols) \u2014 consider recording decisions`,suggestion:"Use paradigm_wisdom_record to capture architectural decisions or antipatterns."});for(let m of e){let y=j$2(s.index,m);if(y.length===0)continue;let f=y[0];f.parentSymbol&&j$2(s.index,f.parentSymbol).length===0&&n.push({type:"broken-reference",severity:"warning",message:`Symbol "${m}" references parent "${f.parentSymbol}" which does not exist`,suggestion:"Create the parent symbol or update the parent reference in the .purpose file."});}let c=n.filter(m=>m.severity==="error").length,l=n.filter(m=>m.severity==="warning").length,d="pass";c>0?d="violations":l>0&&(d="warnings");let p=null;try{let m=re(s.rootDir),f=j$1().getStats(),b=[...new Set(f.toolCalls.map(x=>x.toolName))],h=b.includes("paradigm_lore_record"),w;try{w=execSync("git status --porcelain",{cwd:s.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let S=Gt({toolsCalled:b,filesModified:t,symbolsTouched:e,loreRecorded:h,hasPortalRoutes:s.gateConfig!==null&&s.gateConfig.routes!=null,taskAddsRoutes:!1,gitClean:w}),v=Wt(m,"postflight",S,void 0,s.rootDir);p={trigger:"postflight",total:v.summary.total,followed:v.summary.followed,skipped:v.summary.skipped,partial:v.summary.partial,blockingViolations:v.summary.blockingViolations,results:v.evaluations.map(x=>({id:x.habit.id,name:x.habit.name,severity:x.habit.severity,result:x.result,reason:x.reason}))};let k=H.join(s.rootDir,".paradigm",".habits-blocking");if(v.blocksCompletion){let x=v.evaluations.filter(C=>C.result==="skipped"&&C.habit.severity==="block").map(C=>`${C.habit.name}: ${C.reason}`);E.writeFileSync(k,x.join(`
558
- `),"utf8");}else E.existsSync(k)&&E.unlinkSync(k);}catch{}let u=n.map(m=>({type:{"missing-purpose":"missing-purpose","missing-portal-gate":"missing-gate","unregistered-symbol":"missing-purpose","uncaptured-wisdom":"missing-description","stale-aspect":"aspect-drift","broken-reference":"broken-reference"}[m.type]??"missing-description",target:m.file||m.message.slice(0,80),severity:m.severity==="error"?"blocking":"improvement"})),g=u.length>0?sc(u):null;return {status:d,violations:n,summary:{totalChecks:7,passed:7-(c>0?1:0)-(l>0?1:0),warnings:l,errors:c},blocksCompletion:c>0,habitsEvaluation:p,...g?{narrations:g}:{}}}function ac(){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 cc(t,e,s){switch(t){case "paradigm_habits_list":{let n=vu(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_check":{let n=await ku(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_status":{let n=await Ru(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_practice_context":{let n=await Pu(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_add":{let n=_u(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_edit":{let n=xu(e,s);return o(n.length,t),{text:n,handled:true}}case "paradigm_habits_remove":{let n=Cu(e,s);return o(n.length,t),{text:n,handled:true}}default:return {text:"",handled:false}}}function vu(t,e){let s=t.trigger,n=t.category,i=t.enabled,r=re(e.rootDir);s&&(r=r.filter(a=>a.trigger===s)),n&&(r=r.filter(a=>a.category===n)),i!==void 0&&(r=r.filter(a=>a.enabled===i));let o={};for(let a of r)o[a.trigger]||(o[a.trigger]=[]),o[a.trigger].push(a);return JSON.stringify({total:r.length,filters:Object.fromEntries(Object.entries({trigger:s,category:n,enabled:i}).filter(([,a])=>a!==void 0)),byTrigger:Object.fromEntries(Object.entries(o).map(([a,c])=>[a,c.map(l=>({id:l.id,name:l.name,description:l.description,category:l.category,severity:l.severity,enabled:l.enabled,check:{type:l.check.type,params:l.check.params},platforms:l.platforms||null}))]))},null,2)}async function ku(t,e){let s=t.trigger,n=t.filesModified||[],i=t.symbolsTouched||[],r=t.taskDescription,o=t.record!==false,a=re(e.rootDir),c=j$1(),l=c.getStats(),d=[...new Set(l.toolCalls.map(v=>v.toolName))],p=d.includes("paradigm_lore_record"),u=(r||"").toLowerCase(),g=["endpoint","route","api","handler","get","post","put","patch","delete"].some(v=>u.includes(v)),m;try{m=execSync("git status --porcelain",{cwd:e.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let y=Gt({toolsCalled:d,filesModified:n,symbolsTouched:i,loreRecorded:p,hasPortalRoutes:e.gateConfig!==null&&e.gateConfig.routes!=null,taskAddsRoutes:g,taskDescription:r,gitClean:m}),b=Wt(a,s,y,"claude",e.rootDir),h=[];if(o&&b.evaluations.length>0)try{let v=c.getLastLoreEntryId()??void 0;h=await fa(e.rootDir,b.evaluations.map(k=>({habitId:k.habit.id,habitCategory:k.habit.category,result:k.result,notes:k.reason})),{engineer:"agent",sessionId:l.sessionId,loreEntryId:v,taskDescription:r,symbolsTouched:i,filesModified:n});}catch{}let w=H.join(e.rootDir,".paradigm",".habits-blocking");try{if(s==="on-stop"&&b.blocksCompletion){let v=b.evaluations.filter(k=>k.result==="skipped"&&k.habit.severity==="block").map(k=>`${k.habit.name}: ${k.reason}`);E.writeFileSync(w,v.join(`
559
- `),"utf8");}else s==="on-stop"&&E.existsSync(w)&&E.unlinkSync(w);}catch{}let S=ii;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},...S>0?{graduatedToHooks:S,graduatedNote:`${S} habit(s) enforced by hooks (zero context cost). Not re-evaluated here.`}:{},habits:b.evaluations.map(v=>({id:v.habit.id,name:v.habit.name,category:v.habit.category,severity:v.habit.severity,result:v.result,reason:v.reason,evidence:v.evidence})),recorded:o?h.length:0,recommendations:Su(b)},null,2)}function Su(t){let e=[];for(let s of t.evaluations)if(s.result==="skipped")switch(s.habit.id){case "explore-before-implement":case "ripple-before-modify":e.push("Call paradigm_ripple or paradigm_navigate before modifying symbols.");break;case "check-fragility":e.push("Call paradigm_history_fragility to check for fragile symbols.");break;case "wisdom-before-implement":e.push("Call paradigm_wisdom_context to check team preferences and antipatterns.");break;case "verify-before-done":e.push("Call paradigm_pm_postflight to verify compliance before finishing.");break;case "record-lore-for-significant":e.push("Call paradigm_lore_record to document this session.");break;case "gates-for-routes":e.push("Call paradigm_gates_for_route and update portal.yaml for new routes.");break;case "purpose-coverage":e.push("Update .purpose files using paradigm_purpose_add_component.");break;case "changelog-updated":e.push("Update CHANGELOG.md with the changes made in this phase.");break;case "changes-committed":e.push("Commit all changes to git before finishing this phase.");break;default:e.push(`${s.habit.name}: ${s.reason}`);}return [...new Set(e)]}function _u(t,e){let s=t.id,n=t.scope||"project";if(Un(s))return JSON.stringify({error:true,message:`Cannot create habit "${s}" \u2014 it collides with a seed habit. Choose a different ID or use overrides in habits.yaml to customize the seed habit.`},null,2);if(re(e.rootDir).find(l=>l.id===s))return JSON.stringify({error:true,message:`Habit "${s}" already exists. Use paradigm_habits_edit to update it, or choose a different ID.`},null,2);let o={id:s,name:t.name,description:t.description,category:t.category,trigger:t.trigger,severity:t.severity,check:t.check,enabled:t.enabled!==void 0?t.enabled:true};t.platforms&&(o.platforms=t.platforms);let a=ni(o);if(!a.valid)return JSON.stringify({error:true,message:"Validation failed",errors:a.errors},null,2);let c=si(e.rootDir,o,n);return JSON.stringify({created:true,id:o.id,filePath:c,scope:n,message:`Habit "${o.name}" created at ${c}`},null,2)}function xu(t,e){let s=t.id;if(Un(s))return JSON.stringify({error:true,message:`Cannot edit "${s}" \u2014 it is a seed habit. To customize it, add an override in .paradigm/habits.yaml under the "overrides:" key.`},null,2);let n=H.join(e.rootDir,".paradigm","habits",`${s}.habit`),i=process.env.HOME||process.env.USERPROFILE||"~",r=H.join(i,".paradigm","habits",`${s}.habit`),o=null,a="project";if(E.existsSync(n)?(o=n,a="project"):E.existsSync(r)&&(o=r,a="global"),!o)return JSON.stringify({error:true,message:`No .habit file found for "${s}". It may be defined in habits.yaml \u2014 edit that file directly.`},null,2);let c;try{let p=E.readFileSync(o,"utf8");c=Te.load(p);}catch{return JSON.stringify({error:true,message:`Failed to read ${o}`},null,2)}let l={...c};t.name!==void 0&&(l.name=t.name),t.description!==void 0&&(l.description=t.description),t.category!==void 0&&(l.category=t.category),t.trigger!==void 0&&(l.trigger=t.trigger),t.severity!==void 0&&(l.severity=t.severity),t.check!==void 0&&(l.check=t.check),t.enabled!==void 0&&(l.enabled=t.enabled),t.platforms!==void 0&&(l.platforms=t.platforms);let d=ni(l);return d.valid?(si(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 Cu(t,e){let s=t.id,n=tc(e.rootDir,s);return n.removed?JSON.stringify({removed:true,id:s,message:`Habit "${s}" removed`},null,2):JSON.stringify({error:true,message:n.reason},null,2)}async function Ru(t,e){let s=t.engineer,n=t.period||"30d",i=new Date,r;if(n!=="all"){let h=parseInt(n.replace("d",""),10)||30;r=new Date(i.getTime()-h*24*60*60*1e3).toISOString();}let o={engineer:s,dateFrom:r},a=await de(e.rootDir,o),c=await Tt(e.rootDir,o),l=await ma(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},S=h.result;w[S]++,d.set(h.habitId,w);}let p=null,u=null,g=-1,m=101;for(let h of c)h.rate>g&&(g=h.rate,p=h.category),h.rate<m&&(m=h.rate,u=h.category);let y=re(e.rootDir),f=new Map(y.map(h=>[h.id,h.name])),b=Array.from(d.entries()).map(([h,w])=>{let S=w.followed+w.skipped+w.partial,v=S>0?Math.round((w.followed+w.partial*.5)/S*100):100;return {habitId:h,habitName:f.get(h)||h,...w,total:S,rate:v}}).sort((h,w)=>h.rate-w.rate);return JSON.stringify({period:n,engineer:s||"all",overall:{totalEvents:a.total,complianceRate:a.rate,followed:a.followed,skipped:a.skipped,partial:a.partial,strongestCategory:p,weakestCategory:u},byCategory:c.map(h=>({category:h.category,rate:h.rate,total:h.total,followed:h.followed,skipped:h.skipped,partial:h.partial})),byHabit:b,activeHabits:y.filter(h=>h.enabled).length,totalHabits:y.length},null,2)}async function Pu(t,e){let s=t.symbols||[],n=t.task,r=re(e.rootDir).filter(m=>m.enabled&&m.trigger==="preflight"),a=j$1().getStats(),c=[...new Set(a.toolCalls.map(m=>m.toolName))],l=[];for(let m of r)if(m.check.type==="tool-called"){let y=m.check.params.tools||[];!y.some(b=>c.includes(b))&&s.length>0&&l.push({habitId:m.id,habitName:m.name,category:m.category,severity:m.severity,message:`${m.name}: ${m.description}`,suggestion:`Call one of: ${y.join(", ")}`});}let d=new Date(Date.now()-720*60*60*1e3).toISOString(),p=await de(e.rootDir,{dateFrom:d}),g=(await Tt(e.rootDir,{dateFrom:d})).filter(m=>m.rate<60).map(m=>m.category);return JSON.stringify({symbols:s,task:n||null,warnings:l,recentCompliance:{rate:p.rate,totalEvents:p.total,weakAreas:g},preflightReminders:l.length>0?`${l.length} habit(s) not yet followed this session. See warnings above.`:"All preflight habits satisfied."},null,2)}Jn();Qs();async function lc(t){let e=lt(t);if(!e.enabled)return [];let s=re(t),n=[];for(let i of s){if(!i.enabled)continue;let r=await ju(t,i,e);n.push(r);}return n}async function ju(t,e,s){let n=Gn(t,e.id),i={habitId:e.id,habitName:e.name,currentTier:n.tier,neverGraduate:false,inCooldown:false};if(n.tier==="hook")return {...i,eligible:false,reason:"Already graduated to hook"};if(n.neverGraduate||s.neverGraduate.includes(e.id))return {...i,eligible:false,reason:"Marked as never-graduate (requires agent cognition)",neverGraduate:true};if(Ks.has(e.check.type))return {...i,eligible:false,reason:`Check type "${e.check.type}" cannot graduate \u2014 requires MCP tool output`,neverGraduate:true};if(n.cooldownUntil&&new Date(n.cooldownUntil)>new Date)return {...i,eligible:false,reason:`In cooldown until ${n.cooldownUntil.split("T")[0]} (demoted recently)`,inCooldown:true};let{thresholds:r}=s,o=new Date;o.setDate(o.getDate()-r.timeWindowDays);try{let a=await de(t,{habitId:e.id,dateFrom:o.toISOString()});if(a.total<r.minEvents)return {...i,eligible:!1,reason:`Insufficient data: ${a.total}/${r.minEvents} events in ${r.timeWindowDays}d window`,complianceRate:a.rate,eventCount:a.total};if(a.rate<r.minComplianceRate)return {...i,eligible:!1,reason:`Compliance ${a.rate.toFixed(0)}% < ${r.minComplianceRate}% threshold`,complianceRate:a.rate,eventCount:a.total};let c=new Date;return c.setDate(c.getDate()-r.recencyDays),(await de(t,{habitId:e.id,dateFrom:c.toISOString()})).total===0?{...i,eligible:!1,reason:`No events in last ${r.recencyDays} days \u2014 habit may be dormant`,complianceRate:a.rate,eventCount:a.total}:{...i,eligible:!0,reason:`Ready: ${a.rate.toFixed(0)}% compliance over ${a.total} events in ${r.timeWindowDays}d`,complianceRate:a.rate,eventCount:a.total}}catch{return {...i,eligible:false,reason:"Unable to query practice events (Sentinel DB unavailable)"}}}function dc(t){let e=re(t),s=lt(t),n=Zs(t),i=0,r=0,o=0,a=0;for(let c of e){if(!c.enabled)continue;let l=n[c.id],d=l?.tier||"habit",p=l?.neverGraduate||s.neverGraduate.includes(c.id)||Ks.has(c.check.type);d==="hook"?i++:d==="mcp"?o++:r++,p&&a++;}return {hookCount:i,habitCount:r,mcpCount:o,neverGraduateCount:a,states:n}}Jn();var Au=[{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 Tu(t,e){let s=await lc(t.rootDir),n=s;if(e.habitId&&(n=s.filter(a=>a.habitId===e.habitId),n.length===0))return JSON.stringify({error:`No habit found with ID "${e.habitId}"`});let i=n.filter(a=>a.eligible),r=n.filter(a=>!a.eligible&&!a.neverGraduate),o=n.filter(a=>a.neverGraduate);return JSON.stringify({summary:{checked:n.length,eligible:i.length,ineligible:r.length,neverGraduate:o.length},...i.length>0?{eligible:i.map(pc),action:"Run `paradigm graduate promote <id>` to graduate eligible habits."}:{},...r.length>0?{ineligible:r.map(pc)}:{},...o.length>0?{neverGraduate:o.map(a=>({id:a.habitId,name:a.habitName,reason:a.reason}))}:{}},null,2)}async function Du(t){let e=dc(t.rootDir),s=lt(t.rootDir),n={hook:[],habit:[],mcp:[]};for(let[i,r]of Object.entries(e.states)){let o=r.tier||"habit";n[o]||(n[o]=[]),n[o].push({id:i,...r.graduatedAt?{graduatedAt:r.graduatedAt}:{},...r.neverGraduate?{neverGraduate:true}:{}});}return JSON.stringify({tiers:{hook:e.hookCount,habit:e.habitCount,mcp:e.mcpCount},neverGraduate:e.neverGraduateCount,estimatedSavingsPerSession:`~${e.hookCount*150} tokens`,byTier:n,thresholds:s.thresholds},null,2)}function uc(){return Au}async function gc(t,e,s){switch(t){case "paradigm_graduate_check":return {handled:true,text:await Tu(s,e)};case "paradigm_graduate_status":return {handled:true,text:await Du(s)};default:return {handled:false,text:""}}}function pc(t){return {id:t.habitId,name:t.habitName,tier:t.currentTier,reason:t.reason,...t.complianceRate!==void 0?{complianceRate:t.complianceRate}:{},...t.eventCount!==void 0?{eventCount:t.eventCount}:{},...t.inCooldown?{inCooldown:true}:{}}}var mc=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"]),Ou=.95,Iu=.3,$u=10;function Fu(t,e){let s=t.length,n=e.length;if(s===0)return n;if(n===0)return s;let i=Array.from({length:s+1},()=>Array.from({length:n+1},()=>0));for(let r=0;r<=s;r++)i[r][0]=r;for(let r=0;r<=n;r++)i[0][r]=r;for(let r=1;r<=s;r++)for(let o=1;o<=n;o++){let a=t[r-1]===e[o-1]?0:1;i[r][o]=Math.min(i[r-1][o]+1,i[r][o-1]+1,i[r-1][o-1]+a);}return i[s][n]}function fc(t){let e=t.toLowerCase().split(/\s+/).filter(s=>s.length>0&&!mc.has(s));return e.sort(),e.join(" ")}function Nu(t){try{let e=t.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'aspects_fts'");return e.length>0&&e[0].values.length>0}catch{return false}}function yc(t,e,s){let n=s?.limit??$u,i=fc(e);if(i.length===0)return [];let r=Eu(t,i,s);if(r.length>0)return r.slice(0,n);if(Nu(t)){let a=Hu(t,i,s);if(a.length>0)return a.slice(0,n)}return qu(t,i,s).slice(0,n)}function Eu(t,e,s){try{let n=`
560
- SELECT
561
- a.id, a.description, a.category, a.severity, a.tags,
562
- sw.weight,
563
- (SELECT COUNT(*) FROM anchors anc WHERE anc.aspect_id = a.id) AS anchor_count
564
- FROM search_weights sw
565
- JOIN aspects a ON sw.aspect_id = a.id
566
- WHERE sw.query_normalized LIKE ? || '%'
567
- `,i=[e];s?.category&&(n+=" AND a.category = ?",i.push(s.category)),s?.severity&&(n+=" AND a.severity = ?",i.push(s.severity)),n+=" ORDER BY sw.weight DESC";let r=t.prepare(n);r.bind(i);let o=[];for(;r.step();){let a=r.getAsObject();o.push({id:a.id,description:a.description,category:a.category||void 0,severity:a.severity||void 0,score:a.weight,tier:1,tags:a.tags?oi(a.tags):void 0,anchorCount:a.anchor_count});}return r.free(),o}catch{return []}}function Hu(t,e,s){try{let n=e.split(/\s+/).filter(c=>c.length>0).map(c=>`"${c}"*`).join(" ");if(n.length===0)return [];let i=`
568
- SELECT
569
- a.id, a.description, a.category, a.severity, a.tags,
570
- rank AS fts_rank,
571
- (SELECT COUNT(*) FROM anchors anc WHERE anc.aspect_id = a.id) AS anchor_count
572
- FROM aspects_fts fts
573
- JOIN aspects a ON fts.rowid = a.rowid
574
- WHERE aspects_fts MATCH ?
575
- `,r=[n];s?.category&&(i+=" AND a.category = ?",r.push(s.category)),s?.severity&&(i+=" AND a.severity = ?",r.push(s.severity)),i+=" ORDER BY rank";let o=t.prepare(i);o.bind(r);let a=[];for(;o.step();){let c=o.getAsObject(),l=Math.abs(c.fts_rank);a.push({id:c.id,description:c.description,category:c.category||void 0,severity:c.severity||void 0,score:l,tier:2,tags:c.tags?oi(c.tags):void 0,anchorCount:c.anchor_count});}return o.free(),a}catch{return []}}function qu(t,e,s){try{let n=`
576
- SELECT
577
- a.id, a.description, a.category, a.severity, a.tags,
578
- (SELECT COUNT(*) FROM anchors anc WHERE anc.aspect_id = a.id) AS anchor_count
579
- FROM aspects a
580
- WHERE 1=1
581
- `,i=[];s?.category&&(n+=" AND a.category = ?",i.push(s.category)),s?.severity&&(n+=" AND a.severity = ?",i.push(s.severity));let r=t.prepare(n);r.bind(i);let o=[];for(;r.step();){let c=r.getAsObject();o.push({id:c.id,description:c.description,category:c.category,severity:c.severity,tags:c.tags,anchorCount:c.anchor_count});}r.free();let a=[];for(let c of o){let l=Lu(e,c.id,c.description);l>Iu&&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?oi(c.tags):void 0,anchorCount:c.anchorCount});}return a.sort((c,l)=>l.score-c.score),a}catch{return []}}function Lu(t,e,s){let i=[(e.startsWith("~")?e.slice(1):e).toLowerCase()],r=s.toLowerCase().split(/\s+/).filter(c=>c.length>0&&!mc.has(c));i.push(...r);let o=t.split(/\s+/).filter(c=>c.length>0);if(o.length===0)return 0;let a=0;for(let c of o){let l=0;for(let d of i){let u=1/(1+Fu(c,d));u>l&&(l=u);}a+=l;}return a/o.length}function hc(t,e,s){let n=fc(e),i=new Date().toISOString();try{t.run(`INSERT INTO search_log (query, results, selected, timestamp)
582
- VALUES (?, ?, ?, ?)`,[e,JSON.stringify([s]),s,i]);}catch{}try{t.run(`INSERT INTO search_weights (query_normalized, aspect_id, weight, hit_count, last_hit)
583
- VALUES (?, ?, 1.0, 1, ?)
584
- ON CONFLICT(query_normalized, aspect_id) DO UPDATE SET
585
- weight = weight + 1.0,
586
- hit_count = hit_count + 1,
587
- last_hit = ?`,[n,s,i,i]);}catch{return}try{t.run(`UPDATE search_weights
588
- SET weight = weight * ?
589
- WHERE query_normalized = ? AND aspect_id != ?`,[Ou,n,s]);}catch{}}function oi(t){try{let e=JSON.parse(t);return Array.isArray(e)&&e.length>0?e:void 0}catch{let e=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);return e.length>0?e:void 0}}function wc(){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 vc(t,e,s){switch(t){case "paradigm_aspect_search":return Mu(e,s);case "paradigm_aspect_get":return Wu(e,s);case "paradigm_aspect_graph":return Gu(e,s);case "paradigm_aspect_heatmap":return Ju(e,s);case "paradigm_aspect_suggest_scan":return Uu(e,s);case "paradigm_aspect_drift":return Bu(e,s);case "paradigm_aspect_confirm":return zu(e,s);default:return {handled:false,text:""}}}async function Mu(t,e){let{query:s,limit:n=10}=t,i=null;try{i=await ha$1(e.rootDir);let r=yc(i,s,{limit:n});for(let c of r)try{oa$1(i,c.id,"search");}catch{}let o$1={query:s,count:r.length,results:r.map(c=>({id:c.id,description:c.description,category:c.category,severity:c.severity,score:Math.round(c.score*1e3)/1e3,tier:c.tier,tags:c.tags,anchorCount:c.anchorCount})),tip:r.length>0?"Call paradigm_aspect_confirm with the query and selected aspectId to improve future searches.":"No results found. Try broader terms or check that aspects are defined in .purpose files."},a=JSON.stringify(o$1,null,2);return ia$1(i,e.rootDir),i=null,o(a.length,"paradigm_aspect_search"),{handled:!0,text:a}}catch(r){if(i)try{ia$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to search aspects",details:String(r),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(o$1.length,"paradigm_aspect_search"),{handled:true,text:o$1}}}async function Wu(t,e){let{aspectId:s}=t,n=s.startsWith("~")?s.slice(1):s,i=null;try{i=await ha$1(e.rootDir);let r=ja$1(i,n);if(r||(r=ja$1(i,`~${n}`)),!r){ia$1(i),i=null;let f=JSON.stringify({error:"Aspect not found",aspectId:n,suggestion:"Use paradigm_aspect_search to find aspects by keyword."},null,2);return o(f.length,"paradigm_aspect_get"),{handled:!0,text:f}}let o$1=r.id,c=ka$1(i,o$1).map(f=>{let b=Yu(e.rootDir,f);return {filePath:f.file_path,startLine:f.start_line,endLine:f.end_line,drifted:f.drifted===1,snippet:b}}),l=la$1(i,o$1),d=ma$1(i,o$1),p=[...l.map(f=>({direction:"outgoing",source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin})),...d.map(f=>({direction:"incoming",source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin}))],u=[];try{u=await ra$1(i,e.rootDir,o$1);}catch{}try{oa$1(i,o$1,"direct");}catch{}let g;if(r.tags)try{let f=JSON.parse(r.tags);Array.isArray(f)&&(g=f);}catch{g=r.tags.split(",").map(f=>f.trim()).filter(f=>f.length>0);}let m={id:o$1,description:r.description,category:r.category,severity:r.severity,value:r.value,enforcement:r.enforcement,definedIn:r.defined_in,tags:g,createdAt:r.created_at,updatedAt:r.updated_at,anchors:c,edges:p,lore:u},y=JSON.stringify(m,null,2);return ia$1(i,e.rootDir),i=null,o(y.length,"paradigm_aspect_get"),{handled:!0,text:y}}catch(r){if(i)try{ia$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to get aspect",details:String(r),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(o$1.length,"paradigm_aspect_get"),{handled:true,text:o$1}}}async function Gu(t,e){let{symbol:s,hops:n=2}=t,i=Math.min(Math.max(n,1),5),r=null;try{r=await ha$1(e.rootDir);let o$1=new Set,a=new Map,c=[],l=[{symbol:s,depth:0}];o$1.add(s);let d=ja$1(r,s);for(a.set(s,{aspectId:s,category:d?.category,severity:d?.severity,depth:0});l.length>0;){let m=l.shift();if(m.depth>=i)continue;let y=na$1(r,m.symbol);for(let f of y){let b=f.source===m.symbol?f.target:f.source;if(c.some(w=>w.source===f.source&&w.target===f.target&&w.relation===f.relation)||c.push({source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin,inferred:f.origin==="inferred"}),!o$1.has(b)){o$1.add(b);let w=ja$1(r,b);a.set(b,{aspectId:b,category:w?.category,severity:w?.severity,depth:m.depth+1}),l.push({symbol:b,depth:m.depth+1});}}}let p=Array.from(a.values()),u={startSymbol:s,maxHops:i,nodeCount:p.length,edgeCount:c.length,nodes:p,edges:c},g=JSON.stringify(u,null,2);return ia$1(r),r=null,o(g.length,"paradigm_aspect_graph"),{handled:!0,text:g}}catch(o$1){if(r)try{ia$1(r);}catch{}let a=JSON.stringify({error:"Failed to traverse aspect graph",details:String(o$1),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(a.length,"paradigm_aspect_graph"),{handled:true,text:a}}}async function Ju(t,e){let{limit:s=20,accessType:n}=t,i=null;try{i=await ha$1(e.rootDir);let r=pa$1(i,s*4,n),o$1=new Map;for(let d of r){let p=o$1.get(d.aspect_id);if(!p){let u=ja$1(i,d.aspect_id);p={aspectId:d.aspect_id,description:u?.description,totalCount:0,byType:{},lastAccessed:d.last_accessed},o$1.set(d.aspect_id,p);}p.totalCount+=d.count,p.byType[d.access_type]=d.count,d.last_accessed>p.lastAccessed&&(p.lastAccessed=d.last_accessed);}let a=Array.from(o$1.values()).sort((d,p)=>p.totalCount-d.totalCount).slice(0,s),c={count:a.length,...n?{filteredBy:n}:{},entries:a},l=JSON.stringify(c,null,2);return ia$1(i),i=null,o(l.length,"paradigm_aspect_heatmap"),{handled:!0,text:l}}catch(r){if(i)try{ia$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to get aspect heatmap",details:String(r),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(o$1.length,"paradigm_aspect_heatmap"),{handled:true,text:o$1}}}async function Uu(t,e){let{filePath:s}=t,n=H.isAbsolute(s)?s:H.join(e.rootDir,s);if(!E.existsSync(n)){let i=JSON.stringify({error:"File not found",filePath:n,suggestion:"Provide a valid relative or absolute file path."},null,2);return o(i.length,"paradigm_aspect_suggest_scan"),{handled:true,text:i}}try{let o$1=(await import('../utils/aspect-suggest.js')).suggestAspects(n),a={filePath:n,count:o$1.length,suggestions:o$1.map(l=>({line:l.line,code:l.code,suggestedName:l.suggestedName,category:l.suggestedCategory,description:l.suggestedDescription,confidence:l.confidence,reason:l.reason,inferred:!0})),tip:o$1.length>0?"Review suggestions and add confirmed aspects to your .purpose files with ~ prefix and code anchors.":"No implicit aspects detected in this file."},c=JSON.stringify(a,null,2);return o(c.length,"paradigm_aspect_suggest_scan"),{handled:!0,text:c}}catch(i){let r=String(i);if(r.includes("Cannot find module")||r.includes("MODULE_NOT_FOUND")){let a=JSON.stringify({error:"Aspect suggestion engine not available",details:"The aspect-suggest utility has not been implemented yet.",suggestion:"This feature will be available in a future release. For now, manually identify implicit aspects in your code."},null,2);return o(a.length,"paradigm_aspect_suggest_scan"),{handled:true,text:a}}let o$1=JSON.stringify({error:"Failed to scan for aspect suggestions",details:r},null,2);return o(o$1.length,"paradigm_aspect_suggest_scan"),{handled:true,text:o$1}}}async function Bu(t,e){let{aspectId:s,autoHeal:n}=t,i=n!==false,r=s?s.startsWith("~")?s.slice(1):s:void 0,o$1=.7,a=.85;try{let l=H.join(e.rootDir,".paradigm","config.yaml");if(E.existsSync(l)){let p=Te.load(E.readFileSync(l,"utf-8"))?.drift;typeof p?.["suggest-threshold"]=="number"&&(o$1=p["suggest-threshold"]),typeof p?.["auto-heal-threshold"]=="number"&&(a=p["auto-heal-threshold"]);}}catch{}let c=null;try{c=await ha$1(e.rootDir);let l=qa$1(c,e.rootDir,r,i,o$1,a),d=l.filter(S=>S.status==="clean").length,p=l.filter(S=>S.status==="cosmetic").length,u=l.filter(S=>S.status==="shifted").length,g=l.filter(S=>S.status==="modified").length,m=l.filter(S=>S.status==="missing").length,y=g>0||m>0,f=p>0||u>0,b=y?"drift-detected":f?"clean-with-heals":"clean",h={...r?{aspectId:r}:{scope:"all"},totalAnchors:l.length,clean:d,cosmetic:p,shifted:u,modified:g,missing:m,status:b,results:l.map(S=>({aspectId:S.aspectId,path:S.path,startLine:S.startLine,endLine:S.endLine,status:S.status,resolvedBy:S.resolvedBy,exists:S.exists,...S.status==="shifted"?{suggestedStart:S.suggestedStart,suggestedEnd:S.suggestedEnd,autoHealed:S.autoHealed}:{},...S.status==="modified"&&S.currentContent?{currentContent:S.currentContent.slice(0,500)}:{}})),...p>0||u>0?{healed:[p>0?`${p} cosmetic (whitespace/formatting \u2014 hashes updated)`:"",u>0?`${u} shifted (line numbers updated via git diff${i?" \u2014 .purpose files patched":""})`:""].filter(Boolean).join(", ")}:{},...y?{suggestion:"Review drifted anchors to ensure aspects still apply. Run `paradigm scan` to re-materialize after fixing."}:{}},w=JSON.stringify(h,null,2);return ia$1(c,e.rootDir),c=null,o(w.length,"paradigm_aspect_drift"),{handled:!0,text:w}}catch(l){if(c)try{ia$1(c);}catch{}let d=JSON.stringify({error:"Failed to check aspect drift",details:String(l),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(d.length,"paradigm_aspect_drift"),{handled:true,text:d}}}async function zu(t,e){let{query:s,aspectId:n}=t,i=null;try{i=await ha$1(e.rootDir),hc(i,s,n);let r={confirmed:!0,query:s,aspectId:n,message:`Search mapping reinforced: "${s}" -> ${n}. Future searches for similar queries will rank this aspect higher.`},o$1=JSON.stringify(r,null,2);return ia$1(i,e.rootDir),i=null,o(o$1.length,"paradigm_aspect_confirm"),{handled:!0,text:o$1}}catch(r){if(i)try{ia$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to confirm search",details:String(r)},null,2);return o(o$1.length,"paradigm_aspect_confirm"),{handled:true,text:o$1}}}function Yu(t,e){let s=H.isAbsolute(e.file_path)?e.file_path:H.join(t,e.file_path);if(!E.existsSync(s))return null;try{let i=E.readFileSync(s,"utf8").split(`
590
- `),r=Math.max(0,e.start_line-1),o=Math.min(i.length,e.end_line),a=i.slice(r,o).join(`
591
- `);return a.length>1e3?a.slice(0,1e3)+`
592
- ... (truncated)`:a}catch{return null}}function kc(){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 Sc(t,e,s){switch(t){case "paradigm_task_create":{let n=await c$3(s.rootDir,{blurb:e.blurb,priority:e.priority,tags:e.tags,related_lore:e.related_lore}),i=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({created:n,task:i},null,2)}}case "paradigm_task_list":{let n=await a$7(s.rootDir,{status:e.status||"open",priority:e.priority,tag:e.tag,limit:e.limit||20}),i=e.status||"open",r=[`${n.length} ${i} task(s):`];for(let o of n){let a=o.tags.length>0?` [${o.tags.join(", ")}]`:"";r.push(` [${o.priority}] ${o.id}: ${o.blurb}${a}`);}return {handled:true,text:r.join(`
593
- `)}}case "paradigm_task_update":{let n=e.id,i={};if(e.blurb!==void 0&&(i.blurb=e.blurb),e.priority!==void 0&&(i.priority=e.priority),e.status!==void 0&&(i.status=e.status),e.tags!==void 0&&(i.tags=e.tags),e.related_lore!==void 0&&(i.related_lore=e.related_lore),e.related_assessments!==void 0&&(i.related_assessments=e.related_assessments),!await d$6(s.rootDir,n,i))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let o=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({updated:n,task:o},null,2)}}case "paradigm_task_done":{let n=e.id;if(!await e$5(s.rootDir,n))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let r=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({completed:n,task:r,hint:"Consider recording a lore entry with arc:* tags if this was a significant milestone."},null,2)}}case "paradigm_task_shelve":{let n=e.id;if(!await f$3(s.rootDir,n))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let r=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({shelved:n,task:r},null,2)}}default:return {handled:false,text:""}}}var _c=0;function xc(){let t=new Date().toISOString().slice(0,10);return _c++,`run_${t}_${String(_c).padStart(3,"0")}`}var Cc=/\{\{([^}]+)\}\}/g;function dt(t,e){if(typeof t=="string")return t.replace(Cc,(s,n)=>{let i=Vu(n.trim(),e);return i!==void 0?String(i):s});if(Array.isArray(t))return t.map(s=>dt(s,e));if(t&&typeof t=="object"){let s={};for(let[n,i]of Object.entries(t))s[n]=dt(i,e);return s}return t}function Vu(t,e){let[s,...n]=t.split("."),i=n.join(".");switch(s){case "fixtures":return e.fixtures[i];case "produces":return ai(e.produces,i);case "context":case "parent":return e.context[i];case "env":return e.env[i]??process.env[i];default:return}}function ai(t,e){let s=e.split(/[.\[\]]+/).filter(Boolean),n=t;for(let i of s){if(n==null||typeof n!="object")return;n=n[i];}return n}function Ku(t,e){let s={};for(let[n,i]of Object.entries(t)){let r=i.match(/\{\{response\.(.+)\}\}/);if(r){let o=r[1],a=ai(e,o);a!==void 0&&(s[n]=a);}}return s}function Qu(t,e){if(e.status!==t.status)return {pass:false,failure:`Status mismatch: expected ${t.status}, got ${e.status}`};if(t.body){let s=e.body;if(t.body.has){for(let n of t.body.has)if(s===null||typeof s!="object"||!(n in s))return {pass:false,failure:`Expected body to have key "${n}"`}}if(t.body.match)for(let[n,i]of Object.entries(t.body.match)){let r=ai(s,n);if(JSON.stringify(r)!==JSON.stringify(i))return {pass:false,failure:`Body mismatch at "${n}": expected ${JSON.stringify(i)}, got ${JSON.stringify(r)}`}}}return {pass:true}}async function Xu(t,e,s){let n=Date.now(),i=t.route.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(.*)/);if(!i)return {id:t.id,status:"fail",route:t.route,gates:t.gates,failure:`Invalid route format: ${t.route}`,duration_ms:Date.now()-n};let r=i[1],o=i[2],a=dt(o,s),c=`${e.baseUrl.replace(/\/$/,"")}${a}`,l={"Content-Type":"application/json",...t.headers?dt(t.headers,s):{}},d=t.payload?dt(t.payload,s):void 0,p={url:c,method:r,headers:t.headers?l:void 0,payload:d};if(e.dryRun)return {id:t.id,status:"pass",route:t.route,gates:t.gates,request:p,produced:t.produces?Object.fromEntries(Object.keys(t.produces).map(u=>[u,`<dry-run:${u}>`])):void 0,duration_ms:Date.now()-n};try{let u={method:r,headers:l};d&&["POST","PUT","PATCH"].includes(r)&&(u.body=JSON.stringify(d));let g=await fetch(c,u),m;(g.headers.get("content-type")||"").includes("application/json")?m=await g.json():m=await g.text();let f={status:g.status,body:m},b=Qu(t.expect,f),h;t.produces&&b.pass&&(h=Ku(t.produces,m));let w;return (g.status===401||g.status===403)&&(w=t.gates[t.gates.length-1]),{id:t.id,status:b.pass?"pass":"fail",route:t.route,gates:t.gates,request:p,response:f,produced:h,expected_status:b.pass?void 0:t.expect.status,failure:b.failure,gate_that_blocked:w,duration_ms:Date.now()-n}}catch(u){return {id:t.id,status:"fail",route:t.route,gates:t.gates,request:p,failure:`Request failed: ${u.message}`,duration_ms:Date.now()-n}}}async function Rc(t,e,s){let n=Date.now(),i=await x$1(t,e);return i?Pc(t,i,s):{persona:e,run_id:xc(),status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${e} not found`,duration_ms:Date.now()-n}}async function Pc(t,e,s){let n=Date.now(),i=s.stopOnFailure!==false,r={fixtures:e.fixtures||{},produces:{},context:s.context||{},env:process.env},o=[],a=[],c=[],l=false;for(let y of e.journey){if(l&&i){if(o.push({id:y.id,status:"skip",route:y.route,gates:y.gates,duration_ms:0}),y.spawns)for(let b of y.spawns)c.push(b.persona);continue}let f=await Xu(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:xc(),status:p>0?"fail":"pass",steps:o,spawns_triggered:a,spawns_blocked:c,summary:m,duration_ms:Date.now()-n}}async function jc(t,e,s){let n=Date.now(),i=await import('fs'),r=await import('path'),o=await import('js-yaml'),a=r.join(t,".paradigm","personas","chains",`${e}.yaml`);if(!i.existsSync(a))return {chain_id:e,status:"error",persona_results:[],summary:`Chain ${e} not found`,duration_ms:Date.now()-n};let c=o.load(i.readFileSync(a,"utf8")),l;if(s.permutation&&c.permutations&&(l=c.permutations.find(y=>y.id===s.permutation),!l))return {chain_id:e,status:"error",persona_results:[],summary:`Permutation ${s.permutation} not found in chain ${e}`,duration_ms:Date.now()-n};let d=[],p={},u=s.stopOnFailure!==false;for(let y of c.order){let f=await x$1(t,y.persona);if(!f){if(d.push({persona:y.persona,status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${y.persona} not found`,duration_ms:0}),u)break;continue}if(l&&l.overrides[y.persona]){let S=l.overrides[y.persona];if(S.traits&&(f.traits={...f.traits,...S.traits}),S.journey)for(let[v,k]of Object.entries(S.journey)){let x=f.journey.find(C=>C.id===v);x&&(k.payload&&(x.payload={...x.payload,...k.payload}),k.expect&&(x.expect={...x.expect,...k.expect}));}}let b={};if(y.wait_for){let[S,v]=y.wait_for.split("."),k=d.find(C=>C.persona===S);if(k){let C=k.steps.find(_=>_.id===v);C?.produced&&(b=Object.fromEntries(Object.entries(C.produced).map(([_,P])=>[_,String(P)])));}let x=await x$1(t,S);if(x){let C=x.journey.find(_=>_.id===v);if(C?.spawns){let _=C.spawns.find(P=>P.persona===y.persona);if(_?.context){let P=p[S]||{};for(let[$,R]of Object.entries(_.context))b[$]=String(dt(R,{fixtures:{},produces:P,context:{},env:process.env}));}}}}let h=await Pc(t,f,{...s,context:b});d.push(h);let w={};for(let S of h.steps)S.produced&&Object.assign(w,S.produced);if(p[y.persona]=w,h.status==="fail"&&u)break}let g=d.filter(y=>y.status==="pass").length,m=c.order.length;return {chain_id:e,status:d.some(y=>y.status!=="pass")?"fail":"pass",persona_results:d,summary:`${g}/${m} personas passed.`,duration_ms:Date.now()-n}}function Ac(t){let e=[],s=new Set;for(let n of t.journey){let r=JSON.stringify(n).match(Cc)||[];for(let o of r){let a=o.replace("{{","").replace("}}","").trim(),[c,...l]=a.split("."),d=l.join(".");switch(c){case "fixtures":!t.fixtures||d in t.fixtures;break;case "produces":s.has(d)||e.push({step:n.id,template:o,error:`{{produces.${d}}} used but not produced by a prior step`});break;case "context":case "parent":break;case "env":break;case "response":break;default:e.push({step:n.id,template:o,error:`Unknown namespace "${c}" in ${o}`});}}if(n.produces)for(let o of Object.keys(n.produces))s.add(o);}return {valid:e.length===0,errors:e}}var Dc="paradigm-personas",Zu={id:Dc,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"}}},ci=false;async function Tc(t){try{let{SentinelStorage:e}=await import('./dist-W3XCATBJ.js'),s=new e;if(!ci)try{s.registerSchema(Zu),ci=!0;}catch{ci=!0;}let n=[];if("persona"in t){let i=t;n.push({type:"persona.run.start",timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,total_steps:i.steps.length}});for(let r of i.steps){let o=r.status==="pass"?"persona.step.complete":`persona.step.${r.status}`;n.push({type:o,timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,step_id:r.id,route:r.route,gates:r.gates,gates_traversed:r.gates,status:r.response?.status,body:r.response?.body,signals_fired:[],duration_ms:r.duration_ms,failure:r.failure,gate_that_blocked:r.gate_that_blocked,produced_keys:r.produced?Object.keys(r.produced):[]}});}n.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,status:i.status,total_steps:i.steps.length,passed:i.steps.filter(r=>r.status==="pass").length,failed:i.steps.filter(r=>r.status==="fail").length,skipped:i.steps.filter(r=>r.status==="skip").length,duration_ms:i.duration_ms,spawns_triggered:i.spawns_triggered,spawns_blocked:i.spawns_blocked}});}else {let i=t;for(let r of i.persona_results)n.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:r.persona,data:{persona_id:r.persona,run_id:r.run_id,chain_id:i.chain_id,status:r.status,total_steps:r.steps.length,passed:r.steps.filter(o=>o.status==="pass").length,failed:r.steps.filter(o=>o.status==="fail").length,duration_ms:r.duration_ms}});n.push({type:"persona.chain.complete",timestamp:new Date().toISOString(),data:{chain_id:i.chain_id,status:i.status,personas_run:i.persona_results.length,personas_passed:i.persona_results.filter(r=>r.status==="pass").length,duration_ms:i.duration_ms}});}n.length>0&&s.insertEventBatch(Dc,"paradigm-personas",n);}catch{}}function Oc(){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 Ic(t,e,s){switch(t){case "paradigm_persona_create":try{let n=await y$1(s.rootDir,{id:e.id,name:e.name,description:e.description,traits:e.traits,trigger:e.trigger,fixtures:e.fixtures,tags:e.tags,journey:e.journey}),i=await x$1(s.rootDir,n);return {handled:!0,text:JSON.stringify({created:n,persona:i},null,2)}}catch(n){return {handled:true,text:JSON.stringify({error:n.message})}}case "paradigm_persona_get":{let n=e.id,i=await x$1(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Persona ${n} not found`})};let r=await D(s.rootDir,i);return {handled:true,text:JSON.stringify({persona:i,validation:r},null,2)}}case "paradigm_persona_list":{let n=await w(s.rootDir,{tag:e.tag,trigger_type:e.trigger_type,gate:e.gate,flow:e.flow,limit:e.limit||50}),i=n.map(r=>({id:r.id,name:r.name,trigger:r.trigger.type,steps:r.journey.length,gates:[...new Set(r.journey.flatMap(o=>o.gates))],tags:r.tags||[]}));return {handled:true,text:JSON.stringify({count:n.length,personas:i},null,2)}}case "paradigm_persona_update":{let n=e.id,i={};if(e.name!==void 0&&(i.name=e.name),e.description!==void 0&&(i.description=e.description),e.traits!==void 0&&(i.traits=e.traits),e.trigger!==void 0&&(i.trigger=e.trigger),e.fixtures!==void 0&&(i.fixtures=e.fixtures),e.tags!==void 0&&(i.tags=e.tags),e.journey!==void 0&&(i.journey=e.journey),!await z$1(s.rootDir,n,i))return {handled:true,text:JSON.stringify({error:`Persona ${n} not found`})};let o=await x$1(s.rootDir,n);return {handled:true,text:JSON.stringify({updated:n,persona:o},null,2)}}case "paradigm_persona_delete":{let n=e.id,i=await A$1(s.rootDir,n);return i.deleted?{handled:true,text:JSON.stringify({deleted:n,warnings:i.warnings,hint:i.warnings.length>0?"Other personas reference this one. Update or delete them to avoid broken spawn chains.":void 0},null,2)}:{handled:true,text:JSON.stringify({error:`Persona ${n} not found`})}}case "paradigm_persona_add_step":try{if(!await B(s.rootDir,e.persona_id,e.step,e.after))return {handled:!0,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let i=await x$1(s.rootDir,e.persona_id);return {handled:!0,text:JSON.stringify({added:e.step.id,persona_id:e.persona_id,total_steps:i?.journey.length},null,2)}}catch(n){return {handled:true,text:JSON.stringify({error:n.message})}}case "paradigm_persona_remove_step":{let n=await C(s.rootDir,e.persona_id,e.step_id);return n.removed?{handled:true,text:JSON.stringify({removed:e.step_id,persona_id:e.persona_id,warnings:n.warnings},null,2)}:{handled:true,text:JSON.stringify({error:`Step ${e.step_id} not found in persona ${e.persona_id}`})}}case "paradigm_persona_validate":{let n=e.deep??false,i=e.sentinel??true,r={run_id:e.run_id,chain_id:e.chain_id,environment:e.environment};if(e.persona_id){let d=await x$1(s.rootDir,e.persona_id);if(!d)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let p=await D(s.rootDir,d,n);if(i)try{let u=await G(d,r);p.sentinel_assertions=u,(u.summary.failed>0||u.summary.unmatched>0)&&(p.valid=!1);}catch{}return {handled:true,text:JSON.stringify(p,null,2)}}let o=await w(s.rootDir),a=await Promise.all(o.map(async d=>{let p=await D(s.rootDir,d,n);if(i)try{let u=await G(d,r);p.sentinel_assertions=u,(u.summary.failed>0||u.summary.unmatched>0)&&(p.valid=!1);}catch{}return p})),c=a.filter(d=>d.valid).length,l=a.filter(d=>!d.valid).length;return {handled:true,text:JSON.stringify({total:a.length,valid:c,invalid:l,results:a.filter(d=>!d.valid||d.warnings.length>0||d.sentinel_assertions)},null,2)}}case "paradigm_persona_coverage":{let n=await E$1(s.rootDir);return {handled:true,text:JSON.stringify(n,null,2)}}case "paradigm_persona_affected":{let n=e.symbol,i=await F(s.rootDir,n);return i.length===0?{handled:true,text:JSON.stringify({symbol:n,affected:[],note:"No personas reference this symbol."})}:{handled:true,text:JSON.stringify({symbol:n,affected:i},null,2)}}case "paradigm_persona_run":{let n=e.base_url,i=e.dry_run??false,r=e.stop_on_failure??true;if(e.chain_id){let o=await jc(s.rootDir,e.chain_id,{baseUrl:n,dryRun:i,stopOnFailure:r,permutation:e.permutation});return i||await Tc(o),{handled:true,text:JSON.stringify(o,null,2)}}if(e.persona_id){let o=await x$1(s.rootDir,e.persona_id);if(!o)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let a=Ac(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 Rc(s.rootDir,e.persona_id,{baseUrl:n,dryRun:i,stopOnFailure:r});return i||await Tc(c),{handled:true,text:JSON.stringify(c,null,2)}}return {handled:true,text:JSON.stringify({error:"Either persona_id or chain_id is required"})}}default:return {handled:false,text:""}}}var eg=".paradigm/graphs",pi={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},li=200,di=60,pt=20,zn=40,$c=50,tg=60;function Nc(){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 Ec(t,e,s){if(t!=="paradigm_graph_generate")return {handled:false,text:""};try{let n=e.name||"untitled",i=n.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),r=ig(s.rootDir,e.symbols,e.groups,e.links,n),o$1=JSON.stringify(r,null,2),a=H.join(s.rootDir,eg);E.existsSync(a)||E.mkdirSync(a,{recursive:!0});let c=H.join(a,`${i}.graph.json`);E.writeFileSync(c,o$1,"utf8");let l=JSON.stringify({file:c,name:n,slug:i,nodes:r.nodes.length,edges:r.edges.length,size:`${(o$1.length/1024).toFixed(1)} KB`,hint:"Graph saved. Run `paradigm graph` to view in browser."},null,2);return o(l.length,t),{handled:!0,text:l}}catch(n){let i=JSON.stringify({error:n.message},null,2);return o(i.length,t),{handled:true,text:i}}}var ng={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"};function sg(t){let e=H.join(t,".paradigm","scan-index.json");if(!E.existsSync(e))return [];let s=JSON.parse(E.readFileSync(e,"utf8")),n=[];for(let[i,r]of Object.entries(ng)){let o=s[i];if(!(!o||typeof o!="object"))for(let[a,c]of Object.entries(o)){let l=c;n.push({id:a,name:a,category:r,prefix:pi[r]||"#",description:l.description,path:l.path,tags:l.tags});}}return n}function Fc(t,e){let s=t.replace(/^[#$^!~]/,"");return e.find(n=>n.id===s||n.name===s||n.id===t||n.name===t)}function ig(t,e,s,n,i="Generated Graph"){let r=sg(t),o;e&&e.length>0?o=e.map(g=>Fc(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(k=>Fc(k,o)).filter(Boolean),f=Math.ceil(Math.sqrt(y.length)),b=Math.ceil(y.length/f);for(let k=0;k<y.length;k++){let x=y[k],C=k%f,_=Math.floor(k/f),P=pi[x.category]||"#";a.push({id:`sym-${x.id}`,type:"symbolNode",position:{x:zn+C*(li+pt),y:$c+zn+_*(di+pt)},parentId:m,data:{type:"symbol",symbol:x,label:`${P}${x.name}`}}),d.add(x.id);}let h=Math.max(f,1),w=Math.max(b,1),S=zn*2+h*li+(h-1)*pt,v=$c+zn*2+w*di+(w-1)*pt;a.unshift({id:m,type:"groupNode",position:{x:p,y:0},style:{width:S,height:v},data:{type:"group",label:g.label}}),p+=S+tg;}let u=o.filter(g=>!d.has(g.id));if(u.length>0){let g=s&&s.length>0?400:0,m=Math.ceil(Math.sqrt(u.length));for(let y=0;y<u.length;y++){let f=u[y],b=y%m,h=Math.floor(y/m),w=pi[f.category]||"#";a.push({id:`sym-${f.id}`,type:"symbolNode",position:{x:b*(li+pt),y:g+h*(di+pt)},data:{type:"symbol",symbol:f,label:`${w}${f.name}`}});}}if(n&&n.length>0)for(let g of n){let m=l.get(g.source),y=l.get(g.target);m&&y&&c.push({id:`e-${m}-${y}`,source:m,target:y,type:"default",label:g.label,data:{label:g.label}});}return {version:"1.0",name:i,projectId:H.basename(t),lastModified:new Date().toISOString(),nodes:a,edges:c}}var me=["specify","plan","task","implement","validate"],Bt=".paradigm/pipeline",Hc={"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 Yn(t){return t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Jt(t,e){let s=Yn(e),n=H.join(t,Bt,`${s}.yaml`);return E.existsSync(n)?Te.load(E.readFileSync(n,"utf8")):null}function Ut(t,e){let s=Yn(e.feature),n=H.join(t,Bt);E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=H.join(n,`${s}.yaml`);return E.writeFileSync(i,Te.dump(e,{lineWidth:120}),"utf8"),i}function qc(t){let e=H.join(t,Bt);return E.existsSync(e)?E.readdirSync(e).filter(s=>s.endsWith(".yaml")&&!s.startsWith("completed")).map(s=>{try{return Te.load(E.readFileSync(H.join(e,s),"utf8"))}catch{return null}}).filter(Boolean):[]}function rg(t,e,s){let n={specify:{status:"pending"},plan:{status:"pending"},task:{status:"pending"},implement:{status:"pending"},validate:{status:"pending"}};return n.specify.status="in-progress",{version:"1.0",feature:Yn(t),created:new Date().toISOString(),current_stage:"specify",gate_config:e,template:s,stages:n}}function og(t){let e=me.indexOf(t);return e<me.length-1?me[e+1]:null}function Lc(t,e){let s=Yn(e.feature),n=H.join(t,Bt,"completed");E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=H.join(n,`${s}.yaml`);E.writeFileSync(i,Te.dump(e,{lineWidth:120}),"utf8");let r=H.join(t,Bt,`${s}.yaml`);E.existsSync(r)&&E.unlinkSync(r);}function Mc(){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 Wc(t,e,s){switch(t){case "paradigm_pipeline_start":{let n=e.feature,i=e.template||"add-feature",r=e.gates,o;if(r)o={specify:r.specify||"manual",plan:r.plan||"manual",task:r.task||"auto",implement:r.implement||"sentinel",validate:r.validate||"sentinel"};else {let l=Hc[i];if(!l)return {handled:true,text:JSON.stringify({error:`Unknown template: ${i}`,available:Object.keys(Hc)})};o=l.gates;}let a=rg(n,o,i),c=Ut(s.rootDir,a);return {handled:true,text:JSON.stringify({created:true,feature:a.feature,template:i,file:c,current_stage:a.current_stage,gate_config:a.gate_config,stages:a.stages,hint:`Pipeline '${a.feature}' started at 'specify' stage. Create your spec, then call paradigm_pipeline_advance to move to 'plan'.`},null,2)}}case "paradigm_pipeline_status":{let n=e.feature;if(n){let r=Jt(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};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=qc(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 n=e.feature,i=e.approved_by||"agent",r=Jt(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let o=r.current_stage,a=r.gate_config[o],c=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",Ut(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)}):(Ut(s.rootDir,r),Lc(s.rootDir,r),{handled:true,text:JSON.stringify({completed:true,feature:r.feature,message:`Pipeline '${r.feature}' completed and archived.`,stages:r.stages},null,2)})}case "paradigm_pipeline_configure":{let n=e.feature,i=e.updates,r=e.reason,o=Jt(s.rootDir,n);if(!o)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let a=[];for(let[c,l]of Object.entries(i))if(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"]})}:(Ut(s.rootDir,o),{handled:true,text:JSON.stringify({configured:true,feature:o.feature,changes:a,reason:r,gate_config:o.gate_config},null,2)})}case "paradigm_pipeline_escalate":{let n=e.feature,i=e.stage,r=e.question,o=e.options,a=e.context,c=Jt(s.rootDir,n);return c?(c.stages[i].status="blocked",c.stages[i].block_reason=r,Ut(s.rootDir,c),{handled:true,text:JSON.stringify({escalated:true,feature:c.feature,stage:i,question:r,options:o,context:a||{},current_gate:c.gate_config[i],instruction:"This pipeline stage requires user input. Present the question and options to the user, then use paradigm_pipeline_advance or paradigm_pipeline_configure based on their response."},null,2)}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})}}case "paradigm_pipeline_abort":{let n=e.feature,i=Jt(s.rootDir,n);return i?(Lc(s.rootDir,i),{handled:true,text:JSON.stringify({aborted:true,feature:i.feature,message:`Pipeline '${i.feature}' aborted and archived.`})}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})}}case "paradigm_pipeline_list":{let n=qc(s.rootDir);return n.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines."})}:{handled:true,text:JSON.stringify({count:n.length,pipelines:n.map(i=>{let r=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:""}}}b$1();var ag=H.join(wa.homedir(),".conductor"),mt=H.join(ag,"sessions");function Jc(){E.existsSync(mt)||E.mkdirSync(mt,{recursive:true});}function gi(t){Jc();let e={...t,registeredAt:new Date().toISOString()},s=H.join(mt,`${t.pid}.json`);return E.writeFileSync(s,JSON.stringify(e,null,2),"utf-8"),e}function Vn(t){let e=H.join(mt,`${t}.json`);return E.existsSync(e)?(E.unlinkSync(e),true):false}function mi(){Jc();let t=E.readdirSync(mt).filter(s=>s.endsWith(".json")),e=[];for(let s of t)try{let n=E.readFileSync(H.join(mt,s),"utf-8"),i=JSON.parse(n);e.push(i);}catch{}return e}function Uc(){let t=mi(),e=0;for(let s of t)cg(s.pid)||(Vn(s.pid),e++);return e}function cg(t){try{return process.kill(t,0),!0}catch{return false}}function fi(){try{return execSync(`osascript -e '
594
- tell application "System Events"
595
- set frontApp to first application process whose frontmost is true
596
- return bundle identifier of frontApp
597
- end tell
598
- '`,{encoding:"utf-8",timeout:3e3}).trim()||void 0}catch{return}}function yi(t){try{return execSync("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf-8",timeout:3e3}).trim()||void 0}catch{return}}function Uy(t){try{let e=process.pid,s=fi(),n=yi(t),i;try{let o=execSync(`ps -o ppid= -p ${e}`,{encoding:"utf-8",timeout:3e3}).trim();i=parseInt(o,10),isNaN(i)&&(i=void 0);}catch{}gi({pid:e,parentPid:i,projectDir:t,terminal:s,branch:n});let r=()=>{try{Vn(e);}catch{}};process.on("exit",r),process.on("SIGTERM",()=>{r(),process.exit(0);}),a.component("#conductor-loader").info("Auto-registered with Conductor",{pid:e});}catch{a.component("#conductor-loader").warn("Auto-registration with Conductor skipped (non-fatal)");}}function Bc(){return [{name:"paradigm_conductor_register",description:'Register this Claude Code session with Paradigm Conductor. Makes the session visible in the Conductor overlay for voice/gesture/gaze dispatch. Call this when the user says "/conduct" or wants to surface a session to Conductor. ~100 tokens.',inputSchema:{type:"object",properties:{label:{type:"string",description:'Human-readable label for this session (e.g., "backend refactor", "auth feature")'},terminal:{type:"string",description:'Terminal bundle ID (e.g., "com.mitchellh.ghostty"). Auto-detected if omitted.'}},required:[]},annotations:{title:"Register with Conductor",readOnlyHint:false,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"paradigm_conductor_unregister",description:"Unregister this Claude Code session from Paradigm Conductor. Removes it from the Conductor overlay. Call when ending a session or when the user wants to hide from Conductor. ~50 tokens.",inputSchema:{type:"object",properties:{},required:[]},annotations:{title:"Unregister from Conductor",readOnlyHint:false,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"paradigm_conductor_list",description:"List all Claude Code sessions currently registered with Paradigm Conductor. Shows PIDs, project dirs, and labels. ~150 tokens.",inputSchema:{type:"object",properties:{clean:{type:"boolean",description:"If true, clean up stale sessions (dead PIDs) before listing"}},required:[]},annotations:{title:"List Conductor sessions",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}}]}async function zc(t,e,s){switch(t){case "paradigm_conductor_register":{let n=process.pid,i=s.rootDir,r=e.terminal||fi(),o=yi(i),a;try{let d=execSync(`ps -o ppid= -p ${n}`,{encoding:"utf-8",timeout:3e3}).trim();a=parseInt(d,10),isNaN(a)&&(a=void 0);}catch{}let c=gi({pid:n,parentPid:a,projectDir:i,terminal:r,label:e.label,branch:o}),l=["\u2713 Registered with Conductor","",` PID: ${c.pid}`,` Project: ${c.projectDir}`];return c.branch&&l.push(` Branch: ${c.branch}`),c.label&&l.push(` Label: ${c.label}`),c.terminal&&l.push(` Terminal: ${c.terminal}`),l.push(` File: ~/.conductor/sessions/${c.pid}.json`),l.push(""),l.push("This session is now visible in Paradigm Conductor."),l.push("Conductor will auto-discover it via the registration file."),{text:l.join(`
599
- `),handled:true}}case "paradigm_conductor_unregister":{let n=process.pid;return Vn(n)?{text:`\u2713 Unregistered from Conductor (PID ${n}).
600
- This session is no longer visible in the Conductor overlay.`,handled:true}:{text:`Session (PID ${n}) was not registered with Conductor.`,handled:true}}case "paradigm_conductor_list":{e.clean&&Uc()>0;let n=mi();if(n.length===0)return {text:`No sessions registered with Conductor.
601
- Use paradigm_conductor_register or /conduct to register.`,handled:true};let i=[`${n.length} session(s) registered with Conductor:
602
- `];for(let r of n){let o=[` PID ${r.pid}`];r.label&&o.push(`"${r.label}"`),o.push(`\u2014 ${r.projectDir}`),r.branch&&o.push(`(${r.branch})`),i.push(o.join(" "));}return e.clean&&i.push(`
603
- (Stale sessions cleaned)`),{text:i.join(`
604
- `),handled:true}}default:return {text:"",handled:false}}}function Vc(){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 Kc(t,e,s){let n=n$2(s.rootDir);switch(n||(n=j$4(s.rootDir)),t){case "paradigm_symphony_peek":{let i=e.status;o$3(n.id,i);let{hasNew:r}=s$2(n.id),o=r?N("pending").length:0;return {handled:true,text:JSON.stringify(r?{hasNew:true,pendingFileRequests:o,action:"call paradigm_symphony_poll to read"}:{hasNew:false})}}case "paradigm_symphony_poll":{m$2(),S();let i=e.status;o$3(n.id,i);let r=v$2(n.id);if(r.length>0){let c=r[r.length-1].id;z$2(n.id,c),t$2(n.id);}B$1(n.id);let o=N("pending");return r.length===0&&o.length===0?{handled:true,text:JSON.stringify({messages:0,note:"No new notes. Score is quiet.",identity:n.id})}:{handled:true,text:dg(r,o)}}case "paradigm_symphony_send":{let i=e.intent,r=e.text,o=e.parentId,a=e.threadRoot,c=e.recipients,l=e.symbols,d=e.diff,p=e.decision,u=false;if(!a&&!o){let f=r.length>60?r.slice(0,60)+"...":r;a=C$1(f,zt(n)).id,u=true;}let g;if(c&&c.length>0){let f=l$2();g=c.map(b=>{let h=f.find(w=>w.id===b);return h?zt(h):{id:b,name:b,type:"agent"}});}let m=I({sender:zt(n),recipients:g,intent:i,text:r,parentId:o,threadRoot:a,symbols:l,diff:d,decision:p}),y=J(m);if(fg(m).catch(()=>{}),u&&a){({timestamp:m.timestamp,sender:m.sender,content:{text:`Thread created: ${m.content.text.slice(0,60)}`}});fetch(`${hi}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:"thread:created",category:"lifecycle",timestamp:m.timestamp,scopeValue:a,service:m.sender.project||"symphony",severity:"info",data:{topic:m.content.text.slice(0,60),initiator:m.sender.name,threadId:a}})}).catch(()=>{});}return {handled:true,text:JSON.stringify({sent:true,messageId:m.id,threadId:a,threadCreated:u,deliveredTo:y,intent:i})}}case "paradigm_symphony_status":{m$2();let i=l$2(),r=E$2("active"),o=v$2(n.id),a=N("pending"),c=[];try{let{loadPeers:l}=await import('./symphony-peers-U4KHMKGI.js');c=l().filter(p=>!p.revoked).map(p=>({id:p.id,address:p.address,agents:p.agents?.length??0,lastSeen:p.lastSeen}));}catch{}return {handled:true,text:JSON.stringify({identity:{id:n.id,project:n.project,role:n.role},agents:i.map(l=>({id:l.id,name:l.name,project:l.project,role:l.role,status:q$3(l)?"asleep":"awake",lastPoll:l.lastPoll,statusBlurb:l.statusBlurb})),peers:c,activeThreads:r.map(l=>({id:l.id,topic:l.topic,participants:l.participants.length,messageCount:l.messageCount,lastActivity:l.lastActivity})),unreadCount:o.length,pendingFileRequests:a.length},null,2)}}case "paradigm_symphony_thread":{let i=e.threadId,r=e.depth||50,o=D$1(i);if(!o)return {handled:true,text:JSON.stringify({error:`Thread not found: ${i}`})};let a=H$1(i).slice(0,r),c=[],l=new Set,d=new Set;for(let p of a){p.content.decision&&c.push(p.content.decision),p.intent==="decision"&&p.content.text&&c.push(p.content.text);for(let u of p.symbols)l.add(u);if(p.attachments)for(let u of p.attachments)u.type==="file"&&d.add(u.name);}return {handled:true,text:JSON.stringify({thread:{id:o.id,topic:o.topic,status:o.status,createdAt:o.createdAt,decision:o.decision},participants:o.participants,messages:a.map(p=>({id:p.id,sender:p.sender.name,intent:p.intent,text:p.content.text,timestamp:p.timestamp,symbols:p.symbols,hasDiff:!!p.content.diff,hasDecision:!!p.content.decision})),decisions:c,symbolsDiscussed:[...l],filesReferenced:[...d]},null,2)}}case "paradigm_symphony_request_file":{let i=e.filePath,r=e.from,o=e.reason,a=e.snippet,c=K();if(Q(i,c))return {handled:true,text:JSON.stringify({error:`File path "${i}" is on the hard-deny list and cannot be requested.`,deniedPatterns:c.defaults.neverApprove})};let l=L({filePath:i,requester:zt(n),reason:o,snippet:a,threadRoot:void 0}),d=I({sender:zt(n),recipients:[{id:r,name:r,type:"agent"}],intent:"fileRequest",text:`Requesting file: ${i}
605
- Reason: ${o}${a?`
606
- Snippet: ${a}`:""}`,symbols:[]});return J(d),{handled:true,text:JSON.stringify({requestId:l.request.requestId,status:"pending",filePath:i,from:r,message:`File request created. The owning agent's human must approve via "paradigm symphony approve ${l.request.requestId}" or "paradigm_symphony_approve_file".`})}}case "paradigm_symphony_approve_file":{let i=e.requestId,r=e.action,o=e.reason;if(r==="deny"){let l=P(i,o);return {handled:true,text:JSON.stringify({success:l,requestId:i,action:"denied",reason:o||"No reason provided"})}}let a=r==="approve-redacted",c=O(i,s.rootDir,a);return c.success?{handled:true,text:JSON.stringify({success:true,requestId:i,action:a?"approved-redacted":"approved",filePath:c.delivery?.filePath,size:c.delivery?.size,hash:c.delivery?.hash})}:{handled:true,text:JSON.stringify({success:false,requestId:i,error:c.error})}}default:return {handled:false,text:""}}}function zt(t){return {id:t.id,name:t.name,type:t.type||"agent",project:t.project,role:t.role}}function dg(t,e){let s=[],n=new Map;for(let i of t){let r=i.threadRoot||"direct";n.has(r)||n.set(r,[]),n.get(r).push(i);}for(let[i,r]of n){let o=i;if(i!=="direct"){let a=D$1(i);a&&(o=a.topic);}s.push(`## Symphony: ${r.length} new note${r.length!==1?"s":""} in "${o}"
607
- `);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 ${ug(c.intent)} (${l})`),s.push(`> ${c.content.text.split(`
608
- `).join(`
609
- > `)}`),c.symbols.length>0&&s.push(`> Symbols: ${c.symbols.join(", ")}`),c.content.diff&&s.push(`
610
- \`\`\`diff
611
- ${c.content.diff}
612
- \`\`\``),c.content.decision&&s.push(`
613
- **Decision:** ${c.content.decision}`);let p=pg(c);p&&s.push(`
614
- **Suggested action:** ${p}`),s.push("");}}if(e.length>0){s.push(`## Pending File Requests (${e.length})
615
- `);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(`
616
- `)}function pg(t){switch(t.intent){case "question":return 'Reply with paradigm_symphony_send using intent "context" or "clarification"';case "proposal":return 'Reply with intent "approval" or "rejection"';case "fileRequest":return "Use paradigm_symphony_approve_file to approve or deny";case "handoff":return "Review handoff context and continue the work";case "alert":return 'Investigate the alert and reply with intent "action"';case "verification":return 'Confirm with intent "approval" or clarify with "clarification"';default:return null}}function ug(t){return t.charAt(0).toUpperCase()+t.slice(1)}var hi="http://localhost:3838",Yc=false;function gg(t){switch(t){case "question":return "note:question";case "context":return "note:context";case "clarification":return "note:clarification";case "proposal":return "note:proposal";case "verification":return "note:verification";case "action":return "note:action";case "decision":return "note:decision";case "alert":return "note:alert";case "approval":return "note:approval";case "rejection":return "note:rejection";case "reference":return "note:reference";case "handoff":return "note:handoff";case "fileRequest":return "file:requested";case "fileApproved":return "file:approved";case "fileDenied":return "file:denied";case "fileDelivery":return "file:delivered";default:return "note:context"}}function mg(t){if(t.startsWith("note:")){let e=t.split(":")[1];if(["question","context","clarification","verification","reference"].includes(e))return "dialogue";if(["proposal","action"].includes(e))return "action";if(["decision","approval","rejection"].includes(e))return "outcome";if(e==="alert")return "system";if(e==="handoff")return "lifecycle"}return t.startsWith("thread:")||t.startsWith("participant:")?"lifecycle":t.startsWith("file:")?"transfer":"dialogue"}async function fg(t){try{Yc||(await fetch(`${hi}/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(()=>{}),Yc=!0);let e=gg(t.intent),s=mg(e);await fetch(`${hi}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:e,category:s,timestamp:t.timestamp,scopeValue:t.threadRoot||t.id,service:t.sender.project||"symphony",severity:s==="system"?"error":s==="outcome"?"warn":"info",parentEventId:t.parentId,data:{sender:t.sender.name,senderRole:t.sender.role||"core",text:t.content.text,symbols:t.symbols,diff:t.content.diff,decision:t.content.decision,parentId:t.parentId,threadId:t.threadRoot}})});}catch{}}function Qc(){let t=process.env.PARADIGM_AUTHOR;if(t)return bi(t);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return bi(e)}catch{}try{let e=wa.userInfo().username;if(e)return bi(e)}catch{}return "unknown"}function bi(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function Xc(){return new Date().toISOString().slice(0,10)}function yt(t,e){let s=[];try{s=J$1(t);}catch{}if(e){let c=s.find(l=>l.manifest.id===e);if(c)return {packId:c.manifest.id,packRoot:c.rootDir,packs:s}}let n=s.find(c=>c.manifest.tenant_kind==="project");if(n)return {packId:n.manifest.id,packRoot:n.rootDir,packs:s};let i=s.find(c=>c.manifest.tenant_kind==="first-party");if(i)return {packId:i.manifest.id,packRoot:i.rootDir,packs:s};let r=L$1(t);return {packId:M$1(r)?.id??"project",packRoot:r,packs:s}}function hg(t){let e=["notes","policies","quizzes","paths"];for(let s of ["content","src/content"]){let n=H.join(t,s);if(!E.existsSync(n))continue;let i=0;for(let r of e){let o=H.join(n,r);if(E.existsSync(o))try{i+=E.readdirSync(o).filter(a=>a.endsWith(".md")||a.endsWith(".yaml")).length;}catch{}}if(i>0)return i}return 0}function el(){return [{name:"paradigm_university_search",description:"Search university content by type, tag, difficulty, or symbol. v6.0: result ids are <pack-id>:<entry-id> (minor-breaking). ~150 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["note","policy","guide","runbook","quiz","path"],description:"Filter by content type"},tag:{type:"string",description:"Filter by tag prefix"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"],description:"Filter by difficulty level"},symbol:{type:"string",description:'Filter by Paradigm symbol (e.g., "#api-gateway")'},query:{type:"string",description:"Free-text search in title and tags"},category:{type:"string",description:'Filter by category ID (e.g., "paradigm-core", "extracurricular")'},track:{type:"string",enum:["core","extracurricular"],description:"Filter by track"},pack:{type:"string",description:"v6.0: target a specific content pack by id (default: project pack if present, else first-party)"},discipline:{type:"string",description:"v6.0: filter by discipline sub-pack name"},limit:{type:"number",description:"Maximum results (default: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_get",description:"Fetch a content item by ID. Accepts bare id or <pack-id>:<entry-id>. Returns full content (body for notes/policies, questions for quizzes). ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID: bare (N-foo) or qualified (paradigm:N-foo)"},pack:{type:"string",description:"v6.0: disambiguate a bare id against a specific pack (optional)"}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_create",description:"Create a new university content item (note, policy, quiz, or path). v6.0: honors optional pack selector. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["note","policy","guide","runbook","quiz","path"],description:"Content type to create"},title:{type:"string",description:"Content title"},body:{type:"string",description:"Markdown body for notes/policies. Quiz/path YAML content for those types."},tags:{type:"array",items:{type:"string"},description:"Tags for classification"},symbols:{type:"array",items:{type:"string"},description:"Paradigm symbols referenced by this content"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"],description:"Difficulty level (default: beginner)"},estimatedMinutes:{type:"number",description:"Estimated reading/completion time in minutes"},prerequisites:{type:"array",items:{type:"string"},description:"IDs of prerequisite content items"},category:{type:"string",description:"Category ID for the content (default: project defaultCategory)"},pack:{type:"string",description:"v6.0: target a specific pack by id (default: project pack)"},passThreshold:{type:"number",description:"For quizzes: pass threshold 0.0-1.0 (default: 0.7)"},questions:{type:"array",description:"For quizzes: array of {id, question, choices: {A:..., B:...}, correct, explanation?}"},ordered:{type:"boolean",description:"For learning paths: whether steps must be completed in order"},steps:{type:"array",description:"For learning paths: array of {content, required, passRequired?, note?}"}},required:["type","title"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_university_update",description:"Update an existing content item. id accepts bare or <pack-id>:<entry-id>. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID to update (bare or qualified)"},pack:{type:"string",description:"v6.0: disambiguate a bare id against a specific pack (optional)"},title:{type:"string",description:"New title"},body:{type:"string",description:"New body content"},tags:{type:"array",items:{type:"string"},description:"New tags"},symbols:{type:"array",items:{type:"string"},description:"New symbols"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"]},estimatedMinutes:{type:"number"},category:{type:"string",description:"Category ID for the content"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_university_onboard",description:"Get recommended onboarding sequence. v6.0: honors optional pack selector. ~200 tokens.",inputSchema:{type:"object",properties:{student:{type:"string",description:"Student name to check completion (auto-resolved if omitted)"},pack:{type:"string",description:"v6.0: target a specific pack (default: project pack)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_validate",description:"Validate content integrity. v6.0: honors optional pack selector. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID to validate (bare or qualified; validates all if omitted)"},pack:{type:"string",description:"v6.0: target a specific pack (default: all packs)"},deep:{type:"boolean",description:"Enable deep cross-reference checks against scan-index (default: false)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_pack_list",description:"v6.0: List discovered content packs with manifest metadata. ~200 tokens.",inputSchema:{type:"object",properties:{tenant_kind:{type:"string",enum:["first-party","project","external"],description:"Filter by tenant kind"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function tl(t,e,s){if(t==="paradigm_university_pack_list"){let n=e.tenant_kind,i=[];try{i=J$1(s.rootDir);}catch{i=[];}let o$1={packs:(n?i.filter(c=>c.manifest.tenant_kind===n):i).map(c=>({id:c.manifest.id,name:c.manifest.name,version:c.manifest.version,tenant_kind:c.manifest.tenant_kind,...c.manifest.disciplines&&c.manifest.disciplines.length>0?{discipline:c.manifest.disciplines[0]}:{},entry_count:hg(c.rootDir),path:c.rootDir}))},a=JSON.stringify(o$1,null,2);return o(a.length,t),{handled:true,text:a}}if(t==="paradigm_university_search"){let n=e.pack,{packId:i}=yt(s.rootDir,n),r=U(s.rootDir,{type:e.type,tag:e.tag,difficulty:e.difficulty,symbol:e.symbol,query:e.query,category:e.category,track:e.track,limit:e.limit}),o$1=JSON.stringify({count:r.length,pack:i,results:r.map(a=>({id:`${i}:${a.id}`,title:a.title,type:a.type,difficulty:a.difficulty,tags:a.tags,symbols:a.symbols}))},null,2);return o(o$1.length,t),{handled:true,text:o$1}}if(t==="paradigm_university_get"){let n=e.id;if(!n)return {handled:true,text:JSON.stringify({error:"id is required"})};let i=e.pack,{packId:r,packRoot:o$1}=yt(s.rootDir,i),a;try{a=K$1(n,{activePack:r}).entryId;}catch{a=n;}let c=O$1(s.rootDir,a,o$1);if(c){let u=JSON.stringify({id:c.frontmatter.id,title:c.frontmatter.title,type:c.frontmatter.type,author:c.frontmatter.author,created:c.frontmatter.created,updated:c.frontmatter.updated,tags:c.frontmatter.tags,symbols:c.frontmatter.symbols,difficulty:c.frontmatter.difficulty,prerequisites:c.frontmatter.prerequisites,body:c.body},null,2);return o(u.length,t),{handled:true,text:u}}let l=Q$1(s.rootDir,a,o$1);if(l){let u=JSON.stringify(l,null,2);return o(u.length,t),{handled:true,text:u}}let d=S$1(s.rootDir,a,o$1);if(d){let u=JSON.stringify(d,null,2);return o(u.length,t),{handled:true,text:u}}let p=JSON.stringify({error:`Content "${n}" not found`});return o(p.length,t),{handled:true,text:p}}if(t==="paradigm_university_create"){let n=e.type,i=e.title;if(!n||!i)return {handled:true,text:JSON.stringify({error:"type and title are required"})};let r=e.pack,{packRoot:o$1}=yt(s.rootDir,r),a=Qc(),c=Xc(),l=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40);if(n==="quiz"){let y=`Q-${l}`,f={id:y,title:i,description:e.body||"",author:a,created:c,updated:c,tags:e.tags||[],symbols:e.symbols||[],difficulty:e.difficulty||"beginner",estimatedMinutes:e.estimatedMinutes,passThreshold:e.passThreshold??.7,questions:e.questions||[],...e.category?{category:e.category}:{}};R(s.rootDir,f,o$1),V(s.rootDir);let b=JSON.stringify({created:y,type:"quiz",file:`content/quizzes/${y}.yaml`},null,2);return o(b.length,t),{handled:true,text:b}}if(n==="path"){let y=`LP-${l}`,f={id:y,title:i,description:e.body||"",author:a,created:c,updated:c,tags:e.tags||[],ordered:e.ordered??true,steps:e.steps||[],...e.category?{category:e.category}:{}};T(s.rootDir,f,o$1),V(s.rootDir);let b=JSON.stringify({created:y,type:"path",file:`content/paths/${y}.yaml`},null,2);return o(b.length,t),{handled:true,text:b}}let p=`${n==="policy"?"P":"N"}-${l}`,u={id:p,title:i,type:n,author:a,created:c,updated:c,tags:e.tags||[],symbols:e.symbols||[],difficulty:e.difficulty||"beginner",estimatedMinutes:e.estimatedMinutes,prerequisites:e.prerequisites||[],...e.category?{category:e.category}:{}};P$1(s.rootDir,u,e.body||"",o$1),V(s.rootDir);let m=JSON.stringify({created:p,type:n,file:`content/${n==="policy"?"policies":"notes"}/${p}.md`},null,2);return o(m.length,t),{handled:true,text:m}}if(t==="paradigm_university_update"){let n=e.id;if(!n)return {handled:true,text:JSON.stringify({error:"id is required"})};let i=e.pack,{packId:r,packRoot:o$1}=yt(s.rootDir,i),a;try{a=K$1(n,{activePack:r}).entryId;}catch{a=n;}let c=Xc(),l=O$1(s.rootDir,a,o$1);if(l){let g={...l.frontmatter};e.title&&(g.title=e.title),e.tags&&(g.tags=e.tags),e.symbols&&(g.symbols=e.symbols),e.difficulty&&(g.difficulty=e.difficulty),e.estimatedMinutes!==void 0&&(g.estimatedMinutes=e.estimatedMinutes),e.category!==void 0&&(g.category=e.category),g.updated=c;let m=e.body??l.body;P$1(s.rootDir,g,m,o$1),V(s.rootDir);let y=JSON.stringify({updated:a,type:g.type},null,2);return o(y.length,t),{handled:true,text:y}}let d=Q$1(s.rootDir,a,o$1);if(d){e.title&&(d.title=e.title),e.tags&&(d.tags=e.tags),e.symbols&&(d.symbols=e.symbols),e.difficulty&&(d.difficulty=e.difficulty),e.category!==void 0&&(d.category=e.category),d.updated=c,R(s.rootDir,d,o$1),V(s.rootDir);let g=JSON.stringify({updated:a,type:"quiz"},null,2);return o(g.length,t),{handled:true,text:g}}let p=S$1(s.rootDir,a,o$1);if(p){e.title&&(p.title=e.title),e.tags&&(p.tags=e.tags),e.category!==void 0&&(p.category=e.category),p.updated=c,T(s.rootDir,p,o$1),V(s.rootDir);let g=JSON.stringify({updated:a,type:"path"},null,2);return o(g.length,t),{handled:true,text:g}}let u=JSON.stringify({error:`Content "${n}" not found`});return o(u.length,t),{handled:true,text:u}}if(t==="paradigm_university_onboard"){let n=e.student||Qc(),i=e.pack,{packId:r}=yt(s.rootDir,i),o$1=N$1(s.rootDir),a=Y$1(s.rootDir,n),c=JSON.stringify({university:o$1.branding.name,pack:r,student:n,...a},null,2);return o(c.length,t),{handled:true,text:c}}if(t==="paradigm_university_validate"){let n=e.pack,{packId:i}=yt(s.rootDir,n),r=e.id,o$1=r;if(r)try{o$1=K$1(r,{activePack:i}).entryId;}catch{}let a=W$1(s.rootDir,{id:o$1,deep:e.deep}),c=JSON.stringify({pack:i,...a},null,2);return o(c.length,t),{handled:true,text:c}}return {handled:false,text:""}}function bg(t){try{let e=H.join(t,".paradigm","config.yaml");if(E.existsSync(e)){let n=Te.load(E.readFileSync(e,"utf-8")).platform;if(n?.port&&typeof n.port=="number")return n.port}}catch{}return 3850}function wg(t){try{let e=H.join(t,".paradigm","config.yaml");if(E.existsSync(e)){let s=Te.load(E.readFileSync(e,"utf-8")),n=s.project||H.basename(t),i=s.role||"core";return `${n}/${i}`}}catch{}return `${H.basename(t)}/core`}async function wt(t,e,s){let n=bg(t),i=wg(t),r=`http://localhost:${n}/api/platform/agent-command`;try{let o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:e,agentId:i,payload:s}),signal:AbortSignal.timeout(5e3)});if(!o.ok){let c=await o.text();return {ok:!1,error:`HTTP ${o.status}: ${c}`}}return {ok:!0,data:await o.json()}}catch(o){return {ok:false,error:`Platform server unreachable (${o instanceof Error?o.message:String(o)}). Is \`paradigm serve\` running?`}}}function nl(){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 sl(t,e,s){switch(t){case "paradigm_platform_navigate":{let n=await wt(s.projectDir,"navigate",{section:e.section,symbol:e.symbol,loreId:e.loreId});if(!n.ok)return {handled:true,text:`**Navigate failed:** ${n.error}`};let i=n.data;if(i.navigated){let r=[];i.section&&r.push(`section: **${i.section}**`),i.symbol&&r.push(`symbol: **${i.symbol}**`);let o=i.userActive?" (user was active \u2014 shown as prompt)":"";return {handled:true,text:`Navigated to ${r.join(", ")}${o}`}}return {handled:true,text:`Navigation skipped: ${i.reason}`}}case "paradigm_platform_highlight":{let n=await wt(s.projectDir,"highlight",{symbols:e.symbols,color:e.color,duration:e.duration,pulse:e.pulse,label:e.label});if(!n.ok)return {handled:true,text:`**Highlight failed:** ${n.error}`};let i=n.data;return i.highlighted?{handled:true,text:`Highlighted **${i.count}** symbol(s)${e.label?` with label "${e.label}"`:""}`}:{handled:true,text:`Highlight skipped: ${i.reason}`}}case "paradigm_platform_annotate":{let n=await wt(s.projectDir,"annotate",{type:e.type,message:e.message,symbol:e.symbol,severity:e.severity,duration:e.duration});if(!n.ok)return {handled:true,text:`**Annotate failed:** ${n.error}`};let i=n.data;return i.annotated?{handled:true,text:`Created ${e.type} annotation: "${e.message}"`}:{handled:true,text:`Annotation skipped: ${i.reason}`}}case "paradigm_platform_observe":{let n=await wt(s.projectDir,"observe",{detail:e.detail});if(!n.ok)return {handled:true,text:`**Observe failed:** ${n.error}`};let i=n.data,r=i.state,o=[`## Platform UI State
617
- `];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(`
618
- ### 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(`
619
- ### Active Highlights: ${c.length}`),l?.length&&o.push(`
620
- ### Active Annotations: ${l.length}`);}return {handled:true,text:o.join(`
621
- `)}}case "paradigm_platform_clear":{let n=await wt(s.projectDir,"clear",{target:e.target});return n.ok?{handled:true,text:`Cleared ${n.data.target} agent effects`}:{handled:true,text:`**Clear failed:** ${n.error}`}}default:return {handled:false,text:""}}}z();function il(){return [{name:"paradigm_agent_list",description:"List all agent identity profiles with top expertise areas. Shows agents from both global (~/.paradigm/agents/) and project (.paradigm/agents/) scopes. Returns profile summaries with personality and top symbols. ~150 tokens.",inputSchema:{type:"object",properties:{scope:{type:"string",enum:["all","global","project"],description:"Filter by scope (default: all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_expertise",description:"Find which agents are best qualified to work on a specific symbol. Returns agents ranked by confidence score from their expertise history. Use for symbol-to-agent routing. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to query (e.g., "#auth-middleware", "$checkout-flow")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns only top agent (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_get",description:"Get full agent profile including personality, expertise table, transferable patterns, and per-project contexts. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID or nickname (e.g., "architect", "Apex", "Jinx")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_bench",description:"Bench an agent \u2014 Maestro will skip this agent during orchestration and nomination scoring. Use when an agent is noisy or unhelpful. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to bench (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_agent_activate",description:"Activate a benched agent \u2014 restore it to active Maestro orchestration. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to activate (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function rl(t,e,s){switch(t){case "paradigm_agent_list":{let n=i$3(s.rootDir),i=b$8(s.rootDir);if(n.length===0)return {handled:true,text:JSON.stringify({count:0,agents:[],note:"No .agent profiles found. Create one with `paradigm agent create <id> --global` or via paradigm_agent_create."},null,2)};let r=i?n.filter(l=>i.includes(l.id)):n,o=i?n.length-r.length:0,a=i$4(s.rootDir),c=new Map(a.map(l=>[l.id,l]));return {handled:true,text:JSON.stringify({count:r.length,totalAvailable:n.length,...i?{rosterActive:true,inactiveCount:o}:{rosterActive:false},agents:r.map(l=>{let d=c.get(l.id);return {id:l.id,role:l.role,nickname:l.nickname,personality:l.personality,...d?{lastSession:d.lastSession?.summary?.slice(0,100),lastSessionAge:d.lastSession?.date,pendingWork:d.pendingWork?.length||0,sessionsOnProject:d.sessionsOnProject||0}:{},topExpertise:(l.expertise||[]).sort((p,u)=>u.confidence-p.confidence).slice(0,5).map(p=>({symbol:p.symbol,confidence:parseFloat(p.confidence.toFixed(2)),sessions:p.sessions})),projectContexts:Object.keys(l.contexts||{}),transferableCount:(l.transferable||[]).length,...l.attention?.threshold!=null?{threshold:l.attention.threshold}:{}}})},null,2)}}case "paradigm_agent_expertise":{let n=e.symbol,i=e.response_format,r=l$3(s.rootDir,n);return i==="concise"?{handled:true,text:JSON.stringify({symbol:n,topAgent:r.length>0?{id:r[0].agentId,confidence:parseFloat(r[0].entry.confidence.toFixed(2))}:null},null,2)}:{handled:true,text:JSON.stringify({symbol:n,agents:r.map(o=>({agentId:o.agentId,confidence:parseFloat(o.entry.confidence.toFixed(2)),sessions:o.entry.sessions,lastTouch:o.entry.lastTouch})),count:r.length,...r.length===0?{note:`No agents have recorded expertise on ${n}. Run \`paradigm agent sync\` to bootstrap from lore history.`}:{}},null,2)}}case "paradigm_agent_get":{let n=e.id,i=h$5(s.rootDir,n);if(!i){let o=i$3(s.rootDir),a=n.toLowerCase(),c=o.filter(l=>l.nickname?.toLowerCase().includes(a)||l.id.includes(a));return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found by ID or nickname`,...c.length>0?{didYouMean:c.map(l=>({id:l.id,nickname:l.nickname}))}:{suggestion:`Create with \`paradigm agent create ${n} --global\``}},null,2)}}let r=y$2(i);return {handled:true,text:JSON.stringify({id:i.id,role:i.role,description:i.description,version:i.version,personality:i.personality,expertise:(i.expertise||[]).sort((o,a)=>a.confidence-o.confidence).map(o=>({symbol:o.symbol,confidence:parseFloat(o.confidence.toFixed(2)),sessions:o.sessions,lastTouch:o.lastTouch})),transferable:(i.transferable||[]).map(o=>({id:o.id,description:o.description,learnedIn:o.learnedIn,appliedIn:o.appliedIn,successRate:o.successRate})),contexts:i.contexts,created:i.created,updated:i.updated,...i.permissions?{permissions:i.permissions}:{},integrity:r},null,2)}}case "paradigm_agent_bench":{let n=e.id,i=h$5(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found`},null,2)};let r=i.id,o=b$8(s.rootDir);return o?o=o.filter(a=>a!==r):o=e$6().filter(a=>a!==r),d$7(s.rootDir,o),{handled:true,text:JSON.stringify({id:r,...i.nickname?{nickname:i.nickname}:{},removedFromRoster:true,rosterCount:o.length,note:`${i.nickname||r} (${r}) removed from this project's roster. Still available globally.`},null,2)}}case "paradigm_agent_activate":{let n=e.id,i=h$5(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found`},null,2)};let r=i.id,o=b$8(s.rootDir);return o&&(o.includes(r)||(o.push(r),d$7(s.rootDir,o))),{handled:true,text:JSON.stringify({id:r,...i.nickname?{nickname:i.nickname}:{},addedToRoster:true,rosterCount:o?.length??"all (no roster)",note:`${i.nickname||r} (${r}) is active on this project's roster.`},null,2)}}default:return {handled:false,text:""}}}var cl=H.join(".paradigm","authority.yaml");async function ol(t){let e=H.join(t,cl),s;try{s=await vt.readFile(e,"utf8");}catch(i){if(i.code==="ENOENT")return null;throw i}let n=Te.load(s);return n==null||typeof n!="object"?{version:"1.0",schema:"v0-experimental",claims:{}}:((!n.claims||typeof n.claims!="object")&&(n.claims={}),n)}async function al(t,e){let s=H.join(t,cl);await vt.mkdir(H.dirname(s),{recursive:true});let n=Te.dump(e,{lineWidth:100,sortKeys:false});await vt.writeFile(s,n,"utf8");}function ll(){return [{name:"paradigm_authority_claim",description:"Claim authority over a scope in .paradigm/authority.yaml. Idempotent on `scope` \u2014 re-claiming overwrites severity/claimant. Single-claimant-per-scope at v6.1. Severity vocab: advise|warn|block (policy stance, distinct from remediation severity). ~100 tokens.",inputSchema:{type:"object",properties:{claimant:{type:"string",description:'Archetype id (e.g., "compliance")'},scope:{type:"string",description:'Scope key (e.g., "aspect-coverage", "aspect-drift", "anchor-staleness")'},severity:{type:"string",enum:["advise","warn","block"],description:"Policy stance. Default: advise."}},required:["claimant","scope"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_authority_release",description:"Release authority over a scope. Removes the claim entry from .paradigm/authority.yaml. Succeeds on archetype-default-created scopes (user/agent can override defaults). ~80 tokens.",inputSchema:{type:"object",properties:{claimant:{type:"string",description:"Archetype id (used for audit; release is by scope key)"},scope:{type:"string",description:"Scope key to release"}},required:["claimant","scope"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function dl(t,e,s){if(t==="paradigm_authority_claim"){let n=e.claimant,i=e.scope,r=e.severity??"advise";if(!n||!i)return {handled:true,text:JSON.stringify({error:"Missing required field: claimant, scope"},null,2)};let o=new Date().toISOString(),a={claimant:n,severity:r,since:o,source:"explicit"},c=await ol(s.rootDir)??{version:"1.0",schema:"v0-experimental",claims:{}};return c.claims[i]=a,await al(s.rootDir,c),{handled:true,text:JSON.stringify({scope:i,claimant:n,severity:r,source:"explicit",since:o},null,2)}}if(t==="paradigm_authority_release"){let n=e.claimant,i=e.scope;if(!n||!i)return {handled:true,text:JSON.stringify({error:"Missing required field: claimant, scope"},null,2)};let r=await ol(s.rootDir);if(!r||!(i in r.claims))return {handled:true,text:JSON.stringify({scope:i,released:false,note:"no active claim on this scope"},null,2)};let o=r.claims[i].claimant;return delete r.claims[i],await al(s.rootDir,r),{handled:true,text:JSON.stringify({scope:i,released:true,previousClaimant:o},null,2)}}return {handled:false,text:""}}var pl=H.join(".paradigm","remediations");function vg(){return "rmd-"+Date.now().toString(36)}function gl(){return [{name:"paradigm_propose_block",description:"Author a soft-block (remediation) that the Stop hook will honor until resolved. Use when your archetype detects a condition the user should resolve before continuing (e.g., coverage drop, missing aspect, broken anchor). User can override via `paradigm override <id>` or PARADIGM_OVERRIDE env var. v6.1: only severity=guard hard-blocks; advise/auto-author are informational. ~150 tokens.",inputSchema:{type:"object",properties:{claimant:{type:"string",description:'Archetype id authoring this block (e.g., "compliance", "security"). REQUIRED \u2014 do not infer.'},severity:{type:"string",enum:["advise","auto-author","guard"],description:"Block intent for this event. v6.1: only `guard` hard-blocks; `advise`/`auto-author` are informational."},reason:{type:"string",description:"Free-text explanation surfaced to the user verbatim. Be specific (component name, file path)."},unblock_hint:{type:"string",description:"Plain-string remediation hint (v6.1; JSONLogic predicates ship v6.2). Tell the user how to resolve."},expires_at:{type:"string",description:"OPTIONAL ISO 8601 UTC timestamp. After this, Check 14 silently skips the remediation. Use for time-bounded conditions."},target:{type:"object",description:"OPTIONAL context: {file, symbol, line}.",properties:{file:{type:"string"},symbol:{type:"string"},line:{type:"number"}}}},required:["claimant","severity","reason","unblock_hint"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function ml(t,e,s){if(t!=="paradigm_propose_block")return {handled:false,text:""};let n=e.claimant,i=e.severity,r=e.reason,o=e.unblock_hint,a=e.expires_at,c=e.target;if(!n||!i||!r||!o)return {handled:true,text:JSON.stringify({error:"Missing required field. Required: claimant, severity, reason, unblock_hint."},null,2)};let l=vg(),d=new Date().toISOString(),p={id:l,claimant:n,severity:i,reason:r,unblock_hint:o,created:d};a&&(p.expires_at=a),c&&(c.file||c.symbol||c.line!=null)&&(p.target=c);let u=H.join(s.rootDir,pl);await vt.mkdir(u,{recursive:true});let g=H.join(u,`${l}.yaml`),m=Te.dump(p,{lineWidth:100,sortKeys:false});return await vt.writeFile(g,m,"utf8"),{handled:true,text:JSON.stringify({id:l,path:H.join(pl,`${l}.yaml`),claimant:n,severity:i,...a?{expires_at:a}:{},note:`Stop hook will ${i==="guard"?"block":"note"} on next run. User can clear with: paradigm override ${l}`},null,2)}}h();function fl(){return [{name:"paradigm_notebook_search",description:"Search agent notebook entries by concept, tag, or keyword. Notebooks are curated snippet libraries distilled from lore for reuse in orchestration. ~150 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:'Agent ID to search notebooks for (e.g., "architect", "builder")'},query:{type:"string",description:"Search query \u2014 matches concepts, tags, context, and snippet content"},concepts:{type:"array",items:{type:"string"},description:'Filter by concept tags (e.g., ["auth", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Filter by classification tags"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level (default: "detailed")'}},required:["agentId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_notebook_add",description:"Add a new entry to an agent's notebook. Use for curated, reusable snippets that should be available across sessions. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add notebook entry for"},context:{type:"string",description:"When to apply this snippet \u2014 the retrieval context"},snippet:{type:"string",description:"The reusable code/knowledge snippet"},concepts:{type:"array",items:{type:"string"},description:'Concept tags for retrieval (e.g., ["auth", "jwt", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Classification tags"},confidence:{type:"number",description:"Confidence score 0.0-1.0 (default: 0.7)"},scope:{type:"string",enum:["global","project"],description:'Where to store: global travels across projects (default: "global")'},parentId:{type:"string",description:"Optional: ID of the parent notebook entry this was derived from (soft provenance, no validation)"},lineageType:{type:"string",enum:["fix","derive","capture","promote"],description:"Optional: relationship to parent \u2014 fix (corrects parent), derive (modified from parent), capture (new observation), promote (promoted from lower confidence)"}},required:["agentId","context","snippet","concepts"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_notebook_promote",description:"Extract a lore entry into a notebook entry. Distills the lore into a reusable snippet with provenance linking. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add the promoted entry to"},loreEntryId:{type:"string",description:'Lore entry ID to promote (e.g., "L-2026-03-15-...")'},scope:{type:"string",enum:["global","project"],description:'Where to store (default: "global")'}},required:["agentId","loreEntryId"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function yl(t,e,s){switch(t){case "paradigm_notebook_search":{let n=e.agentId,i=e.query,r=e.concepts,o=e.tags,a=e.response_format,c;return i?c=b$9(n,i,s.rootDir):c=a$8(n,s.rootDir,{concepts:r,tags:o}),a==="concise"?{handled:true,text:JSON.stringify({agentId:n,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,concepts:l.concepts}))},null,2)}:{handled:true,text:JSON.stringify({agentId:n,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,snippet:l.snippet.length>500?l.snippet.slice(0,500)+"...":l.snippet,concepts:l.concepts,tags:l.tags,appliedCount:l.appliedCount,confidence:l.confidence,provenance:l.provenance}))},null,2)}}case "paradigm_notebook_add":{let n=e.agentId,i=e.context,r=e.snippet,o=e.concepts||[],a=e.tags||[],c=e.confidence??.7,l=e.scope||(s.rootDir?"project":"global"),d=e.parentId,p=e.lineageType,u=e.publishable,g=e.scope,m={context:i,snippet:r,provenance:{source:"manual",createdBy:n},confidence:c,concepts:o,tags:a,...g?{scope:g}:{},...u!==void 0?{publishable:u}:{},...d?{parentId:d}:{},...p?{lineageType:p}:{}},y=d$8(n,m,l,s.rootDir);return {handled:true,text:JSON.stringify({action:"notebook_add",id:y.entry.id,agentId:n,scope:l,filePath:y.filePath,concepts:y.entry.concepts,...d?{parentId:d}:{},...p?{lineageType:p}:{}},null,2)}}case "paradigm_notebook_promote":{let n=e.agentId,i=e.loreEntryId,r=e.scope||(s.rootDir?"project":"global"),o=await e$7(n,i,s.rootDir,r);return o?{handled:true,text:JSON.stringify({action:"notebook_promote",id:o.entry.id,agentId:n,loreEntryId:i,scope:r,publishScope:o.entry.scope,publishable:o.entry.publishable,filePath:o.filePath,concepts:o.entry.concepts,confidence:o.entry.confidence,note:o.entry.scope!=="generalizable"?`scope auto-classified as "${o.entry.scope}" \u2014 confirm or override with "nevr notebook audit"`:void 0},null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry "${i}" not found`,suggestion:"Check the lore entry ID with paradigm_lore_search"},null,2)}}default:return {handled:false,text:""}}}var kg=".paradigm/scan-index.json",Sg=".paradigm/flow-index.json",_g=".paradigm/config.yaml",xg="portal.yaml",Cg=".paradigm/university/index.yaml",oe={enabled:true,title:null,theme:"dark",customCss:null,customContent:"docs/",exclude:{tags:[],patterns:[]},sidebar:{collapsed:[]},output:".paradigm/docs-site"};function _t(t){let e=H.join(t,_g);if(!E.existsSync(e))return {...oe};try{let s=E.readFileSync(e,"utf8"),n=Te.load(s);if(!n||!n.docs)return {...oe};let i=n.docs;return {enabled:i.enabled??oe.enabled,title:i.title??oe.title,theme:i.theme??oe.theme,customCss:i.customCss??oe.customCss,customContent:i.customContent??oe.customContent,exclude:{tags:i.exclude?.tags??oe.exclude.tags,patterns:i.exclude?.patterns??oe.exclude.patterns},sidebar:{collapsed:i.sidebar?.collapsed??oe.sidebar.collapsed},output:i.output??oe.output}}catch{return {...oe}}}function Xn(t){let e=H.join(t,kg);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function Si(t){let e=H.join(t,Sg);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function Zn(t){let e=H.join(t,xg);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch{return null}}function bl(t){let e=H.join(t,Cg);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return Te.load(s)}catch{return null}}function wl(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:Te.load(e[1]),body:e[2].trim()}}catch{return null}}function vl(t){let e=new Map,s=[t.components,t.features,t.flows,t.state,t.gates,t.signals,t.aspects];for(let n of s)if(n)for(let[i,r]of Object.entries(n))e.set(i,r);return e}function Rg(t){return {components:"component",features:"component",flows:"flow",state:"component",gates:"gate",signals:"signal",aspects:"aspect"}[t]||"component"}function St(t,e){if(e.exclude.tags.length>0&&t.visualTags){for(let s of t.visualTags)if(e.exclude.tags.includes(s))return true}if(e.exclude.patterns.length>0&&t.path){for(let s of e.exclude.patterns)if(s.endsWith("*")){let n=s.slice(0,-1);if(t.path.includes(n))return true}else if(t.path.includes(s))return true}return false}function kl(t,e){let s=H.join(t,e);if(!E.existsSync(s))return [];let n=[];try{let i=E.readdirSync(s).filter(r=>r.endsWith(".md"));for(let r of i)try{let o=E.readFileSync(H.join(s,r),"utf8"),a=r.replace(/\.md$/,""),c=wl(o);c?n.push({slug:a,title:c.frontmatter.title||a,body:c.body,order:typeof c.frontmatter.order=="number"?c.frontmatter.order:void 0,description:c.frontmatter.description||void 0}):n.push({slug:a,title:a,body:o.trim()});}catch{}}catch{}return n.sort((i,r)=>i.order!=null&&r.order!=null?i.order-r.order:i.order!=null?-1:r.order!=null?1:i.title.localeCompare(r.title)),n}function Sl(t,e,s){let n=s||_t(t),i=H.join(t,n.customContent),r=H.join(i,`${e}.md`);if(!E.existsSync(r))return null;try{let o=E.readFileSync(r,"utf8"),a=wl(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(t,e){let s=e||_t(t),n=Xn(t),i=Si(t),r=Zn(t),o=kl(t,s.customContent),a=bl(t),c=n?.$meta?.project||H.basename(t),l=s.title||`${c} Docs`,d=[],p={},u=0;if(o.length>0&&d.push({id:"custom-pages",label:"Pages",collapsed:s.sidebar.collapsed.includes("custom-pages"),items:o.map(g=>({id:g.slug,label:g.title,kind:"custom",description:g.description}))}),a&&a.entries.length>0){let g=a.entries.filter(m=>(m.type==="note"||m.type==="policy")&&m.symbols.length>0);g.length>0&&d.push({id:"guides",label:"Guides",collapsed:s.sidebar.collapsed.includes("guides"),items:g.map(m=>({id:m.id,label:m.title,kind:"guide",description:void 0,badge:m.symbols.length>0?`${m.symbols.length} symbols`:void 0}))});}if(n){let g=Object.values(n.components||{}).filter(k=>!St(k,s));if(g.length>0){let k=new Map;for(let _ of g){let P=_.componentType||"other";k.has(P)||k.set(P,[]),k.get(P).push(_);}let C=[...k.entries()].sort((_,P)=>P[1].length-_[1].length).map(([_,P])=>({id:`components-${_}`,label:`${_.charAt(0).toUpperCase()+_.slice(1)} (${P.length})`,collapsed:s.sidebar.collapsed.includes(`components-${_}`),items:P.sort(($,R)=>$.name.localeCompare(R.name)).map($=>({id:$.id,label:$.name,kind:"component",description:$.description,badge:$.componentType}))}));d.push({id:"components",label:`Components (${g.length})`,collapsed:s.sidebar.collapsed.includes("components"),items:[],subgroups:C}),p.components=g.length,u+=g.length;}let m=Object.values(n.features||{}).filter(k=>!St(k,s));m.length>0&&(d.push({id:"features",label:`Features (${m.length})`,collapsed:s.sidebar.collapsed.includes("features"),items:m.sort((k,x)=>k.name.localeCompare(x.name)).map(k=>({id:k.id,label:k.name,kind:"component",description:k.description}))}),p.features=m.length,u+=m.length);let y=Object.values(n.flows||{}).filter(k=>!St(k,s)),f=new Set(y.map(k=>k.id)),b=[];if(i)for(let[k,x]of Object.entries(i.flows)){let C=k.replace(/^\$/,"");f.has(C)||b.push({id:C,label:x.name||C,kind:"flow",description:x.description});}let h=[...y.sort((k,x)=>k.name.localeCompare(x.name)).map(k=>({id:k.id,label:k.name,kind:"flow",description:k.description})),...b];h.length>0&&(d.push({id:"flows",label:`Flows (${h.length})`,collapsed:s.sidebar.collapsed.includes("flows"),items:h}),p.flows=h.length,u+=h.length);let w=Object.values(n.gates||{}).filter(k=>!St(k,s));w.length>0&&(d.push({id:"gates",label:`Gates (${w.length})`,collapsed:s.sidebar.collapsed.includes("gates"),items:w.sort((k,x)=>k.name.localeCompare(x.name)).map(k=>({id:k.id,label:k.name,kind:"gate",description:k.description}))}),p.gates=w.length,u+=w.length);let S=Object.values(n.signals||{}).filter(k=>!St(k,s));S.length>0&&(d.push({id:"signals",label:`Signals (${S.length})`,collapsed:s.sidebar.collapsed.includes("signals"),items:S.sort((k,x)=>k.name.localeCompare(x.name)).map(k=>({id:k.id,label:k.name,kind:"signal",description:k.description}))}),p.signals=S.length,u+=S.length);let v=Object.values(n.aspects||{}).filter(k=>!St(k,s));v.length>0&&(d.push({id:"aspects",label:`Aspects (${v.length})`,collapsed:s.sidebar.collapsed.includes("aspects"),items:v.sort((k,x)=>k.name.localeCompare(x.name)).map(k=>({id:k.id,label:k.name,kind:"aspect",description:k.description}))}),p.aspects=v.length,u+=v.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 xl(t,e){let s=Xn(t);if(!s)return null;let n=vl(s),i=n.get(e);if(!i)return null;let r=[];for(let[f,b]of n)f!==e&&b.related&&b.related.includes(i.symbol)&&r.push(b.symbol);let o=(i.related||[]).slice(),a=[],c=Si(t);if(c)for(let[f,b]of Object.entries(c.flows)){let h=(b.steps||[]).map(w=>w.symbol);(h.includes(i.symbol)||h.includes(`#${e}`))&&a.push({id:f.replace(/^\$/,""),name:b.name||f});}if(s.flows)for(let[f,b]of Object.entries(s.flows)){if(a.some(w=>w.id===f))continue;let h=(b.steps||[]).map(w=>w.symbol).filter(Boolean);(h.includes(i.symbol)||h.includes(`#${e}`))&&a.push({id:f,name:b.name});}let l=[],d=Zn(t);if(d&&i.category==="gates"){let f=Object.keys(d.gates||{}).find(b=>b.replace(/^\^/,"")===e);f&&l.push({id:f.replace(/^\^/,""),description:d.gates[f].description});}else if(d){let f=new Set((i.related||[]).filter(b=>b.startsWith("^")));for(let[b,h]of Object.entries(d.routes||{}))for(let w of h){let S=w.replace(/^\^/,"");if(f.has(w)||f.has(`^${S}`)){let v=d.gates[w]||d.gates[`^${S}`]||d.gates[S];v&&!l.some(k=>k.id===S)&&l.push({id:S,description:v.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=bl(t);if(g)for(let f of g.entries)f.symbols.includes(i.symbol)&&u.push({id:f.id,title:f.title});let m=i.parent||void 0,y=[];if(s.components)for(let f of Object.values(s.components))f.parent===i.symbol&&y.push(f.symbol);return {id:i.id,symbol:i.symbol,name:i.name,description:i.description||"",category:i.category||"components",componentType:i.componentType,tags:i.visualTags||[],path:i.path||"",related:i.related||[],referencedBy:r,references:o,flows:a,gates:l,aspects:p,guides:u,parent:m,children:y}}function Cl(t,e){let s=Si(t),n=Xn(t);if(s){let i=s.flows[`$${e}`]?`$${e}`:e,r=s.flows[i];if(r){let o=(r.steps||[]).map(c=>({type:c.type||"action",symbol:c.symbol||"",description:c.description})),a=n?.flows?.[e.replace(/^\$/,"")];return {id:e.replace(/^\$/,""),symbol:`$${e.replace(/^\$/,"")}`,name:r.name||e,description:r.description,trigger:r.trigger,steps:o,successSignal:r.successSignal,errorSignal:r.errorSignal,tags:a?.visualTags||[],path:a?.path||r.definedIn||""}}}if(n?.flows){let i=e.replace(/^\$/,""),r=n.flows[i];if(r){let o=(r.steps||[]).map(a=>({type:"action",symbol:a.symbol||"",description:a.action||a.name}));return {id:i,symbol:`$${i}`,name:r.name,description:r.description,steps:o,tags:r.visualTags||[],path:r.path||""}}}return null}function Rl(t){let e=Zn(t);if(!e)return {version:"0",gates:[],routes:[]};let s=new Map;for(let[r,o]of Object.entries(e.routes||{}))for(let a of o){let c=a.replace(/^\^/,"");s.has(c)||s.set(c,[]),s.get(c).push(r);}let n=Object.entries(e.gates||{}).map(([r,o])=>{let a=r.replace(/^\^/,"");return {symbol:`^${a}`,description:o.description,check:o.check,routes:s.get(a)||[]}}),i=Object.entries(e.routes||{}).map(([r,o])=>{let a=r.indexOf(" "),c=a>0?r.substring(0,a):"GET";return {route:a>0?r.substring(a+1):r,method:c,gates:o.map(d=>{let p=d.replace(/^\^/,""),u=e.gates[d]||e.gates[`^${p}`]||e.gates[p];return {symbol:`^${p}`,description:u?.description}})}});return {version:e.version||"1.0",gates:n,routes:i}}function Pl(t,e,s){let n=s||20,i=[],r=e.toLowerCase(),o=Xn(t);if(o){let d=vl(o);for(let[p,u]of d){let g=ki(u.name,u.description||"",u.visualTags||[],r);g>0&&i.push({id:u.id,kind:Rg(u.category),label:u.name,description:u.description||"",matchContext:hl(u.name,u.description||"",r),score:g});}}let a=_t(t),c=kl(t,a.customContent);for(let d of c){let p=d.body.substring(0,200),u=ki(d.title,p,[],r);u>0&&i.push({id:d.slug,kind:"custom",label:d.title,description:d.description||p.substring(0,100),matchContext:hl(d.title,d.body,r),score:u});}let l=Zn(t);if(l)for(let[d,p]of Object.entries(l.gates||{})){let u=d.replace(/^\^/,""),g=ki(u,p.description,[],r);g>0&&i.push({id:u,kind:"portal",label:`^${u}`,description:p.description,score:g});}return i.sort((d,p)=>p.score-d.score||d.label.localeCompare(p.label)),i.slice(0,n)}function ki(t,e,s,n){let i=t.toLowerCase(),r=e.toLowerCase();return i===n?1:i.startsWith(n)?.8:i.includes(n)?.6:r.includes(n)?.5:s.some(o=>o.toLowerCase().includes(n))?.3:0}function hl(t,e,s){let i=e.toLowerCase().indexOf(s);if(i<0)return t.toLowerCase().includes(s)?t:void 0;let r=Math.max(0,i-40),o=Math.min(e.length,i+s.length+40),a=e.substring(r,o).trim();return r>0&&(a=`...${a}`),o<e.length&&(a=`${a}...`),a}function jl(){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 Al(t,e,s){if(t==="paradigm_docs_manifest"){let n=_t(s.rootDir),i=_l(s.rootDir,n),r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}if(t==="paradigm_docs_page"){if(e.portal){let i=Rl(s.rootDir),r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}if(e.flow){let i=e.flow,r=Cl(s.rootDir,i);if(!r){let a=JSON.stringify({error:`Flow "${i}" not found`});return o(a.length,t),{handled:true,text:a}}let o$1=JSON.stringify(r,null,2);return o(o$1.length,t),{handled:true,text:o$1}}if(e.slug){let i=_t(s.rootDir),r=Sl(s.rootDir,e.slug,i);if(!r){let a=JSON.stringify({error:`Page "${e.slug}" not found`});return o(a.length,t),{handled:true,text:a}}let o$1=JSON.stringify(r,null,2);return o(o$1.length,t),{handled:true,text:o$1}}if(e.symbol){let i=xl(s.rootDir,e.symbol);if(!i){let o$1=JSON.stringify({error:`Symbol "${e.symbol}" not found`});return o(o$1.length,t),{handled:true,text:o$1}}let r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}let n=JSON.stringify({error:"Provide one of: symbol, flow, portal, or slug"});return o(n.length,t),{handled:true,text:n}}if(t==="paradigm_docs_search"){let n=e.query;if(!n)return {handled:true,text:JSON.stringify({error:"query is required"})};let i=Pl(s.rootDir,n,e.limit),r=JSON.stringify({count:i.length,results:i},null,2);return o(r.length,t),{handled:true,text:r}}return {handled:false,text:""}}g();e();function Tl(){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 Dl(t,e,s){let n=i=>JSON.stringify(i,null,2);switch(t){case "paradigm_work_log_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.summary,i,"work_log"),o=a$5(s.rootDir,{agent:e.agent,summary:r,outcome:e.outcome,task_ref:e.task_ref,files_modified:e.files_modified,symbols_touched:e.symbols_touched,next_steps:e.next_steps,blockers:e.blockers,duration_minutes:e.duration_minutes,commit:e.commit});return {text:n({recorded:true,id:o.id,timestamp:o.timestamp}),handled:true}}case "paradigm_work_log_search":{if(e.summary){let r=d$5(s.rootDir,7);return {text:n(r),handled:true}}let i=b$6(s.rootDir,{agent:e.agent,outcome:e.outcome,task_ref:e.task_ref,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,summary:r.summary,outcome:r.outcome,timestamp:r.timestamp,symbols_touched:r.symbols_touched,task_ref:r.task_ref}))}),handled:true}}case "paradigm_journal_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.insight,i,"learning_journal"),o=a$4(e.agent,{trigger:e.trigger,insight:r,project:e.project,transferable:e.transferable,confidence_before:e.confidence_before,confidence_after:e.confidence_after,pattern:e.pattern,linked_work_log:e.linked_work_log,tags:e.tags});return {text:n({recorded:true,id:o.id,agent:o.agent,timestamp:o.timestamp}),handled:true}}case "paradigm_journal_search":{if(e.stats&&e.agent){let r=e$4(e.agent);return {text:n(r),handled:true}}let i=e.agent?b$5(e.agent,{trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20}):d$4({trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,trigger:r.trigger,insight:r.insight.slice(0,200),project:r.project,transferable:r.transferable,timestamp:r.timestamp}))}),handled:true}}case "paradigm_decision_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.decision,i,"team_decisions"),{filtered:o}=d$3(e.rationale,i,"team_decisions"),a=a$2(s.rootDir,{title:e.title,decision:r,rationale:o,participants:e.participants,alternatives_considered:e.alternatives_considered,symbols_affected:e.symbols_affected,status:e.status||"active",tags:e.tags}),c=d$1(s.rootDir,a.id);return {text:n({recorded:true,id:a.id,title:a.title,timestamp:a.timestamp,...c?{companion_lore_id:c}:{}}),handled:true}}case "paradigm_decision_search":{if(e.summary){let r=h$4(s.rootDir);return {text:n(r),handled:true}}let i=e$3(s.rootDir,{status:e.status,participant:e.participant,symbol:e.symbol,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:i.length,entries:i.map(r=>({id:r.id,title:r.title,status:r.status,decision:r.decision.slice(0,200),participants:r.participants.map(o=>`${o.id} (${o.stance})`),symbols_affected:r.symbols_affected,timestamp:r.timestamp}))}),handled:true}}default:return {text:`Unknown streams tool: ${t}`,handled:false}}}v();b$2();z();g();q();function Ol(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function Pg(t){let e=Date.now(),s=t.match(/^(\d+)(m|h|d)$/);if(s){let n=parseInt(s[1],10),i=s[2],r=i==="m"?n*6e4:i==="h"?n*36e5:n*864e5;return new Date(e-r).toISOString()}return t}async function Il(t,e,s){let n=i=>JSON.stringify(i,null,2);switch(t){case "paradigm_ambient_nominations":{m$1(s.rootDir);let r=e.pending_only!==false,o=e.limit||20,a=i$2(s.rootDir,{agent:e.agent,urgency:e.urgency,pending_only:r,limit:o+20}),c=t$1(s.rootDir);a=u$1(a,c).slice(0,o);let l=H.join(s.rootDir,".paradigm/events/nominations.jsonl");if(E.existsSync(l))try{let p=E.readFileSync(l,"utf8"),u=new Set(a.map(m=>m.id)),g=p.trim().split(`
622
- `).map(m=>{try{let y=JSON.parse(m);return u.has(y.id)?(y.surfaced=!0,JSON.stringify(y)):m}catch{return m}});E.writeFileSync(l,g.join(`
623
- `)+`
624
- `,"utf8");}catch{}let d={count:a.length,nominations:a.map(p=>({id:p.id,agent:p.agent,urgency:p.urgency,type:p.type,brief:p.brief,relevance:p.relevance,timestamp:p.timestamp,engaged:p.engaged,response:p.response}))};if(e.include_debates){let u=j$3(s.rootDir).filter(g=>!g.resolution);d.debates=u.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),d.debate_count=u.length;}return {text:n(d),handled:true}}case "paradigm_ambient_events":{let i=e.since?Pg(e.since):void 0,r=e.limit||50,o=a$6(s.rootDir,{type:e.type,source:e.source,symbol:e.symbol,agent:e.agent,since:i,limit:r});return {text:n({count:o.length,events:o.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i=e.nomination_id,r=e.response,o=e.reason,a=k$1(s.rootDir,i,r,o);if(a)try{let{appendSessionWorkEntry:l,appendVerdictEntry:d}=await import('./session-work-log-MEJ33TYD.js'),u=i$2(s.rootDir,{limit:500}).find(m=>m.id===i),g={timestamp:new Date().toISOString(),type:"user-verdict",agent:u?.agent,nominationId:i,verdict:r,reason:o};l(s.rootDir,g),d(s.rootDir,g);}catch{}let c=false;return e.resolve_debate&&a&&(c=l$1(s.rootDir,e.resolve_debate,i,e.reason)),{text:n({engaged:a,nomination_id:i,response:r,debate_resolved:c||void 0}),handled:true}}case "paradigm_context_compose":{let i=e.agent,r=e.symbols||[],o=e.include_nominations!==false,a=e.include_decisions!==false,c=e.include_journal!==false,l=e.max_decisions||5,d=e.max_journal||5,p=f$2(s.rootDir,i);if(!p)return {text:n({error:`Agent profile not found: ${i}`}),handled:true};let u=[],g=p$1(p,r);if(g.trim()&&u.push(g),a){let m=e$3(s.rootDir,{status:"active",limit:l});if(m.length>0){u.push("## Recent Team Decisions");for(let y of m)u.push(`- **${y.title}**: ${y.decision.slice(0,150)}${y.decision.length>150?"...":""}`);u.push("");}}if(c){let m=b$5(i,{transferable:true,limit:d});if(m.length>0){u.push("## Transferable Insights");for(let y of m)u.push(`- [${y.trigger}] ${y.insight.slice(0,150)}${y.insight.length>150?"...":""}`);u.push("");}}if(o){let m=i$2(s.rootDir,{pending_only:true,limit:10});if(m.length>0){u.push("## Pending Nominations");for(let y of m)u.push(`- [${y.urgency}] ${y.brief}`);u.push("");}}return {text:n({agent:i,context:u.join(`
625
- `),sections_included:{profile:true,decisions:a,journal:c,nominations:o}}),handled:true}}case "paradigm_ambient_promote":{let i=e.agent,r=s$1(s.rootDir,i);return {text:n({agent:i,promoted:r.promoted,entries:r.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e.agent,r=e.dry_run===true,o=p(s.rootDir,i);if(r)return {text:n({agent:i,dry_run:true,stats:o,note:o.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(o.acceptRate*100).toFixed(0)}% \u2014 ${o.acceptRate>.8?"would lower threshold":o.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=o$1(s.rootDir,i);return {text:n({agent:i,...a,stats:o}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let i=q$2(s.rootDir);return {text:n(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:n(await Tg(s.rootDir,e)),handled:true};default:return {text:`Unknown ambient tool: ${t}`,handled:false}}}var jg={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function Ag(t){try{let e=H.join(t,".paradigm","config.yaml");if(E.existsSync(e)){let n=E.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(n)return n[1].trim()}}catch{}return H.basename(t)}async function Tg(t,e={}){let s=e.dry_run===true,n=Ag(t),i=e$8(t).filter(m=>m.verdict&&m.agent),r=b$a(t);if(i.length===0)return {sessionEntries:r.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:s,details:[]};let o=new Map;for(let m of i){let y=m.agent;o.has(y)||o.set(y,[]),o.get(y).push(m);}let a=r.filter(m=>m.type==="agent-contribution"),c=new Map;for(let m of a)m.agent&&(c.has(m.agent)||c.set(m.agent,[]),c.get(m.agent).push(m));let l=[],d={},p=0;for(let[m,y]of o){d[m]=0;let f=y.filter(v=>v.verdict==="accepted").length;y.filter(v=>v.verdict==="dismissed").length;y.filter(v=>v.verdict==="revised").length;let w=y.length,S=w>0?f/w:0;for(let v of y){let k=jg[v.verdict];if(!k)continue;let x=c.get(m)?.shift(),C=Dg(v,x,{acceptRate:S,total:w,accepted:f}),_=v.verdict==="accepted"?.85:v.verdict==="revised"?.6:.4,P={agent:m,verdict:v.verdict,trigger:k,insight:C,symbols:v.symbols};if(l.push(P),s)d[m]++,p++;else try{a$4(m,{trigger:k,insight:C,confidence_before:v.verdict==="accepted"?.7:.8,confidence_after:_,project:n,transferable:v.verdict==="dismissed",tags:["postflight",`verdict:${v.verdict}`,...(v.symbols||[]).map($=>`symbol:${$}`)]}),d[m]++,p++;}catch{}}}let u={},g=0;if(!s)for(let m of o.keys())try{let y=s$1(t,m);y.promoted>0&&(u[m]=y.promoted,g+=y.promoted);}catch{}return !s&&i.length>0&&f$4(t,i.map(m=>m.nominationId).filter(Boolean)),{sessionEntries:r.length,agentsProcessed:Array.from(o.keys()),journalsWritten:p,journalsByAgent:d,promoted:g,promotedByAgent:u,dryRun:s,details:l}}function Dg(t,e,s){let n=t.symbols?.length?` (symbols: ${t.symbols.join(", ")})`:"",i=t.reason?` Reason: ${t.reason}.`:"";switch(t.verdict){case "accepted":return `Contribution accepted by user${n}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;case "dismissed":return `Contribution dismissed by user${n}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;case "revised":return `Contribution revised by user${n}.${i}`+(t.revisionDelta?` Delta: "${t.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;default:return `Unknown verdict "${t.verdict}"${n}.${i}`}}var Xt=["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"],$l={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 es(t){let e=H.join(t,".paradigm","config.yaml");if(!E.existsSync(e))return {};try{return Te.load(E.readFileSync(e,"utf8"))||{}}catch{return {}}}function _i(t,e){let s=H.join(t,".paradigm","config.yaml");E.writeFileSync(s,Te.dump(e,{lineWidth:120,noRefs:true}),"utf8");}function ts(t){let e=t.enforcement?.level||"minimal",s=$l[e]||$l.minimal,n=t.enforcement?.checks||{},i=t.enforcement?.orchestration?.threshold??3,r={...s};for(let[o,a]of Object.entries(n))Xt.includes(o)&&Fl(a)&&(r[o]=a);return r.orchestrationThreshold=i,r}function Fl(t){return t==="block"||t==="warn"||t==="off"}function Og(t){return t==="strict"||t==="balanced"||t==="minimal"}function Ig(t){return Xt.includes(t)}var $g=[{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: "+Xt.join(", ")},severity:{type:"string",enum:["block","warn","off"],description:"Severity to set for the check (for override action)."}},required:["action"]}}];async function Fg(t,e){let{action:s,level:n,checkId:i,severity:r}=e;switch(s){case "status":{let o=es(t.rootDir),a=ts(o),c=o.enforcement?.level||"minimal",l=o.enforcement?.checks||{},d=o.enforcement?.orchestration?.threshold??3;return JSON.stringify({level:c,orchestrationThreshold:d,orchestrationNote:"Threshold is compared against magnitude score (not just file count). Magnitude = source files + cross-package penalty + security-adjacent penalty + symbol file changes.",overrides:Object.keys(l).length>0?l:void 0,effective:a,checkIds:[...Xt],presetLevels:["strict","balanced","minimal"]},null,2)}case "set-level":{if(!n||!Og(n))return JSON.stringify({error:`Invalid level "${n}". Must be one of: strict, balanced, minimal`});let o=es(t.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.level=n,o.enforcement.checks={},_i(t.rootDir,o);let a=ts(o);return JSON.stringify({success:true,level:n,message:`Enforcement level set to "${n}". Per-check overrides cleared.`,effective:a},null,2)}case "override":{if(!i||!Ig(i))return JSON.stringify({error:`Invalid checkId "${i}". Must be one of: ${Xt.join(", ")}`});if(!r||!Fl(r))return JSON.stringify({error:`Invalid severity "${r}". Must be one of: block, warn, off`});let o=es(t.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.checks||(o.enforcement.checks={}),o.enforcement.checks[i]=r,_i(t.rootDir,o);let a=ts(o);return JSON.stringify({success:true,checkId:i,severity:r,message:`Override set: ${i} = ${r}`,effective:a},null,2)}case "reset":{let o=es(t.rootDir);o.enforcement&&(o.enforcement.checks={}),_i(t.rootDir,o);let a=ts(o),c=o.enforcement?.level||"minimal";return JSON.stringify({success:true,message:`All per-check overrides cleared. Preset "${c}" is now fully in effect.`,effective:a},null,2)}default:return JSON.stringify({error:`Unknown action "${s}". Must be one of: status, set-level, override, reset`})}}function Nl(){return $g}async function El(t,e,s){if(t==="paradigm_enforcement_configure"){let n=await Fg(s,e);return o(n.length,"paradigm_enforcement_configure"),{handled:true,text:n}}return {handled:false,text:""}}b$1();function Hl(){return [{name:"paradigm_arch_status",description:"Get the architectural layer map summary and drift report. Shows tiers, their components, and any symbols that are unassigned (not in any tier) or missing from the index. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_arch_diagram",description:"Render the architectural map as a Mermaid diagram. Returns a Mermaid graph TD string showing tiers and their links. ~150 tokens.",inputSchema:{type:"object",properties:{format:{type:"string",enum:["mermaid"],description:'Output format. Only "mermaid" supported (default: "mermaid").'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ql(t,e,s){try{if(t==="paradigm_arch_status"){let n=rt(s.rootDir);if(!n)return {text:JSON.stringify({exists:!1,message:"No arch.yaml found. Create .paradigm/arch.yaml to start mapping your architecture."}),handled:!0};let i=ca(s.rootDir,s);return {text:JSON.stringify({exists:!0,version:n.version,tierCount:n.tiers.length,tiers:n.tiers.map(r=>({id:r.id,label:r.label,responsibility:r.responsibility,framework:r.tech?.framework??"",componentCount:r.components.length,components:r.components})),links:n.links,drift:{unassigned:i.unassigned,missing_purpose:i.missing_purpose,clean:i.unassigned.length===0&&i.missing_purpose.length===0}}),handled:!0}}if(t==="paradigm_arch_diagram"){let n=rt(s.rootDir);if(!n)return {text:JSON.stringify({error:"No arch.yaml found. Cannot render diagram."}),handled:!0};let i=la(n);return {text:JSON.stringify({format:"mermaid",diagram:i}),handled:!0}}return {handled:!1,text:""}}catch(n){return a.component("#arch-tools").warn(`Unexpected error in arch tool ${t}`,{error:String(n)}),{text:JSON.stringify({error:String(n)}),handled:true}}}function Ng(t,e){let s=[];for(let n=0;n<=e.length;n++)s[n]=[n];for(let n=0;n<=t.length;n++)s[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=t.length;i++)e.charAt(n-1)===t.charAt(i-1)?s[n][i]=s[n-1][i-1]:s[n][i]=Math.min(s[n-1][i-1]+1,s[n][i-1]+1,s[n-1][i]+1);return s[e.length][t.length]}function Ll(t,e,s={}){let{maxDistance:n=3,maxResults:i=5}=s,r=t.toLowerCase(),o=[];for(let a of e){let c=a.toLowerCase();if(c===r){o.push({match:a,distance:0});continue}if(c.includes(r)||r.includes(c)){o.push({match:a,distance:1});continue}let l=Ng(r,c);l<=n&&o.push({match:a,distance:l});}return o.sort((a,c)=>a.distance!==c.distance?a.distance-c.distance:a.match.localeCompare(c.match)),o.slice(0,i)}v();function qg(t,e){let s$1=new u(t),n=e||(async()=>{}),i=o=>async(a,c,l)=>o(a,c,l),r$1=o=>async(a,c,l)=>o(a,c,l,n);return s$1.registerAll([{key:"context",tier:"core",getToolsList:r,handleTool:i(s)},{key:"navigate",tier:"core",getToolsList:Ko,handleTool:i(_n)},{key:"tags",tier:"core",getToolsList:Ia,handleTool:i($a)},{key:"purpose-portal",tier:"core",getToolsList:Ma,handleTool:r$1(Wa)},{key:"pm",tier:"core",getToolsList:ic,handleTool:i(rc)},{key:"reindex",tier:"core",getToolsList:sa,handleTool:r$1(ta$1)},{key:"docs",tier:"core",getToolsList:jl,handleTool:i(Al)},{key:"ripple",tier:"core",getToolsList:pa,handleTool:i(On)},{key:"captain",tier:"core",getToolsList:Sa,handleTool:i(Ot)}]),s$1.registerAll([{key:"wisdom",tier:"feature",getToolsList:Mo,handleTool:i(kn)},{key:"history",tier:"feature",getToolsList:Wo,handleTool:i(Go)},{key:"lore",tier:"feature",getToolsList:va,handleTool:i(Dt)},{key:"streams",tier:"feature",getToolsList:Tl,handleTool:i(Dl)},{key:"ambient",tier:"feature",getToolsList:Ol,handleTool:i(Il)},{key:"sentinel",tier:"feature",getToolsList:Qo,handleTool:i(Xo)},{key:"flows",tier:"feature",getToolsList:ea,handleTool:i(ta)},{key:"fixtures",tier:"feature",getToolsList:oa,handleTool:i(aa)},{key:"orchestration",tier:"feature",getToolsList:Pa,handleTool:i(ja)},{key:"habits",tier:"feature",getToolsList:ac,handleTool:i(cc)},{key:"tasks",tier:"feature",getToolsList:kc,handleTool:i(Sc)},{key:"personas",tier:"feature",getToolsList:Oc,handleTool:i(Ic)},{key:"protocols",tier:"feature",getToolsList:ua,handleTool:i(In)},{key:"symphony",tier:"feature",getToolsList:Vc,handleTool:i(Kc)},{key:"university",tier:"feature",getToolsList:el,handleTool:i(tl)},{key:"agents",tier:"feature",getToolsList:il,handleTool:i(rl)},{key:"authority",tier:"feature",getToolsList:ll,handleTool:i(dl)},{key:"propose-block",tier:"feature",getToolsList:gl,handleTool:i(ml)},{key:"notebooks",tier:"feature",getToolsList:fl,handleTool:i(yl)},{key:"aspect-graph",tier:"feature",getToolsList:wc,handleTool:i(vc)},{key:"enforcement",tier:"feature",getToolsList:Nl,handleTool:i(El),detect:o=>E.existsSync(H.join(o,".paradigm","config.yaml"))},{key:"graph",tier:"feature",getToolsList:Nc,handleTool:i(Ec),detect:o=>E.existsSync(H.join(o,".paradigm","aspect-graph.db"))},{key:"arch",tier:"feature",getToolsList:Hl,handleTool:i(ql),detect:o=>E.existsSync(H.join(o,Us))}]),s$1.registerAll([{key:"conductor",tier:"advanced",getToolsList:Bc,handleTool:i(zc)},{key:"platform",tier:"advanced",getToolsList:nl,handleTool:i(sl)},{key:"pipeline",tier:"advanced",getToolsList:Mc,handleTool:i(Wc)},{key:"graduation",tier:"advanced",getToolsList:uc,handleTool:i(gc)}]),s$1}function Lg(t,e){let s=g=>g.toLowerCase().replace(/\/+$/,""),n=s(t),i=s(e);if(n===i)return 1;let r=g=>!g.includes("/")&&g.includes("."),o=g=>r(g)?g.split("."):g.split("/").filter(Boolean),a=o(n),c=o(i);if(r(n)||r(i)){let g=r(n)?n.split("."):n.split("/").filter(Boolean),m=r(i)?i.split("."):i.split("/").filter(Boolean),y=0;for(let f=0;f<Math.min(g.length,m.length)&&g[f]===m[f];f++)y++;return y>0?Math.min(1,.5+y/Math.max(g.length,m.length)*.5):0}let l=0,d=Math.max(a.length,c.length);for(let g=0;g<d;g++){let m=a[g]||"",y=c[g]||"";m===y?l++:m.startsWith(":")&&y.startsWith(":")?l+=.9:m.startsWith(":")||y.startsWith(":")?l+=.7:(m.replace(/s$/,"")===y.replace(/s$/,"")||y.replace(/s$/,"")===m.replace(/s$/,""))&&(l+=.8);}let p=l/d,u=a.length===c.length?.1:0;return Math.min(1,p+u)}function Mg(){return [{name:"paradigm_search",description:"Search for Paradigm symbols by name, description, or tags. Includes fuzzy matching for typo tolerance. Returns matching symbols with names, paths, types, and descriptions. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query (matches symbol names, descriptions, tags)"},type:{type:"string",enum:["component","flow","gate","signal","aspect"],description:"Optional: filter by symbol type (v2: #component, $flow, ^gate, !signal, ~aspect)"},limit:{type:"number",description:"Maximum results to return (default: 10)"},fuzzy:{type:"boolean",description:"Enable fuzzy matching for typos (default: true)"},includeWorkspace:{type:"boolean",description:"Also search sibling workspace projects (default: false). Requires workspace configured in config.yaml."},componentType:{type:"string",description:'Filter components by type (e.g., "view", "service", "tool"). Only applies to #component symbols.'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["find","lookup","locate","where is","which symbol","find symbol"]},{name:"paradigm_related",description:"Get all symbols related to a given symbol. Call before modifying code to understand what uses this symbol and what it depends on. Returns uses/used-by lists with symbol types. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to find relations for"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_status",description:"Get project overview - call this at session start for orientation. Shows symbol counts, project health, and available features. Returns symbol counts by type, project health score, and feature flags. ~100 tokens.",inputSchema:{type:"object",properties:{response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["health","overview","dashboard","project status","orientation"]},{name:"paradigm_gates_for_route",description:"Suggest which gates should be applied to a route based on patterns in the project. Returns suggested gates with confidence scores and existing patterns. ~150 tokens.",inputSchema:{type:"object",properties:{route:{type:"string",description:"Route path (e.g., /api/users, /admin/settings)"},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["route"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["auth","permissions","route security","what gates","protect route"]},{name:"paradigm_plugin_check",description:"Check for updates to installed Claude Code plugins. Reports which marketplace clones have newer remote commits and which cached versions are stale.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_workspace_reindex",description:"Rebuild scan-index.json for all workspace members. Requires workspace configured in config.yaml. Returns per-member symbol counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_tool_activate",description:"Activate an advanced-tier tool module for this session. Advanced tools are not loaded by default to reduce tool count. Call with a feature key to make its tools available. ~50 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:'Feature key to activate (e.g., "graph", "heatmap", "pipeline", "conductor", "platform")'}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}function Nb(t$1,e,s){let n$2=e(),i$1=qg(n$2.rootDir,s);t$1.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[...Mg(),...i$1.getActiveTools()]})),t$1.setRequestHandler(CallToolRequestSchema,async r=>{let{name:o$1,arguments:a}=r.params;q$1(o$1,a??{});let c=e(),l$1=j$1();l$1.setRootDir(c.rootDir);let d=null,p=null;l$1.hasRecoveredThisSession()||(d=await t(c.rootDir),p=a$1(),b$3(),l$1.markRecovered());let u=await(async()=>{switch(o$1){case "paradigm_search":{let{query:g,type:m,limit:y=10,fuzzy:f=true,includeWorkspace:b=false,componentType:h,response_format:w}=a,S=`search:${g}:${m||""}:${y}:${f}:${b}:${h||""}`,v=await v$1.getOrCompute(S,()=>{let _=j$2(c.index,g);return m&&(_=_.filter(P=>P.type===m)),h&&(_=_.filter(P=>P.componentType===h)),_}),k=[];if(v.length===0&&f){let _=n$1(c.index),P=_.map($=>$.symbol);k=Ll(g,P,{maxDistance:3,maxResults:5}),k.length>0&&(v=k.map($=>_.find(R=>R.symbol===$.match)).filter($=>$!=null),m&&(v=v.filter($=>$.type===m)));}v=v.slice(0,y);let x={query:g,count:v.length,results:v.map(_=>({symbol:_.symbol,type:_.type,description:_.description,filePath:_.filePath,..._.componentType?{componentType:_.componentType}:{},..._.parentSymbol?{parentSymbol:_.parentSymbol}:{}}))};if(k.length>0&&(x.fuzzyMatched=true,x.fuzzyNote=`No exact matches for "${g}". Showing similar symbols.`,x.suggestions=k.map(_=>({symbol:_.match,distance:_.distance}))),b&&c.workspace){let _=jt(c.workspace,g),P=m?_.filter($=>$.type===m):_;P.length>0&&(x.workspaceResults=P.slice(0,y).map($=>({symbol:$.symbol,type:$.type,description:$.description,filePath:$.filePath,project:$.project})),x.workspaceCount=P.length);}w==="concise"&&(x.results=v.map(_=>({symbol:_.symbol,type:_.type})),delete x.fuzzyMatched,delete x.fuzzyNote,delete x.suggestions,delete x.workspaceResults,delete x.workspaceCount);let C=JSON.stringify(x,null,2);return o(C.length,o$1),{content:[{type:"text",text:C}]}}case "paradigm_related":{let{symbol:g}=a,m=h$1(c.index,g);if(!m){let h=Dn(c.rootDir,g,{maxResults:20});if(h.length===0){let x=JSON.stringify({error:"Symbol not found",symbol:g,fallback:"searched",referencesFound:0,recovery:["Run `paradigm_search` with a partial name to find similar symbols","Check `.purpose` files for symbol definitions","Use `paradigm_status` to see available symbols by type","The symbol may not be indexed yet - run `paradigm scan`"]},null,2);return o(x.length,o$1),{content:[{type:"text",text:x}]}}let w=[...new Set(h.map(x=>x.filePath))],S=h.filter(x=>x.context==="purpose"),v=h.filter(x=>x.context==="code"),k=JSON.stringify({symbol:g,status:"not-indexed",fallback:"grep-search",note:"Approximate relationships from grep \u2014 run `paradigm scan` for accurate graph data.",usedBy:w.slice(0,10).map(x=>({file:x,references:h.filter(C=>C.filePath===x).length})),uses:[],summary:{totalFiles:w.length,totalReferences:h.length,purposeFileRefs:S.length,codeRefs:v.length},suggestion:"Run `paradigm scan` to enable full relationship tracking"},null,2);return o(k.length,o$1),{content:[{type:"text",text:k}]}}let y=k(c.index,g),f=l(c.index,g),b=JSON.stringify({symbol:m.symbol,type:m.type,description:m.description,usedBy:y.map(h=>({symbol:h.symbol,type:h.type,description:h.description})),uses:f.map(h=>({symbol:h.symbol,type:h.type,description:h.description}))},null,2);return o(b.length,o$1),{content:[{type:"text",text:b}]}}case "paradigm_status":{let g=a.response_format,m$1=await v$1.getOrCompute("status",async()=>{let f=m(c.index),b=Object.values(f).reduce((T,j)=>T+j,0),h={};for(let T of Object.keys(f)){let j=i(c.index,T);h[T]=j.slice(0,3).map(A=>A.symbol);}let w=wa.platform(),S=w==="win32",v=S?"PowerShell/CMD":w==="darwin"?"zsh/bash":"bash",k;try{let T=await $(c.rootDir);T&&T.health.total>0&&(k=T.health);}catch{}let x=i(c.index,"component"),C={};for(let T of x)T.componentType&&(C[T.componentType]=(C[T.componentType]||0)+1);let _=x.filter(T=>!T.componentType).length,P;try{let{checkPurposeHealth:T}=await import('./integrity-checker-DHGMZQDG.js');P=T(c.aggregation.purposeFiles,c.rootDir).healthScore;}catch{}let $$1;try{let{countNotebookReferences:T}=await import('./session-work-log-MEJ33TYD.js'),j=T(c.rootDir);j>0&&($$1=j);}catch{}let R;try{let{getComplianceTrend:T,getHealthDot:j}=await import('./compliance-health-JNP3P35P.js'),A=T(c.rootDir);A&&(R={trend:A,dot:j(A,c.rootDir)});}catch{}return JSON.stringify({project:c.projectName,symbolSystem:"v2",counts:{"# components":f.component,"$ flows":f.flow,"^ gates":f.gate,"! signals":f.signal,"~ aspects":f.aspect},total:b,...Object.keys(C).length>0?{componentTypes:{...C,..._>0?{"(untyped)":_}:{}}}:{},examples:h,hasPortalYaml:c.gateConfig!==null,purposeFiles:c.aggregation.purposeFiles.length,...P!==void 0?{purposeHealthScore:P}:{},...k?{protocols:k}:{},...$$1!==void 0?{notebookReferences:$$1}:{},...R?{complianceHealth:R}:{},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:v,terminalNote:S?"Use PowerShell syntax: semicolons for command chaining, backslashes for paths, $env:VAR for env vars":"Use Unix syntax: && for command chaining, forward slashes for paths, $VAR for env vars"}},null,2)}),y=m$1;if(g==="concise")try{let f=JSON.parse(m$1);y=JSON.stringify({project:f.project,counts:f.counts,total:f.total},null,2);}catch{}return o(y.length,o$1),{content:[{type:"text",text:y}]}}case "paradigm_gates_for_route":{let{route:g,response_format:m}=a,f=typeof g=="string"&&!g.includes("/")&&g.includes(".")?"POST":a.method||"GET",b=i(c.index,"gate"),h=[],w=[];if(c.gateConfig?.routes)for(let[R,T]of Object.entries(c.gateConfig.routes))T.gates&&w.push({route:R,gates:T.gates,method:T.method});if(c.workspace)for(let[R,T]of c.workspace.siblingIndices){let j=T.gateConfig;if(j?.routes)for(let[A,O]of Object.entries(j.routes)){let I=O,N=Array.isArray(I)?I:I?.gates;N&&w.push({route:A,gates:N,method:Array.isArray(I)?void 0:I?.method,source:R});}}for(let R of w){let T=Lg(g,R.route);if(T>=.6&&(!R.method||R.method===f))for(let j of R.gates){let A=b.find(O=>O.symbol===j||O.symbol===`^${j}`);if(A&&!h.find(O=>O.gate===A.symbol)){let O=R.source?`${R.source}/portal.yaml`:"portal.yaml";h.push({gate:A.symbol,reason:`Similar route "${R.route}" uses this gate`,confidence:T>=.8?"high":"medium",source:O});}}}let k=g.split("/").filter(Boolean).find(R=>!R.startsWith(":")&&R!=="api")?.replace(/s$/,"")||"",x=g.match(/\/:(id|[a-z]+Id)($|\/)/i);if(x&&k){let R=b.find(T=>{let j=T.symbol.toLowerCase(),A=(T.description||"").toLowerCase();return j.includes(`${k}-owner`)||j.includes("owner")||j.includes("ownership")||A.includes("owner")||A.includes("ownership")||A.includes("belongs to")});R?h.push({gate:R.symbol,reason:`Resource ID route (${k}) typically needs ownership verification`,confidence:"high"}):h.push({gate:`^${k}-owner`,reason:`Consider adding ownership gate for ${k} resource`,confidence:"medium"});}if(g.includes("/admin")||g.includes("/settings")){let R=b.find(T=>T.symbol.includes("admin")||T.description?.toLowerCase().includes("admin"));R&&h.push({gate:R.symbol,reason:"Route appears to be admin-related",confidence:"high"});}if(g.startsWith("/api/")||g.includes("/user")||g.includes("/account")){let R=b.find(T=>T.symbol.includes("authenticated")||T.symbol.includes("auth"));R&&h.push({gate:R.symbol,reason:"API/user routes typically require authentication",confidence:"high"});}if(g.includes("/premium")||g.includes("/pro")||g.includes("/export")){let R=b.find(T=>T.symbol.includes("subscription")||T.symbol.includes("premium"));R&&h.push({gate:R.symbol,reason:"Route appears to be a premium feature",confidence:"medium"});}if(f==="DELETE"){let R=b.find(T=>T.symbol.includes("authenticated"));R&&!h.find(T=>T.gate===R.symbol)&&h.push({gate:R.symbol,reason:"DELETE operations require authentication",confidence:"high"});}if(["POST","PUT","PATCH"].includes(f)){let R=b.find(T=>T.symbol.includes("authenticated"));R&&!h.find(T=>T.gate===R.symbol)&&h.push({gate:R.symbol,reason:"Write operations typically require authentication",confidence:"high"});}let C=new Set,_=h.filter(R=>C.has(R.gate)?false:(C.add(R.gate),true)),P=m==="concise"?{suggestions:_.map(R=>({gate:R.gate,confidence:R.confidence}))}:{route:g,method:f,suggestions:_,availableGates:b.map(R=>({symbol:R.symbol,description:R.description})),note:x?"Resource ID routes should verify the user owns/has access to the specific resource.":"These are suggestions based on route patterns. Review your portal.yaml for exact requirements."},$=JSON.stringify(P,null,2);o($.length,o$1);try{n(c.rootDir,{type:"gate-checked",source:"mcp-tool-call",tool:"paradigm_gates_for_route",symbols:_.map(R=>R.gate),context:`Gate check for ${f} ${g}`});}catch{}return {content:[{type:"text",text:$}]}}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:
626
- `],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(`
627
- Update command:
628
- ${b.join(` && \\
629
- `)}`),f.push(`
630
- After running, restart the session to apply updates.`)):f.push(`
631
- Restart the session to apply cached updates.`);let h=f.join(`
632
- `);return o(h.length,o$1),{content:[{type:"text",text:h}]}}case "paradigm_workspace_reindex":{if(!c.workspace){let f=JSON.stringify({error:"No workspace configured",suggestion:'Add a "workspace" field to .paradigm/config.yaml pointing to your .paradigm-workspace file, then run `paradigm workspace init` to create one.'},null,2);return o(f.length,o$1),{content:[{type:"text",text:f}]}}let{rebuildStaticFiles:g}=await import('./reindex-GSRV4MQO.js'),m=[];for(let f of c.workspace.config.members){let b=H.resolve(H.dirname(c.workspace.workspacePath),f.path);try{let h=await g(b);m.push({name:f.name,symbolCount:h.symbolCount,status:"ok"});}catch(h){m.push({name:f.name,symbolCount:0,status:`error: ${h.message}`});}}let y=JSON.stringify({action:"workspace_reindex",workspace:c.workspace.config.name,members:m,totalSymbols:m.reduce((f,b)=>f+b.symbolCount,0)},null,2);return o(y.length,o$1),v$1.clear(),{content:[{type:"text",text:y}]}}case "paradigm_tool_activate":{let g=a.feature,m=i$1.activateAdvanced(g);if(m){let h=JSON.stringify({action:"tool_activate",feature:g,status:"activated",toolsAdded:m.map(w=>w.name),note:`Advanced module "${g}" activated for this session. ${m.length} tool(s) now available.`},null,2);return o(h.length,o$1),{content:[{type:"text",text:h}]}}let y=i$1.getRegistryInfo(),f=y.activeFeatures.includes(g),b=JSON.stringify({action:"tool_activate",feature:g,status:f?"already_active":"not_found",note:f?`Module "${g}" is already active (auto-detected or core tier).`:`Module "${g}" not found. Available advanced modules: ${y.availableAdvanced.join(", ")||"(none)"}`,availableAdvanced:y.availableAdvanced},null,2);return o(b.length,o$1),{content:[{type:"text",text:b}]}}default:{let g=await i$1.dispatch(o$1,a,c);if(g&&g.handled)return o$1.startsWith("paradigm_context_")||o$1.startsWith("paradigm_session_")||o$1==="paradigm_handoff_prepare"||o(g.text.length,o$1),Wg(o$1,a,c.rootDir),{content:[{type:"text",text:g.text}]};throw new Error(`Unknown tool: ${o$1}`)}}})();if(d||p){let g=u.content?.[0];if(g&&typeof g=="object"&&"text"in g&&typeof g.text=="string"){let m=[p,d].filter(Boolean).join(`
633
-
634
- `);g.text=m+`
635
-
636
- `+g.text;}}return u});}function Wg(t,e,s){try{switch(t){case "paradigm_sentinel_record":n(s,{type:"error-encountered",source:"mcp-tool-call",tool:t,severity:e.severity||"warning",context:`Sentinel: ${e.title||e.summary||"incident recorded"}`});break;case "paradigm_lore_record":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,symbols:Array.isArray(e.symbols_touched)?e.symbols_touched.map(String):[],context:`Lore recorded: ${e.title||"untitled"}`});break;case "paradigm_work_log_record":case "paradigm_journal_record":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,symbols:Array.isArray(e.symbols)?e.symbols.map(String):[],context:`Work logged: ${e.summary||e.title||"entry"}`});break;case "paradigm_decision_record":n(s,{type:"decision-made",source:"mcp-tool-call",tool:t,symbols:Array.isArray(e.symbols)?e.symbols.map(String):[],context:`Decision: ${e.title||e.summary||"recorded"}`});break;case "paradigm_persona_run":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:`Persona run: ${e.persona||"unknown"}`});break;case "paradigm_protocol_record":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:`Protocol recorded: ${e.name||e.id||"unknown"}`});break;case "paradigm_reindex":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:"Index rebuilt"},{skipNominations:!0});break;default:(t.startsWith("paradigm_purpose_")||t.startsWith("paradigm_portal_"))&&(t.includes("_add_")||t.includes("_update_")||t.includes("_remove_"))&&n(s,{type:"file-modified",source:"mcp-tool-call",tool:t,symbols:e.id?[`#${e.id}`]:e.symbol?[String(e.symbol)]:[],context:`Purpose/portal update via ${t}`});break}}catch{}}export{ed as a,jo as b,sd as c,im as d,vn as e,Ns as f,Uy as g,Nb as h};