@a-company/paradigm 7.0.0 → 7.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{accept-orchestration-YO2V2WYA.js → accept-orchestration-WMGFGYDK.js} +1 -1
- package/dist/{agent-loader-VGBPL3TH.js → agent-loader-Z753DQWH.js} +1 -1
- package/dist/{ambient-OX7YJ4PJ.js → ambient-HAXPDIWK.js} +1 -1
- package/dist/ambient-OW5M5LVN.js +2 -0
- package/dist/ambient-QB7V4TBR.js +6 -0
- package/dist/calibrate-PHVP7RPH.js +4 -0
- package/dist/{captain-YUP3KVCA.js → captain-3COP6YTD.js} +1 -1
- package/dist/chunk-4CGPLLWQ.js +30 -0
- package/dist/{chunk-3MZ4J2LF.js → chunk-CHSU6LTR.js} +1 -1
- package/dist/chunk-ECO3LHCE.js +2 -0
- package/dist/chunk-EG22HDXI.js +33 -0
- package/dist/{chunk-GD4F2HC6.js → chunk-H55W26AR.js} +1 -1
- package/dist/{chunk-ROU3F2HZ.js → chunk-HSY75GRR.js} +3 -3
- package/dist/chunk-KAUGQMXU.js +4 -0
- package/dist/{chunk-QBIQ2FYB.js → chunk-KP5VOYAH.js} +1 -1
- package/dist/{chunk-K54L6CFR.js → chunk-OIYJUU6T.js} +4 -4
- package/dist/{chunk-47YPID6H.js → chunk-RDWWSQGH.js} +21 -21
- package/dist/chunk-RVXQNS6K.js +30 -0
- package/dist/{chunk-WROJSWAO.js → chunk-VPNJL4LS.js} +1 -1
- package/dist/{chunk-JCGCPAHF.js → chunk-W4BW7GXA.js} +1 -1
- package/dist/chunk-XPPFILCM.js +2 -0
- package/dist/{chunk-V6MIKLMY.js → chunk-YCDOA5IQ.js} +1 -1
- package/dist/chunk-YQK3XU63.js +504 -0
- package/dist/{compliance-MLG4W6S4.js → compliance-4P3EE5OA.js} +1 -1
- package/dist/{diff-MC6AXLKX.js → diff-VBVIUNL5.js} +1 -1
- package/dist/{docs-3YFNNZRV.js → docs-NTP6UENF.js} +1 -1
- package/dist/index.js +5 -5
- package/dist/journal-loader-CNNA4EAU.js +2 -0
- package/dist/lore-loader-HAZ5FRLP.js +2 -0
- package/dist/mcp.js +1 -1
- package/dist/nomination-engine-ORHH4L2W.js +2 -0
- package/dist/{nomination-engine-AQHU2KBU.js → nomination-engine-YRHZZZUN.js} +1 -1
- package/dist/notebook-loader-TZVIMNDJ.js +2 -0
- package/dist/{orchestrate-GMYEBA5T.js → orchestrate-MLUGQOEJ.js} +1 -1
- package/dist/orchestration-O2OVPTIZ.js +2 -0
- package/dist/{platform-server-WIBVYHIV.js → platform-server-Y6TLEXR2.js} +1 -1
- package/dist/{reindex-XTRF23F7.js → reindex-ZLDQBFUR.js} +1 -1
- package/dist/{serve-SMGWGJLM.js → serve-XZ6GBUS3.js} +1 -1
- package/dist/{session-work-log-QXPAXY5K.js → session-work-log-FF7CKMWP.js} +1 -1
- package/dist/{shift-JBCEDCGA.js → shift-PM4GI736.js} +1 -1
- package/dist/{symphony-G6IENE4K.js → symphony-CFAYJGLF.js} +1 -1
- package/dist/{symphony-7INZR43F.js → symphony-L56O5ZG3.js} +3 -3
- package/dist/{symphony-relay-2RHG25Z4.js → symphony-relay-Y2UR3YNR.js} +1 -1
- package/dist/{task-loader-IGQQ6ZFL.js → task-loader-H7HQAYGL.js} +1 -1
- package/dist/task-loader-YZME4RKE.js +2 -0
- package/dist/{task-settlement-NW4XMJGJ.js → task-settlement-HINBVZBE.js} +2 -2
- package/dist/task-settlement-XC6E6JNT.js +3 -0
- package/dist/{team-J2YXPEGX.js → team-25LK6CWM.js} +1 -1
- package/dist/tools-GAU5WOEI.js +2 -0
- package/dist/university-ui/assets/{index-B8hm_MdR.js → index-AbTjHBCf.js} +2 -2
- package/dist/university-ui/assets/{index-B8hm_MdR.js.map → index-AbTjHBCf.js.map} +1 -1
- package/dist/university-ui/index.html +1 -1
- package/dist/work-log-loader-CRVTOMVB.js +2 -0
- package/package.json +1 -1
- package/dist/ambient-7HBJHJL2.js +0 -2
- package/dist/ambient-SST5CLEC.js +0 -35
- package/dist/chunk-6AKNXD22.js +0 -32
- package/dist/chunk-FRQRREJ6.js +0 -29
- package/dist/chunk-QEQCPVF5.js +0 -4
- package/dist/chunk-QGZRM6ZB.js +0 -2
- package/dist/chunk-S4J337EQ.js +0 -504
- package/dist/journal-loader-GLH7XFTK.js +0 -2
- package/dist/lore-loader-D2ISOASW.js +0 -2
- package/dist/notebook-loader-6DYFMNJ2.js +0 -2
- package/dist/orchestration-G5MAY6IA.js +0 -2
- package/dist/tools-HNJ7D5IO.js +0 -2
- /package/dist/{chunk-CVPKQ3JH.js → chunk-HE2NA5QF.js} +0 -0
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a,O,l as l$1,D as D$1,G as G$1,L,F,K,J,I as I$1,N}from'./chunk-QBIQ2FYB.js';import {a as a$2,d as d$1}from'./chunk-Q527BPUF.js';import {b as b$2}from'./chunk-RGSFU2YW.js';import {m,q,k,n,o,l,i,j as j$1,g}from'./chunk-TMDPDIWA.js';import {f}from'./chunk-KLBH26PA.js';import {j,a as a$3,i as i$1,b as b$1,h as h$1,g as g$2,c,d as d$2}from'./chunk-GRZQIKST.js';import {d,g as g$1,e,h,j as j$2,f as f$1}from'./chunk-ACJWUOMA.js';import {b,a as a$1}from'./chunk-EK4ZRIFJ.js';import*as D from'fs';import*as I from'path';import*as G from'js-yaml';import {execSync}from'child_process';import*as Ot from'os';b();b();var Tt=".paradigm/navigator.yaml";async function nt(n){let e=I.join(n,Tt);if(!D.existsSync(e))return {config:null,configPath:null};try{let o=D.readFileSync(e,"utf8");return {config:G.load(o),configPath:e}}catch(o){return a$1.component("#navigator-loader").error("Error parsing navigator.yaml",{error:o}),{config:null,configPath:e}}}function ot(n,e,o){switch(e.intent){case "find":return Wt(n,e.target||"");case "explore":return Lt(n,e.target||"");case "context":return Ht(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Wt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let r=n.symbols[e];if(r)t.paths.push(r),t.symbols.push(e),t.explanation=`Found symbol ${e} at ${r}`;else {let s=Object.entries(n.symbols).filter(([i])=>i.includes(e.slice(1))).slice(0,5);s.length>0?(t.paths=s.map(([,i])=>i),t.symbols=s.map(([i])=>i),t.explanation=`Found ${s.length} symbols matching "${e}"`):t.explanation=`Symbol ${e} not found in navigator`;}}else {let r=Object.entries(n.symbols).filter(([s])=>s.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(r.length>0)t.paths=r.map(([,s])=>s),t.symbols=r.map(([s])=>s),t.explanation=`Found ${r.length} symbols matching "${e}"`;else {let s=Bt(n,e);s?(t.paths=s.paths,t.explanation=`Found ${e} in structure: ${s.paths.join(", ")}`):t.explanation=`No matches found for "${e}"`;}}return t.suggested_order=we(t.paths,n),t}function Lt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase();for(let[s,i]of Object.entries(n.structure))if(i&&(s.toLowerCase().includes(r)||r.includes(s.toLowerCase()))){t.paths.push(...i.paths);let a=Object.entries(n.symbols).filter(([c])=>c.startsWith(i.symbol)).slice(0,10);t.symbols.push(...a.map(([c])=>c));}for(let[s,i]of Object.entries(n.key_files))s.toLowerCase().includes(r)&&t.paths.push(...i);if(t.paths.length===0){let s=Object.entries(n.symbols).filter(([i,a])=>i.toLowerCase().includes(r)||a.toLowerCase().includes(r)).slice(0,10);t.paths=[...new Set(s.map(([,i])=>i))],t.symbols=s.map(([i])=>i);}return t.explanation=`Exploration paths for "${e}": ${t.paths.length} locations, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Ht(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase(),s=Mt(r);for(let[i,a]of Object.entries(n.structure))a&&s.some(c=>i.toLowerCase().includes(c))&&t.paths.push(...a.paths);for(let[i,a]of Object.entries(n.symbols)){let c=i.slice(1).toLowerCase();s.some(l=>c.includes(l)||l.includes(c))&&(t.paths.push(a),t.symbols.push(i));}return t.paths.push(...n.key_files.config),t.paths=[...new Set(t.paths)],t.symbols=[...new Set(t.symbols)],r.includes("test")?t.skip=n.skip_patterns.always:t.skip=[...n.skip_patterns.always,...n.skip_patterns.unless_testing],!r.includes("doc")&&!r.includes("readme")&&t.skip.push(...n.skip_patterns.unless_docs),t.explanation=`Context for "${e}": ${t.paths.length} relevant files, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Bt(n,e){let o=e.toLowerCase();for(let[t,r]of Object.entries(n.structure))if(r&&(t.toLowerCase().includes(o)||o.includes(t.toLowerCase())))return r;return null}function Mt(n){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return n.split(/\s+/).map(o=>o.replace(/[^a-z0-9]/g,"")).filter(o=>o.length>2&&!e.has(o))}function we(n,e){let o={};for(let t of n){let r=0;e.key_files.config.some(s=>t.includes(s))&&(r+=100),e.key_files.entry.some(s=>t.includes(s))&&(r+=80),e.key_files.types.some(s=>t.includes(s))&&(r+=60),r-=t.split("/").length*2,o[t]=r;}return [...n].sort((t,r)=>(o[r]||0)-(o[t]||0))}b();function Jt(n){let e=I.resolve(n),o=D.readFileSync(e,"utf8"),t=G.load(o);if(!t||typeof t!="object")throw new Error(`Invalid workspace file: ${n}`);let r={version:String(t.version||"1.0"),name:String(t.name||"unnamed-workspace"),members:[]};if(Array.isArray(t.members)){for(let s of t.members)if(typeof s=="object"&&s!==null){let i=s;r.members.push({name:String(i.name||""),path:String(i.path||""),role:i.role,exports:Array.isArray(i.exports)?i.exports.map(String):void 0});}}return r}function rt(n,e){let o=I.resolve(n),t=I.resolve(o,e);if(!D.existsSync(t))return a$1.component("#workspace-loader").warn("Workspace file not found",{workspacePath:t}),null;let r;try{r=Jt(t);}catch(c){return a$1.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let s=I.dirname(t),i="";for(let c of r.members){let l=I.resolve(s,c.path);if(st(l)===st(o)){i=c.name;break}}if(!i)return a$1.component("#workspace-loader").warn("Current directory is not a member of workspace",{workspace:r.name}),null;let a=new Map;for(let c of r.members){if(c.name===i)continue;let l=I.resolve(s,c.path),d=I.join(l,".paradigm","scan-index.json");if(!D.existsSync(d)){a$1.component("#workspace-loader").warn("No scan-index.json for workspace member",{member:c.name,scanIndexPath:d});continue}try{let p=JSON.parse(D.readFileSync(d,"utf8")),m=Ut(p);c.exports&&c.exports.length>0&&(m=Gt(m,c.exports));let h=null,x=I.join(l,"portal.yaml");if(D.existsSync(x))try{let f=D.readFileSync(x,"utf8"),P=G.load(f);P&&(h=P);}catch{}a.set(c.name,{index:m,gateConfig:h});}catch(p){a$1.component("#workspace-loader").warn("Could not load index for workspace member",{member:c.name,error:p.message});}}return {config:r,workspacePath:t,currentMember:i,siblingIndices:a}}function Gt(n,e){let t=q(n).filter(r=>{let s=r.symbol;return e.some(i=>qt(i,s))});return zt(t)}function qt(n,e){let o=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${o}$`,"i").test(e)}function xe(n,e){let o=[];for(let[t,r]of n.siblingIndices){let s=m(r.index,e);for(let i of s)o.push({project:t,symbol:`${t}/${i.symbol}`,type:i.type,description:i.description,filePath:i.filePath});}return o}function it(n,e){let o=[],t=e.includes("/")?e.split("/").pop():e;for(let[r,s]of n.siblingIndices){let i=[],a=q(s.index);for(let c of a){let l=c.references||[],d=c.description||"",p=l.some(h=>h===t||h===e||h.endsWith(`/${t}`)),m=d.includes(t);(p||m)&&i.push({symbol:c.symbol,type:c.type,description:c.description});}i.length>0&&o.push({project:r,references:i});}return o}function st(n){return I.resolve(n).replace(/\/+$/,"")}function Ut(n){let e={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"},o=[];for(let[t,r]of Object.entries(e)){let s=n[t];if(!(!s||typeof s!="object"))for(let[i,a]of Object.entries(s)){let c={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"}[r]||"#";o.push({id:i,symbol:a.symbol||`${c}${i}`,type:r,source:"purpose",filePath:a.path||"",data:{},references:a.related||[],referencedBy:[],description:a.description,tags:a.visualTags||[]});}}return j$1({symbols:o,purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}function zt(n){return j$1({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()})}var Vt={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function Zn(){return [Vt]}async function lt(n,e,o){if(n!=="paradigm_navigate")return {handled:false,text:""};let t={intent:e.intent||"find",target:e.target,task:e.task},r=await nt(o.rootDir);if(r.config||(r={config:Kt(o),configPath:null}),false);if(t.intent==="context"&&!t.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((t.intent==="find"||t.intent==="explore")&&!t.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${t.intent} intent`,example:t.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let s=`navigate:${t.intent}:${t.target||""}:${t.task||""}`,i=await a.getOrCompute(s,()=>{let c=ot(r.config,t,o.rootDir),l={intent:t.intent,...t.target&&{target:t.target},...t.task&&{task:t.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(r.config?.auto_generated&&(l.auto_generated=true,l.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(l.note="No paths found.",l.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(l.tip=l.tip||"Many paths returned. Start with suggested_order for efficient exploration."),o.workspace){if(t.intent==="find"&&t.target&&c.paths.length===0){let d=xe(o.workspace,t.target);d.length>0&&(l.workspaceResults=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(t.intent==="context"&&t.task){let d=xe(o.workspace,t.task);d.length>0&&(l.workspaceContext=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})));}}return JSON.stringify(l,null,2)}),a$1=i;if(e.response_format==="concise")try{let c=JSON.parse(i);delete c.skip,delete c.tip,delete c.note,delete c.recovery,delete c.workspaceResults,delete c.workspaceContext,delete c.auto_generated,a$1=JSON.stringify(c,null,2);}catch{}try{let c=I.join(o.rootDir,".paradigm",".nav-called");D.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a$1}}function Kt(n){let e={},o={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},t=q(n.index),r=new Set;for(let a of t)if(a.filePath){e[a.symbol]=a.filePath,r.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":o.features.paths.includes(c)||o.features.paths.push(c);break;case "component":o.components.paths.includes(c)||o.components.paths.push(c);break;case "gate":o.gates.paths.includes(c)||o.gates.paths.push(c);break;case "flow":o.flows.paths.includes(c)||o.flows.paths.push(c);break}}let s=[],i=[];for(let a of n.aggregation.purposeFiles)s.push(a.filePath);return s.push(".paradigm/config.yaml"),n.gateConfig&&s.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:o,key_files:{config:s.slice(0,10),entry:i,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}function pt(n,e,o={}){let{maxResults:t=20}=o,r=[],s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=[`rg -n --no-heading "${s}" "${n}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${s}" "${n}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of i)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return r;let c=a.trim().split(`
|
|
2
|
+
import {a,O,l as l$1,D as D$1,G as G$1,L,F,K,J,I as I$1,N}from'./chunk-KP5VOYAH.js';import {a as a$2,d as d$1}from'./chunk-Q527BPUF.js';import {b as b$2}from'./chunk-RGSFU2YW.js';import {m,q,k,n,o,l,i,j as j$1,g}from'./chunk-TMDPDIWA.js';import {f}from'./chunk-KLBH26PA.js';import {j,a as a$3,i as i$1,b as b$1,h as h$1,g as g$2,c,d as d$2}from'./chunk-GRZQIKST.js';import {d,g as g$1,e,h,j as j$2,f as f$1}from'./chunk-ACJWUOMA.js';import {b,a as a$1}from'./chunk-EK4ZRIFJ.js';import*as D from'fs';import*as I from'path';import*as G from'js-yaml';import {execSync}from'child_process';import*as Ot from'os';b();b();var Tt=".paradigm/navigator.yaml";async function nt(n){let e=I.join(n,Tt);if(!D.existsSync(e))return {config:null,configPath:null};try{let o=D.readFileSync(e,"utf8");return {config:G.load(o),configPath:e}}catch(o){return a$1.component("#navigator-loader").error("Error parsing navigator.yaml",{error:o}),{config:null,configPath:e}}}function ot(n,e,o){switch(e.intent){case "find":return Wt(n,e.target||"");case "explore":return Lt(n,e.target||"");case "context":return Ht(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Wt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let r=n.symbols[e];if(r)t.paths.push(r),t.symbols.push(e),t.explanation=`Found symbol ${e} at ${r}`;else {let s=Object.entries(n.symbols).filter(([i])=>i.includes(e.slice(1))).slice(0,5);s.length>0?(t.paths=s.map(([,i])=>i),t.symbols=s.map(([i])=>i),t.explanation=`Found ${s.length} symbols matching "${e}"`):t.explanation=`Symbol ${e} not found in navigator`;}}else {let r=Object.entries(n.symbols).filter(([s])=>s.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(r.length>0)t.paths=r.map(([,s])=>s),t.symbols=r.map(([s])=>s),t.explanation=`Found ${r.length} symbols matching "${e}"`;else {let s=Bt(n,e);s?(t.paths=s.paths,t.explanation=`Found ${e} in structure: ${s.paths.join(", ")}`):t.explanation=`No matches found for "${e}"`;}}return t.suggested_order=we(t.paths,n),t}function Lt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase();for(let[s,i]of Object.entries(n.structure))if(i&&(s.toLowerCase().includes(r)||r.includes(s.toLowerCase()))){t.paths.push(...i.paths);let a=Object.entries(n.symbols).filter(([c])=>c.startsWith(i.symbol)).slice(0,10);t.symbols.push(...a.map(([c])=>c));}for(let[s,i]of Object.entries(n.key_files))s.toLowerCase().includes(r)&&t.paths.push(...i);if(t.paths.length===0){let s=Object.entries(n.symbols).filter(([i,a])=>i.toLowerCase().includes(r)||a.toLowerCase().includes(r)).slice(0,10);t.paths=[...new Set(s.map(([,i])=>i))],t.symbols=s.map(([i])=>i);}return t.explanation=`Exploration paths for "${e}": ${t.paths.length} locations, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Ht(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase(),s=Mt(r);for(let[i,a]of Object.entries(n.structure))a&&s.some(c=>i.toLowerCase().includes(c))&&t.paths.push(...a.paths);for(let[i,a]of Object.entries(n.symbols)){let c=i.slice(1).toLowerCase();s.some(l=>c.includes(l)||l.includes(c))&&(t.paths.push(a),t.symbols.push(i));}return t.paths.push(...n.key_files.config),t.paths=[...new Set(t.paths)],t.symbols=[...new Set(t.symbols)],r.includes("test")?t.skip=n.skip_patterns.always:t.skip=[...n.skip_patterns.always,...n.skip_patterns.unless_testing],!r.includes("doc")&&!r.includes("readme")&&t.skip.push(...n.skip_patterns.unless_docs),t.explanation=`Context for "${e}": ${t.paths.length} relevant files, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Bt(n,e){let o=e.toLowerCase();for(let[t,r]of Object.entries(n.structure))if(r&&(t.toLowerCase().includes(o)||o.includes(t.toLowerCase())))return r;return null}function Mt(n){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return n.split(/\s+/).map(o=>o.replace(/[^a-z0-9]/g,"")).filter(o=>o.length>2&&!e.has(o))}function we(n,e){let o={};for(let t of n){let r=0;e.key_files.config.some(s=>t.includes(s))&&(r+=100),e.key_files.entry.some(s=>t.includes(s))&&(r+=80),e.key_files.types.some(s=>t.includes(s))&&(r+=60),r-=t.split("/").length*2,o[t]=r;}return [...n].sort((t,r)=>(o[r]||0)-(o[t]||0))}b();function Jt(n){let e=I.resolve(n),o=D.readFileSync(e,"utf8"),t=G.load(o);if(!t||typeof t!="object")throw new Error(`Invalid workspace file: ${n}`);let r={version:String(t.version||"1.0"),name:String(t.name||"unnamed-workspace"),members:[]};if(Array.isArray(t.members)){for(let s of t.members)if(typeof s=="object"&&s!==null){let i=s;r.members.push({name:String(i.name||""),path:String(i.path||""),role:i.role,exports:Array.isArray(i.exports)?i.exports.map(String):void 0});}}return r}function rt(n,e){let o=I.resolve(n),t=I.resolve(o,e);if(!D.existsSync(t))return a$1.component("#workspace-loader").warn("Workspace file not found",{workspacePath:t}),null;let r;try{r=Jt(t);}catch(c){return a$1.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let s=I.dirname(t),i="";for(let c of r.members){let l=I.resolve(s,c.path);if(st(l)===st(o)){i=c.name;break}}if(!i)return a$1.component("#workspace-loader").warn("Current directory is not a member of workspace",{workspace:r.name}),null;let a=new Map;for(let c of r.members){if(c.name===i)continue;let l=I.resolve(s,c.path),d=I.join(l,".paradigm","scan-index.json");if(!D.existsSync(d)){a$1.component("#workspace-loader").warn("No scan-index.json for workspace member",{member:c.name,scanIndexPath:d});continue}try{let p=JSON.parse(D.readFileSync(d,"utf8")),m=Ut(p);c.exports&&c.exports.length>0&&(m=Gt(m,c.exports));let h=null,x=I.join(l,"portal.yaml");if(D.existsSync(x))try{let f=D.readFileSync(x,"utf8"),P=G.load(f);P&&(h=P);}catch{}a.set(c.name,{index:m,gateConfig:h});}catch(p){a$1.component("#workspace-loader").warn("Could not load index for workspace member",{member:c.name,error:p.message});}}return {config:r,workspacePath:t,currentMember:i,siblingIndices:a}}function Gt(n,e){let t=q(n).filter(r=>{let s=r.symbol;return e.some(i=>qt(i,s))});return zt(t)}function qt(n,e){let o=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${o}$`,"i").test(e)}function xe(n,e){let o=[];for(let[t,r]of n.siblingIndices){let s=m(r.index,e);for(let i of s)o.push({project:t,symbol:`${t}/${i.symbol}`,type:i.type,description:i.description,filePath:i.filePath});}return o}function it(n,e){let o=[],t=e.includes("/")?e.split("/").pop():e;for(let[r,s]of n.siblingIndices){let i=[],a=q(s.index);for(let c of a){let l=c.references||[],d=c.description||"",p=l.some(h=>h===t||h===e||h.endsWith(`/${t}`)),m=d.includes(t);(p||m)&&i.push({symbol:c.symbol,type:c.type,description:c.description});}i.length>0&&o.push({project:r,references:i});}return o}function st(n){return I.resolve(n).replace(/\/+$/,"")}function Ut(n){let e={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"},o=[];for(let[t,r]of Object.entries(e)){let s=n[t];if(!(!s||typeof s!="object"))for(let[i,a]of Object.entries(s)){let c={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"}[r]||"#";o.push({id:i,symbol:a.symbol||`${c}${i}`,type:r,source:"purpose",filePath:a.path||"",data:{},references:a.related||[],referencedBy:[],description:a.description,tags:a.visualTags||[]});}}return j$1({symbols:o,purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}function zt(n){return j$1({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()})}var Vt={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function Zn(){return [Vt]}async function lt(n,e,o){if(n!=="paradigm_navigate")return {handled:false,text:""};let t={intent:e.intent||"find",target:e.target,task:e.task},r=await nt(o.rootDir);if(r.config||(r={config:Kt(o),configPath:null}),false);if(t.intent==="context"&&!t.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((t.intent==="find"||t.intent==="explore")&&!t.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${t.intent} intent`,example:t.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let s=`navigate:${t.intent}:${t.target||""}:${t.task||""}`,i=await a.getOrCompute(s,()=>{let c=ot(r.config,t,o.rootDir),l={intent:t.intent,...t.target&&{target:t.target},...t.task&&{task:t.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(r.config?.auto_generated&&(l.auto_generated=true,l.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(l.note="No paths found.",l.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(l.tip=l.tip||"Many paths returned. Start with suggested_order for efficient exploration."),o.workspace){if(t.intent==="find"&&t.target&&c.paths.length===0){let d=xe(o.workspace,t.target);d.length>0&&(l.workspaceResults=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(t.intent==="context"&&t.task){let d=xe(o.workspace,t.task);d.length>0&&(l.workspaceContext=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})));}}return JSON.stringify(l,null,2)}),a$1=i;if(e.response_format==="concise")try{let c=JSON.parse(i);delete c.skip,delete c.tip,delete c.note,delete c.recovery,delete c.workspaceResults,delete c.workspaceContext,delete c.auto_generated,a$1=JSON.stringify(c,null,2);}catch{}try{let c=I.join(o.rootDir,".paradigm",".nav-called");D.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a$1}}function Kt(n){let e={},o={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},t=q(n.index),r=new Set;for(let a of t)if(a.filePath){e[a.symbol]=a.filePath,r.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":o.features.paths.includes(c)||o.features.paths.push(c);break;case "component":o.components.paths.includes(c)||o.components.paths.push(c);break;case "gate":o.gates.paths.includes(c)||o.gates.paths.push(c);break;case "flow":o.flows.paths.includes(c)||o.flows.paths.push(c);break}}let s=[],i=[];for(let a of n.aggregation.purposeFiles)s.push(a.filePath);return s.push(".paradigm/config.yaml"),n.gateConfig&&s.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:o,key_files:{config:s.slice(0,10),entry:i,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}function pt(n,e,o={}){let{maxResults:t=20}=o,r=[],s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=[`rg -n --no-heading "${s}" "${n}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${s}" "${n}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of i)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return r;let c=a.trim().split(`
|
|
3
3
|
`);for(let l of c.slice(0,t)){let d=l.match(/^(.+?):(\d+):(.*)$/);if(d){let[,p,m,h]=d,x=I.relative(n,p),f="unknown";x.includes(".purpose")||x.includes("portal.yaml")?f="purpose":h.includes("//")||h.includes("#")||h.includes("*")?f="comment":f="code",r.push({filePath:x,line:parseInt(m,10),content:h.trim().slice(0,200),context:f});}}return r}b();var Yt=30*1e3,ft=new Map;async function mt(n){let e=I.resolve(n),o=ft.get(e);if(o&&Date.now()-o.loadedAt<Yt)return o.index;let t=await Xt(e);return t&&ft.set(e,{index:t,loadedAt:Date.now()}),t}async function Xt(n){let e=I.join(n,".paradigm","flow-index.json");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return JSON.parse(o)}catch(o){return a$1.component("#flow-loader").error("Error parsing flow-index.json",{error:o}),null}}function Zt(n,e){let o=n.symbolToFlows[e]||[],t=[];for(let r of o){let s=n.flows[r];if(!s)continue;let i=s.steps.map((a,c)=>({step:a,index:c})).filter(({step:a})=>a.symbol===e);for(let{step:a,index:c}of i){let l=s.steps.slice(c+1).map(d=>d.id);t.push({flowId:s.id,definedIn:s.definedIn,description:s.description,trigger:s.trigger,stepAffected:{id:a.id,action:a.action,position:c+1},downstreamSteps:l,validation:s.validation});}}return t}function ut(n,e){let o=Zt(n,e),t=new Set;for(let i of o)i.validation?.command&&t.add(i.validation.command);let r="low",s=o.reduce((i,a)=>i+a.downstreamSteps.length,0);return o.length>3||s>10?r="high":(o.length>1||s>3)&&(r="medium"),{symbol:e,totalFlows:o.length,impactLevel:r,affectedFlows:o,validationCommands:Array.from(t),suggestion:o.length>0?`Changes to ${e} may affect ${o.length} flow(s). ${t.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function mo(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["dependencies","impact","blast radius","what would break","dependents","affects"]}]}async function le(n$1,e,o$1){if(n$1!=="paradigm_ripple")return {handled:false,text:""};let{symbol:t,depth:r=3,includeWorkspace:s=false,response_format:i}=e,a=k(o$1.index,t);if(!a){let w=en(o$1.rootDir,t);return O(w.length,n$1),{handled:true,text:w}}let c=Math.min(Math.max(r||3,1),5),l$2=n(o$1.index,t),d=new Set([t]),p=new Map;function m(w,v){if(v>=c)return;let u=[];for(let k of w){if(d.has(k))continue;d.add(k);let N=n(o$1.index,k);for(let T of N)d.has(T.symbol)||u.push(T.symbol);}u.length>0&&(p.set(v+1,u),m(u,v+1));}m(l$2.map(w=>w.symbol),1);let h=new Set;for(let[,w]of p)for(let v of w)v!==t&&!l$2.find(u=>u.symbol===v)&&h.add(v);let x=o(o$1.index,t),f=l$2.length+h.size,P="low";f>10?P="high":f>3&&(P="medium");let A=await mt(o$1.rootDir),R=null;if(A){let w=ut(A,t);w.totalFlows>0&&(w.impactLevel==="high"&&P==="low"?P="medium":w.impactLevel==="high"&&(P="high"),R={totalFlows:w.totalFlows,affectedFlows:w.affectedFlows.map(v=>({flowId:v.flowId,impactLevel:v.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${v.stepAffected.position}, affects ${v.downstreamSteps.length} downstream steps`})),validationSuggestion:w.validationCommands.length>0?`Run: ${w.validationCommands[0]}`:void 0});}let $=new Set([t,...l$2.map(w=>w.symbol),...h]),F=[];try{let w=l(o$1.index,"gate");for(let v of w)$.has(v.symbol)&&F.push({gate:v.symbol,description:v.description});for(let v of l$2)v.type==="gate"&&!F.find(u=>u.gate===v.symbol)&&F.push({gate:v.symbol,description:v.description});}catch{}let C={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:P,analysis:{directlyAffected:l$2.map(w=>({symbol:w.symbol,type:w.type,description:w.description})),indirectlyAffected:Array.from(h),indirectByLevel:Object.fromEntries(p),dependsOn:x.map(w=>({symbol:w.symbol,type:w.type}))},summary:{directCount:l$2.length,indirectCount:h.size,totalAffected:f,dependsOnCount:x.length,levelsAnalyzed:c},recommendation:tn(P)};R&&(C.affectedFlows=R),F.length>0&&(C.affectedGates=F),C.suggestedReviewScope=nn(P,l$2.length,h.size,F.length,R?.totalFlows??0);try{let w=await l$1(o$1.rootDir,t);w.length>0&&(C.personas_affected=w,w.length>2&&P==="low"&&(C.impact="medium"));}catch{}try{let w=D$1(o$1.rootDir,t);w.length>0&&(C.university_content_affected=w.map(v=>({id:v.id,title:v.title,type:v.type,stale:v.stale})));}catch{}if(s&&o$1.workspace){let w=it(o$1.workspace,t);if(w.length>0){C.workspaceImpact={siblings:w.map(u=>({project:u.project,references:u.references.map(k=>({symbol:k.symbol,type:k.type,description:k.description}))}))};let v=w.reduce((u,k)=>u+k.references.length,0);v>0&&P==="low"&&(C.impact="medium"),v>5&&(C.impact="high");}}let O$1=i==="concise"?{symbol:C.symbol,impact:C.impact,summary:C.summary}:C,E=JSON.stringify(O$1,null,2);return O(E.length,n$1),{handled:true,text:E}}function en(n,e){let o=pt(n,e,{maxResults:20});if(o.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(o.map(i=>i.filePath))],r={};for(let i of o)r[i.context]=(r[i.context]||0)+1;let s="low";return t.length>10||o.length>20?s="high":(t.length>3||o.length>5)&&(s="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:s,analysis:{filesAffected:t.slice(0,10),totalFilesAffected:t.length,totalReferences:o.length,contextBreakdown:r,sampleReferences:o.slice(0,5).map(i=>({file:i.filePath,line:i.line,preview:i.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 tn(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 nn(n,e,o,t,r){let s=[];return e>0&&s.push(`Review ${e} direct dependent(s) for breaking changes`),o>0&&s.push(`Scan ${o} indirect dependent(s) for cascading effects`),t>0&&s.push(`Verify ${t} affected gate(s) still enforce correct auth/access`),r>0&&s.push(`Validate ${r} affected flow(s) end-to-end`),n==="high"?s.push("Consider running full test suite before merging"):n==="medium"&&s.push("Run targeted tests for affected components"),s.length===0&&s.push("No downstream dependents detected - safe to proceed"),s}b();b();var on=30*1e3,ve=new Map,yt=".paradigm/wisdom";async function ht(n){let e=I.resolve(n),o=ve.get(e);if(o&&Date.now()-o.loadedAt<on)return o.context;let t=await sn(e);return ve.set(e,{context:t,loadedAt:Date.now()}),t}async function sn(n){let e$1=I.join(n,yt),o=D.existsSync(e$1),[t,r,s,i]=o?await Promise.all([rn(e$1),an(e$1),cn(e$1),ln(e$1)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e(),l=f$1();}catch{}let d$1=new Set(r.map(f=>f.id)),p=r.map(f=>({...f,scope:"project"}));for(let f of a)d$1.has(f.id)||p.push({...f,scope:"global"});let m=new Set(i.map(f=>f.id)),h=i.map(f=>({...f,scope:"project"}));for(let f of c)m.has(f.id)||h.push({...f,scope:"global"});let x=t;if(l&&!t)x=l;else if(l&&t){let f={...t.by_symbol};if(l.by_symbol)for(let[P,A]of Object.entries(l.by_symbol))f[P]||(f[P]=A);x={...t,by_symbol:f,global:{...l.global,...t.global}};}return {preferences:x,antipatterns:p,decisions:h,expertise:s}}function z(n){let e=I.resolve(n);ve.delete(e);}async function rn(n){let e=I.join(n,"preferences.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return G.load(o)}catch(o){return a$1.component("#wisdom-loader").error("Error parsing preferences.yaml",{error:o}),null}}async function an(n){let e=I.join(n,"antipatterns.yaml");if(!D.existsSync(e))return [];try{let o=D.readFileSync(e,"utf8");return G.load(o).antipatterns||[]}catch(o){return a$1.component("#wisdom-loader").error("Error parsing antipatterns.yaml",{error:o}),[]}}async function cn(n){let e=I.join(n,"expertise.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return G.load(o)}catch(o){return a$1.component("#wisdom-loader").error("Error parsing expertise.yaml",{error:o}),null}}var gt=new Set;async function ln(n){let e=I.join(n,"decisions");if(!D.existsSync(e))return [];let o=[];try{let t=D.readdirSync(e);t.some(s=>s.endsWith(".yaml")||s.endsWith(".yml"))&&!gt.has(e)&&(gt.add(e),a$1.component("#wisdom-loader").warn("wisdom-decisions found; run `paradigm migrate decisions` in v6.0. In v5.39.0 wisdom-decisions are still read but will be migrated to TD-streams in v6.0."));for(let s of t){if(!s.endsWith(".yaml")&&!s.endsWith(".yml"))continue;let i=I.join(e,s);try{let a=D.readFileSync(i,"utf8"),c=G.load(a);o.push(c);}catch(a){a$1.component("#wisdom-loader").error(`Error parsing ${s}`,{error:a});}}}catch(t){a$1.component("#wisdom-loader").error("Error reading decisions directory",{error:t});}return o.sort((t,r)=>t.id.localeCompare(r.id)),o}function bt(n,e){return e.map(o=>dn(n,o))}function dn(n,e){let o=n.preferences?.by_symbol?.[e]||null,t=n.antipatterns.filter(i=>i.symbols.some(a=>a===e||de(e,a))),r=n.decisions.filter(i=>i.symbols.some(a=>a===e||de(e,a))),s=n.expertise?.experts.filter(i=>i.symbols?.some(a=>a===e||de(e,a)))||[];return {symbol:e,preferences:o,antipatterns:t,decisions:r,experts:s}}function wt(n,e){return n.expertise?n.expertise.experts.filter(o=>!!(e.symbol&&o.symbols&&o.symbols.some(t=>t===e.symbol||de(e.symbol,t))||e.area&&o.areas&&o.areas.some(t=>t.toLowerCase().includes(e.area.toLowerCase())))):[]}function de(n,e){if(e.endsWith("*")){let o=e.slice(0,-1);return n.startsWith(o)}return n===e}async function St(n,e){let o=I.join(n,yt),t=I.join(o,"antipatterns.yaml");D.existsSync(o)||D.mkdirSync(o,{recursive:true});let r={version:"1.0",antipatterns:[]};if(D.existsSync(t))try{let s=D.readFileSync(t,"utf8"),i=G.load(s);i&&typeof i=="object"&&(r={version:i.version||"1.0",antipatterns:Array.isArray(i.antipatterns)?i.antipatterns:[]});}catch{}r.antipatterns.push({...e,added:new Date().toISOString()}),D.writeFileSync(t,G.dump(r,{lineWidth:-1})),z(n);}b();var xt=".paradigm/history";async function vt(n){let e=I.join(n,xt);if(!D.existsSync(e))return {index:null,validation:null};let[o,t]=await Promise.all([pn(e),fn(e)]);return {index:o,validation:t}}async function pn(n){let e=I.join(n,"index.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return G.load(o)}catch(o){return a$1.component("#history-loader").error("Error parsing index.yaml",{error:o.message}),null}}async function fn(n){let e=I.join(n,"validation.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return G.load(o)}catch(o){return a$1.component("#history-loader").error("Error parsing validation.yaml",{error:o.message}),null}}function wo(n,e){return e.map(o=>mn(n,o))}function mn(n,e){let o=n.index?.by_symbol?.[e]||null,t=[];if(n.index?.co_changes){for(let s of n.index.co_changes)if(s.symbols.includes(e))for(let i of s.symbols)i!==e&&!t.includes(i)&&t.push(i);}let r=n.validation?.by_symbol?.[e]||null;return {symbol:e,summary:o,recent:o?.recent||[],co_changes:t,validation:r}}function So(n,e){let o=[],t=[];if(!n.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let i of e){let a=n.index.by_symbol?.[i];a&&(a.fragility==="high"||a.fragility==="critical")&&o.push({symbol:i,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=n.index.fragile_symbols?.find(l=>l.symbol===i);c&&!o.find(l=>l.symbol===i)&&o.push(c);}for(let i of e){let a=n.index.co_changes?.filter(c=>c.symbols.includes(i));if(a?.length)for(let c of a){let l=c.symbols.filter(d=>d!==i&&!e.includes(d));l.length>0&&c.correlation>.7&&t.push(`${i} often changes with ${l.join(", ")} (${Math.round(c.correlation*100)}% correlation)`);}}let r=o.filter(i=>i.fragility==="critical").length===0,s=[];return o.length>0&&(s.push("Consider adding extra test coverage before modifying fragile symbols"),s.push("Review recent rollbacks and failures for these symbols")),t.length>0&&s.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:o,warnings:t,safe_to_modify:r,recommendations:s}}async function un(n,e){let o=I.join(n,xt),t=I.join(o,"log.jsonl");D.existsSync(o)||D.mkdirSync(o,{recursive:true});let r=gn(t),s=new Date().toISOString(),i={id:r,ts:s,...e},a=JSON.stringify(i)+`
|
|
4
4
|
`;return D.appendFileSync(t,a),r}async function xo(n,e,o,t){return un(n,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:o,tests:t})}function gn(n){let e=1;return D.existsSync(n)&&(e=D.readFileSync(n,"utf8").split(`
|
|
5
|
-
`).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}async function Fo(n){let e=I.resolve(n),o=await i(e),t=j$1(o),r=null,s=I.join(e,"portal.yaml");if(D.existsSync(s))try{r=await g(s);}catch(d){let p=d?.name??"Error";a$1.component("#index-loader").warn("Could not parse portal.yaml",{errorClass:p});}let i$1=I.basename(e),a=I.join(e,".premise");if(D.existsSync(a))try{let p=D.readFileSync(a,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);p&&(i$1=p[1].trim());}catch{}let c=null,l=I.join(e,".paradigm","config.yaml");if(D.existsSync(l))try{let d=D.readFileSync(l,"utf8"),p=G.load(d);p&&typeof p=="object"&&(p.version||a$1.component("#index-loader").warn('config.yaml missing "version" field'),p.project||a$1.component("#index-loader").warn('config.yaml missing "project" field')),p&&typeof p.workspace=="string"&&(c=rt(e,p.workspace));}catch(d){a$1.component("#index-loader").warn("Failed to load workspace config",{error:d.message});}return {rootDir:e,index:t,aggregation:o,gateConfig:r,projectName:i$1,wisdom:null,history:null,workspace:c,_loadedAt:Date.now()}}async function fe(n){return n.wisdom||(n.wisdom=await ht(n.rootDir)),n.wisdom}async function Io(n){return n.history||(n.history=await vt(n.rootDir)),n.history}j();b();var _t=false;function Bo(){return [{name:"paradigm_wisdom_context",description:"Get team wisdom (preferences, antipatterns, decisions) for symbols before implementing. Call this before making changes to understand team patterns. Returns preferences, antipatterns, and decisions relevant to the specified symbols. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get wisdom for (e.g., ["@checkout", "#payment-form"])'},include_global:{type:"boolean",description:"Include global preferences (default: true)"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_wisdom_record",description:"Record a new team learning: antipattern (what not to do) or decision (architectural choice). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to record"},id:{type:"string",description:'Unique ID (for antipattern: e.g., "api-001", for decision: e.g., "001")'},symbols:{type:"array",items:{type:"string"},description:"Related symbols"},description:{type:"string",description:"What not to do (antipattern) or the decision made (decision)"},reason:{type:"string",description:"Why this is an antipattern / context for decision"},alternative:{type:"string",description:"What to do instead (for antipatterns)"},title:{type:"string",description:"Decision title (for decisions)"},status:{type:"string",enum:["proposed","accepted","deprecated","superseded"],description:"Decision status (for decisions)"},rationale:{type:"object",properties:{factors:{type:"array",items:{type:"string"}},conclusion:{type:"string"}},description:"Decision rationale (for decisions)"},consequences:{type:"object",properties:{positive:{type:"array",items:{type:"string"}},negative:{type:"array",items:{type:"string"}},mitigations:{type:"array",items:{type:"string"}}},description:"Expected consequences (for decisions)"},scope:{type:"string",enum:["project","global"],description:'Where to store: "project" (default) writes to .paradigm/wisdom/, "global" writes to ~/.paradigm/wisdom/'}},required:["type","id","symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]}},{name:"paradigm_wisdom_expert",description:"Find human experts who know about specific symbols or areas. Returns names and contact info for relevant experts. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to find experts for (e.g., "@checkout")'},area:{type:"string",description:'General area to find experts for (e.g., "payments", "auth")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Pt(n,e$1,o){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:r=true}=e$1,s=await fe(o),i=bt(s,t),a={symbols:t,wisdom:i.map(d=>({symbol:d.symbol,preferences:d.preferences,antipatterns:d.antipatterns.map(p=>({id:p.id,description:p.description,reason:p.reason,alternative:p.alternative,scope:p.scope||"project"})),decisions:d.decisions.map(p=>({id:p.id,title:p.title,status:p.status,decision:p.decision,scope:p.scope||"project"})),experts:d.experts.map(p=>p.name)}))};r&&s.preferences?.global&&(a.global_preferences=s.preferences.global);let c=i.reduce((d,p)=>d+p.antipatterns.length,0),l=i.reduce((d,p)=>d+p.decisions.length,0);a.summary={symbols_with_preferences:i.filter(d=>d.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:i.some(d=>d.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let d={},p=[];for(let m of t){let h=await a$3(o.rootDir,{symbol:m,hasAssessment:!0,limit:100});if(h.length===0)continue;let x={correct:0,partial:0,incorrect:0},f=0,P=0;for(let R of h){let $=R.assessment.verdict;x[$]++,R.confidence!=null&&(f+=R.confidence,P++);}d[m]={total:h.length,...x,avgConfidence:P>0?Math.round(f/P*1e3)/1e3:null};let A=(x.correct+x.partial*.5)/h.length;A<.6&&h.length>=3&&p.push(`Low historical accuracy for ${m}: ${Math.round(A*100)}% across ${h.length} entries. Proceed with extra caution.`);}Object.keys(d).length>0&&(a.calibration=d),p.length>0&&(a.calibration_warnings=p);}catch{}return {handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_wisdom_record":{let{type:t,id:r,symbols:s,description:i,reason:a,alternative:c,title:l,status:d,rationale:p,consequences:m,scope:h$1="project"}=e$1;if(t==="antipattern"){if(!i||!a||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let x={id:r,symbols:s,description:i,reason:a,alternative:c};return h$1==="global"?g$1(x):await St(o.rootDir,x),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,scope:h$1,message:`Antipattern recorded to ${h$1} scope`})}}if(t==="decision"){if(!l||!i||!p||!m)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};if(_t||(_t=true,a$1.component("#wisdom").warn('paradigm_wisdom_record({type:"decision"}) is deprecated. Use paradigm_decision_record instead.',{deprecation:"v6.0",canonical_tool:"paradigm_decision_record"})),h$1==="global"){let P={id:r,title:l,status:d||"proposed",date:new Date().toISOString().split("T")[0],symbols:s,context:a||"",decision:i,rationale:p,consequences:m};return h(P),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,scope:"global",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record for project-scoped decisions.',message:"Decision recorded to global scope"})}}let x=a$2(o.rootDir,{title:l,decision:i,rationale:{factors:p.factors,conclusion:p.conclusion},participants:[{id:"wisdom-record",role:"agent",stance:"proposed"}],symbols_affected:s,status:d==="accepted"?"active":d==="proposed"?"proposed":"active",context:a||void 0,consequences:m,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),f=d$1(o.rootDir,x.id);return z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:x.id,legacy_id:r,scope:"project",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record going forward.',message:`Decision recorded (routed to decisions stream as ${x.id})`,...f?{companion_lore_id:f}:{}})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_promote":{let{type:t,id:r}=e$1,s=await fe(o),i=I.basename(o.rootDir);if(t==="antipattern"){let a=s.antipatterns.find(l=>l.id===r);return a?d().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Antipattern "${r}" already exists in global scope`})}:(g$1({...a,learned_from:`promoted from ${i}`}),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,promoted_from:i,message:`Antipattern "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${r}" not found in project`})}}if(t==="decision"){let a=s.decisions.find(l=>l.id===r);return a?e().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Decision "${r}" already exists in global scope`})}:(h(a),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,promoted_from:i,message:`Decision "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${r}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_expert":{let{symbol:t,area:r}=e$1;if(!t&&!r)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let s=await fe(o),i=wt(s,{symbol:t,area:r});return {handled:true,text:JSON.stringify({query:{symbol:t,area:r},count:i.length,experts:i.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:i.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function Go(){return [{name:"paradigm_protocol_search",description:"Search for protocols matching a task description. Call BEFORE exploring the codebase \u2014 if a matching protocol exists, follow its steps instead of discovering the pattern from scratch. Returns top matches with steps, exemplar, and freshness info. ~200 tokens.",inputSchema:{type:"object",properties:{task:{type:"string",description:'Task description to search for (e.g., "add a new page", "add API route")'},limit:{type:"number",description:"Maximum results (default: 3)"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_get",description:"Get a specific protocol by ID with full details and freshness check. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID (e.g., "P-add-view")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_record",description:"Record a new protocol after completing repeatable work. Captures the steps you followed so future agents can skip exploration. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Protocol name (e.g., "Add a new view")'},description:{type:"string",description:"What this protocol accomplishes"},trigger:{type:"array",items:{type:"string"},description:'Phrases that should match this protocol (e.g., ["add view", "new page"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g., ["ui", "frontend"])'},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols involved (e.g., ["#logs-view"])'},exemplar:{type:"string",description:'Canonical file to study for this pattern (e.g., "ui/src/views/LogsView.tsx")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"],description:"Step action type"},target:{type:"string",description:"File path (supports {Name}/{name} placeholders)"},template_from:{type:"string",description:"File to use as template (for create actions)"},reference:{type:"string",description:"Where in the file to make changes (for modify actions)"},command:{type:"string",description:"Command to execute (for run actions)"},notes:{type:"string",description:"Additional guidance for this step"}},required:["action"]},description:"Ordered steps to follow"},recorded_from:{type:"string",description:'Lore entry ID this protocol was learned from (e.g., "L-2026-03-01-001")'}},required:["name","description","trigger","tags","steps"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_update",description:"Update an existing protocol. Use refresh:true after successfully following a protocol to bump last_verified. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID to update (e.g., "P-add-view")'},refresh:{type:"boolean",description:"Set true to bump last_verified to now (use after successfully following the protocol)"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},trigger:{type:"array",items:{type:"string"},description:"Updated trigger phrases"},tags:{type:"array",items:{type:"string"},description:"Updated tags"},symbols:{type:"array",items:{type:"string"},description:"Updated symbols"},exemplar:{type:"string",description:"Updated exemplar path"},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"]},target:{type:"string"},template_from:{type:"string"},reference:{type:"string"},command:{type:"string"},notes:{type:"string"}},required:["action"]},description:"Updated steps"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_validate",description:"Validate protocol references \u2014 check that referenced files exist, exemplars haven't drifted. Validates all protocols if no ID given. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Protocol ID to validate (omit to validate all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function jt(n,e,o){switch(n){case "paradigm_protocol_search":{let t=e.task,r=e.limit||3,s=await I$1(o.rootDir,t,r);return s.length===0?{handled:true,text:JSON.stringify({count:0,task:t,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:s.length,task:t,matches:s.map(i=>({id:i.protocol.id,name:i.protocol.name,description:i.protocol.description,score:i.score,status:i.protocol.status,exemplar:i.protocol.exemplar,last_verified:i.protocol.last_verified,steps:i.protocol.steps.map(yn)}))},null,2)}}case "paradigm_protocol_get":{let t=e.id,r=await G$1(o.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let s=L(o.rootDir,r);return {handled:true,text:JSON.stringify({...r,freshness:{status:s.status,issues:s.issues}},null,2)}}case "paradigm_protocol_record":{let t=e.steps||[],r=await J(o.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:t,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:r,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let t=e.id,r=e.refresh,s={};e.name!==void 0&&(s.name=e.name),e.description!==void 0&&(s.description=e.description),e.trigger!==void 0&&(s.trigger=e.trigger),e.tags!==void 0&&(s.tags=e.tags),e.symbols!==void 0&&(s.symbols=e.symbols),e.exemplar!==void 0&&(s.exemplar=e.exemplar),e.steps!==void 0&&(s.steps=e.steps);let i=await K(o.rootDir,t,s,r===true);return {handled:true,text:JSON.stringify({success:i,id:t,refreshed:r===true,message:i?r?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${t}`})}}case "paradigm_protocol_validate":{let t=e.id;if(t){let a=await G$1(o.rootDir,t);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let c=L(o.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let s=(await F(o.rootDir)).map(a=>{let c=L(o.rootDir,a);return {id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified}}),i={total:s.length,current:s.filter(a=>a.status==="current").length,stale:s.filter(a=>a.status==="stale").length,broken:s.filter(a=>a.status==="broken").length};return {handled:true,text:JSON.stringify({protocols:s,health:i},null,2)}}default:return {handled:false,text:""}}}function yn(n){let e={action:n.action};return n.target&&(e.target=n.target),n.template_from&&(e.template_from=n.template_from),n.reference&&(e.reference=n.reference),n.command&&(e.command=n.command),n.notes&&(e.notes=n.notes),e}j();var ee=null,ke=false;async function _e(n){if(ee)ke||(await ee.ensureReady(),ke=true);else {let e=I.join(n,".paradigm","sentinel","sentinel.db");ee=new f(e),await ee.ensureReady(),ke=true;}return ee}async function hn(n,e){return (await _e(n)).recordPracticeEvent(e)}async function zo(n,e){return (await _e(n)).getPracticeEvents(e)}async function Ce(n,e){return (await _e(n)).getComplianceRate(e)}async function Rt(n,e){let o=["discovery","verification","testing","documentation","collaboration","security"],t=[];for(let r of o){let s=await Ce(n,{...e,habitCategory:r});s.total>0&&t.push({category:r,...s});}return t}async function Vo(n,e,o){let t=[];for(let r of e){let s=await hn(n,{habitId:r.habitId,habitCategory:r.habitCategory,result:r.result,engineer:o.engineer,sessionId:o.sessionId,loreEntryId:o.loreEntryId,taskDescription:o.taskDescription,symbolsTouched:o.symbolsTouched,filesModified:o.filesModified,notes:r.notes});t.push(s);}return t}b();function Ft(n){return {handled:true,text:JSON.stringify({error:n},null,2)}}var me={code:"lore_type_decision_removed",message:"lore type 'decision' was removed in v6.0. Use paradigm_decision_record instead. The decision will be stored in .paradigm/decisions/ and a companion lore insight entry (type:'insight' with references.decision_id) will be written automatically so the timeline stays complete. For narrative-only references, use paradigm_lore_record({type:'insight', references:{decision_id}}).",successor_tool:"paradigm_decision_record",doc:"docs/private/plans/v6.0-decisions-locked.md",removed_in:"6.0.0"};function It(){let n=process.env.PARADIGM_AUTHOR;if(n)return Pe(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Pe(e)}catch{}try{let e=Ot.userInfo().username;if(e)return Pe(e)}catch{}return "unknown"}function Pe(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function ss(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, milestone, retro, insight, etc.). Call after completing significant work. Returns the created entry ID and file path. For decisions, use paradigm_decision_record (a companion lore insight is auto-written). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function je(n,e,o){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},r=await a$3(o.rootDir,t);return {handled:true,text:JSON.stringify({count:r.length,filter:Object.fromEntries(Object.entries(t).filter(([,s])=>s!==void 0)),entries:r.map(At)},null,2)}}case "paradigm_lore_record":{let{type:t,title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:m,duration_minutes:h,decisions:x,errors_encountered:f,learnings:P,verification:A,tags:R,meta:$,body:F,linked_lore:C,linked_tasks:O,linked_commits:E,confidence:w}=e;if(t==="decision")return a$1.component("#lore").warn("rejected paradigm_lore_record({type:'decision'}) \u2014 removed in v6.0",{removed_in:me.removed_in,successor_tool:me.successor_tool}),Ft(me);let v;try{let S=new Date(Date.now()-2592e6).toISOString(),b=await Ce(o.rootDir,{dateFrom:S});if(b.total>0){let y=(await Rt(o.rootDir,{dateFrom:S})).filter(_=>_.rate<60).map(_=>_.category);v={rate:b.rate,followed:b.followed,skipped:b.skipped,partial:b.partial,weakAreas:y.length>0?y:void 0};}}catch{}let u={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:h,author:It(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:m,decisions:x,errors_encountered:f,learnings:P,verification:A,tags:R,meta:$||void 0,habit_compliance:v,body:F,linked_lore:C,linked_tasks:O,linked_commits:E,confidence:w!=null&&w>=0&&w<=1?w:void 0},k=await d$2(o.rootDir,u);j$2().setLastLoreEntryId(k);try{let S=process.env.PARADIGM_AGENT_ID;if(S&&i&&i.length>0){let{updateExpertiseFromLore:b}=await import('./agent-loader-W3RQJVW7.js');b(o.rootDir,S,{symbols_touched:i,confidence:w!=null&&w>=0&&w<=1?w:void 0});}}catch{}let N$1=null;try{c&&c.length>=2&&(N$1=N(o.rootDir,c,l||[]));}catch{}let T;if(e.stream){let S=e.stream,b=S==="auto"?wn(e):S;try{if(b==="work-log"){let{recordWorkLog:g}=await import('./work-log-loader-DL5GZ2BQ.js');g(o.rootDir,{agent:u.agent?.model||"unknown",summary:u.summary,outcome:u.verification?.status==="pass"?"pass":u.verification?.status==="fail"?"fail":"partial",files_modified:u.files_modified,symbols_touched:u.symbols_touched,commit:u.commit,linked_lore:u.id||k}),T="work-log";}else if(b==="journal"&&u.learnings?.length){let{recordJournalEntry:g}=await import('./journal-loader-GLH7XFTK.js');for(let y of u.learnings)g(u.agent?.model||"unknown",{trigger:"self_reflection",insight:y,project:o.projectName||"unknown",transferable:!1,linked_work_log:u.id||k});T="journal";}else if(b==="decision"&&u.decisions?.length){let{recordDecision:g}=await import('./decision-loader-HELL2AMX.js');for(let y of u.decisions)g(o.rootDir,{title:y.decision.slice(0,100),decision:y.decision,rationale:y.rationale,participants:[{id:`agent/${u.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:u.symbols_touched,status:"active",linked_lore:u.id||k});T="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:k,type:t,title:r,message:"Lore entry recorded successfully",...T?{stream:T}:{},...N$1?{protocol_suggestion:N$1}:{}})}}case "paradigm_lore_timeline":{let t=e.limit||10,r=await c(o.rootDir),s=await a$3(o.rootDir,{limit:t}),i={};for(let l of s)for(let d of l.symbols_touched)i[d]=(i[d]||0)+1;let a=Object.entries(i).sort(([,l],[,d])=>d-l).slice(0,10).map(([l,d])=>({symbol:l,count:d})),c$1={};for(let l of s){let d=l.author;c$1[d]||(c$1[d]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c$1[d].count++,l.agent&&(c$1[d].hasAgent=true),l.timestamp>c$1[d].lastActive&&(c$1[d].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:r||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:s.map(At),hotSymbols:a,authors:Object.entries(c$1).map(([l,d])=>({id:l,hasAgent:d.hasAgent,entries:d.count,lastActive:d.lastActive}))},null,2)}}case "paradigm_lore_get":{let t=e.id,r=await b$1(o.rootDir,t);return r?{handled:true,text:JSON.stringify(r,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})}}case "paradigm_lore_update":{let t=e.id,{id:r,...s}=e,i={};for(let[c,l]of Object.entries(s))l!==void 0&&(i[c]=l);let a=await g$2(o.rootDir,t,i);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,r=e.verdict,s=e.notes,i=await b$1(o.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})};let a={verdict:r,assessed_by:It(),assessed_at:new Date().toISOString(),notes:s},c=await h$1(o.rootDir,t,a);try{let m=process.env.PARADIGM_AGENT_ID;if(m&&c&&i.symbols_touched?.length){let{updateExpertiseFromAssessment:h}=await import('./agent-loader-W3RQJVW7.js');h(o.rootDir,m,{symbols_touched:i.symbols_touched,verdict:r});}}catch{}let l=r==="correct"?1:r==="partial"?.5:0,d=i.confidence!=null?l-i.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:r,confidence:i.confidence??null,delta:d,deltaDescription:p,message:c?`Assessment recorded: ${r}${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},r=await a$3(o.rootDir,t),s=r.filter(F=>F.confidence!=null),i=r.length,a=s.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,p=0;for(let F of r){let C=F.assessment.verdict;c[C]++;let O=C==="correct"?1:C==="partial"?.5:0;l+=O,F.confidence!=null&&(d+=F.confidence,p+=Math.abs(O-F.confidence));}let m=i>0?l/i:0,h=a>0?d/a:null,x=a>0?l/i-d/a:null,f=a>0?1-p/a:null,P=e.groupBy,A;if(P&&i>0){let F=new Map;for(let C of r){let O=[];P==="symbol"?O=C.symbols_touched||[]:P==="tag"?O=C.tags||[]:P==="type"&&(O=[C.type||"agent-session"]);for(let E of O)F.has(E)||F.set(E,[]),F.get(E).push(C);}A=Array.from(F.entries()).map(([C,O])=>{let E=O.filter(N=>N.confidence!=null),w={correct:0,partial:0,incorrect:0},v=0,u=0,k=0;for(let N of O){let T=N.assessment.verdict;w[T]++;let S=T==="correct"?1:T==="partial"?.5:0;v+=S,N.confidence!=null&&(u+=N.confidence,k+=Math.abs(S-N.confidence));}return {key:C,total:O.length,accuracyRate:v/O.length,avgConfidence:E.length>0?u/E.length:null,calibrationScore:E.length>0?1-k/E.length:null,verdictBreakdown:w}}).sort((C,O)=>O.total-C.total);}let R=[],$=i<5?`Low sample size (N=${i}). Stats may not be representative.`:i<15?`Moderate sample (N=${i}). Trends are directional, not conclusive.`:null;return $&&R.push($),f!=null&&(f>=.9?R.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):f>=.7?R.push("Good calibration \u2014 some room for improvement in confidence estimates."):f>=.5?R.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):R.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),x!=null&&(x>.15?R.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):x<-0.15&&R.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>i*.3&&i>=5&&R.push(`High error rate: ${c.incorrect}/${i} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:i,totalWithConfidence:a,accuracyRate:Math.round(m*1e3)/1e3,avgConfidence:h!=null?Math.round(h*1e3)/1e3:null,avgDelta:x!=null?Math.round(x*1e3)/1e3:null,calibrationScore:f!=null?Math.round(f*1e3)/1e3:null,verdictBreakdown:c,...A?{groups:A}:{},insights:R},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 s=await i$1(o.rootDir,t);return {handled:true,text:JSON.stringify({success:s,id:t,message:s?"Lore entry deleted":`Lore entry not found: ${t}`})}}default:return {handled:false,text:""}}}function wn(n){return n.task_ref||n.files_modified||n.commit?"work-log":n.learnings||n.confidence!==void 0?"journal":n.decisions?.some(o=>o.rationale)?"decision":"work-log"}function At(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 hs(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_captain_board",description:"Cid's owned run-DAG board (#captain-board). action='read' (default, read-only) assembles the live orchestration DAG \u2014 each run's epic + ordered stage-children with status/claimant/dependsOn, plus ripple-ranked unclaimed open tasks and a summary. action='claim' writes a task's claimant (status stays open; human/peer claims override an archetype proposal). action='advance' records a blocked_on reason without changing status (orchestration owns in-progress/done). ~300 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["read","claim","advance"],description:"Board action. Default 'read'."},taskId:{type:"string",description:"Target task id (required for claim/advance)."},claimant:{type:"object",description:"For claim: the new owner { kind: 'archetype'|'human'|'peer', ref }.",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},blockedOn:{type:"string",description:"For advance: the blocking reason recorded on the task."}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function bs(n,e,o){return n==="paradigm_captain_brief"?Sn(e,o):n==="paradigm_captain_debrief"?xn(e,o):n==="paradigm_captain_board"?Cn(e,o):{handled:false,text:""}}async function Sn(n,e){let o=n.taskDescription,t=n.symbols||[],r=n.depth||"standard",s=I.join(e.rootDir,".paradigm"),i=I.join(s,".cid-session"),a=I.join(s,".cid-briefed");try{D.existsSync(a)&&D.unlinkSync(a);let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r};D.mkdirSync(s,{recursive:!0}),D.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let c=$n(o),l=[],d=new Set;for(let S of t)if(!d.has(S)){d.add(S);let b=$t(S);l.push({id:S,type:b,description:"Provided as anchor symbol"});}let p=[];try{for(let S of c.slice(0,3)){let g=m(e.index,S).slice(0,5);for(let y of g)if(!d.has(y.symbol)){d.add(y.symbol);let _=Tn(y.type);l.push({id:y.symbol,type:_,description:y.description||"",file:y.file}),p.push(y.symbol);}}}catch{}let m$1={directories:[],files:[]};try{let S=await lt("paradigm_navigate",{intent:"context",task:o,response_format:"concise"},e);if(S.handled){let b=JSON.parse(S.text);if(b.files)for(let g of b.files){let y=typeof g=="string"?g:g.path||g.file||"";y&&m$1.files.push(y);}if(b.directories)for(let g of b.directories){let y=typeof g=="string"?g:g.path||g.directory||"";y&&m$1.directories.push(y);}if(b.symbols)for(let g of b.symbols){let y=typeof g=="string"?g:g.id;y&&!d.has(y)&&(d.add(y),l.push({id:y,type:$t(y),description:typeof g=="object"&&g.description||""}));}}}catch{}let h=new Set(m$1.directories);for(let S of m$1.files){let b=I.dirname(S);b&&b!=="."&&h.add(b);}let x=l.slice(0,r==="deep"?5:3),f={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(r!=="quick"&&x.length>0)for(let S of x)try{let b=await le("paradigm_ripple",{symbol:S.id,depth:2,response_format:"concise"},e);if(b.handled){let g=JSON.parse(b.text);if(g.analysis){for(let y of g.analysis.directlyAffected||[]){let _=y.symbol||y;_&&!f.affectedSymbols.includes(_)&&f.affectedSymbols.push(_);}for(let y of g.analysis.indirectlyAffected||[])y&&!f.affectedSymbols.includes(y)&&f.affectedSymbols.push(y);}if(g.affectedFlows?.affectedFlows)for(let y of g.affectedFlows.affectedFlows){let _=y.flowId||y;_&&!f.affectedFlows.includes(_)&&f.affectedFlows.push(_);}if(g.affectedGates)for(let y of g.affectedGates){let _=y.gate||y;_&&!f.affectedGates.includes(_)&&f.affectedGates.push(_);}g.impact==="high"&&(f.fragileSymbols.includes(S.id)||f.fragileSymbols.push(S.id));}}catch{}let P=[],A=En(o);if(A.length>0)try{let{handleGatesForRoute:S}=await import('./tools-HNJ7D5IO.js').catch(()=>({handleGatesForRoute:null})),b=I.join(e.rootDir,"portal.yaml");if(D.existsSync(b)){let g=D.readFileSync(b,"utf8");for(let y of A){let _=g.includes(y);P.push({route:y,gate:"^authenticated",declared:_});}}else for(let g of A)P.push({route:g,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let R=[];if(r!=="quick"&&l.length>0)try{let S=l.slice(0,5).map(g=>g.id),b=await Pt("paradigm_wisdom_context",{symbols:S,include_global:!0},e);if(b.handled){let g=JSON.parse(b.text);if(g.antipatterns)for(let y of g.antipatterns.slice(0,3)){let _=y.pattern||y.description||y.text||String(y);_&&!R.includes(_)&&R.push(_);}if(g.wisdom?.antipatterns)for(let y of g.wisdom.antipatterns.slice(0,3)){let _=y.pattern||y.description||String(y);_&&!R.includes(_)&&R.push(_);}}}catch{}let $={matched:false};try{let S=await jt("paradigm_protocol_search",{task:o,limit:1},e);if(S.handled){let b=JSON.parse(S.text),g=b.matches||b.protocols||b.results||[];if(g.length>0){let y=g[0];$={matched:!0,id:y.id,name:y.name||y.title,steps:(y.steps||[]).slice(0,5).map(_=>typeof _=="string"?_:_.description||String(_))};}}}catch{}let F=[];if(r!=="quick")try{let S=l[0]?.id,b={limit:r==="deep"?5:3};S&&(b.symbol=S);let g=await je("paradigm_lore_search",b,e);if(g.handled){let _=JSON.parse(g.text).entries||[];for(let K of _.slice(0,3))F.push({id:K.id,summary:(K.summary||K.title||"").slice(0,100),relevance:S?`Related to ${S}`:"Recent project history"});}}catch{}let C=Array.from(h),O$1=0;for(let S of C){let b=I.join(e.rootDir,S,".purpose");if(D.existsSync(b))try{D.readFileSync(b,"utf8").trim().length>50&&O$1++;}catch{}}let E=C.length>0?O$1/C.length:.5,w=Wn(E),v=Ln(E,w,C.length),u=f.affectedSymbols.length+m$1.files.length,k=u>20?"large":u>8?"medium":u>2?"small":"tiny",N={territory:{directories:C.slice(0,10),files:m$1.files.slice(0,10),estimatedScope:k},symbols:l.slice(0,10),blastRadius:f,gates:P,protocol:$,warnings:R,coverage:{score:E,label:w,note:v},loreRefs:F,archMap:b$2(e.rootDir),renderedBrief:""};N.renderedBrief=Hn(N);try{let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r,coverageScore:E};D.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let T=JSON.stringify(N,null,2);return O(T.length,"paradigm_captain_brief"),{handled:true,text:T}}async function xn(n,e){let o=n.orchestrationId,t=n.sessionSummary,r=n.touchedFiles||[],s=n.newSymbols||[],i=n.notes,a=I.join(e.rootDir,".paradigm"),c=I.join(a,".cid-briefed"),l=I.join(a,".pending-review"),d=new Set;for(let u of r){let k=I.dirname(u);k&&k!=="."&&d.add(k);}let p=0,m=d.size;for(let u of d){let k=I.join(e.rootDir,u,".purpose");if(D.existsSync(k))try{D.readFileSync(k,"utf8").trim().length>50&&p++;}catch{}}let h=m>0?p/m:1,x=[],f=[];for(let u of d){let k=I.join(e.rootDir,u,".purpose"),N=I.join(e.rootDir,u),T=false;if(D.existsSync(k))try{T=D.readFileSync(k,"utf8").trim().length>50;}catch{}if(T){if(r.some(b=>I.dirname(b)===u&&s.length>0)){f.push(u);try{let b=JSON.stringify({path:u,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${o}: ${s.join(", ")}`,timestamp:new Date().toISOString()});D.appendFileSync(l,b+`
|
|
5
|
+
`).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}async function Fo(n){let e=I.resolve(n),o=await i(e),t=j$1(o),r=null,s=I.join(e,"portal.yaml");if(D.existsSync(s))try{r=await g(s);}catch(d){let p=d?.name??"Error";a$1.component("#index-loader").warn("Could not parse portal.yaml",{errorClass:p});}let i$1=I.basename(e),a=I.join(e,".premise");if(D.existsSync(a))try{let p=D.readFileSync(a,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);p&&(i$1=p[1].trim());}catch{}let c=null,l=I.join(e,".paradigm","config.yaml");if(D.existsSync(l))try{let d=D.readFileSync(l,"utf8"),p=G.load(d);p&&typeof p=="object"&&(p.version||a$1.component("#index-loader").warn('config.yaml missing "version" field'),p.project||a$1.component("#index-loader").warn('config.yaml missing "project" field')),p&&typeof p.workspace=="string"&&(c=rt(e,p.workspace));}catch(d){a$1.component("#index-loader").warn("Failed to load workspace config",{error:d.message});}return {rootDir:e,index:t,aggregation:o,gateConfig:r,projectName:i$1,wisdom:null,history:null,workspace:c,_loadedAt:Date.now()}}async function fe(n){return n.wisdom||(n.wisdom=await ht(n.rootDir)),n.wisdom}async function Io(n){return n.history||(n.history=await vt(n.rootDir)),n.history}j();b();var _t=false;function Bo(){return [{name:"paradigm_wisdom_context",description:"Get team wisdom (preferences, antipatterns, decisions) for symbols before implementing. Call this before making changes to understand team patterns. Returns preferences, antipatterns, and decisions relevant to the specified symbols. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get wisdom for (e.g., ["@checkout", "#payment-form"])'},include_global:{type:"boolean",description:"Include global preferences (default: true)"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_wisdom_record",description:"Record a new team learning: antipattern (what not to do) or decision (architectural choice). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to record"},id:{type:"string",description:'Unique ID (for antipattern: e.g., "api-001", for decision: e.g., "001")'},symbols:{type:"array",items:{type:"string"},description:"Related symbols"},description:{type:"string",description:"What not to do (antipattern) or the decision made (decision)"},reason:{type:"string",description:"Why this is an antipattern / context for decision"},alternative:{type:"string",description:"What to do instead (for antipatterns)"},title:{type:"string",description:"Decision title (for decisions)"},status:{type:"string",enum:["proposed","accepted","deprecated","superseded"],description:"Decision status (for decisions)"},rationale:{type:"object",properties:{factors:{type:"array",items:{type:"string"}},conclusion:{type:"string"}},description:"Decision rationale (for decisions)"},consequences:{type:"object",properties:{positive:{type:"array",items:{type:"string"}},negative:{type:"array",items:{type:"string"}},mitigations:{type:"array",items:{type:"string"}}},description:"Expected consequences (for decisions)"},scope:{type:"string",enum:["project","global"],description:'Where to store: "project" (default) writes to .paradigm/wisdom/, "global" writes to ~/.paradigm/wisdom/'}},required:["type","id","symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]}},{name:"paradigm_wisdom_expert",description:"Find human experts who know about specific symbols or areas. Returns names and contact info for relevant experts. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to find experts for (e.g., "@checkout")'},area:{type:"string",description:'General area to find experts for (e.g., "payments", "auth")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Pt(n,e$1,o){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:r=true}=e$1,s=await fe(o),i=bt(s,t),a={symbols:t,wisdom:i.map(d=>({symbol:d.symbol,preferences:d.preferences,antipatterns:d.antipatterns.map(p=>({id:p.id,description:p.description,reason:p.reason,alternative:p.alternative,scope:p.scope||"project"})),decisions:d.decisions.map(p=>({id:p.id,title:p.title,status:p.status,decision:p.decision,scope:p.scope||"project"})),experts:d.experts.map(p=>p.name)}))};r&&s.preferences?.global&&(a.global_preferences=s.preferences.global);let c=i.reduce((d,p)=>d+p.antipatterns.length,0),l=i.reduce((d,p)=>d+p.decisions.length,0);a.summary={symbols_with_preferences:i.filter(d=>d.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:i.some(d=>d.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let d={},p=[];for(let m of t){let h=await a$3(o.rootDir,{symbol:m,hasAssessment:!0,limit:100});if(h.length===0)continue;let x={correct:0,partial:0,incorrect:0},f=0,P=0;for(let R of h){let $=R.assessment.verdict;x[$]++,R.confidence!=null&&(f+=R.confidence,P++);}d[m]={total:h.length,...x,avgConfidence:P>0?Math.round(f/P*1e3)/1e3:null};let A=(x.correct+x.partial*.5)/h.length;A<.6&&h.length>=3&&p.push(`Low historical accuracy for ${m}: ${Math.round(A*100)}% across ${h.length} entries. Proceed with extra caution.`);}Object.keys(d).length>0&&(a.calibration=d),p.length>0&&(a.calibration_warnings=p);}catch{}return {handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_wisdom_record":{let{type:t,id:r,symbols:s,description:i,reason:a,alternative:c,title:l,status:d,rationale:p,consequences:m,scope:h$1="project"}=e$1;if(t==="antipattern"){if(!i||!a||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let x={id:r,symbols:s,description:i,reason:a,alternative:c};return h$1==="global"?g$1(x):await St(o.rootDir,x),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,scope:h$1,message:`Antipattern recorded to ${h$1} scope`})}}if(t==="decision"){if(!l||!i||!p||!m)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};if(_t||(_t=true,a$1.component("#wisdom").warn('paradigm_wisdom_record({type:"decision"}) is deprecated. Use paradigm_decision_record instead.',{deprecation:"v6.0",canonical_tool:"paradigm_decision_record"})),h$1==="global"){let P={id:r,title:l,status:d||"proposed",date:new Date().toISOString().split("T")[0],symbols:s,context:a||"",decision:i,rationale:p,consequences:m};return h(P),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,scope:"global",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record for project-scoped decisions.',message:"Decision recorded to global scope"})}}let x=a$2(o.rootDir,{title:l,decision:i,rationale:{factors:p.factors,conclusion:p.conclusion},participants:[{id:"wisdom-record",role:"agent",stance:"proposed"}],symbols_affected:s,status:d==="accepted"?"active":d==="proposed"?"proposed":"active",context:a||void 0,consequences:m,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),f=d$1(o.rootDir,x.id);return z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:x.id,legacy_id:r,scope:"project",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record going forward.',message:`Decision recorded (routed to decisions stream as ${x.id})`,...f?{companion_lore_id:f}:{}})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_promote":{let{type:t,id:r}=e$1,s=await fe(o),i=I.basename(o.rootDir);if(t==="antipattern"){let a=s.antipatterns.find(l=>l.id===r);return a?d().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Antipattern "${r}" already exists in global scope`})}:(g$1({...a,learned_from:`promoted from ${i}`}),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,promoted_from:i,message:`Antipattern "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${r}" not found in project`})}}if(t==="decision"){let a=s.decisions.find(l=>l.id===r);return a?e().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Decision "${r}" already exists in global scope`})}:(h(a),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,promoted_from:i,message:`Decision "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${r}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_expert":{let{symbol:t,area:r}=e$1;if(!t&&!r)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let s=await fe(o),i=wt(s,{symbol:t,area:r});return {handled:true,text:JSON.stringify({query:{symbol:t,area:r},count:i.length,experts:i.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:i.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function Go(){return [{name:"paradigm_protocol_search",description:"Search for protocols matching a task description. Call BEFORE exploring the codebase \u2014 if a matching protocol exists, follow its steps instead of discovering the pattern from scratch. Returns top matches with steps, exemplar, and freshness info. ~200 tokens.",inputSchema:{type:"object",properties:{task:{type:"string",description:'Task description to search for (e.g., "add a new page", "add API route")'},limit:{type:"number",description:"Maximum results (default: 3)"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_get",description:"Get a specific protocol by ID with full details and freshness check. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID (e.g., "P-add-view")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_record",description:"Record a new protocol after completing repeatable work. Captures the steps you followed so future agents can skip exploration. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Protocol name (e.g., "Add a new view")'},description:{type:"string",description:"What this protocol accomplishes"},trigger:{type:"array",items:{type:"string"},description:'Phrases that should match this protocol (e.g., ["add view", "new page"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g., ["ui", "frontend"])'},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols involved (e.g., ["#logs-view"])'},exemplar:{type:"string",description:'Canonical file to study for this pattern (e.g., "ui/src/views/LogsView.tsx")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"],description:"Step action type"},target:{type:"string",description:"File path (supports {Name}/{name} placeholders)"},template_from:{type:"string",description:"File to use as template (for create actions)"},reference:{type:"string",description:"Where in the file to make changes (for modify actions)"},command:{type:"string",description:"Command to execute (for run actions)"},notes:{type:"string",description:"Additional guidance for this step"}},required:["action"]},description:"Ordered steps to follow"},recorded_from:{type:"string",description:'Lore entry ID this protocol was learned from (e.g., "L-2026-03-01-001")'}},required:["name","description","trigger","tags","steps"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_update",description:"Update an existing protocol. Use refresh:true after successfully following a protocol to bump last_verified. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID to update (e.g., "P-add-view")'},refresh:{type:"boolean",description:"Set true to bump last_verified to now (use after successfully following the protocol)"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},trigger:{type:"array",items:{type:"string"},description:"Updated trigger phrases"},tags:{type:"array",items:{type:"string"},description:"Updated tags"},symbols:{type:"array",items:{type:"string"},description:"Updated symbols"},exemplar:{type:"string",description:"Updated exemplar path"},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"]},target:{type:"string"},template_from:{type:"string"},reference:{type:"string"},command:{type:"string"},notes:{type:"string"}},required:["action"]},description:"Updated steps"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_validate",description:"Validate protocol references \u2014 check that referenced files exist, exemplars haven't drifted. Validates all protocols if no ID given. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Protocol ID to validate (omit to validate all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function jt(n,e,o){switch(n){case "paradigm_protocol_search":{let t=e.task,r=e.limit||3,s=await I$1(o.rootDir,t,r);return s.length===0?{handled:true,text:JSON.stringify({count:0,task:t,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:s.length,task:t,matches:s.map(i=>({id:i.protocol.id,name:i.protocol.name,description:i.protocol.description,score:i.score,status:i.protocol.status,exemplar:i.protocol.exemplar,last_verified:i.protocol.last_verified,steps:i.protocol.steps.map(yn)}))},null,2)}}case "paradigm_protocol_get":{let t=e.id,r=await G$1(o.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let s=L(o.rootDir,r);return {handled:true,text:JSON.stringify({...r,freshness:{status:s.status,issues:s.issues}},null,2)}}case "paradigm_protocol_record":{let t=e.steps||[],r=await J(o.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:t,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:r,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let t=e.id,r=e.refresh,s={};e.name!==void 0&&(s.name=e.name),e.description!==void 0&&(s.description=e.description),e.trigger!==void 0&&(s.trigger=e.trigger),e.tags!==void 0&&(s.tags=e.tags),e.symbols!==void 0&&(s.symbols=e.symbols),e.exemplar!==void 0&&(s.exemplar=e.exemplar),e.steps!==void 0&&(s.steps=e.steps);let i=await K(o.rootDir,t,s,r===true);return {handled:true,text:JSON.stringify({success:i,id:t,refreshed:r===true,message:i?r?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${t}`})}}case "paradigm_protocol_validate":{let t=e.id;if(t){let a=await G$1(o.rootDir,t);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let c=L(o.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let s=(await F(o.rootDir)).map(a=>{let c=L(o.rootDir,a);return {id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified}}),i={total:s.length,current:s.filter(a=>a.status==="current").length,stale:s.filter(a=>a.status==="stale").length,broken:s.filter(a=>a.status==="broken").length};return {handled:true,text:JSON.stringify({protocols:s,health:i},null,2)}}default:return {handled:false,text:""}}}function yn(n){let e={action:n.action};return n.target&&(e.target=n.target),n.template_from&&(e.template_from=n.template_from),n.reference&&(e.reference=n.reference),n.command&&(e.command=n.command),n.notes&&(e.notes=n.notes),e}j();var ee=null,ke=false;async function _e(n){if(ee)ke||(await ee.ensureReady(),ke=true);else {let e=I.join(n,".paradigm","sentinel","sentinel.db");ee=new f(e),await ee.ensureReady(),ke=true;}return ee}async function hn(n,e){return (await _e(n)).recordPracticeEvent(e)}async function zo(n,e){return (await _e(n)).getPracticeEvents(e)}async function Ce(n,e){return (await _e(n)).getComplianceRate(e)}async function Rt(n,e){let o=["discovery","verification","testing","documentation","collaboration","security"],t=[];for(let r of o){let s=await Ce(n,{...e,habitCategory:r});s.total>0&&t.push({category:r,...s});}return t}async function Vo(n,e,o){let t=[];for(let r of e){let s=await hn(n,{habitId:r.habitId,habitCategory:r.habitCategory,result:r.result,engineer:o.engineer,sessionId:o.sessionId,loreEntryId:o.loreEntryId,taskDescription:o.taskDescription,symbolsTouched:o.symbolsTouched,filesModified:o.filesModified,notes:r.notes});t.push(s);}return t}b();function Ft(n){return {handled:true,text:JSON.stringify({error:n},null,2)}}var me={code:"lore_type_decision_removed",message:"lore type 'decision' was removed in v6.0. Use paradigm_decision_record instead. The decision will be stored in .paradigm/decisions/ and a companion lore insight entry (type:'insight' with references.decision_id) will be written automatically so the timeline stays complete. For narrative-only references, use paradigm_lore_record({type:'insight', references:{decision_id}}).",successor_tool:"paradigm_decision_record",doc:"docs/private/plans/v6.0-decisions-locked.md",removed_in:"6.0.0"};function It(){let n=process.env.PARADIGM_AUTHOR;if(n)return Pe(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Pe(e)}catch{}try{let e=Ot.userInfo().username;if(e)return Pe(e)}catch{}return "unknown"}function Pe(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function ss(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, milestone, retro, insight, etc.). Call after completing significant work. Returns the created entry ID and file path. For decisions, use paradigm_decision_record (a companion lore insight is auto-written). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function je(n,e,o){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},r=await a$3(o.rootDir,t);return {handled:true,text:JSON.stringify({count:r.length,filter:Object.fromEntries(Object.entries(t).filter(([,s])=>s!==void 0)),entries:r.map(At)},null,2)}}case "paradigm_lore_record":{let{type:t,title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:m,duration_minutes:h,decisions:x,errors_encountered:f,learnings:P,verification:A,tags:R,meta:$,body:F,linked_lore:C,linked_tasks:O,linked_commits:E,confidence:w}=e;if(t==="decision")return a$1.component("#lore").warn("rejected paradigm_lore_record({type:'decision'}) \u2014 removed in v6.0",{removed_in:me.removed_in,successor_tool:me.successor_tool}),Ft(me);let v;try{let S=new Date(Date.now()-2592e6).toISOString(),b=await Ce(o.rootDir,{dateFrom:S});if(b.total>0){let y=(await Rt(o.rootDir,{dateFrom:S})).filter(_=>_.rate<60).map(_=>_.category);v={rate:b.rate,followed:b.followed,skipped:b.skipped,partial:b.partial,weakAreas:y.length>0?y:void 0};}}catch{}let u={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:h,author:It(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:m,decisions:x,errors_encountered:f,learnings:P,verification:A,tags:R,meta:$||void 0,habit_compliance:v,body:F,linked_lore:C,linked_tasks:O,linked_commits:E,confidence:w!=null&&w>=0&&w<=1?w:void 0},k=await d$2(o.rootDir,u);j$2().setLastLoreEntryId(k);try{let S=process.env.PARADIGM_AGENT_ID;if(S&&i&&i.length>0){let{updateExpertiseFromLore:b}=await import('./agent-loader-W3RQJVW7.js');b(o.rootDir,S,{symbols_touched:i,confidence:w!=null&&w>=0&&w<=1?w:void 0});}}catch{}let N$1=null;try{c&&c.length>=2&&(N$1=N(o.rootDir,c,l||[]));}catch{}let T;if(e.stream){let S=e.stream,b=S==="auto"?wn(e):S;try{if(b==="work-log"){let{recordWorkLog:g}=await import('./work-log-loader-DL5GZ2BQ.js');g(o.rootDir,{agent:u.agent?.model||"unknown",summary:u.summary,outcome:u.verification?.status==="pass"?"pass":u.verification?.status==="fail"?"fail":"partial",files_modified:u.files_modified,symbols_touched:u.symbols_touched,commit:u.commit,linked_lore:u.id||k}),T="work-log";}else if(b==="journal"&&u.learnings?.length){let{recordJournalEntry:g}=await import('./journal-loader-CNNA4EAU.js');for(let y of u.learnings)g(u.agent?.model||"unknown",{trigger:"self_reflection",insight:y,project:o.projectName||"unknown",transferable:!1,linked_work_log:u.id||k});T="journal";}else if(b==="decision"&&u.decisions?.length){let{recordDecision:g}=await import('./decision-loader-HELL2AMX.js');for(let y of u.decisions)g(o.rootDir,{title:y.decision.slice(0,100),decision:y.decision,rationale:y.rationale,participants:[{id:`agent/${u.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:u.symbols_touched,status:"active",linked_lore:u.id||k});T="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:k,type:t,title:r,message:"Lore entry recorded successfully",...T?{stream:T}:{},...N$1?{protocol_suggestion:N$1}:{}})}}case "paradigm_lore_timeline":{let t=e.limit||10,r=await c(o.rootDir),s=await a$3(o.rootDir,{limit:t}),i={};for(let l of s)for(let d of l.symbols_touched)i[d]=(i[d]||0)+1;let a=Object.entries(i).sort(([,l],[,d])=>d-l).slice(0,10).map(([l,d])=>({symbol:l,count:d})),c$1={};for(let l of s){let d=l.author;c$1[d]||(c$1[d]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c$1[d].count++,l.agent&&(c$1[d].hasAgent=true),l.timestamp>c$1[d].lastActive&&(c$1[d].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:r||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:s.map(At),hotSymbols:a,authors:Object.entries(c$1).map(([l,d])=>({id:l,hasAgent:d.hasAgent,entries:d.count,lastActive:d.lastActive}))},null,2)}}case "paradigm_lore_get":{let t=e.id,r=await b$1(o.rootDir,t);return r?{handled:true,text:JSON.stringify(r,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})}}case "paradigm_lore_update":{let t=e.id,{id:r,...s}=e,i={};for(let[c,l]of Object.entries(s))l!==void 0&&(i[c]=l);let a=await g$2(o.rootDir,t,i);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,r=e.verdict,s=e.notes,i=await b$1(o.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})};let a={verdict:r,assessed_by:It(),assessed_at:new Date().toISOString(),notes:s},c=await h$1(o.rootDir,t,a);try{let m=process.env.PARADIGM_AGENT_ID;if(m&&c&&i.symbols_touched?.length){let{updateExpertiseFromAssessment:h}=await import('./agent-loader-W3RQJVW7.js');h(o.rootDir,m,{symbols_touched:i.symbols_touched,verdict:r});}}catch{}let l=r==="correct"?1:r==="partial"?.5:0,d=i.confidence!=null?l-i.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:r,confidence:i.confidence??null,delta:d,deltaDescription:p,message:c?`Assessment recorded: ${r}${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},r=await a$3(o.rootDir,t),s=r.filter(F=>F.confidence!=null),i=r.length,a=s.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,p=0;for(let F of r){let C=F.assessment.verdict;c[C]++;let O=C==="correct"?1:C==="partial"?.5:0;l+=O,F.confidence!=null&&(d+=F.confidence,p+=Math.abs(O-F.confidence));}let m=i>0?l/i:0,h=a>0?d/a:null,x=a>0?l/i-d/a:null,f=a>0?1-p/a:null,P=e.groupBy,A;if(P&&i>0){let F=new Map;for(let C of r){let O=[];P==="symbol"?O=C.symbols_touched||[]:P==="tag"?O=C.tags||[]:P==="type"&&(O=[C.type||"agent-session"]);for(let E of O)F.has(E)||F.set(E,[]),F.get(E).push(C);}A=Array.from(F.entries()).map(([C,O])=>{let E=O.filter(N=>N.confidence!=null),w={correct:0,partial:0,incorrect:0},v=0,u=0,k=0;for(let N of O){let T=N.assessment.verdict;w[T]++;let S=T==="correct"?1:T==="partial"?.5:0;v+=S,N.confidence!=null&&(u+=N.confidence,k+=Math.abs(S-N.confidence));}return {key:C,total:O.length,accuracyRate:v/O.length,avgConfidence:E.length>0?u/E.length:null,calibrationScore:E.length>0?1-k/E.length:null,verdictBreakdown:w}}).sort((C,O)=>O.total-C.total);}let R=[],$=i<5?`Low sample size (N=${i}). Stats may not be representative.`:i<15?`Moderate sample (N=${i}). Trends are directional, not conclusive.`:null;return $&&R.push($),f!=null&&(f>=.9?R.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):f>=.7?R.push("Good calibration \u2014 some room for improvement in confidence estimates."):f>=.5?R.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):R.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),x!=null&&(x>.15?R.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):x<-0.15&&R.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>i*.3&&i>=5&&R.push(`High error rate: ${c.incorrect}/${i} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:i,totalWithConfidence:a,accuracyRate:Math.round(m*1e3)/1e3,avgConfidence:h!=null?Math.round(h*1e3)/1e3:null,avgDelta:x!=null?Math.round(x*1e3)/1e3:null,calibrationScore:f!=null?Math.round(f*1e3)/1e3:null,verdictBreakdown:c,...A?{groups:A}:{},insights:R},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 s=await i$1(o.rootDir,t);return {handled:true,text:JSON.stringify({success:s,id:t,message:s?"Lore entry deleted":`Lore entry not found: ${t}`})}}default:return {handled:false,text:""}}}function wn(n){return n.task_ref||n.files_modified||n.commit?"work-log":n.learnings||n.confidence!==void 0?"journal":n.decisions?.some(o=>o.rationale)?"decision":"work-log"}function At(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 hs(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_captain_board",description:"Cid's owned run-DAG board (#captain-board). action='read' (default, read-only) assembles the live orchestration DAG \u2014 each run's epic + ordered stage-children with status/claimant/dependsOn, plus ripple-ranked unclaimed open tasks and a summary. action='claim' writes a task's claimant (status stays open; human/peer claims override an archetype proposal). action='advance' records a blocked_on reason without changing status (orchestration owns in-progress/done). ~300 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["read","claim","advance"],description:"Board action. Default 'read'."},taskId:{type:"string",description:"Target task id (required for claim/advance)."},claimant:{type:"object",description:"For claim: the new owner { kind: 'archetype'|'human'|'peer', ref }.",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},blockedOn:{type:"string",description:"For advance: the blocking reason recorded on the task."}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function bs(n,e,o){return n==="paradigm_captain_brief"?Sn(e,o):n==="paradigm_captain_debrief"?xn(e,o):n==="paradigm_captain_board"?Cn(e,o):{handled:false,text:""}}async function Sn(n,e){let o=n.taskDescription,t=n.symbols||[],r=n.depth||"standard",s=I.join(e.rootDir,".paradigm"),i=I.join(s,".cid-session"),a=I.join(s,".cid-briefed");try{D.existsSync(a)&&D.unlinkSync(a);let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r};D.mkdirSync(s,{recursive:!0}),D.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let c=$n(o),l=[],d=new Set;for(let S of t)if(!d.has(S)){d.add(S);let b=$t(S);l.push({id:S,type:b,description:"Provided as anchor symbol"});}let p=[];try{for(let S of c.slice(0,3)){let g=m(e.index,S).slice(0,5);for(let y of g)if(!d.has(y.symbol)){d.add(y.symbol);let _=Tn(y.type);l.push({id:y.symbol,type:_,description:y.description||"",file:y.file}),p.push(y.symbol);}}}catch{}let m$1={directories:[],files:[]};try{let S=await lt("paradigm_navigate",{intent:"context",task:o,response_format:"concise"},e);if(S.handled){let b=JSON.parse(S.text);if(b.files)for(let g of b.files){let y=typeof g=="string"?g:g.path||g.file||"";y&&m$1.files.push(y);}if(b.directories)for(let g of b.directories){let y=typeof g=="string"?g:g.path||g.directory||"";y&&m$1.directories.push(y);}if(b.symbols)for(let g of b.symbols){let y=typeof g=="string"?g:g.id;y&&!d.has(y)&&(d.add(y),l.push({id:y,type:$t(y),description:typeof g=="object"&&g.description||""}));}}}catch{}let h=new Set(m$1.directories);for(let S of m$1.files){let b=I.dirname(S);b&&b!=="."&&h.add(b);}let x=l.slice(0,r==="deep"?5:3),f={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(r!=="quick"&&x.length>0)for(let S of x)try{let b=await le("paradigm_ripple",{symbol:S.id,depth:2,response_format:"concise"},e);if(b.handled){let g=JSON.parse(b.text);if(g.analysis){for(let y of g.analysis.directlyAffected||[]){let _=y.symbol||y;_&&!f.affectedSymbols.includes(_)&&f.affectedSymbols.push(_);}for(let y of g.analysis.indirectlyAffected||[])y&&!f.affectedSymbols.includes(y)&&f.affectedSymbols.push(y);}if(g.affectedFlows?.affectedFlows)for(let y of g.affectedFlows.affectedFlows){let _=y.flowId||y;_&&!f.affectedFlows.includes(_)&&f.affectedFlows.push(_);}if(g.affectedGates)for(let y of g.affectedGates){let _=y.gate||y;_&&!f.affectedGates.includes(_)&&f.affectedGates.push(_);}g.impact==="high"&&(f.fragileSymbols.includes(S.id)||f.fragileSymbols.push(S.id));}}catch{}let P=[],A=En(o);if(A.length>0)try{let{handleGatesForRoute:S}=await import('./tools-GAU5WOEI.js').catch(()=>({handleGatesForRoute:null})),b=I.join(e.rootDir,"portal.yaml");if(D.existsSync(b)){let g=D.readFileSync(b,"utf8");for(let y of A){let _=g.includes(y);P.push({route:y,gate:"^authenticated",declared:_});}}else for(let g of A)P.push({route:g,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let R=[];if(r!=="quick"&&l.length>0)try{let S=l.slice(0,5).map(g=>g.id),b=await Pt("paradigm_wisdom_context",{symbols:S,include_global:!0},e);if(b.handled){let g=JSON.parse(b.text);if(g.antipatterns)for(let y of g.antipatterns.slice(0,3)){let _=y.pattern||y.description||y.text||String(y);_&&!R.includes(_)&&R.push(_);}if(g.wisdom?.antipatterns)for(let y of g.wisdom.antipatterns.slice(0,3)){let _=y.pattern||y.description||String(y);_&&!R.includes(_)&&R.push(_);}}}catch{}let $={matched:false};try{let S=await jt("paradigm_protocol_search",{task:o,limit:1},e);if(S.handled){let b=JSON.parse(S.text),g=b.matches||b.protocols||b.results||[];if(g.length>0){let y=g[0];$={matched:!0,id:y.id,name:y.name||y.title,steps:(y.steps||[]).slice(0,5).map(_=>typeof _=="string"?_:_.description||String(_))};}}}catch{}let F=[];if(r!=="quick")try{let S=l[0]?.id,b={limit:r==="deep"?5:3};S&&(b.symbol=S);let g=await je("paradigm_lore_search",b,e);if(g.handled){let _=JSON.parse(g.text).entries||[];for(let K of _.slice(0,3))F.push({id:K.id,summary:(K.summary||K.title||"").slice(0,100),relevance:S?`Related to ${S}`:"Recent project history"});}}catch{}let C=Array.from(h),O$1=0;for(let S of C){let b=I.join(e.rootDir,S,".purpose");if(D.existsSync(b))try{D.readFileSync(b,"utf8").trim().length>50&&O$1++;}catch{}}let E=C.length>0?O$1/C.length:.5,w=Wn(E),v=Ln(E,w,C.length),u=f.affectedSymbols.length+m$1.files.length,k=u>20?"large":u>8?"medium":u>2?"small":"tiny",N={territory:{directories:C.slice(0,10),files:m$1.files.slice(0,10),estimatedScope:k},symbols:l.slice(0,10),blastRadius:f,gates:P,protocol:$,warnings:R,coverage:{score:E,label:w,note:v},loreRefs:F,archMap:b$2(e.rootDir),renderedBrief:""};N.renderedBrief=Hn(N);try{let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r,coverageScore:E};D.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let T=JSON.stringify(N,null,2);return O(T.length,"paradigm_captain_brief"),{handled:true,text:T}}async function xn(n,e){let o=n.orchestrationId,t=n.sessionSummary,r=n.touchedFiles||[],s=n.newSymbols||[],i=n.notes,a=I.join(e.rootDir,".paradigm"),c=I.join(a,".cid-briefed"),l=I.join(a,".pending-review"),d=new Set;for(let u of r){let k=I.dirname(u);k&&k!=="."&&d.add(k);}let p=0,m=d.size;for(let u of d){let k=I.join(e.rootDir,u,".purpose");if(D.existsSync(k))try{D.readFileSync(k,"utf8").trim().length>50&&p++;}catch{}}let h=m>0?p/m:1,x=[],f=[];for(let u of d){let k=I.join(e.rootDir,u,".purpose"),N=I.join(e.rootDir,u),T=false;if(D.existsSync(k))try{T=D.readFileSync(k,"utf8").trim().length>50;}catch{}if(T){if(r.some(b=>I.dirname(b)===u&&s.length>0)){f.push(u);try{let b=JSON.stringify({path:u,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${o}: ${s.join(", ")}`,timestamp:new Date().toISOString()});D.appendFileSync(l,b+`
|
|
6
6
|
`,"utf8");}catch{}}}else try{if(!D.existsSync(N))continue;let S=I.basename(u),b=Bn(S,u,r);D.writeFileSync(k,b,"utf8"),x.push(u),f.push(u);try{let g=JSON.stringify({path:u,reason:"captain-debrief",priority:"high",context:`Touched during orchestration ${o}. Files: ${r.filter(y=>I.dirname(y)===u).join(", ")}`,timestamp:new Date().toISOString()});D.appendFileSync(l,g+`
|
|
7
|
-
`,"utf8");}catch{}}catch{}}let P=0;for(let u of d){let k=I.join(e.rootDir,u,".purpose");if(D.existsSync(k))try{D.readFileSync(k,"utf8").trim().length>50&&P++;}catch{}}let A=m>0?P/m:1,R="";try{let u=await je("paradigm_lore_record",{type:"agent-session",title:`Cid Debrief: ${t.slice(0,80)}`,summary:t,symbols_touched:s,files_modified:r,tags:["arc:cid-debrief",`orch:${o}`],meta:{orchestrationId:o,coverageScore:{before:h,after:A},coverageAdded:x,...i?{notes:i}:{}}},e);if(u.handled){let k=JSON.parse(u.text);R=k.id||k.entry?.id||"";}}catch{}let $={ranThisSession:false,selfHealed:false,blockProposed:false};if($.ranThisSession=_n(a),!$.ranThisSession)try{let{runPostflightLearning:u}=await import('./ambient-
|
|
7
|
+
`,"utf8");}catch{}}catch{}}let P=0;for(let u of d){let k=I.join(e.rootDir,u,".purpose");if(D.existsSync(k))try{D.readFileSync(k,"utf8").trim().length>50&&P++;}catch{}}let A=m>0?P/m:1,R="";try{let u=await je("paradigm_lore_record",{type:"agent-session",title:`Cid Debrief: ${t.slice(0,80)}`,summary:t,symbols_touched:s,files_modified:r,tags:["arc:cid-debrief",`orch:${o}`],meta:{orchestrationId:o,coverageScore:{before:h,after:A},coverageAdded:x,...i?{notes:i}:{}}},e);if(u.handled){let k=JSON.parse(u.text);R=k.id||k.entry?.id||"";}}catch{}let $={ranThisSession:false,selfHealed:false,blockProposed:false};if($.ranThisSession=_n(a),!$.ranThisSession)try{let{runPostflightLearning:u}=await import('./ambient-OW5M5LVN.js');await u(e.rootDir,{claimant:"navigation"}),$.selfHealed=!0,a$1.flow("$captain-board").info("Cid self-healed postflight (no prior liveness record)",{orchestrationId:o});}catch(u){$.selfHealError=u instanceof Error?u.message:String(u),a$1.flow("$captain-board").warn("Cid postflight self-heal threw \u2014 proposing advise block",{orchestrationId:o,error:$.selfHealError});try{let{handleProposeBlockTool:k}=await import('./propose-block-ZEMEWJQF.js');await k("paradigm_propose_block",{claimant:"navigation",severity:"advise",reason:`Postflight learning did not run and Cid's self-heal failed: ${$.selfHealError}`,unblock_hint:"Run `paradigm_ambient_learn_postflight` manually, or inspect .paradigm/events/settlement-liveness.jsonl for the severed stage."},e),$.blockProposed=!0;}catch{}}let F=false;try{let u={timestamp:new Date().toISOString(),sessionId:o,touchedFiles:r,coverageScore:A};D.mkdirSync(a,{recursive:!0}),D.writeFileSync(c,JSON.stringify(u,null,2),"utf8"),F=!0;}catch{}let C={taskDescription:t,orchestrationId:o,agentContributions:[],coverageDelta:{before:h,after:A},newSymbols:s,touchedFiles:r,notes:i||""};try{let u=I.join(a,"events","session-log.jsonl");if(D.existsSync(u)){let T=D.readFileSync(u,"utf8").split(`
|
|
8
8
|
`).filter(b=>b.trim().length>0).slice(-50),S=new Map;for(let b of T)try{let g=JSON.parse(b),y=g.agentId||g.agent||g.role||"";if(!y)continue;S.has(y)||S.set(y,{contributions:[],symbolsTouched:new Set,patternsObserved:[]});let _=S.get(y),K=g.action||g.event||g.message||"";if(K&&_.contributions.push(String(K).slice(0,120)),Array.isArray(g.symbols))for(let te of g.symbols)_.symbolsTouched.add(String(te));let De=g.symbol||"";if(De&&_.symbolsTouched.add(De),Array.isArray(g.patterns))for(let te of g.patterns)_.patternsObserved.includes(String(te))||_.patternsObserved.push(String(te));}catch{}for(let[b,g]of S.entries())C.agentContributions.push({agentId:b,contribution:g.contributions.slice(-3).join(" | "),symbolsTouched:Array.from(g.symbolsTouched).slice(0,10),patternsObserved:g.patternsObserved.slice(0,5)});}}catch{}C.agentContributions.length===0&&C.agentContributions.push({agentId:"session",contribution:t.slice(0,200),symbolsTouched:s.slice(0,10),patternsObserved:[]});let O$1={coverageAdded:x,delegatedToDocumentor:f,loreEntryId:R,coverageScore:{before:h,after:A,delta:A-h},stopHookCleared:F,postflight:$,sessionInsights:C},E=["","\u2501\u2501\u2501 LEARNING HANDOFF (\u2192 Loid) \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501","","Cid has prepared session insights for Loid's learning pass.","Call paradigm_ambient_learn_postflight with the sessionInsights","from this debrief to complete the session.","","sessionInsights available in: debrief.sessionInsights"].join(`
|
|
9
9
|
`),v=JSON.stringify(O$1,null,2)+`
|
|
10
10
|
`+E;return O(v.length,"paradigm_captain_debrief"),{handled:true,text:v}}var vn=I.join("events","settlement-liveness.jsonl"),kn=360*60*1e3;function _n(n){let e=I.join(n,vn);if(!D.existsSync(e))return false;try{let t=D.readFileSync(e,"utf8").split(`
|
|
11
|
-
`).filter(s=>s.trim().length>0),r=Date.now()-kn;for(let s of t.slice(-50))try{let i=JSON.parse(s),a=i.ts?new Date(i.ts).getTime():NaN;if(Number.isNaN(a)||a<r)continue;if(i.stages?.runPostflightLearning==="ok")return !0}catch{}}catch{return false}return false}async function Cn(n,e){let o=n.action||"read";if(o==="claim")return On(n,e);if(o==="advance")return Nn(n,e);let t=await In(e.rootDir,{},e),r=JSON.stringify(t,null,2);return O(r.length,"paradigm_captain_board"),{handled:true,text:r}}function Pn(n,e){return n.settledAt?n.crashed_at||e.some(t=>t.crashed_at)?"crashed":"settled":e.length===0?"pending":e.some(t=>t.status==="in-progress")||n.status==="in-progress"?"in-progress":"pending"}function jn(n){return [...n].sort((e,o)=>{let t=e.stage??0,r=o.stage??0;if(t!==r)return t-r;let s=e.dependsOn?.length??0,i=o.dependsOn?.length??0;return s!==i?s-i:e.id.localeCompare(o.id)})}async function Dn(n,e){let o=Et(n).slice(0,3),t=[];for(let r of o)try{let s=await le("paradigm_ripple",{symbol:r,depth:1,response_format:"concise"},e);s.handled&&JSON.parse(s.text).impact==="high"&&!t.includes(r)&&t.push(r);}catch{}return t}var Rn=/[#$^!~][a-z][a-z0-9-]*/gi;function Et(n){let e=new Set;for(let t of n.tags||[])/^[#$^!~]/.test(t)&&e.add(t);let o=n.blurb?.match(Rn)||[];for(let t of o)e.add(t);return Array.from(e)}async function Fn(n,e){let o=Et(n).slice(0,3),t=0,r=[];for(let s of o)try{let i=await le("paradigm_ripple",{symbol:s,depth:2,response_format:"concise"},e);if(i.handled){let a=JSON.parse(i.text),c=a.analysis?.directlyAffected?.length??0,l=a.analysis?.indirectlyAffected?.length??0;t+=c*2+l,a.impact==="high"&&!r.includes(s)&&r.push(s);}}catch{}return {score:t,fragile:r}}var Nt={high:0,medium:1,low:2};async function In(n,e={},o){let t=o,{loadTasks:r}=await import('./task-loader-
|
|
11
|
+
`).filter(s=>s.trim().length>0),r=Date.now()-kn;for(let s of t.slice(-50))try{let i=JSON.parse(s),a=i.ts?new Date(i.ts).getTime():NaN;if(Number.isNaN(a)||a<r)continue;if(i.stages?.runPostflightLearning==="ok")return !0}catch{}}catch{return false}return false}async function Cn(n,e){let o=n.action||"read";if(o==="claim")return On(n,e);if(o==="advance")return Nn(n,e);let t=await In(e.rootDir,{},e),r=JSON.stringify(t,null,2);return O(r.length,"paradigm_captain_board"),{handled:true,text:r}}function Pn(n,e){return n.settledAt?n.crashed_at||e.some(t=>t.crashed_at)?"crashed":"settled":e.length===0?"pending":e.some(t=>t.status==="in-progress")||n.status==="in-progress"?"in-progress":"pending"}function jn(n){return [...n].sort((e,o)=>{let t=e.stage??0,r=o.stage??0;if(t!==r)return t-r;let s=e.dependsOn?.length??0,i=o.dependsOn?.length??0;return s!==i?s-i:e.id.localeCompare(o.id)})}async function Dn(n,e){let o=Et(n).slice(0,3),t=[];for(let r of o)try{let s=await le("paradigm_ripple",{symbol:r,depth:1,response_format:"concise"},e);s.handled&&JSON.parse(s.text).impact==="high"&&!t.includes(r)&&t.push(r);}catch{}return t}var Rn=/[#$^!~][a-z][a-z0-9-]*/gi;function Et(n){let e=new Set;for(let t of n.tags||[])/^[#$^!~]/.test(t)&&e.add(t);let o=n.blurb?.match(Rn)||[];for(let t of o)e.add(t);return Array.from(e)}async function Fn(n,e){let o=Et(n).slice(0,3),t=0,r=[];for(let s of o)try{let i=await le("paradigm_ripple",{symbol:s,depth:2,response_format:"concise"},e);if(i.handled){let a=JSON.parse(i.text),c=a.analysis?.directlyAffected?.length??0,l=a.analysis?.indirectlyAffected?.length??0;t+=c*2+l,a.impact==="high"&&!r.includes(s)&&r.push(s);}}catch{}return {score:t,fragile:r}}var Nt={high:0,medium:1,low:2};async function In(n,e={},o){let t=o,{loadTasks:r}=await import('./task-loader-YZME4RKE.js'),s=[];try{s=await r(n,{status:"all",limit:9999});}catch(m){a$1.flow("$captain-board").warn("Board task load failed",{error:m instanceof Error?m.message:String(m)});}let i=s.filter(m=>m.external_ref?.kind==="orchestration"&&!m.parentTaskId&&!m.settledAt),a=[];for(let m of i){let h=jn(s.filter(f=>f.parentTaskId===m.id)),x=[];for(let f of h){let P=t?await Dn(f,t):[];x.push({taskId:f.id,blurb:f.blurb,stage:f.stage,status:f.status,claimant:f.claimant,dependsOn:f.dependsOn||[],fragileSymbols:P});}a.push({epicTaskId:m.id,blurb:m.blurb,runStatus:Pn(m,h),settledAt:m.settledAt,nodes:x});}let c=s.filter(m=>m.status==="open"&&!m.claimant),l=[];for(let m of c){let{score:h,fragile:x}=t?await Fn(m,t):{score:0,fragile:[]},f;e.proposeClaimants&&(f=await An(m,n)),l.push({taskId:m.id,blurb:m.blurb,priority:m.priority,tags:m.tags||[],rippleScore:h,fragileSymbols:x,proposedClaimant:f});}l.sort((m,h)=>{if(h.rippleScore!==m.rippleScore)return h.rippleScore-m.rippleScore;let x=(Nt[m.priority]??1)-(Nt[h.priority]??1);return x!==0?x:h.taskId.localeCompare(m.taskId)});let d=s.filter(m=>m.status==="in-progress").length,p=s.filter(m=>m.status==="open").length;return {runs:a,unclaimed:l,summary:{runs:a.length,open:p,inFlight:d,unclaimed:l.length}}}async function An(n,e){try{let{suggestAgentsForTask:o,loadAgentsManifest:t}=await import('./orchestration-O2OVPTIZ.js'),r=t(e);if(!r?.agents)return;let s=[n.blurb,...n.tags||[]].join(" "),i=o(s,r.agents);return i.length===0?void 0:{kind:"archetype",ref:i[0].name}}catch{return}}async function On(n,e){let o=n.taskId,t=n.claimant;if(!o||!t?.kind||!t?.ref)return {handled:true,text:JSON.stringify({ok:false,error:"claim requires taskId and claimant {kind, ref}"})};let{loadTask:r,updateTask:s}=await import('./task-loader-YZME4RKE.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a=i.claimant;if(a&&a.kind!=="archetype"&&t.kind==="archetype")return a$1.flow("$captain-board").info("Claim rejected: archetype cannot override human/peer claim",{taskId:o,existing:a.kind,proposed:t.kind}),{handled:true,text:JSON.stringify({ok:false,error:`task ${o} is claimed by ${a.kind}:${a.ref}; archetype proposal cannot override`,claimant:a})};let c=await s(e.rootDir,o,{claimant:t});return a$1.flow("$captain-board").info("Captain claim written",{taskId:o,claimant:t,ok:c}),{handled:true,text:JSON.stringify({ok:c,taskId:o,claimant:t,status:"open"})}}async function Nn(n,e){let o=n.taskId,t=n.blockedOn;if(!o||!t)return {handled:true,text:JSON.stringify({ok:false,error:"advance requires taskId and blockedOn (v7.0 has no 'blocked' status \u2014 advance records a reason only)"})};let{loadTask:r,updateTask:s}=await import('./task-loader-YZME4RKE.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a=await s(e.rootDir,o,{blocked_on:t});return a$1.flow("$captain-board").info("Captain advance: blocked_on recorded (status unchanged)",{taskId:o,blockedOn:t,status:i.status,ok:a}),{handled:true,text:JSON.stringify({ok:a,taskId:o,blocked_on:t,status:i.status})}}function $n(n){let e=new Set(["the","a","an","to","of","in","and","or","for","with","that","this","is","it","be","as","at","by","from","add","create","update","fix","implement","make","build","change","modify","new","old","get","set","use","using"]),o=n.match(/[#$^!~@&%?][a-z][a-z0-9-]*/g)||[],t=n.replace(/[#$^!~@&%?]/g," ").split(/[\s\-_\/.,;:'"()\[\]{}!?]+/).map(s=>s.toLowerCase()).filter(s=>s.length>2&&!e.has(s));return [...new Set([...o,...t])].slice(0,6)}function En(n){let e=[],o=/(?:GET|POST|PUT|PATCH|DELETE)\s+(\/[a-z0-9\-\/:_{}]+)/gi,t;for(;(t=o.exec(n))!==null;)e.push(t[1]);let r=/\/api\/[a-z0-9\-\/:_{}]+/g;for(;(t=r.exec(n))!==null;)e.includes(t[0])||e.push(t[0]);return e}function $t(n){return n.startsWith("#")?"component":n.startsWith("$")?"flow":n.startsWith("^")?"gate":n.startsWith("!")?"signal":n.startsWith("~")?"aspect":"component"}function Tn(n){switch(n){case "component":return "component";case "flow":return "flow";case "gate":return "gate";case "signal":return "signal";case "aspect":return "aspect";default:return "component"}}function Wn(n){return n>=.85?"comprehensive":n>=.6?"reliable":n>=.3?"partial":"sparse"}function Ln(n,e,o){let t=Math.round(n*100);switch(e){case "sparse":return `${t}% of ${o} director(ies) covered. Brief may be significantly incomplete. Builder should explore directly.`;case "partial":return `${t}% of ${o} director(ies) covered. Brief covers key symbols. Some areas uncharted.`;case "reliable":return `${t}% of ${o} director(ies) covered. Brief is reliable for this task.`;case "comprehensive":return `${t}% of ${o} director(ies) covered. Area is fully mapped.`}}function Hn(n){let e=[],o="\u2501".repeat(52);e.push(`${o}`),e.push("");let t=n.territory.directories.slice(0,3).join(", ")||"(none detected)";e.push(`Territory: ${t}`);let r=n.symbols.slice(0,5).map(d=>d.id).join(", ")||"(none found)";e.push(`Symbols: ${r}`);let s=n.blastRadius.affectedFiles.length+n.territory.files.length,i=n.blastRadius.affectedFlows.length,a=n.blastRadius.affectedGates.length,c=n.blastRadius.fragileSymbols.length>0?` \xB7 \u26A0 ${n.blastRadius.fragileSymbols.slice(0,2).join(", ")} (fragile)`:"";if(e.push(`Blast Radius: ${s} files \xB7 ${i} flows \xB7 ${a} gates${c}`),n.gates.length>0){let d=n.gates.slice(0,2).map(p=>`${p.route} \u2192 ${p.gate} (${p.declared?"declared \u2713":"UNDECLARED \u2717"})`);e.push(`Gates: ${d.join("; ")}`);}if(n.protocol.matched){let d=n.protocol.steps?.length?` (${n.protocol.steps.length} steps)`:"";e.push(`Protocol: ${n.protocol.name||n.protocol.id}${d} \u2014 matched`);}else e.push("Protocol: (none matched)");n.warnings.length>0&&e.push(`Warnings: "${n.warnings[0].slice(0,80)}"`);let l=Math.round(n.coverage.score*100);return e.push(`Coverage: ${l}% \u2014 brief is ${n.coverage.label}`),e.push(""),e.push(`${o}`),e.join(`
|
|
12
12
|
`)}function Bn(n,e,o){let r=o.filter(s=>I.dirname(s)===e).slice(0,3).map(s=>`# - ${I.basename(s)}`).join(`
|
|
13
13
|
`);return `# Auto-generated .purpose stub \u2014 created by Cid (captain debrief)
|
|
14
14
|
# Delegate to Scribe (Documentor) for rich documentation
|