@a-company/paradigm 5.24.0 → 5.27.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-loader-EPXURMO7.js → agent-loader-MQMXCI3D.js} +1 -1
- package/dist/{agent-loader-PYGPX6D2.js → agent-loader-RGPE3LRD.js} +1 -1
- package/dist/{ambient-HYZR42NX.js → ambient-2RAKMUC7.js} +2 -2
- package/dist/{chunk-V7K6CQVX.js → chunk-4YIKDQRB.js} +9 -9
- package/dist/{chunk-Z34K6GY2.js → chunk-CUOEZAVL.js} +4 -4
- package/dist/{chunk-HXKWL3VK.js → chunk-DJERXYEL.js} +1 -1
- package/dist/{chunk-4ZGGWZ32.js → chunk-HBGRP73K.js} +1 -1
- package/dist/chunk-KYA4TP26.js +2 -0
- package/dist/{chunk-PUBB7LIT.js → chunk-PBVBTHGE.js} +1 -1
- package/dist/{chunk-AD5TAD2A.js → chunk-UELDOSWH.js} +1 -1
- package/dist/{chunk-6EX37L4Q.js → chunk-VZLGBGU3.js} +5 -5
- package/dist/{chunk-2QO33NYK.js → chunk-XGAOYG77.js} +2 -2
- package/dist/{chunk-XUFYOXOU.js → chunk-ZMQXXFG2.js} +2 -2
- package/dist/{compliance-NLG7KB73.js → compliance-LM2NN2S6.js} +1 -1
- package/dist/{docs-UIYXJ3O3.js → docs-5BX2YWYK.js} +1 -1
- package/dist/{enforcement-MKFUH4TE.js → enforcement-46XWPNSA.js} +1 -1
- package/dist/{enforcement-TJOXPSTJ.js → enforcement-BEGPQIUN.js} +1 -1
- package/dist/index.js +2 -2
- package/dist/mcp.js +7 -7
- package/dist/{nomination-engine-XF7TWPAP.js → nomination-engine-K7MQD53E.js} +1 -1
- package/dist/{platform-server-FXYBBH6E.js → platform-server-G6MJIAJS.js} +1 -1
- package/dist/reindex-HA3CJG7S.js +2 -0
- package/dist/{serve-5W6KOA4R.js → serve-ZJ3EXVA5.js} +1 -1
- package/dist/session-tracker-G7VOLRMR.js +2 -0
- package/dist/{session-work-log-3MNUDEZ6.js → session-work-log-HFOD7LEG.js} +1 -1
- package/dist/{session-work-log-J2H5OZBR.js → session-work-log-IEYBPFUC.js} +1 -1
- package/dist/{shift-TDOYQKR4.js → shift-WNP27SPB.js} +7 -7
- package/dist/{symphony-3QMBGCZY.js → symphony-43N4R6C2.js} +1 -1
- package/dist/{symphony-QI63XL62.js → symphony-ZQ5OHJTP.js} +3 -3
- package/dist/{symphony-loader-XACVV2E3.js → symphony-loader-XJT43FOS.js} +1 -1
- package/dist/{symphony-relay-5GY5JIPT.js → symphony-relay-KBHN3ZMR.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-27FBCZX6.js +0 -2
- package/dist/reindex-PGDQSM42.js +0 -2
- package/dist/session-tracker-SKOMBDOW.js +0 -2
package/dist/mcp.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a,b as b$2}from'./chunk-4UJ4NIEQ.js';import {e,v,b as b$1,n as n$1,c as c$2,d as d$3,q as q$1,p as p$1,o as o$1,s as s$1,i as i$2,k as k$1,l as l$1,a as a$5,m as m$1,t as t$2,u as u$1,j as j$3}from'./chunk-HXKWL3VK.js';import {o as o$2,A,y,x,f as f$4,r as r$2}from'./chunk-KLBH26PA.js';import {g as g$5,d as d$2,a as a$2}from'./chunk-Q2J542ST.js';import {i as i$3}from'./chunk-XROULIQN.js';import {l as l$2,h as h$4,M as M$2,L as L$1,H as H$1,N as N$1,I as I$1,F as F$1,G,A as A$1,E,k as k$2,j as j$4,B,t as t$3,K as K$1,o as o$3,z,P as P$1,m as m$2,w,r as r$1,y as y$1,q as q$2}from'./chunk-6EX37L4Q.js';import {f,g as g$2,e as e$1,m,n,p,h as h$1,i,q,t as t$1,o,v as v$1,U,k,l,j as j$2,u,r,ma as ma$1,s,na as na$1,Q,ka as ka$1,Z as Z$1,I,P,O as O$1,R,H,N,M as M$1,L,K,J as J$1,T,Y,S,X as X$1,W,V,ha as ha$1,$,ba as ba$1,da as da$1,ca as ca$1,ia as ia$1,ea as ea$1,aa as aa$1,ga as ga$1,_,la as la$1,fa as fa$1,ja as ja$1,oa,a as a$8,d as d$9,c as c$5,w as w$1,x as x$1,F as F$2,E as E$1,y as y$2,C,z as z$1,A as A$2,B as B$1,G as G$1,D,b as b$a}from'./chunk-V7K6CQVX.js';import'./chunk-M4UMM6DC.js';import {d as d$5,b as b$5,a as a$4}from'./chunk-JNSJVCTU.js';import {j,a as a$1,i as i$1,b as b$3,h as h$3,g as g$4,c as c$1,d as d$1}from'./chunk-ODVKPZZ4.js';import {t,f as f$2,n as n$2,b as b$7,d as d$7,e as e$5,s as s$2,j as j$5,g as g$6}from'./chunk-XUFYOXOU.js';import {j as j$1,d,e as e$2,f as f$1,g as g$3,h as h$2}from'./chunk-4ZGGWZ32.js';import {h,b as b$9}from'./chunk-AD5TAD2A.js';import {f as f$3,b as b$6,e as e$4,d as d$6,a as a$6,c as c$3}from'./chunk-DVZWCXB6.js';import {g as g$1,e as e$3,b as b$4,d as d$4,a as a$3}from'./chunk-QGZRM6ZB.js';import {g,d as d$8,c as c$4,b as b$8,a as a$7}from'./chunk-VG7FN2TU.js';import {b,c,d as d$a}from'./chunk-5TAVYPOV.js';import*as O from'fs';import*as F from'path';import*as Z from'js-yaml';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {ListResourcesRequestSchema,ReadResourceRequestSchema,ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import*as ga from'os';import {execSync}from'child_process';var $t,Ns,Es=b(()=>{$t={enabled:true,thresholds:{minComplianceRate:90,minEvents:20,timeWindowDays:30,minConsecutiveSessions:5,recencyDays:7},demotion:{failureThreshold:3,failureWindowDays:7,cooldownDays:14},neverGraduate:["explore-before-implement","ripple-before-modify","check-fragility","wisdom-before-implement","confidence-on-decisions","university-onboarded","university-content-valid"]},Ns=new Set(["tool-called","context-checked"]);});var $a={};c($a,{getAllStates:()=>qs,getConfig:()=>lt,getState:()=>Hn,incrementFailure:()=>Ia,invalidateGraduationCache:()=>Hp,isGraduated:()=>Np,loadGraduation:()=>Ze,markNeverGraduate:()=>Ep,saveGraduation:()=>En,setTier:()=>Oa});function Aa(n){return F.join(n,".paradigm","graduation.yaml")}function Ze(n){let e=F.resolve(n);if(Ft&&$n===e&&Date.now()-Fn<Fp)return Ft;let s=Aa(e),t;if(O.existsSync(s))try{let i=O.readFileSync(s,"utf8");t=Z.load(i);}catch{t={version:"1.0",config:{},states:{}};}else t={version:"1.0",config:{},states:{}};return t.version||(t.version="1.0"),t.config||(t.config={}),t.states||(t.states={}),Ft=t,$n=e,Fn=Date.now(),t}function En(n,e){let s=F.resolve(n),t=Aa(s),i=F.dirname(t);O.existsSync(i)||O.mkdirSync(i,{recursive:true});let r=Z.dump(e,{lineWidth:120,noRefs:true,sortKeys:true});O.writeFileSync(t,r,"utf8"),Ft=e,$n=s,Fn=Date.now();}function lt(n){let e=Ze(n);return {...$t,...e.config,thresholds:{...$t.thresholds,...e.config?.thresholds},demotion:{...$t.demotion,...e.config?.demotion},neverGraduate:e.config?.neverGraduate??$t.neverGraduate}}function Hs(n){return {habitId:n,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function Hn(n,e){let t=Ze(n).states[e];return t?{...Hs(e),...t,habitId:e}:Hs(e)}function qs(n){let e=Ze(n),s={};for(let[t,i]of Object.entries(e.states))s[t]={...Hs(t),...i,habitId:t};return s}function Np(n,e){return Hn(n,e).tier==="hook"}function Oa(n,e,s,t){let i=Ze(n),r=i.states[e]||{};i.states[e]={...r,tier:s,previousTier:r.tier||"habit",...s==="hook"?{graduatedAt:new Date().toISOString(),failureCount:0}:{},...s==="habit"&&r.tier==="hook"?{demotedAt:new Date().toISOString()}:{},...t},En(n,i);}function Ep(n,e){let s=Ze(n);s.states[e]||(s.states[e]={}),s.states[e].neverGraduate=true,s.states[e].tier="habit",En(n,s);}function Ia(n,e){let s=Ze(n);s.states[e]||(s.states[e]={});let t=(s.states[e].failureCount||0)+1;return s.states[e].failureCount=t,En(n,s),t}function Hp(){Ft=null,$n=null,Fn=0;}var Ft,$n,Fn,Fp,qn=b(()=>{Es();Ft=null,$n=null,Fn=0,Fp=3e4;});var Yl=30*1e3,ks=new Map,Ss=".paradigm/wisdom";async function co(n){let e=F.resolve(n),s=ks.get(e);if(s&&Date.now()-s.loadedAt<Yl)return s.context;let t=await Kl(e);return ks.set(e,{context:t,loadedAt:Date.now()}),t}async function Kl(n){let e=F.join(n,Ss),s=O.existsSync(e),[t,i,r,o]=s?await Promise.all([Ql(e),Xl(e),Zl(e),ed(e)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e$2(),l=f$1();}catch{}let d$1=new Set(i.map(y=>y.id)),p=i.map(y=>({...y,scope:"project"}));for(let y of a)d$1.has(y.id)||p.push({...y,scope:"global"});let u=new Set(o.map(y=>y.id)),g=o.map(y=>({...y,scope:"project"}));for(let y of c)u.has(y.id)||g.push({...y,scope:"global"});let m=t;if(l&&!t)m=l;else if(l&&t){let y={...t.by_symbol};if(l.by_symbol)for(let[f,b]of Object.entries(l.by_symbol))y[f]||(y[f]=b);m={...t,by_symbol:y,global:{...l.global,...t.global}};}return {preferences:m,antipatterns:p,decisions:g,expertise:r}}function Be(n){let e=F.resolve(n);ks.delete(e);}async function Ql(n){let e=F.join(n,"preferences.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[wisdom-loader] Error parsing preferences.yaml:",s),null}}async function Xl(n){let e=F.join(n,"antipatterns.yaml");if(!O.existsSync(e))return [];try{let s=O.readFileSync(e,"utf8");return Z.load(s).antipatterns||[]}catch(s){return console.error("[wisdom-loader] Error parsing antipatterns.yaml:",s),[]}}async function Zl(n){let e=F.join(n,"expertise.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[wisdom-loader] Error parsing expertise.yaml:",s),null}}async function ed(n){let e=F.join(n,"decisions");if(!O.existsSync(e))return [];let s=[];try{let t=O.readdirSync(e);for(let i of t){if(!i.endsWith(".yaml")&&!i.endsWith(".yml"))continue;let r=F.join(e,i);try{let o=O.readFileSync(r,"utf8"),a=Z.load(o);s.push(a);}catch(o){console.error(`[wisdom-loader] Error parsing ${i}:`,o);}}}catch(t){console.error("[wisdom-loader] Error reading decisions directory:",t);}return s.sort((t,i)=>t.id.localeCompare(i.id)),s}function lo(n,e){return e.map(s=>yn(n,s))}function yn(n,e){let s=n.preferences?.by_symbol?.[e]||null,t=n.antipatterns.filter(o=>o.symbols.some(a=>a===e||fn(e,a))),i=n.decisions.filter(o=>o.symbols.some(a=>a===e||fn(e,a))),r=n.expertise?.experts.filter(o=>o.symbols?.some(a=>a===e||fn(e,a)))||[];return {symbol:e,preferences:s,antipatterns:t,decisions:i,experts:r}}function hn(n,e){return n.expertise?n.expertise.experts.filter(s=>!!(e.symbol&&s.symbols&&s.symbols.some(t=>t===e.symbol||fn(e.symbol,t))||e.area&&s.areas&&s.areas.some(t=>t.toLowerCase().includes(e.area.toLowerCase())))):[]}function fn(n,e){if(e.endsWith("*")){let s=e.slice(0,-1);return n.startsWith(s)}return n===e}async function po(n,e){let s=F.join(n,Ss),t=F.join(s,"antipatterns.yaml");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let i={version:"1.0",antipatterns:[]};if(O.existsSync(t)){let r=O.readFileSync(t,"utf8");i=Z.load(r);}i.antipatterns.push({...e,added:new Date().toISOString()}),O.writeFileSync(t,Z.dump(i,{lineWidth:-1})),Be(n);}async function uo(n,e){let s=F.join(n,Ss,"decisions");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let t=`${e.id}-${td(e.title)}.yaml`,i=F.join(s,t);O.writeFileSync(i,Z.dump(e,{lineWidth:-1})),Be(n);}function td(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var go=".paradigm/history";async function mo(n){let e=F.join(n,go);if(!O.existsSync(e))return {index:null,validation:null};let[s,t]=await Promise.all([nd(e),sd(e)]);return {index:s,validation:t}}async function nd(n){let e=F.join(n,"index.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[history-loader] Error parsing index.yaml:",s),null}}async function sd(n){let e=F.join(n,"validation.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[history-loader] Error parsing validation.yaml:",s),null}}function fo(n,e){return e.map(s=>wn(n,s))}function wn(n,e){let s=n.index?.by_symbol?.[e]||null,t=[];if(n.index?.co_changes){for(let r of n.index.co_changes)if(r.symbols.includes(e))for(let o of r.symbols)o!==e&&!t.includes(o)&&t.push(o);}let i=n.validation?.by_symbol?.[e]||null;return {symbol:e,summary:s,recent:s?.recent||[],co_changes:t,validation:i}}function yo(n,e){let s=[],t=[];if(!n.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let o of e){let a=n.index.by_symbol?.[o];a&&(a.fragility==="high"||a.fragility==="critical")&&s.push({symbol:o,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=n.index.fragile_symbols?.find(l=>l.symbol===o);c&&!s.find(l=>l.symbol===o)&&s.push(c);}for(let o of e){let a=n.index.co_changes?.filter(c=>c.symbols.includes(o));if(a?.length)for(let c of a){let l=c.symbols.filter(d=>d!==o&&!e.includes(d));l.length>0&&c.correlation>.7&&t.push(`${o} often changes with ${l.join(", ")} (${Math.round(c.correlation*100)}% correlation)`);}}let i=s.filter(o=>o.fragility==="critical").length===0,r=[];return s.length>0&&(r.push("Consider adding extra test coverage before modifying fragile symbols"),r.push("Review recent rollbacks and failures for these symbols")),t.length>0&&r.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:s,warnings:t,safe_to_modify:i,recommendations:r}}async function xs(n,e){let s=F.join(n,go),t=F.join(s,"log.jsonl");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let i=id(t),r=new Date().toISOString(),o={id:i,ts:r,...e},a=JSON.stringify(o)+`
|
|
2
|
+
import {a,b as b$2}from'./chunk-4UJ4NIEQ.js';import {e,v,b as b$1,n as n$1,c as c$2,d as d$3,q as q$1,p as p$1,o as o$1,s as s$1,i as i$2,k as k$1,l as l$1,a as a$5,m as m$1,t as t$2,u as u$1,j as j$3}from'./chunk-DJERXYEL.js';import {o as o$2,A,y,x,f as f$4,r as r$2}from'./chunk-KLBH26PA.js';import {g as g$5,d as d$2,a as a$2}from'./chunk-Q2J542ST.js';import {i as i$3}from'./chunk-XROULIQN.js';import {l as l$2,h as h$4,M as M$2,L as L$1,H as H$1,N as N$1,I as I$1,F as F$1,G,A as A$1,E,k as k$2,j as j$4,B,t as t$3,K as K$1,o as o$3,z,P as P$1,m as m$2,w,r as r$1,y as y$1,q as q$2}from'./chunk-VZLGBGU3.js';import {f,g as g$2,e as e$1,m,n,p,h as h$1,i,q,t as t$1,o,v as v$1,U,k,l,j as j$2,u,r,ma as ma$1,s,na as na$1,Q,ka as ka$1,Z as Z$1,I,P,O as O$1,R,H,N,M as M$1,L,K,J as J$1,T,Y,S,X as X$1,W,V,ha as ha$1,$,ba as ba$1,da as da$1,ca as ca$1,ia as ia$1,ea as ea$1,aa as aa$1,ga as ga$1,_,la as la$1,fa as fa$1,ja as ja$1,oa,a as a$8,d as d$9,c as c$5,w as w$1,x as x$1,F as F$2,E as E$1,y as y$2,C,z as z$1,A as A$2,B as B$1,G as G$1,D,b as b$a}from'./chunk-4YIKDQRB.js';import'./chunk-M4UMM6DC.js';import {d as d$5,b as b$5,a as a$4}from'./chunk-JNSJVCTU.js';import {j,a as a$1,i as i$1,b as b$3,h as h$3,g as g$4,c as c$1,d as d$1}from'./chunk-ODVKPZZ4.js';import {t,f as f$2,n as n$2,b as b$7,d as d$7,e as e$5,s as s$2,j as j$5,g as g$6}from'./chunk-ZMQXXFG2.js';import {j as j$1,d,e as e$2,f as f$1,g as g$3,h as h$2}from'./chunk-HBGRP73K.js';import {h,b as b$9}from'./chunk-UELDOSWH.js';import {f as f$3,b as b$6,e as e$4,d as d$6,a as a$6,c as c$3}from'./chunk-DVZWCXB6.js';import {g as g$1,e as e$3,b as b$4,d as d$4,a as a$3}from'./chunk-QGZRM6ZB.js';import {g,d as d$8,c as c$4,b as b$8,a as a$7}from'./chunk-VG7FN2TU.js';import {b,c,d as d$a}from'./chunk-5TAVYPOV.js';import*as O from'fs';import*as F from'path';import*as Z from'js-yaml';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {ListResourcesRequestSchema,ReadResourceRequestSchema,ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import*as ga from'os';import {execSync}from'child_process';var $t,Ns,Es=b(()=>{$t={enabled:true,thresholds:{minComplianceRate:90,minEvents:20,timeWindowDays:30,minConsecutiveSessions:5,recencyDays:7},demotion:{failureThreshold:3,failureWindowDays:7,cooldownDays:14},neverGraduate:["explore-before-implement","ripple-before-modify","check-fragility","wisdom-before-implement","confidence-on-decisions","university-onboarded","university-content-valid"]},Ns=new Set(["tool-called","context-checked"]);});var $a={};c($a,{getAllStates:()=>qs,getConfig:()=>lt,getState:()=>Hn,incrementFailure:()=>Ia,invalidateGraduationCache:()=>Hp,isGraduated:()=>Np,loadGraduation:()=>Ze,markNeverGraduate:()=>Ep,saveGraduation:()=>En,setTier:()=>Oa});function Aa(n){return F.join(n,".paradigm","graduation.yaml")}function Ze(n){let e=F.resolve(n);if(Ft&&$n===e&&Date.now()-Fn<Fp)return Ft;let s=Aa(e),t;if(O.existsSync(s))try{let i=O.readFileSync(s,"utf8");t=Z.load(i);}catch{t={version:"1.0",config:{},states:{}};}else t={version:"1.0",config:{},states:{}};return t.version||(t.version="1.0"),t.config||(t.config={}),t.states||(t.states={}),Ft=t,$n=e,Fn=Date.now(),t}function En(n,e){let s=F.resolve(n),t=Aa(s),i=F.dirname(t);O.existsSync(i)||O.mkdirSync(i,{recursive:true});let r=Z.dump(e,{lineWidth:120,noRefs:true,sortKeys:true});O.writeFileSync(t,r,"utf8"),Ft=e,$n=s,Fn=Date.now();}function lt(n){let e=Ze(n);return {...$t,...e.config,thresholds:{...$t.thresholds,...e.config?.thresholds},demotion:{...$t.demotion,...e.config?.demotion},neverGraduate:e.config?.neverGraduate??$t.neverGraduate}}function Hs(n){return {habitId:n,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function Hn(n,e){let t=Ze(n).states[e];return t?{...Hs(e),...t,habitId:e}:Hs(e)}function qs(n){let e=Ze(n),s={};for(let[t,i]of Object.entries(e.states))s[t]={...Hs(t),...i,habitId:t};return s}function Np(n,e){return Hn(n,e).tier==="hook"}function Oa(n,e,s,t){let i=Ze(n),r=i.states[e]||{};i.states[e]={...r,tier:s,previousTier:r.tier||"habit",...s==="hook"?{graduatedAt:new Date().toISOString(),failureCount:0}:{},...s==="habit"&&r.tier==="hook"?{demotedAt:new Date().toISOString()}:{},...t},En(n,i);}function Ep(n,e){let s=Ze(n);s.states[e]||(s.states[e]={}),s.states[e].neverGraduate=true,s.states[e].tier="habit",En(n,s);}function Ia(n,e){let s=Ze(n);s.states[e]||(s.states[e]={});let t=(s.states[e].failureCount||0)+1;return s.states[e].failureCount=t,En(n,s),t}function Hp(){Ft=null,$n=null,Fn=0;}var Ft,$n,Fn,Fp,qn=b(()=>{Es();Ft=null,$n=null,Fn=0,Fp=3e4;});var Yl=30*1e3,ks=new Map,Ss=".paradigm/wisdom";async function co(n){let e=F.resolve(n),s=ks.get(e);if(s&&Date.now()-s.loadedAt<Yl)return s.context;let t=await Kl(e);return ks.set(e,{context:t,loadedAt:Date.now()}),t}async function Kl(n){let e=F.join(n,Ss),s=O.existsSync(e),[t,i,r,o]=s?await Promise.all([Ql(e),Xl(e),Zl(e),ed(e)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e$2(),l=f$1();}catch{}let d$1=new Set(i.map(y=>y.id)),p=i.map(y=>({...y,scope:"project"}));for(let y of a)d$1.has(y.id)||p.push({...y,scope:"global"});let u=new Set(o.map(y=>y.id)),g=o.map(y=>({...y,scope:"project"}));for(let y of c)u.has(y.id)||g.push({...y,scope:"global"});let m=t;if(l&&!t)m=l;else if(l&&t){let y={...t.by_symbol};if(l.by_symbol)for(let[f,b]of Object.entries(l.by_symbol))y[f]||(y[f]=b);m={...t,by_symbol:y,global:{...l.global,...t.global}};}return {preferences:m,antipatterns:p,decisions:g,expertise:r}}function Be(n){let e=F.resolve(n);ks.delete(e);}async function Ql(n){let e=F.join(n,"preferences.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[wisdom-loader] Error parsing preferences.yaml:",s),null}}async function Xl(n){let e=F.join(n,"antipatterns.yaml");if(!O.existsSync(e))return [];try{let s=O.readFileSync(e,"utf8");return Z.load(s).antipatterns||[]}catch(s){return console.error("[wisdom-loader] Error parsing antipatterns.yaml:",s),[]}}async function Zl(n){let e=F.join(n,"expertise.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[wisdom-loader] Error parsing expertise.yaml:",s),null}}async function ed(n){let e=F.join(n,"decisions");if(!O.existsSync(e))return [];let s=[];try{let t=O.readdirSync(e);for(let i of t){if(!i.endsWith(".yaml")&&!i.endsWith(".yml"))continue;let r=F.join(e,i);try{let o=O.readFileSync(r,"utf8"),a=Z.load(o);s.push(a);}catch(o){console.error(`[wisdom-loader] Error parsing ${i}:`,o);}}}catch(t){console.error("[wisdom-loader] Error reading decisions directory:",t);}return s.sort((t,i)=>t.id.localeCompare(i.id)),s}function lo(n,e){return e.map(s=>yn(n,s))}function yn(n,e){let s=n.preferences?.by_symbol?.[e]||null,t=n.antipatterns.filter(o=>o.symbols.some(a=>a===e||fn(e,a))),i=n.decisions.filter(o=>o.symbols.some(a=>a===e||fn(e,a))),r=n.expertise?.experts.filter(o=>o.symbols?.some(a=>a===e||fn(e,a)))||[];return {symbol:e,preferences:s,antipatterns:t,decisions:i,experts:r}}function hn(n,e){return n.expertise?n.expertise.experts.filter(s=>!!(e.symbol&&s.symbols&&s.symbols.some(t=>t===e.symbol||fn(e.symbol,t))||e.area&&s.areas&&s.areas.some(t=>t.toLowerCase().includes(e.area.toLowerCase())))):[]}function fn(n,e){if(e.endsWith("*")){let s=e.slice(0,-1);return n.startsWith(s)}return n===e}async function po(n,e){let s=F.join(n,Ss),t=F.join(s,"antipatterns.yaml");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let i={version:"1.0",antipatterns:[]};if(O.existsSync(t)){let r=O.readFileSync(t,"utf8");i=Z.load(r);}i.antipatterns.push({...e,added:new Date().toISOString()}),O.writeFileSync(t,Z.dump(i,{lineWidth:-1})),Be(n);}async function uo(n,e){let s=F.join(n,Ss,"decisions");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let t=`${e.id}-${td(e.title)}.yaml`,i=F.join(s,t);O.writeFileSync(i,Z.dump(e,{lineWidth:-1})),Be(n);}function td(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var go=".paradigm/history";async function mo(n){let e=F.join(n,go);if(!O.existsSync(e))return {index:null,validation:null};let[s,t]=await Promise.all([nd(e),sd(e)]);return {index:s,validation:t}}async function nd(n){let e=F.join(n,"index.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[history-loader] Error parsing index.yaml:",s),null}}async function sd(n){let e=F.join(n,"validation.yaml");if(!O.existsSync(e))return null;try{let s=O.readFileSync(e,"utf8");return Z.load(s)}catch(s){return console.error("[history-loader] Error parsing validation.yaml:",s),null}}function fo(n,e){return e.map(s=>wn(n,s))}function wn(n,e){let s=n.index?.by_symbol?.[e]||null,t=[];if(n.index?.co_changes){for(let r of n.index.co_changes)if(r.symbols.includes(e))for(let o of r.symbols)o!==e&&!t.includes(o)&&t.push(o);}let i=n.validation?.by_symbol?.[e]||null;return {symbol:e,summary:s,recent:s?.recent||[],co_changes:t,validation:i}}function yo(n,e){let s=[],t=[];if(!n.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let o of e){let a=n.index.by_symbol?.[o];a&&(a.fragility==="high"||a.fragility==="critical")&&s.push({symbol:o,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=n.index.fragile_symbols?.find(l=>l.symbol===o);c&&!s.find(l=>l.symbol===o)&&s.push(c);}for(let o of e){let a=n.index.co_changes?.filter(c=>c.symbols.includes(o));if(a?.length)for(let c of a){let l=c.symbols.filter(d=>d!==o&&!e.includes(d));l.length>0&&c.correlation>.7&&t.push(`${o} often changes with ${l.join(", ")} (${Math.round(c.correlation*100)}% correlation)`);}}let i=s.filter(o=>o.fragility==="critical").length===0,r=[];return s.length>0&&(r.push("Consider adding extra test coverage before modifying fragile symbols"),r.push("Review recent rollbacks and failures for these symbols")),t.length>0&&r.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:s,warnings:t,safe_to_modify:i,recommendations:r}}async function xs(n,e){let s=F.join(n,go),t=F.join(s,"log.jsonl");O.existsSync(s)||O.mkdirSync(s,{recursive:true});let i=id(t),r=new Date().toISOString(),o={id:i,ts:r,...e},a=JSON.stringify(o)+`
|
|
3
3
|
`;return O.appendFileSync(t,a),i}async function ho(n,e,s,t){return xs(n,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:s,tests:t})}function id(n){let e=1;return O.existsSync(n)&&(e=O.readFileSync(n,"utf8").split(`
|
|
4
4
|
`).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}function rd(n){let e=F.resolve(n),s=O.readFileSync(e,"utf8"),t=Z.load(s);if(!t||typeof t!="object")throw new Error(`Invalid workspace file: ${n}`);let i={version:String(t.version||"1.0"),name:String(t.name||"unnamed-workspace"),members:[]};if(Array.isArray(t.members)){for(let r of t.members)if(typeof r=="object"&&r!==null){let o=r;i.members.push({name:String(o.name||""),path:String(o.path||""),role:o.role,exports:Array.isArray(o.exports)?o.exports.map(String):void 0});}}return i}function wo(n,e){let s=F.resolve(n),t=F.resolve(s,e);if(!O.existsSync(t))return console.error(`Warning: Workspace file not found at ${t}`),null;let i;try{i=rd(t);}catch(c){return console.error(`Warning: Could not parse workspace file: ${c.message}`),null}let r=F.dirname(t),o="";for(let c of i.members){let l=F.resolve(r,c.path);if(bo(l)===bo(s)){o=c.name;break}}if(!o)return console.error(`Warning: Current directory is not a member of workspace "${i.name}"`),null;let a=new Map;for(let c of i.members){if(c.name===o)continue;let l=F.resolve(r,c.path),d=F.join(l,".paradigm","scan-index.json");if(!O.existsSync(d)){console.error(`Warning: No scan-index.json for workspace member "${c.name}" at ${d}`);continue}try{let p=JSON.parse(O.readFileSync(d,"utf8")),u=cd(p);c.exports&&c.exports.length>0&&(u=od(u,c.exports));let g=null,m=F.join(l,"portal.yaml");if(O.existsSync(m))try{let y=O.readFileSync(m,"utf8"),f=Z.load(y);f&&(g=f);}catch{}a.set(c.name,{index:u,gateConfig:g});}catch(p){console.error(`Warning: Could not load index for workspace member "${c.name}": ${p.message}`);}}return {config:i,workspacePath:t,currentMember:o,siblingIndices:a}}function od(n$1,e){let t=n(n$1).filter(i=>{let r=i.symbol;return e.some(o=>ad(o,r))});return ld(t)}function ad(n,e){let s=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${s}$`,"i").test(e)}function Tt(n,e){let s=[];for(let[t,i]of n.siblingIndices){let r=j$2(i.index,e);for(let o of r)s.push({project:t,symbol:`${t}/${o.symbol}`,type:o.type,description:o.description,filePath:o.filePath});}return s}function vo(n$1,e){let s=[],t=e.includes("/")?e.split("/").pop():e;for(let[i,r]of n$1.siblingIndices){let o=[],a=n(r.index);for(let c of a){let l=c.references||[],d=c.description||"",p=l.some(g=>g===t||g===e||g.endsWith(`/${t}`)),u=d.includes(t);(p||u)&&o.push({symbol:c.symbol,type:c.type,description:c.description});}o.length>0&&s.push({project:i,references:o});}return s}function bo(n){return F.resolve(n).replace(/\/+$/,"")}function cd(n){let e={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"},s=[];for(let[t,i]of Object.entries(e)){let r=n[t];if(!(!r||typeof r!="object"))for(let[o,a]of Object.entries(r)){let c={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"}[i]||"#";s.push({id:o,symbol:a.symbol||`${c}${o}`,type:i,source:"purpose",filePath:a.path||"",data:{},references:a.related||[],referencedBy:[],description:a.description,tags:a.visualTags||[]});}}return g$2({symbols:s,purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}function ld(n){return g$2({symbols:n.map(e=>({id:e.id||e.symbol.replace(/^[#$^!~]/,""),symbol:e.symbol,type:e.type,source:"purpose",filePath:e.filePath||"",data:e.data||{},references:e.references||[],referencedBy:e.referencedBy||[],description:e.description,tags:e.tags})),purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}async function Ps(n){let e=F.resolve(n),s=await f(e),t=g$2(s),i=null,r=F.join(e,"portal.yaml");if(O.existsSync(r))try{i=await e$1(r);}catch(d){console.error("Warning: Could not parse portal.yaml:",d.message);}let o=F.basename(e),a=F.join(e,".premise");if(O.existsSync(a))try{let p=O.readFileSync(a,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);p&&(o=p[1].trim());}catch{}let c=null,l=F.join(e,".paradigm","config.yaml");if(O.existsSync(l))try{let d=O.readFileSync(l,"utf8"),p=Z.load(d);p&&typeof p=="object"&&(p.version||console.error('[paradigm] Warning: config.yaml missing "version" field'),p.project||console.error('[paradigm] Warning: config.yaml missing "project" field')),p&&typeof p.workspace=="string"&&(c=wo(e,p.workspace));}catch(d){console.error(`[paradigm] Warning: Failed to load workspace config: ${d.message}`);}return {rootDir:e,index:t,aggregation:s,gateConfig:i,projectName:o,wisdom:null,history:null,workspace:c,_loadedAt:Date.now()}}async function se(n){return n.wisdom||(n.wisdom=await co(n.rootDir)),n.wisdom}async function ke(n){return n.history||(n.history=await mo(n.rootDir)),n.history}function dd(n){return {id:n.id,symbol:`^${n.id}`,description:n.description,locks:n.locks?.map(e=>({id:e.id,description:e.description,keys:e.keys?.map(s=>s.expression||s),mode:e.mode||"all"})),prizes:n.prizes?.map(e=>({id:e.id,oneTime:e.oneTime}))}}function ko(n){let e=n.gateConfig?.gates||[],s=i(n.index,"gate"),t=new Map;for(let i of s){let r=i.symbol.replace(/^\^/,"");t.set(r,{id:r,symbol:i.symbol,description:i.description,source:"purpose",filePath:i.filePath,data:i.data});}for(let i of e)t.set(i.id,{...dd(i),source:"portal.yaml"});return Array.from(t.values())}function So(n){let e=n.gateConfig?.flows||[],s=i(n.index,"flow"),t=new Map;for(let i of s){let r=i.symbol.replace(/^\$/,"");t.set(r,{id:r,symbol:i.symbol,description:i.description,source:"purpose",filePath:i.filePath,data:i.data});}for(let i of e)t.set(i.id,{id:i.id,symbol:`$${i.id}`,description:i.description,gates:i.gates,source:"portal.yaml"});return Array.from(t.values())}function xo(){return [{uri:"paradigm://wisdom/preferences",name:"Wisdom - Preferences",description:"Team preferences for patterns, testing, and code style",mimeType:"application/json"},{uri:"paradigm://wisdom/antipatterns",name:"Wisdom - Antipatterns",description:"What NOT to do, with reasons and alternatives",mimeType:"application/json"},{uri:"paradigm://wisdom/decisions",name:"Wisdom - Decisions",description:"Architectural Decision Records (ADRs) index",mimeType:"application/json"}]}async function Co(n,e){if(n==="wisdom/preferences"){let s=await se(e);return {handled:true,text:JSON.stringify({version:s.preferences?.version||"1.0",global:s.preferences?.global||{},by_symbol:s.preferences?.by_symbol||{},symbol_count:Object.keys(s.preferences?.by_symbol||{}).length},null,2)}}if(n.startsWith("wisdom/preferences/")){let s=decodeURIComponent(n.replace("wisdom/preferences/","")),t=await se(e),i=yn(t,s);return {handled:true,text:JSON.stringify({symbol:s,preferences:i.preferences,global:t.preferences?.global||{}},null,2)}}if(n==="wisdom/antipatterns"){let s=await se(e);return {handled:true,text:JSON.stringify({count:s.antipatterns.length,antipatterns:s.antipatterns},null,2)}}if(n.startsWith("wisdom/antipatterns/")){let s=decodeURIComponent(n.replace("wisdom/antipatterns/","")),t=await se(e),i=yn(t,s);return {handled:true,text:JSON.stringify({symbol:s,count:i.antipatterns.length,antipatterns:i.antipatterns},null,2)}}if(n==="wisdom/decisions"){let s=await se(e);return {handled:true,text:JSON.stringify({count:s.decisions.length,decisions:s.decisions.map(t=>({id:t.id,title:t.title,status:t.status,date:t.date,symbols:t.symbols}))},null,2)}}if(n.startsWith("wisdom/decision/")){let s=n.replace("wisdom/decision/",""),t=await se(e),i=t.decisions.find(r=>r.id===s);return i?{handled:true,text:JSON.stringify(i,null,2)}:{handled:true,text:JSON.stringify({error:"Decision not found",id:s,available:t.decisions.map(r=>r.id)},null,2)}}if(n.startsWith("wisdom/expertise/")){let s=decodeURIComponent(n.replace("wisdom/expertise/","")),t=await se(e),i=hn(t,{symbol:s});return {handled:true,text:JSON.stringify({symbol:s,count:i.length,experts:i.map(r=>({name:r.name,symbols:r.symbols,areas:r.areas,contact:r.contact}))},null,2)}}return {handled:false,text:""}}function Po(){return [{uri:"paradigm://history/fragile",name:"History - Fragile Symbols",description:"Symbols with high fragility that need extra care when modifying",mimeType:"application/json"},{uri:"paradigm://history/validation/summary",name:"History - Validation Summary",description:"Overall validation statistics and pass rates",mimeType:"application/json"}]}async function Ro(n,e){if(n.startsWith("history/symbol/")&&!n.endsWith("/recent")){let s=decodeURIComponent(n.replace("history/symbol/","")),t=await ke(e),i=wn(t,s);return {handled:true,text:JSON.stringify({symbol:s,summary:i.summary?{total_changes:i.summary.total_changes,last_modified:i.summary.last_modified,stability_score:i.summary.stability_score,fragility:i.summary.fragility,contributors:i.summary.contributors}:null,recent:i.recent,co_changes:i.co_changes,validation:i.validation},null,2)}}if(n.startsWith("history/symbol/")&&n.endsWith("/recent")){let s=decodeURIComponent(n.replace("history/symbol/","").replace("/recent","")),t=await ke(e),i=wn(t,s);return {handled:true,text:JSON.stringify({symbol:s,fragility:i.summary?.fragility||"unknown",stability_score:i.summary?.stability_score,recent:i.recent.slice(0,5)},null,2)}}if(n==="history/fragile"){let s=await ke(e);return {handled:true,text:JSON.stringify({count:s.index?.fragile_symbols?.length||0,fragile_symbols:s.index?.fragile_symbols||[],recommendation:"Consider adding extra test coverage and reviewing recent changes before modifying these symbols"},null,2)}}if(n.startsWith("history/cochanges/")){let s=decodeURIComponent(n.replace("history/cochanges/","")),i=(await ke(e)).index?.co_changes?.filter(r=>r.symbols.includes(s))||[];return {handled:true,text:JSON.stringify({symbol:s,count:i.length,co_changes:i.map(r=>({with:r.symbols.filter(o=>o!==s),frequency:r.frequency,correlation:r.correlation})),recommendation:i.length>0?"These symbols often change together - consider if they need updates too":"No strong co-change patterns detected"},null,2)}}if(n==="history/validation/summary"){let s=await ke(e);return {handled:true,text:JSON.stringify({last_run:s.validation?.last_run,total_validations:s.validation?.total_validations||0,pass_rate:s.validation?.pass_rate||0,by_symbol:s.validation?.by_symbol||{}},null,2)}}return {handled:false,text:""}}function jo(){return [{uri:"paradigm://context/agent-protocol",name:"Agent Protocol",description:"IMPORTANT: Read this first. Workflow instructions for using Paradigm MCP tools effectively.",mimeType:"text/markdown"},{uri:"paradigm://context/session",name:"Session Info",description:"Current MCP session statistics and context usage estimate",mimeType:"application/json"},{uri:"paradigm://context/handoff-guide",name:"Handoff Guide",description:"When and how to perform context handoffs",mimeType:"text/markdown"}]}async function To(n,e){if(n==="context/agent-protocol")return {handled:true,text:`# Agent Protocol for Paradigm MCP Tools
|
|
5
5
|
|
|
@@ -730,10 +730,10 @@ Examples:
|
|
|
730
730
|
- "Fix the login bug" \u2192 quick (greenlight or escalate)
|
|
731
731
|
- "Add user authentication with JWT" \u2192 plan \u2192 architect + security + builder + tester
|
|
732
732
|
- "Should I use soft delete or hard delete?" \u2192 plan \u2192 architect only (analysis)
|
|
733
|
-
- "Refactor the payment module" \u2192 plan \u2192 architect + builder`,inputSchema:{type:"object",properties:{task:{type:"string",description:'The task to orchestrate (e.g., "Build @payment-system with Stripe integration")'},mode:{type:"string",enum:["quick","plan","execute"],description:'Mode: "quick" for lightweight pre-check (advocate + reviewer), "plan" returns suggested agents and plan, "execute" returns prompts ready for Task tool'},agents:{type:"array",items:{type:"string"},description:'Optional: Override which agents to use (e.g., ["architect", "builder"])'}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_prompt",description:"Get the complete prompt for a specific agent to execute a task. Use this when you need to spawn an agent via the Task tool with full context.",inputSchema:{type:"object",properties:{agent:{type:"string",enum:["advocate","architect","builder","tester","reviewer","security","documentor"],description:"The agent role to get prompt for"},task:{type:"string",description:"The specific task for this agent"},handoffContext:{type:"string",description:"Optional: Context passed from a previous agent"},previousAgent:{type:"string",description:"Optional: Name of the agent that handed off"}},required:["agent","task"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ya(n,e,s){return n==="paradigm_orchestrate_inline"?Jd(e,s):n==="paradigm_agent_prompt"?Ud(e,s):{handled:false,text:""}}async function Jd(n,e){let s=n.task,t=n.mode||"execute",i=n.agents;try{let b=F.join(e.rootDir,".paradigm",".orchestrated");O.writeFileSync(b,new Date().toISOString(),"utf8");}catch{}let r=wa(e.rootDir);if(!r){let b=JSON.stringify({error:"No agents.yaml found",suggestion:"Run `paradigm team init` to set up multi-agent orchestration"},null,2);return o(b.length,"paradigm_orchestrate_inline"),{handled:true,text:b}}let o$1=b$7(e.rootDir);if(o$1&&r.agents){let b={};for(let[h,w]of Object.entries(r.agents))o$1.includes(h)&&(b[h]=w);r.agents=b;}let a=It(s),c=[];try{let{processPendingEvents:b,loadNominations:h}=await import('./nomination-engine-
|
|
733
|
+
- "Refactor the payment module" \u2192 plan \u2192 architect + builder`,inputSchema:{type:"object",properties:{task:{type:"string",description:'The task to orchestrate (e.g., "Build @payment-system with Stripe integration")'},mode:{type:"string",enum:["quick","plan","execute"],description:'Mode: "quick" for lightweight pre-check (advocate + reviewer), "plan" returns suggested agents and plan, "execute" returns prompts ready for Task tool'},agents:{type:"array",items:{type:"string"},description:'Optional: Override which agents to use (e.g., ["architect", "builder"])'}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_prompt",description:"Get the complete prompt for a specific agent to execute a task. Use this when you need to spawn an agent via the Task tool with full context.",inputSchema:{type:"object",properties:{agent:{type:"string",enum:["advocate","architect","builder","tester","reviewer","security","documentor"],description:"The agent role to get prompt for"},task:{type:"string",description:"The specific task for this agent"},handoffContext:{type:"string",description:"Optional: Context passed from a previous agent"},previousAgent:{type:"string",description:"Optional: Name of the agent that handed off"}},required:["agent","task"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ya(n,e,s){return n==="paradigm_orchestrate_inline"?Jd(e,s):n==="paradigm_agent_prompt"?Ud(e,s):{handled:false,text:""}}async function Jd(n,e){let s=n.task,t=n.mode||"execute",i=n.agents;try{let b=F.join(e.rootDir,".paradigm",".orchestrated");O.writeFileSync(b,new Date().toISOString(),"utf8");}catch{}let r=wa(e.rootDir);if(!r){let b=JSON.stringify({error:"No agents.yaml found",suggestion:"Run `paradigm team init` to set up multi-agent orchestration"},null,2);return o(b.length,"paradigm_orchestrate_inline"),{handled:true,text:b}}let o$1=b$7(e.rootDir);if(o$1&&r.agents){let b={};for(let[h,w]of Object.entries(r.agents))o$1.includes(h)&&(b[h]=w);r.agents=b;}let a=It(s),c=[];try{let{processPendingEvents:b,loadNominations:h}=await import('./nomination-engine-K7MQD53E.js');b(e.rootDir),c=h(e.rootDir,{pending_only:!0,limit:10}).filter(_=>_.urgency==="high"||_.urgency==="critical").map(_=>({agent:_.agent,urgency:_.urgency,brief:_.brief}));}catch{}let l=ep(s);if(t==="quick")return Gd(s,a,l,c,r,e);let d=Bd(s,r.agents,i,l,r.orchestration);if(t==="plan"){let b=np(s,r.agents),h=tp(d,l),w;try{let{loadNotebookEntries:x}=await import('./notebook-loader-CENTDDUJ.js'),C=a.map(P=>P.replace(/^[#$^!~@&%?]/,"").toLowerCase()),T={},j=new Set;for(let P of d.stages)for(let D of P.agents){if(j.has(D.name))continue;j.add(D.name);let I=x(D.name,e.rootDir),A=C.length>0?x(D.name,e.rootDir,{concepts:C}):I;I.length>0&&(T[D.name]={totalEntries:I.length,relevantEntries:A.length});}Object.keys(T).length>0&&(w=T);}catch{}let _=d.stages.flatMap(x=>x.agents.map(C=>C.name)),k=ha(_,r.agents),v=k.length>0?{edges:k,note:"Shows which agents hand off to which based on agents.yaml handoff_to. Stage ordering was derived from this graph."}:void 0,S=JSON.stringify({task:s,mode:"plan",classification:{type:l.type,complexity:l.complexity,securityRequired:l.securityRequired,costMultiplier:l.costMultiplier},plan:d,suggestedAgents:b,costPreview:h,...v?{collaborationGraph:v}:{},...w?{notebookKnowledge:w,notebookNote:"Agents with relevant notebook entries will have curated knowledge injected into their prompts during execute mode."}:{},...c.length>0?{activeNominations:c,nominationNote:`${c.length} high-urgency agent nomination(s) pending. These agents have been flagged by the system for attention on this project.`}:{},instructions:["Review task classification and cost preview above","Review suggested agents based on task triggers",...v?["Review collaboration graph \u2014 stage ordering was derived from agent handoff_to edges"]:[],...w?["Review notebook knowledge \u2014 agents with relevant entries will receive curated snippets in execute mode"]:[],...c.length>0?["Review active nominations \u2014 agents flagged by the system may need to be included"]:[],'Call again with mode="execute" to get full prompts and execution strategy',"Stages marked canRunParallel: true can be launched simultaneously","After each agent completes, pass handoff context to the next stage"]},null,2);return o(S.length,"paradigm_orchestrate_inline"),{handled:true,text:S}}let p=new Map;try{let{loadAgentProfile:b,buildProfileEnrichment:h}=await import('./agent-loader-MQMXCI3D.js'),{loadDecisions:w}=await import('./decision-loader-2XPZE4EZ.js'),{loadJournalEntries:_}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:k}=await import('./nomination-engine-K7MQD53E.js'),{loadAgentState:v}=await import('./agent-state-KSQ3S7OB.js'),{loadNotebookEntries:S}=await import('./notebook-loader-CENTDDUJ.js'),x=w(e.rootDir,{status:"active",limit:5}).map(j=>({title:j.title,decision:j.decision.slice(0,150)})),C=k(e.rootDir,{pending_only:!0,limit:10}).map(j=>({urgency:j.urgency,brief:j.brief})),T=a.map(j=>j.replace(/^[#$^!~@&%?]/,"").toLowerCase());for(let j of d.stages)for(let P of j.agents)if(!p.has(P.name)){let D=b(e.rootDir,P.name);if(D){if(D.benched)continue;let I=_(P.name,{transferable:!0,limit:5}).map(q=>({trigger:q.trigger,insight:q.insight.slice(0,150)})),A=v(P.name,e.rootDir),N;try{let q=S(P.name,e.rootDir,T.length>0?{concepts:T}:void 0);q.length>0&&(N=q.sort((et,yi)=>yi.confidence-et.confidence||new Date(yi.updated).getTime()-new Date(et.updated).getTime()).slice(0,5).map(et=>({context:et.context,snippet:et.snippet,concepts:et.concepts})));}catch{}let H=h(D,a,N,{recentDecisions:x,journalInsights:I,pendingNominations:C},A?{lastSession:A.lastSession,pendingWork:A.pendingWork,recentPatterns:A.recentPatterns,sessionsOnProject:A.sessionsOnProject}:void 0);if(D.permissions){let q=[`
|
|
734
734
|
## Permission Constraints`];D.permissions.paths?.deny?.length&&q.push(`**Denied paths:** ${D.permissions.paths.deny.join(", ")}`),D.permissions.paths?.write?.length&&q.push(`**Writable paths:** ${D.permissions.paths.write.join(", ")}`),D.permissions.tools?.deny?.length&&q.push(`**Denied tools:** ${D.permissions.tools.deny.join(", ")}`),D.permissions.dangerous_actions?.length&&q.push(`**Requires approval for:** ${D.permissions.dangerous_actions.join(", ")}`),H+=`
|
|
735
735
|
`+q.join(`
|
|
736
|
-
`);}H.trim()&&p.set(P.name,{enrichment:H,nickname:D.nickname});}}}catch{}let u=[];for(let b of d.stages){let h=[];for(let w of b.agents){let _=r.agents[w.name],k={name:_?.name||w.name,role:_?.role||At[w.name]||`${w.name} agent`,focus:_?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:ma(w.name,e.rootDir,_),triggers:_?.triggers,handoff_to:_?.handoff_to,context:_?.context,protocol:_?.protocol},v=p.get(w.name),S=ba({agent:k,task:w.task,symbols:a,dependsOn:w.dependsOn,profileEnrichment:v?.enrichment,nickname:v?.nickname});h.push(S);}u.push({stage:b.stage,canRunParallel:b.canRunParallel,agents:h});}let g=`orch-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`;sp(e.rootDir,g,s,d);try{let{appendSessionWorkEntry:b}=await import('./session-work-log-J2H5OZBR.js');for(let h of u)for(let w of h.agents)b(e.rootDir,{timestamp:new Date().toISOString(),type:"agent-contribution",agent:w.agent,contribution:w.taskDescription?.slice(0,200)||s.slice(0,200),attribution:w.attribution,symbols:a});}catch{}try{let{recordAgentSession:b}=await import('./agent-state-KSQ3S7OB.js'),w=(await import('./session-tracker-SKOMBDOW.js')).default?.session?.sessionId||g;for(let _ of u)for(let k of _.agents)b(k.agent,e.rootDir,{sessionId:w,summary:`${k.attribution||k.agent}: ${(k.taskDescription||s).slice(0,200)}`,symbolsTouched:a});}catch{}let m=`thr-orch-${g}`;try{let b=await import('./symphony-loader-XACVV2E3.js'),h=F.basename(e.rootDir),w=`${h}/maestro`;try{b.getMyIdentity(e.rootDir)||b.registerAgent(e.rootDir,"maestro","Maestro (orchestrator)");}catch{}b.createThread(`Orchestration: ${s.slice(0,80)}`,{id:w,name:"Maestro",type:"agent",project:h,role:"orchestrator"});let _=F.join(ga.homedir(),".paradigm","score","threads"),k=O.readdirSync(_).filter(S=>S.endsWith(".json")).sort(),v=k[k.length-1];if(v){let S=F.join(_,v),x=F.join(_,`${m}.json`),C=JSON.parse(O.readFileSync(S,"utf8"));C.id=m,O.writeFileSync(x,JSON.stringify(C,null,2),"utf8"),S!==x&&O.unlinkSync(S);}for(let S of u)for(let x of S.agents){let C=b.buildMessage({threadRoot:m,sender:{id:w,name:"Maestro",type:"agent",project:h,role:"orchestrator"},intent:"task",text:`[Maestro] Stage ${S.stage}: Assigned to ${x.attribution||x.agent} \u2014 ${x.taskDescription||s}`,symbols:a,metadata:{task:{stage:S.stage,canRunParallel:S.canRunParallel}}});b.routeMessage(C);}}catch{}let y={orchestrationId:g,task:s,mode:"execute",symbols:a,totalAgents:d.estimatedAgents,...c.length>0?{activeNominations:c}:{},stages:u,executionInstructions:["Execute stages in order (stage 0, then stage 1, etc.)","Agents within a stage can be run in parallel if your environment supports it","Pass handoff context between stages",'Present each agent response as an attributed message using the attribution prefix (e.g., "[architect] Rate limiter should go before ^authenticated")',"Do NOT synthesize agent responses \u2014 show them as distinct contributions from each agent","After all agents in a stage complete, reconcile their outputs before proceeding to the next stage"],claudeCode:{method:"Task tool",example:{description:u[0]?.agents[0]?.taskDescription||"Agent task",prompt:"(see agent prompts above)",subagent_type:"general-purpose"},parallel:"Launch multiple Task calls in one message for parallel stages"},sequential:{method:"Execute each role in sequence within this session",steps:d.stages.map((b,h)=>({stage:h,rolePrompt:`Adopt the ${b.agents[0]?.name} role. Focus ONLY on: ${b.agents.map(w=>w.task).join(", ")}`,constraint:h===0?"Design/plan only \u2014 do NOT write implementation code":h===d.stages.length-1?"Verify and test \u2014 do NOT change implementation":"Implement following the design from the previous stage"}))},cli:{method:"paradigm team orchestrate",command:`paradigm team orchestrate "${s}"`,note:"Spawns independent agent processes \u2014 works from any terminal"},symphony:{enabled:true,orchestrationThread:m,instructions:["After each agent completes, call paradigm_symphony_send to report progress. This makes the work visible in Conductor.",'Use intent "context" for analysis, "proposal" for recommendations, "decision" for decisions made',`Set threadRoot to "${m}" so all contributions are in one thread`,"Include the symbols array from the agent relay output"],perAgentInstruction:`When each agent finishes, run: paradigm_symphony_send threadId="${m}" intent="task-complete" text="[agentName] Summary of completed work" symbols=[touched symbols]`,exampleCall:{intent:"context",text:"[architect] Rate limiter should be placed before ^authenticated gate to prevent unauthenticated flood",threadRoot:m,symbols:["#rate-limiter","^authenticated"]}}},f=JSON.stringify(y,null,2);return o(f.length,"paradigm_orchestrate_inline"),{handled:true,text:f}}async function Gd(n,e,s,t,i,r){let o$1=n.toLowerCase(),a=[];s.securityRequired&&a.push("security-adjacent task (auth, gates, permissions detected)"),s.complexity==="high"&&a.push(`high complexity task (type: ${s.type})`),e.length>=4&&a.push(`${e.length} symbols in scope \u2014 cross-cutting change`);let c=t.filter(f=>f.urgency==="critical");c.length>0&&a.push(`${c.length} critical agent nomination(s) pending`);let l={assumptions:[],risks:[],edgeCases:[],questions:[]};(o$1.includes("simple")||o$1.includes("just")||o$1.includes("only"))&&l.assumptions.push("Task framed as simple \u2014 verify no hidden complexity"),(o$1.includes("always")||o$1.includes("never"))&&l.assumptions.push("Absolute language detected \u2014 edge cases likely exist"),!o$1.includes("error")&&!o$1.includes("fail")&&!o$1.includes("invalid")&&l.assumptions.push("No error/failure handling mentioned \u2014 what happens when it fails?"),e.some(f=>f.startsWith("$"))&&l.risks.push("Flow symbols detected \u2014 multi-step changes have ordering/rollback risk"),e.some(f=>f.startsWith("^"))&&(l.risks.push("Gate symbols detected \u2014 authorization changes require security review"),a.some(f=>f.includes("security"))||a.push("gate symbols in scope \u2014 security review recommended")),s.matchedKeywords.some(f=>["migration","database","schema"].includes(f))&&l.risks.push("Data migration risk \u2014 irreversible changes need rollback plan"),s.matchedKeywords.some(f=>["delete","remove","drop"].includes(f))&&l.risks.push("Destructive operation \u2014 verify nothing depends on removed items"),(o$1.includes("add")||o$1.includes("new"))&&l.edgeCases.push("New feature \u2014 how does it interact with existing features?"),(o$1.includes("refactor")||o$1.includes("rename"))&&l.edgeCases.push("Refactor \u2014 all callers updated? Integration tests cover the change?"),(o$1.includes("fix")||o$1.includes("bug"))&&l.edgeCases.push("Bug fix \u2014 does the fix address the root cause or just the symptom?"),o$1.includes("test")||l.questions.push("How will this be tested?"),e.length===0&&l.questions.push("No symbols referenced \u2014 which components are actually affected?");let d={concerns:[],suggestions:[]};for(let f of e){let b=f.replace(/^[#$^!~@&%?]/,"");!i.agents[b]&&f.startsWith("#");}s.costMultiplier.max>1&&d.concerns.push(`Higher-than-average complexity (${s.costMultiplier.min}x-${s.costMultiplier.max}x baseline) \u2014 consider breaking into smaller tasks`);let p=[];try{let{loadNotebookEntries:f}=await import('./notebook-loader-CENTDDUJ.js'),b=e.map(w=>w.replace(/^[#$^!~@&%?]/,"").toLowerCase()),h=f("advocate",r.rootDir,b.length>0?{concepts:b}:void 0);h.length>0&&(p=h.sort((w,_)=>_.confidence-w.confidence).slice(0,3).map(w=>w.snippet));}catch{}let g=a.length>=2||a.some(f=>f.includes("security")||f.includes("critical"))?"escalate":"greenlight",m={mode:"quick",task:n,verdict:g,classification:{type:s.type,complexity:s.complexity,securityRequired:s.securityRequired},advocate:{agent:"Jinx (advocate)",...l.assumptions.length>0?{assumptions:l.assumptions}:{},...l.risks.length>0?{risks:l.risks}:{},...l.edgeCases.length>0?{edgeCases:l.edgeCases}:{},...l.questions.length>0?{questions:l.questions}:{},...p.length>0?{notebookInsights:p}:{}},reviewer:{agent:"reviewer",...d.concerns.length>0?{concerns:d.concerns}:{},...d.suggestions.length>0?{suggestions:d.suggestions}:{}},...a.length>0?{escalationSignals:a}:{},...t.length>0?{activeNominations:t}:{},symbols:e,instructions:g==="greenlight"?["Quick check passed \u2014 proceed with implementation.","Orchestration enforcement is satisfied.",l.questions.length>0?`Address Jinx's questions during implementation: ${l.questions.join("; ")}`:"No open questions from advocate."]:["Quick check recommends full orchestration.",`Escalation reasons: ${a.join("; ")}`,'Call paradigm_orchestrate_inline mode="plan" for full agent planning.',"Orchestration enforcement is satisfied regardless of verdict."]},y=JSON.stringify(m,null,2);return o(y.length,"paradigm_orchestrate_inline"),{handled:true,text:y}}async function Ud(n,e){let s=n.agent,t=n.task,i=n.handoffContext,r=n.previousAgent,o$1=wa(e.rootDir),a=b$7(e.rootDir);if(a&&!a.includes(s)){let f=JSON.stringify({warning:`Agent "${s}" is not on this project's roster`,suggestion:`Run paradigm_agent_activate id="${s}" to add it, or check .paradigm/roster.yaml`,activeRoster:a},null,2);return o(f.length,"paradigm_agent_prompt"),{handled:true,text:f}}let c=o$1?.agents[s],l={name:c?.name||s,role:c?.role||At[s]||At.builder,focus:c?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:ma(s,e.rootDir,c),triggers:c?.triggers,handoff_to:c?.handoff_to,context:c?.context,protocol:c?.protocol},d=It(t),p,u;try{let{loadAgentProfile:f,buildProfileEnrichment:b}=await import('./agent-loader-EPXURMO7.js'),{loadDecisions:h}=await import('./decision-loader-2XPZE4EZ.js'),{loadJournalEntries:w}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:_}=await import('./nomination-engine-XF7TWPAP.js'),{loadNotebookEntries:k}=await import('./notebook-loader-CENTDDUJ.js'),v=f(e.rootDir,s);if(v){u=v.nickname;let S=h(e.rootDir,{status:"active",limit:5}).map(P=>({title:P.title,decision:P.decision.slice(0,150)})),x=w(s,{transferable:!0,limit:5}).map(P=>({trigger:P.trigger,insight:P.insight.slice(0,150)})),C=_(e.rootDir,{pending_only:!0,limit:10}).map(P=>({urgency:P.urgency,brief:P.brief})),T;try{let P=d.map(I=>I.replace(/^[#$^!~@&%?]/,"").toLowerCase()),D=k(s,e.rootDir,P.length>0?{concepts:P}:void 0);D.length>0&&(T=D.sort((A,N)=>N.confidence-A.confidence||new Date(N.updated).getTime()-new Date(A.updated).getTime()).slice(0,5).map(A=>({context:A.context,snippet:A.snippet,concepts:A.concepts})));}catch{}let j=b(v,d,T,{recentDecisions:S,journalInsights:x,pendingNominations:C});if(v.permissions){let P=[`
|
|
736
|
+
`);}H.trim()&&p.set(P.name,{enrichment:H,nickname:D.nickname});}}}catch{}let u=[];for(let b of d.stages){let h=[];for(let w of b.agents){let _=r.agents[w.name],k={name:_?.name||w.name,role:_?.role||At[w.name]||`${w.name} agent`,focus:_?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:ma(w.name,e.rootDir,_),triggers:_?.triggers,handoff_to:_?.handoff_to,context:_?.context,protocol:_?.protocol},v=p.get(w.name),S=ba({agent:k,task:w.task,symbols:a,dependsOn:w.dependsOn,profileEnrichment:v?.enrichment,nickname:v?.nickname});h.push(S);}u.push({stage:b.stage,canRunParallel:b.canRunParallel,agents:h});}let g=`orch-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`;sp(e.rootDir,g,s,d);try{let{appendSessionWorkEntry:b}=await import('./session-work-log-IEYBPFUC.js');for(let h of u)for(let w of h.agents)b(e.rootDir,{timestamp:new Date().toISOString(),type:"agent-contribution",agent:w.agent,contribution:w.taskDescription?.slice(0,200)||s.slice(0,200),attribution:w.attribution,symbols:a});}catch{}try{let{recordAgentSession:b}=await import('./agent-state-KSQ3S7OB.js'),w=(await import('./session-tracker-G7VOLRMR.js')).default?.session?.sessionId||g;for(let _ of u)for(let k of _.agents)b(k.agent,e.rootDir,{sessionId:w,summary:`${k.attribution||k.agent}: ${(k.taskDescription||s).slice(0,200)}`,symbolsTouched:a});}catch{}let m=`thr-orch-${g}`;try{let b=await import('./symphony-loader-XJT43FOS.js'),h=F.basename(e.rootDir),w=`${h}/maestro`;try{b.getMyIdentity(e.rootDir)||b.registerAgent(e.rootDir,"maestro","Maestro (orchestrator)");}catch{}b.createThread(`Orchestration: ${s.slice(0,80)}`,{id:w,name:"Maestro",type:"agent",project:h,role:"orchestrator"});let _=F.join(ga.homedir(),".paradigm","score","threads"),k=O.readdirSync(_).filter(S=>S.endsWith(".json")).sort(),v=k[k.length-1];if(v){let S=F.join(_,v),x=F.join(_,`${m}.json`),C=JSON.parse(O.readFileSync(S,"utf8"));C.id=m,O.writeFileSync(x,JSON.stringify(C,null,2),"utf8"),S!==x&&O.unlinkSync(S);}for(let S of u)for(let x of S.agents){let C=b.buildMessage({threadRoot:m,sender:{id:w,name:"Maestro",type:"agent",project:h,role:"orchestrator"},intent:"task",text:`[Maestro] Stage ${S.stage}: Assigned to ${x.attribution||x.agent} \u2014 ${x.taskDescription||s}`,symbols:a,metadata:{task:{stage:S.stage,canRunParallel:S.canRunParallel}}});b.routeMessage(C);}}catch{}let y={orchestrationId:g,task:s,mode:"execute",symbols:a,totalAgents:d.estimatedAgents,...c.length>0?{activeNominations:c}:{},stages:u,executionInstructions:["Execute stages in order (stage 0, then stage 1, etc.)","Agents within a stage can be run in parallel if your environment supports it","Pass handoff context between stages",'Present each agent response as an attributed message using the attribution prefix (e.g., "[architect] Rate limiter should go before ^authenticated")',"Do NOT synthesize agent responses \u2014 show them as distinct contributions from each agent","After all agents in a stage complete, reconcile their outputs before proceeding to the next stage"],claudeCode:{method:"Task tool",example:{description:u[0]?.agents[0]?.taskDescription||"Agent task",prompt:"(see agent prompts above)",subagent_type:"general-purpose"},parallel:"Launch multiple Task calls in one message for parallel stages"},sequential:{method:"Execute each role in sequence within this session",steps:d.stages.map((b,h)=>({stage:h,rolePrompt:`Adopt the ${b.agents[0]?.name} role. Focus ONLY on: ${b.agents.map(w=>w.task).join(", ")}`,constraint:h===0?"Design/plan only \u2014 do NOT write implementation code":h===d.stages.length-1?"Verify and test \u2014 do NOT change implementation":"Implement following the design from the previous stage"}))},cli:{method:"paradigm team orchestrate",command:`paradigm team orchestrate "${s}"`,note:"Spawns independent agent processes \u2014 works from any terminal"},symphony:{enabled:true,orchestrationThread:m,instructions:["After each agent completes, call paradigm_symphony_send to report progress. This makes the work visible in Conductor.",'Use intent "context" for analysis, "proposal" for recommendations, "decision" for decisions made',`Set threadRoot to "${m}" so all contributions are in one thread`,"Include the symbols array from the agent relay output"],perAgentInstruction:`When each agent finishes, run: paradigm_symphony_send threadId="${m}" intent="task-complete" text="[agentName] Summary of completed work" symbols=[touched symbols]`,exampleCall:{intent:"context",text:"[architect] Rate limiter should be placed before ^authenticated gate to prevent unauthenticated flood",threadRoot:m,symbols:["#rate-limiter","^authenticated"]}}},f=JSON.stringify(y,null,2);return o(f.length,"paradigm_orchestrate_inline"),{handled:true,text:f}}async function Gd(n,e,s,t,i,r){let o$1=n.toLowerCase(),a=[];s.securityRequired&&a.push("security-adjacent task (auth, gates, permissions detected)"),s.complexity==="high"&&a.push(`high complexity task (type: ${s.type})`),e.length>=4&&a.push(`${e.length} symbols in scope \u2014 cross-cutting change`);let c=t.filter(f=>f.urgency==="critical");c.length>0&&a.push(`${c.length} critical agent nomination(s) pending`);let l={assumptions:[],risks:[],edgeCases:[],questions:[]};(o$1.includes("simple")||o$1.includes("just")||o$1.includes("only"))&&l.assumptions.push("Task framed as simple \u2014 verify no hidden complexity"),(o$1.includes("always")||o$1.includes("never"))&&l.assumptions.push("Absolute language detected \u2014 edge cases likely exist"),!o$1.includes("error")&&!o$1.includes("fail")&&!o$1.includes("invalid")&&l.assumptions.push("No error/failure handling mentioned \u2014 what happens when it fails?"),e.some(f=>f.startsWith("$"))&&l.risks.push("Flow symbols detected \u2014 multi-step changes have ordering/rollback risk"),e.some(f=>f.startsWith("^"))&&(l.risks.push("Gate symbols detected \u2014 authorization changes require security review"),a.some(f=>f.includes("security"))||a.push("gate symbols in scope \u2014 security review recommended")),s.matchedKeywords.some(f=>["migration","database","schema"].includes(f))&&l.risks.push("Data migration risk \u2014 irreversible changes need rollback plan"),s.matchedKeywords.some(f=>["delete","remove","drop"].includes(f))&&l.risks.push("Destructive operation \u2014 verify nothing depends on removed items"),(o$1.includes("add")||o$1.includes("new"))&&l.edgeCases.push("New feature \u2014 how does it interact with existing features?"),(o$1.includes("refactor")||o$1.includes("rename"))&&l.edgeCases.push("Refactor \u2014 all callers updated? Integration tests cover the change?"),(o$1.includes("fix")||o$1.includes("bug"))&&l.edgeCases.push("Bug fix \u2014 does the fix address the root cause or just the symptom?"),o$1.includes("test")||l.questions.push("How will this be tested?"),e.length===0&&l.questions.push("No symbols referenced \u2014 which components are actually affected?");let d={concerns:[],suggestions:[]};for(let f of e){let b=f.replace(/^[#$^!~@&%?]/,"");!i.agents[b]&&f.startsWith("#");}s.costMultiplier.max>1&&d.concerns.push(`Higher-than-average complexity (${s.costMultiplier.min}x-${s.costMultiplier.max}x baseline) \u2014 consider breaking into smaller tasks`);let p=[];try{let{loadNotebookEntries:f}=await import('./notebook-loader-CENTDDUJ.js'),b=e.map(w=>w.replace(/^[#$^!~@&%?]/,"").toLowerCase()),h=f("advocate",r.rootDir,b.length>0?{concepts:b}:void 0);h.length>0&&(p=h.sort((w,_)=>_.confidence-w.confidence).slice(0,3).map(w=>w.snippet));}catch{}let g=a.length>=2||a.some(f=>f.includes("security")||f.includes("critical"))?"escalate":"greenlight",m={mode:"quick",task:n,verdict:g,classification:{type:s.type,complexity:s.complexity,securityRequired:s.securityRequired},advocate:{agent:"Jinx (advocate)",...l.assumptions.length>0?{assumptions:l.assumptions}:{},...l.risks.length>0?{risks:l.risks}:{},...l.edgeCases.length>0?{edgeCases:l.edgeCases}:{},...l.questions.length>0?{questions:l.questions}:{},...p.length>0?{notebookInsights:p}:{}},reviewer:{agent:"reviewer",...d.concerns.length>0?{concerns:d.concerns}:{},...d.suggestions.length>0?{suggestions:d.suggestions}:{}},...a.length>0?{escalationSignals:a}:{},...t.length>0?{activeNominations:t}:{},symbols:e,instructions:g==="greenlight"?["Quick check passed \u2014 proceed with implementation.","Orchestration enforcement is satisfied.",l.questions.length>0?`Address Jinx's questions during implementation: ${l.questions.join("; ")}`:"No open questions from advocate."]:["Quick check recommends full orchestration.",`Escalation reasons: ${a.join("; ")}`,'Call paradigm_orchestrate_inline mode="plan" for full agent planning.',"Orchestration enforcement is satisfied regardless of verdict."]},y=JSON.stringify(m,null,2);return o(y.length,"paradigm_orchestrate_inline"),{handled:true,text:y}}async function Ud(n,e){let s=n.agent,t=n.task,i=n.handoffContext,r=n.previousAgent,o$1=wa(e.rootDir),a=b$7(e.rootDir);if(a&&!a.includes(s)){let f=JSON.stringify({warning:`Agent "${s}" is not on this project's roster`,suggestion:`Run paradigm_agent_activate id="${s}" to add it, or check .paradigm/roster.yaml`,activeRoster:a},null,2);return o(f.length,"paradigm_agent_prompt"),{handled:true,text:f}}let c=o$1?.agents[s],l={name:c?.name||s,role:c?.role||At[s]||At.builder,focus:c?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:ma(s,e.rootDir,c),triggers:c?.triggers,handoff_to:c?.handoff_to,context:c?.context,protocol:c?.protocol},d=It(t),p,u;try{let{loadAgentProfile:f,buildProfileEnrichment:b}=await import('./agent-loader-MQMXCI3D.js'),{loadDecisions:h}=await import('./decision-loader-2XPZE4EZ.js'),{loadJournalEntries:w}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:_}=await import('./nomination-engine-K7MQD53E.js'),{loadNotebookEntries:k}=await import('./notebook-loader-CENTDDUJ.js'),v=f(e.rootDir,s);if(v){u=v.nickname;let S=h(e.rootDir,{status:"active",limit:5}).map(P=>({title:P.title,decision:P.decision.slice(0,150)})),x=w(s,{transferable:!0,limit:5}).map(P=>({trigger:P.trigger,insight:P.insight.slice(0,150)})),C=_(e.rootDir,{pending_only:!0,limit:10}).map(P=>({urgency:P.urgency,brief:P.brief})),T;try{let P=d.map(I=>I.replace(/^[#$^!~@&%?]/,"").toLowerCase()),D=k(s,e.rootDir,P.length>0?{concepts:P}:void 0);D.length>0&&(T=D.sort((A,N)=>N.confidence-A.confidence||new Date(N.updated).getTime()-new Date(A.updated).getTime()).slice(0,5).map(A=>({context:A.context,snippet:A.snippet,concepts:A.concepts})));}catch{}let j=b(v,d,T,{recentDecisions:S,journalInsights:x,pendingNominations:C});if(v.permissions){let P=[`
|
|
737
737
|
## Permission Constraints`];v.permissions.paths?.deny?.length&&P.push(`**Denied paths:** ${v.permissions.paths.deny.join(", ")}`),v.permissions.paths?.write?.length&&P.push(`**Writable paths:** ${v.permissions.paths.write.join(", ")}`),v.permissions.tools?.deny?.length&&P.push(`**Denied tools:** ${v.permissions.tools.deny.join(", ")}`),v.permissions.dangerous_actions?.length&&P.push(`**Requires approval for:** ${v.permissions.dangerous_actions.join(", ")}`),j+=`
|
|
738
738
|
`+P.join(`
|
|
739
739
|
`);}j.trim()&&(p=j);}}catch{}let g=ba({agent:l,task:t,symbols:d,handoffContext:i,previousAgent:r,profileEnrichment:p,nickname:u}),m={agent:s,model:g.model,prompt:g.prompt,attribution:g.attribution,taskToolParams:{description:g.taskDescription,prompt:g.prompt,subagent_type:g.subagentType,model:g.model},focusAreas:g.focusAreas,usage:"Use the Task tool with the taskToolParams to spawn this agent. Present the response with the attribution prefix."},y=JSON.stringify(m,null,2);return o(y.length,"paradigm_agent_prompt"),{handled:true,text:y}}function ha(n,e){let s=new Set(n),t=[];for(let i of n){let r=e[i];if(r?.handoff_to)for(let o of r.handoff_to)s.has(o)&&t.push({from:i,to:o});}return t}function zd(n,e){let s=ha(n,e);if(s.length===0)return null;let t=new Set,i=new Set(s.map(u=>`${u.from}->${u.to}`));for(let u of s)if(i.has(`${u.to}->${u.from}`)){let g=[u.from,u.to].sort().join(",");t.add(g);}let r=new Map;for(let u of t){let[g,m]=u.split(","),y=r.get(g)||g,f=r.get(m)||m,b=y<f?y:f;for(let[h,w]of r)(w===y||w===f)&&r.set(h,b);r.set(g,b),r.set(m,b);}for(let u of n)r.has(u)||r.set(u,u);let o=[...new Set(r.values())],a=new Map,c=new Map;for(let u of o)a.set(u,0),c.set(u,new Set);for(let u of s){let g=r.get(u.from),m=r.get(u.to);g!==m&&(c.get(g).has(m)||(c.get(g).add(m),a.set(m,(a.get(m)||0)+1)));}let l=new Map,d=[];for(let u of o)(a.get(u)||0)===0&&(d.push(u),l.set(u,0));for(;d.length>0;){let u=d.shift(),g=l.get(u)||0;for(let m of c.get(u)||[]){let y=(a.get(m)||1)-1;a.set(m,y);let f=g+1;l.set(m,Math.max(l.get(m)||0,f)),y===0&&d.push(m);}}if(l.size<o.length)return null;let p=new Map;for(let u of n){let g=r.get(u);p.set(u,l.get(g)||0);}return p}function Bd(n,e,s,t,i){let r=It(n),o=n.toLowerCase(),a=[],c=[];if(s&&s.length>0)for(let _=0;_<s.length;_++){let k=s[_];e[k]&&c.push({name:k,task:`${k==="architect"?"Design":k==="builder"?"Implement":k==="tester"?"Test":"Process"}: ${n}`,dependsOn:_>0?[s[_-1]]:[],required:true,stage:_});}else {let _=o.includes("design")||o.includes("architect")||o.includes("plan")||o.includes("spec"),k=o.includes("auth")||o.includes("security")||o.includes("gate")||r.some(j=>j.startsWith("^")),v=o.includes("build")||o.includes("implement")||o.includes("create")||o.includes("add")||o.includes("fix"),S=o.includes("review")||o.includes("check"),x=o.includes("test")||o.includes("verify")||o.includes("validate");if(_&&e.architect&&c.push({name:"architect",task:`Design and specify: ${n}`,dependsOn:[],required:true,stage:0}),k&&e.security&&c.push({name:"security",task:`Review security aspects of: ${n}`,dependsOn:[],required:false,stage:0}),v&&e.builder){let j=_&&e.architect?["architect"]:[];c.push({name:"builder",task:`Implement: ${n}`,dependsOn:j,required:true,stage:j.length>0?1:0});}let C=c.some(j=>j.name==="builder"),T=C?2:_?1:0;if(S&&e.reviewer&&c.push({name:"reviewer",task:`Review: ${n}`,dependsOn:C?["builder"]:[],required:false,stage:T}),x&&e.tester&&c.push({name:"tester",task:`Test and validate: ${n}`,dependsOn:C?["builder"]:[],required:false,stage:T}),c.length===0){let j=t?.recommendedAgents||["architect","builder","tester"],P={architect:"Design",security:"Review security of",builder:"Implement",tester:"Test",reviewer:"Review"},D=0,I=null;for(let A of j){if(!e[A])continue;let N=I?[I]:[],H=P[A]||"Process",q=A==="architect"||A==="builder";c.push({name:A,task:`${H}: ${n}`,required:q,stage:D,dependsOn:N}),I=A,D++;}}}let l=c.map(_=>_.name),d=zd(l,e);if(d)for(let _ of c){_.stage=d.get(_.name)||0;let k=[];for(let v of l){if(v===_.name)continue;e[v]?.handoff_to?.includes(_.name)&&(d.get(v)||0)<_.stage&&k.push(v);}k.length>0&&(_.dependsOn=k);}let p=new Map;for(let _ of c){let k=p.get(_.stage)||[];k.push(_),p.set(_.stage,k);}let u=Array.from(p.keys()).sort((_,k)=>_-k);for(let _ of u){let k=p.get(_)||[];a.push({stage:_,agents:k.map(v=>({name:v.name,task:v.task,dependsOn:v.dependsOn,required:v.required})),canRunParallel:k.length>1});}let g=c.some(_=>_.name==="builder"||_.name==="tester"),y=t?.type==="analysis"||!g,f=false;if(!y){let _=u.length>0?u[u.length-1]+1:0;a.push({stage:_,agents:[{name:"documentor",task:"Review all changes made by previous agents. Update .purpose files, portal.yaml, and symbol registrations using only paradigm_purpose_* and paradigm_portal_* MCP tools. Run paradigm_reindex when done. Do NOT modify source code.",dependsOn:c.map(k=>k.name),required:true}],canRunParallel:false}),f=true;}let b=0,h=0;for(let _ of c){let k=Wd[_.name]||{min:5e3,max:2e4};b+=k.min,h+=k.max;}f&&(b+=2e3,h+=8e3);let w=i?.default_mode||"faceted";return {task:n,mode:w,stages:a,symbols:r,estimatedAgents:c.length+(f?1:0),estimatedTokens:{min:b,max:h}}}function ba(n){let{agent:e,task:s,symbols:t,handoffContext:i,previousAgent:r}=n,o=[];n.profileEnrichment&&(o.push(n.profileEnrichment),o.push("---"),o.push(""));let a=At[e.name]||e.role||At.builder;if(o.push(a),o.push(""),o.push("---"),o.push(""),o.push("## Your Task"),o.push(""),o.push(s),o.push(""),t.length>0){o.push("## Symbols in Scope"),o.push("");for(let p of t){let u=Vd(p);o.push(`- \`${p}\` (${u})`);}o.push("");}i&&(o.push("## Context from Previous Agent"),r&&o.push(`*Handed off from ${r}:*`),o.push(""),o.push(i),o.push("")),(e.focus?.reads||e.focus?.writes)&&(o.push("## Focus Areas"),o.push(""),o.push(`**Read from:** ${e.focus?.reads?.join(", ")||"**/*"}`),o.push(`**Write to:** ${e.focus?.writes?.join(", ")||"**/*"}`),o.push("")),o.push(`## Output Format
|
|
@@ -765,7 +765,7 @@ This structured output helps track progress and pass context between agents.`);l
|
|
|
765
765
|
`);typeof m.lines=="number"?b=1:Array.isArray(m.lines)&&m.lines.length===2?b=m.lines[1]-m.lines[0]+1:Array.isArray(m.lines)&&(b=m.lines.length);}catch{}a.push({path:m.path,lines:m.raw.split(":")[1]||"full file",exists:f,lineCount:b});}let c=o.length>0&&a.every(m=>m.exists),l=r.appliesTo||[],d=n(s.index),p=[],u=[];for(let m of d)for(let y of l)if(new RegExp("^"+y.replace(/\*/g,".*").replace(/\?/g,".")+"$").test(m.symbol)){p.push(m.symbol),(m.data?.aspects?.includes?.(i)||m.data?.aspects?.includes?.(t))&&u.push(m.symbol);break}let g=p.filter(m=>!u.includes(m));return {handled:true,text:JSON.stringify({aspect:i,valid:c,description:r.description,enforcement:r.enforcement,anchors:a,coverage:{appliesTo:l,matchingSymbols:p.length,symbolsWithAspect:u.length,missing:g.slice(0,10),missingCount:g.length},warnings:[...o.length===0?["CRITICAL: Aspect has no anchors - aspects MUST have code anchors"]:[],...a.filter(m=>!m.exists).map(m=>`Anchor file not found: ${m.path}`),...g.length>0?[`${g.length} symbols match applies-to but don't have this aspect`]:[]],recommendation:c?g.length>0?"Aspect is valid but has coverage gaps - consider applying to matching symbols":"Aspect is valid and fully applied":"INVALID: Add code anchors to this aspect"},null,2)}}default:return {handled:false,text:""}}}var rp=["#","$","^","!","~"];function J(n){return n.length>1&&rp.includes(n[0])?n.slice(1):n}function M(n,e){let s=J(n);return `${e}${s}`}function le(n,e){let s=F.isAbsolute(n)?n:F.resolve(e,n);return s.endsWith(".purpose")?s:F.join(s,".purpose")}function de(n){if(!O.existsSync(n))return {};let e=a$8(n);if(!e.data)throw new Error(`Failed to parse ${n}: ${e.errors.join(", ")}`);return e.data}function pe(n,e){let s=F.dirname(n);O.existsSync(s)||O.mkdirSync(s,{recursive:true});let t=b$a(e);O.writeFileSync(n,t,"utf8");}function Ke(n){if(!n)return {};if(!Array.isArray(n))return n;let e={};for(let s of n){let{id:t,...i}=s;e[t]=i;}return e}function An(n){if(!n)return {};if(!Array.isArray(n))return n;let e={};for(let s of n)e[s.name]={description:s.description,steps:s.steps};return e}function at(n,e){if(!e||e.length===0)return n;if(!n||n.length===0)return e;let s=new Set(n);for(let t of e)s.add(t);return Array.from(s)}var op={"#":"#","^":"^","!":"!",$:"$","~":"~"};async function Sa(n,e,s,t){let i=op[t];if(!i)throw new Error(`Invalid symbol type: ${t}. Expected one of: # ^ ! $ ~`);let r=J(e),o=J(s),a=M(r,i),c=M(o,i),l=await c$5(n),d=[];for(let p of l){let u=de(p),g=false,y={"#":"components","^":"gates","!":"signals",$:"flows","~":"aspects"}[i];if(y&&y!=="flows"){let f=u[y];f&&!Array.isArray(f)&&r in f&&(f[o]=f[r],delete f[r],g=true);}if(i==="#")for(let f of ["features","components"]){let b=u[f];b&&!Array.isArray(b)&&r in b&&(b[o]=b[r],delete b[r],g=true);}i==="$"&&u.flows&&!Array.isArray(u.flows)&&r in u.flows&&(u.flows[o]=u.flows[r],delete u.flows[r],g=true);for(let f of ["features","components"]){let b=Ke(u[f]);for(let[h,w]of Object.entries(b))g=ap(w,a,c)||g;g&&Object.keys(b).length>0&&(u[f]=b);}if(u.flows){let f=An(u.flows);for(let[b,h]of Object.entries(f)){if(h.gates){let w=h.gates.indexOf(a);w!==-1&&(h.gates[w]=c,g=true);}if(h.signals){let w=h.signals.indexOf(a);w!==-1&&(h.signals[w]=c,g=true);}if(h.components){let w=h.components.indexOf(a);w!==-1&&(h.components[w]=c,g=true);}if(h.steps)for(let w of h.steps)typeof w=="object"&&"component"in w&&(w.component===a||w.component===r)&&(w.component=i==="#"?o:c,g=true);}g&&(u.flows=f);}if(u.gates){for(let[f,b]of Object.entries(u.gates))if(b.signals){let h=b.signals.indexOf(a);h!==-1&&(b.signals[h]=c,g=true);}}if(u.aspects){for(let[f,b]of Object.entries(u.aspects))if(b["applies-to"]){let h=b["applies-to"].indexOf(a);h!==-1&&(b["applies-to"][h]=c,g=true);}}g&&(pe(p,u),d.push(p));}return d}function ap(n,e,s){let t=false,i=["signals","gates","flows","components","states"];for(let r of i){let o=n[r];if(o){let a=o.indexOf(e);a!==-1&&(o[a]=s,t=true);}}if(n.aspects&&Array.isArray(n.aspects)){let r=n.aspects.indexOf(e);r!==-1&&(n.aspects[r]=s,t=true);}return t}function In(n){let e=F.join(n,"portal.yaml");if(!O.existsSync(e))return {data:{version:"1.0.0",gates:{}},filePath:e};let s=O.readFileSync(e,"utf8");return {data:Z.load(s)||{version:"1.0.0",gates:{}},filePath:e}}function Ca(n,e){let s=Z.dump(e,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});O.writeFileSync(n,s,"utf8");}function Pa(n,e){let{data:s,filePath:t}=In(n);s.gates||(s.gates={});let i=J(e.id),r=s.gates[i]||{};return r.description=e.description,e.type!==void 0&&(r.type=e.type),e.location!==void 0&&(r.location=e.location),e.requires!==void 0&&(r.requires=e.requires),e.check!==void 0&&(r.check=e.check),e.grants!==void 0&&(r.grants=e.grants),e.emits!==void 0&&(r.emits=e.emits),e.prizes!==void 0&&(r.prizes=e.prizes),r.prizes||(r.prizes=[]),s.gates[i]=r,Ca(t,s),t}function Ra(n,e){let{data:s,filePath:t}=In(n);s.routes||(s.routes={});let i=`${e.method} ${e.route}`,r=e.gates.map(o=>`^${J(o)}`);return s.routes[i]=r,Ca(t,s),t}var cp={name:"paradigm_purpose_init",description:"Create or update file-level metadata on a .purpose file. Does NOT overwrite existing components/signals/etc \u2014 only touches top-level metadata (name, description, context, version). ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory (relative to project root)"},name:{type:"string",description:"Name/title for this purpose file"},description:{type:"string",description:"Description of what this directory/module does"},context:{type:"array",items:{type:"string"},description:"Context notes for AI agents"},version:{type:"string",description:'Version string (default: "1.0.0")'}},required:["purposeFile","name"]},annotations:{readOnlyHint:false,destructiveHint:false}},lp={name:"paradigm_purpose_add_component",description:"Add or update a component (#) or feature in a .purpose file. Strips # prefix from id automatically. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Component ID (e.g. "payment-service" or "#payment-service")'},description:{type:"string",description:"What this component does"},section:{type:"string",enum:["components","features"],description:'Which section to add to (default: "components")'},file:{type:"string",description:"Source file path for this component"},status:{type:"string",description:'Component status (e.g. "active", "deprecated")'},endpoints:{type:"array",items:{type:"string"},description:'API endpoints (e.g. ["POST /api/payments"])'},tests:{type:"array",items:{type:"string"},description:"Test file paths"},flows:{type:"array",items:{type:"string"},description:'Flow references (e.g. ["$checkout-flow"])'},gates:{type:"array",items:{type:"string"},description:'Gate references (e.g. ["^authenticated"])'},signals:{type:"array",items:{type:"string"},description:'Signal references (e.g. ["!payment-completed"])'},aspects:{type:"array",items:{type:"string"},description:'Aspect references (e.g. ["~audit-required"])'},components:{type:"array",items:{type:"string"},description:'Component references (e.g. ["#stripe-service"])'},type:{type:"string",description:'Component type (e.g., "view", "service", "model", "tool"). Open string per project vocabulary.'},parent:{type:"string",description:'Parent component (e.g., "#payment-page"). Establishes hierarchy.'}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},dp={name:"paradigm_purpose_add_aspect",description:'Add or update an aspect (~) with ENFORCED anchors. Anchors are required and must point to code locations. Strips ~ prefix automatically. This prevents the common "~aspect:name" format error. ~100 tokens.',inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Aspect ID (e.g. "audit-required" or "~audit-required")'},description:{type:"string",description:"What this aspect enforces"},anchors:{type:"array",items:{type:"string"},description:'REQUIRED. Code anchor locations (e.g. ["src/middleware/audit.ts:15-35"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g. ["compliance", "security"])'},appliesTo:{type:"array",items:{type:"string"},description:'Glob patterns for symbols this applies to (e.g. ["#*Service"])'},enforcement:{type:"string",description:'How this aspect is enforced (e.g. "middleware", "decorator")'}},required:["purposeFile","id","description","anchors"]},annotations:{readOnlyHint:false,destructiveHint:false}},pp={name:"paradigm_purpose_add_signal",description:"Add a signal (!) definition. Handles YAML ! quoting automatically. Strips ! prefix from id. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Signal ID (e.g. "payment-completed" or "!payment-completed")'},description:{type:"string",description:"What this signal represents"},category:{type:"string",description:'Signal category (e.g. "business", "system", "security")'},severity:{type:"string",enum:["info","warn","error"],description:"Severity level"},emitters:{type:"array",items:{type:"string"},description:'Components that emit this signal (e.g. ["#payment-service"])'},related:{type:"array",items:{type:"string"},description:"Related signals or symbols"},data:{type:"object",description:"Schema/shape of data emitted with this signal"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},up={name:"paradigm_purpose_add_flow",description:"Add a flow ($) definition. Strips $ prefix from id. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Flow ID (e.g. "checkout-flow" or "$checkout-flow")'},description:{type:"string",description:"What this flow does"},gates:{type:"array",items:{type:"string"},description:"Gate references in this flow"},signals:{type:"array",items:{type:"string"},description:"Signals emitted during this flow"},components:{type:"array",items:{type:"string"},description:"Components involved in this flow"},steps:{type:"array",items:{type:"object",properties:{component:{type:"string"},action:{type:"string"},description:{type:"string"}},required:["component","action"]},description:"Ordered steps in the flow"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},gp={name:"paradigm_purpose_add_gate",description:"Add a gate (^) to a .purpose file's gates section. This is for purpose-level gates, NOT portal.yaml. Strips ^ prefix. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Gate ID (e.g. "authenticated" or "^authenticated")'},description:{type:"string",description:"What this gate checks"},requires:{type:"array",items:{type:"string"},description:"Requirements for this gate"},keys:{type:"array",items:{type:"string"},description:"Key expressions for gate evaluation"},signals:{type:"array",items:{type:"string"},description:"Signals emitted by this gate (e.g. on pass/fail)"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},mp={name:"paradigm_purpose_add_state",description:"Add a state definition to a .purpose file. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'State ID (e.g. "user-store")'},description:{type:"string",description:"What this state represents"},type:{type:"string",description:'Type of state (e.g. "object", "array", "string")'},default:{description:"Default value for the state"},properties:{type:"object",description:"State properties as {name: {type, description}}"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},fp={name:"paradigm_purpose_link",description:"Add references to an existing component without rewriting all fields. Merges into existing arrays (no clobber). Example: add ~rate-limited to #payment-service's aspects. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},componentId:{type:"string",description:"Component or feature ID to add references to"},section:{type:"string",enum:["components","features"],description:"Which section the component is in (default: auto-detect)"},signals:{type:"array",items:{type:"string"},description:"Signal references to add"},aspects:{type:"array",items:{type:"string"},description:"Aspect references to add"},gates:{type:"array",items:{type:"string"},description:"Gate references to add"},flows:{type:"array",items:{type:"string"},description:"Flow references to add"},components:{type:"array",items:{type:"string"},description:"Component references to add"}},required:["purposeFile","componentId"]},annotations:{readOnlyHint:false,destructiveHint:false}},yp={name:"paradigm_purpose_remove",description:"Remove any element by section + id from a .purpose file. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},section:{type:"string",enum:["components","features","gates","signals","aspects","flows","states"],description:"Which section to remove from"},id:{type:"string",description:"ID of the element to remove"}},required:["purposeFile","section","id"]},annotations:{readOnlyHint:false,destructiveHint:true}},hp={name:"paradigm_purpose_rename",description:"Rename a symbol across ALL .purpose files in the project. Updates both definitions and references. ~200 tokens.",inputSchema:{type:"object",properties:{oldId:{type:"string",description:'Current symbol ID (e.g. "payment-service")'},newId:{type:"string",description:'New symbol ID (e.g. "billing-service")'},symbolType:{type:"string",enum:["#","^","!","$","~"],description:"Symbol type prefix"}},required:["oldId","newId","symbolType"]},annotations:{readOnlyHint:false,destructiveHint:false}},bp={name:"paradigm_portal_add_gate",description:"Add or update a gate (^) in portal.yaml. Creates portal.yaml if it doesn't exist. Strips ^ prefix. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Gate ID (e.g. "authenticated" or "^authenticated")'},description:{type:"string",description:"What this gate checks"},type:{type:"string",description:'Gate type (e.g. "auth", "role", "ownership")'},location:{type:"string",description:'Where the gate is enforced (e.g. "middleware", "route-handler")'},requires:{type:"array",items:{type:"string"},description:"Prerequisite gates"},check:{type:"string",description:'Expression to evaluate (e.g. "req.user != null")'},grants:{type:"array",items:{type:"string"},description:"What passing this gate grants access to"},emits:{type:"array",items:{type:"string"},description:"Signals emitted when gate is checked"},prizes:{type:"array",items:{type:"object",properties:{id:{type:"string"},oneTime:{type:"boolean"}},required:["id"]},description:"Side effects triggered on pass"}},required:["id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},wp={name:"paradigm_portal_add_route",description:"Add a route with gates to portal.yaml. Creates routes section if needed. ~100 tokens.",inputSchema:{type:"object",properties:{route:{type:"string",description:'Route path (e.g. "/api/users/:id")'},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method"},gates:{type:"array",items:{type:"string"},description:'Gate IDs to apply (e.g. ["^authenticated", "^user-owner"])'}},required:["route","method","gates"]},annotations:{readOnlyHint:false,destructiveHint:false}},vp={name:"paradigm_purpose_validate",description:"Validate .purpose files and portal.yaml. Returns issues found. If no purposeFile specified, validates all files. ~200 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Specific .purpose file to validate (validates all if omitted)"},includePortal:{type:"boolean",description:"Also validate portal.yaml (default: true)"}}},annotations:{readOnlyHint:true,destructiveHint:false}};function Ta(){return [cp,lp,dp,pp,up,gp,mp,fp,yp,hp,bp,wp,vp]}async function Da(n,e,s,t){switch(n){case "paradigm_purpose_init":return _p(e,s,t);case "paradigm_purpose_add_component":return kp(e,s,t);case "paradigm_purpose_add_aspect":return Sp(e,s,t);case "paradigm_purpose_add_signal":return xp(e,s,t);case "paradigm_purpose_add_flow":return Cp(e,s,t);case "paradigm_purpose_add_gate":return Pp(e,s,t);case "paradigm_purpose_add_state":return Rp(e,s,t);case "paradigm_purpose_link":return jp(e,s,t);case "paradigm_purpose_remove":return Tp(e,s,t);case "paradigm_purpose_rename":return Dp(e,s,t);case "paradigm_portal_add_gate":return Ap(e,s,t);case "paradigm_portal_add_route":return Op(e,s,t);case "paradigm_purpose_validate":return $p(e,s);default:return {handled:false,text:""}}}function X(n){return {handled:true,text:JSON.stringify(n,null,2)}}function qe(n){return {handled:true,text:JSON.stringify({error:n},null,2)}}async function _p(n,e,s){let{purposeFile:t,name:i,description:r,context:o,version:a}=n,c=le(t,e.rootDir),l=de(c);return a!==void 0?l.version=a:l.version||(l.version="1.0.0"),r!==void 0?l.description=r:l.description||(l.description=i),o!==void 0&&(l.context=o),pe(c,l),await s(),X({action:"purpose_init",file:c,metadata:{name:i,description:l.description,version:l.version}})}async function kp(n,e,s){let{purposeFile:t,id:i,description:r,section:o="components",file:a,status:c,endpoints:l,tests:d,flows:p,gates:u,signals:g,aspects:m,components:y,type:f,parent:b}=n,h=le(t,e.rootDir),w=de(h),_=J(i),k=o,v=Ke(w[k]),S=v[_]||{description:""};return S.description=r,a!==void 0&&(S.file=a),c!==void 0&&(S.status=c),l!==void 0&&(S.endpoints=l),d!==void 0&&(S.tests=d),p!==void 0&&(S.flows=p.map(x=>M(x,"$"))),u!==void 0&&(S.gates=u.map(x=>M(x,"^"))),g!==void 0&&(S.signals=g.map(x=>M(x,"!"))),m!==void 0&&(S.aspects=m.map(x=>M(x,"~"))),y!==void 0&&(S.components=y.map(x=>M(x,"#"))),f!==void 0&&(S.type=f),b!==void 0&&(S.parent=M(b,"#")),v[_]=S,w[k]=v,pe(h,w),await s(),X({action:"add_component",file:h,section:k,id:_,symbol:`#${_}`})}async function Sp(n,e,s){let{purposeFile:t,id:i,description:r,anchors:o,tags:a,appliesTo:c,enforcement:l}=n;if(!o||o.length===0)return qe('Aspects (~) REQUIRE at least one code anchor. Provide anchors like ["src/middleware/audit.ts:15-35"].');let d=/^[^\s:]+:\d+(-\d+)?(,\d+)*$/;for(let y of o)if(!d.test(y))return qe(`Invalid anchor format: "${y}". Expected format: "file.ts:15", "file.ts:15-20", or "file.ts:15,25,30".`);let p=le(t,e.rootDir),u=F.dirname(p);for(let y of o){let f=y.replace(/:.*$/,""),b=F.resolve(u,f);if(!O.existsSync(b)){let h=F.resolve(e.rootDir,f);if(O.existsSync(h)){let w=F.relative(u,h),_=o.indexOf(y);o[_]=y.replace(f,w);}else return qe(`Anchor file not found: "${f}". Anchors must be relative to the .purpose file directory (${u}).`)}}let g=de(p);g.aspects||(g.aspects={});let m=J(i);return g.aspects[m]={description:r,anchors:o,...a&&{tags:a},...c&&{"applies-to":c},...l&&{enforcement:l}},pe(p,g),await s(),X({action:"add_aspect",file:p,id:m,symbol:`~${m}`,anchors:o})}async function xp(n,e,s){let{purposeFile:t,id:i,description:r,category:o,severity:a,emitters:c,related:l,data:d}=n,p=le(t,e.rootDir),u=de(p);u.signals||(u.signals={});let g=J(i);return u.signals[g]={description:r,...o&&{category:o},...a&&{severity:a},...c&&{emitters:c.map(m=>M(m,"#"))},...l&&{related:l},...d&&{data:d}},pe(p,u),await s(),X({action:"add_signal",file:p,id:g,symbol:`!${g}`})}async function Cp(n,e,s){let{purposeFile:t,id:i,description:r,gates:o,signals:a,components:c,steps:l}=n,d=le(t,e.rootDir),p=de(d),u=An(p.flows),g=J(i),m={description:r,...o&&{gates:o.map(y=>M(y,"^"))},...a&&{signals:a.map(y=>M(y,"!"))},...c&&{components:c.map(y=>M(y,"#"))},...l&&{steps:l}};return u[g]=m,p.flows=u,pe(d,p),await s(),X({action:"add_flow",file:d,id:g,symbol:`$${g}`})}async function Pp(n,e,s){let{purposeFile:t,id:i,description:r,requires:o,keys:a,signals:c}=n,l=le(t,e.rootDir),d=de(l);d.gates||(d.gates={});let p=J(i);return d.gates[p]={description:r,...o&&{requires:o},...a&&{keys:a},...c&&{signals:c.map(u=>M(u,"!"))}},pe(l,d),await s(),X({action:"add_gate",file:l,id:p,symbol:`^${p}`})}async function Rp(n,e,s){let{purposeFile:t,id:i,description:r,type:o,default:a,properties:c}=n,l=le(t,e.rootDir),d=de(l);d.states||(d.states={});let p=J(i),u={description:r};return o!==void 0&&(u.type=o),a!==void 0&&(u.default=a),c!==void 0&&(u.properties=c),d.states[p]=u,pe(l,d),await s(),X({action:"add_state",file:l,id:p})}async function jp(n,e,s){let{purposeFile:t,componentId:i,section:r,signals:o,aspects:a,gates:c,flows:l,components:d}=n,p=le(t,e.rootDir),u=de(p),g=J(i),m=r;if(!m){let h=Ke(u.components),w=Ke(u.features);if(g in h)m="components";else if(g in w)m="features";else return qe(`Component "${g}" not found in components or features. Specify section explicitly.`)}let y=Ke(u[m]);if(!(g in y))return qe(`Component "${g}" not found in ${m} section.`);let f=y[g];o&&(f.signals=at(f.signals,o.map(h=>M(h,"!")))),c&&(f.gates=at(f.gates,c.map(h=>M(h,"^")))),l&&(f.flows=at(f.flows,l.map(h=>M(h,"$")))),d&&(f.components=at(f.components,d.map(h=>M(h,"#")))),a&&(f.aspects=at(f.aspects,a.map(h=>M(h,"~")))),y[g]=f,u[m]=y,pe(p,u),await s();let b=[];return o&&b.push(`signals: ${o.join(", ")}`),a&&b.push(`aspects: ${a.join(", ")}`),c&&b.push(`gates: ${c.join(", ")}`),l&&b.push(`flows: ${l.join(", ")}`),d&&b.push(`components: ${d.join(", ")}`),X({action:"link",file:p,componentId:g,section:m,added:b})}async function Tp(n,e,s){let{purposeFile:t,section:i,id:r}=n,o=le(t,e.rootDir),a=de(o),c=J(r);if(i==="flows"){let l=An(a.flows);if(!(c in l))return qe(`Flow "${c}" not found in flows section.`);delete l[c],a.flows=l;}else if(i==="components"||i==="features"){let l=Ke(a[i]);if(!(c in l))return qe(`"${c}" not found in ${i} section.`);delete l[c],a[i]=l;}else {let l=a[i];if(!l||!(c in l))return qe(`"${c}" not found in ${i} section.`);delete l[c];}return pe(o,a),await s(),X({action:"remove",file:o,section:i,id:c})}async function Dp(n,e,s){let{oldId:t,newId:i,symbolType:r}=n,o=await Sa(e.rootDir,t,i,r);return await s(),X({action:"rename",oldSymbol:`${r}${J(t)}`,newSymbol:`${r}${J(i)}`,filesModified:o.length,files:o})}async function Ap(n,e,s){let{id:t,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:p}=n,u=Pa(e.rootDir,{id:t,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:p});await s();let g=J(t);return X({action:"portal_add_gate",file:u,id:g,symbol:`^${g}`})}async function Op(n,e,s){let{route:t,method:i,gates:r}=n,o=Ra(e.rootDir,{route:t,method:i,gates:r});return await s(),X({action:"portal_add_route",file:o,route:`${i} ${t}`,gates:r})}var Ip=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi;function ja(n,e){let s=[];function t(r,o){if(typeof r=="string"){let a=r.match(Ip);if(a)for(let c of a)s.push({type:"warning",message:`Clarification needed: ${c}`,path:o});}}t(n.description,"description");let i=[{key:"components",items:n.components},{key:"features",items:n.features},{key:"gates",items:n.gates},{key:"signals",items:n.signals},{key:"aspects",items:n.aspects}];for(let r of i)if(r.items&&typeof r.items=="object")for(let[o,a]of Object.entries(r.items))a&&typeof a.description=="string"&&t(a.description,`${r.key}.${o}.description`);if(n.flows&&typeof n.flows=="object"){let r=Array.isArray(n.flows)?[]:Object.entries(n.flows);for(let[o,a]of r)a&&typeof a.description=="string"&&t(a.description,`flows.${o}.description`);}return s}async function $p(n,e){let{purposeFile:s,includePortal:t=true}=n,i=[];if(s){let a=le(s,e.rootDir),c=a$8(a);if(!c.data)i.push({file:a,valid:false,issues:c.errors.map(l=>({type:"error",message:l}))});else {let l=d$9(c.data,a);if(c.data.aspects)for(let[p,u]of Object.entries(c.data.aspects))(!u.anchors||u.anchors.length===0)&&(l.issues.push({type:"error",message:`Aspect "${p}" is missing required anchors`,path:`aspects.${p}`}),l.valid=false);let d=ja(c.data);l.issues.push(...d),i.push({file:a,valid:l.valid,issues:l.issues});}}else {let a=await c$5(e.rootDir);for(let c of a){let l=a$8(c);if(!l.data){i.push({file:c,valid:false,issues:l.errors.map(u=>({type:"error",message:u}))});continue}let d=d$9(l.data,c);if(l.data.aspects)for(let[u,g]of Object.entries(l.data.aspects))(!g.anchors||g.anchors.length===0)&&(d.issues.push({type:"error",message:`Aspect "${u}" is missing required anchors`,path:`aspects.${u}`}),d.valid=false);let p=ja(l.data);d.issues.push(...p),i.push({file:c,valid:d.valid,issues:d.issues});}}if(t){let{data:a,filePath:c}=In(e.rootDir),l=[];if(a.gates)for(let[d,p]of Object.entries(a.gates))p.description||l.push({type:"warning",message:`Gate "${d}" has no description`,path:`gates.${d}`}),p.prizes||l.push({type:"warning",message:`Gate "${d}" is missing prizes array (v2 requirement)`,path:`gates.${d}`});l.length>0&&i.push({file:c,valid:l.every(d=>d.type!=="error"),issues:l});}let r=i.reduce((a,c)=>a+c.issues.length,0),o=i.every(a=>a.valid);return X({action:"validate",valid:o,totalFiles:i.length,totalIssues:r,results:i})}var Wa=[{id:"explore-before-implement",name:"Explore Before Implementing",description:"Call ripple/navigate/search before modifying existing symbols to understand impact",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple","paradigm_navigate","paradigm_search","paradigm_related"]}},enabled:true},{id:"ripple-before-modify",name:"Ripple Before Modifying",description:"Run ripple analysis before modifying symbols with dependents",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple"]}},enabled:true},{id:"check-fragility",name:"Check Fragility",description:"Check history fragility for symbols before modifying frequently-broken code",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_history_fragility"]}},enabled:true},{id:"wisdom-before-implement",name:"Check Team Wisdom",description:"Check team wisdom (preferences, antipatterns, decisions) before implementing",category:"collaboration",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_wisdom_context","paradigm_wisdom_expert"]}},enabled:true},{id:"verify-before-done",name:"Verify Before Done",description:"Run postflight compliance checks before finishing a session",category:"verification",trigger:"on-stop",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight"]}},enabled:true},{id:"postflight-compliance",name:"Postflight Compliance",description:"Ensure postflight checks pass without errors before finishing",category:"verification",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight","paradigm_reindex"]}},enabled:true},{id:"test-new-components",name:"Test New Components",description:"New components should have associated tests or test plan documented",category:"testing",trigger:"postflight",severity:"advisory",check:{type:"tests-exist",params:{patterns:["**/*.test.*","**/*.spec.*","**/tests/**"]}},enabled:true},{id:"purpose-coverage",name:"Purpose File Coverage",description:"All modified source directories should have .purpose file coverage",category:"documentation",trigger:"postflight",severity:"warn",check:{type:"file-exists",params:{patterns:["**/.purpose"]}},enabled:true},{id:"record-lore-for-significant",name:"Record Lore for Significant Changes",description:"Sessions modifying 3+ files should record a lore entry",category:"documentation",trigger:"on-stop",severity:"warn",check:{type:"lore-recorded",params:{}},enabled:true},{id:"confidence-on-decisions",name:"Confidence on Decisions",description:"When recording lore, include a confidence score (0.0-1.0) to enable calibration tracking over time",category:"documentation",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_lore_record"]}},enabled:true},{id:"gates-for-routes",name:"Gates for Routes",description:"API routes should have corresponding gate declarations in portal.yaml",category:"security",trigger:"postflight",severity:"warn",check:{type:"gates-declared",params:{requireRoutes:true}},enabled:true},{id:"university-content-valid",name:"University Content Valid",description:"Validate university content integrity when files in symbol-covered areas change",category:"quality",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_validate"]}},enabled:true},{id:"university-onboarded",name:"University Onboarding",description:"Call paradigm_university_onboard at session start for project-specific learning content",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_onboard"]}},enabled:false},{id:"orchestration-required",name:"Orchestrate Complex Tasks",description:"Tasks affecting 3+ files or touching security symbols should use paradigm_orchestrate_inline to determine which agents are needed. Ensures security review, test coverage, and documentation.",category:"collaboration",trigger:"preflight",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_orchestrate_inline"]}},enabled:true},{id:"agent-coverage-validated",name:"Validate Agent Involvement",description:"After completing work, verify that agents with relevant expertise were consulted. Check nominations that were surfaced but not acted on.",category:"collaboration",trigger:"postflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ambient_nominations","paradigm_agent_list"]}},enabled:true},{id:"hot-mode-incident",name:"Incident Response Acknowledgment",description:"During incident response, orchestration enforcement is waived. But a post-incident lore entry is required and a postflight review should be scheduled.",category:"collaboration",trigger:"on-stop",severity:"advisory",check:{type:"lore-recorded"},enabled:true}],qp=30*1e3,Ms=new Map;function ie(n){let e=F.resolve(n),s=Ms.get(e);if(s&&Date.now()-s.loadedAt<qp)return s.habits;let t=Mp(e);return Ms.set(e,{habits:t,loadedAt:Date.now()}),t}function Mp(n){let e=new Map;for(let a of Wa)e.set(a.id,{...a});let s=process.env.HOME||process.env.USERPROFILE||"~",t=Fa(F.join(s,".paradigm","habits.yaml"));t&&Na(e,t);let i=Ea(F.join(s,".paradigm","habits"));for(let a of i)e.set(a.id,a);let r=Fa(F.join(n,".paradigm","habits.yaml"));r&&Na(e,r);let o=Ea(F.join(n,".paradigm","habits"));for(let a of o)e.set(a.id,a);return Array.from(e.values())}function Fa(n){if(!O.existsSync(n))return null;try{let e=O.readFileSync(n,"utf8");return Z.load(e)}catch{return null}}function Na(n,e){if(e.habits)for(let s of e.habits)n.set(s.id,{...s});if(e.overrides)for(let[s,t]of Object.entries(e.overrides)){let i=n.get(s);i&&(t.severity!==void 0&&(i.severity=t.severity),t.enabled!==void 0&&(i.enabled=t.enabled));}}function Lp(n,e){return n.filter(s=>s.enabled&&s.trigger===e)}function Ls(n){Ms.delete(F.resolve(n));}function Ea(n){if(!O.existsSync(n))return [];try{let e=O.readdirSync(n).filter(t=>t.endsWith(".habit")).sort(),s=[];for(let t of e)try{let i=O.readFileSync(F.join(n,t),"utf8"),r=Z.load(i);r?.id&&r?.name&&s.push(r);}catch{}return s}catch{return []}}var Ha=["discovery","verification","testing","documentation","collaboration","security"],qa=["preflight","postflight","on-commit","on-stop"],Ma=["advisory","warn","block"],La=["tool-called","file-exists","file-modified","lore-recorded","symbols-registered","gates-declared","tests-exist","git-clean","commit-message-format","flow-coverage","context-checked","aspect-anchored"],Wp=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Ws(n){let e=[];if(n.id||e.push("Missing required field: id"),n.name||e.push("Missing required field: name"),n.description||e.push("Missing required field: description"),n.category||e.push("Missing required field: category"),n.trigger||e.push("Missing required field: trigger"),n.severity||e.push("Missing required field: severity"),n.check||e.push("Missing required field: check"),(n.enabled===void 0||n.enabled===null)&&e.push("Missing required field: enabled"),n.id&&!Wp.test(n.id)&&e.push(`Invalid id format: "${n.id}" \u2014 must be kebab-case (lowercase, hyphens only)`),n.category&&!Ha.includes(n.category)&&e.push(`Invalid category: "${n.category}" \u2014 must be one of: ${Ha.join(", ")}`),n.trigger&&!qa.includes(n.trigger)&&e.push(`Invalid trigger: "${n.trigger}" \u2014 must be one of: ${qa.join(", ")}`),n.severity&&!Ma.includes(n.severity)&&e.push(`Invalid severity: "${n.severity}" \u2014 must be one of: ${Ma.join(", ")}`),n.check){La.includes(n.check.type)||e.push(`Invalid check.type: "${n.check.type}" \u2014 must be one of: ${La.join(", ")}`);let s=n.check.params||{};switch(n.check.type){case "tool-called":(!s.tools||!Array.isArray(s.tools)||s.tools.length===0)&&e.push('check.type "tool-called" requires check.params.tools[] (non-empty array)');break;case "file-exists":case "file-modified":(!s.patterns||!Array.isArray(s.patterns)||s.patterns.length===0)&&e.push(`check.type "${n.check.type}" requires check.params.patterns[] (non-empty array)`);break;case "commit-message-format":(!s.messagePatterns||!Array.isArray(s.messagePatterns)||s.messagePatterns.length===0)&&e.push('check.type "commit-message-format" requires check.params.messagePatterns[] (non-empty array)');break}}return {valid:e.length===0,errors:e}}var Jp=new Set(Wa.map(n=>n.id));function Mn(n){return Jp.has(n)}function Js(n,e,s="project"){let t=s==="global"?F.join(process.env.HOME||process.env.USERPROFILE||"~",".paradigm","habits"):F.join(n,".paradigm","habits");O.existsSync(t)||O.mkdirSync(t,{recursive:true});let i=F.join(t,`${e.id}.habit`),r=Z.dump(e,{lineWidth:120,noRefs:true});return O.writeFileSync(i,r,"utf8"),Ls(n),i}function Ja(n,e){if(Mn(e))return {removed:false,reason:`"${e}" is a seed habit and cannot be removed. Use overrides in habits.yaml to disable it.`};let s=F.join(n,".paradigm","habits",`${e}.habit`);if(O.existsSync(s))return O.unlinkSync(s),Ls(n),{removed:true};let t=process.env.HOME||process.env.USERPROFILE||"~",i=F.join(t,".paradigm","habits",`${e}.habit`);return O.existsSync(i)?(O.unlinkSync(i),Ls(n),{removed:true}):{removed:false,reason:`No .habit file found for "${e}". It may be defined in habits.yaml \u2014 edit that file directly.`}}var Gs=0;function Et(n,e,s,t,i){let r=Lp(n,e);t&&(r=r.filter(u=>!u.platforms||u.platforms.includes(t)));let o=0;if(i)try{let{isGraduated:u}=(qn(),d$a($a)),g=r.length;r=r.filter(m=>!u(i,m.id)),o=g-r.length;}catch{}Gs=o;let a=r.map(u=>Gp(u,s)),c=a.filter(u=>u.result==="followed").length,l=a.filter(u=>u.result==="skipped").length,d=a.filter(u=>u.result==="partial").length,p=a.filter(u=>u.result==="skipped"&&u.habit.severity==="block").length;return {trigger:e,evaluations:a,summary:{total:a.length,followed:c,skipped:l,partial:d,blockingViolations:p},blocksCompletion:p>0}}function Ht(n){return {toolsCalled:n.toolsCalled||[],filesModified:n.filesModified||[],symbolsTouched:n.symbolsTouched||[],loreRecorded:n.loreRecorded||false,hasPortalRoutes:n.hasPortalRoutes||false,taskAddsRoutes:n.taskAddsRoutes||false,taskDescription:n.taskDescription,gitClean:n.gitClean}}function Gp(n,e){switch(n.check.type){case "tool-called":return Up(n,e);case "file-exists":return zp(n,e);case "file-modified":return Qp(n,e);case "lore-recorded":return Bp(n,e);case "symbols-registered":return Vp(n,e);case "gates-declared":return Yp(n,e);case "tests-exist":return Kp(n,e);case "git-clean":return Xp(n,e);case "commit-message-format":return Zp(n,e);case "flow-coverage":return eu(n,e);case "context-checked":return tu(n,e);case "aspect-anchored":return nu(n,e);default:return {habit:n,result:"partial",reason:`Unknown check: ${n.check.type}`}}}function Up(n,e){let s=n.check.params.tools||[];if(s.length===0)return {habit:n,result:"followed",reason:"No tools required"};let t=s.filter(i=>e.toolsCalled.includes(i));return t.length>0?{habit:n,result:"followed",reason:`Called: ${t.join(", ")}`,evidence:t}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:n,result:"followed",reason:"No modifications, habit not applicable"}:{habit:n,result:"skipped",reason:`None of [${s.join(", ")}] were called before modifying code`}}function zp(n,e){if(e.filesModified.length===0)return {habit:n,result:"followed",reason:"No files modified"};if(e.filesModified.some(i=>i.endsWith(".purpose")||i.includes(".paradigm/")))return {habit:n,result:"followed",reason:"Purpose files updated"};let t=e.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".yml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/"));return t.length===0?{habit:n,result:"followed",reason:"Only non-source files modified"}:{habit:n,result:"skipped",reason:`${t.length} source file(s) without .purpose updates`,evidence:t.slice(0,5)}}function Bp(n,e){let s=e.filesModified.filter(t=>!t.endsWith(".md")&&!t.endsWith(".json")&&!t.endsWith(".yaml")&&!t.endsWith(".yml")&&!t.endsWith(".lock")&&!t.endsWith(".purpose")&&!t.includes(".paradigm/"));return s.length<3?{habit:n,result:"followed",reason:"Session not significant (< 3 source files)"}:e.loreRecorded||e.toolsCalled.includes("paradigm_lore_record")?{habit:n,result:"followed",reason:"Lore recorded"}:{habit:n,result:"skipped",reason:`${s.length} source files modified, no lore entry`,evidence:s.slice(0,5)}}function Vp(n,e){if(e.symbolsTouched.length===0)return {habit:n,result:"followed",reason:"No symbols touched"};let t=["paradigm_purpose_add_component","paradigm_purpose_add_signal","paradigm_purpose_add_flow","paradigm_purpose_add_gate","paradigm_purpose_add_aspect","paradigm_purpose_init"].filter(i=>e.toolsCalled.includes(i));return t.length>0?{habit:n,result:"followed",reason:`Purpose tools called: ${t.join(", ")}`,evidence:t}:{habit:n,result:"partial",reason:`${e.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function Yp(n,e){if(!e.taskAddsRoutes)return {habit:n,result:"followed",reason:"No routes added"};if(e.hasPortalRoutes)return {habit:n,result:"followed",reason:"Portal.yaml has routes"};let t=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(i=>e.toolsCalled.includes(i));return t.length>0?{habit:n,result:"followed",reason:`Gate tools called: ${t.join(", ")}`,evidence:t}:{habit:n,result:"skipped",reason:"Routes added without gate declarations"}}function Kp(n,e){if(e.filesModified.length===0)return {habit:n,result:"followed",reason:"No files modified"};let s=e.filesModified.filter(i=>i.includes(".test.")||i.includes(".spec.")||i.includes("/tests/")||i.includes("/test/")||i.includes("__tests__"));if(s.length>0)return {habit:n,result:"followed",reason:`Test files: ${s.length}`,evidence:s.slice(0,5)};let t=e.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/")&&!i.includes("node_modules/"));return t.length===0?{habit:n,result:"followed",reason:"No source files to test"}:{habit:n,result:"partial",reason:`${t.length} source file(s), no test files updated`,evidence:t.slice(0,5)}}function Qp(n,e){if(e.filesModified.length===0)return {habit:n,result:"followed",reason:"No files modified"};let s=n.check.params.patterns||[];if(s.length===0)return {habit:n,result:"followed",reason:"No patterns specified"};if(n.trigger==="on-stop"&&n.severity==="block"){let i=e.filesModified.filter(r=>s.some(o=>r.includes(o)||F.basename(r)===o));return i.length>0?{habit:n,result:"followed",reason:`Matching files: ${i.join(", ")}`,evidence:i}:{habit:n,result:"partial",reason:`None of [${s.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let t=e.filesModified.filter(i=>s.some(r=>i.includes(r)||F.basename(i)===r));return t.length>0?{habit:n,result:"followed",reason:`Matching files: ${t.join(", ")}`,evidence:t}:{habit:n,result:"skipped",reason:`None of [${s.join(", ")}] found in modified files`}}function Xp(n,e){return e.filesModified.length===0?{habit:n,result:"followed",reason:"No files modified"}:n.trigger==="on-stop"?{habit:n,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:e.gitClean===void 0?{habit:n,result:"partial",reason:"Git status not available"}:e.gitClean?{habit:n,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:n,result:"skipped",reason:"Uncommitted changes in working tree"}}function Zp(n,e){if(!e.commitMessage)return {habit:n,result:"followed",reason:"No commit message to check (not a commit trigger)"};let s=n.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],t=s.filter(i=>new RegExp(i,"m").test(e.commitMessage));if(t.length===s.length)return {habit:n,result:"followed",reason:"Commit message matches all required patterns",evidence:t};if(t.length>0){let i=s.filter(r=>!new RegExp(r,"m").test(e.commitMessage));return {habit:n,result:"partial",reason:`Matches ${t.length}/${s.length} patterns. Missing: ${i.join(", ")}`}}return {habit:n,result:"skipped",reason:"Commit message does not match required format patterns"}}function eu(n,e){let s=e.symbolsTouched.filter(r=>r.startsWith("#"));if(s.length<3)return {habit:n,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(e.hasFlowCoverage)return {habit:n,result:"followed",reason:"Flow coverage exists for multi-component changes"};let i=["paradigm_flow_validate","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(r=>e.toolsCalled.includes(r));return i.length>0?{habit:n,result:"followed",reason:`Flow tools called: ${i.join(", ")}`,evidence:i}:{habit:n,result:"skipped",reason:`${s.length} components touched without flow coverage`,evidence:s.slice(0,5)}}function tu(n,e){let t=(n.check.params.contextTools||["paradigm_context_check","paradigm_session_recover","paradigm_session_checkpoint"]).filter(i=>e.toolsCalled.includes(i));return t.length>0?{habit:n,result:"followed",reason:`Context tools called: ${t.join(", ")}`,evidence:t}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:n,result:"followed",reason:"No modifications, context check not applicable"}:{habit:n,result:"skipped",reason:"No context/session tools called during session"}}function nu(n,e){let s=e.symbolsTouched.filter(t=>t.startsWith("~"));return s.length===0?{habit:n,result:"followed",reason:"No aspects touched"}:e.aspectAnchorsValid===true?{habit:n,result:"followed",reason:"Aspect anchors validated and valid"}:e.toolsCalled.includes("paradigm_aspect_check")?{habit:n,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:n,result:"skipped",reason:`${s.length} aspect(s) touched without anchor validation`,evidence:s.slice(0,5)}}var qt=null,Us=false;async function zs(n){if(qt)Us||(await qt.ensureReady(),Us=true);else {let e=F.join(n,".paradigm","sentinel","sentinel.db");qt=new f$4(e),await qt.ensureReady(),Us=true;}return qt}async function su(n,e){return (await zs(n)).recordPracticeEvent(e)}async function Ua(n,e){return (await zs(n)).getPracticeEvents(e)}async function ue(n,e){return (await zs(n)).getComplianceRate(e)}async function Mt(n,e){let s=["discovery","verification","testing","documentation","collaboration","security"],t=[];for(let i of s){let r=await ue(n,{...e,habitCategory:i});r.total>0&&t.push({category:i,...r});}return t}async function za(n,e,s){let t=[];for(let i of e){let r=await su(n,{habitId:i.habitId,habitCategory:i.habitCategory,result:i.result,engineer:s.engineer,sessionId:s.sessionId,loreEntryId:s.loreEntryId,taskDescription:s.taskDescription,symbolsTouched:s.symbolsTouched,filesModified:s.filesModified,notes:i.notes});t.push(r);}return t}var ru=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,ou=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"],au=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi];function Ba(){return [{name:"paradigm_pm_preflight",description:`REQUIRED before implementing features. Call with mode="plan" to get the right agents and cost estimate. Skipping this for complex tasks leads to missed security reviews and wasted tokens.
|
|
766
766
|
|
|
767
767
|
Runs pre-flight compliance checks: extracts affected symbols, runs ripple analysis, checks portal.yaml status, and suggests required agents. Returns affected symbols, ripple summary, gate recommendations, and suggested agents. ~300 tokens.`,inputSchema:{type:"object",properties:{task:{type:"string",description:"The task description to analyze for compliance requirements"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_pm_postflight",description:"Run after completing a task to check compliance. Verifies that new components, routes, and events are properly registered in .purpose files and portal.yaml. Flags unregistered symbols and uncaptured wisdom. Returns compliance checklist with pass/fail status for purpose files, portal.yaml, and wisdom capture. ~200 tokens.",inputSchema:{type:"object",properties:{filesModified:{type:"array",items:{type:"string"},description:"List of files modified during the task"},symbolsTouched:{type:"array",items:{type:"string"},description:'List of symbols (e.g., ["#auth-handler", "^authenticated"]) touched during the task'}},required:["filesModified","symbolsTouched"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Va(n,e,s){switch(n){case "paradigm_pm_preflight":{let{task:t}=e,i=await cu(t,s),r=JSON.stringify(i,null,2);return o(r.length,n),{text:r,handled:true}}case "paradigm_pm_postflight":{let{filesModified:t,symbolsTouched:i}=e,r=du(t,i,s),o$1=JSON.stringify(r,null,2);return o(o$1.length,n),{text:o$1,handled:true}}default:return {text:"",handled:false}}}async function cu(n,e){let s=n.toLowerCase(),t=n.match(ru)||[],i=[...new Set(t)],r=i.map(u=>{let g=j$2(e.index,u),m=g.length>0?g[0]:null;return {symbol:u,exists:!!m,type:m?.type,description:m?.description}}),o=r.filter(u=>u.exists).map(u=>{let g=k(e.index,u.symbol),m=new Set;for(let b of g){let h=k(e.index,b.symbol);for(let w of h)w.symbol!==u.symbol&&!g.find(_=>_.symbol===w.symbol)&&m.add(w.symbol);}let y=g.length+m.size,f="low";return y>10?f="high":y>3&&(f="medium"),{symbol:u.symbol,directDependents:g.length,indirectDependents:m.size,impact:f}}),a={exists:e.gateConfig!==null,gateCount:0,gates:[],routeCount:0};if(e.gateConfig){let u=Object.keys(e.gateConfig.gates||{});a.gateCount=u.length,a.gates=u.map(g=>g.startsWith("^")?g:`^${g}`),a.routeCount=Object.keys(e.gateConfig.routes||{}).length;}let c=ou.some(u=>s.includes(u)),l=[];r.some(u=>u.exists)&&l.push("ripple-analysis"),c&&l.push("portal-compliance"),i.some(u=>u.startsWith("^"))&&l.push("gate-validation"),i.some(u=>u.startsWith("!"))&&l.push("signal-registration"),l.push("purpose-coverage");let d=null,p=null;try{let u=ie(e.rootDir),m=j$1().getStats(),y=[...new Set(m.toolCalls.map(w=>w.toolName))],f=Ht({toolsCalled:y,filesModified:[],symbolsTouched:i,loreRecorded:!1,hasPortalRoutes:a.exists&&a.routeCount>0,taskAddsRoutes:c,taskDescription:n}),b=Et(u,"preflight",f,void 0,e.rootDir);d={total:b.summary.total,followed:b.summary.followed,skipped:b.summary.skipped,partial:b.summary.partial,results:b.evaluations.map(w=>({id:w.habit.id,name:w.habit.name,severity:w.habit.severity,result:w.result,reason:w.reason}))};let h=new Date(Date.now()-720*60*60*1e3).toISOString();p=await ue(e.rootDir,{dateFrom:h});}catch{}return {task:n.slice(0,100)+(n.length>100?"...":""),affectedSymbols:r,rippleAnalysis:o,portalStatus:a,taskAddsRoutes:c,requiredChecks:l,recommendations:lu(r,o,a,c),habits:{evaluation:d,recentCompliance:p?{rate:p.rate,totalEvents:p.total}:null}}}function lu(n,e,s,t){let i=[],r=n.filter(c=>!c.exists);r.length>0&&i.push(`New symbols detected: ${r.map(c=>c.symbol).join(", ")}. Register in .purpose files after implementation.`);let o=e.filter(c=>c.impact==="high");o.length>0&&i.push(`HIGH IMPACT: ${o.map(c=>c.symbol).join(", ")} \u2014 review all dependents before modifying.`),t&&!s.exists?i.push("Task adds routes but no portal.yaml exists. Create one with appropriate ^gates."):t&&i.push("Task adds routes. Update portal.yaml with gate entries after implementation.");let a=n.filter(c=>c.symbol.startsWith("^")&&!c.exists);return a.length>0&&i.push(`New gates referenced: ${a.map(c=>c.symbol).join(", ")}. Add to portal.yaml.`),i}function du(n,e,s){let t=[],i$1=s.gateConfig?.routes?Object.keys(s.gateConfig.routes):[];for(let p of n){let u=F.isAbsolute(p)?p:F.join(s.rootDir,p);if(!O.existsSync(u))continue;let g;try{g=O.readFileSync(u,"utf-8");}catch{continue}for(let m of au){m.lastIndex=0;let y;for(;(y=m.exec(g))!==null;){let f=y[2]||y[0];f&&f.startsWith("/")&&(!i$1.some(h=>h.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===f)&&s.gateConfig?t.push({type:"missing-portal-gate",severity:"warning",message:`Route "${f}" in ${F.relative(s.rootDir,u)} not in portal.yaml`,file:F.relative(s.rootDir,u),suggestion:"Add route to portal.yaml with ^gates. Use paradigm_gates_for_route for suggestions."}):!s.gateConfig&&f.startsWith("/api/")&&t.push({type:"missing-portal-gate",severity:"warning",message:`API route "${f}" found but no portal.yaml exists`,file:F.relative(s.rootDir,u),suggestion:"Create portal.yaml to declare gates for API routes."}));}}}for(let p of e)j$2(s.index,p).length===0&&t.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${p}" is not registered in any .purpose file`,suggestion:"Add to nearest .purpose file using paradigm_purpose_add_component or paradigm_purpose_add_signal."});let r=s.gateConfig?Object.keys(s.gateConfig.gates||{}).map(p=>p.startsWith("^")?p.slice(1):p):[];for(let p of e)if(p.startsWith("^")){let u=p.slice(1);r.includes(u)||t.push({type:"missing-portal-gate",severity:"error",message:`Gate "${p}" referenced but not declared in portal.yaml`,suggestion:`Add ${p} to portal.yaml with description and check expression.`});}let o=i(s.index,"aspect");for(let p of o){let u=p.appliesTo||[];if(u.length!==0){for(let g of u){let m=g.includes("*");for(let y of e){let f=false;if(m?f=new RegExp("^"+g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(y):f=y===g,f){let b=p.anchors||[];if(b.length===0)t.push({type:"stale-aspect",severity:"warning",message:`Aspect "${p.symbol}" applies to "${y}" but has no code anchors`,suggestion:`Add anchors to ${p.symbol} in .purpose file. Run paradigm_aspect_check for details.`});else for(let h of b){let w=F.isAbsolute(h.path)?h.path:F.join(s.rootDir,h.path);O.existsSync(w)||t.push({type:"stale-aspect",severity:"warning",message:`Aspect "${p.symbol}" anchor "${h.raw}" points to missing file`,suggestion:`Update anchors for ${p.symbol} in .purpose file.`});}}}}for(let g of e){if(!g.startsWith("#"))continue;(p.data||{}).aspects||[];for(let f of u){if(!f.includes("*"))continue;if(new RegExp("^"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(g))break}}}}n.length>=5&&e.length>=3&&t.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${n.length} files, ${e.length} symbols) \u2014 consider recording decisions`,suggestion:"Use paradigm_wisdom_record to capture architectural decisions or antipatterns."});for(let p of e){let u=j$2(s.index,p);if(u.length===0)continue;let g=u[0];g.parentSymbol&&j$2(s.index,g.parentSymbol).length===0&&t.push({type:"broken-reference",severity:"warning",message:`Symbol "${p}" references parent "${g.parentSymbol}" which does not exist`,suggestion:"Create the parent symbol or update the parent reference in the .purpose file."});}let a=t.filter(p=>p.severity==="error").length,c=t.filter(p=>p.severity==="warning").length,l="pass";a>0?l="violations":c>0&&(l="warnings");let d=null;try{let p=ie(s.rootDir),g=j$1().getStats(),m=[...new Set(g.toolCalls.map(_=>_.toolName))],y=m.includes("paradigm_lore_record"),f;try{f=execSync("git status --porcelain",{cwd:s.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let b=Ht({toolsCalled:m,filesModified:n,symbolsTouched:e,loreRecorded:y,hasPortalRoutes:s.gateConfig!==null&&s.gateConfig.routes!=null,taskAddsRoutes:!1,gitClean:f}),h=Et(p,"postflight",b,void 0,s.rootDir);d={trigger:"postflight",total:h.summary.total,followed:h.summary.followed,skipped:h.summary.skipped,partial:h.summary.partial,blockingViolations:h.summary.blockingViolations,results:h.evaluations.map(_=>({id:_.habit.id,name:_.habit.name,severity:_.habit.severity,result:_.result,reason:_.reason}))};let w=F.join(s.rootDir,".paradigm",".habits-blocking");if(h.blocksCompletion){let _=h.evaluations.filter(k=>k.result==="skipped"&&k.habit.severity==="block").map(k=>`${k.habit.name}: ${k.reason}`);O.writeFileSync(w,_.join(`
|
|
768
|
-
`),"utf8");}else O.existsSync(w)&&O.unlinkSync(w);}catch{}return {status:l,violations:t,summary:{totalChecks:7,passed:7-(a>0?1:0)-(c>0?1:0),warnings:c,errors:a},blocksCompletion:a>0,habitsEvaluation:d}}j();function Ya(){let n=process.env.PARADIGM_AUTHOR;if(n)return Bs(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Bs(e)}catch{}try{let e=ga.userInfo().username;if(e)return Bs(e)}catch{}return "unknown"}function Bs(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function Xa(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","decision","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, decision, milestone, etc.). Call after completing significant work. Returns the created entry ID and file path. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","decision","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","decision","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function Za(n,e,s){switch(n){case "paradigm_lore_search":{let t={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},i=await a$1(s.rootDir,t);return {handled:true,text:JSON.stringify({count:i.length,filter:Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),entries:i.map(Ka)},null,2)}}case "paradigm_lore_record":{let{type:t,title:i,summary:r,symbols_touched:o,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:u,duration_minutes:g,decisions:m,errors_encountered:y,learnings:f,verification:b,tags:h,meta:w,body:_,linked_lore:k,linked_tasks:v,linked_commits:S,confidence:x}=e,C;try{let I=new Date(Date.now()-2592e6).toISOString(),A=await ue(s.rootDir,{dateFrom:I});if(A.total>0){let H=(await Mt(s.rootDir,{dateFrom:I})).filter(q=>q.rate<60).map(q=>q.category);C={rate:A.rate,followed:A.followed,skipped:A.skipped,partial:A.partial,weakAreas:H.length>0?H:void 0};}}catch{}let T={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:g,author:Ya(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:i,summary:r,symbols_touched:o,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:u,decisions:m,errors_encountered:y,learnings:f,verification:b,tags:h,meta:w||void 0,habit_compliance:C,body:_,linked_lore:k,linked_tasks:v,linked_commits:S,confidence:x!=null&&x>=0&&x<=1?x:void 0},j=await d$1(s.rootDir,T);j$1().setLastLoreEntryId(j);try{let I=process.env.PARADIGM_AGENT_ID;if(I&&o&&o.length>0){let{updateExpertiseFromLore:A}=await import('./agent-loader-EPXURMO7.js');A(s.rootDir,I,{symbols_touched:o,confidence:x!=null&&x>=0&&x<=1?x:void 0});}}catch{}let P=null;try{c&&c.length>=2&&(P=Z$1(s.rootDir,c,l||[]));}catch{}let D;if(e.stream){let I=e.stream,A=I==="auto"?uu(e):I;try{if(A==="work-log"){let{recordWorkLog:N}=await import('./work-log-loader-DL5GZ2BQ.js');N(s.rootDir,{agent:T.agent?.model||"unknown",summary:T.summary,outcome:T.verification?.status==="pass"?"pass":T.verification?.status==="fail"?"fail":"partial",files_modified:T.files_modified,symbols_touched:T.symbols_touched,commit:T.commit,linked_lore:T.id||j}),D="work-log";}else if(A==="journal"&&T.learnings?.length){let{recordJournalEntry:N}=await import('./journal-loader-GLH7XFTK.js');for(let H of T.learnings)N(T.agent?.model||"unknown",{trigger:"self_reflection",insight:H,project:s.projectName||"unknown",transferable:!1,linked_work_log:T.id||j});D="journal";}else if(A==="decision"&&T.decisions?.length){let{recordDecision:N}=await import('./decision-loader-2XPZE4EZ.js');for(let H of T.decisions)N(s.rootDir,{title:H.decision.slice(0,100),decision:H.decision,rationale:H.rationale,participants:[{id:`agent/${T.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:T.symbols_touched,status:"active",linked_lore:T.id||j});D="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:j,type:t,title:i,message:"Lore entry recorded successfully",...D?{stream:D}:{},...P?{protocol_suggestion:P}:{}})}}case "paradigm_lore_timeline":{let t=e.limit||10,i=await c$1(s.rootDir),r=await a$1(s.rootDir,{limit:t}),o={};for(let l of r)for(let d of l.symbols_touched)o[d]=(o[d]||0)+1;let a=Object.entries(o).sort(([,l],[,d])=>d-l).slice(0,10).map(([l,d])=>({symbol:l,count:d})),c={};for(let l of r){let d=l.author;c[d]||(c[d]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c[d].count++,l.agent&&(c[d].hasAgent=true),l.timestamp>c[d].lastActive&&(c[d].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:i||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:r.map(Ka),hotSymbols:a,authors:Object.entries(c).map(([l,d])=>({id:l,hasAgent:d.hasAgent,entries:d.count,lastActive:d.lastActive}))},null,2)}}case "paradigm_lore_get":{let t=e.id,i=await b$3(s.rootDir,t);return i?{handled:true,text:JSON.stringify(i,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})}}case "paradigm_lore_update":{let t=e.id,{id:i,...r}=e,o={};for(let[c,l]of Object.entries(r))l!==void 0&&(o[c]=l);let a=await g$4(s.rootDir,t,o);return {handled:true,text:JSON.stringify({success:a,id:t,message:a?"Lore entry updated":`Lore entry not found: ${t}`})}}case "paradigm_lore_assess":{let t=e.id,i=e.verdict,r=e.notes,o=await b$3(s.rootDir,t);if(!o)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})};let a={verdict:i,assessed_by:Ya(),assessed_at:new Date().toISOString(),notes:r},c=await h$3(s.rootDir,t,a);try{let u=process.env.PARADIGM_AGENT_ID;if(u&&c&&o.symbols_touched?.length){let{updateExpertiseFromAssessment:g}=await import('./agent-loader-EPXURMO7.js');g(s.rootDir,u,{symbols_touched:o.symbols_touched,verdict:i});}}catch{}let l=i==="correct"?1:i==="partial"?.5:0,d=o.confidence!=null?l-o.confidence:null,p=d!=null?d>.1?"Under-confident (actual outcome better than predicted)":d<-0.1?"Over-confident (actual outcome worse than predicted)":"Well-calibrated":"No confidence recorded \u2014 delta not computed";return {handled:true,text:JSON.stringify({success:c,id:t,verdict:i,confidence:o.confidence??null,delta:d,deltaDescription:p,message:c?`Assessment recorded: ${i}${d!=null?` (delta: ${d>0?"+":""}${d.toFixed(2)})`:""}`:`Failed to assess: ${t}`})}}case "paradigm_lore_calibration":{let t={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},i=await a$1(s.rootDir,t),r=i.filter(_=>_.confidence!=null),o=i.length,a=r.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,p=0;for(let _ of i){let k=_.assessment.verdict;c[k]++;let v=k==="correct"?1:k==="partial"?.5:0;l+=v,_.confidence!=null&&(d+=_.confidence,p+=Math.abs(v-_.confidence));}let u=o>0?l/o:0,g=a>0?d/a:null,m=a>0?l/o-d/a:null,y=a>0?1-p/a:null,f=e.groupBy,b;if(f&&o>0){let _=new Map;for(let k of i){let v=[];f==="symbol"?v=k.symbols_touched||[]:f==="tag"?v=k.tags||[]:f==="type"&&(v=[k.type||"agent-session"]);for(let S of v)_.has(S)||_.set(S,[]),_.get(S).push(k);}b=Array.from(_.entries()).map(([k,v])=>{let S=v.filter(P=>P.confidence!=null),x={correct:0,partial:0,incorrect:0},C=0,T=0,j=0;for(let P of v){let D=P.assessment.verdict;x[D]++;let I=D==="correct"?1:D==="partial"?.5:0;C+=I,P.confidence!=null&&(T+=P.confidence,j+=Math.abs(I-P.confidence));}return {key:k,total:v.length,accuracyRate:C/v.length,avgConfidence:S.length>0?T/S.length:null,calibrationScore:S.length>0?1-j/S.length:null,verdictBreakdown:x}}).sort((k,v)=>v.total-k.total);}let h=[],w=o<5?`Low sample size (N=${o}). Stats may not be representative.`:o<15?`Moderate sample (N=${o}). Trends are directional, not conclusive.`:null;return w&&h.push(w),y!=null&&(y>=.9?h.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):y>=.7?h.push("Good calibration \u2014 some room for improvement in confidence estimates."):y>=.5?h.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):h.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),m!=null&&(m>.15?h.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):m<-0.15&&h.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>o*.3&&o>=5&&h.push(`High error rate: ${c.incorrect}/${o} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:o,totalWithConfidence:a,accuracyRate:Math.round(u*1e3)/1e3,avgConfidence:g!=null?Math.round(g*1e3)/1e3:null,avgDelta:m!=null?Math.round(m*1e3)/1e3:null,calibrationScore:y!=null?Math.round(y*1e3)/1e3:null,verdictBreakdown:c,...b?{groups:b}:{},insights:h},null,2)}}case "paradigm_lore_delete":{let t=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let r=await i$1(s.rootDir,t);return {handled:true,text:JSON.stringify({success:r,id:t,message:r?"Lore entry deleted":`Lore entry not found: ${t}`})}}default:return {handled:false,text:""}}}function uu(n){return n.task_ref||n.files_modified||n.commit?"work-log":n.learnings||n.confidence!==void 0?"journal":n.decisions?.some(s=>s.rationale)?"decision":"work-log"}function Ka(n){return {id:n.id,type:n.type,title:n.title,summary:n.summary,author:n.author,agent:n.agent,timestamp:n.timestamp,duration_minutes:n.duration_minutes,symbols_touched:n.symbols_touched,verification:n.verification?.status,review:n.review?{completeness:n.review.completeness,quality:n.review.quality}:null,confidence:n.confidence??null,assessment:n.assessment?n.assessment.verdict:null,assessment_delta:n.assessment_delta??null,tags:n.tags}}function tc(){return [{name:"paradigm_habits_list",description:"List all habit definitions: seed (built-in), global (~/.paradigm/habits.yaml), and project (.paradigm/habits.yaml). Shows what habits exist, their triggers, severity, and enabled state. Use to discover available habits before evaluating them. Returns habit definitions with id, check type, trigger, severity, category, and enabled state. ~300 tokens.",inputSchema:{type:"object",properties:{trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"],description:"Filter by trigger point"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"],description:"Filter by category"},enabled:{type:"boolean",description:"Filter by enabled state (default: show all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_habits_check",description:"Evaluate habit compliance for the current session and record practice events. Call at preflight (before implementing), postflight (after implementing), or on-stop (session end). Returns which habits were followed, skipped, or partially met. Returns per-habit follow/skip/partial results and blocking status. ~200 tokens.",inputSchema:{type:"object",properties:{trigger:{type:"string",enum:["preflight","postflight","on-stop","on-commit"],description:"When to evaluate: preflight (before task), postflight (after task), on-stop (session end)"},filesModified:{type:"array",items:{type:"string"},description:"Files modified during the session/task"},symbolsTouched:{type:"array",items:{type:"string"},description:"Symbols touched during the session/task"},taskDescription:{type:"string",description:"Description of the task being performed"},record:{type:"boolean",description:"Whether to record practice events (default: true)"}},required:["trigger"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_status",description:"View practice profile: compliance rates by category, trends, and incident correlations. Shows how well habits are being followed over time. Returns overall rate, per-category rates, trend direction, and incident correlations. ~200 tokens.",inputSchema:{type:"object",properties:{engineer:{type:"string",description:"Filter by engineer name (default: all)"},period:{type:"string",enum:["7d","30d","90d","all"],description:"Time period for analysis (default: 30d)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_practice_context",description:"Get proactive practice warnings before modifying symbols. Shows recent compliance gaps and team-aware suggestions. Call this alongside paradigm_wisdom_context for full context. Returns relevant habits, compliance gaps, and behavioral suggestions. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:"Symbols about to be modified"},task:{type:"string",description:"Description of the upcoming task"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_habits_add",description:'Create a new custom habit as an individual .habit file. Validates all fields and checks for ID collisions with seed habits. Use scope "global" for ~/.paradigm/habits/ or "project" (default) for .paradigm/habits/. ~150 tokens.',inputSchema:{type:"object",properties:{id:{type:"string",description:'Unique habit ID in kebab-case (e.g. "check-changelog")'},name:{type:"string",description:"Human-readable habit name"},description:{type:"string",description:"What this habit checks and why"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"],description:"Habit category"},trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"],description:"When the habit is evaluated"},severity:{type:"string",enum:["advisory","warn","block"],description:"How strictly to enforce (block prevents session completion)"},check:{type:"object",description:"Check definition with type and params",properties:{type:{type:"string",enum:["tool-called","file-exists","file-modified","lore-recorded","symbols-registered","gates-declared","tests-exist","git-clean","commit-message-format","flow-coverage","context-checked","aspect-anchored"]},params:{type:"object",description:"Check-specific parameters (tools[], patterns[], etc.)"}},required:["type","params"]},enabled:{type:"boolean",description:"Whether the habit is active (default: true)"},platforms:{type:"array",items:{type:"string"},description:'Platforms this habit applies to (e.g. ["claude", "cursor"]). Omit for all.'},scope:{type:"string",enum:["project","global"],description:'Where to save: "project" (default) or "global" (~/.paradigm/habits/)'}},required:["id","name","description","category","trigger","severity","check"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_edit",description:"Update fields on an existing custom .habit file. Cannot edit seed habits \u2014 use overrides in habits.yaml instead. Merges provided fields with existing definition and re-validates. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"ID of the habit to edit"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"]},trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"]},severity:{type:"string",enum:["advisory","warn","block"]},check:{type:"object",properties:{type:{type:"string"},params:{type:"object"}},required:["type","params"]},enabled:{type:"boolean"},platforms:{type:"array",items:{type:"string"}}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_remove",description:"Delete a custom .habit file. Cannot remove seed habits \u2014 use overrides to disable them instead. Searches both project and global habit directories. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"ID of the habit to remove"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function nc(n,e,s){switch(n){case "paradigm_habits_list":{let t=mu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_check":{let t=await fu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_status":{let t=await vu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_practice_context":{let t=await _u(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_add":{let t=hu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_edit":{let t=bu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_remove":{let t=wu(e,s);return o(t.length,n),{text:t,handled:true}}default:return {text:"",handled:false}}}function mu(n,e){let s=n.trigger,t=n.category,i=n.enabled,r=ie(e.rootDir);s&&(r=r.filter(a=>a.trigger===s)),t&&(r=r.filter(a=>a.category===t)),i!==void 0&&(r=r.filter(a=>a.enabled===i));let o={};for(let a of r)o[a.trigger]||(o[a.trigger]=[]),o[a.trigger].push(a);return JSON.stringify({total:r.length,filters:Object.fromEntries(Object.entries({trigger:s,category:t,enabled:i}).filter(([,a])=>a!==void 0)),byTrigger:Object.fromEntries(Object.entries(o).map(([a,c])=>[a,c.map(l=>({id:l.id,name:l.name,description:l.description,category:l.category,severity:l.severity,enabled:l.enabled,check:{type:l.check.type,params:l.check.params},platforms:l.platforms||null}))]))},null,2)}async function fu(n,e){let s=n.trigger,t=n.filesModified||[],i=n.symbolsTouched||[],r=n.taskDescription,o=n.record!==false,a=ie(e.rootDir),c=j$1(),l=c.getStats(),d=[...new Set(l.toolCalls.map(k=>k.toolName))],p=d.includes("paradigm_lore_record"),u=(r||"").toLowerCase(),g=["endpoint","route","api","handler","get","post","put","patch","delete"].some(k=>u.includes(k)),m;try{m=execSync("git status --porcelain",{cwd:e.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let y=Ht({toolsCalled:d,filesModified:t,symbolsTouched:i,loreRecorded:p,hasPortalRoutes:e.gateConfig!==null&&e.gateConfig.routes!=null,taskAddsRoutes:g,taskDescription:r,gitClean:m}),b=Et(a,s,y,"claude",e.rootDir),h=[];if(o&&b.evaluations.length>0)try{let k=c.getLastLoreEntryId()??void 0;h=await za(e.rootDir,b.evaluations.map(v=>({habitId:v.habit.id,habitCategory:v.habit.category,result:v.result,notes:v.reason})),{engineer:"agent",sessionId:l.sessionId,loreEntryId:k,taskDescription:r,symbolsTouched:i,filesModified:t});}catch{}let w=F.join(e.rootDir,".paradigm",".habits-blocking");try{if(s==="on-stop"&&b.blocksCompletion){let k=b.evaluations.filter(v=>v.result==="skipped"&&v.habit.severity==="block").map(v=>`${v.habit.name}: ${v.reason}`);O.writeFileSync(w,k.join(`
|
|
768
|
+
`),"utf8");}else O.existsSync(w)&&O.unlinkSync(w);}catch{}return {status:l,violations:t,summary:{totalChecks:7,passed:7-(a>0?1:0)-(c>0?1:0),warnings:c,errors:a},blocksCompletion:a>0,habitsEvaluation:d}}j();function Ya(){let n=process.env.PARADIGM_AUTHOR;if(n)return Bs(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Bs(e)}catch{}try{let e=ga.userInfo().username;if(e)return Bs(e)}catch{}return "unknown"}function Bs(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function Xa(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","decision","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, decision, milestone, etc.). Call after completing significant work. Returns the created entry ID and file path. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","decision","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","decision","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function Za(n,e,s){switch(n){case "paradigm_lore_search":{let t={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},i=await a$1(s.rootDir,t);return {handled:true,text:JSON.stringify({count:i.length,filter:Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),entries:i.map(Ka)},null,2)}}case "paradigm_lore_record":{let{type:t,title:i,summary:r,symbols_touched:o,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:u,duration_minutes:g,decisions:m,errors_encountered:y,learnings:f,verification:b,tags:h,meta:w,body:_,linked_lore:k,linked_tasks:v,linked_commits:S,confidence:x}=e,C;try{let I=new Date(Date.now()-2592e6).toISOString(),A=await ue(s.rootDir,{dateFrom:I});if(A.total>0){let H=(await Mt(s.rootDir,{dateFrom:I})).filter(q=>q.rate<60).map(q=>q.category);C={rate:A.rate,followed:A.followed,skipped:A.skipped,partial:A.partial,weakAreas:H.length>0?H:void 0};}}catch{}let T={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:g,author:Ya(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:i,summary:r,symbols_touched:o,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:u,decisions:m,errors_encountered:y,learnings:f,verification:b,tags:h,meta:w||void 0,habit_compliance:C,body:_,linked_lore:k,linked_tasks:v,linked_commits:S,confidence:x!=null&&x>=0&&x<=1?x:void 0},j=await d$1(s.rootDir,T);j$1().setLastLoreEntryId(j);try{let I=process.env.PARADIGM_AGENT_ID;if(I&&o&&o.length>0){let{updateExpertiseFromLore:A}=await import('./agent-loader-MQMXCI3D.js');A(s.rootDir,I,{symbols_touched:o,confidence:x!=null&&x>=0&&x<=1?x:void 0});}}catch{}let P=null;try{c&&c.length>=2&&(P=Z$1(s.rootDir,c,l||[]));}catch{}let D;if(e.stream){let I=e.stream,A=I==="auto"?uu(e):I;try{if(A==="work-log"){let{recordWorkLog:N}=await import('./work-log-loader-DL5GZ2BQ.js');N(s.rootDir,{agent:T.agent?.model||"unknown",summary:T.summary,outcome:T.verification?.status==="pass"?"pass":T.verification?.status==="fail"?"fail":"partial",files_modified:T.files_modified,symbols_touched:T.symbols_touched,commit:T.commit,linked_lore:T.id||j}),D="work-log";}else if(A==="journal"&&T.learnings?.length){let{recordJournalEntry:N}=await import('./journal-loader-GLH7XFTK.js');for(let H of T.learnings)N(T.agent?.model||"unknown",{trigger:"self_reflection",insight:H,project:s.projectName||"unknown",transferable:!1,linked_work_log:T.id||j});D="journal";}else if(A==="decision"&&T.decisions?.length){let{recordDecision:N}=await import('./decision-loader-2XPZE4EZ.js');for(let H of T.decisions)N(s.rootDir,{title:H.decision.slice(0,100),decision:H.decision,rationale:H.rationale,participants:[{id:`agent/${T.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:T.symbols_touched,status:"active",linked_lore:T.id||j});D="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:j,type:t,title:i,message:"Lore entry recorded successfully",...D?{stream:D}:{},...P?{protocol_suggestion:P}:{}})}}case "paradigm_lore_timeline":{let t=e.limit||10,i=await c$1(s.rootDir),r=await a$1(s.rootDir,{limit:t}),o={};for(let l of r)for(let d of l.symbols_touched)o[d]=(o[d]||0)+1;let a=Object.entries(o).sort(([,l],[,d])=>d-l).slice(0,10).map(([l,d])=>({symbol:l,count:d})),c={};for(let l of r){let d=l.author;c[d]||(c[d]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c[d].count++,l.agent&&(c[d].hasAgent=true),l.timestamp>c[d].lastActive&&(c[d].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:i||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:r.map(Ka),hotSymbols:a,authors:Object.entries(c).map(([l,d])=>({id:l,hasAgent:d.hasAgent,entries:d.count,lastActive:d.lastActive}))},null,2)}}case "paradigm_lore_get":{let t=e.id,i=await b$3(s.rootDir,t);return i?{handled:true,text:JSON.stringify(i,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})}}case "paradigm_lore_update":{let t=e.id,{id:i,...r}=e,o={};for(let[c,l]of Object.entries(r))l!==void 0&&(o[c]=l);let a=await g$4(s.rootDir,t,o);return {handled:true,text:JSON.stringify({success:a,id:t,message:a?"Lore entry updated":`Lore entry not found: ${t}`})}}case "paradigm_lore_assess":{let t=e.id,i=e.verdict,r=e.notes,o=await b$3(s.rootDir,t);if(!o)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})};let a={verdict:i,assessed_by:Ya(),assessed_at:new Date().toISOString(),notes:r},c=await h$3(s.rootDir,t,a);try{let u=process.env.PARADIGM_AGENT_ID;if(u&&c&&o.symbols_touched?.length){let{updateExpertiseFromAssessment:g}=await import('./agent-loader-MQMXCI3D.js');g(s.rootDir,u,{symbols_touched:o.symbols_touched,verdict:i});}}catch{}let l=i==="correct"?1:i==="partial"?.5:0,d=o.confidence!=null?l-o.confidence:null,p=d!=null?d>.1?"Under-confident (actual outcome better than predicted)":d<-0.1?"Over-confident (actual outcome worse than predicted)":"Well-calibrated":"No confidence recorded \u2014 delta not computed";return {handled:true,text:JSON.stringify({success:c,id:t,verdict:i,confidence:o.confidence??null,delta:d,deltaDescription:p,message:c?`Assessment recorded: ${i}${d!=null?` (delta: ${d>0?"+":""}${d.toFixed(2)})`:""}`:`Failed to assess: ${t}`})}}case "paradigm_lore_calibration":{let t={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},i=await a$1(s.rootDir,t),r=i.filter(_=>_.confidence!=null),o=i.length,a=r.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,p=0;for(let _ of i){let k=_.assessment.verdict;c[k]++;let v=k==="correct"?1:k==="partial"?.5:0;l+=v,_.confidence!=null&&(d+=_.confidence,p+=Math.abs(v-_.confidence));}let u=o>0?l/o:0,g=a>0?d/a:null,m=a>0?l/o-d/a:null,y=a>0?1-p/a:null,f=e.groupBy,b;if(f&&o>0){let _=new Map;for(let k of i){let v=[];f==="symbol"?v=k.symbols_touched||[]:f==="tag"?v=k.tags||[]:f==="type"&&(v=[k.type||"agent-session"]);for(let S of v)_.has(S)||_.set(S,[]),_.get(S).push(k);}b=Array.from(_.entries()).map(([k,v])=>{let S=v.filter(P=>P.confidence!=null),x={correct:0,partial:0,incorrect:0},C=0,T=0,j=0;for(let P of v){let D=P.assessment.verdict;x[D]++;let I=D==="correct"?1:D==="partial"?.5:0;C+=I,P.confidence!=null&&(T+=P.confidence,j+=Math.abs(I-P.confidence));}return {key:k,total:v.length,accuracyRate:C/v.length,avgConfidence:S.length>0?T/S.length:null,calibrationScore:S.length>0?1-j/S.length:null,verdictBreakdown:x}}).sort((k,v)=>v.total-k.total);}let h=[],w=o<5?`Low sample size (N=${o}). Stats may not be representative.`:o<15?`Moderate sample (N=${o}). Trends are directional, not conclusive.`:null;return w&&h.push(w),y!=null&&(y>=.9?h.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):y>=.7?h.push("Good calibration \u2014 some room for improvement in confidence estimates."):y>=.5?h.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):h.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),m!=null&&(m>.15?h.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):m<-0.15&&h.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>o*.3&&o>=5&&h.push(`High error rate: ${c.incorrect}/${o} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:o,totalWithConfidence:a,accuracyRate:Math.round(u*1e3)/1e3,avgConfidence:g!=null?Math.round(g*1e3)/1e3:null,avgDelta:m!=null?Math.round(m*1e3)/1e3:null,calibrationScore:y!=null?Math.round(y*1e3)/1e3:null,verdictBreakdown:c,...b?{groups:b}:{},insights:h},null,2)}}case "paradigm_lore_delete":{let t=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let r=await i$1(s.rootDir,t);return {handled:true,text:JSON.stringify({success:r,id:t,message:r?"Lore entry deleted":`Lore entry not found: ${t}`})}}default:return {handled:false,text:""}}}function uu(n){return n.task_ref||n.files_modified||n.commit?"work-log":n.learnings||n.confidence!==void 0?"journal":n.decisions?.some(s=>s.rationale)?"decision":"work-log"}function Ka(n){return {id:n.id,type:n.type,title:n.title,summary:n.summary,author:n.author,agent:n.agent,timestamp:n.timestamp,duration_minutes:n.duration_minutes,symbols_touched:n.symbols_touched,verification:n.verification?.status,review:n.review?{completeness:n.review.completeness,quality:n.review.quality}:null,confidence:n.confidence??null,assessment:n.assessment?n.assessment.verdict:null,assessment_delta:n.assessment_delta??null,tags:n.tags}}function tc(){return [{name:"paradigm_habits_list",description:"List all habit definitions: seed (built-in), global (~/.paradigm/habits.yaml), and project (.paradigm/habits.yaml). Shows what habits exist, their triggers, severity, and enabled state. Use to discover available habits before evaluating them. Returns habit definitions with id, check type, trigger, severity, category, and enabled state. ~300 tokens.",inputSchema:{type:"object",properties:{trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"],description:"Filter by trigger point"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"],description:"Filter by category"},enabled:{type:"boolean",description:"Filter by enabled state (default: show all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_habits_check",description:"Evaluate habit compliance for the current session and record practice events. Call at preflight (before implementing), postflight (after implementing), or on-stop (session end). Returns which habits were followed, skipped, or partially met. Returns per-habit follow/skip/partial results and blocking status. ~200 tokens.",inputSchema:{type:"object",properties:{trigger:{type:"string",enum:["preflight","postflight","on-stop","on-commit"],description:"When to evaluate: preflight (before task), postflight (after task), on-stop (session end)"},filesModified:{type:"array",items:{type:"string"},description:"Files modified during the session/task"},symbolsTouched:{type:"array",items:{type:"string"},description:"Symbols touched during the session/task"},taskDescription:{type:"string",description:"Description of the task being performed"},record:{type:"boolean",description:"Whether to record practice events (default: true)"}},required:["trigger"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_status",description:"View practice profile: compliance rates by category, trends, and incident correlations. Shows how well habits are being followed over time. Returns overall rate, per-category rates, trend direction, and incident correlations. ~200 tokens.",inputSchema:{type:"object",properties:{engineer:{type:"string",description:"Filter by engineer name (default: all)"},period:{type:"string",enum:["7d","30d","90d","all"],description:"Time period for analysis (default: 30d)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_practice_context",description:"Get proactive practice warnings before modifying symbols. Shows recent compliance gaps and team-aware suggestions. Call this alongside paradigm_wisdom_context for full context. Returns relevant habits, compliance gaps, and behavioral suggestions. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:"Symbols about to be modified"},task:{type:"string",description:"Description of the upcoming task"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_habits_add",description:'Create a new custom habit as an individual .habit file. Validates all fields and checks for ID collisions with seed habits. Use scope "global" for ~/.paradigm/habits/ or "project" (default) for .paradigm/habits/. ~150 tokens.',inputSchema:{type:"object",properties:{id:{type:"string",description:'Unique habit ID in kebab-case (e.g. "check-changelog")'},name:{type:"string",description:"Human-readable habit name"},description:{type:"string",description:"What this habit checks and why"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"],description:"Habit category"},trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"],description:"When the habit is evaluated"},severity:{type:"string",enum:["advisory","warn","block"],description:"How strictly to enforce (block prevents session completion)"},check:{type:"object",description:"Check definition with type and params",properties:{type:{type:"string",enum:["tool-called","file-exists","file-modified","lore-recorded","symbols-registered","gates-declared","tests-exist","git-clean","commit-message-format","flow-coverage","context-checked","aspect-anchored"]},params:{type:"object",description:"Check-specific parameters (tools[], patterns[], etc.)"}},required:["type","params"]},enabled:{type:"boolean",description:"Whether the habit is active (default: true)"},platforms:{type:"array",items:{type:"string"},description:'Platforms this habit applies to (e.g. ["claude", "cursor"]). Omit for all.'},scope:{type:"string",enum:["project","global"],description:'Where to save: "project" (default) or "global" (~/.paradigm/habits/)'}},required:["id","name","description","category","trigger","severity","check"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_edit",description:"Update fields on an existing custom .habit file. Cannot edit seed habits \u2014 use overrides in habits.yaml instead. Merges provided fields with existing definition and re-validates. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"ID of the habit to edit"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"]},trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"]},severity:{type:"string",enum:["advisory","warn","block"]},check:{type:"object",properties:{type:{type:"string"},params:{type:"object"}},required:["type","params"]},enabled:{type:"boolean"},platforms:{type:"array",items:{type:"string"}}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_remove",description:"Delete a custom .habit file. Cannot remove seed habits \u2014 use overrides to disable them instead. Searches both project and global habit directories. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"ID of the habit to remove"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function nc(n,e,s){switch(n){case "paradigm_habits_list":{let t=mu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_check":{let t=await fu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_status":{let t=await vu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_practice_context":{let t=await _u(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_add":{let t=hu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_edit":{let t=bu(e,s);return o(t.length,n),{text:t,handled:true}}case "paradigm_habits_remove":{let t=wu(e,s);return o(t.length,n),{text:t,handled:true}}default:return {text:"",handled:false}}}function mu(n,e){let s=n.trigger,t=n.category,i=n.enabled,r=ie(e.rootDir);s&&(r=r.filter(a=>a.trigger===s)),t&&(r=r.filter(a=>a.category===t)),i!==void 0&&(r=r.filter(a=>a.enabled===i));let o={};for(let a of r)o[a.trigger]||(o[a.trigger]=[]),o[a.trigger].push(a);return JSON.stringify({total:r.length,filters:Object.fromEntries(Object.entries({trigger:s,category:t,enabled:i}).filter(([,a])=>a!==void 0)),byTrigger:Object.fromEntries(Object.entries(o).map(([a,c])=>[a,c.map(l=>({id:l.id,name:l.name,description:l.description,category:l.category,severity:l.severity,enabled:l.enabled,check:{type:l.check.type,params:l.check.params},platforms:l.platforms||null}))]))},null,2)}async function fu(n,e){let s=n.trigger,t=n.filesModified||[],i=n.symbolsTouched||[],r=n.taskDescription,o=n.record!==false,a=ie(e.rootDir),c=j$1(),l=c.getStats(),d=[...new Set(l.toolCalls.map(k=>k.toolName))],p=d.includes("paradigm_lore_record"),u=(r||"").toLowerCase(),g=["endpoint","route","api","handler","get","post","put","patch","delete"].some(k=>u.includes(k)),m;try{m=execSync("git status --porcelain",{cwd:e.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let y=Ht({toolsCalled:d,filesModified:t,symbolsTouched:i,loreRecorded:p,hasPortalRoutes:e.gateConfig!==null&&e.gateConfig.routes!=null,taskAddsRoutes:g,taskDescription:r,gitClean:m}),b=Et(a,s,y,"claude",e.rootDir),h=[];if(o&&b.evaluations.length>0)try{let k=c.getLastLoreEntryId()??void 0;h=await za(e.rootDir,b.evaluations.map(v=>({habitId:v.habit.id,habitCategory:v.habit.category,result:v.result,notes:v.reason})),{engineer:"agent",sessionId:l.sessionId,loreEntryId:k,taskDescription:r,symbolsTouched:i,filesModified:t});}catch{}let w=F.join(e.rootDir,".paradigm",".habits-blocking");try{if(s==="on-stop"&&b.blocksCompletion){let k=b.evaluations.filter(v=>v.result==="skipped"&&v.habit.severity==="block").map(v=>`${v.habit.name}: ${v.reason}`);O.writeFileSync(w,k.join(`
|
|
769
769
|
`),"utf8");}else s==="on-stop"&&O.existsSync(w)&&O.unlinkSync(w);}catch{}let _=Gs;return JSON.stringify({trigger:s,evaluation:{total:b.summary.total,followed:b.summary.followed,skipped:b.summary.skipped,partial:b.summary.partial,blockingViolations:b.summary.blockingViolations,blocksCompletion:b.blocksCompletion},..._>0?{graduatedToHooks:_,graduatedNote:`${_} habit(s) enforced by hooks (zero context cost). Not re-evaluated here.`}:{},habits:b.evaluations.map(k=>({id:k.habit.id,name:k.habit.name,category:k.habit.category,severity:k.habit.severity,result:k.result,reason:k.reason,evidence:k.evidence})),recorded:o?h.length:0,recommendations:yu(b)},null,2)}function yu(n){let e=[];for(let s of n.evaluations)if(s.result==="skipped")switch(s.habit.id){case "explore-before-implement":case "ripple-before-modify":e.push("Call paradigm_ripple or paradigm_navigate before modifying symbols.");break;case "check-fragility":e.push("Call paradigm_history_fragility to check for fragile symbols.");break;case "wisdom-before-implement":e.push("Call paradigm_wisdom_context to check team preferences and antipatterns.");break;case "verify-before-done":e.push("Call paradigm_pm_postflight to verify compliance before finishing.");break;case "record-lore-for-significant":e.push("Call paradigm_lore_record to document this session.");break;case "gates-for-routes":e.push("Call paradigm_gates_for_route and update portal.yaml for new routes.");break;case "purpose-coverage":e.push("Update .purpose files using paradigm_purpose_add_component.");break;case "changelog-updated":e.push("Update CHANGELOG.md with the changes made in this phase.");break;case "changes-committed":e.push("Commit all changes to git before finishing this phase.");break;default:e.push(`${s.habit.name}: ${s.reason}`);}return [...new Set(e)]}function hu(n,e){let s=n.id,t=n.scope||"project";if(Mn(s))return JSON.stringify({error:true,message:`Cannot create habit "${s}" \u2014 it collides with a seed habit. Choose a different ID or use overrides in habits.yaml to customize the seed habit.`},null,2);if(ie(e.rootDir).find(l=>l.id===s))return JSON.stringify({error:true,message:`Habit "${s}" already exists. Use paradigm_habits_edit to update it, or choose a different ID.`},null,2);let o={id:s,name:n.name,description:n.description,category:n.category,trigger:n.trigger,severity:n.severity,check:n.check,enabled:n.enabled!==void 0?n.enabled:true};n.platforms&&(o.platforms=n.platforms);let a=Ws(o);if(!a.valid)return JSON.stringify({error:true,message:"Validation failed",errors:a.errors},null,2);let c=Js(e.rootDir,o,t);return JSON.stringify({created:true,id:o.id,filePath:c,scope:t,message:`Habit "${o.name}" created at ${c}`},null,2)}function bu(n,e){let s=n.id;if(Mn(s))return JSON.stringify({error:true,message:`Cannot edit "${s}" \u2014 it is a seed habit. To customize it, add an override in .paradigm/habits.yaml under the "overrides:" key.`},null,2);let t=F.join(e.rootDir,".paradigm","habits",`${s}.habit`),i=process.env.HOME||process.env.USERPROFILE||"~",r=F.join(i,".paradigm","habits",`${s}.habit`),o=null,a="project";if(O.existsSync(t)?(o=t,a="project"):O.existsSync(r)&&(o=r,a="global"),!o)return JSON.stringify({error:true,message:`No .habit file found for "${s}". It may be defined in habits.yaml \u2014 edit that file directly.`},null,2);let c;try{let p=O.readFileSync(o,"utf8");c=Z.load(p);}catch{return JSON.stringify({error:true,message:`Failed to read ${o}`},null,2)}let l={...c};n.name!==void 0&&(l.name=n.name),n.description!==void 0&&(l.description=n.description),n.category!==void 0&&(l.category=n.category),n.trigger!==void 0&&(l.trigger=n.trigger),n.severity!==void 0&&(l.severity=n.severity),n.check!==void 0&&(l.check=n.check),n.enabled!==void 0&&(l.enabled=n.enabled),n.platforms!==void 0&&(l.platforms=n.platforms);let d=Ws(l);return d.valid?(Js(e.rootDir,l,a),JSON.stringify({updated:true,id:l.id,filePath:o,message:`Habit "${l.name}" updated`},null,2)):JSON.stringify({error:true,message:"Validation failed after merge",errors:d.errors},null,2)}function wu(n,e){let s=n.id,t=Ja(e.rootDir,s);return t.removed?JSON.stringify({removed:true,id:s,message:`Habit "${s}" removed`},null,2):JSON.stringify({error:true,message:t.reason},null,2)}async function vu(n,e){let s=n.engineer,t=n.period||"30d",i=new Date,r;if(t!=="all"){let h=parseInt(t.replace("d",""),10)||30;r=new Date(i.getTime()-h*24*60*60*1e3).toISOString();}let o={engineer:s,dateFrom:r},a=await ue(e.rootDir,o),c=await Mt(e.rootDir,o),l=await Ua(e.rootDir,{...o,limit:200}),d=new Map;for(let h of l){let w=d.get(h.habitId)||{followed:0,skipped:0,partial:0},_=h.result;w[_]++,d.set(h.habitId,w);}let p=null,u=null,g=-1,m=101;for(let h of c)h.rate>g&&(g=h.rate,p=h.category),h.rate<m&&(m=h.rate,u=h.category);let y=ie(e.rootDir),f=new Map(y.map(h=>[h.id,h.name])),b=Array.from(d.entries()).map(([h,w])=>{let _=w.followed+w.skipped+w.partial,k=_>0?Math.round((w.followed+w.partial*.5)/_*100):100;return {habitId:h,habitName:f.get(h)||h,...w,total:_,rate:k}}).sort((h,w)=>h.rate-w.rate);return JSON.stringify({period:t,engineer:s||"all",overall:{totalEvents:a.total,complianceRate:a.rate,followed:a.followed,skipped:a.skipped,partial:a.partial,strongestCategory:p,weakestCategory:u},byCategory:c.map(h=>({category:h.category,rate:h.rate,total:h.total,followed:h.followed,skipped:h.skipped,partial:h.partial})),byHabit:b,activeHabits:y.filter(h=>h.enabled).length,totalHabits:y.length},null,2)}async function _u(n,e){let s=n.symbols||[],t=n.task,r=ie(e.rootDir).filter(m=>m.enabled&&m.trigger==="preflight"),a=j$1().getStats(),c=[...new Set(a.toolCalls.map(m=>m.toolName))],l=[];for(let m of r)if(m.check.type==="tool-called"){let y=m.check.params.tools||[];!y.some(b=>c.includes(b))&&s.length>0&&l.push({habitId:m.id,habitName:m.name,category:m.category,severity:m.severity,message:`${m.name}: ${m.description}`,suggestion:`Call one of: ${y.join(", ")}`});}let d=new Date(Date.now()-720*60*60*1e3).toISOString(),p=await ue(e.rootDir,{dateFrom:d}),g=(await Mt(e.rootDir,{dateFrom:d})).filter(m=>m.rate<60).map(m=>m.category);return JSON.stringify({symbols:s,task:t||null,warnings:l,recentCompliance:{rate:p.rate,totalEvents:p.total,weakAreas:g},preflightReminders:l.length>0?`${l.length} habit(s) not yet followed this session. See warnings above.`:"All preflight habits satisfied."},null,2)}qn();Es();async function sc(n){let e=lt(n);if(!e.enabled)return [];let s=ie(n),t=[];for(let i of s){if(!i.enabled)continue;let r=await ku(n,i,e);t.push(r);}return t}async function ku(n,e,s){let t=Hn(n,e.id),i={habitId:e.id,habitName:e.name,currentTier:t.tier,neverGraduate:false,inCooldown:false};if(t.tier==="hook")return {...i,eligible:false,reason:"Already graduated to hook"};if(t.neverGraduate||s.neverGraduate.includes(e.id))return {...i,eligible:false,reason:"Marked as never-graduate (requires agent cognition)",neverGraduate:true};if(Ns.has(e.check.type))return {...i,eligible:false,reason:`Check type "${e.check.type}" cannot graduate \u2014 requires MCP tool output`,neverGraduate:true};if(t.cooldownUntil&&new Date(t.cooldownUntil)>new Date)return {...i,eligible:false,reason:`In cooldown until ${t.cooldownUntil.split("T")[0]} (demoted recently)`,inCooldown:true};let{thresholds:r}=s,o=new Date;o.setDate(o.getDate()-r.timeWindowDays);try{let a=await ue(n,{habitId:e.id,dateFrom:o.toISOString()});if(a.total<r.minEvents)return {...i,eligible:!1,reason:`Insufficient data: ${a.total}/${r.minEvents} events in ${r.timeWindowDays}d window`,complianceRate:a.rate,eventCount:a.total};if(a.rate<r.minComplianceRate)return {...i,eligible:!1,reason:`Compliance ${a.rate.toFixed(0)}% < ${r.minComplianceRate}% threshold`,complianceRate:a.rate,eventCount:a.total};let c=new Date;return c.setDate(c.getDate()-r.recencyDays),(await ue(n,{habitId:e.id,dateFrom:c.toISOString()})).total===0?{...i,eligible:!1,reason:`No events in last ${r.recencyDays} days \u2014 habit may be dormant`,complianceRate:a.rate,eventCount:a.total}:{...i,eligible:!0,reason:`Ready: ${a.rate.toFixed(0)}% compliance over ${a.total} events in ${r.timeWindowDays}d`,complianceRate:a.rate,eventCount:a.total}}catch{return {...i,eligible:false,reason:"Unable to query practice events (Sentinel DB unavailable)"}}}function ic(n){let e=ie(n),s=lt(n),t=qs(n),i=0,r=0,o=0,a=0;for(let c of e){if(!c.enabled)continue;let l=t[c.id],d=l?.tier||"habit",p=l?.neverGraduate||s.neverGraduate.includes(c.id)||Ns.has(c.check.type);d==="hook"?i++:d==="mcp"?o++:r++,p&&a++;}return {hookCount:i,habitCount:r,mcpCount:o,neverGraduateCount:a,states:t}}qn();var Su=[{name:"paradigm_graduate_check",description:"Check which habits are eligible for graduation from habit tier to hook tier. Returns eligibility status for each habit with compliance data and reasoning. ~300 tokens.",inputSchema:{type:"object",properties:{habitId:{type:"string",description:"Check a specific habit by ID. Omit to check all."}}}},{name:"paradigm_graduate_status",description:"Show the current automation tier of every habit. Returns tier map grouped by hook/habit/mcp with graduation dates and savings estimate. ~200 tokens.",inputSchema:{type:"object",properties:{}}}];async function xu(n,e){let s=await sc(n.rootDir),t=s;if(e.habitId&&(t=s.filter(a=>a.habitId===e.habitId),t.length===0))return JSON.stringify({error:`No habit found with ID "${e.habitId}"`});let i=t.filter(a=>a.eligible),r=t.filter(a=>!a.eligible&&!a.neverGraduate),o=t.filter(a=>a.neverGraduate);return JSON.stringify({summary:{checked:t.length,eligible:i.length,ineligible:r.length,neverGraduate:o.length},...i.length>0?{eligible:i.map(rc),action:"Run `paradigm graduate promote <id>` to graduate eligible habits."}:{},...r.length>0?{ineligible:r.map(rc)}:{},...o.length>0?{neverGraduate:o.map(a=>({id:a.habitId,name:a.habitName,reason:a.reason}))}:{}},null,2)}async function Cu(n){let e=ic(n.rootDir),s=lt(n.rootDir),t={hook:[],habit:[],mcp:[]};for(let[i,r]of Object.entries(e.states)){let o=r.tier||"habit";t[o]||(t[o]=[]),t[o].push({id:i,...r.graduatedAt?{graduatedAt:r.graduatedAt}:{},...r.neverGraduate?{neverGraduate:true}:{}});}return JSON.stringify({tiers:{hook:e.hookCount,habit:e.habitCount,mcp:e.mcpCount},neverGraduate:e.neverGraduateCount,estimatedSavingsPerSession:`~${e.hookCount*150} tokens`,byTier:t,thresholds:s.thresholds},null,2)}function oc(){return Su}async function ac(n,e,s){switch(n){case "paradigm_graduate_check":return {handled:true,text:await xu(s,e)};case "paradigm_graduate_status":return {handled:true,text:await Cu(s)};default:return {handled:false,text:""}}}function rc(n){return {id:n.habitId,name:n.habitName,tier:n.currentTier,reason:n.reason,...n.complianceRate!==void 0?{complianceRate:n.complianceRate}:{},...n.eventCount!==void 0?{eventCount:n.eventCount}:{},...n.inCooldown?{inCooldown:true}:{}}}var cc=new Set(["the","a","an","is","how","does","what","why","when","where","do","can","will","should","would","could","are","was","were","been","being","have","has","had","this","that","it","its","of","in","to","for","with","on","at","by","from","or","and","but","not"]),Pu=.95,Ru=.3,ju=10;function Tu(n,e){let s=n.length,t=e.length;if(s===0)return t;if(t===0)return s;let i=Array.from({length:s+1},()=>Array.from({length:t+1},()=>0));for(let r=0;r<=s;r++)i[r][0]=r;for(let r=0;r<=t;r++)i[0][r]=r;for(let r=1;r<=s;r++)for(let o=1;o<=t;o++){let a=n[r-1]===e[o-1]?0:1;i[r][o]=Math.min(i[r-1][o]+1,i[r][o-1]+1,i[r-1][o-1]+a);}return i[s][t]}function lc(n){let e=n.toLowerCase().split(/\s+/).filter(s=>s.length>0&&!cc.has(s));return e.sort(),e.join(" ")}function Du(n){try{let e=n.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'aspects_fts'");return e.length>0&&e[0].values.length>0}catch{return false}}function dc(n,e,s){let t=s?.limit??ju,i=lc(e);if(i.length===0)return [];let r=Au(n,i,s);if(r.length>0)return r.slice(0,t);if(Du(n)){let a=Ou(n,i,s);if(a.length>0)return a.slice(0,t)}return Iu(n,i,s).slice(0,t)}function Au(n,e,s){try{let t=`
|
|
770
770
|
SELECT
|
|
771
771
|
a.id, a.description, a.category, a.severity, a.tags,
|
|
@@ -836,15 +836,15 @@ ${c.content.diff}
|
|
|
836
836
|
`);for(let l of c.slice(0,t)){let d=l.match(/^(.+?):(\d+):(.*)$/);if(d){let[,p,u,g]=d,m=F.relative(n,p),y="unknown";m.includes(".purpose")||m.includes("portal.yaml")?y="purpose":g.includes("//")||g.includes("#")||g.includes("*")?y="comment":y="code",i.push({filePath:m,line:parseInt(u,10),content:g.trim().slice(0,200),context:y});}}return i}function Tl(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Dl(n,e,s){if(n!=="paradigm_ripple")return {handled:false,text:""};let{symbol:t,depth:i$1=3,includeWorkspace:r=false,response_format:o$1}=e,a=h$1(s.index,t);if(!a){let x=Ag(s.rootDir,t);return o(x.length,n),{handled:true,text:x}}let c=Math.min(Math.max(i$1||3,1),5),l$1=k(s.index,t),d=new Set([t]),p=new Map;function u(x,C){if(C>=c)return;let T=[];for(let j of x){if(d.has(j))continue;d.add(j);let P=k(s.index,j);for(let D of P)d.has(D.symbol)||T.push(D.symbol);}T.length>0&&(p.set(C+1,T),u(T,C+1));}u(l$1.map(x=>x.symbol),1);let g=new Set;for(let[,x]of p)for(let C of x)C!==t&&!l$1.find(T=>T.symbol===C)&&g.add(C);let m=l(s.index,t),y=l$1.length+g.size,f="low";y>10?f="high":y>3&&(f="medium");let b=await Cn(s.rootDir),h=null;if(b){let x=Pn(b,t);x.totalFlows>0&&(x.impactLevel==="high"&&f==="low"?f="medium":x.impactLevel==="high"&&(f="high"),h={totalFlows:x.totalFlows,affectedFlows:x.affectedFlows.map(C=>({flowId:C.flowId,impactLevel:C.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${C.stepAffected.position}, affects ${C.downstreamSteps.length} downstream steps`})),validationSuggestion:x.validationCommands.length>0?`Run: ${x.validationCommands[0]}`:void 0});}let w=new Set([t,...l$1.map(x=>x.symbol),...g]),_=[];try{let x=i(s.index,"gate");for(let C of x)w.has(C.symbol)&&_.push({gate:C.symbol,description:C.description});for(let C of l$1)C.type==="gate"&&!_.find(T=>T.gate===C.symbol)&&_.push({gate:C.symbol,description:C.description});}catch{}let k$1={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:f,analysis:{directlyAffected:l$1.map(x=>({symbol:x.symbol,type:x.type,description:x.description})),indirectlyAffected:Array.from(g),indirectByLevel:Object.fromEntries(p),dependsOn:m.map(x=>({symbol:x.symbol,type:x.type}))},summary:{directCount:l$1.length,indirectCount:g.size,totalAffected:y,dependsOnCount:m.length,levelsAnalyzed:c},recommendation:Og(f)};h&&(k$1.affectedFlows=h),_.length>0&&(k$1.affectedGates=_),k$1.suggestedReviewScope=Ig(f,l$1.length,g.size,_.length,h?.totalFlows??0);try{let x=await Q(s.rootDir,t);x.length>0&&(k$1.personas_affected=x,x.length>2&&f==="low"&&(k$1.impact="medium"));}catch{}try{let x=ka$1(s.rootDir,t);x.length>0&&(k$1.university_content_affected=x.map(C=>({id:C.id,title:C.title,type:C.type,stale:C.stale})));}catch{}if(r&&s.workspace){let x=vo(s.workspace,t);if(x.length>0){k$1.workspaceImpact={siblings:x.map(T=>({project:T.project,references:T.references.map(j=>({symbol:j.symbol,type:j.type,description:j.description}))}))};let C=x.reduce((T,j)=>T+j.references.length,0);C>0&&f==="low"&&(k$1.impact="medium"),C>5&&(k$1.impact="high");}}let v=o$1==="concise"?{symbol:k$1.symbol,impact:k$1.impact,summary:k$1.summary}:k$1,S=JSON.stringify(v,null,2);return o(S.length,n),{handled:true,text:S}}function Ag(n,e){let s=Bn(n,e,{maxResults:20});if(s.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let t=[...new Set(s.map(o=>o.filePath))],i={};for(let o of s)i[o.context]=(i[o.context]||0)+1;let r="low";return t.length>10||s.length>20?r="high":(t.length>3||s.length>5)&&(r="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:r,analysis:{filesAffected:t.slice(0,10),totalFilesAffected:t.length,totalReferences:s.length,contextBreakdown:i,sampleReferences:s.slice(0,5).map(o=>({file:o.filePath,line:o.line,preview:o.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function Og(n){switch(n){case "high":return "High impact change - review all affected symbols carefully before modifying";case "medium":return "Moderate impact - check direct dependencies for breaking changes";case "low":return "Low impact - safe to modify with standard review"}}function Ig(n,e,s,t,i){let r=[];return e>0&&r.push(`Review ${e} direct dependent(s) for breaking changes`),s>0&&r.push(`Scan ${s} indirect dependent(s) for cascading effects`),t>0&&r.push(`Verify ${t} affected gate(s) still enforce correct auth/access`),i>0&&r.push(`Validate ${i} affected flow(s) end-to-end`),n==="high"?r.push("Consider running full test suite before merging"):n==="medium"&&r.push("Run targeted tests for affected components"),r.length===0&&r.push("No downstream dependents detected - safe to proceed"),r}g$1();e();function Al(){return [{name:"paradigm_work_log_record",description:"Record a work log entry \u2014 what got done. Auto-attached to sprint boards and standup summaries. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent that did the work (e.g., "builder")'},summary:{type:"string",description:"What was done"},outcome:{type:"string",enum:["pass","fail","partial","blocked"],description:"How it went"},task_ref:{type:"string",description:'Ticket/issue reference (e.g., "ENG-142")'},files_modified:{type:"array",items:{type:"string"},description:"Files that were modified"},symbols_touched:{type:"array",items:{type:"string"},description:"Paradigm symbols touched"},next_steps:{type:"array",items:{type:"string"},description:"What's left to do"},blockers:{type:"array",items:{type:"string"},description:"What's blocking progress"},duration_minutes:{type:"number",description:"How long it took"},commit:{type:"string",description:"Git commit hash"}},required:["agent","summary","outcome"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_work_log_search",description:"Search work log entries \u2014 what got done. Returns recent work, filterable by agent, outcome, symbol, date. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent"},outcome:{type:"string",enum:["pass","fail","partial","blocked"]},task_ref:{type:"string",description:"Filter by ticket reference"},symbol:{type:"string",description:"Filter by symbol touched"},dateFrom:{type:"string",description:"Start date (YYYY-MM-DD)"},dateTo:{type:"string",description:"End date (YYYY-MM-DD)"},limit:{type:"number",description:"Max entries to return (default 20)"},summary:{type:"boolean",description:"Return aggregate summary instead of entries"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_journal_record",description:"Record a learning journal entry \u2014 what an agent learned. Agent-private, travels across projects. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent who learned this (e.g., "security")'},trigger:{type:"string",enum:["correction_received","confidence_miss","pattern_discovered","debate_loss","failure_analysis","human_feedback","self_reflection"],description:"What triggered this learning moment"},insight:{type:"string",description:"The insight itself"},project:{type:"string",description:"Project where this happened"},transferable:{type:"boolean",description:"Whether this applies to other projects"},confidence_before:{type:"number",description:"Confidence before (0.0-1.0)"},confidence_after:{type:"number",description:"Confidence after (0.0-1.0)"},pattern:{type:"object",properties:{id:{type:"string"},applies_when:{type:"string"},correct_approach:{type:"string"}}},linked_work_log:{type:"string",description:"Work log entry that prompted this"},tags:{type:"array",items:{type:"string"}}},required:["agent","trigger","insight","project","transferable"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_journal_search",description:"Search learning journal entries \u2014 what agents learned. Can search across all agents or a specific one. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent (omit for all agents)"},trigger:{type:"string",description:"Filter by trigger type"},project:{type:"string",description:"Filter by project"},transferable:{type:"boolean",description:"Only show transferable insights"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},stats:{type:"boolean",description:"Return stats instead of entries (requires agent)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_decision_record",description:"Record a team decision \u2014 what we decided and why. Institutional memory with rationale and alternatives. ~100 tokens.",inputSchema:{type:"object",properties:{title:{type:"string",description:"Decision title"},decision:{type:"string",description:"The decision itself"},rationale:{type:"string",description:"Why this was chosen"},participants:{type:"array",items:{type:"object",properties:{id:{type:"string"},role:{type:"string",enum:["human","agent"]},stance:{type:"string",enum:["proposed","supported","dissented","abstained","neutral"]}},required:["id","role","stance"]}},alternatives_considered:{type:"array",items:{type:"object",properties:{option:{type:"string"},rejected_because:{type:"string"}}}},symbols_affected:{type:"array",items:{type:"string"}},status:{type:"string",enum:["active","proposed"],description:"Decision status (default: active)"},tags:{type:"array",items:{type:"string"}}},required:["title","decision","rationale","participants"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_decision_search",description:"Search team decisions \u2014 what we decided. Find active decisions by symbol, participant, status. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",enum:["active","superseded","deprecated","proposed","rejected"]},participant:{type:"string",description:"Filter by participant ID"},symbol:{type:"string",description:"Filter by affected symbol"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},summary:{type:"boolean",description:"Return aggregate summary"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Ol(n,e,s){let t=i=>JSON.stringify(i,null,2);switch(n){case "paradigm_work_log_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.summary,i,"work_log"),o=a$4(s.rootDir,{agent:e.agent,summary:r,outcome:e.outcome,task_ref:e.task_ref,files_modified:e.files_modified,symbols_touched:e.symbols_touched,next_steps:e.next_steps,blockers:e.blockers,duration_minutes:e.duration_minutes,commit:e.commit});return {text:t({recorded:true,id:o.id,timestamp:o.timestamp}),handled:true}}case "paradigm_work_log_search":{if(e.summary){let r=d$5(s.rootDir,7);return {text:t(r),handled:true}}let i=b$5(s.rootDir,{agent:e.agent,outcome:e.outcome,task_ref:e.task_ref,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:t({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,summary:r.summary,outcome:r.outcome,timestamp:r.timestamp,symbols_touched:r.symbols_touched,task_ref:r.task_ref}))}),handled:true}}case "paradigm_journal_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.insight,i,"learning_journal"),o=a$3(e.agent,{trigger:e.trigger,insight:r,project:e.project,transferable:e.transferable,confidence_before:e.confidence_before,confidence_after:e.confidence_after,pattern:e.pattern,linked_work_log:e.linked_work_log,tags:e.tags});return {text:t({recorded:true,id:o.id,agent:o.agent,timestamp:o.timestamp}),handled:true}}case "paradigm_journal_search":{if(e.stats&&e.agent){let r=e$3(e.agent);return {text:t(r),handled:true}}let i=e.agent?b$4(e.agent,{trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20}):d$4({trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:t({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,trigger:r.trigger,insight:r.insight.slice(0,200),project:r.project,transferable:r.transferable,timestamp:r.timestamp}))}),handled:true}}case "paradigm_decision_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.decision,i,"team_decisions"),{filtered:o}=d$3(e.rationale,i,"team_decisions"),a=a$2(s.rootDir,{title:e.title,decision:r,rationale:o,participants:e.participants,alternatives_considered:e.alternatives_considered,symbols_affected:e.symbols_affected,status:e.status||"active",tags:e.tags});return {text:t({recorded:true,id:a.id,title:a.title,timestamp:a.timestamp}),handled:true}}case "paradigm_decision_search":{if(e.summary){let r=g$5(s.rootDir);return {text:t(r),handled:true}}let i=d$2(s.rootDir,{status:e.status,participant:e.participant,symbol:e.symbol,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:t({count:i.length,entries:i.map(r=>({id:r.id,title:r.title,status:r.status,decision:r.decision.slice(0,200),participants:r.participants.map(o=>`${o.id} (${o.stance})`),symbols_affected:r.symbols_affected,timestamp:r.timestamp}))}),handled:true}}default:return {text:`Unknown streams tool: ${n}`,handled:false}}}v();b$1();t();g$1();h();function Il(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_neverland",description:"Neverland Validation \u2014 aggregate learning metrics across all agents. Shows acceptance rates, threshold drift, expertise growth, notebook counts, cross-project transfer, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature). ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function $g(n){let e=Date.now(),s=n.match(/^(\d+)(m|h|d)$/);if(s){let t=parseInt(s[1],10),i=s[2],r=i==="m"?t*6e4:i==="h"?t*36e5:t*864e5;return new Date(e-r).toISOString()}return n}async function $l(n,e,s){let t=i=>JSON.stringify(i,null,2);switch(n){case "paradigm_ambient_nominations":{m$1(s.rootDir);let r=e.pending_only!==false,o=e.limit||20,a=i$2(s.rootDir,{agent:e.agent,urgency:e.urgency,pending_only:r,limit:o+20}),c=t$2(s.rootDir);a=u$1(a,c).slice(0,o);let l=F.join(s.rootDir,".paradigm/events/nominations.jsonl");if(O.existsSync(l))try{let p=O.readFileSync(l,"utf8"),u=new Set(a.map(m=>m.id)),g=p.trim().split(`
|
|
837
837
|
`).map(m=>{try{let y=JSON.parse(m);return u.has(y.id)?(y.surfaced=!0,JSON.stringify(y)):m}catch{return m}});O.writeFileSync(l,g.join(`
|
|
838
838
|
`)+`
|
|
839
|
-
`,"utf8");}catch{}let d={count:a.length,nominations:a.map(p=>({id:p.id,agent:p.agent,urgency:p.urgency,type:p.type,brief:p.brief,relevance:p.relevance,timestamp:p.timestamp,engaged:p.engaged,response:p.response}))};if(e.include_debates){let u=j$3(s.rootDir).filter(g=>!g.resolution);d.debates=u.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),d.debate_count=u.length;}return {text:t(d),handled:true}}case "paradigm_ambient_events":{let i=e.since?$g(e.since):void 0,r=e.limit||50,o=a$5(s.rootDir,{type:e.type,source:e.source,symbol:e.symbol,agent:e.agent,since:i,limit:r});return {text:t({count:o.length,events:o.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i=e.nomination_id,r=e.response,o=e.reason,a=k$1(s.rootDir,i,r,o);if(a)try{let{appendSessionWorkEntry:l}=await import('./session-work-log-
|
|
840
|
-
`),sections_included:{profile:true,decisions:a,journal:c,nominations:o}}),handled:true}}case "paradigm_ambient_promote":{let i=e.agent,r=s$1(s.rootDir,i);return {text:t({agent:i,promoted:r.promoted,entries:r.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e.agent,r=e.dry_run===true,o=p$1(s.rootDir,i);if(r)return {text:t({agent:i,dry_run:true,stats:o,note:o.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(o.acceptRate*100).toFixed(0)}% \u2014 ${o.acceptRate>.8?"would lower threshold":o.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=o$1(s.rootDir,i);return {text:t({agent:i,...a,stats:o}),handled:true}}case "paradigm_ambient_neverland":{let i=q$1(s.rootDir);return {text:t(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:t(await Eg(s.rootDir,e)),handled:true};default:return {text:`Unknown ambient tool: ${n}`,handled:false}}}var Fg={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function Ng(n){try{let e=F.join(n,".paradigm","config.yaml");if(O.existsSync(e)){let t=O.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(t)return t[1].trim()}}catch{}return F.basename(n)}async function Eg(n,e={}){let s=e.dry_run===true,t=Ng(n),i=b$9(n),r=i.filter(m=>m.type==="user-verdict"&&m.verdict&&m.agent);if(r.length===0)return {sessionEntries:i.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:s,details:[]};let o=new Map;for(let m of r){let y=m.agent;o.has(y)||o.set(y,[]),o.get(y).push(m);}let a=i.filter(m=>m.type==="agent-contribution"),c=new Map;for(let m of a)m.agent&&(c.has(m.agent)||c.set(m.agent,[]),c.get(m.agent).push(m));let l=[],d={},p=0;for(let[m,y]of o){d[m]=0;let f=y.filter(k=>k.verdict==="accepted").length;y.filter(k=>k.verdict==="dismissed").length;y.filter(k=>k.verdict==="revised").length;let w=y.length,_=w>0?f/w:0;for(let k of y){let v=Fg[k.verdict];if(!v)continue;let S=c.get(m)?.shift(),x=Hg(k,S,{acceptRate:_,total:w,accepted:f}),C=k.verdict==="accepted"?.85:k.verdict==="revised"?.6:.4,T={agent:m,verdict:k.verdict,trigger:v,insight:x,symbols:k.symbols};if(l.push(T),s)d[m]++,p++;else try{a$3(m,{trigger:v,insight:x,confidence_before:k.verdict==="accepted"?.7:.8,confidence_after:C,project:t,transferable:k.verdict==="dismissed",tags:["postflight",`verdict:${k.verdict}`,...(k.symbols||[]).map(j=>`symbol:${j}`)]}),d[m]++,p++;}catch{}}}let u={},g=0;if(!s)for(let m of o.keys())try{let y=s$1(n,m);y.promoted>0&&(u[m]=y.promoted,g+=y.promoted);}catch{}return {sessionEntries:i.length,agentsProcessed:Array.from(o.keys()),journalsWritten:p,journalsByAgent:d,promoted:g,promotedByAgent:u,dryRun:s,details:l}}function Hg(n,e,s){let t=n.symbols?.length?` (symbols: ${n.symbols.join(", ")})`:"",i=n.reason?` Reason: ${n.reason}.`:"";switch(n.verdict){case "accepted":return `Contribution accepted by user${t}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;case "dismissed":return `Contribution dismissed by user${t}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;case "revised":return `Contribution revised by user${t}.${i}`+(n.revisionDelta?` Delta: "${n.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;default:return `Unknown verdict "${n.verdict}"${t}.${i}`}}var Yt=["purpose-coverage","purpose-exists","portal-gates","aspect-anchors","purpose-freshness","aspect-advisory","lore-required","habits-blocking","purpose-required-patterns","drift-detection","portal-compliance","graduation-tracking","orchestration-required"],Fl={strict:{"purpose-coverage":"block","purpose-exists":"block","portal-gates":"block","aspect-anchors":"block","purpose-freshness":"warn","aspect-advisory":"warn","lore-required":"block","habits-blocking":"block","purpose-required-patterns":"block","drift-detection":"block","portal-compliance":"block","graduation-tracking":"warn","orchestration-required":"block"},balanced:{"purpose-coverage":"block","purpose-exists":"warn","portal-gates":"warn","aspect-anchors":"warn","purpose-freshness":"warn","aspect-advisory":"off","lore-required":"warn","habits-blocking":"block","purpose-required-patterns":"warn","drift-detection":"warn","portal-compliance":"warn","graduation-tracking":"off","orchestration-required":"warn"},minimal:{"purpose-coverage":"warn","purpose-exists":"off","portal-gates":"off","aspect-anchors":"off","purpose-freshness":"off","aspect-advisory":"off","lore-required":"off","habits-blocking":"warn","purpose-required-patterns":"off","drift-detection":"off","portal-compliance":"off","graduation-tracking":"off","orchestration-required":"off"}};function Vn(n){let e=F.join(n,".paradigm","config.yaml");if(!O.existsSync(e))return {};try{return Z.load(O.readFileSync(e,"utf8"))||{}}catch{return {}}}function mi(n,e){let s=F.join(n,".paradigm","config.yaml");O.writeFileSync(s,Z.dump(e,{lineWidth:120,noRefs:true}),"utf8");}function Yn(n){let e=n.enforcement?.level||"balanced",s=Fl[e]||Fl.balanced,t=n.enforcement?.checks||{},i=n.enforcement?.orchestration?.threshold??3,r={...s};for(let[o,a]of Object.entries(t))Yt.includes(o)&&Nl(a)&&(r[o]=a);return r.orchestrationThreshold=i,r}function Nl(n){return n==="block"||n==="warn"||n==="off"}function qg(n){return n==="strict"||n==="balanced"||n==="minimal"}function Mg(n){return Yt.includes(n)}var Lg=[{name:"paradigm_enforcement_configure",description:"View or modify stop hook enforcement levels. Actions: status (view current), set-level (change preset), override (set per-check severity), reset (clear overrides). ~250 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["status","set-level","override","reset"],description:"Action to perform."},level:{type:"string",enum:["strict","balanced","minimal"],description:"Enforcement preset level (for set-level action)."},checkId:{type:"string",description:"Check ID to override (for override action). One of: "+Yt.join(", ")},severity:{type:"string",enum:["block","warn","off"],description:"Severity to set for the check (for override action)."}},required:["action"]}}];async function Wg(n,e){let{action:s,level:t,checkId:i,severity:r}=e;switch(s){case "status":{let o=Vn(n.rootDir),a=Yn(o),c=o.enforcement?.level||"balanced",l=o.enforcement?.checks||{},d=o.enforcement?.orchestration?.threshold??3;return JSON.stringify({level:c,orchestrationThreshold:d,orchestrationNote:"Threshold is compared against magnitude score (not just file count). Magnitude = source files + cross-package penalty + security-adjacent penalty + symbol file changes.",overrides:Object.keys(l).length>0?l:void 0,effective:a,checkIds:[...Yt],presetLevels:["strict","balanced","minimal"]},null,2)}case "set-level":{if(!t||!qg(t))return JSON.stringify({error:`Invalid level "${t}". Must be one of: strict, balanced, minimal`});let o=Vn(n.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.level=t,o.enforcement.checks={},mi(n.rootDir,o);let a=Yn(o);return JSON.stringify({success:true,level:t,message:`Enforcement level set to "${t}". Per-check overrides cleared.`,effective:a},null,2)}case "override":{if(!i||!Mg(i))return JSON.stringify({error:`Invalid checkId "${i}". Must be one of: ${Yt.join(", ")}`});if(!r||!Nl(r))return JSON.stringify({error:`Invalid severity "${r}". Must be one of: block, warn, off`});let o=Vn(n.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.checks||(o.enforcement.checks={}),o.enforcement.checks[i]=r,mi(n.rootDir,o);let a=Yn(o);return JSON.stringify({success:true,checkId:i,severity:r,message:`Override set: ${i} = ${r}`,effective:a},null,2)}case "reset":{let o=Vn(n.rootDir);o.enforcement&&(o.enforcement.checks={}),mi(n.rootDir,o);let a=Yn(o),c=o.enforcement?.level||"balanced";return JSON.stringify({success:true,message:`All per-check overrides cleared. Preset "${c}" is now fully in effect.`,effective:a},null,2)}default:return JSON.stringify({error:`Unknown action "${s}". Must be one of: status, set-level, override, reset`})}}function El(){return Lg}async function Hl(n,e,s){if(n==="paradigm_enforcement_configure"){let t=await Wg(s,e);return o(t.length,"paradigm_enforcement_configure"),{handled:true,text:t}}return {handled:false,text:""}}function Jg(n,e){let s=[];for(let t=0;t<=e.length;t++)s[t]=[t];for(let t=0;t<=n.length;t++)s[0][t]=t;for(let t=1;t<=e.length;t++)for(let i=1;i<=n.length;i++)e.charAt(t-1)===n.charAt(i-1)?s[t][i]=s[t-1][i-1]:s[t][i]=Math.min(s[t-1][i-1]+1,s[t][i-1]+1,s[t-1][i]+1);return s[e.length][n.length]}function ql(n,e,s={}){let{maxDistance:t=3,maxResults:i=5}=s,r=n.toLowerCase(),o=[];for(let a of e){let c=a.toLowerCase();if(c===r){o.push({match:a,distance:0});continue}if(c.includes(r)||r.includes(c)){o.push({match:a,distance:1});continue}let l=Jg(r,c);l<=t&&o.push({match:a,distance:l});}return o.sort((a,c)=>a.distance!==c.distance?a.distance-c.distance:a.match.localeCompare(c.match)),o.slice(0,i)}v();function zg(n,e){let s$1=new u(n),t=e||(async()=>{}),i=o=>async(a,c,l)=>o(a,c,l),r$1=o=>async(a,c,l)=>o(a,c,l,t);return s$1.registerAll([{key:"context",tier:"core",getToolsList:r,handleTool:i(s)},{key:"navigate",tier:"core",getToolsList:Xo,handleTool:i(Zo)},{key:"tags",tier:"core",getToolsList:_a,handleTool:i(ka)},{key:"purpose-portal",tier:"core",getToolsList:Ta,handleTool:r$1(Da)},{key:"pm",tier:"core",getToolsList:Ba,handleTool:i(Va)},{key:"reindex",tier:"core",getToolsList:ma$1,handleTool:r$1(na$1)},{key:"docs",tier:"core",getToolsList:Pl,handleTool:i(Rl)},{key:"ripple",tier:"core",getToolsList:Tl,handleTool:i(Dl)}]),s$1.registerAll([{key:"wisdom",tier:"feature",getToolsList:Go,handleTool:i(Uo)},{key:"history",tier:"feature",getToolsList:zo,handleTool:i(Bo)},{key:"lore",tier:"feature",getToolsList:Xa,handleTool:i(Za)},{key:"streams",tier:"feature",getToolsList:Al,handleTool:i(Ol)},{key:"ambient",tier:"feature",getToolsList:Il,handleTool:i($l)},{key:"sentinel",tier:"feature",getToolsList:ea,handleTool:i(ta)},{key:"flows",tier:"feature",getToolsList:sa,handleTool:i(ia)},{key:"fixtures",tier:"feature",getToolsList:la,handleTool:i(da)},{key:"orchestration",tier:"feature",getToolsList:fa,handleTool:i(ya)},{key:"habits",tier:"feature",getToolsList:tc,handleTool:i(nc)},{key:"tasks",tier:"feature",getToolsList:mc,handleTool:i(fc)},{key:"personas",tier:"feature",getToolsList:Fc,handleTool:i(Nc)},{key:"protocols",tier:"feature",getToolsList:Ec,handleTool:i(Hc)},{key:"symphony",tier:"feature",getToolsList:il,handleTool:i(rl)},{key:"university",tier:"feature",getToolsList:al,handleTool:i(cl)},{key:"agents",tier:"feature",getToolsList:pl,handleTool:i(ul)},{key:"notebooks",tier:"feature",getToolsList:gl,handleTool:i(ml)},{key:"aspect-graph",tier:"feature",getToolsList:uc,handleTool:i(gc)},{key:"enforcement",tier:"feature",getToolsList:El,handleTool:i(Hl),detect:o=>O.existsSync(F.join(o,".paradigm","config.yaml"))},{key:"graph",tier:"feature",getToolsList:Lc,handleTool:i(Wc),detect:o=>O.existsSync(F.join(o,".paradigm","aspect-graph.db"))},{key:"heatmap",tier:"feature",getToolsList:Gc,handleTool:i(Uc),detect:o=>O.existsSync(F.join(o,".paradigm","aspect-graph.db"))}]),s$1.registerAll([{key:"conductor",tier:"advanced",getToolsList:tl,handleTool:i(nl)},{key:"platform",tier:"advanced",getToolsList:ll,handleTool:i(dl)},{key:"pipeline",tier:"advanced",getToolsList:Yc,handleTool:i(Kc)},{key:"graduation",tier:"advanced",getToolsList:oc,handleTool:i(ac)},{key:"assessment",tier:"advanced",getToolsList:xc,handleTool:i(Cc)}]),s$1}function Bg(n,e){let s=g=>g.toLowerCase().replace(/\/+$/,""),t=s(n),i=s(e);if(t===i)return 1;let r=g=>!g.includes("/")&&g.includes("."),o=g=>r(g)?g.split("."):g.split("/").filter(Boolean),a=o(t),c=o(i);if(r(t)||r(i)){let g=r(t)?t.split("."):t.split("/").filter(Boolean),m=r(i)?i.split("."):i.split("/").filter(Boolean),y=0;for(let f=0;f<Math.min(g.length,m.length)&&g[f]===m[f];f++)y++;return y>0?Math.min(1,.5+y/Math.max(g.length,m.length)*.5):0}let l=0,d=Math.max(a.length,c.length);for(let g=0;g<d;g++){let m=a[g]||"",y=c[g]||"";m===y?l++:m.startsWith(":")&&y.startsWith(":")?l+=.9:m.startsWith(":")||y.startsWith(":")?l+=.7:(m.replace(/s$/,"")===y.replace(/s$/,"")||y.replace(/s$/,"")===m.replace(/s$/,""))&&(l+=.8);}let p=l/d,u=a.length===c.length?.1:0;return Math.min(1,p+u)}function Vg(){return [{name:"paradigm_search",description:"Search for Paradigm symbols by name, description, or tags. Includes fuzzy matching for typo tolerance. Returns matching symbols with names, paths, types, and descriptions. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query (matches symbol names, descriptions, tags)"},type:{type:"string",enum:["component","flow","gate","signal","aspect"],description:"Optional: filter by symbol type (v2: #component, $flow, ^gate, !signal, ~aspect)"},limit:{type:"number",description:"Maximum results to return (default: 10)"},fuzzy:{type:"boolean",description:"Enable fuzzy matching for typos (default: true)"},includeWorkspace:{type:"boolean",description:"Also search sibling workspace projects (default: false). Requires workspace configured in config.yaml."},componentType:{type:"string",description:'Filter components by type (e.g., "view", "service", "tool"). Only applies to #component symbols.'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_related",description:"Get all symbols related to a given symbol. Call before modifying code to understand what uses this symbol and what it depends on. Returns uses/used-by lists with symbol types. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to find relations for"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_status",description:"Get project overview - call this at session start for orientation. Shows symbol counts, project health, and available features. Returns symbol counts by type, project health score, and feature flags. ~100 tokens.",inputSchema:{type:"object",properties:{response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_gates_for_route",description:"Suggest which gates should be applied to a route based on patterns in the project. Returns suggested gates with confidence scores and existing patterns. ~150 tokens.",inputSchema:{type:"object",properties:{route:{type:"string",description:"Route path (e.g., /api/users, /admin/settings)"},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["route"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_plugin_check",description:"Check for updates to installed Claude Code plugins. Reports which marketplace clones have newer remote commits and which cached versions are stale.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_workspace_reindex",description:"Rebuild scan-index.json for all workspace members. Requires workspace configured in config.yaml. Returns per-member symbol counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_tool_activate",description:"Activate an advanced-tier tool module for this session. Advanced tools are not loaded by default to reduce tool count. Call with a feature key to make its tools available. ~50 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:'Feature key to activate (e.g., "graph", "heatmap", "pipeline", "conductor", "platform")'}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}function Ll(n$2,e,s){let t=e(),i$1=zg(t.rootDir,s);n$2.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[...Vg(),...i$1.getActiveTools()]})),n$2.setRequestHandler(CallToolRequestSchema,async r=>{let{name:o$1,arguments:a$1}=r.params;q(o$1,a$1??{});let c=e(),l$1=j$1();l$1.setRootDir(c.rootDir);let d=null,p=null;l$1.hasRecoveredThisSession()||(d=await t$1(c.rootDir),p=a(),b$2(),l$1.markRecovered());let u=await(async()=>{switch(o$1){case "paradigm_search":{let{query:g,type:m,limit:y=10,fuzzy:f=true,includeWorkspace:b=false,componentType:h,response_format:w}=a$1,_=`search:${g}:${m||""}:${y}:${f}:${b}:${h||""}`,k=await v$1.getOrCompute(_,()=>{let C=j$2(c.index,g);return m&&(C=C.filter(T=>T.type===m)),h&&(C=C.filter(T=>T.componentType===h)),C}),v=[];if(k.length===0&&f){let C=n(c.index),T=C.map(j=>j.symbol);v=ql(g,T,{maxDistance:3,maxResults:5}),v.length>0&&(k=v.map(j=>C.find(P=>P.symbol===j.match)).filter(j=>j!=null),m&&(k=k.filter(j=>j.type===m)));}k=k.slice(0,y);let S={query:g,count:k.length,results:k.map(C=>({symbol:C.symbol,type:C.type,description:C.description,filePath:C.filePath,...C.componentType?{componentType:C.componentType}:{},...C.parentSymbol?{parentSymbol:C.parentSymbol}:{}}))};if(v.length>0&&(S.fuzzyMatched=true,S.fuzzyNote=`No exact matches for "${g}". Showing similar symbols.`,S.suggestions=v.map(C=>({symbol:C.match,distance:C.distance}))),b&&c.workspace){let C=Tt(c.workspace,g),T=m?C.filter(j=>j.type===m):C;T.length>0&&(S.workspaceResults=T.slice(0,y).map(j=>({symbol:j.symbol,type:j.type,description:j.description,filePath:j.filePath,project:j.project})),S.workspaceCount=T.length);}w==="concise"&&(S.results=k.map(C=>({symbol:C.symbol,type:C.type})),delete S.fuzzyMatched,delete S.fuzzyNote,delete S.suggestions,delete S.workspaceResults,delete S.workspaceCount);let x=JSON.stringify(S,null,2);return o(x.length,o$1),{content:[{type:"text",text:x}]}}case "paradigm_related":{let{symbol:g}=a$1,m=h$1(c.index,g);if(!m){let h=Bn(c.rootDir,g,{maxResults:20});if(h.length===0){let S=JSON.stringify({error:"Symbol not found",symbol:g,fallback:"searched",referencesFound:0,recovery:["Run `paradigm_search` with a partial name to find similar symbols","Check `.purpose` files for symbol definitions","Use `paradigm_status` to see available symbols by type","The symbol may not be indexed yet - run `paradigm scan`"]},null,2);return o(S.length,o$1),{content:[{type:"text",text:S}]}}let w=[...new Set(h.map(S=>S.filePath))],_=h.filter(S=>S.context==="purpose"),k=h.filter(S=>S.context==="code"),v=JSON.stringify({symbol:g,status:"not-indexed",fallback:"grep-search",note:"Approximate relationships from grep \u2014 run `paradigm scan` for accurate graph data.",usedBy:w.slice(0,10).map(S=>({file:S,references:h.filter(x=>x.filePath===S).length})),uses:[],summary:{totalFiles:w.length,totalReferences:h.length,purposeFileRefs:_.length,codeRefs:k.length},suggestion:"Run `paradigm scan` to enable full relationship tracking"},null,2);return o(v.length,o$1),{content:[{type:"text",text:v}]}}let y=k(c.index,g),f=l(c.index,g),b=JSON.stringify({symbol:m.symbol,type:m.type,description:m.description,usedBy:y.map(h=>({symbol:h.symbol,type:h.type,description:h.description})),uses:f.map(h=>({symbol:h.symbol,type:h.type,description:h.description}))},null,2);return o(b.length,o$1),{content:[{type:"text",text:b}]}}case "paradigm_status":{let g=a$1.response_format,m$1=await v$1.getOrCompute("status",async()=>{let f=m(c.index),b=Object.values(f).reduce((j,P)=>j+P,0),h={};for(let j of Object.keys(f)){let P=i(c.index,j);h[j]=P.slice(0,3).map(D=>D.symbol);}let w=ga.platform(),_=w==="win32",k=_?"PowerShell/CMD":w==="darwin"?"zsh/bash":"bash",v;try{let j=await U(c.rootDir);j&&j.health.total>0&&(v=j.health);}catch{}let S=i(c.index,"component"),x={};for(let j of S)j.componentType&&(x[j.componentType]=(x[j.componentType]||0)+1);let C=S.filter(j=>!j.componentType).length,T;try{let{checkPurposeHealth:j}=await import('./integrity-checker-DHGMZQDG.js');T=j(c.aggregation.purposeFiles,c.rootDir).healthScore;}catch{}return JSON.stringify({project:c.projectName,symbolSystem:"v2",counts:{"# components":f.component,"$ flows":f.flow,"^ gates":f.gate,"! signals":f.signal,"~ aspects":f.aspect},total:b,...Object.keys(x).length>0?{componentTypes:{...x,...C>0?{"(untyped)":C}:{}}}:{},examples:h,hasPortalYaml:c.gateConfig!==null,purposeFiles:c.aggregation.purposeFiles.length,...T!==void 0?{purposeHealthScore:T}:{},...v?{protocols:v}:{},note:"Symbol System v2: Use tags [feature], [state], [integration], [idea] for classification. Use type field for structural role (view, service, tool, etc.)",environment:{os:w,shell:k,terminalNote:_?"Use PowerShell syntax: semicolons for command chaining, backslashes for paths, $env:VAR for env vars":"Use Unix syntax: && for command chaining, forward slashes for paths, $VAR for env vars"}},null,2)}),y=m$1;if(g==="concise")try{let f=JSON.parse(m$1);y=JSON.stringify({project:f.project,counts:f.counts,total:f.total},null,2);}catch{}return o(y.length,o$1),{content:[{type:"text",text:y}]}}case "paradigm_gates_for_route":{let{route:g,response_format:m}=a$1,f=typeof g=="string"&&!g.includes("/")&&g.includes(".")?"POST":a$1.method||"GET",b=i(c.index,"gate"),h=[],w=[];if(c.gateConfig?.routes)for(let[P,D]of Object.entries(c.gateConfig.routes))D.gates&&w.push({route:P,gates:D.gates,method:D.method});if(c.workspace)for(let[P,D]of c.workspace.siblingIndices){let I=D.gateConfig;if(I?.routes)for(let[A,N]of Object.entries(I.routes)){let H=N,q=Array.isArray(H)?H:H?.gates;q&&w.push({route:A,gates:q,method:Array.isArray(H)?void 0:H?.method,source:P});}}for(let P of w){let D=Bg(g,P.route);if(D>=.6&&(!P.method||P.method===f))for(let I of P.gates){let A=b.find(N=>N.symbol===I||N.symbol===`^${I}`);if(A&&!h.find(N=>N.gate===A.symbol)){let N=P.source?`${P.source}/portal.yaml`:"portal.yaml";h.push({gate:A.symbol,reason:`Similar route "${P.route}" uses this gate`,confidence:D>=.8?"high":"medium",source:N});}}}let v=g.split("/").filter(Boolean).find(P=>!P.startsWith(":")&&P!=="api")?.replace(/s$/,"")||"",S=g.match(/\/:(id|[a-z]+Id)($|\/)/i);if(S&&v){let P=b.find(D=>{let I=D.symbol.toLowerCase(),A=(D.description||"").toLowerCase();return I.includes(`${v}-owner`)||I.includes("owner")||I.includes("ownership")||A.includes("owner")||A.includes("ownership")||A.includes("belongs to")});P?h.push({gate:P.symbol,reason:`Resource ID route (${v}) typically needs ownership verification`,confidence:"high"}):h.push({gate:`^${v}-owner`,reason:`Consider adding ownership gate for ${v} resource`,confidence:"medium"});}if(g.includes("/admin")||g.includes("/settings")){let P=b.find(D=>D.symbol.includes("admin")||D.description?.toLowerCase().includes("admin"));P&&h.push({gate:P.symbol,reason:"Route appears to be admin-related",confidence:"high"});}if(g.startsWith("/api/")||g.includes("/user")||g.includes("/account")){let P=b.find(D=>D.symbol.includes("authenticated")||D.symbol.includes("auth"));P&&h.push({gate:P.symbol,reason:"API/user routes typically require authentication",confidence:"high"});}if(g.includes("/premium")||g.includes("/pro")||g.includes("/export")){let P=b.find(D=>D.symbol.includes("subscription")||D.symbol.includes("premium"));P&&h.push({gate:P.symbol,reason:"Route appears to be a premium feature",confidence:"medium"});}if(f==="DELETE"){let P=b.find(D=>D.symbol.includes("authenticated"));P&&!h.find(D=>D.gate===P.symbol)&&h.push({gate:P.symbol,reason:"DELETE operations require authentication",confidence:"high"});}if(["POST","PUT","PATCH"].includes(f)){let P=b.find(D=>D.symbol.includes("authenticated"));P&&!h.find(D=>D.gate===P.symbol)&&h.push({gate:P.symbol,reason:"Write operations typically require authentication",confidence:"high"});}let x=new Set,C=h.filter(P=>x.has(P.gate)?false:(x.add(P.gate),true)),T=m==="concise"?{suggestions:C.map(P=>({gate:P.gate,confidence:P.confidence}))}:{route:g,method:f,suggestions:C,availableGates:b.map(P=>({symbol:P.symbol,description:P.description})),note:S?"Resource ID routes should verify the user owns/has access to the specific resource.":"These are suggestions based on route patterns. Review your portal.yaml for exact requirements."},j=JSON.stringify(T,null,2);o(j.length,o$1);try{n$1(c.rootDir,{type:"gate-checked",source:"mcp-tool-call",tool:"paradigm_gates_for_route",symbols:C.map(P=>P.gate),context:`Gate check for ${f} ${g}`});}catch{}return {content:[{type:"text",text:j}]}}case "paradigm_plugin_check":{let{runPluginUpdateCheck:g}=await import('./plugin-update-checker-M7PW434O.js'),m=await g(),y=m.filter(w=>w.hasRemoteUpdate||w.hasCacheStale);if(y.length===0){let w=m.length===0?"No Claude Code plugins found in ~/.claude/plugins/marketplaces/.":"All installed plugins are up to date.";return o(w.length,o$1),{content:[{type:"text",text:w}]}}let f=[`Plugin updates available:
|
|
839
|
+
`,"utf8");}catch{}let d={count:a.length,nominations:a.map(p=>({id:p.id,agent:p.agent,urgency:p.urgency,type:p.type,brief:p.brief,relevance:p.relevance,timestamp:p.timestamp,engaged:p.engaged,response:p.response}))};if(e.include_debates){let u=j$3(s.rootDir).filter(g=>!g.resolution);d.debates=u.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),d.debate_count=u.length;}return {text:t(d),handled:true}}case "paradigm_ambient_events":{let i=e.since?$g(e.since):void 0,r=e.limit||50,o=a$5(s.rootDir,{type:e.type,source:e.source,symbol:e.symbol,agent:e.agent,since:i,limit:r});return {text:t({count:o.length,events:o.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i=e.nomination_id,r=e.response,o=e.reason,a=k$1(s.rootDir,i,r,o);if(a)try{let{appendSessionWorkEntry:l}=await import('./session-work-log-IEYBPFUC.js'),p=i$2(s.rootDir,{limit:500}).find(u=>u.id===i);l(s.rootDir,{timestamp:new Date().toISOString(),type:"user-verdict",agent:p?.agent,nominationId:i,verdict:r,reason:o});}catch{}let c=false;return e.resolve_debate&&a&&(c=l$1(s.rootDir,e.resolve_debate,i,e.reason)),{text:t({engaged:a,nomination_id:i,response:r,debate_resolved:c||void 0}),handled:true}}case "paradigm_context_compose":{let i=e.agent,r=e.symbols||[],o=e.include_nominations!==false,a=e.include_decisions!==false,c=e.include_journal!==false,l=e.max_decisions||5,d=e.max_journal||5,p=f$2(s.rootDir,i);if(!p)return {text:t({error:`Agent profile not found: ${i}`}),handled:true};let u=[],g=n$2(p,r);if(g.trim()&&u.push(g),a){let m=d$2(s.rootDir,{status:"active",limit:l});if(m.length>0){u.push("## Recent Team Decisions");for(let y of m)u.push(`- **${y.title}**: ${y.decision.slice(0,150)}${y.decision.length>150?"...":""}`);u.push("");}}if(c){let m=b$4(i,{transferable:true,limit:d});if(m.length>0){u.push("## Transferable Insights");for(let y of m)u.push(`- [${y.trigger}] ${y.insight.slice(0,150)}${y.insight.length>150?"...":""}`);u.push("");}}if(o){let m=i$2(s.rootDir,{pending_only:true,limit:10});if(m.length>0){u.push("## Pending Nominations");for(let y of m)u.push(`- [${y.urgency}] ${y.brief}`);u.push("");}}return {text:t({agent:i,context:u.join(`
|
|
840
|
+
`),sections_included:{profile:true,decisions:a,journal:c,nominations:o}}),handled:true}}case "paradigm_ambient_promote":{let i=e.agent,r=s$1(s.rootDir,i);return {text:t({agent:i,promoted:r.promoted,entries:r.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e.agent,r=e.dry_run===true,o=p$1(s.rootDir,i);if(r)return {text:t({agent:i,dry_run:true,stats:o,note:o.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(o.acceptRate*100).toFixed(0)}% \u2014 ${o.acceptRate>.8?"would lower threshold":o.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=o$1(s.rootDir,i);return {text:t({agent:i,...a,stats:o}),handled:true}}case "paradigm_ambient_neverland":{let i=q$1(s.rootDir);return {text:t(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:t(await Eg(s.rootDir,e)),handled:true};default:return {text:`Unknown ambient tool: ${n}`,handled:false}}}var Fg={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function Ng(n){try{let e=F.join(n,".paradigm","config.yaml");if(O.existsSync(e)){let t=O.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(t)return t[1].trim()}}catch{}return F.basename(n)}async function Eg(n,e={}){let s=e.dry_run===true,t=Ng(n),i=b$9(n),r=i.filter(m=>m.type==="user-verdict"&&m.verdict&&m.agent);if(r.length===0)return {sessionEntries:i.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:s,details:[]};let o=new Map;for(let m of r){let y=m.agent;o.has(y)||o.set(y,[]),o.get(y).push(m);}let a=i.filter(m=>m.type==="agent-contribution"),c=new Map;for(let m of a)m.agent&&(c.has(m.agent)||c.set(m.agent,[]),c.get(m.agent).push(m));let l=[],d={},p=0;for(let[m,y]of o){d[m]=0;let f=y.filter(k=>k.verdict==="accepted").length;y.filter(k=>k.verdict==="dismissed").length;y.filter(k=>k.verdict==="revised").length;let w=y.length,_=w>0?f/w:0;for(let k of y){let v=Fg[k.verdict];if(!v)continue;let S=c.get(m)?.shift(),x=Hg(k,S,{acceptRate:_,total:w,accepted:f}),C=k.verdict==="accepted"?.85:k.verdict==="revised"?.6:.4,T={agent:m,verdict:k.verdict,trigger:v,insight:x,symbols:k.symbols};if(l.push(T),s)d[m]++,p++;else try{a$3(m,{trigger:v,insight:x,confidence_before:k.verdict==="accepted"?.7:.8,confidence_after:C,project:t,transferable:k.verdict==="dismissed",tags:["postflight",`verdict:${k.verdict}`,...(k.symbols||[]).map(j=>`symbol:${j}`)]}),d[m]++,p++;}catch{}}}let u={},g=0;if(!s)for(let m of o.keys())try{let y=s$1(n,m);y.promoted>0&&(u[m]=y.promoted,g+=y.promoted);}catch{}return {sessionEntries:i.length,agentsProcessed:Array.from(o.keys()),journalsWritten:p,journalsByAgent:d,promoted:g,promotedByAgent:u,dryRun:s,details:l}}function Hg(n,e,s){let t=n.symbols?.length?` (symbols: ${n.symbols.join(", ")})`:"",i=n.reason?` Reason: ${n.reason}.`:"";switch(n.verdict){case "accepted":return `Contribution accepted by user${t}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;case "dismissed":return `Contribution dismissed by user${t}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;case "revised":return `Contribution revised by user${t}.${i}`+(n.revisionDelta?` Delta: "${n.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;default:return `Unknown verdict "${n.verdict}"${t}.${i}`}}var Yt=["purpose-coverage","purpose-exists","portal-gates","aspect-anchors","purpose-freshness","aspect-advisory","lore-required","habits-blocking","purpose-required-patterns","drift-detection","portal-compliance","graduation-tracking","orchestration-required"],Fl={strict:{"purpose-coverage":"block","purpose-exists":"block","portal-gates":"block","aspect-anchors":"block","purpose-freshness":"warn","aspect-advisory":"warn","lore-required":"block","habits-blocking":"block","purpose-required-patterns":"block","drift-detection":"block","portal-compliance":"block","graduation-tracking":"warn","orchestration-required":"block"},balanced:{"purpose-coverage":"block","purpose-exists":"warn","portal-gates":"warn","aspect-anchors":"warn","purpose-freshness":"warn","aspect-advisory":"off","lore-required":"warn","habits-blocking":"block","purpose-required-patterns":"warn","drift-detection":"warn","portal-compliance":"warn","graduation-tracking":"off","orchestration-required":"warn"},minimal:{"purpose-coverage":"warn","purpose-exists":"off","portal-gates":"off","aspect-anchors":"off","purpose-freshness":"off","aspect-advisory":"off","lore-required":"off","habits-blocking":"warn","purpose-required-patterns":"off","drift-detection":"off","portal-compliance":"off","graduation-tracking":"off","orchestration-required":"off"}};function Vn(n){let e=F.join(n,".paradigm","config.yaml");if(!O.existsSync(e))return {};try{return Z.load(O.readFileSync(e,"utf8"))||{}}catch{return {}}}function mi(n,e){let s=F.join(n,".paradigm","config.yaml");O.writeFileSync(s,Z.dump(e,{lineWidth:120,noRefs:true}),"utf8");}function Yn(n){let e=n.enforcement?.level||"minimal",s=Fl[e]||Fl.minimal,t=n.enforcement?.checks||{},i=n.enforcement?.orchestration?.threshold??3,r={...s};for(let[o,a]of Object.entries(t))Yt.includes(o)&&Nl(a)&&(r[o]=a);return r.orchestrationThreshold=i,r}function Nl(n){return n==="block"||n==="warn"||n==="off"}function qg(n){return n==="strict"||n==="balanced"||n==="minimal"}function Mg(n){return Yt.includes(n)}var Lg=[{name:"paradigm_enforcement_configure",description:"View or modify stop hook enforcement levels. Actions: status (view current), set-level (change preset), override (set per-check severity), reset (clear overrides). ~250 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["status","set-level","override","reset"],description:"Action to perform."},level:{type:"string",enum:["strict","balanced","minimal"],description:"Enforcement preset level (for set-level action)."},checkId:{type:"string",description:"Check ID to override (for override action). One of: "+Yt.join(", ")},severity:{type:"string",enum:["block","warn","off"],description:"Severity to set for the check (for override action)."}},required:["action"]}}];async function Wg(n,e){let{action:s,level:t,checkId:i,severity:r}=e;switch(s){case "status":{let o=Vn(n.rootDir),a=Yn(o),c=o.enforcement?.level||"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:[...Yt],presetLevels:["strict","balanced","minimal"]},null,2)}case "set-level":{if(!t||!qg(t))return JSON.stringify({error:`Invalid level "${t}". Must be one of: strict, balanced, minimal`});let o=Vn(n.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.level=t,o.enforcement.checks={},mi(n.rootDir,o);let a=Yn(o);return JSON.stringify({success:true,level:t,message:`Enforcement level set to "${t}". Per-check overrides cleared.`,effective:a},null,2)}case "override":{if(!i||!Mg(i))return JSON.stringify({error:`Invalid checkId "${i}". Must be one of: ${Yt.join(", ")}`});if(!r||!Nl(r))return JSON.stringify({error:`Invalid severity "${r}". Must be one of: block, warn, off`});let o=Vn(n.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.checks||(o.enforcement.checks={}),o.enforcement.checks[i]=r,mi(n.rootDir,o);let a=Yn(o);return JSON.stringify({success:true,checkId:i,severity:r,message:`Override set: ${i} = ${r}`,effective:a},null,2)}case "reset":{let o=Vn(n.rootDir);o.enforcement&&(o.enforcement.checks={}),mi(n.rootDir,o);let a=Yn(o),c=o.enforcement?.level||"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 El(){return Lg}async function Hl(n,e,s){if(n==="paradigm_enforcement_configure"){let t=await Wg(s,e);return o(t.length,"paradigm_enforcement_configure"),{handled:true,text:t}}return {handled:false,text:""}}function Jg(n,e){let s=[];for(let t=0;t<=e.length;t++)s[t]=[t];for(let t=0;t<=n.length;t++)s[0][t]=t;for(let t=1;t<=e.length;t++)for(let i=1;i<=n.length;i++)e.charAt(t-1)===n.charAt(i-1)?s[t][i]=s[t-1][i-1]:s[t][i]=Math.min(s[t-1][i-1]+1,s[t][i-1]+1,s[t-1][i]+1);return s[e.length][n.length]}function ql(n,e,s={}){let{maxDistance:t=3,maxResults:i=5}=s,r=n.toLowerCase(),o=[];for(let a of e){let c=a.toLowerCase();if(c===r){o.push({match:a,distance:0});continue}if(c.includes(r)||r.includes(c)){o.push({match:a,distance:1});continue}let l=Jg(r,c);l<=t&&o.push({match:a,distance:l});}return o.sort((a,c)=>a.distance!==c.distance?a.distance-c.distance:a.match.localeCompare(c.match)),o.slice(0,i)}v();function zg(n,e){let s$1=new u(n),t=e||(async()=>{}),i=o=>async(a,c,l)=>o(a,c,l),r$1=o=>async(a,c,l)=>o(a,c,l,t);return s$1.registerAll([{key:"context",tier:"core",getToolsList:r,handleTool:i(s)},{key:"navigate",tier:"core",getToolsList:Xo,handleTool:i(Zo)},{key:"tags",tier:"core",getToolsList:_a,handleTool:i(ka)},{key:"purpose-portal",tier:"core",getToolsList:Ta,handleTool:r$1(Da)},{key:"pm",tier:"core",getToolsList:Ba,handleTool:i(Va)},{key:"reindex",tier:"core",getToolsList:ma$1,handleTool:r$1(na$1)},{key:"docs",tier:"core",getToolsList:Pl,handleTool:i(Rl)},{key:"ripple",tier:"core",getToolsList:Tl,handleTool:i(Dl)}]),s$1.registerAll([{key:"wisdom",tier:"feature",getToolsList:Go,handleTool:i(Uo)},{key:"history",tier:"feature",getToolsList:zo,handleTool:i(Bo)},{key:"lore",tier:"feature",getToolsList:Xa,handleTool:i(Za)},{key:"streams",tier:"feature",getToolsList:Al,handleTool:i(Ol)},{key:"ambient",tier:"feature",getToolsList:Il,handleTool:i($l)},{key:"sentinel",tier:"feature",getToolsList:ea,handleTool:i(ta)},{key:"flows",tier:"feature",getToolsList:sa,handleTool:i(ia)},{key:"fixtures",tier:"feature",getToolsList:la,handleTool:i(da)},{key:"orchestration",tier:"feature",getToolsList:fa,handleTool:i(ya)},{key:"habits",tier:"feature",getToolsList:tc,handleTool:i(nc)},{key:"tasks",tier:"feature",getToolsList:mc,handleTool:i(fc)},{key:"personas",tier:"feature",getToolsList:Fc,handleTool:i(Nc)},{key:"protocols",tier:"feature",getToolsList:Ec,handleTool:i(Hc)},{key:"symphony",tier:"feature",getToolsList:il,handleTool:i(rl)},{key:"university",tier:"feature",getToolsList:al,handleTool:i(cl)},{key:"agents",tier:"feature",getToolsList:pl,handleTool:i(ul)},{key:"notebooks",tier:"feature",getToolsList:gl,handleTool:i(ml)},{key:"aspect-graph",tier:"feature",getToolsList:uc,handleTool:i(gc)},{key:"enforcement",tier:"feature",getToolsList:El,handleTool:i(Hl),detect:o=>O.existsSync(F.join(o,".paradigm","config.yaml"))},{key:"graph",tier:"feature",getToolsList:Lc,handleTool:i(Wc),detect:o=>O.existsSync(F.join(o,".paradigm","aspect-graph.db"))},{key:"heatmap",tier:"feature",getToolsList:Gc,handleTool:i(Uc),detect:o=>O.existsSync(F.join(o,".paradigm","aspect-graph.db"))}]),s$1.registerAll([{key:"conductor",tier:"advanced",getToolsList:tl,handleTool:i(nl)},{key:"platform",tier:"advanced",getToolsList:ll,handleTool:i(dl)},{key:"pipeline",tier:"advanced",getToolsList:Yc,handleTool:i(Kc)},{key:"graduation",tier:"advanced",getToolsList:oc,handleTool:i(ac)},{key:"assessment",tier:"advanced",getToolsList:xc,handleTool:i(Cc)}]),s$1}function Bg(n,e){let s=g=>g.toLowerCase().replace(/\/+$/,""),t=s(n),i=s(e);if(t===i)return 1;let r=g=>!g.includes("/")&&g.includes("."),o=g=>r(g)?g.split("."):g.split("/").filter(Boolean),a=o(t),c=o(i);if(r(t)||r(i)){let g=r(t)?t.split("."):t.split("/").filter(Boolean),m=r(i)?i.split("."):i.split("/").filter(Boolean),y=0;for(let f=0;f<Math.min(g.length,m.length)&&g[f]===m[f];f++)y++;return y>0?Math.min(1,.5+y/Math.max(g.length,m.length)*.5):0}let l=0,d=Math.max(a.length,c.length);for(let g=0;g<d;g++){let m=a[g]||"",y=c[g]||"";m===y?l++:m.startsWith(":")&&y.startsWith(":")?l+=.9:m.startsWith(":")||y.startsWith(":")?l+=.7:(m.replace(/s$/,"")===y.replace(/s$/,"")||y.replace(/s$/,"")===m.replace(/s$/,""))&&(l+=.8);}let p=l/d,u=a.length===c.length?.1:0;return Math.min(1,p+u)}function Vg(){return [{name:"paradigm_search",description:"Search for Paradigm symbols by name, description, or tags. Includes fuzzy matching for typo tolerance. Returns matching symbols with names, paths, types, and descriptions. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query (matches symbol names, descriptions, tags)"},type:{type:"string",enum:["component","flow","gate","signal","aspect"],description:"Optional: filter by symbol type (v2: #component, $flow, ^gate, !signal, ~aspect)"},limit:{type:"number",description:"Maximum results to return (default: 10)"},fuzzy:{type:"boolean",description:"Enable fuzzy matching for typos (default: true)"},includeWorkspace:{type:"boolean",description:"Also search sibling workspace projects (default: false). Requires workspace configured in config.yaml."},componentType:{type:"string",description:'Filter components by type (e.g., "view", "service", "tool"). Only applies to #component symbols.'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_related",description:"Get all symbols related to a given symbol. Call before modifying code to understand what uses this symbol and what it depends on. Returns uses/used-by lists with symbol types. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to find relations for"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_status",description:"Get project overview - call this at session start for orientation. Shows symbol counts, project health, and available features. Returns symbol counts by type, project health score, and feature flags. ~100 tokens.",inputSchema:{type:"object",properties:{response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_gates_for_route",description:"Suggest which gates should be applied to a route based on patterns in the project. Returns suggested gates with confidence scores and existing patterns. ~150 tokens.",inputSchema:{type:"object",properties:{route:{type:"string",description:"Route path (e.g., /api/users, /admin/settings)"},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["route"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_plugin_check",description:"Check for updates to installed Claude Code plugins. Reports which marketplace clones have newer remote commits and which cached versions are stale.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_workspace_reindex",description:"Rebuild scan-index.json for all workspace members. Requires workspace configured in config.yaml. Returns per-member symbol counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_tool_activate",description:"Activate an advanced-tier tool module for this session. Advanced tools are not loaded by default to reduce tool count. Call with a feature key to make its tools available. ~50 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:'Feature key to activate (e.g., "graph", "heatmap", "pipeline", "conductor", "platform")'}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}function Ll(n$2,e,s){let t=e(),i$1=zg(t.rootDir,s);n$2.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[...Vg(),...i$1.getActiveTools()]})),n$2.setRequestHandler(CallToolRequestSchema,async r=>{let{name:o$1,arguments:a$1}=r.params;q(o$1,a$1??{});let c=e(),l$1=j$1();l$1.setRootDir(c.rootDir);let d=null,p=null;l$1.hasRecoveredThisSession()||(d=await t$1(c.rootDir),p=a(),b$2(),l$1.markRecovered());let u=await(async()=>{switch(o$1){case "paradigm_search":{let{query:g,type:m,limit:y=10,fuzzy:f=true,includeWorkspace:b=false,componentType:h,response_format:w}=a$1,_=`search:${g}:${m||""}:${y}:${f}:${b}:${h||""}`,k=await v$1.getOrCompute(_,()=>{let C=j$2(c.index,g);return m&&(C=C.filter(T=>T.type===m)),h&&(C=C.filter(T=>T.componentType===h)),C}),v=[];if(k.length===0&&f){let C=n(c.index),T=C.map(j=>j.symbol);v=ql(g,T,{maxDistance:3,maxResults:5}),v.length>0&&(k=v.map(j=>C.find(P=>P.symbol===j.match)).filter(j=>j!=null),m&&(k=k.filter(j=>j.type===m)));}k=k.slice(0,y);let S={query:g,count:k.length,results:k.map(C=>({symbol:C.symbol,type:C.type,description:C.description,filePath:C.filePath,...C.componentType?{componentType:C.componentType}:{},...C.parentSymbol?{parentSymbol:C.parentSymbol}:{}}))};if(v.length>0&&(S.fuzzyMatched=true,S.fuzzyNote=`No exact matches for "${g}". Showing similar symbols.`,S.suggestions=v.map(C=>({symbol:C.match,distance:C.distance}))),b&&c.workspace){let C=Tt(c.workspace,g),T=m?C.filter(j=>j.type===m):C;T.length>0&&(S.workspaceResults=T.slice(0,y).map(j=>({symbol:j.symbol,type:j.type,description:j.description,filePath:j.filePath,project:j.project})),S.workspaceCount=T.length);}w==="concise"&&(S.results=k.map(C=>({symbol:C.symbol,type:C.type})),delete S.fuzzyMatched,delete S.fuzzyNote,delete S.suggestions,delete S.workspaceResults,delete S.workspaceCount);let x=JSON.stringify(S,null,2);return o(x.length,o$1),{content:[{type:"text",text:x}]}}case "paradigm_related":{let{symbol:g}=a$1,m=h$1(c.index,g);if(!m){let h=Bn(c.rootDir,g,{maxResults:20});if(h.length===0){let S=JSON.stringify({error:"Symbol not found",symbol:g,fallback:"searched",referencesFound:0,recovery:["Run `paradigm_search` with a partial name to find similar symbols","Check `.purpose` files for symbol definitions","Use `paradigm_status` to see available symbols by type","The symbol may not be indexed yet - run `paradigm scan`"]},null,2);return o(S.length,o$1),{content:[{type:"text",text:S}]}}let w=[...new Set(h.map(S=>S.filePath))],_=h.filter(S=>S.context==="purpose"),k=h.filter(S=>S.context==="code"),v=JSON.stringify({symbol:g,status:"not-indexed",fallback:"grep-search",note:"Approximate relationships from grep \u2014 run `paradigm scan` for accurate graph data.",usedBy:w.slice(0,10).map(S=>({file:S,references:h.filter(x=>x.filePath===S).length})),uses:[],summary:{totalFiles:w.length,totalReferences:h.length,purposeFileRefs:_.length,codeRefs:k.length},suggestion:"Run `paradigm scan` to enable full relationship tracking"},null,2);return o(v.length,o$1),{content:[{type:"text",text:v}]}}let y=k(c.index,g),f=l(c.index,g),b=JSON.stringify({symbol:m.symbol,type:m.type,description:m.description,usedBy:y.map(h=>({symbol:h.symbol,type:h.type,description:h.description})),uses:f.map(h=>({symbol:h.symbol,type:h.type,description:h.description}))},null,2);return o(b.length,o$1),{content:[{type:"text",text:b}]}}case "paradigm_status":{let g=a$1.response_format,m$1=await v$1.getOrCompute("status",async()=>{let f=m(c.index),b=Object.values(f).reduce((j,P)=>j+P,0),h={};for(let j of Object.keys(f)){let P=i(c.index,j);h[j]=P.slice(0,3).map(D=>D.symbol);}let w=ga.platform(),_=w==="win32",k=_?"PowerShell/CMD":w==="darwin"?"zsh/bash":"bash",v;try{let j=await U(c.rootDir);j&&j.health.total>0&&(v=j.health);}catch{}let S=i(c.index,"component"),x={};for(let j of S)j.componentType&&(x[j.componentType]=(x[j.componentType]||0)+1);let C=S.filter(j=>!j.componentType).length,T;try{let{checkPurposeHealth:j}=await import('./integrity-checker-DHGMZQDG.js');T=j(c.aggregation.purposeFiles,c.rootDir).healthScore;}catch{}return JSON.stringify({project:c.projectName,symbolSystem:"v2",counts:{"# components":f.component,"$ flows":f.flow,"^ gates":f.gate,"! signals":f.signal,"~ aspects":f.aspect},total:b,...Object.keys(x).length>0?{componentTypes:{...x,...C>0?{"(untyped)":C}:{}}}:{},examples:h,hasPortalYaml:c.gateConfig!==null,purposeFiles:c.aggregation.purposeFiles.length,...T!==void 0?{purposeHealthScore:T}:{},...v?{protocols:v}:{},note:"Symbol System v2: Use tags [feature], [state], [integration], [idea] for classification. Use type field for structural role (view, service, tool, etc.)",environment:{os:w,shell:k,terminalNote:_?"Use PowerShell syntax: semicolons for command chaining, backslashes for paths, $env:VAR for env vars":"Use Unix syntax: && for command chaining, forward slashes for paths, $VAR for env vars"}},null,2)}),y=m$1;if(g==="concise")try{let f=JSON.parse(m$1);y=JSON.stringify({project:f.project,counts:f.counts,total:f.total},null,2);}catch{}return o(y.length,o$1),{content:[{type:"text",text:y}]}}case "paradigm_gates_for_route":{let{route:g,response_format:m}=a$1,f=typeof g=="string"&&!g.includes("/")&&g.includes(".")?"POST":a$1.method||"GET",b=i(c.index,"gate"),h=[],w=[];if(c.gateConfig?.routes)for(let[P,D]of Object.entries(c.gateConfig.routes))D.gates&&w.push({route:P,gates:D.gates,method:D.method});if(c.workspace)for(let[P,D]of c.workspace.siblingIndices){let I=D.gateConfig;if(I?.routes)for(let[A,N]of Object.entries(I.routes)){let H=N,q=Array.isArray(H)?H:H?.gates;q&&w.push({route:A,gates:q,method:Array.isArray(H)?void 0:H?.method,source:P});}}for(let P of w){let D=Bg(g,P.route);if(D>=.6&&(!P.method||P.method===f))for(let I of P.gates){let A=b.find(N=>N.symbol===I||N.symbol===`^${I}`);if(A&&!h.find(N=>N.gate===A.symbol)){let N=P.source?`${P.source}/portal.yaml`:"portal.yaml";h.push({gate:A.symbol,reason:`Similar route "${P.route}" uses this gate`,confidence:D>=.8?"high":"medium",source:N});}}}let v=g.split("/").filter(Boolean).find(P=>!P.startsWith(":")&&P!=="api")?.replace(/s$/,"")||"",S=g.match(/\/:(id|[a-z]+Id)($|\/)/i);if(S&&v){let P=b.find(D=>{let I=D.symbol.toLowerCase(),A=(D.description||"").toLowerCase();return I.includes(`${v}-owner`)||I.includes("owner")||I.includes("ownership")||A.includes("owner")||A.includes("ownership")||A.includes("belongs to")});P?h.push({gate:P.symbol,reason:`Resource ID route (${v}) typically needs ownership verification`,confidence:"high"}):h.push({gate:`^${v}-owner`,reason:`Consider adding ownership gate for ${v} resource`,confidence:"medium"});}if(g.includes("/admin")||g.includes("/settings")){let P=b.find(D=>D.symbol.includes("admin")||D.description?.toLowerCase().includes("admin"));P&&h.push({gate:P.symbol,reason:"Route appears to be admin-related",confidence:"high"});}if(g.startsWith("/api/")||g.includes("/user")||g.includes("/account")){let P=b.find(D=>D.symbol.includes("authenticated")||D.symbol.includes("auth"));P&&h.push({gate:P.symbol,reason:"API/user routes typically require authentication",confidence:"high"});}if(g.includes("/premium")||g.includes("/pro")||g.includes("/export")){let P=b.find(D=>D.symbol.includes("subscription")||D.symbol.includes("premium"));P&&h.push({gate:P.symbol,reason:"Route appears to be a premium feature",confidence:"medium"});}if(f==="DELETE"){let P=b.find(D=>D.symbol.includes("authenticated"));P&&!h.find(D=>D.gate===P.symbol)&&h.push({gate:P.symbol,reason:"DELETE operations require authentication",confidence:"high"});}if(["POST","PUT","PATCH"].includes(f)){let P=b.find(D=>D.symbol.includes("authenticated"));P&&!h.find(D=>D.gate===P.symbol)&&h.push({gate:P.symbol,reason:"Write operations typically require authentication",confidence:"high"});}let x=new Set,C=h.filter(P=>x.has(P.gate)?false:(x.add(P.gate),true)),T=m==="concise"?{suggestions:C.map(P=>({gate:P.gate,confidence:P.confidence}))}:{route:g,method:f,suggestions:C,availableGates:b.map(P=>({symbol:P.symbol,description:P.description})),note:S?"Resource ID routes should verify the user owns/has access to the specific resource.":"These are suggestions based on route patterns. Review your portal.yaml for exact requirements."},j=JSON.stringify(T,null,2);o(j.length,o$1);try{n$1(c.rootDir,{type:"gate-checked",source:"mcp-tool-call",tool:"paradigm_gates_for_route",symbols:C.map(P=>P.gate),context:`Gate check for ${f} ${g}`});}catch{}return {content:[{type:"text",text:j}]}}case "paradigm_plugin_check":{let{runPluginUpdateCheck:g}=await import('./plugin-update-checker-M7PW434O.js'),m=await g(),y=m.filter(w=>w.hasRemoteUpdate||w.hasCacheStale);if(y.length===0){let w=m.length===0?"No Claude Code plugins found in ~/.claude/plugins/marketplaces/.":"All installed plugins are up to date.";return o(w.length,o$1),{content:[{type:"text",text:w}]}}let f=[`Plugin updates available:
|
|
841
841
|
`],b=[];for(let w of y)w.hasRemoteUpdate?(f.push(` ${w.plugin} (${w.repo}): remote has newer commits`),b.push(`git -C ${w.marketplacePath} pull origin main`)):w.hasCacheStale&&f.push(` ${w.plugin} (${w.repo}): ${w.installedVersion} \u2192 ${w.localVersion} (restart needed)`);b.length>0?(f.push(`
|
|
842
842
|
Update command:
|
|
843
843
|
${b.join(` && \\
|
|
844
844
|
`)}`),f.push(`
|
|
845
845
|
After running, restart the session to apply updates.`)):f.push(`
|
|
846
846
|
Restart the session to apply cached updates.`);let h=f.join(`
|
|
847
|
-
`);return o(h.length,o$1),{content:[{type:"text",text:h}]}}case "paradigm_workspace_reindex":{if(!c.workspace){let f=JSON.stringify({error:"No workspace configured",suggestion:'Add a "workspace" field to .paradigm/config.yaml pointing to your .paradigm-workspace file, then run `paradigm workspace init` to create one.'},null,2);return o(f.length,o$1),{content:[{type:"text",text:f}]}}let{rebuildStaticFiles:g}=await import('./reindex-
|
|
847
|
+
`);return o(h.length,o$1),{content:[{type:"text",text:h}]}}case "paradigm_workspace_reindex":{if(!c.workspace){let f=JSON.stringify({error:"No workspace configured",suggestion:'Add a "workspace" field to .paradigm/config.yaml pointing to your .paradigm-workspace file, then run `paradigm workspace init` to create one.'},null,2);return o(f.length,o$1),{content:[{type:"text",text:f}]}}let{rebuildStaticFiles:g}=await import('./reindex-HA3CJG7S.js'),m=[];for(let f of c.workspace.config.members){let b=F.resolve(F.dirname(c.workspace.workspacePath),f.path);try{let h=await g(b);m.push({name:f.name,symbolCount:h.symbolCount,status:"ok"});}catch(h){m.push({name:f.name,symbolCount:0,status:`error: ${h.message}`});}}let y=JSON.stringify({action:"workspace_reindex",workspace:c.workspace.config.name,members:m,totalSymbols:m.reduce((f,b)=>f+b.symbolCount,0)},null,2);return o(y.length,o$1),v$1.clear(),{content:[{type:"text",text:y}]}}case "paradigm_tool_activate":{let g=a$1.feature,m=i$1.activateAdvanced(g);if(m){let h=JSON.stringify({action:"tool_activate",feature:g,status:"activated",toolsAdded:m.map(w=>w.name),note:`Advanced module "${g}" activated for this session. ${m.length} tool(s) now available.`},null,2);return o(h.length,o$1),{content:[{type:"text",text:h}]}}let y=i$1.getRegistryInfo(),f=y.activeFeatures.includes(g),b=JSON.stringify({action:"tool_activate",feature:g,status:f?"already_active":"not_found",note:f?`Module "${g}" is already active (auto-detected or core tier).`:`Module "${g}" not found. Available advanced modules: ${y.availableAdvanced.join(", ")||"(none)"}`,availableAdvanced:y.availableAdvanced},null,2);return o(b.length,o$1),{content:[{type:"text",text:b}]}}default:{let g=await i$1.dispatch(o$1,a$1,c);if(g&&g.handled)return o$1.startsWith("paradigm_context_")||o$1.startsWith("paradigm_session_")||o$1==="paradigm_handoff_prepare"||o(g.text.length,o$1),Yg(o$1,a$1,c.rootDir),{content:[{type:"text",text:g.text}]};throw new Error(`Unknown tool: ${o$1}`)}}})();if(d||p){let g=u.content?.[0];if(g&&typeof g=="object"&&"text"in g&&typeof g.text=="string"){let m=[p,d].filter(Boolean).join(`
|
|
848
848
|
|
|
849
849
|
`);g.text=m+`
|
|
850
850
|
|