@a-company/paradigm 7.2.0 → 7.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/{accept-orchestration-XW44LF5Y.js → accept-orchestration-JA3A3TSU.js} +1 -1
  2. package/dist/calibrate-SH6PRZFD.js +2 -0
  3. package/dist/calibration-aggregate-5IVXSBDP.js +2 -0
  4. package/dist/calibration-aggregate-DUEE3LL2.js +4 -0
  5. package/dist/{captain-CAXGHC2V.js → captain-ILBN2IKJ.js} +1 -1
  6. package/dist/{captain-CWCLFOXV.js → captain-J4FZ5PRU.js} +1 -1
  7. package/dist/{chunk-W3VWORQZ.js → chunk-3F4QP2Z5.js} +1 -1
  8. package/dist/{chunk-QPQBXRXX.js → chunk-5VR7FKS5.js} +1 -1
  9. package/dist/chunk-7BZPDOOQ.js +25 -0
  10. package/dist/{chunk-XSKIXXFW.js → chunk-7HUPVOAY.js} +12 -12
  11. package/dist/{chunk-ASBK55FU.js → chunk-DLMDHS2X.js} +1 -1
  12. package/dist/{chunk-6HYRS3PH.js → chunk-IBKCMLOW.js} +8 -8
  13. package/dist/{chunk-USYV5QYU.js → chunk-KA6QEI3C.js} +1 -1
  14. package/dist/{chunk-UNSI6DVD.js → chunk-L3AOKDMU.js} +1 -1
  15. package/dist/chunk-MBKTVQS2.js +2 -0
  16. package/dist/{chunk-RZRFYGND.js → chunk-O4ADSTSY.js} +12 -12
  17. package/dist/chunk-RPGSQQTS.js +2 -0
  18. package/dist/chunk-RQHZUPLO.js +4 -0
  19. package/dist/chunk-SD3KVW5Q.js +2 -0
  20. package/dist/chunk-VKVVIN6J.js +25 -0
  21. package/dist/{chunk-2KK4JQ55.js → chunk-VR2LLUYE.js} +1 -1
  22. package/dist/{chunk-NRP2KJ6I.js → chunk-YNFF7XHV.js} +2 -2
  23. package/dist/{diff-Z2YSIRC4.js → diff-NZSJW3V3.js} +1 -1
  24. package/dist/dist-6TDAY6TQ-HMSTBL57.js +39 -0
  25. package/dist/{docs-OWJ7EPD7.js → docs-DWU3T2BV.js} +1 -1
  26. package/dist/github-GI3HX3N5.js +4 -0
  27. package/dist/index.js +6 -6
  28. package/dist/mcp.js +1 -1
  29. package/dist/{orchestrate-C5NM5MFN.js → orchestrate-C7SI4J7C.js} +1 -1
  30. package/dist/orchestration-4MJKBSGM.js +2 -0
  31. package/dist/orchestration-S2ESNKSA.js +2 -0
  32. package/dist/platform-server-IOWHNS7Q.js +25 -0
  33. package/dist/{reindex-W67B2LQP.js → reindex-G2JLIGOQ.js} +1 -1
  34. package/dist/reindex-JR3PXYQE.js +2 -0
  35. package/dist/{sentinel-EFPEX246.js → sentinel-RIEQWALQ.js} +1 -1
  36. package/dist/{sentinel-bridge-UR2MKARY.js → sentinel-bridge-D4LFDFCH.js} +1 -1
  37. package/dist/serve-PWAFVYYC.js +9 -0
  38. package/dist/{server-4D77LCST.js → server-K7G3IHR3.js} +1 -1
  39. package/dist/{shift-UDKXCIW7.js → shift-HGXZ5THV.js} +1 -1
  40. package/dist/{spawn-I6XG57S2.js → spawn-PHA2SVQ3.js} +1 -1
  41. package/dist/sync-layer-C2PF273N.js +2 -0
  42. package/dist/task-PRLQ4VPK.js +3 -0
  43. package/dist/task-loader-EIXPKHA3.js +2 -0
  44. package/dist/task-loader-LFEE6OU7.js +2 -0
  45. package/dist/task-settlement-A2T6EACG.js +3 -0
  46. package/dist/task-settlement-ZXOY4YGX.js +3 -0
  47. package/dist/{team-6WNNLBAO.js → team-KP4HMUB5.js} +1 -1
  48. package/dist/tools-NOMEIBS7.js +2 -0
  49. package/dist/{tools-SDWAFQMQ.js → tools-YW3Q27UI.js} +11 -11
  50. package/package.json +2 -6
  51. package/platform-ui/dist/assets/{AmbientSection-CwatqcBD.js → AmbientSection-xoxr3DQg.js} +1 -1
  52. package/platform-ui/dist/assets/{DocsSection-BZ2SFJBZ.js → DocsSection-Us2qksna.js} +1 -1
  53. package/platform-ui/dist/assets/{GitSection-MNNYU1tO.js → GitSection-DIHZyadf.js} +1 -1
  54. package/platform-ui/dist/assets/{GraphSection-COYjb4Pt.js → GraphSection-9TO0L1IO.js} +1 -1
  55. package/platform-ui/dist/assets/{LoreSection-B0hUbfsJ.js → LoreSection-DVDit8Aw.js} +1 -1
  56. package/platform-ui/dist/assets/{SentinelSection-BCxW1DCp.js → SentinelSection-a5_VNYcx.js} +1 -1
  57. package/platform-ui/dist/assets/{SymphonySection-BsucZRqy.js → SymphonySection-cRHEoJ9t.js} +1 -1
  58. package/platform-ui/dist/assets/TasksSection-44_gDO3L.css +1 -0
  59. package/platform-ui/dist/assets/TasksSection-h8x3qRIj.js +1 -0
  60. package/platform-ui/dist/assets/{TeamSection-C0QNTudW.js → TeamSection-mFoDyNic.js} +1 -1
  61. package/platform-ui/dist/assets/{UniversitySection-DN1-g9pw.js → UniversitySection-D99YRjmC.js} +1 -1
  62. package/platform-ui/dist/assets/{index-DwUT8pju.js → index-D_wB2S_2.js} +11 -11
  63. package/platform-ui/dist/index.html +1 -1
  64. package/dist/calibrate-PHVP7RPH.js +0 -4
  65. package/dist/chunk-3I3TITBA.js +0 -25
  66. package/dist/chunk-3YM5ABNX.js +0 -2
  67. package/dist/chunk-727PXENG.js +0 -2
  68. package/dist/chunk-K7KT6FL3.js +0 -25
  69. package/dist/chunk-XMAV5AG6.js +0 -2
  70. package/dist/dist-GQ42YS5N-4HIJZVBB.js +0 -39
  71. package/dist/github-4X4MYINS.js +0 -4
  72. package/dist/lore-server-FC2GMDLT.js +0 -14
  73. package/dist/orchestration-EVWQWTOV.js +0 -2
  74. package/dist/orchestration-UP3KFUJT.js +0 -2
  75. package/dist/platform-server-FXF3XFHM.js +0 -25
  76. package/dist/reindex-QZYOD5K4.js +0 -2
  77. package/dist/serve-L52ZUTU6.js +0 -10
  78. package/dist/serve-ZT2Z54NK.js +0 -8
  79. package/dist/task-KFND4HLF.js +0 -3
  80. package/dist/task-loader-HBZ3KRH2.js +0 -2
  81. package/dist/task-loader-IO4UVFUD.js +0 -2
  82. package/dist/task-settlement-NF7PFSNE.js +0 -3
  83. package/dist/task-settlement-TATNPY6L.js +0 -3
  84. package/dist/tools-GDWT74O6.js +0 -2
  85. package/graph-ui/dist/assets/index-BlgXTl53.css +0 -1
  86. package/graph-ui/dist/assets/index-Bq5nXK8p.js +0 -63
  87. package/graph-ui/dist/index.html +0 -13
  88. package/lore-ui/dist/assets/index-C3EixkjW.css +0 -1
  89. package/lore-ui/dist/assets/index-DKhNxgtW.js +0 -56
  90. package/lore-ui/dist/index.html +0 -13
  91. package/platform-ui/dist/assets/CanvasSection-dFAthehN.js +0 -9
  92. package/platform-ui/dist/assets/CanvasSection-flMXU19z.css +0 -1
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import {a,O,l as l$1,D,G,L,F,K,J,I as I$1,N}from'./chunk-3F4QP2Z5.js';import {a as a$2,d as d$1}from'./chunk-Q527BPUF.js';import {a as a$4}from'./chunk-VOPJ47QY.js';import {b as b$2}from'./chunk-RGSFU2YW.js';import {m,q as q$1,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 I from'fs';import*as E from'path';import*as q from'js-yaml';import {execSync}from'child_process';import*as Et from'os';b();b();var Ht=".paradigm/navigator.yaml";async function st(n){let e=E.join(n,Ht);if(!I.existsSync(e))return {config:null,configPath:null};try{let o=I.readFileSync(e,"utf8");return {config:q.load(o),configPath:e}}catch(o){return a$1.component("#navigator-loader").error("Error parsing navigator.yaml",{error:o}),{config:null,configPath:e}}}function rt(n,e,o){switch(e.intent){case "find":return Mt(n,e.target||"");case "explore":return Bt(n,e.target||"");case "context":return Jt(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Mt(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=Gt(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 Bt(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 Jt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase(),s=qt(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 Gt(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 qt(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 Ut(n){let e=E.resolve(n),o=I.readFileSync(e,"utf8"),t=q.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 at(n,e){let o=E.resolve(n),t=E.resolve(o,e);if(!I.existsSync(t))return a$1.component("#workspace-loader").warn("Workspace file not found",{workspacePath:t}),null;let r;try{r=Ut(t);}catch(c){return a$1.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let s=E.dirname(t),i="";for(let c of r.members){let l=E.resolve(s,c.path);if(it(l)===it(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=E.resolve(s,c.path),p=E.join(l,".paradigm","scan-index.json");if(!I.existsSync(p)){a$1.component("#workspace-loader").warn("No scan-index.json for workspace member",{member:c.name,scanIndexPath:p});continue}try{let f=JSON.parse(I.readFileSync(p,"utf8")),k=Kt(f);c.exports&&c.exports.length>0&&(k=zt(k,c.exports));let w=null,x=E.join(l,"portal.yaml");if(I.existsSync(x))try{let y=I.readFileSync(x,"utf8"),j=q.load(y);j&&(w=j);}catch{}a.set(c.name,{index:k,gateConfig:w});}catch(f){a$1.component("#workspace-loader").warn("Could not load index for workspace member",{member:c.name,error:f.message});}}return {config:r,workspacePath:t,currentMember:i,siblingIndices:a}}function zt(n,e){let t=q$1(n).filter(r=>{let s=r.symbol;return e.some(i=>Vt(i,s))});return Qt(t)}function Vt(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 ct(n,e){let o=[],t=e.includes("/")?e.split("/").pop():e;for(let[r,s]of n.siblingIndices){let i=[],a=q$1(s.index);for(let c of a){let l=c.references||[],p=c.description||"",f=l.some(w=>w===t||w===e||w.endsWith(`/${t}`)),k=p.includes(t);(f||k)&&i.push({symbol:c.symbol,type:c.type,description:c.description});}i.length>0&&o.push({project:r,references:i});}return o}function it(n){return E.resolve(n).replace(/\/+$/,"")}function Kt(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 Qt(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 Yt={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 to(){return [Yt]}async function pt(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 st(o.rootDir);if(r.config||(r={config:Xt(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=rt(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 p=xe(o.workspace,t.target);p.length>0&&(l.workspaceResults=p.slice(0,5).map(f=>({symbol:f.symbol,type:f.type,description:f.description,project:f.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(t.intent==="context"&&t.task){let p=xe(o.workspace,t.task);p.length>0&&(l.workspaceContext=p.slice(0,5).map(f=>({symbol:f.symbol,type:f.type,description:f.description,project:f.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=E.join(o.rootDir,".paradigm",".nav-called");I.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a$1}}function Xt(n){let e={},o={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},t=q$1(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 mt(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
+ `);for(let l of c.slice(0,t)){let p=l.match(/^(.+?):(\d+):(.*)$/);if(p){let[,f,k,w]=p,x=E.relative(n,f),y="unknown";x.includes(".purpose")||x.includes("portal.yaml")?y="purpose":w.includes("//")||w.includes("#")||w.includes("*")?y="comment":y="code",r.push({filePath:x,line:parseInt(k,10),content:w.trim().slice(0,200),context:y});}}return r}b();var en=30*1e3,ut=new Map;async function gt(n){let e=E.resolve(n),o=ut.get(e);if(o&&Date.now()-o.loadedAt<en)return o.index;let t=await tn(e);return t&&ut.set(e,{index:t,loadedAt:Date.now()}),t}async function tn(n){let e=E.join(n,".paradigm","flow-index.json");if(!I.existsSync(e))return null;try{let o=I.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 nn(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(p=>p.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 yt(n,e){let o=nn(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 go(){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 u=on(o$1.rootDir,t);return O(u.length,n$1),{handled:true,text:u}}let c=Math.min(Math.max(r||3,1),5),l$2=n(o$1.index,t),p=new Set([t]),f=new Map;function k$1(u,P){if(P>=c)return;let v=[];for(let b of u){if(p.has(b))continue;p.add(b);let D=n(o$1.index,b);for(let T of D)p.has(T.symbol)||v.push(T.symbol);}v.length>0&&(f.set(P+1,v),k$1(v,P+1));}k$1(l$2.map(u=>u.symbol),1);let w=new Set;for(let[,u]of f)for(let P of u)P!==t&&!l$2.find(v=>v.symbol===P)&&w.add(P);let x=o(o$1.index,t),y=l$2.length+w.size,j="low";y>10?j="high":y>3&&(j="medium");let N=await gt(o$1.rootDir),F=null;if(N){let u=yt(N,t);u.totalFlows>0&&(u.impactLevel==="high"&&j==="low"?j="medium":u.impactLevel==="high"&&(j="high"),F={totalFlows:u.totalFlows,affectedFlows:u.affectedFlows.map(P=>({flowId:P.flowId,impactLevel:P.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${P.stepAffected.position}, affects ${P.downstreamSteps.length} downstream steps`})),validationSuggestion:u.validationCommands.length>0?`Run: ${u.validationCommands[0]}`:void 0});}let $=new Set([t,...l$2.map(u=>u.symbol),...w]),A=[];try{let u=l(o$1.index,"gate");for(let P of u)$.has(P.symbol)&&A.push({gate:P.symbol,description:P.description});for(let P of l$2)P.type==="gate"&&!A.find(v=>v.gate===P.symbol)&&A.push({gate:P.symbol,description:P.description});}catch{}let d={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:j,analysis:{directlyAffected:l$2.map(u=>({symbol:u.symbol,type:u.type,description:u.description})),indirectlyAffected:Array.from(w),indirectByLevel:Object.fromEntries(f),dependsOn:x.map(u=>({symbol:u.symbol,type:u.type}))},summary:{directCount:l$2.length,indirectCount:w.size,totalAffected:y,dependsOnCount:x.length,levelsAnalyzed:c},recommendation:sn(j)};F&&(d.affectedFlows=F),A.length>0&&(d.affectedGates=A),d.suggestedReviewScope=rn(j,l$2.length,w.size,A.length,F?.totalFlows??0);try{let u=await l$1(o$1.rootDir,t);u.length>0&&(d.personas_affected=u,u.length>2&&j==="low"&&(d.impact="medium"));}catch{}try{let u=D(o$1.rootDir,t);u.length>0&&(d.university_content_affected=u.map(P=>({id:P.id,title:P.title,type:P.type,stale:P.stale})));}catch{}if(s&&o$1.workspace){let u=ct(o$1.workspace,t);if(u.length>0){d.workspaceImpact={siblings:u.map(v=>({project:v.project,references:v.references.map(b=>({symbol:b.symbol,type:b.type,description:b.description}))}))};let P=u.reduce((v,b)=>v+b.references.length,0);P>0&&j==="low"&&(d.impact="medium"),P>5&&(d.impact="high");}}let _=i==="concise"?{symbol:d.symbol,impact:d.impact,summary:d.summary}:d,O$1=JSON.stringify(_,null,2);return O(O$1.length,n$1),{handled:true,text:O$1}}function on(n,e){let o=mt(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 sn(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 rn(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 an=30*1e3,ve=new Map,bt=".paradigm/wisdom";async function wt(n){let e=E.resolve(n),o=ve.get(e);if(o&&Date.now()-o.loadedAt<an)return o.context;let t=await cn(e);return ve.set(e,{context:t,loadedAt:Date.now()}),t}async function cn(n){let e$1=E.join(n,bt),o=I.existsSync(e$1),[t,r,s,i]=o?await Promise.all([ln(e$1),dn(e$1),pn(e$1),fn(e$1)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e(),l=f$1();}catch{}let p=new Set(r.map(y=>y.id)),f=r.map(y=>({...y,scope:"project"}));for(let y of a)p.has(y.id)||f.push({...y,scope:"global"});let k=new Set(i.map(y=>y.id)),w=i.map(y=>({...y,scope:"project"}));for(let y of c)k.has(y.id)||w.push({...y,scope:"global"});let x=t;if(l&&!t)x=l;else if(l&&t){let y={...t.by_symbol};if(l.by_symbol)for(let[j,N]of Object.entries(l.by_symbol))y[j]||(y[j]=N);x={...t,by_symbol:y,global:{...l.global,...t.global}};}return {preferences:x,antipatterns:f,decisions:w,expertise:s}}function V(n){let e=E.resolve(n);ve.delete(e);}async function ln(n){let e=E.join(n,"preferences.yaml");if(!I.existsSync(e))return null;try{let o=I.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#wisdom-loader").error("Error parsing preferences.yaml",{error:o}),null}}async function dn(n){let e=E.join(n,"antipatterns.yaml");if(!I.existsSync(e))return [];try{let o=I.readFileSync(e,"utf8");return q.load(o).antipatterns||[]}catch(o){return a$1.component("#wisdom-loader").error("Error parsing antipatterns.yaml",{error:o}),[]}}async function pn(n){let e=E.join(n,"expertise.yaml");if(!I.existsSync(e))return null;try{let o=I.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#wisdom-loader").error("Error parsing expertise.yaml",{error:o}),null}}var ht=new Set;async function fn(n){let e=E.join(n,"decisions");if(!I.existsSync(e))return [];let o=[];try{let t=I.readdirSync(e);t.some(s=>s.endsWith(".yaml")||s.endsWith(".yml"))&&!ht.has(e)&&(ht.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=E.join(e,s);try{let a=I.readFileSync(i,"utf8"),c=q.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 St(n,e){return e.map(o=>mn(n,o))}function mn(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 xt(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 vt(n,e){let o=E.join(n,bt),t=E.join(o,"antipatterns.yaml");I.existsSync(o)||I.mkdirSync(o,{recursive:true});let r={version:"1.0",antipatterns:[]};if(I.existsSync(t))try{let s=I.readFileSync(t,"utf8"),i=q.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()}),I.writeFileSync(t,q.dump(r,{lineWidth:-1})),V(n);}b();var kt=".paradigm/history";async function _t(n){let e=E.join(n,kt);if(!I.existsSync(e))return {index:null,validation:null};let[o,t]=await Promise.all([un(e),gn(e)]);return {index:o,validation:t}}async function un(n){let e=E.join(n,"index.yaml");if(!I.existsSync(e))return null;try{let o=I.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#history-loader").error("Error parsing index.yaml",{error:o.message}),null}}async function gn(n){let e=E.join(n,"validation.yaml");if(!I.existsSync(e))return null;try{let o=I.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#history-loader").error("Error parsing validation.yaml",{error:o.message}),null}}function xo(n,e){return e.map(o=>yn(n,o))}function yn(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 vo(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(p=>p!==i&&!e.includes(p));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 hn(n,e){let o=E.join(n,kt),t=E.join(o,"log.jsonl");I.existsSync(o)||I.mkdirSync(o,{recursive:true});let r=bn(t),s=new Date().toISOString(),i={id:r,ts:s,...e},a=JSON.stringify(i)+`
4
+ `;return I.appendFileSync(t,a),r}async function ko(n,e,o,t){return hn(n,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:o,tests:t})}function bn(n){let e=1;return I.existsSync(n)&&(e=I.readFileSync(n,"utf8").split(`
5
+ `).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}async function Ao(n){let e=E.resolve(n),o=await i(e),t=j$1(o),r=null,s=E.join(e,"portal.yaml");if(I.existsSync(s))try{r=await g(s);}catch(p){let f=p?.name??"Error";a$1.component("#index-loader").warn("Could not parse portal.yaml",{errorClass:f});}let i$1=E.basename(e),a=E.join(e,".premise");if(I.existsSync(a))try{let f=I.readFileSync(a,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);f&&(i$1=f[1].trim());}catch{}let c=null,l=E.join(e,".paradigm","config.yaml");if(I.existsSync(l))try{let p=I.readFileSync(l,"utf8"),f=q.load(p);f&&typeof f=="object"&&(f.version||a$1.component("#index-loader").warn('config.yaml missing "version" field'),f.project||a$1.component("#index-loader").warn('config.yaml missing "project" field')),f&&typeof f.workspace=="string"&&(c=at(e,f.workspace));}catch(p){a$1.component("#index-loader").warn("Failed to load workspace config",{error:p.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 wt(n.rootDir)),n.wisdom}async function Oo(n){return n.history||(n.history=await _t(n.rootDir)),n.history}j();b();var Pt=false;function Jo(){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 Dt(n,e$1,o){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:r=true}=e$1,s=await fe(o),i=St(s,t),a={symbols:t,wisdom:i.map(p=>({symbol:p.symbol,preferences:p.preferences,antipatterns:p.antipatterns.map(f=>({id:f.id,description:f.description,reason:f.reason,alternative:f.alternative,scope:f.scope||"project"})),decisions:p.decisions.map(f=>({id:f.id,title:f.title,status:f.status,decision:f.decision,scope:f.scope||"project"})),experts:p.experts.map(f=>f.name)}))};r&&s.preferences?.global&&(a.global_preferences=s.preferences.global);let c=i.reduce((p,f)=>p+f.antipatterns.length,0),l=i.reduce((p,f)=>p+f.decisions.length,0);a.summary={symbols_with_preferences:i.filter(p=>p.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:i.some(p=>p.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let p={},f=[];for(let k of t){let w=await a$3(o.rootDir,{symbol:k,hasAssessment:!0,limit:100});if(w.length===0)continue;let x={correct:0,partial:0,incorrect:0},y=0,j=0;for(let F of w){let $=F.assessment.verdict;x[$]++,F.confidence!=null&&(y+=F.confidence,j++);}p[k]={total:w.length,...x,avgConfidence:j>0?Math.round(y/j*1e3)/1e3:null};let N=(x.correct+x.partial*.5)/w.length;N<.6&&w.length>=3&&f.push(`Low historical accuracy for ${k}: ${Math.round(N*100)}% across ${w.length} entries. Proceed with extra caution.`);}Object.keys(p).length>0&&(a.calibration=p),f.length>0&&(a.calibration_warnings=f);}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:p,rationale:f,consequences:k,scope:w="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 w==="global"?g$1(x):await vt(o.rootDir,x),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,scope:w,message:`Antipattern recorded to ${w} scope`})}}if(t==="decision"){if(!l||!i||!f||!k)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};if(Pt||(Pt=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"})),w==="global"){let j={id:r,title:l,status:p||"proposed",date:new Date().toISOString().split("T")[0],symbols:s,context:a||"",decision:i,rationale:f,consequences:k};return h(j),V(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:f.factors,conclusion:f.conclusion},participants:[{id:"wisdom-record",role:"agent",stance:"proposed"}],symbols_affected:s,status:p==="accepted"?"active":p==="proposed"?"proposed":"active",context:a||void 0,consequences:k,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),y=d$1(o.rootDir,x.id);return V(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})`,...y?{companion_lore_id:y}:{}})}}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=E.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}`}),V(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),V(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=xt(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 Uo(){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 Rt(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(wn)}))},null,2)}}case "paradigm_protocol_get":{let t=e.id,r=await G(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(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 wn(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=E.join(n,".paradigm","sentinel","sentinel.db");ee=new f(e),await ee.ensureReady(),ke=true;}return ee}async function Sn(n,e){return (await _e(n)).recordPracticeEvent(e)}async function Ko(n,e){return (await _e(n)).getPracticeEvents(e)}async function Ce(n,e){return (await _e(n)).getComplianceRate(e)}async function It(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 Qo(n,e,o){let t=[];for(let r of e){let s=await Sn(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 At(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 Ot(){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=Et.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 is(){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(Nt)},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:p,lines_removed:f,commit:k,duration_minutes:w,decisions:x,errors_encountered:y,learnings:j,verification:N$1,tags:F,meta:$,body:A,linked_lore:d,linked_tasks:_,linked_commits:O,confidence:u}=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}),At(me);let P;try{let S=new Date(Date.now()-2592e6).toISOString(),h=await Ce(o.rootDir,{dateFrom:S});if(h.total>0){let m=(await It(o.rootDir,{dateFrom:S})).filter(C=>C.rate<60).map(C=>C.category);P={rate:h.rate,followed:h.followed,skipped:h.skipped,partial:h.partial,weakAreas:m.length>0?m:void 0};}}catch{}let v={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:w,author:Ot(),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:p,lines_removed:f,commit:k,decisions:x,errors_encountered:y,learnings:j,verification:N$1,tags:F,meta:$||void 0,habit_compliance:P,body:A,linked_lore:d,linked_tasks:_,linked_commits:O,confidence:u!=null&&u>=0&&u<=1?u:void 0},b=await d$2(o.rootDir,v);j$2().setLastLoreEntryId(b);try{let S=process.env.PARADIGM_AGENT_ID;if(S&&i&&i.length>0){let{updateExpertiseFromLore:h}=await import('./agent-loader-W3RQJVW7.js');h(o.rootDir,S,{symbols_touched:i,confidence:u!=null&&u>=0&&u<=1?u:void 0});}}catch{}let D=null;try{c&&c.length>=2&&(D=N(o.rootDir,c,l||[]));}catch{}let T;if(e.stream){let S=e.stream,h=S==="auto"?vn(e):S;try{if(h==="work-log"){let{recordWorkLog:g}=await import('./work-log-loader-DL5GZ2BQ.js');g(o.rootDir,{agent:v.agent?.model||"unknown",summary:v.summary,outcome:v.verification?.status==="pass"?"pass":v.verification?.status==="fail"?"fail":"partial",files_modified:v.files_modified,symbols_touched:v.symbols_touched,commit:v.commit,linked_lore:v.id||b}),T="work-log";}else if(h==="journal"&&v.learnings?.length){let{recordJournalEntry:g}=await import('./journal-loader-CNNA4EAU.js');for(let m of v.learnings)g(v.agent?.model||"unknown",{trigger:"self_reflection",insight:m,project:o.projectName||"unknown",transferable:!1,linked_work_log:v.id||b});T="journal";}else if(h==="decision"&&v.decisions?.length){let{recordDecision:g}=await import('./decision-loader-HELL2AMX.js');for(let m of v.decisions)g(o.rootDir,{title:m.decision.slice(0,100),decision:m.decision,rationale:m.rationale,participants:[{id:`agent/${v.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:v.symbols_touched,status:"active",linked_lore:v.id||b});T="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:b,type:t,title:r,message:"Lore entry recorded successfully",...T?{stream:T}:{},...D?{protocol_suggestion:D}:{}})}}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 p of l.symbols_touched)i[p]=(i[p]||0)+1;let a=Object.entries(i).sort(([,l],[,p])=>p-l).slice(0,10).map(([l,p])=>({symbol:l,count:p})),c$1={};for(let l of s){let p=l.author;c$1[p]||(c$1[p]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c$1[p].count++,l.agent&&(c$1[p].hasAgent=true),l.timestamp>c$1[p].lastActive&&(c$1[p].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:r||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:s.map(Nt),hotSymbols:a,authors:Object.entries(c$1).map(([l,p])=>({id:l,hasAgent:p.hasAgent,entries:p.count,lastActive:p.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:Ot(),assessed_at:new Date().toISOString(),notes:s},c=await h$1(o.rootDir,t,a);try{let k=process.env.PARADIGM_AGENT_ID;if(k&&c&&i.symbols_touched?.length){let{updateExpertiseFromAssessment:w}=await import('./agent-loader-W3RQJVW7.js');w(o.rootDir,k,{symbols_touched:i.symbols_touched,verdict:r});}}catch{}let l=r==="correct"?1:r==="partial"?.5:0,p=i.confidence!=null?l-i.confidence:null,f=p!=null?p>.1?"Under-confident (actual outcome better than predicted)":p<-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:p,deltaDescription:f,message:c?`Assessment recorded: ${r}${p!=null?` (delta: ${p>0?"+":""}${p.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(A=>A.confidence!=null),i=r.length,a=s.length,c={correct:0,partial:0,incorrect:0},l=0,p=0,f=0;for(let A of r){let d=A.assessment.verdict;c[d]++;let _=d==="correct"?1:d==="partial"?.5:0;l+=_,A.confidence!=null&&(p+=A.confidence,f+=Math.abs(_-A.confidence));}let k=i>0?l/i:0,w=a>0?p/a:null,x=a>0?l/i-p/a:null,y=a>0?1-f/a:null,j=e.groupBy,N;if(j&&i>0){let A=new Map;for(let d of r){let _=[];j==="symbol"?_=d.symbols_touched||[]:j==="tag"?_=d.tags||[]:j==="type"&&(_=[d.type||"agent-session"]);for(let O of _)A.has(O)||A.set(O,[]),A.get(O).push(d);}N=Array.from(A.entries()).map(([d,_])=>{let O=_.filter(D=>D.confidence!=null),u={correct:0,partial:0,incorrect:0},P=0,v=0,b=0;for(let D of _){let T=D.assessment.verdict;u[T]++;let S=T==="correct"?1:T==="partial"?.5:0;P+=S,D.confidence!=null&&(v+=D.confidence,b+=Math.abs(S-D.confidence));}return {key:d,total:_.length,accuracyRate:P/_.length,avgConfidence:O.length>0?v/O.length:null,calibrationScore:O.length>0?1-b/O.length:null,verdictBreakdown:u}}).sort((d,_)=>_.total-d.total);}let F=[],$=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 $&&F.push($),y!=null&&(y>=.9?F.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):y>=.7?F.push("Good calibration \u2014 some room for improvement in confidence estimates."):y>=.5?F.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):F.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),x!=null&&(x>.15?F.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):x<-0.15&&F.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>i*.3&&i>=5&&F.push(`High error rate: ${c.incorrect}/${i} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:i,totalWithConfidence:a,accuracyRate:Math.round(k*1e3)/1e3,avgConfidence:w!=null?Math.round(w*1e3)/1e3:null,avgDelta:x!=null?Math.round(x*1e3)/1e3:null,calibrationScore:y!=null?Math.round(y*1e3)/1e3:null,verdictBreakdown:c,...N?{groups:N}:{},insights:F},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 vn(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 Nt(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 Ss(){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 xs(n,e,o){return n==="paradigm_captain_brief"?kn(e,o):n==="paradigm_captain_debrief"?_n(e,o):n==="paradigm_captain_board"?Dn(e,o):{handled:false,text:""}}async function kn(n,e){let o=n.taskDescription,t=n.symbols||[],r=n.depth||"standard",s=E.join(e.rootDir,".paradigm"),i=E.join(s,".cid-session"),a=E.join(s,".cid-briefed");try{I.existsSync(a)&&I.unlinkSync(a);let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r};I.mkdirSync(s,{recursive:!0}),I.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let c=Tn(o),l=[],p=new Set;for(let S of t)if(!p.has(S)){p.add(S);let h=Wt(S);l.push({id:S,type:h,description:"Provided as anchor symbol"});}let f=[];try{for(let S of c.slice(0,3)){let g=m(e.index,S).slice(0,5);for(let m of g)if(!p.has(m.symbol)){p.add(m.symbol);let C=Ln(m.type);l.push({id:m.symbol,type:C,description:m.description||"",file:m.file}),f.push(m.symbol);}}}catch{}let k={directories:[],files:[]};try{let S=await pt("paradigm_navigate",{intent:"context",task:o,response_format:"concise"},e);if(S.handled){let h=JSON.parse(S.text);if(h.files)for(let g of h.files){let m=typeof g=="string"?g:g.path||g.file||"";m&&k.files.push(m);}if(h.directories)for(let g of h.directories){let m=typeof g=="string"?g:g.path||g.directory||"";m&&k.directories.push(m);}if(h.symbols)for(let g of h.symbols){let m=typeof g=="string"?g:g.id;m&&!p.has(m)&&(p.add(m),l.push({id:m,type:Wt(m),description:typeof g=="object"&&g.description||""}));}}}catch{}let w=new Set(k.directories);for(let S of k.files){let h=E.dirname(S);h&&h!=="."&&w.add(h);}let x=l.slice(0,r==="deep"?5:3),y={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(r!=="quick"&&x.length>0)for(let S of x)try{let h=await le("paradigm_ripple",{symbol:S.id,depth:2,response_format:"concise"},e);if(h.handled){let g=JSON.parse(h.text);if(g.analysis){for(let m of g.analysis.directlyAffected||[]){let C=m.symbol||m;C&&!y.affectedSymbols.includes(C)&&y.affectedSymbols.push(C);}for(let m of g.analysis.indirectlyAffected||[])m&&!y.affectedSymbols.includes(m)&&y.affectedSymbols.push(m);}if(g.affectedFlows?.affectedFlows)for(let m of g.affectedFlows.affectedFlows){let C=m.flowId||m;C&&!y.affectedFlows.includes(C)&&y.affectedFlows.push(C);}if(g.affectedGates)for(let m of g.affectedGates){let C=m.gate||m;C&&!y.affectedGates.includes(C)&&y.affectedGates.push(C);}g.impact==="high"&&(y.fragileSymbols.includes(S.id)||y.fragileSymbols.push(S.id));}}catch{}let j=[],N=Wn(o);if(N.length>0)try{let{handleGatesForRoute:S}=await import('./tools-NOMEIBS7.js').catch(()=>({handleGatesForRoute:null})),h=E.join(e.rootDir,"portal.yaml");if(I.existsSync(h)){let g=I.readFileSync(h,"utf8");for(let m of N){let C=g.includes(m);j.push({route:m,gate:"^authenticated",declared:C});}}else for(let g of N)j.push({route:g,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let F=[];if(r!=="quick"&&l.length>0)try{let S=l.slice(0,5).map(g=>g.id),h=await Dt("paradigm_wisdom_context",{symbols:S,include_global:!0},e);if(h.handled){let g=JSON.parse(h.text);if(g.antipatterns)for(let m of g.antipatterns.slice(0,3)){let C=m.pattern||m.description||m.text||String(m);C&&!F.includes(C)&&F.push(C);}if(g.wisdom?.antipatterns)for(let m of g.wisdom.antipatterns.slice(0,3)){let C=m.pattern||m.description||String(m);C&&!F.includes(C)&&F.push(C);}}}catch{}let $={matched:false};try{let S=await Rt("paradigm_protocol_search",{task:o,limit:1},e);if(S.handled){let h=JSON.parse(S.text),g=h.matches||h.protocols||h.results||[];if(g.length>0){let m=g[0];$={matched:!0,id:m.id,name:m.name||m.title,steps:(m.steps||[]).slice(0,5).map(C=>typeof C=="string"?C:C.description||String(C))};}}}catch{}let A=[];if(r!=="quick")try{let S=l[0]?.id,h={limit:r==="deep"?5:3};S&&(h.symbol=S);let g=await je("paradigm_lore_search",h,e);if(g.handled){let C=JSON.parse(g.text).entries||[];for(let B of C.slice(0,3))A.push({id:B.id,summary:(B.summary||B.title||"").slice(0,100),relevance:S?`Related to ${S}`:"Recent project history"});}}catch{}let d=Array.from(w),_=0;for(let S of d){let h=E.join(e.rootDir,S,".purpose");if(I.existsSync(h))try{I.readFileSync(h,"utf8").trim().length>50&&_++;}catch{}}let O$1=d.length>0?_/d.length:.5,u=Hn(O$1),P=Mn(O$1,u,d.length),v=y.affectedSymbols.length+k.files.length,b=v>20?"large":v>8?"medium":v>2?"small":"tiny",D={territory:{directories:d.slice(0,10),files:k.files.slice(0,10),estimatedScope:b},symbols:l.slice(0,10),blastRadius:y,gates:j,protocol:$,warnings:F,coverage:{score:O$1,label:u,note:P},loreRefs:A,archMap:b$2(e.rootDir),renderedBrief:""};D.renderedBrief=Bn(D);try{let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r,coverageScore:O$1};I.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let T=JSON.stringify(D,null,2);return O(T.length,"paradigm_captain_brief"),{handled:true,text:T}}async function _n(n,e){let o=n.orchestrationId,t=n.sessionSummary,r=n.touchedFiles||[],s=n.newSymbols||[],i=n.notes,a=E.join(e.rootDir,".paradigm"),c=E.join(a,".cid-briefed"),l=E.join(a,".pending-review"),p=new Set;for(let b of r){let D=E.dirname(b);D&&D!=="."&&p.add(D);}let f=0,k=p.size;for(let b of p){let D=E.join(e.rootDir,b,".purpose");if(I.existsSync(D))try{I.readFileSync(D,"utf8").trim().length>50&&f++;}catch{}}let w=k>0?f/k:1,x=[],y=[];for(let b of p){let D=E.join(e.rootDir,b,".purpose"),T=E.join(e.rootDir,b),S=false;if(I.existsSync(D))try{S=I.readFileSync(D,"utf8").trim().length>50;}catch{}if(S){if(r.some(g=>E.dirname(g)===b&&s.length>0)){y.push(b);try{let g=JSON.stringify({path:b,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${o}: ${s.join(", ")}`,timestamp:new Date().toISOString()});I.appendFileSync(l,g+`
6
+ `,"utf8");}catch{}}}else try{if(!I.existsSync(T))continue;let h=E.basename(b),g=Jn(h,b,r);I.writeFileSync(D,g,"utf8"),x.push(b),y.push(b);try{let m=JSON.stringify({path:b,reason:"captain-debrief",priority:"high",context:`Touched during orchestration ${o}. Files: ${r.filter(C=>E.dirname(C)===b).join(", ")}`,timestamp:new Date().toISOString()});I.appendFileSync(l,m+`
7
+ `,"utf8");}catch{}}catch{}}let j=0;for(let b of p){let D=E.join(e.rootDir,b,".purpose");if(I.existsSync(D))try{I.readFileSync(D,"utf8").trim().length>50&&j++;}catch{}}let N=k>0?j/k:1,F="";try{let b=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:w,after:N},coverageAdded:x,...i?{notes:i}:{}}},e);if(b.handled){let D=JSON.parse(b.text);F=D.id||D.entry?.id||"";}}catch{}let $={ranThisSession:false,selfHealed:false,blockProposed:false};if($.ranThisSession=jn(a),!$.ranThisSession)try{let{runPostflightLearning:b}=await import('./ambient-OW5M5LVN.js');await b(e.rootDir,{claimant:"navigation"}),$.selfHealed=!0,a$1.flow("$captain-board").info("Cid self-healed postflight (no prior liveness record)",{orchestrationId:o});}catch(b){$.selfHealError=b instanceof Error?b.message:String(b),a$1.flow("$captain-board").warn("Cid postflight self-heal threw \u2014 proposing advise block",{orchestrationId:o,error:$.selfHealError});try{let{handleProposeBlockTool:D}=await import('./propose-block-ZEMEWJQF.js');await D("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 A=false;try{let b={timestamp:new Date().toISOString(),sessionId:o,touchedFiles:r,coverageScore:N};I.mkdirSync(a,{recursive:!0}),I.writeFileSync(c,JSON.stringify(b,null,2),"utf8"),A=!0;}catch{}let d={taskDescription:t,orchestrationId:o,agentContributions:[],coverageDelta:{before:w,after:N},newSymbols:s,touchedFiles:r,notes:i||""};try{let b=E.join(a,"events","session-log.jsonl");if(I.existsSync(b)){let S=I.readFileSync(b,"utf8").split(`
8
+ `).filter(g=>g.trim().length>0).slice(-50),h=new Map;for(let g of S)try{let m=JSON.parse(g),C=m.agentId||m.agent||m.role||"";if(!C)continue;h.has(C)||h.set(C,{contributions:[],symbolsTouched:new Set,patternsObserved:[]});let B=h.get(C),De=m.action||m.event||m.message||"";if(De&&B.contributions.push(String(De).slice(0,120)),Array.isArray(m.symbols))for(let te of m.symbols)B.symbolsTouched.add(String(te));let Re=m.symbol||"";if(Re&&B.symbolsTouched.add(Re),Array.isArray(m.patterns))for(let te of m.patterns)B.patternsObserved.includes(String(te))||B.patternsObserved.push(String(te));}catch{}for(let[g,m]of h.entries())d.agentContributions.push({agentId:g,contribution:m.contributions.slice(-3).join(" | "),symbolsTouched:Array.from(m.symbolsTouched).slice(0,10),patternsObserved:m.patternsObserved.slice(0,5)});}}catch{}let _=d.agentContributions.length;d.agentContributions.length===0&&d.agentContributions.push({agentId:"session",contribution:t.slice(0,200),symbolsTouched:s.slice(0,10),patternsObserved:[]}),_>0&&a$4(e.rootDir,{verdicts:_,source:"debrief"});let O$1={coverageAdded:x,delegatedToDocumentor:y,loreEntryId:F,coverageScore:{before:w,after:N,delta:N-w},stopHookCleared:A,postflight:$,sessionInsights:d},u=["","\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
+ `),v=JSON.stringify(O$1,null,2)+`
10
+ `+u;return O(v.length,"paradigm_captain_debrief"),{handled:true,text:v}}var Cn=E.join("events","settlement-liveness.jsonl"),Pn=360*60*1e3;function jn(n){let e=E.join(n,Cn);if(!I.existsSync(e))return false;try{let t=I.readFileSync(e,"utf8").split(`
11
+ `).filter(s=>s.trim().length>0),r=Date.now()-Pn;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 Dn(n,e){let o=n.action||"read";if(o==="claim")return En(n,e);if(o==="advance")return $n(n,e);let t=await On(e.rootDir,{},e),r=JSON.stringify(t,null,2);return O(r.length,"paradigm_captain_board"),{handled:true,text:r}}function Rn(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 Fn(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 $t(n,e){let o=Lt(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 In=/[#$^!~][a-z][a-z0-9-]*/gi;function Lt(n){let e=new Set;for(let t of n.tags||[])/^[#$^!~]/.test(t)&&e.add(t);let o=n.blurb?.match(In)||[];for(let t of o)e.add(t);return Array.from(e)}async function An(n,e){let o=Lt(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 Tt={high:0,medium:1,low:2};async function On(n,e={},o){let t=o,{loadTasks:r}=await import('./task-loader-LFEE6OU7.js'),s=[];try{s=await r(n,{status:"all",limit:9999});}catch(d){a$1.flow("$captain-board").warn("Board task load failed",{error:d instanceof Error?d.message:String(d)});}let i=s.filter(d=>d.external_ref?.provider==="orchestration"&&!d.parentTaskId&&!d.settledAt),a=[];for(let d of i){let _=Fn(s.filter(u=>u.parentTaskId===d.id)),O=[];for(let u of _){let P=t?await $t(u,t):[];O.push({taskId:u.id,blurb:u.blurb,stage:u.stage,status:u.status,claimant:u.claimant,dependsOn:u.dependsOn||[],fragileSymbols:P});}a.push({epicTaskId:d.id,blurb:d.blurb,runStatus:Rn(d,_),settledAt:d.settledAt,nodes:O});}let c=s.filter(d=>d.status==="open"&&!d.claimant),l=[];for(let d of c){let{score:_,fragile:O}=t?await An(d,t):{score:0,fragile:[]},u;e.proposeClaimants&&(u=await Nn(d,n)),l.push({taskId:d.id,blurb:d.blurb,priority:d.priority,tags:d.tags||[],rippleScore:_,fragileSymbols:O,proposedClaimant:u});}l.sort((d,_)=>{if(_.rippleScore!==d.rippleScore)return _.rippleScore-d.rippleScore;let O=(Tt[d.priority]??1)-(Tt[_.priority]??1);return O!==0?O:_.taskId.localeCompare(d.taskId)});let p=s.filter(d=>d.status==="in-progress").length,f=s.filter(d=>d.status==="open").length,k=new Set(i.map(d=>d.id)),w=new Set(c.map(d=>d.id)),x=[];for(let d of s){if(!d.id||d.status==="done"||d.status==="shelved"||d.parentTaskId||k.has(d.id)||w.has(d.id))continue;let _=t?await $t(d,t):[];x.push({taskId:d.id,blurb:d.blurb,stage:d.stage,status:d.status,claimant:d.claimant,dependsOn:d.dependsOn||[],fragileSymbols:_});}let{validateTaskDag:y}=await import('./task-loader-LFEE6OU7.js'),j=y(s),N=a.filter(d=>!d.settledAt&&d.nodes.length>0&&d.nodes.every(_=>_.status==="done"||_.status==="shelved")).map(d=>({epicTaskId:d.epicTaskId,blurb:d.blurb,reason:"all children terminal but run never settled"})),F=7,$=Date.now(),A=s.filter(d=>d.status==="open"&&d.claimant?.kind==="archetype"&&!d.started_at).map(d=>({task:d,ageDays:Math.floor(($-new Date(d.created).getTime())/864e5)})).filter(({ageDays:d})=>Number.isFinite(d)&&d>=F).map(({task:d,ageDays:_})=>({taskId:d.id,blurb:d.blurb,claimant:d.claimant,ageDays:_}));return {runs:a,unclaimed:l,loose:x,summary:{runs:a.length,open:f,inFlight:p,unclaimed:l.length,loose:x.length},integrity:j.length>0?j:void 0,settlementDebt:N.length>0?N:void 0,staleClaims:A.length>0?A:void 0}}async function Nn(n,e){try{let{suggestAgentsForTask:o,loadAgentsManifest:t}=await import('./orchestration-S2ESNKSA.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 En(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-LFEE6OU7.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 $n(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-LFEE6OU7.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 Tn(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 Wn(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 Wt(n){return n.startsWith("#")?"component":n.startsWith("$")?"flow":n.startsWith("^")?"gate":n.startsWith("!")?"signal":n.startsWith("~")?"aspect":"component"}function Ln(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 Hn(n){return n>=.85?"comprehensive":n>=.6?"reliable":n>=.3?"partial":"sparse"}function Mn(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 Bn(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(p=>p.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 p=n.gates.slice(0,2).map(f=>`${f.route} \u2192 ${f.gate} (${f.declared?"declared \u2713":"UNDECLARED \u2717"})`);e.push(`Gates: ${p.join("; ")}`);}if(n.protocol.matched){let p=n.protocol.steps?.length?` (${n.protocol.steps.length} steps)`:"";e.push(`Protocol: ${n.protocol.name||n.protocol.id}${p} \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
+ `)}function Jn(n,e,o){let r=o.filter(s=>E.dirname(s)===e).slice(0,3).map(s=>`# - ${E.basename(s)}`).join(`
13
+ `);return `# Auto-generated .purpose stub \u2014 created by Cid (captain debrief)
14
+ # Delegate to Scribe (Documentor) for rich documentation
15
+ name: ${n}
16
+ description: "TODO: describe what this directory/module does"
17
+ context:
18
+ - "Stub created by Cid during coverage audit \u2014 update with real context"
19
+ ${r?`# Key files touched:
20
+ ${r}`:""}
21
+ components:
22
+ ${n}:
23
+ description: "TODO: describe this component"
24
+ tags: []
25
+ `}export{is as A,je as B,Ss as C,xs as D,On as E,Nn as F,mn as a,xt as b,xo as c,yn as d,vo as e,hn as f,ko as g,xe as h,Ao as i,fe as j,Oo as k,to as l,pt as m,mt as n,gt as o,yt as p,go as q,le as r,Jo as s,Dt as t,Uo as u,Rt as v,Ko as w,Ce as x,It as y,Qo as z};
@@ -12,6 +12,6 @@ ${i.map((S,v)=>`${v+1}. ${S}`).join(`
12
12
  - Modified files: ${r.length>0?r.join(", "):"(not specified)"}
13
13
  - Symbols touched: ${u.length>0?u.join(", "):"(not specified)"}
14
14
  - Open questions: ${l.length>0?l.join(", "):"(none)"}
15
- `;return W(),{handled:true,text:JSON.stringify({handoff:p,markdownSummary:w,persisted:y,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(o==="paradigm_session_stats"){let s=t.getStats(),i=t.getCostBreakdown(),a=t.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(s.startTime).toISOString(),durationMinutes:a,lastActivity:new Date(s.lastActivity).toISOString()},model:{name:i.model,id:i.modelId,pricing:{inputPerMillion:`$${i.pricing.input.toFixed(2)}`,outputPerMillion:`$${i.pricing.output.toFixed(2)}`}},interactions:{toolCalls:s.totals.toolCallCount,resourceReads:s.totals.resourceReadCount,totalInteractions:s.totals.toolCallCount+s.totals.resourceReadCount},tokens:{total:s.totals.totalTokens,byCategory:{resources:i.resources.tokens,tools:i.tools.tokens}},cost:{totalUsd:`$${i.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${i.resources.costUsd.toFixed(4)}`,tools:`$${i.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:i.resources.byType,toolsByName:i.tools.byName}},null,2)}}if(o==="paradigm_session_recover"){let{checkpoint:s,pendingHandoffs:i,previousSession:a}=z(n.rootDir);if(!a&&i.length===0&&!s)return {handled:true,text:JSON.stringify({found:false,message:"No previous session breadcrumbs, checkpoints, or pending handoffs found.",tip:"Breadcrumbs persist to ~/.paradigm/sessions/ and handoffs persist via paradigm_handoff_prepare. Checkpoints persist via paradigm_session_checkpoint."},null,2)};let r={found:true};if(s){let l=Date.now()-s.timestamp,d=Math.round(l/6e4),c=Math.round(l/36e5);r.checkpoint={phase:s.phase,context:s.context,age:c>1?`${c} hours ago`:`${d} minutes ago`,timestamp:new Date(s.timestamp).toISOString(),sessionId:s.sessionId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:s.recentBreadcrumbs?.map(f=>({time:new Date(f.timestamp).toISOString(),action:f.action,tool:f.tool,symbol:f.symbol,summary:f.summary}))};}if(a){let l=Date.now()-a.lastActivity,d=Math.round(l/6e4),c=Math.round(l/36e5),g=a.breadcrumbs.slice(-10).map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}));r.previousSession={sessionId:a.sessionId,startTime:new Date(a.startTime).toISOString(),lastActivity:new Date(a.lastActivity).toISOString(),age:c>1?`${c} hours ago`:`${d} minutes ago`},r.context={symbolsModified:a.symbolsModified,filesExplored:a.filesExplored},r.recentActions=g;}if(i.length>0){r.pendingHandoffs=i.map(l=>({id:l.id,timestamp:l.timestamp,from:l.from,to:l.to,summary:l.summary,nextSteps:l.nextSteps,modifiedFiles:l.modifiedFiles,symbolsTouched:l.symbolsTouched,openQuestions:l.openQuestions}));for(let l of i)try{c(n.rootDir,l.id);}catch{}}let u="Continue where the previous session left off.";if(s)u=`Previous session was in "${s.phase}" phase: ${s.context}`,s.decisions?.length&&(u+=` Key decisions: ${s.decisions.slice(0,2).join("; ")}`);else if(i.length>0){let l=i[i.length-1];u=`Handoff received: "${l.summary}". `,l.nextSteps.length>0&&(u+=`Start with: ${l.nextSteps[0]}`);}else if(a){let l=a.breadcrumbs.slice(-10);if(l.length>0){let d=l[l.length-1];d.symbol&&(u=`Last work involved ${d.symbol}. Consider checking its current state with paradigm_ripple.`);}}return r.suggestion=u,r.agentInstruction="Present a brief summary of the previous session, then ask the user what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking.",t.markRecovered(),{handled:true,text:JSON.stringify(r,null,2)}}if(o==="paradigm_session_checkpoint"){t.setRootDir(n.rootDir);let s=e.phase,i=e.context,a=e.externalId,r=e.plan,u=e.modifiedFiles,l=e.symbolsTouched,d=e.decisions,{checkpoint:c,persisted:f}=t.saveCheckpoint({phase:s,context:i,externalId:a,plan:r,modifiedFiles:u,symbolsTouched:l,decisions:d}),g=f.local||f.global;return {handled:true,text:JSON.stringify({saved:g,persisted:f,checkpoint:{phase:c.phase,context:c.context,sessionId:c.sessionId,...c.externalId?{externalId:c.externalId}:{},timestamp:new Date(c.timestamp).toISOString(),modifiedFiles:c.modifiedFiles?.length||0,symbolsTouched:c.symbolsTouched?.length||0,decisions:c.decisions?.length||0,recentBreadcrumbs:c.recentBreadcrumbs?.length||0},...g?{note:"Checkpoint saved. Recovery data will be auto-surfaced on the first tool call of the next session."}:{warning:"Checkpoint was NOT persisted to disk. Both local and global writes failed. Check MCP server stderr for details."}},null,2)}}return {handled:false,text:""}}function z(o){let e=j();e.setRootDir(o);let n=e.loadCheckpoint(),t=e.loadPreviousSession(),s=[];try{s=b$1(o);}catch{}return {checkpoint:n,pendingHandoffs:s,previousSession:t}}async function le(o){let{checkpoint:e,pendingHandoffs:n}=z(o);if(!e&&n.length===0)return null;let t=[];if(t.push("--- SESSION RECOVERY ---"),e){let s=Date.now()-e.timestamp,i=Math.round(s/6e4),a=Math.round(s/36e5),r=a>1?`${a}h ago`:`${i}m ago`;t.push(`Previous session was in "${e.phase}" phase (${r}): ${e.context}`),e.modifiedFiles?.length&&t.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&t.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&t.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&t.push(`Plan: ${e.plan.slice(0,200)}`);}if(n.length>0){let s=n[n.length-1];t.push(`Pending handoff: "${s.summary}"`),s.nextSteps.length>0&&t.push(`Next steps: ${s.nextSteps.slice(0,3).join(", ")}`);}try{try{let{reapStaleInProgress:u}=await import('./task-settlement-TATNPY6L.js');await u(o);}catch{}let{assembleCaptainBoard:s,proposeClaimantFor:i}=await import('./captain-CWCLFOXV.js'),a=await s(o,{proposeClaimants:!0}),r=a.unclaimed.slice(0,5);if(a.summary.open>0||a.summary.inFlight>0||a.summary.runs>0){t.push(""),t.push(`Cid (captain): ${a.summary.open} open, ${a.summary.inFlight} in-flight`+(a.summary.runs>0?`, ${a.summary.runs} active run(s)`:"")+`, ${a.summary.unclaimed} unclaimed`);let{updateTask:u,loadTask:l}=await import('./task-loader-HBZ3KRH2.js');for(let d of r){let c=d.tags.length>0?` [${d.tags.join(", ")}]`:"",f=d.proposedClaimant;if(!f){let g=await l(o,d.taskId);g&&(f=await i(g,o));}if(f){try{let g=await l(o,d.taskId);g&&!g.claimant&&g.status==="open"&&await u(o,d.taskId,{claimant:f});}catch{}t.push(` [${d.priority}] ${d.taskId}: ${d.blurb}${c} \u2192 proposed ${f.ref}`);}else t.push(` [${d.priority}] ${d.taskId}: ${d.blurb}${c}`);}}}catch{try{let{loadTasks:s}=await import('./task-loader-HBZ3KRH2.js'),i=await s(o,{status:"open",limit:5});if(i.length>0){t.push(""),t.push("Open tasks:");for(let a of i){let r=a.tags.length>0?` [${a.tags.join(", ")}]`:"";t.push(` [${a.priority}] ${a.id}: ${a.blurb}${r}`);}}}catch{}}try{let{loadLoreEntries:s}=await import('./lore-loader-PXFKMKAN.js'),a=(await s(o,{limit:10})).filter(r=>r.tags?.some(u=>u.startsWith("arc:")));if(a.length>0){let r=new Map;for(let d of a){let c=d.tags?.find(f=>f.startsWith("arc:"))||"";r.set(c,(r.get(c)||0)+1);}let u=e?.symbolsTouched||[];if((u.length>0?a.filter(d=>d.symbols_touched?.some(c=>u.includes(c))):a.slice(0,3)).length>0||r.size>0){t.push(""),t.push("Active lore arcs:");for(let[d,c]of r)t.push(` ${d} (${c} entries)`);}}}catch{}try{let{loadNominations:s}=await import('./nomination-engine-EFXDEPZN.js'),i=s(o,{pending_only:!0}).filter(a=>a.urgency==="critical"||a.urgency==="high");if(i.length>0){t.push(""),t.push("Ambient nominations (urgent):");for(let a of i.slice(0,5))t.push(` [${a.urgency}] ${a.brief}`);i.length>5&&t.push(` ... and ${i.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return t.push(""),t.push("IMPORTANT: Present a brief summary of this recovery data to the user, then ask what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking."),t.push("---"),t.join(`
15
+ `;return W(),{handled:true,text:JSON.stringify({handoff:p,markdownSummary:w,persisted:y,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(o==="paradigm_session_stats"){let s=t.getStats(),i=t.getCostBreakdown(),a=t.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(s.startTime).toISOString(),durationMinutes:a,lastActivity:new Date(s.lastActivity).toISOString()},model:{name:i.model,id:i.modelId,pricing:{inputPerMillion:`$${i.pricing.input.toFixed(2)}`,outputPerMillion:`$${i.pricing.output.toFixed(2)}`}},interactions:{toolCalls:s.totals.toolCallCount,resourceReads:s.totals.resourceReadCount,totalInteractions:s.totals.toolCallCount+s.totals.resourceReadCount},tokens:{total:s.totals.totalTokens,byCategory:{resources:i.resources.tokens,tools:i.tools.tokens}},cost:{totalUsd:`$${i.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${i.resources.costUsd.toFixed(4)}`,tools:`$${i.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:i.resources.byType,toolsByName:i.tools.byName}},null,2)}}if(o==="paradigm_session_recover"){let{checkpoint:s,pendingHandoffs:i,previousSession:a}=z(n.rootDir);if(!a&&i.length===0&&!s)return {handled:true,text:JSON.stringify({found:false,message:"No previous session breadcrumbs, checkpoints, or pending handoffs found.",tip:"Breadcrumbs persist to ~/.paradigm/sessions/ and handoffs persist via paradigm_handoff_prepare. Checkpoints persist via paradigm_session_checkpoint."},null,2)};let r={found:true};if(s){let l=Date.now()-s.timestamp,d=Math.round(l/6e4),c=Math.round(l/36e5);r.checkpoint={phase:s.phase,context:s.context,age:c>1?`${c} hours ago`:`${d} minutes ago`,timestamp:new Date(s.timestamp).toISOString(),sessionId:s.sessionId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:s.recentBreadcrumbs?.map(f=>({time:new Date(f.timestamp).toISOString(),action:f.action,tool:f.tool,symbol:f.symbol,summary:f.summary}))};}if(a){let l=Date.now()-a.lastActivity,d=Math.round(l/6e4),c=Math.round(l/36e5),g=a.breadcrumbs.slice(-10).map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}));r.previousSession={sessionId:a.sessionId,startTime:new Date(a.startTime).toISOString(),lastActivity:new Date(a.lastActivity).toISOString(),age:c>1?`${c} hours ago`:`${d} minutes ago`},r.context={symbolsModified:a.symbolsModified,filesExplored:a.filesExplored},r.recentActions=g;}if(i.length>0){r.pendingHandoffs=i.map(l=>({id:l.id,timestamp:l.timestamp,from:l.from,to:l.to,summary:l.summary,nextSteps:l.nextSteps,modifiedFiles:l.modifiedFiles,symbolsTouched:l.symbolsTouched,openQuestions:l.openQuestions}));for(let l of i)try{c(n.rootDir,l.id);}catch{}}let u="Continue where the previous session left off.";if(s)u=`Previous session was in "${s.phase}" phase: ${s.context}`,s.decisions?.length&&(u+=` Key decisions: ${s.decisions.slice(0,2).join("; ")}`);else if(i.length>0){let l=i[i.length-1];u=`Handoff received: "${l.summary}". `,l.nextSteps.length>0&&(u+=`Start with: ${l.nextSteps[0]}`);}else if(a){let l=a.breadcrumbs.slice(-10);if(l.length>0){let d=l[l.length-1];d.symbol&&(u=`Last work involved ${d.symbol}. Consider checking its current state with paradigm_ripple.`);}}return r.suggestion=u,r.agentInstruction="Present a brief summary of the previous session, then ask the user what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking.",t.markRecovered(),{handled:true,text:JSON.stringify(r,null,2)}}if(o==="paradigm_session_checkpoint"){t.setRootDir(n.rootDir);let s=e.phase,i=e.context,a=e.externalId,r=e.plan,u=e.modifiedFiles,l=e.symbolsTouched,d=e.decisions,{checkpoint:c,persisted:f}=t.saveCheckpoint({phase:s,context:i,externalId:a,plan:r,modifiedFiles:u,symbolsTouched:l,decisions:d}),g=f.local||f.global;return {handled:true,text:JSON.stringify({saved:g,persisted:f,checkpoint:{phase:c.phase,context:c.context,sessionId:c.sessionId,...c.externalId?{externalId:c.externalId}:{},timestamp:new Date(c.timestamp).toISOString(),modifiedFiles:c.modifiedFiles?.length||0,symbolsTouched:c.symbolsTouched?.length||0,decisions:c.decisions?.length||0,recentBreadcrumbs:c.recentBreadcrumbs?.length||0},...g?{note:"Checkpoint saved. Recovery data will be auto-surfaced on the first tool call of the next session."}:{warning:"Checkpoint was NOT persisted to disk. Both local and global writes failed. Check MCP server stderr for details."}},null,2)}}return {handled:false,text:""}}function z(o){let e=j();e.setRootDir(o);let n=e.loadCheckpoint(),t=e.loadPreviousSession(),s=[];try{s=b$1(o);}catch{}return {checkpoint:n,pendingHandoffs:s,previousSession:t}}async function le(o){let{checkpoint:e,pendingHandoffs:n}=z(o);if(!e&&n.length===0)return null;let t=[];if(t.push("--- SESSION RECOVERY ---"),e){let s=Date.now()-e.timestamp,i=Math.round(s/6e4),a=Math.round(s/36e5),r=a>1?`${a}h ago`:`${i}m ago`;t.push(`Previous session was in "${e.phase}" phase (${r}): ${e.context}`),e.modifiedFiles?.length&&t.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&t.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&t.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&t.push(`Plan: ${e.plan.slice(0,200)}`);}if(n.length>0){let s=n[n.length-1];t.push(`Pending handoff: "${s.summary}"`),s.nextSteps.length>0&&t.push(`Next steps: ${s.nextSteps.slice(0,3).join(", ")}`);}try{try{let{reapStaleInProgress:u}=await import('./task-settlement-ZXOY4YGX.js');await u(o);}catch{}let{assembleCaptainBoard:s,proposeClaimantFor:i}=await import('./captain-J4FZ5PRU.js'),a=await s(o,{proposeClaimants:!0}),r=a.unclaimed.slice(0,5);if(a.summary.open>0||a.summary.inFlight>0||a.summary.runs>0){t.push(""),t.push(`Cid (captain): ${a.summary.open} open, ${a.summary.inFlight} in-flight`+(a.summary.runs>0?`, ${a.summary.runs} active run(s)`:"")+`, ${a.summary.unclaimed} unclaimed`);let{updateTask:u,loadTask:l}=await import('./task-loader-EIXPKHA3.js');for(let d of r){let c=d.tags.length>0?` [${d.tags.join(", ")}]`:"",f=d.proposedClaimant;if(!f){let g=await l(o,d.taskId);g&&(f=await i(g,o));}if(f){try{let g=await l(o,d.taskId);g&&!g.claimant&&g.status==="open"&&await u(o,d.taskId,{claimant:f});}catch{}t.push(` [${d.priority}] ${d.taskId}: ${d.blurb}${c} \u2192 proposed ${f.ref}`);}else t.push(` [${d.priority}] ${d.taskId}: ${d.blurb}${c}`);}}}catch{try{let{loadTasks:s}=await import('./task-loader-EIXPKHA3.js'),i=await s(o,{status:"open",limit:5});if(i.length>0){t.push(""),t.push("Open tasks:");for(let a of i){let r=a.tags.length>0?` [${a.tags.join(", ")}]`:"";t.push(` [${a.priority}] ${a.id}: ${a.blurb}${r}`);}}}catch{}}try{let{loadLoreEntries:s}=await import('./lore-loader-PXFKMKAN.js'),a=(await s(o,{limit:10})).filter(r=>r.tags?.some(u=>u.startsWith("arc:")));if(a.length>0){let r=new Map;for(let d of a){let c=d.tags?.find(f=>f.startsWith("arc:"))||"";r.set(c,(r.get(c)||0)+1);}let u=e?.symbolsTouched||[];if((u.length>0?a.filter(d=>d.symbols_touched?.some(c=>u.includes(c))):a.slice(0,3)).length>0||r.size>0){t.push(""),t.push("Active lore arcs:");for(let[d,c]of r)t.push(` ${d} (${c} entries)`);}}}catch{}try{let{loadNominations:s}=await import('./nomination-engine-EFXDEPZN.js'),i=s(o,{pending_only:!0}).filter(a=>a.urgency==="critical"||a.urgency==="high");if(i.length>0){t.push(""),t.push("Ambient nominations (urgent):");for(let a of i.slice(0,5))t.push(` [${a.urgency}] ${a.brief}`);i.length>5&&t.push(` ... and ${i.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return t.push(""),t.push("IMPORTANT: Present a brief summary of this recovery data to the user, then ask what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking."),t.push("---"),t.join(`
16
16
  `)}var T=class{cache=new Map;ttlMs;constructor(e=3e4){this.ttlMs=e;}async getOrCompute(e,n){let t=this.cache.get(e);if(t&&Date.now()-t.createdAt<this.ttlMs)return t.data;let s=await n();return this.cache.set(e,{data:s,createdAt:Date.now()}),s}invalidate(e){this.cache.delete(e);}invalidatePrefix(e){for(let n of this.cache.keys())n.startsWith(e)&&this.cache.delete(n);}clear(){this.cache.clear();}stats(){return {size:this.cache.size,ttlMs:this.ttlMs}}},fe=new T(3e4);var $=".paradigm/personas",B="index.yaml";async function O(o,e){let n=b.join(o,$);if(!m.existsSync(n))return [];let t=m.readdirSync(n).filter(i=>i.endsWith(".persona")),s=[];for(let i of t)try{let a=m.readFileSync(b.join(n,i),"utf8"),r=k.load(a);r&&r.id&&s.push(r);}catch{}return G(s,e)}async function R(o,e){let n=b.join(o,$,`${e}.persona`);if(!m.existsSync(n))return null;try{return k.load(m.readFileSync(n,"utf8"))}catch{return null}}function G(o,e){if(!e)return o;let n=o;return e.tag&&(n=n.filter(t=>t.tags?.includes(e.tag))),e.trigger_type&&(n=n.filter(t=>t.trigger.type===e.trigger_type)),e.gate&&(n=n.filter(t=>t.journey.some(s=>s.gates.includes(e.gate)))),e.flow&&(n=n.filter(t=>t.journey.some(s=>s.flow===e.flow))),e.limit&&(n=n.slice(0,e.limit)),n}async function me(o,e){let n=b.join(o,$);m.mkdirSync(n,{recursive:true});let t=b.join(n,`${e.id}.persona`);if(m.existsSync(t))throw new Error(`Persona ${e.id} already exists`);let s=new Date().toISOString(),i={version:"1.0",id:e.id,name:e.name,description:e.description,traits:e.traits,trigger:e.trigger,fixtures:e.fixtures,tags:e.tags||[],journey:e.journey||[],created:s,updated:s};return m.writeFileSync(t,k.dump(i,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await A(o),e.id}async function H(o,e,n){let t=await R(o,e);if(!t)return false;let s=b.join(o,$,`${e}.persona`),i={...t,...n,id:t.id,version:t.version,created:t.created,updated:new Date().toISOString()};return m.writeFileSync(s,k.dump(i,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await A(o),true}async function ge(o,e){let n=b.join(o,$,`${e}.persona`);if(!m.existsSync(n))return {deleted:false,warnings:[]};let t=[],s=await O(o);for(let i of s)if(i.id!==e){i.trigger.spawned_by?.startsWith(e+".")&&t.push(`Persona ${i.id} is spawned by ${e} \u2014 it will become orphaned`);for(let a of i.journey)a.spawns?.some(r=>r.persona===e)&&t.push(`Persona ${i.id} step ${a.id} spawns ${e} \u2014 spawn will break`);}return m.unlinkSync(n),await A(o),{deleted:true,warnings:t}}async function ye(o,e,n,t){let s=await R(o,e);if(!s)return false;if(s.journey.some(i=>i.id===n.id))throw new Error(`Step ${n.id} already exists in persona ${e}`);if(t){let i=s.journey.findIndex(a=>a.id===t);if(i===-1)throw new Error(`Step ${t} not found in persona ${e}`);s.journey.splice(i+1,0,n);}else s.journey.push(n);return H(o,e,{journey:s.journey})}async function he(o,e,n){let t=await R(o,e);if(!t)return {removed:false,warnings:[]};let s=t.journey.findIndex(r=>r.id===n);if(s===-1)return {removed:false,warnings:[]};let i=t.journey[s],a=[];if(i.produces)for(let r of Object.keys(i.produces)){let u=`{{produces.${r}}}`;for(let l=s+1;l<t.journey.length;l++){let d=t.journey[l];JSON.stringify(d).includes(u)&&a.push(`Step ${d.id} consumes {{produces.${r}}} from this step`);}}if(i.spawns&&i.spawns.length>0)for(let r of i.spawns)a.push(`Step spawns persona ${r.persona} \u2014 spawn chain will break`);return t.journey.splice(s,1),await H(o,e,{journey:t.journey}),{removed:true,warnings:a}}var q=/^[a-z][a-z0-9-]*$/,V=/^[a-z][a-z0-9-]*$/,Q=/^(GET|POST|PUT|PATCH|DELETE)\s+\//;async function we(o,e,n=false){let t=[],s=[];q.test(e.id)||t.push({type:"invalid-id",detail:`ID "${e.id}" must match /^[a-z][a-z0-9-]*$/`}),(!e.name||e.name.trim()==="")&&t.push({type:"missing-name",detail:"Name is required"}),(!e.trigger||!e.trigger.type)&&t.push({type:"missing-trigger",detail:"Trigger with type is required"}),e.trigger.type!=="root"&&!e.trigger.spawned_by&&t.push({type:"missing-spawned-by",detail:`Non-root trigger type "${e.trigger.type}" requires spawned_by`}),(!e.journey||e.journey.length===0)&&t.push({type:"empty-journey",detail:"Journey must have at least one step"});let i=new Set,a=new Set;for(let r of e.journey){V.test(r.id)||t.push({type:"invalid-step-id",step:r.id,detail:"Step ID must match /^[a-z][a-z0-9-]*$/"}),i.has(r.id)&&t.push({type:"duplicate-step-id",step:r.id,detail:`Duplicate step ID "${r.id}"`}),i.add(r.id),Q.test(r.route)||t.push({type:"invalid-route",step:r.id,route:r.route,detail:'Route must match "METHOD /path" (e.g., "POST /api/auth/signup")'}),(!r.gates||r.gates.length===0)&&t.push({type:"missing-gates",step:r.id,detail:"Step must have at least one gate"}),(!r.expect||r.expect.status===void 0)&&t.push({type:"missing-expect",step:r.id,detail:"Step must have expect with status"});let l=JSON.stringify(r).match(/\{\{produces\.([^}]+)\}\}/g)||[];for(let d of l){let c=d.replace("{{produces.","").replace("}}","");a.has(c)||t.push({type:"unresolved-produces",step:r.id,key:c,detail:`{{produces.${c}}} used but not produced by a prior step`});}if(r.produces)for(let d of Object.keys(r.produces))a.add(d);}if(n){let r=b.join(o,"portal.yaml"),u=[],l=[];if(m.existsSync(r))try{let c=k.load(m.readFileSync(r,"utf8"));c.gates&&typeof c.gates=="object"&&(u=Object.keys(c.gates)),c.routes&&typeof c.routes=="object"&&(l=Object.keys(c.routes));}catch{}for(let c of e.journey)for(let f of c.gates)u.length>0&&!u.includes(f)&&t.push({type:"gate-not-found",step:c.id,gate:f,detail:`Gate ${f} not defined in portal.yaml`});for(let c of e.journey)if(l.length>0){let f=c.route;l.some(p=>I(p,f))||s.push({type:"route-not-in-portal",detail:`Route "${f}" (step ${c.id}) not found in portal.yaml`});}for(let c of e.journey)if(c.spawns)for(let f of c.spawns)await R(o,f.persona)||t.push({type:"spawn-target-missing",step:c.id,detail:`Spawn target persona "${f.persona}" does not exist`});let d=await K(o,e.id);if(d&&t.push({type:"spawn-cycle",detail:`Circular spawn dependency: ${d.join(" \u2192 ")}`}),l.length>0||u.length>0){let c=await O(o),f=new Set,g=new Set;for(let S of c)for(let v of S.journey){for(let j of v.gates)f.add(j);g.add(v.route);}let p=[],y=b.join(o,".paradigm","flow-index.json");if(m.existsSync(y))try{let S=JSON.parse(m.readFileSync(y,"utf8"));p=Object.keys(S.flows||{});}catch{}let w=new Set;for(let S of c)for(let v of S.journey)v.flow&&w.add(v.flow);return {persona:e.id,valid:t.length===0,errors:t,warnings:s,coverage:{routes:{covered:g.size,total:l.length,uncovered:l.filter(S=>!g.has(S))},gates:{covered:f.size,total:u.length,uncovered:u.filter(S=>!f.has(S))},flows:{covered:w.size,total:p.length,uncovered:p.filter(S=>!w.has(S))}}}}}return {persona:e.id,valid:t.length===0,errors:t,warnings:s}}function I(o,e){let n=t=>t.replace(/:[a-zA-Z_]+/g,":param").replace(/\{\{[^}]+\}\}/g,":param");return n(o)===n(e)}async function K(o,e){let n=new Set,t=[];async function s(i){if(n.has(i)){let r=t.indexOf(i);return r!==-1?[...t.slice(r),i]:null}n.add(i),t.push(i);let a=await R(o,i);if(a){for(let r of a.journey)if(r.spawns)for(let u of r.spawns){let l=await s(u.persona);if(l)return l}}return t.pop(),null}return s(e)}async function A(o){let e=b.join(o,$);m.mkdirSync(e,{recursive:true});let n=await O(o),t={},s={},i={};for(let c of n){let f=new Set,g=new Set,p=[],y=new Set;for(let w of c.journey){for(let S of w.gates)f.add(S);if(w.flow&&g.add(w.flow),p.push(w.route),w.spawns)for(let S of w.spawns)y.add(S.persona);}t[c.id]={name:c.name,trigger:c.trigger.type,spawned_by:c.trigger.spawned_by,steps:c.journey.length,gates:[...f],flows:[...g],routes:p,spawns:[...y],tags:c.tags||[]};for(let w of f)s[w]||(s[w]=[]),s[w].push(c.id);for(let w of p)i[w]||(i[w]=[]),i[w].push(c.id);}let a=[],r=b.join(o,"portal.yaml");if(m.existsSync(r))try{let c=k.load(m.readFileSync(r,"utf8"));c.routes&&typeof c.routes=="object"&&(a=Object.keys(c.routes).filter(g=>!Object.keys(i).some(p=>I(g,p))));}catch{}let u={},l=b.join(e,"chains");if(m.existsSync(l)){let c=m.readdirSync(l).filter(f=>f.endsWith(".yaml"));for(let f of c)try{let g=m.readFileSync(b.join(l,f),"utf8"),p=k.load(g);if(p&&p.id){let y=p.order.map(v=>v.persona),w=0,S=new Set;for(let v of y){let j=t[v];if(j){w+=j.steps;for(let U of j.gates)S.add(U);}}u[p.id]={description:p.description||"",order:y,total_steps:w,total_gates:S.size};}}catch{}}let d={version:"1.0",generated:new Date().toISOString(),personas:t,chains:u,gate_coverage:s,route_coverage:i,uncovered_routes:a};return m.writeFileSync(b.join(e,B),k.dump(d,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),d}async function be(o){let e=await O(o),n=new Set,t=new Set,s=new Set;for(let d of e)for(let c of d.journey){for(let f of c.gates)n.add(f);t.add(c.route),c.flow&&s.add(c.flow);}let i=[],a=[],r=b.join(o,"portal.yaml");if(m.existsSync(r))try{let d=k.load(m.readFileSync(r,"utf8"));d.gates&&typeof d.gates=="object"&&(i=Object.keys(d.gates)),d.routes&&typeof d.routes=="object"&&(a=Object.keys(d.routes));}catch{}let u=[],l=b.join(o,".paradigm","flow-index.json");if(m.existsSync(l))try{let d=JSON.parse(m.readFileSync(l,"utf8"));u=Object.keys(d.flows||{});}catch{}return {routes:{covered:t.size,total:a.length,uncovered:a.filter(d=>!Array.from(t).some(c=>I(d,c)))},gates:{covered:n.size,total:i.length,uncovered:i.filter(d=>!n.has(d))},flows:{covered:s.size,total:u.length,uncovered:u.filter(d=>!s.has(d))},personas:e.length}}async function Se(o,e){let n=await O(o),t=[];for(let s of n){let i=[],a=[];for(let r of s.journey)if((r.gates.includes(e)||r.flow===e||r.route===e||r.signals?.includes(e))&&(i.push(r.id),r.spawns))for(let l of r.spawns)a.push(l.persona);i.length>0&&t.push({persona:s.id,steps:i,spawns_blocked:a});}return t}function X(o,e){let n=e.split(/[.\[\]]+/).filter(Boolean),t=o;for(let s of n){if(t==null||typeof t!="object")return;t=t[s];}return t}function Y(o,e){let n=[];if(e.status!==o.expect.status&&n.push({type:"status",field:"status",expected:o.expect.status,actual:e.status,message:`Step ${o.id}: status is ${e.status}, expected ${o.expect.status}`}),o.expect.body?.has){let t=e.body;for(let s of o.expect.body.has)(!t||typeof t!="object"||!(s in t))&&n.push({type:"body.has",field:s,expected:true,actual:false,message:`Step ${o.id}: body missing key '${s}'`});}if(o.expect.body?.match){let t=e.body;for(let[s,i]of Object.entries(o.expect.body.match)){let a=t?X(t,s):void 0;JSON.stringify(a)!==JSON.stringify(i)&&n.push({type:"body.match",field:s,expected:i,actual:a??null,message:`Step ${o.id}: '${s}' is ${JSON.stringify(a??null)}, expected ${JSON.stringify(i)}`});}}if(o.signals&&o.signals.length>0){let t=e.signals_fired||[];for(let s of o.signals)t.includes(s)||n.push({type:"signal",field:"signals_fired",expected:s,actual:t,message:`Step ${o.id}: signal '${s}' was not fired`});}if(o.gates.length>0&&e.gates_traversed)for(let t of o.gates)e.gates_traversed.includes(t)||n.push({type:"gate",field:"gates_traversed",expected:t,actual:e.gates_traversed,message:`Step ${o.id}: gate '${t}' was not traversed`});return n}async function xe(o,e={}){let n=[];try{let{SentinelStorage:r}=await import('./dist-VGFSP3XM.js'),u=new r,d=(u.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.complete",scopeValue:o.id,limit:500})||[]).filter(p=>{let y=JSON.parse(p.data_json||"{}");return !(e.run_id&&y.run_id!==e.run_id||e.chain_id&&y.chain_id!==e.chain_id||e.environment&&y.environment!==e.environment)}),f=(u.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.fail",scopeValue:o.id,limit:500})||[]).filter(p=>{let y=JSON.parse(p.data_json||"{}");return !(e.run_id&&y.run_id!==e.run_id||e.chain_id&&y.chain_id!==e.chain_id||e.environment&&y.environment!==e.environment)}),g=new Map;for(let p of [...d,...f]){let y=JSON.parse(p.data_json||"{}");y.step_id&&g.set(y.step_id,y);}for(let p of o.journey){let y=g.get(p.id);if(!y){n.push({step_id:p.id,matched:!1,assertions:[],message:`No Sentinel event found for step '${p.id}' \u2014 step was never exercised`});continue}let w=Y(p,{status:y.status,body:y.body,gates_traversed:y.gates_traversed,signals_fired:y.signals_fired});n.push({step_id:p.id,matched:!0,passed:w.length===0,assertions:w});}}catch{for(let r of o.journey)n.push({step_id:r.id,matched:false,assertions:[],message:"Sentinel unavailable \u2014 cannot validate events"});}let t=n.filter(r=>r.matched).length,s=n.filter(r=>r.passed).length,i=n.filter(r=>r.matched&&!r.passed).length,a=n.reduce((r,u)=>r+u.assertions.length,0);return {run_id:e.run_id,environment:e.environment,steps:n,summary:{total_steps:o.journey.length,matched:t,unmatched:o.journey.length-t,passed:s,failed:i,assertion_failures:a}}}var _=".paradigm/protocols",L="index.yaml";async function E(o){let e=b.join(o,_);if(!m.existsSync(e))return [];let n=m.readdirSync(e).filter(s=>s.endsWith(".protocol")).sort(),t=[];for(let s of n)try{let i=m.readFileSync(b.join(e,s),"utf8"),a=k.load(i);a?.id&&a?.name&&t.push(a);}catch{}return t}async function Z(o,e){let n=e.replace(/^P-/,""),t=b.join(o,_,`${n}.protocol`);if(m.existsSync(t))try{let i=m.readFileSync(t,"utf8");return k.load(i)}catch{return null}return (await E(o)).find(i=>i.id===e)||null}async function Qe(o){let e=b.join(o,_,L);if(!m.existsSync(e))return null;try{let n=m.readFileSync(e,"utf8");return k.load(n)}catch{return null}}async function Ke(o,e,n=3){let t=await E(o);if(t.length===0)return [];let s=te(e);if(s.length===0)return [];let i=[];for(let a of t){let r=0;for(let d of a.trigger){let c=d.toLowerCase();for(let f of s)c.includes(f)&&(r+=3);}for(let d of a.tags){let c=d.toLowerCase();for(let f of s)(c.includes(f)||f.includes(c))&&(r+=2);}let u=a.name.toLowerCase(),l=a.description.toLowerCase();for(let d of s)u.includes(d)&&(r+=1),l.includes(d)&&(r+=1);for(let d of a.steps)if(d.notes){let c=d.notes.toLowerCase();for(let f of s)c.includes(f)&&(r+=.5);}r>0&&i.push({protocol:a,score:r});}return i.sort((a,r)=>r.score-a.score),i.slice(0,n)}async function Xe(o,e){let n=b.join(o,_);m.existsSync(n)||m.mkdirSync(n,{recursive:true});let t=ne(e.name),s=`P-${t}`,i=new Date().toISOString(),a={id:s,name:e.name,description:e.description,trigger:e.trigger,tags:e.tags,symbols:e.symbols||[],exemplar:e.exemplar,steps:e.steps,recorded_from:e.recorded_from,recorded_at:i,last_verified:i,verified_by:e.verified_by||"claude-opus-4-6",status:"current"},r=b.join(n,`${t}.protocol`);return m.writeFileSync(r,k.dump(a,{lineWidth:-1,noRefs:true}),"utf8"),s}async function Ye(o,e,n,t=false){let s=await Z(o,e);if(!s)return false;n.name!==void 0&&(s.name=n.name),n.description!==void 0&&(s.description=n.description),n.trigger!==void 0&&(s.trigger=n.trigger),n.tags!==void 0&&(s.tags=n.tags),n.symbols!==void 0&&(s.symbols=n.symbols),n.exemplar!==void 0&&(s.exemplar=n.exemplar),n.steps!==void 0&&(s.steps=n.steps),n.status!==void 0&&(s.status=n.status),n.verified_by!==void 0&&(s.verified_by=n.verified_by),t&&(s.last_verified=new Date().toISOString(),s.verified_by=n.verified_by||"claude-opus-4-6");let i=e.replace(/^P-/,""),a=b.join(o,_,`${i}.protocol`);return m.writeFileSync(a,k.dump(s,{lineWidth:-1,noRefs:true}),"utf8"),true}function ee(o,e){let n=[],t="current";if(e.exemplar){let s=b.join(o,e.exemplar);m.existsSync(s)?m.statSync(s).mtime.toISOString()>e.last_verified&&(n.push(`Exemplar modified since last verified: ${e.exemplar}`),t!=="broken"&&(t="stale")):(n.push(`Exemplar missing: ${e.exemplar}`),t="broken");}for(let s of e.steps){if(s.template_from){let i=b.join(o,s.template_from);m.existsSync(i)||(n.push(`Template file missing: ${s.template_from}`),t="broken");}if(s.action==="modify"&&s.target){let i=b.join(o,s.target);!s.target.includes("{")&&!m.existsSync(i)&&(n.push(`Modify target missing: ${s.target}`),t="broken");}}return {status:t,issues:n}}async function Ze(o){let e=await E(o),n=[],t=0,s=0,i=0;for(let u of e){let l=ee(o,u);if(u.status!==l.status){u.status=l.status;let d=u.id.replace(/^P-/,""),c=b.join(o,_,`${d}.protocol`);m.existsSync(c)&&m.writeFileSync(c,k.dump(u,{lineWidth:-1,noRefs:true}),"utf8");}switch(l.status){case "current":t++;break;case "stale":s++;break;case "broken":i++;break}n.push({id:u.id,name:u.name,status:l.status,last_verified:u.last_verified,trigger:u.trigger,tags:u.tags});}let a={version:"1.0",generated:new Date().toISOString(),protocols:n,health:{total:e.length,current:t,stale:s,broken:i}},r=b.join(o,_);if(e.length>0){m.existsSync(r)||m.mkdirSync(r,{recursive:true});let u=b.join(r,L);m.writeFileSync(u,k.dump(a,{lineWidth:-1,noRefs:true}),"utf8");}return a}function et(o,e,n){if(!e||e.length<2)return null;let t={};for(let s of e){let i=b.dirname(s);t[i]||(t[i]=[]),t[i].push(s);}for(let[s,i]of Object.entries(t)){if(i.length<2)continue;let a=b.join(o,s);if(!m.existsSync(a))continue;let u=m.readdirSync(a).filter(l=>{let d=b.extname(l);return [".ts",".tsx",".js",".jsx",".rs",".py"].includes(d)}).filter(l=>!i.some(d=>b.basename(d)===l));if(u.length>0){let l=b.join(s,u[0]),d=[...i.map(c=>({action:"create",target:c})),...n.map(c=>({action:"modify",target:c}))];return {hint:`This session created ${i.length} new files in ${s}/ following existing patterns. Consider recording a protocol.`,draft:{name:`Add a ${b.basename(s).replace(/s$/,"")}`,exemplar:l,steps:d}}}}return null}function te(o){return o.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(e=>e.length>1).filter(e=>!se.has(e))}var se=new Set(["a","an","the","is","are","was","were","be","been","to","of","in","for","on","with","at","by","from","it","this","that","and","or","but","if","then","so","as","do","does","did","will","would","can","could","should","may","might","must","shall","i","me","my","we","our","you","your","he","she","how","what","when","where","which","who","whom"]);function ne(o){return o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}
17
17
  export{et as A,re as a,ae as b,ce as c,de as d,le as e,fe as f,O as g,R as h,me as i,H as j,ge as k,ye as l,he as m,we as n,A as o,be as p,Se as q,xe as r,E as s,Z as t,Qe as u,Ke as v,Xe as w,Ye as x,ee as y,Ze as z};
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import {a as a$2}from'./chunk-TYWB5IQJ.js';import {b as b$1,a as a$1}from'./chunk-ASBK55FU.js';import {e}from'./chunk-YXLGVOZO.js';import {a}from'./chunk-FYDRENK7.js';import {f,g,h}from'./chunk-3YM5ABNX.js';import {b,a as a$4}from'./chunk-EK4ZRIFJ.js';import {b as b$2}from'./chunk-EKZDFEJW.js';import {a as a$3,b as b$3}from'./chunk-LPBCQM5Y.js';import {o,t,x}from'./chunk-D6BSCELB.js';import'minimatch';import*as S from'fs';import*as C from'path';import*as W from'js-yaml';import {spawn}from'child_process';var Ae=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","tradeoff","pros and cons","decision"],Ce=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs","changelog","architecture doc"],Ie=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","doesn't work","doesn't","cant","can't","regression","patch"],De=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify","modularize","decouple","split","merge"],$e=["auth","authentication","authorization","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","api key","role","access","gate","portal","sensitive","private","security","vulnerability","xss","sql injection","csrf"],Me=/[@#$%^!?&~][a-zA-Z0-9_-]+/g,me={analysis:{agents:["architect"],models:{architect:"opus"},costMultiplier:{min:.3,max:.5}},documentation:{agents:["architect"],models:{architect:"sonnet"},costMultiplier:{min:.25,max:.45}},bugfix:{agents:["security","builder"],models:{security:"opus",builder:"haiku"},costMultiplier:{min:.5,max:.8}},refactor:{agents:["architect","builder"],models:{architect:"opus",builder:"haiku"},costMultiplier:{min:.6,max:.85}},feature:{agents:["architect","security","builder","tester"],models:{architect:"opus",security:"opus",builder:"haiku",tester:"haiku"},costMultiplier:{min:.8,max:1.2}}};function Fe(h){let t=h.match(Me)||[];return [...new Set(t)]}function U(h,t){let e=h.toLowerCase();return t.filter(s=>e.includes(s.toLowerCase()))}function Be(h,t,e,s){let n=0;e.length>=5?n+=2:e.length>=2&&(n+=1);let i=h.split(/\s+/).length;i>=100?n+=2:i>=50&&(n+=1);let r=new Set(e.map(l=>l[0]));return r.size>=4?n+=2:r.size>=2&&(n+=1),e.some(l=>l.startsWith("^"))&&(n+=1),e.some(l=>l.startsWith("$"))&&(n+=1),t==="feature"&&(n+=1),t==="refactor"&&(n+=1),n>=5?"high":n>=2?"medium":"low"}function _e(h,t,e){if(U(h,$e).length>0||t.some(n=>n.startsWith("^")))return true;return false}function K(h,t){let e=Fe(h),s=U(h,Ae),n=U(h,Ce),i=U(h,Ie),r=U(h,De),l,o;s.length>0&&i.length===0&&r.length===0?(l="analysis",o=s):n.length>0&&i.length===0?(l="documentation",o=n):i.length>0?(l="bugfix",o=i):r.length>0?(l="refactor",o=r):(l="feature",o=[]);let a=me[l],d=_e(h,e),c=[...a.agents];d&&!c.includes("security")&&(c=["security",...c]);let f=Be(h,l,e),p={...a.costMultiplier};return f==="high"?(p.min*=1.2,p.max*=1.3):f==="low"&&(p.min*=.8,p.max*=.9),d&&!a.agents.includes("security")&&(p.min+=.15,p.max+=.2),{type:l,complexity:f,recommendedAgents:c,securityRequired:d,costMultiplier:p,matchedKeywords:o,symbols:e}}function H(h,t){let e=me[t.type];return h==="security"&&t.securityRequired?"opus":e.models[h]||"sonnet"}var Ee=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,Le=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi],je=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"];function ye(h,t$1,e$1){let s=h.toLowerCase(),n=h.match(Ee)||[],i=[...new Set(n)],r=i.map(g=>{let y=t(e$1,g),w=y.length>0?y[0]:null;return {symbol:g,exists:!!w,type:w?.type,description:w?.description}}),l=r.filter(g=>g.exists).map(g=>{let y=x(e$1,g.symbol),w=new Set;for(let F of y){let v=x(e$1,F.symbol);for(let P of v)P.symbol!==g.symbol&&!y.find(ee=>ee.symbol===P.symbol)&&w.add(P.symbol);}let R=y.length+w.size,I="low";return R>10?I="high":R>3&&(I="medium"),{symbol:g.symbol,directDependents:y.length,indirectDependents:w.size,impact:I}}),o=a$3(t$1),a=o.status==="ok"?o.data:null,d={exists:o.status!=="missing",gateCount:a?b$3(a).length:0,gates:a?b$3(a).map(g=>`^${g}`):[],routeCount:a?.routes?Object.keys(a.routes).length:0},c=je.some(g=>s.includes(g)),f=e(t$1),p=f?a$2(h,f.agents).map(g=>({name:g.name,confidence:g.confidence,reason:g.reason})):[],u=[];return r.some(g=>g.exists)&&u.push("ripple-analysis"),c&&u.push("portal-compliance"),i.some(g=>g.startsWith("^"))&&u.push("gate-validation"),i.some(g=>g.startsWith("!"))&&u.push("signal-registration"),u.push("purpose-coverage"),{affectedSymbols:r,rippleAnalysis:l,portalStatus:d,taskAddsRoutes:c,suggestedAgents:p,requiredChecks:u}}function be(h,t$1,e,s){let n=[],i=a$3(e),r=i.status==="ok"?i.data:null,l=r?b$3(r):[],o=r?.routes?Object.keys(r.routes):[];for(let p of h){let u=C.isAbsolute(p)?p:C.join(e,p);if(!S.existsSync(u))continue;let g;try{g=S.readFileSync(u,"utf-8");}catch{continue}for(let y of Le){y.lastIndex=0;let w;for(;(w=y.exec(g))!==null;){let R=w[2]||w[0];R&&R.startsWith("/")&&(!o.some(F=>F.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===R)&&r?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${R}" found in ${C.relative(e,u)} but not declared in portal.yaml`,file:C.relative(e,u),suggestion:"Add this route to portal.yaml with appropriate ^gates. Run paradigm_gates_for_route to get suggestions."}):!r&&R.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${R}" found but no portal.yaml exists`,file:C.relative(e,u),suggestion:"Create portal.yaml to declare gates for API routes. Run: paradigm portal init"}));}}}for(let p of t$1)t(s,p).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${p}" was touched but is not registered in any .purpose file`,suggestion:`Add "${p}" to the nearest .purpose file. Use paradigm_purpose_add_component or paradigm_purpose_add_signal.`});for(let p of t$1)if(p.startsWith("^")){let u=p.slice(1);l.includes(u)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${p}" is referenced but not declared in portal.yaml`,suggestion:`Add ${p} to portal.yaml with description and check expression.`});}h.length>=5&&t$1.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${h.length} files, ${t$1.length} symbols) \u2014 consider recording architectural decisions`,suggestion:"Use paradigm_wisdom_record to capture any decisions or antipatterns discovered during this task."});let a=n.filter(p=>p.severity==="error").length,d=n.filter(p=>p.severity==="warning").length,c=4,f="pass";return a>0?f="violations":d>0&&(f="warnings"),{status:f,violations:n,summary:{totalChecks:c,passed:c-(a>0?1:0)-(d>0?1:0),warnings:d,errors:a},blocksCompletion:a>0}}var qe=".paradigm/events/iteration-revisions.jsonl";function we(h,t){try{let e=C.join(h,qe),s=C.dirname(e);S.existsSync(s)||S.mkdirSync(s,{recursive:!0});let n={timestamp:new Date().toISOString(),type:"iteration-revision",...t};S.appendFileSync(e,JSON.stringify(n)+`
3
- `,"utf8");}catch{}}function ke(h,t){let e=Math.random().toString(36).substring(2,8);return `itrev-${h}-r${t}-${Date.now()}-${e}`}b();async function le(h,t,e,s){let n=new Map,i;try{i=await f(h,{blurb:e,priority:"medium",tags:["orchestration","epic"],claimant:{kind:"archetype",ref:"orchestrator"},external_ref:{provider:"orchestration",ref:t}});try{await g(h,i,{status:"in-progress"});}catch(l){a$4.flow("$cli-task-bridge").warn("Epic promote to in-progress failed",{orchestrationId:t,epicTaskId:i,error:l instanceof Error?l.message:String(l)});}let r=[...s].sort((l,o)=>l.stage-o.stage);for(let l of r)try{let o=(l.dependsOn||[]).map(d=>n.get(d)).filter(d=>typeof d=="string"),a=await f(h,{blurb:l.subtask,priority:"medium",tags:["orchestration"],claimant:{kind:"archetype",ref:l.agent},parentTaskId:i,stage:l.stage,...o.length>0?{dependsOn:o}:{},external_ref:{provider:"orchestration",ref:t}});n.set(l.agent,a);}catch(o){a$4.flow("$cli-task-bridge").warn("Stage task emission failed",{orchestrationId:t,agent:l.agent,stage:l.stage,error:o instanceof Error?o.message:String(o)});}a$4.flow("$cli-task-bridge").info("Emitted CLI orchestration task DAG",{orchestrationId:t,epicTaskId:i,stageTasks:n.size});}catch(r){a$4.flow("$cli-task-bridge").warn("CLI task DAG emission failed; orchestration continues",{orchestrationId:t,error:r instanceof Error?r.message:String(r)});}return {epicTaskId:i,stageTaskIds:n}}async function ce(h,t){if(!t)return false;try{return await g(h,t,{status:"in-progress"})}catch(e){return a$4.flow("$cli-task-bridge").warn("Stage progress update failed (non-fatal)",{taskId:t,error:e instanceof Error?e.message:String(e)}),false}}async function G(h$1,t,e){if(!t)return false;try{return e==="success"?await h(h$1,t):await g(h$1,t,{status:"shelved",shelved:new Date().toISOString()})}catch(s){return a$4.flow("$cli-task-bridge").warn("Stage complete update failed (non-fatal)",{taskId:t,outcome:e,error:s instanceof Error?s.message:String(s)}),false}}b();var Ne=".paradigm/events/estimate-actuals.jsonl";function ue(h,t){try{let e=C.join(h,Ne),s=C.dirname(e);S.existsSync(s)||S.mkdirSync(s,{recursive:!0});let n={archetype:t.archetype,taskType:t.taskType,actualTokens:t.actualTokens,...t.parentTaskId?{parentTaskId:t.parentTaskId}:{},ts:t.ts||new Date().toISOString()};return S.appendFileSync(e,JSON.stringify(n)+`
2
+ import {a as a$2}from'./chunk-TYWB5IQJ.js';import {b as b$1,a as a$1}from'./chunk-DLMDHS2X.js';import {a}from'./chunk-FYDRENK7.js';import {e}from'./chunk-YXLGVOZO.js';import {h,i,j}from'./chunk-MBKTVQS2.js';import {b,a as a$4}from'./chunk-EK4ZRIFJ.js';import {b as b$2}from'./chunk-EKZDFEJW.js';import {a as a$3,b as b$3}from'./chunk-LPBCQM5Y.js';import {o,t,x}from'./chunk-D6BSCELB.js';import'minimatch';import*as S from'fs';import*as C from'path';import*as W from'js-yaml';import {spawn}from'child_process';var Ae=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","tradeoff","pros and cons","decision"],Ce=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs","changelog","architecture doc"],Ie=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","doesn't work","doesn't","cant","can't","regression","patch"],De=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify","modularize","decouple","split","merge"],$e=["auth","authentication","authorization","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","api key","role","access","gate","portal","sensitive","private","security","vulnerability","xss","sql injection","csrf"],Me=/[@#$%^!?&~][a-zA-Z0-9_-]+/g,me={analysis:{agents:["architect"],models:{architect:"opus"},costMultiplier:{min:.3,max:.5}},documentation:{agents:["architect"],models:{architect:"sonnet"},costMultiplier:{min:.25,max:.45}},bugfix:{agents:["security","builder"],models:{security:"opus",builder:"haiku"},costMultiplier:{min:.5,max:.8}},refactor:{agents:["architect","builder"],models:{architect:"opus",builder:"haiku"},costMultiplier:{min:.6,max:.85}},feature:{agents:["architect","security","builder","tester"],models:{architect:"opus",security:"opus",builder:"haiku",tester:"haiku"},costMultiplier:{min:.8,max:1.2}}};function Fe(h){let t=h.match(Me)||[];return [...new Set(t)]}function U(h,t){let e=h.toLowerCase();return t.filter(s=>e.includes(s.toLowerCase()))}function Be(h,t,e,s){let n=0;e.length>=5?n+=2:e.length>=2&&(n+=1);let i=h.split(/\s+/).length;i>=100?n+=2:i>=50&&(n+=1);let r=new Set(e.map(l=>l[0]));return r.size>=4?n+=2:r.size>=2&&(n+=1),e.some(l=>l.startsWith("^"))&&(n+=1),e.some(l=>l.startsWith("$"))&&(n+=1),t==="feature"&&(n+=1),t==="refactor"&&(n+=1),n>=5?"high":n>=2?"medium":"low"}function _e(h,t,e){if(U(h,$e).length>0||t.some(n=>n.startsWith("^")))return true;return false}function K(h,t){let e=Fe(h),s=U(h,Ae),n=U(h,Ce),i=U(h,Ie),r=U(h,De),l,o;s.length>0&&i.length===0&&r.length===0?(l="analysis",o=s):n.length>0&&i.length===0?(l="documentation",o=n):i.length>0?(l="bugfix",o=i):r.length>0?(l="refactor",o=r):(l="feature",o=[]);let a=me[l],d=_e(h,e),c=[...a.agents];d&&!c.includes("security")&&(c=["security",...c]);let f=Be(h,l,e),p={...a.costMultiplier};return f==="high"?(p.min*=1.2,p.max*=1.3):f==="low"&&(p.min*=.8,p.max*=.9),d&&!a.agents.includes("security")&&(p.min+=.15,p.max+=.2),{type:l,complexity:f,recommendedAgents:c,securityRequired:d,costMultiplier:p,matchedKeywords:o,symbols:e}}function H(h,t){let e=me[t.type];return h==="security"&&t.securityRequired?"opus":e.models[h]||"sonnet"}var Ee=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,Le=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi],je=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"];function ye(h,t$1,e$1){let s=h.toLowerCase(),n=h.match(Ee)||[],i=[...new Set(n)],r=i.map(g=>{let y=t(e$1,g),w=y.length>0?y[0]:null;return {symbol:g,exists:!!w,type:w?.type,description:w?.description}}),l=r.filter(g=>g.exists).map(g=>{let y=x(e$1,g.symbol),w=new Set;for(let F of y){let v=x(e$1,F.symbol);for(let P of v)P.symbol!==g.symbol&&!y.find(ee=>ee.symbol===P.symbol)&&w.add(P.symbol);}let R=y.length+w.size,I="low";return R>10?I="high":R>3&&(I="medium"),{symbol:g.symbol,directDependents:y.length,indirectDependents:w.size,impact:I}}),o=a$3(t$1),a=o.status==="ok"?o.data:null,d={exists:o.status!=="missing",gateCount:a?b$3(a).length:0,gates:a?b$3(a).map(g=>`^${g}`):[],routeCount:a?.routes?Object.keys(a.routes).length:0},c=je.some(g=>s.includes(g)),f=e(t$1),p=f?a$2(h,f.agents).map(g=>({name:g.name,confidence:g.confidence,reason:g.reason})):[],u=[];return r.some(g=>g.exists)&&u.push("ripple-analysis"),c&&u.push("portal-compliance"),i.some(g=>g.startsWith("^"))&&u.push("gate-validation"),i.some(g=>g.startsWith("!"))&&u.push("signal-registration"),u.push("purpose-coverage"),{affectedSymbols:r,rippleAnalysis:l,portalStatus:d,taskAddsRoutes:c,suggestedAgents:p,requiredChecks:u}}function be(h,t$1,e,s){let n=[],i=a$3(e),r=i.status==="ok"?i.data:null,l=r?b$3(r):[],o=r?.routes?Object.keys(r.routes):[];for(let p of h){let u=C.isAbsolute(p)?p:C.join(e,p);if(!S.existsSync(u))continue;let g;try{g=S.readFileSync(u,"utf-8");}catch{continue}for(let y of Le){y.lastIndex=0;let w;for(;(w=y.exec(g))!==null;){let R=w[2]||w[0];R&&R.startsWith("/")&&(!o.some(F=>F.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===R)&&r?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${R}" found in ${C.relative(e,u)} but not declared in portal.yaml`,file:C.relative(e,u),suggestion:"Add this route to portal.yaml with appropriate ^gates. Run paradigm_gates_for_route to get suggestions."}):!r&&R.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${R}" found but no portal.yaml exists`,file:C.relative(e,u),suggestion:"Create portal.yaml to declare gates for API routes. Run: paradigm portal init"}));}}}for(let p of t$1)t(s,p).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${p}" was touched but is not registered in any .purpose file`,suggestion:`Add "${p}" to the nearest .purpose file. Use paradigm_purpose_add_component or paradigm_purpose_add_signal.`});for(let p of t$1)if(p.startsWith("^")){let u=p.slice(1);l.includes(u)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${p}" is referenced but not declared in portal.yaml`,suggestion:`Add ${p} to portal.yaml with description and check expression.`});}h.length>=5&&t$1.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${h.length} files, ${t$1.length} symbols) \u2014 consider recording architectural decisions`,suggestion:"Use paradigm_wisdom_record to capture any decisions or antipatterns discovered during this task."});let a=n.filter(p=>p.severity==="error").length,d=n.filter(p=>p.severity==="warning").length,c=4,f="pass";return a>0?f="violations":d>0&&(f="warnings"),{status:f,violations:n,summary:{totalChecks:c,passed:c-(a>0?1:0)-(d>0?1:0),warnings:d,errors:a},blocksCompletion:a>0}}var qe=".paradigm/events/iteration-revisions.jsonl";function we(h,t){try{let e=C.join(h,qe),s=C.dirname(e);S.existsSync(s)||S.mkdirSync(s,{recursive:!0});let n={timestamp:new Date().toISOString(),type:"iteration-revision",...t};S.appendFileSync(e,JSON.stringify(n)+`
3
+ `,"utf8");}catch{}}function ke(h,t){let e=Math.random().toString(36).substring(2,8);return `itrev-${h}-r${t}-${Date.now()}-${e}`}b();async function le(h$1,t,e,s){let n=new Map,i$1;try{i$1=await h(h$1,{blurb:e,priority:"medium",tags:["orchestration","epic"],claimant:{kind:"archetype",ref:"orchestrator"},external_ref:{provider:"orchestration",ref:t}});try{await i(h$1,i$1,{status:"in-progress"});}catch(l){a$4.flow("$cli-task-bridge").warn("Epic promote to in-progress failed",{orchestrationId:t,epicTaskId:i$1,error:l instanceof Error?l.message:String(l)});}let r=[...s].sort((l,o)=>l.stage-o.stage);for(let l of r)try{let o=(l.dependsOn||[]).map(d=>n.get(d)).filter(d=>typeof d=="string"),a=await h(h$1,{blurb:l.subtask,priority:"medium",tags:["orchestration"],claimant:{kind:"archetype",ref:l.agent},parentTaskId:i$1,stage:l.stage,...o.length>0?{dependsOn:o}:{},external_ref:{provider:"orchestration",ref:t}});n.set(l.agent,a);}catch(o){a$4.flow("$cli-task-bridge").warn("Stage task emission failed",{orchestrationId:t,agent:l.agent,stage:l.stage,error:o instanceof Error?o.message:String(o)});}a$4.flow("$cli-task-bridge").info("Emitted CLI orchestration task DAG",{orchestrationId:t,epicTaskId:i$1,stageTasks:n.size});}catch(r){a$4.flow("$cli-task-bridge").warn("CLI task DAG emission failed; orchestration continues",{orchestrationId:t,error:r instanceof Error?r.message:String(r)});}return {epicTaskId:i$1,stageTaskIds:n}}async function ce(h,t){if(!t)return false;try{return await i(h,t,{status:"in-progress"})}catch(e){return a$4.flow("$cli-task-bridge").warn("Stage progress update failed (non-fatal)",{taskId:t,error:e instanceof Error?e.message:String(e)}),false}}async function G(h,t,e){if(!t)return false;try{return e==="success"?await j(h,t):await i(h,t,{status:"shelved",shelved:new Date().toISOString()})}catch(s){return a$4.flow("$cli-task-bridge").warn("Stage complete update failed (non-fatal)",{taskId:t,outcome:e,error:s instanceof Error?s.message:String(s)}),false}}b();var Ne=".paradigm/events/estimate-actuals.jsonl";function ue(h,t){try{let e=C.join(h,Ne),s=C.dirname(e);S.existsSync(s)||S.mkdirSync(s,{recursive:!0});let n={archetype:t.archetype,taskType:t.taskType,actualTokens:t.actualTokens,...t.parentTaskId?{parentTaskId:t.parentTaskId}:{},ts:t.ts||new Date().toISOString()};return S.appendFileSync(e,JSON.stringify(n)+`
4
4
  `,"utf8"),!0}catch(e){return a$4.component("#calibration").warn("estimate-actual capture failed (non-fatal)",{archetype:t.archetype,taskType:t.taskType,error:e instanceof Error?e.message:String(e)}),false}}var Se={architect:"opus",security:"opus",reviewer:"sonnet",builder:"haiku",tester:"haiku"},Ge=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","role","access control","vulnerability","injection","xss","csrf"];function ze(h,t){let e=h.toLowerCase(),s=Ge.some(r=>e.includes(r.toLowerCase())),n=h.includes("^"),i=false;return s||n||i}var Ve=["rename","refactor","migrate","restructure","move","reorganize"];function Ye(h){let t=h.toLowerCase();return Ve.some(e=>t.includes(e))}var Q=class{spawner;auditLogger;rootDir;constructor(t){this.rootDir=t,this.spawner=new b$1(t),this.auditLogger=new a(t);}async initialize(){await this.spawner.initialize();}async orchestrate(t,e={}){let s=e.mode||"faceted",n=Date.now(),i=this.generateOrchestrationId(),r={success:false,mode:s,orchestrationId:i,task:t,agentsSpawned:0,totalTokens:{input:0,output:0,total:0},totalCost:0,duration_ms:0,agentResults:[]};try{let l;if(e.pmGovernance?.enabled)try{let{aggregateFromDirectory:a}=await import('./dist-PW5YPGFF.js'),d=await a(this.rootDir),c=o(d);l=ye(t,this.rootDir,c);}catch{}if(s==="solo"){let a=await this.runSoloMode(t,e,i);r.agentsSpawned=1,r.agentResults=[a],r.success=a.success,a.relay&&(r.totalTokens=a.relay.metrics.tokens_used,r.totalCost=b$2(r.totalTokens,e.orchestratorModel||"opus"));}else {let a=await this.runFacetedMode(t,e,i);r.agentsSpawned=a.results.length,r.agentResults=a.results,r.totalTokens=a.totalTokens,r.totalCost=a.totalCost,r.success=a.success,r.parallelBuilderStats=a.parallelBuilderStats,r.iterationOutcome=a.iterationOutcome;}if(e.pmGovernance?.enabled&&l)try{let{aggregateFromDirectory:a}=await import('./dist-PW5YPGFF.js'),d=await a(this.rootDir),c=o(d),f=[],p=[];for(let g of r.agentResults)g.relay?.outputs?.artifacts&&f.push(...g.relay.outputs.artifacts.map(y=>y.path));for(let g of l.affectedSymbols)p.push(g.symbol);let u=be(f,p,this.rootDir,c);r.complianceReport={preflight:l,postflight:u},e.pmGovernance.blockOnViolations&&u.blocksCompletion&&(r.success=!1);}catch{r.complianceReport={preflight:l};}r.duration_ms=Date.now()-n;let o$1=this.auditLogger.startOrchestration(i,t,s);return o$1.completed=new Date().toISOString(),o$1.status=r.success?"success":"failed",o$1.totals={duration_ms:r.duration_ms,tokens:r.totalTokens.total,cost_usd:r.totalCost,agents_spawned:r.agentsSpawned,files_created:0,files_modified:0},this.auditLogger.saveOrchestration(o$1),r.log=o$1,r}catch(l){return r.error=l instanceof Error?l.message:String(l),r.duration_ms=Date.now()-n,r}}async compare(t,e={}){let s=await this.orchestrate(t,{...e,mode:"solo"}),n=await this.orchestrate(t,{...e,mode:"faceted"}),i=s.totalTokens.total-n.totalTokens.total,r=s.totalCost-n.totalCost,l=s.duration_ms-n.duration_ms,o="tie";return n.success&&!s.success?o="faceted":s.success&&!n.success?o="solo":n.totalCost<s.totalCost*.8?o="faceted":s.totalCost<n.totalCost*.8&&(o="solo"),{solo:s,faceted:n,comparison:{winner:o,tokensSaved:i,costDiff:r,timeDiff:l,soloSucceeded:s.success,facetedSucceeded:n.success}}}async runSoloMode(t,e$1,s){let i=e(this.rootDir)?.team.default_agent||"architect",r=e$1.orchestratorModel||"opus",l;s&&(l=await le(this.rootDir,s,t,[{agent:i,stage:0,subtask:t,dependsOn:[]}]));let o=l?.stageTaskIds.get(i),a={model:r,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.budget,onMessage:e$1.onMessage?c=>e$1.onMessage("solo",c):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart("solo",t,r),await ce(this.rootDir,o);let d=await this.spawner.spawn(i,t,a);return e$1.onAgentComplete&&e$1.onAgentComplete("solo",d,r),d.relay&&ue(this.rootDir,{archetype:i,taskType:K(t).type,actualTokens:d.relay.metrics.tokens_used,parentTaskId:l?.epicTaskId}),await G(this.rootDir,o,d.success?"success":"failure"),d}async runFacetedMode(t,e$1,s){let n=e(this.rootDir);if(!n)return {success:false,results:[],totalTokens:{input:0,output:0,total:0},totalCost:0};let i=K(t).type,r="";if(Ye(t)){let k=a$1(t);if(k.length>0){let b=[];b.push(`## Auto-Ripple Analysis
5
5
  `),b.push("The following symbols are affected by this refactoring:"),b.push("");for(let T of k.slice(0,5))b.push(`- **${T}**: Check dependencies before renaming/moving`);b.push(""),b.push("**Recommendation:** Run `paradigm_ripple` for each symbol before making changes."),r=b.join(`
6
6
  `);}}let l=this.planAgentSequence(t,n.agents),o=this.groupByStage(l),a;if(s){let k=l.map(b=>({agent:b.agent,stage:b.stage,subtask:b.subtask,dependsOn:b.dependsOn}));a=await le(this.rootDir,s,t,k);}let d=new Set,c=[],f={input:0,output:0,total:0},p=0,u=new Map,g=true,y=n.orchestration?.iteration,w=y?.enabled===true,R=l.find(k=>k.agent==="builder")?.subtask,I=l.some(k=>k.agent==="reviewer"),F=l.some(k=>k.agent==="tester"),v=w&&!!R&&I,P,ee=Array.from(o.keys()).sort((k,b)=>k-b);for(let k of ee){let b=o.get(k)||[];if(b.length===0)continue;if(e$1.checkpoints?.beforeAgentSpawn&&e$1.onCheckpoint){let m=b.map(D=>D.agent).join(", ");if(!await e$1.onCheckpoint(`Stage ${k}: Spawn ${m}${b.length>1?" (parallel)":""}`)){g=false;break}}let T=b.map(async m=>{let O=e$1.agentBudgets?.[m.agent]?.maxTokens?"haiku":m.model||Se[m.agent]||"sonnet",D="";if(m.dependsOn.length>0){let _=m.dependsOn.map(te=>u.get(te)).filter(Boolean);_.length>0&&(D=_.join(`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-NRP2KJ6I.js';import'./chunk-TYWB5IQJ.js';import'./chunk-ASBK55FU.js';import'./chunk-ECLUYHAR.js';import'./chunk-YXLGVOZO.js';import'./chunk-FYDRENK7.js';import'./chunk-3YM5ABNX.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-EKZDFEJW.js';import'./chunk-LPBCQM5Y.js';import'./chunk-D6BSCELB.js';import'./chunk-K6TLYNRQ.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as i from'fs';import*as a from'path';import o from'chalk';async function D(l,f,t){let d=f?a.resolve(f):process.cwd();if(!l){t.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(o.red(`
2
+ import {b}from'./chunk-YNFF7XHV.js';import'./chunk-TYWB5IQJ.js';import'./chunk-DLMDHS2X.js';import'./chunk-FYDRENK7.js';import'./chunk-ECLUYHAR.js';import'./chunk-YXLGVOZO.js';import'./chunk-MBKTVQS2.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-EKZDFEJW.js';import'./chunk-LPBCQM5Y.js';import'./chunk-D6BSCELB.js';import'./chunk-K6TLYNRQ.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as i from'fs';import*as a from'path';import o from'chalk';async function D(l,f,t){let d=f?a.resolve(f):process.cwd();if(!l){t.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(o.red(`
3
3
  Orchestration ID required.`)),console.log(o.gray(`Usage: paradigm team diff <orchestration-id>
4
4
  `)));return}let e=new b(d).getOrchestration(l);if(!e){t.json?console.log(JSON.stringify({error:"Orchestration not found",id:l})):console.log(o.red(`
5
5
  Orchestration not found: ${l}