@a-company/paradigm 6.6.6 → 7.0.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 (93) hide show
  1. package/dist/{accept-orchestration-JHDCVHB2.js → accept-orchestration-YO2V2WYA.js} +1 -1
  2. package/dist/{agents-suggest-IKY6VD2R.js → agents-suggest-WZEGQT5E.js} +1 -1
  3. package/dist/ambient-7HBJHJL2.js +2 -0
  4. package/dist/{ambient-FNNFB4AP.js → ambient-OX7YJ4PJ.js} +1 -1
  5. package/dist/ambient-SST5CLEC.js +35 -0
  6. package/dist/captain-YUP3KVCA.js +2 -0
  7. package/dist/chunk-33ERV2MW.js +18 -0
  8. package/dist/chunk-3MZ4J2LF.js +2 -0
  9. package/dist/chunk-47YPID6H.js +142 -0
  10. package/dist/chunk-6AKNXD22.js +32 -0
  11. package/dist/chunk-6HVOZANP.js +4 -0
  12. package/dist/chunk-ACJWUOMA.js +3 -0
  13. package/dist/chunk-B5KLSBOZ.js +2 -0
  14. package/dist/chunk-DLMDHS2X.js +10 -0
  15. package/dist/chunk-FRQRREJ6.js +29 -0
  16. package/dist/{chunk-5RFISGUW.js → chunk-G6DK3ND3.js} +250 -25
  17. package/dist/{chunk-XKNJSPB5.js → chunk-JCGCPAHF.js} +1 -1
  18. package/dist/chunk-K54L6CFR.js +25 -0
  19. package/dist/chunk-QBIQ2FYB.js +20 -0
  20. package/dist/chunk-QEQCPVF5.js +4 -0
  21. package/dist/chunk-ROU3F2HZ.js +6 -0
  22. package/dist/chunk-S4J337EQ.js +504 -0
  23. package/dist/chunk-V6MIKLMY.js +18 -0
  24. package/dist/chunk-WROJSWAO.js +93 -0
  25. package/dist/{chunk-TQOT2LBO.js → chunk-YXLGVOZO.js} +1 -1
  26. package/dist/chunk-ZSWXLFN7.js +12 -0
  27. package/dist/{compliance-J3VOV445.js → compliance-MLG4W6S4.js} +1 -1
  28. package/dist/{diff-ANKTFDRA.js → diff-MC6AXLKX.js} +1 -1
  29. package/dist/{docs-TSAAS4W3.js → docs-3YFNNZRV.js} +1 -1
  30. package/dist/doctor-CBZYYQQH.js +2 -0
  31. package/dist/{hooks-45WDP6QS.js → hooks-AXBWYJ5V.js} +1 -1
  32. package/dist/index.js +4 -4
  33. package/dist/mcp.js +3 -3
  34. package/dist/{migrate-R64OQGSM.js → migrate-5M4KUQ2L.js} +1 -1
  35. package/dist/{nomination-engine-NCLTGMAK.js → nomination-engine-AQHU2KBU.js} +1 -1
  36. package/dist/notebook-loader-6DYFMNJ2.js +2 -0
  37. package/dist/orchestrate-GMYEBA5T.js +8 -0
  38. package/dist/orchestration-G5MAY6IA.js +2 -0
  39. package/dist/propose-block-ZEMEWJQF.js +2 -0
  40. package/dist/{providers-TBPOE4DI.js → providers-5EHD45C6.js} +1 -1
  41. package/dist/reindex-XTRF23F7.js +2 -0
  42. package/dist/{serve-3FMUWW5K.js → serve-SMGWGJLM.js} +1 -1
  43. package/dist/session-tracker-BZ7FU4AT.js +2 -0
  44. package/dist/session-work-log-QXPAXY5K.js +2 -0
  45. package/dist/session-work-log-T2IE4Y4T.js +2 -0
  46. package/dist/{shift-TNA2E5O7.js → shift-JBCEDCGA.js} +2 -2
  47. package/dist/solo-OWR3MX74.js +3 -0
  48. package/dist/{spawn-KKDDR6UR.js → spawn-PHA2SVQ3.js} +1 -1
  49. package/dist/task-loader-IGQQ6ZFL.js +2 -0
  50. package/dist/task-settlement-NW4XMJGJ.js +3 -0
  51. package/dist/{team-PEGP6F7S.js → team-J2YXPEGX.js} +1 -1
  52. package/dist/team-funnel-RAJ6EDG3.js +2 -0
  53. package/dist/tools-HNJ7D5IO.js +2 -0
  54. package/dist/university-content/notes/N-para-801-cid-becomes-real.md +60 -0
  55. package/dist/university-content/notes/N-para-801-falsifiable-self-improvement.md +66 -0
  56. package/dist/university-content/notes/N-para-801-honest-routing-and-the-method.md +57 -0
  57. package/dist/university-content/notes/N-para-801-orchestration-emits-dag.md +60 -0
  58. package/dist/university-content/notes/N-para-801-settlement-closes-the-loop.md +64 -0
  59. package/dist/university-content/notes/N-para-801-the-task-dag.md +93 -0
  60. package/dist/university-content/paths/LP-para-801.yaml +43 -0
  61. package/dist/university-content/quizzes/Q-para-801-cid-becomes-real.yaml +54 -0
  62. package/dist/university-content/quizzes/Q-para-801-falsifiable-self-improvement.yaml +54 -0
  63. package/dist/university-content/quizzes/Q-para-801-honest-routing-and-the-method.yaml +54 -0
  64. package/dist/university-content/quizzes/Q-para-801-orchestration-emits-dag.yaml +54 -0
  65. package/dist/university-content/quizzes/Q-para-801-settlement-closes-the-loop.yaml +54 -0
  66. package/dist/university-content/quizzes/Q-para-801-the-task-dag.yaml +54 -0
  67. package/dist/university-ui/assets/{index-DrtbBC21.js → index-B8hm_MdR.js} +2 -2
  68. package/dist/university-ui/assets/{index-DrtbBC21.js.map → index-B8hm_MdR.js.map} +1 -1
  69. package/dist/university-ui/index.html +1 -1
  70. package/package.json +1 -1
  71. package/dist/ambient-AI42BOM5.js +0 -35
  72. package/dist/chunk-3OXR6F65.js +0 -666
  73. package/dist/chunk-4N56FRNE.js +0 -29
  74. package/dist/chunk-6QXBXZF6.js +0 -3
  75. package/dist/chunk-AMLD7IYC.js +0 -10
  76. package/dist/chunk-DVZWCXB6.js +0 -2
  77. package/dist/chunk-F6E3HW45.js +0 -14
  78. package/dist/chunk-K7X3Z3GL.js +0 -4
  79. package/dist/chunk-LAYBUKMB.js +0 -14
  80. package/dist/chunk-MU5YWTNE.js +0 -24
  81. package/dist/chunk-PMKZMCTS.js +0 -111
  82. package/dist/chunk-XQLO5URP.js +0 -11
  83. package/dist/doctor-L5XZENCF.js +0 -2
  84. package/dist/notebook-loader-3J2OFMS3.js +0 -2
  85. package/dist/orchestrate-UG5QXNAU.js +0 -8
  86. package/dist/reindex-PTIQ2UGY.js +0 -2
  87. package/dist/session-tracker-HHNY6J4I.js +0 -2
  88. package/dist/session-work-log-MEJ33TYD.js +0 -2
  89. package/dist/session-work-log-ZVVJGO7X.js +0 -2
  90. package/dist/task-loader-NZFDTUQ5.js +0 -2
  91. package/dist/tools-PUSDXUYE.js +0 -2
  92. /package/dist/{chunk-HXGYVS2N.js → chunk-ECLUYHAR.js} +0 -0
  93. /package/dist/{platform-server-ANOALDPL.js → platform-server-WIBVYHIV.js} +0 -0
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import {a,O,l as l$1,D as D$1,G as G$1,L,F,K,J,I as I$1,N}from'./chunk-QBIQ2FYB.js';import {a as a$2,d as d$1}from'./chunk-Q527BPUF.js';import {b as b$2}from'./chunk-RGSFU2YW.js';import {m,q,k,n,o,l,i,j as j$1,g}from'./chunk-TMDPDIWA.js';import {f}from'./chunk-KLBH26PA.js';import {j,a as a$3,i as i$1,b as b$1,h as h$1,g as g$2,c,d as d$2}from'./chunk-GRZQIKST.js';import {d,g as g$1,e,h,j as j$2,f as f$1}from'./chunk-ACJWUOMA.js';import {b,a as a$1}from'./chunk-EK4ZRIFJ.js';import*as D from'fs';import*as I from'path';import*as G from'js-yaml';import {execSync}from'child_process';import*as Ot from'os';b();b();var Tt=".paradigm/navigator.yaml";async function nt(n){let e=I.join(n,Tt);if(!D.existsSync(e))return {config:null,configPath:null};try{let o=D.readFileSync(e,"utf8");return {config:G.load(o),configPath:e}}catch(o){return a$1.component("#navigator-loader").error("Error parsing navigator.yaml",{error:o}),{config:null,configPath:e}}}function ot(n,e,o){switch(e.intent){case "find":return Wt(n,e.target||"");case "explore":return Lt(n,e.target||"");case "context":return Ht(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Wt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let r=n.symbols[e];if(r)t.paths.push(r),t.symbols.push(e),t.explanation=`Found symbol ${e} at ${r}`;else {let s=Object.entries(n.symbols).filter(([i])=>i.includes(e.slice(1))).slice(0,5);s.length>0?(t.paths=s.map(([,i])=>i),t.symbols=s.map(([i])=>i),t.explanation=`Found ${s.length} symbols matching "${e}"`):t.explanation=`Symbol ${e} not found in navigator`;}}else {let r=Object.entries(n.symbols).filter(([s])=>s.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(r.length>0)t.paths=r.map(([,s])=>s),t.symbols=r.map(([s])=>s),t.explanation=`Found ${r.length} symbols matching "${e}"`;else {let s=Bt(n,e);s?(t.paths=s.paths,t.explanation=`Found ${e} in structure: ${s.paths.join(", ")}`):t.explanation=`No matches found for "${e}"`;}}return t.suggested_order=we(t.paths,n),t}function Lt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase();for(let[s,i]of Object.entries(n.structure))if(i&&(s.toLowerCase().includes(r)||r.includes(s.toLowerCase()))){t.paths.push(...i.paths);let a=Object.entries(n.symbols).filter(([c])=>c.startsWith(i.symbol)).slice(0,10);t.symbols.push(...a.map(([c])=>c));}for(let[s,i]of Object.entries(n.key_files))s.toLowerCase().includes(r)&&t.paths.push(...i);if(t.paths.length===0){let s=Object.entries(n.symbols).filter(([i,a])=>i.toLowerCase().includes(r)||a.toLowerCase().includes(r)).slice(0,10);t.paths=[...new Set(s.map(([,i])=>i))],t.symbols=s.map(([i])=>i);}return t.explanation=`Exploration paths for "${e}": ${t.paths.length} locations, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Ht(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase(),s=Mt(r);for(let[i,a]of Object.entries(n.structure))a&&s.some(c=>i.toLowerCase().includes(c))&&t.paths.push(...a.paths);for(let[i,a]of Object.entries(n.symbols)){let c=i.slice(1).toLowerCase();s.some(l=>c.includes(l)||l.includes(c))&&(t.paths.push(a),t.symbols.push(i));}return t.paths.push(...n.key_files.config),t.paths=[...new Set(t.paths)],t.symbols=[...new Set(t.symbols)],r.includes("test")?t.skip=n.skip_patterns.always:t.skip=[...n.skip_patterns.always,...n.skip_patterns.unless_testing],!r.includes("doc")&&!r.includes("readme")&&t.skip.push(...n.skip_patterns.unless_docs),t.explanation=`Context for "${e}": ${t.paths.length} relevant files, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Bt(n,e){let o=e.toLowerCase();for(let[t,r]of Object.entries(n.structure))if(r&&(t.toLowerCase().includes(o)||o.includes(t.toLowerCase())))return r;return null}function Mt(n){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return n.split(/\s+/).map(o=>o.replace(/[^a-z0-9]/g,"")).filter(o=>o.length>2&&!e.has(o))}function we(n,e){let o={};for(let t of n){let r=0;e.key_files.config.some(s=>t.includes(s))&&(r+=100),e.key_files.entry.some(s=>t.includes(s))&&(r+=80),e.key_files.types.some(s=>t.includes(s))&&(r+=60),r-=t.split("/").length*2,o[t]=r;}return [...n].sort((t,r)=>(o[r]||0)-(o[t]||0))}b();function Jt(n){let e=I.resolve(n),o=D.readFileSync(e,"utf8"),t=G.load(o);if(!t||typeof t!="object")throw new Error(`Invalid workspace file: ${n}`);let r={version:String(t.version||"1.0"),name:String(t.name||"unnamed-workspace"),members:[]};if(Array.isArray(t.members)){for(let s of t.members)if(typeof s=="object"&&s!==null){let i=s;r.members.push({name:String(i.name||""),path:String(i.path||""),role:i.role,exports:Array.isArray(i.exports)?i.exports.map(String):void 0});}}return r}function rt(n,e){let o=I.resolve(n),t=I.resolve(o,e);if(!D.existsSync(t))return a$1.component("#workspace-loader").warn("Workspace file not found",{workspacePath:t}),null;let r;try{r=Jt(t);}catch(c){return a$1.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let s=I.dirname(t),i="";for(let c of r.members){let l=I.resolve(s,c.path);if(st(l)===st(o)){i=c.name;break}}if(!i)return a$1.component("#workspace-loader").warn("Current directory is not a member of workspace",{workspace:r.name}),null;let a=new Map;for(let c of r.members){if(c.name===i)continue;let l=I.resolve(s,c.path),d=I.join(l,".paradigm","scan-index.json");if(!D.existsSync(d)){a$1.component("#workspace-loader").warn("No scan-index.json for workspace member",{member:c.name,scanIndexPath:d});continue}try{let p=JSON.parse(D.readFileSync(d,"utf8")),m=Ut(p);c.exports&&c.exports.length>0&&(m=Gt(m,c.exports));let h=null,x=I.join(l,"portal.yaml");if(D.existsSync(x))try{let f=D.readFileSync(x,"utf8"),P=G.load(f);P&&(h=P);}catch{}a.set(c.name,{index:m,gateConfig:h});}catch(p){a$1.component("#workspace-loader").warn("Could not load index for workspace member",{member:c.name,error:p.message});}}return {config:r,workspacePath:t,currentMember:i,siblingIndices:a}}function Gt(n,e){let t=q(n).filter(r=>{let s=r.symbol;return e.some(i=>qt(i,s))});return zt(t)}function qt(n,e){let o=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${o}$`,"i").test(e)}function xe(n,e){let o=[];for(let[t,r]of n.siblingIndices){let s=m(r.index,e);for(let i of s)o.push({project:t,symbol:`${t}/${i.symbol}`,type:i.type,description:i.description,filePath:i.filePath});}return o}function it(n,e){let o=[],t=e.includes("/")?e.split("/").pop():e;for(let[r,s]of n.siblingIndices){let i=[],a=q(s.index);for(let c of a){let l=c.references||[],d=c.description||"",p=l.some(h=>h===t||h===e||h.endsWith(`/${t}`)),m=d.includes(t);(p||m)&&i.push({symbol:c.symbol,type:c.type,description:c.description});}i.length>0&&o.push({project:r,references:i});}return o}function st(n){return I.resolve(n).replace(/\/+$/,"")}function Ut(n){let e={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"},o=[];for(let[t,r]of Object.entries(e)){let s=n[t];if(!(!s||typeof s!="object"))for(let[i,a]of Object.entries(s)){let c={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"}[r]||"#";o.push({id:i,symbol:a.symbol||`${c}${i}`,type:r,source:"purpose",filePath:a.path||"",data:{},references:a.related||[],referencedBy:[],description:a.description,tags:a.visualTags||[]});}}return j$1({symbols:o,purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}function zt(n){return j$1({symbols:n.map(e=>({id:e.id||e.symbol.replace(/^[#$^!~]/,""),symbol:e.symbol,type:e.type,source:"purpose",filePath:e.filePath||"",data:e.data||{},references:e.references||[],referencedBy:e.referencedBy||[],description:e.description,tags:e.tags})),purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}var Vt={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function Zn(){return [Vt]}async function lt(n,e,o){if(n!=="paradigm_navigate")return {handled:false,text:""};let t={intent:e.intent||"find",target:e.target,task:e.task},r=await nt(o.rootDir);if(r.config||(r={config:Kt(o),configPath:null}),false);if(t.intent==="context"&&!t.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((t.intent==="find"||t.intent==="explore")&&!t.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${t.intent} intent`,example:t.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let s=`navigate:${t.intent}:${t.target||""}:${t.task||""}`,i=await a.getOrCompute(s,()=>{let c=ot(r.config,t,o.rootDir),l={intent:t.intent,...t.target&&{target:t.target},...t.task&&{task:t.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(r.config?.auto_generated&&(l.auto_generated=true,l.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(l.note="No paths found.",l.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(l.tip=l.tip||"Many paths returned. Start with suggested_order for efficient exploration."),o.workspace){if(t.intent==="find"&&t.target&&c.paths.length===0){let d=xe(o.workspace,t.target);d.length>0&&(l.workspaceResults=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(t.intent==="context"&&t.task){let d=xe(o.workspace,t.task);d.length>0&&(l.workspaceContext=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})));}}return JSON.stringify(l,null,2)}),a$1=i;if(e.response_format==="concise")try{let c=JSON.parse(i);delete c.skip,delete c.tip,delete c.note,delete c.recovery,delete c.workspaceResults,delete c.workspaceContext,delete c.auto_generated,a$1=JSON.stringify(c,null,2);}catch{}try{let c=I.join(o.rootDir,".paradigm",".nav-called");D.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a$1}}function Kt(n){let e={},o={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},t=q(n.index),r=new Set;for(let a of t)if(a.filePath){e[a.symbol]=a.filePath,r.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":o.features.paths.includes(c)||o.features.paths.push(c);break;case "component":o.components.paths.includes(c)||o.components.paths.push(c);break;case "gate":o.gates.paths.includes(c)||o.gates.paths.push(c);break;case "flow":o.flows.paths.includes(c)||o.flows.paths.push(c);break}}let s=[],i=[];for(let a of n.aggregation.purposeFiles)s.push(a.filePath);return s.push(".paradigm/config.yaml"),n.gateConfig&&s.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:o,key_files:{config:s.slice(0,10),entry:i,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}function pt(n,e,o={}){let{maxResults:t=20}=o,r=[],s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=[`rg -n --no-heading "${s}" "${n}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${s}" "${n}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of i)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return r;let c=a.trim().split(`
3
+ `);for(let l of c.slice(0,t)){let d=l.match(/^(.+?):(\d+):(.*)$/);if(d){let[,p,m,h]=d,x=I.relative(n,p),f="unknown";x.includes(".purpose")||x.includes("portal.yaml")?f="purpose":h.includes("//")||h.includes("#")||h.includes("*")?f="comment":f="code",r.push({filePath:x,line:parseInt(m,10),content:h.trim().slice(0,200),context:f});}}return r}b();var Yt=30*1e3,ft=new Map;async function mt(n){let e=I.resolve(n),o=ft.get(e);if(o&&Date.now()-o.loadedAt<Yt)return o.index;let t=await Xt(e);return t&&ft.set(e,{index:t,loadedAt:Date.now()}),t}async function Xt(n){let e=I.join(n,".paradigm","flow-index.json");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return JSON.parse(o)}catch(o){return a$1.component("#flow-loader").error("Error parsing flow-index.json",{error:o}),null}}function Zt(n,e){let o=n.symbolToFlows[e]||[],t=[];for(let r of o){let s=n.flows[r];if(!s)continue;let i=s.steps.map((a,c)=>({step:a,index:c})).filter(({step:a})=>a.symbol===e);for(let{step:a,index:c}of i){let l=s.steps.slice(c+1).map(d=>d.id);t.push({flowId:s.id,definedIn:s.definedIn,description:s.description,trigger:s.trigger,stepAffected:{id:a.id,action:a.action,position:c+1},downstreamSteps:l,validation:s.validation});}}return t}function ut(n,e){let o=Zt(n,e),t=new Set;for(let i of o)i.validation?.command&&t.add(i.validation.command);let r="low",s=o.reduce((i,a)=>i+a.downstreamSteps.length,0);return o.length>3||s>10?r="high":(o.length>1||s>3)&&(r="medium"),{symbol:e,totalFlows:o.length,impactLevel:r,affectedFlows:o,validationCommands:Array.from(t),suggestion:o.length>0?`Changes to ${e} may affect ${o.length} flow(s). ${t.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function mo(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["dependencies","impact","blast radius","what would break","dependents","affects"]}]}async function le(n$1,e,o$1){if(n$1!=="paradigm_ripple")return {handled:false,text:""};let{symbol:t,depth:r=3,includeWorkspace:s=false,response_format:i}=e,a=k(o$1.index,t);if(!a){let w=en(o$1.rootDir,t);return O(w.length,n$1),{handled:true,text:w}}let c=Math.min(Math.max(r||3,1),5),l$2=n(o$1.index,t),d=new Set([t]),p=new Map;function m(w,v){if(v>=c)return;let u=[];for(let k of w){if(d.has(k))continue;d.add(k);let N=n(o$1.index,k);for(let T of N)d.has(T.symbol)||u.push(T.symbol);}u.length>0&&(p.set(v+1,u),m(u,v+1));}m(l$2.map(w=>w.symbol),1);let h=new Set;for(let[,w]of p)for(let v of w)v!==t&&!l$2.find(u=>u.symbol===v)&&h.add(v);let x=o(o$1.index,t),f=l$2.length+h.size,P="low";f>10?P="high":f>3&&(P="medium");let A=await mt(o$1.rootDir),R=null;if(A){let w=ut(A,t);w.totalFlows>0&&(w.impactLevel==="high"&&P==="low"?P="medium":w.impactLevel==="high"&&(P="high"),R={totalFlows:w.totalFlows,affectedFlows:w.affectedFlows.map(v=>({flowId:v.flowId,impactLevel:v.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${v.stepAffected.position}, affects ${v.downstreamSteps.length} downstream steps`})),validationSuggestion:w.validationCommands.length>0?`Run: ${w.validationCommands[0]}`:void 0});}let $=new Set([t,...l$2.map(w=>w.symbol),...h]),F=[];try{let w=l(o$1.index,"gate");for(let v of w)$.has(v.symbol)&&F.push({gate:v.symbol,description:v.description});for(let v of l$2)v.type==="gate"&&!F.find(u=>u.gate===v.symbol)&&F.push({gate:v.symbol,description:v.description});}catch{}let C={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:P,analysis:{directlyAffected:l$2.map(w=>({symbol:w.symbol,type:w.type,description:w.description})),indirectlyAffected:Array.from(h),indirectByLevel:Object.fromEntries(p),dependsOn:x.map(w=>({symbol:w.symbol,type:w.type}))},summary:{directCount:l$2.length,indirectCount:h.size,totalAffected:f,dependsOnCount:x.length,levelsAnalyzed:c},recommendation:tn(P)};R&&(C.affectedFlows=R),F.length>0&&(C.affectedGates=F),C.suggestedReviewScope=nn(P,l$2.length,h.size,F.length,R?.totalFlows??0);try{let w=await l$1(o$1.rootDir,t);w.length>0&&(C.personas_affected=w,w.length>2&&P==="low"&&(C.impact="medium"));}catch{}try{let w=D$1(o$1.rootDir,t);w.length>0&&(C.university_content_affected=w.map(v=>({id:v.id,title:v.title,type:v.type,stale:v.stale})));}catch{}if(s&&o$1.workspace){let w=it(o$1.workspace,t);if(w.length>0){C.workspaceImpact={siblings:w.map(u=>({project:u.project,references:u.references.map(k=>({symbol:k.symbol,type:k.type,description:k.description}))}))};let v=w.reduce((u,k)=>u+k.references.length,0);v>0&&P==="low"&&(C.impact="medium"),v>5&&(C.impact="high");}}let O$1=i==="concise"?{symbol:C.symbol,impact:C.impact,summary:C.summary}:C,E=JSON.stringify(O$1,null,2);return O(E.length,n$1),{handled:true,text:E}}function en(n,e){let o=pt(n,e,{maxResults:20});if(o.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let t=[...new Set(o.map(i=>i.filePath))],r={};for(let i of o)r[i.context]=(r[i.context]||0)+1;let s="low";return t.length>10||o.length>20?s="high":(t.length>3||o.length>5)&&(s="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:s,analysis:{filesAffected:t.slice(0,10),totalFilesAffected:t.length,totalReferences:o.length,contextBreakdown:r,sampleReferences:o.slice(0,5).map(i=>({file:i.filePath,line:i.line,preview:i.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function tn(n){switch(n){case "high":return "High impact change - review all affected symbols carefully before modifying";case "medium":return "Moderate impact - check direct dependencies for breaking changes";case "low":return "Low impact - safe to modify with standard review"}}function nn(n,e,o,t,r){let s=[];return e>0&&s.push(`Review ${e} direct dependent(s) for breaking changes`),o>0&&s.push(`Scan ${o} indirect dependent(s) for cascading effects`),t>0&&s.push(`Verify ${t} affected gate(s) still enforce correct auth/access`),r>0&&s.push(`Validate ${r} affected flow(s) end-to-end`),n==="high"?s.push("Consider running full test suite before merging"):n==="medium"&&s.push("Run targeted tests for affected components"),s.length===0&&s.push("No downstream dependents detected - safe to proceed"),s}b();b();var on=30*1e3,ve=new Map,yt=".paradigm/wisdom";async function ht(n){let e=I.resolve(n),o=ve.get(e);if(o&&Date.now()-o.loadedAt<on)return o.context;let t=await sn(e);return ve.set(e,{context:t,loadedAt:Date.now()}),t}async function sn(n){let e$1=I.join(n,yt),o=D.existsSync(e$1),[t,r,s,i]=o?await Promise.all([rn(e$1),an(e$1),cn(e$1),ln(e$1)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e(),l=f$1();}catch{}let d$1=new Set(r.map(f=>f.id)),p=r.map(f=>({...f,scope:"project"}));for(let f of a)d$1.has(f.id)||p.push({...f,scope:"global"});let m=new Set(i.map(f=>f.id)),h=i.map(f=>({...f,scope:"project"}));for(let f of c)m.has(f.id)||h.push({...f,scope:"global"});let x=t;if(l&&!t)x=l;else if(l&&t){let f={...t.by_symbol};if(l.by_symbol)for(let[P,A]of Object.entries(l.by_symbol))f[P]||(f[P]=A);x={...t,by_symbol:f,global:{...l.global,...t.global}};}return {preferences:x,antipatterns:p,decisions:h,expertise:s}}function z(n){let e=I.resolve(n);ve.delete(e);}async function rn(n){let e=I.join(n,"preferences.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return G.load(o)}catch(o){return a$1.component("#wisdom-loader").error("Error parsing preferences.yaml",{error:o}),null}}async function an(n){let e=I.join(n,"antipatterns.yaml");if(!D.existsSync(e))return [];try{let o=D.readFileSync(e,"utf8");return G.load(o).antipatterns||[]}catch(o){return a$1.component("#wisdom-loader").error("Error parsing antipatterns.yaml",{error:o}),[]}}async function cn(n){let e=I.join(n,"expertise.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return G.load(o)}catch(o){return a$1.component("#wisdom-loader").error("Error parsing expertise.yaml",{error:o}),null}}var gt=new Set;async function ln(n){let e=I.join(n,"decisions");if(!D.existsSync(e))return [];let o=[];try{let t=D.readdirSync(e);t.some(s=>s.endsWith(".yaml")||s.endsWith(".yml"))&&!gt.has(e)&&(gt.add(e),a$1.component("#wisdom-loader").warn("wisdom-decisions found; run `paradigm migrate decisions` in v6.0. In v5.39.0 wisdom-decisions are still read but will be migrated to TD-streams in v6.0."));for(let s of t){if(!s.endsWith(".yaml")&&!s.endsWith(".yml"))continue;let i=I.join(e,s);try{let a=D.readFileSync(i,"utf8"),c=G.load(a);o.push(c);}catch(a){a$1.component("#wisdom-loader").error(`Error parsing ${s}`,{error:a});}}}catch(t){a$1.component("#wisdom-loader").error("Error reading decisions directory",{error:t});}return o.sort((t,r)=>t.id.localeCompare(r.id)),o}function bt(n,e){return e.map(o=>dn(n,o))}function dn(n,e){let o=n.preferences?.by_symbol?.[e]||null,t=n.antipatterns.filter(i=>i.symbols.some(a=>a===e||de(e,a))),r=n.decisions.filter(i=>i.symbols.some(a=>a===e||de(e,a))),s=n.expertise?.experts.filter(i=>i.symbols?.some(a=>a===e||de(e,a)))||[];return {symbol:e,preferences:o,antipatterns:t,decisions:r,experts:s}}function wt(n,e){return n.expertise?n.expertise.experts.filter(o=>!!(e.symbol&&o.symbols&&o.symbols.some(t=>t===e.symbol||de(e.symbol,t))||e.area&&o.areas&&o.areas.some(t=>t.toLowerCase().includes(e.area.toLowerCase())))):[]}function de(n,e){if(e.endsWith("*")){let o=e.slice(0,-1);return n.startsWith(o)}return n===e}async function St(n,e){let o=I.join(n,yt),t=I.join(o,"antipatterns.yaml");D.existsSync(o)||D.mkdirSync(o,{recursive:true});let r={version:"1.0",antipatterns:[]};if(D.existsSync(t))try{let s=D.readFileSync(t,"utf8"),i=G.load(s);i&&typeof i=="object"&&(r={version:i.version||"1.0",antipatterns:Array.isArray(i.antipatterns)?i.antipatterns:[]});}catch{}r.antipatterns.push({...e,added:new Date().toISOString()}),D.writeFileSync(t,G.dump(r,{lineWidth:-1})),z(n);}b();var xt=".paradigm/history";async function vt(n){let e=I.join(n,xt);if(!D.existsSync(e))return {index:null,validation:null};let[o,t]=await Promise.all([pn(e),fn(e)]);return {index:o,validation:t}}async function pn(n){let e=I.join(n,"index.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return G.load(o)}catch(o){return a$1.component("#history-loader").error("Error parsing index.yaml",{error:o.message}),null}}async function fn(n){let e=I.join(n,"validation.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return G.load(o)}catch(o){return a$1.component("#history-loader").error("Error parsing validation.yaml",{error:o.message}),null}}function wo(n,e){return e.map(o=>mn(n,o))}function mn(n,e){let o=n.index?.by_symbol?.[e]||null,t=[];if(n.index?.co_changes){for(let s of n.index.co_changes)if(s.symbols.includes(e))for(let i of s.symbols)i!==e&&!t.includes(i)&&t.push(i);}let r=n.validation?.by_symbol?.[e]||null;return {symbol:e,summary:o,recent:o?.recent||[],co_changes:t,validation:r}}function So(n,e){let o=[],t=[];if(!n.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let i of e){let a=n.index.by_symbol?.[i];a&&(a.fragility==="high"||a.fragility==="critical")&&o.push({symbol:i,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=n.index.fragile_symbols?.find(l=>l.symbol===i);c&&!o.find(l=>l.symbol===i)&&o.push(c);}for(let i of e){let a=n.index.co_changes?.filter(c=>c.symbols.includes(i));if(a?.length)for(let c of a){let l=c.symbols.filter(d=>d!==i&&!e.includes(d));l.length>0&&c.correlation>.7&&t.push(`${i} often changes with ${l.join(", ")} (${Math.round(c.correlation*100)}% correlation)`);}}let r=o.filter(i=>i.fragility==="critical").length===0,s=[];return o.length>0&&(s.push("Consider adding extra test coverage before modifying fragile symbols"),s.push("Review recent rollbacks and failures for these symbols")),t.length>0&&s.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:o,warnings:t,safe_to_modify:r,recommendations:s}}async function un(n,e){let o=I.join(n,xt),t=I.join(o,"log.jsonl");D.existsSync(o)||D.mkdirSync(o,{recursive:true});let r=gn(t),s=new Date().toISOString(),i={id:r,ts:s,...e},a=JSON.stringify(i)+`
4
+ `;return D.appendFileSync(t,a),r}async function xo(n,e,o,t){return un(n,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:o,tests:t})}function gn(n){let e=1;return D.existsSync(n)&&(e=D.readFileSync(n,"utf8").split(`
5
+ `).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}async function Fo(n){let e=I.resolve(n),o=await i(e),t=j$1(o),r=null,s=I.join(e,"portal.yaml");if(D.existsSync(s))try{r=await g(s);}catch(d){let p=d?.name??"Error";a$1.component("#index-loader").warn("Could not parse portal.yaml",{errorClass:p});}let i$1=I.basename(e),a=I.join(e,".premise");if(D.existsSync(a))try{let p=D.readFileSync(a,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);p&&(i$1=p[1].trim());}catch{}let c=null,l=I.join(e,".paradigm","config.yaml");if(D.existsSync(l))try{let d=D.readFileSync(l,"utf8"),p=G.load(d);p&&typeof p=="object"&&(p.version||a$1.component("#index-loader").warn('config.yaml missing "version" field'),p.project||a$1.component("#index-loader").warn('config.yaml missing "project" field')),p&&typeof p.workspace=="string"&&(c=rt(e,p.workspace));}catch(d){a$1.component("#index-loader").warn("Failed to load workspace config",{error:d.message});}return {rootDir:e,index:t,aggregation:o,gateConfig:r,projectName:i$1,wisdom:null,history:null,workspace:c,_loadedAt:Date.now()}}async function fe(n){return n.wisdom||(n.wisdom=await ht(n.rootDir)),n.wisdom}async function Io(n){return n.history||(n.history=await vt(n.rootDir)),n.history}j();b();var _t=false;function Bo(){return [{name:"paradigm_wisdom_context",description:"Get team wisdom (preferences, antipatterns, decisions) for symbols before implementing. Call this before making changes to understand team patterns. Returns preferences, antipatterns, and decisions relevant to the specified symbols. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get wisdom for (e.g., ["@checkout", "#payment-form"])'},include_global:{type:"boolean",description:"Include global preferences (default: true)"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_wisdom_record",description:"Record a new team learning: antipattern (what not to do) or decision (architectural choice). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to record"},id:{type:"string",description:'Unique ID (for antipattern: e.g., "api-001", for decision: e.g., "001")'},symbols:{type:"array",items:{type:"string"},description:"Related symbols"},description:{type:"string",description:"What not to do (antipattern) or the decision made (decision)"},reason:{type:"string",description:"Why this is an antipattern / context for decision"},alternative:{type:"string",description:"What to do instead (for antipatterns)"},title:{type:"string",description:"Decision title (for decisions)"},status:{type:"string",enum:["proposed","accepted","deprecated","superseded"],description:"Decision status (for decisions)"},rationale:{type:"object",properties:{factors:{type:"array",items:{type:"string"}},conclusion:{type:"string"}},description:"Decision rationale (for decisions)"},consequences:{type:"object",properties:{positive:{type:"array",items:{type:"string"}},negative:{type:"array",items:{type:"string"}},mitigations:{type:"array",items:{type:"string"}}},description:"Expected consequences (for decisions)"},scope:{type:"string",enum:["project","global"],description:'Where to store: "project" (default) writes to .paradigm/wisdom/, "global" writes to ~/.paradigm/wisdom/'}},required:["type","id","symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]}},{name:"paradigm_wisdom_expert",description:"Find human experts who know about specific symbols or areas. Returns names and contact info for relevant experts. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to find experts for (e.g., "@checkout")'},area:{type:"string",description:'General area to find experts for (e.g., "payments", "auth")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Pt(n,e$1,o){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:r=true}=e$1,s=await fe(o),i=bt(s,t),a={symbols:t,wisdom:i.map(d=>({symbol:d.symbol,preferences:d.preferences,antipatterns:d.antipatterns.map(p=>({id:p.id,description:p.description,reason:p.reason,alternative:p.alternative,scope:p.scope||"project"})),decisions:d.decisions.map(p=>({id:p.id,title:p.title,status:p.status,decision:p.decision,scope:p.scope||"project"})),experts:d.experts.map(p=>p.name)}))};r&&s.preferences?.global&&(a.global_preferences=s.preferences.global);let c=i.reduce((d,p)=>d+p.antipatterns.length,0),l=i.reduce((d,p)=>d+p.decisions.length,0);a.summary={symbols_with_preferences:i.filter(d=>d.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:i.some(d=>d.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let d={},p=[];for(let m of t){let h=await a$3(o.rootDir,{symbol:m,hasAssessment:!0,limit:100});if(h.length===0)continue;let x={correct:0,partial:0,incorrect:0},f=0,P=0;for(let R of h){let $=R.assessment.verdict;x[$]++,R.confidence!=null&&(f+=R.confidence,P++);}d[m]={total:h.length,...x,avgConfidence:P>0?Math.round(f/P*1e3)/1e3:null};let A=(x.correct+x.partial*.5)/h.length;A<.6&&h.length>=3&&p.push(`Low historical accuracy for ${m}: ${Math.round(A*100)}% across ${h.length} entries. Proceed with extra caution.`);}Object.keys(d).length>0&&(a.calibration=d),p.length>0&&(a.calibration_warnings=p);}catch{}return {handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_wisdom_record":{let{type:t,id:r,symbols:s,description:i,reason:a,alternative:c,title:l,status:d,rationale:p,consequences:m,scope:h$1="project"}=e$1;if(t==="antipattern"){if(!i||!a||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let x={id:r,symbols:s,description:i,reason:a,alternative:c};return h$1==="global"?g$1(x):await St(o.rootDir,x),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,scope:h$1,message:`Antipattern recorded to ${h$1} scope`})}}if(t==="decision"){if(!l||!i||!p||!m)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};if(_t||(_t=true,a$1.component("#wisdom").warn('paradigm_wisdom_record({type:"decision"}) is deprecated. Use paradigm_decision_record instead.',{deprecation:"v6.0",canonical_tool:"paradigm_decision_record"})),h$1==="global"){let P={id:r,title:l,status:d||"proposed",date:new Date().toISOString().split("T")[0],symbols:s,context:a||"",decision:i,rationale:p,consequences:m};return h(P),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,scope:"global",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record for project-scoped decisions.',message:"Decision recorded to global scope"})}}let x=a$2(o.rootDir,{title:l,decision:i,rationale:{factors:p.factors,conclusion:p.conclusion},participants:[{id:"wisdom-record",role:"agent",stance:"proposed"}],symbols_affected:s,status:d==="accepted"?"active":d==="proposed"?"proposed":"active",context:a||void 0,consequences:m,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),f=d$1(o.rootDir,x.id);return z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:x.id,legacy_id:r,scope:"project",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record going forward.',message:`Decision recorded (routed to decisions stream as ${x.id})`,...f?{companion_lore_id:f}:{}})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_promote":{let{type:t,id:r}=e$1,s=await fe(o),i=I.basename(o.rootDir);if(t==="antipattern"){let a=s.antipatterns.find(l=>l.id===r);return a?d().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Antipattern "${r}" already exists in global scope`})}:(g$1({...a,learned_from:`promoted from ${i}`}),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,promoted_from:i,message:`Antipattern "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${r}" not found in project`})}}if(t==="decision"){let a=s.decisions.find(l=>l.id===r);return a?e().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Decision "${r}" already exists in global scope`})}:(h(a),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,promoted_from:i,message:`Decision "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${r}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_expert":{let{symbol:t,area:r}=e$1;if(!t&&!r)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let s=await fe(o),i=wt(s,{symbol:t,area:r});return {handled:true,text:JSON.stringify({query:{symbol:t,area:r},count:i.length,experts:i.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:i.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function Go(){return [{name:"paradigm_protocol_search",description:"Search for protocols matching a task description. Call BEFORE exploring the codebase \u2014 if a matching protocol exists, follow its steps instead of discovering the pattern from scratch. Returns top matches with steps, exemplar, and freshness info. ~200 tokens.",inputSchema:{type:"object",properties:{task:{type:"string",description:'Task description to search for (e.g., "add a new page", "add API route")'},limit:{type:"number",description:"Maximum results (default: 3)"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_get",description:"Get a specific protocol by ID with full details and freshness check. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID (e.g., "P-add-view")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_record",description:"Record a new protocol after completing repeatable work. Captures the steps you followed so future agents can skip exploration. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Protocol name (e.g., "Add a new view")'},description:{type:"string",description:"What this protocol accomplishes"},trigger:{type:"array",items:{type:"string"},description:'Phrases that should match this protocol (e.g., ["add view", "new page"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g., ["ui", "frontend"])'},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols involved (e.g., ["#logs-view"])'},exemplar:{type:"string",description:'Canonical file to study for this pattern (e.g., "ui/src/views/LogsView.tsx")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"],description:"Step action type"},target:{type:"string",description:"File path (supports {Name}/{name} placeholders)"},template_from:{type:"string",description:"File to use as template (for create actions)"},reference:{type:"string",description:"Where in the file to make changes (for modify actions)"},command:{type:"string",description:"Command to execute (for run actions)"},notes:{type:"string",description:"Additional guidance for this step"}},required:["action"]},description:"Ordered steps to follow"},recorded_from:{type:"string",description:'Lore entry ID this protocol was learned from (e.g., "L-2026-03-01-001")'}},required:["name","description","trigger","tags","steps"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_update",description:"Update an existing protocol. Use refresh:true after successfully following a protocol to bump last_verified. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID to update (e.g., "P-add-view")'},refresh:{type:"boolean",description:"Set true to bump last_verified to now (use after successfully following the protocol)"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},trigger:{type:"array",items:{type:"string"},description:"Updated trigger phrases"},tags:{type:"array",items:{type:"string"},description:"Updated tags"},symbols:{type:"array",items:{type:"string"},description:"Updated symbols"},exemplar:{type:"string",description:"Updated exemplar path"},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"]},target:{type:"string"},template_from:{type:"string"},reference:{type:"string"},command:{type:"string"},notes:{type:"string"}},required:["action"]},description:"Updated steps"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_validate",description:"Validate protocol references \u2014 check that referenced files exist, exemplars haven't drifted. Validates all protocols if no ID given. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Protocol ID to validate (omit to validate all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function jt(n,e,o){switch(n){case "paradigm_protocol_search":{let t=e.task,r=e.limit||3,s=await I$1(o.rootDir,t,r);return s.length===0?{handled:true,text:JSON.stringify({count:0,task:t,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:s.length,task:t,matches:s.map(i=>({id:i.protocol.id,name:i.protocol.name,description:i.protocol.description,score:i.score,status:i.protocol.status,exemplar:i.protocol.exemplar,last_verified:i.protocol.last_verified,steps:i.protocol.steps.map(yn)}))},null,2)}}case "paradigm_protocol_get":{let t=e.id,r=await G$1(o.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let s=L(o.rootDir,r);return {handled:true,text:JSON.stringify({...r,freshness:{status:s.status,issues:s.issues}},null,2)}}case "paradigm_protocol_record":{let t=e.steps||[],r=await J(o.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:t,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:r,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let t=e.id,r=e.refresh,s={};e.name!==void 0&&(s.name=e.name),e.description!==void 0&&(s.description=e.description),e.trigger!==void 0&&(s.trigger=e.trigger),e.tags!==void 0&&(s.tags=e.tags),e.symbols!==void 0&&(s.symbols=e.symbols),e.exemplar!==void 0&&(s.exemplar=e.exemplar),e.steps!==void 0&&(s.steps=e.steps);let i=await K(o.rootDir,t,s,r===true);return {handled:true,text:JSON.stringify({success:i,id:t,refreshed:r===true,message:i?r?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${t}`})}}case "paradigm_protocol_validate":{let t=e.id;if(t){let a=await G$1(o.rootDir,t);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let c=L(o.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let s=(await F(o.rootDir)).map(a=>{let c=L(o.rootDir,a);return {id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified}}),i={total:s.length,current:s.filter(a=>a.status==="current").length,stale:s.filter(a=>a.status==="stale").length,broken:s.filter(a=>a.status==="broken").length};return {handled:true,text:JSON.stringify({protocols:s,health:i},null,2)}}default:return {handled:false,text:""}}}function yn(n){let e={action:n.action};return n.target&&(e.target=n.target),n.template_from&&(e.template_from=n.template_from),n.reference&&(e.reference=n.reference),n.command&&(e.command=n.command),n.notes&&(e.notes=n.notes),e}j();var ee=null,ke=false;async function _e(n){if(ee)ke||(await ee.ensureReady(),ke=true);else {let e=I.join(n,".paradigm","sentinel","sentinel.db");ee=new f(e),await ee.ensureReady(),ke=true;}return ee}async function hn(n,e){return (await _e(n)).recordPracticeEvent(e)}async function zo(n,e){return (await _e(n)).getPracticeEvents(e)}async function Ce(n,e){return (await _e(n)).getComplianceRate(e)}async function Rt(n,e){let o=["discovery","verification","testing","documentation","collaboration","security"],t=[];for(let r of o){let s=await Ce(n,{...e,habitCategory:r});s.total>0&&t.push({category:r,...s});}return t}async function Vo(n,e,o){let t=[];for(let r of e){let s=await hn(n,{habitId:r.habitId,habitCategory:r.habitCategory,result:r.result,engineer:o.engineer,sessionId:o.sessionId,loreEntryId:o.loreEntryId,taskDescription:o.taskDescription,symbolsTouched:o.symbolsTouched,filesModified:o.filesModified,notes:r.notes});t.push(s);}return t}b();function Ft(n){return {handled:true,text:JSON.stringify({error:n},null,2)}}var me={code:"lore_type_decision_removed",message:"lore type 'decision' was removed in v6.0. Use paradigm_decision_record instead. The decision will be stored in .paradigm/decisions/ and a companion lore insight entry (type:'insight' with references.decision_id) will be written automatically so the timeline stays complete. For narrative-only references, use paradigm_lore_record({type:'insight', references:{decision_id}}).",successor_tool:"paradigm_decision_record",doc:"docs/private/plans/v6.0-decisions-locked.md",removed_in:"6.0.0"};function It(){let n=process.env.PARADIGM_AUTHOR;if(n)return Pe(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Pe(e)}catch{}try{let e=Ot.userInfo().username;if(e)return Pe(e)}catch{}return "unknown"}function Pe(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function ss(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, milestone, retro, insight, etc.). Call after completing significant work. Returns the created entry ID and file path. For decisions, use paradigm_decision_record (a companion lore insight is auto-written). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function je(n,e,o){switch(n){case "paradigm_lore_search":{let t={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},r=await a$3(o.rootDir,t);return {handled:true,text:JSON.stringify({count:r.length,filter:Object.fromEntries(Object.entries(t).filter(([,s])=>s!==void 0)),entries:r.map(At)},null,2)}}case "paradigm_lore_record":{let{type:t,title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:m,duration_minutes:h,decisions:x,errors_encountered:f,learnings:P,verification:A,tags:R,meta:$,body:F,linked_lore:C,linked_tasks:O,linked_commits:E,confidence:w}=e;if(t==="decision")return a$1.component("#lore").warn("rejected paradigm_lore_record({type:'decision'}) \u2014 removed in v6.0",{removed_in:me.removed_in,successor_tool:me.successor_tool}),Ft(me);let v;try{let S=new Date(Date.now()-2592e6).toISOString(),b=await Ce(o.rootDir,{dateFrom:S});if(b.total>0){let y=(await Rt(o.rootDir,{dateFrom:S})).filter(_=>_.rate<60).map(_=>_.category);v={rate:b.rate,followed:b.followed,skipped:b.skipped,partial:b.partial,weakAreas:y.length>0?y:void 0};}}catch{}let u={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:h,author:It(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:m,decisions:x,errors_encountered:f,learnings:P,verification:A,tags:R,meta:$||void 0,habit_compliance:v,body:F,linked_lore:C,linked_tasks:O,linked_commits:E,confidence:w!=null&&w>=0&&w<=1?w:void 0},k=await d$2(o.rootDir,u);j$2().setLastLoreEntryId(k);try{let S=process.env.PARADIGM_AGENT_ID;if(S&&i&&i.length>0){let{updateExpertiseFromLore:b}=await import('./agent-loader-W3RQJVW7.js');b(o.rootDir,S,{symbols_touched:i,confidence:w!=null&&w>=0&&w<=1?w:void 0});}}catch{}let N$1=null;try{c&&c.length>=2&&(N$1=N(o.rootDir,c,l||[]));}catch{}let T;if(e.stream){let S=e.stream,b=S==="auto"?wn(e):S;try{if(b==="work-log"){let{recordWorkLog:g}=await import('./work-log-loader-DL5GZ2BQ.js');g(o.rootDir,{agent:u.agent?.model||"unknown",summary:u.summary,outcome:u.verification?.status==="pass"?"pass":u.verification?.status==="fail"?"fail":"partial",files_modified:u.files_modified,symbols_touched:u.symbols_touched,commit:u.commit,linked_lore:u.id||k}),T="work-log";}else if(b==="journal"&&u.learnings?.length){let{recordJournalEntry:g}=await import('./journal-loader-GLH7XFTK.js');for(let y of u.learnings)g(u.agent?.model||"unknown",{trigger:"self_reflection",insight:y,project:o.projectName||"unknown",transferable:!1,linked_work_log:u.id||k});T="journal";}else if(b==="decision"&&u.decisions?.length){let{recordDecision:g}=await import('./decision-loader-HELL2AMX.js');for(let y of u.decisions)g(o.rootDir,{title:y.decision.slice(0,100),decision:y.decision,rationale:y.rationale,participants:[{id:`agent/${u.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:u.symbols_touched,status:"active",linked_lore:u.id||k});T="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:k,type:t,title:r,message:"Lore entry recorded successfully",...T?{stream:T}:{},...N$1?{protocol_suggestion:N$1}:{}})}}case "paradigm_lore_timeline":{let t=e.limit||10,r=await c(o.rootDir),s=await a$3(o.rootDir,{limit:t}),i={};for(let l of s)for(let d of l.symbols_touched)i[d]=(i[d]||0)+1;let a=Object.entries(i).sort(([,l],[,d])=>d-l).slice(0,10).map(([l,d])=>({symbol:l,count:d})),c$1={};for(let l of s){let d=l.author;c$1[d]||(c$1[d]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c$1[d].count++,l.agent&&(c$1[d].hasAgent=true),l.timestamp>c$1[d].lastActive&&(c$1[d].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:r||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:s.map(At),hotSymbols:a,authors:Object.entries(c$1).map(([l,d])=>({id:l,hasAgent:d.hasAgent,entries:d.count,lastActive:d.lastActive}))},null,2)}}case "paradigm_lore_get":{let t=e.id,r=await b$1(o.rootDir,t);return r?{handled:true,text:JSON.stringify(r,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})}}case "paradigm_lore_update":{let t=e.id,{id:r,...s}=e,i={};for(let[c,l]of Object.entries(s))l!==void 0&&(i[c]=l);let a=await g$2(o.rootDir,t,i);return {handled:true,text:JSON.stringify({success:a,id:t,message:a?"Lore entry updated":`Lore entry not found: ${t}`})}}case "paradigm_lore_assess":{let t=e.id,r=e.verdict,s=e.notes,i=await b$1(o.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})};let a={verdict:r,assessed_by:It(),assessed_at:new Date().toISOString(),notes:s},c=await h$1(o.rootDir,t,a);try{let m=process.env.PARADIGM_AGENT_ID;if(m&&c&&i.symbols_touched?.length){let{updateExpertiseFromAssessment:h}=await import('./agent-loader-W3RQJVW7.js');h(o.rootDir,m,{symbols_touched:i.symbols_touched,verdict:r});}}catch{}let l=r==="correct"?1:r==="partial"?.5:0,d=i.confidence!=null?l-i.confidence:null,p=d!=null?d>.1?"Under-confident (actual outcome better than predicted)":d<-0.1?"Over-confident (actual outcome worse than predicted)":"Well-calibrated":"No confidence recorded \u2014 delta not computed";return {handled:true,text:JSON.stringify({success:c,id:t,verdict:r,confidence:i.confidence??null,delta:d,deltaDescription:p,message:c?`Assessment recorded: ${r}${d!=null?` (delta: ${d>0?"+":""}${d.toFixed(2)})`:""}`:`Failed to assess: ${t}`})}}case "paradigm_lore_calibration":{let t={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},r=await a$3(o.rootDir,t),s=r.filter(F=>F.confidence!=null),i=r.length,a=s.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,p=0;for(let F of r){let C=F.assessment.verdict;c[C]++;let O=C==="correct"?1:C==="partial"?.5:0;l+=O,F.confidence!=null&&(d+=F.confidence,p+=Math.abs(O-F.confidence));}let m=i>0?l/i:0,h=a>0?d/a:null,x=a>0?l/i-d/a:null,f=a>0?1-p/a:null,P=e.groupBy,A;if(P&&i>0){let F=new Map;for(let C of r){let O=[];P==="symbol"?O=C.symbols_touched||[]:P==="tag"?O=C.tags||[]:P==="type"&&(O=[C.type||"agent-session"]);for(let E of O)F.has(E)||F.set(E,[]),F.get(E).push(C);}A=Array.from(F.entries()).map(([C,O])=>{let E=O.filter(N=>N.confidence!=null),w={correct:0,partial:0,incorrect:0},v=0,u=0,k=0;for(let N of O){let T=N.assessment.verdict;w[T]++;let S=T==="correct"?1:T==="partial"?.5:0;v+=S,N.confidence!=null&&(u+=N.confidence,k+=Math.abs(S-N.confidence));}return {key:C,total:O.length,accuracyRate:v/O.length,avgConfidence:E.length>0?u/E.length:null,calibrationScore:E.length>0?1-k/E.length:null,verdictBreakdown:w}}).sort((C,O)=>O.total-C.total);}let R=[],$=i<5?`Low sample size (N=${i}). Stats may not be representative.`:i<15?`Moderate sample (N=${i}). Trends are directional, not conclusive.`:null;return $&&R.push($),f!=null&&(f>=.9?R.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):f>=.7?R.push("Good calibration \u2014 some room for improvement in confidence estimates."):f>=.5?R.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):R.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),x!=null&&(x>.15?R.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):x<-0.15&&R.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>i*.3&&i>=5&&R.push(`High error rate: ${c.incorrect}/${i} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:i,totalWithConfidence:a,accuracyRate:Math.round(m*1e3)/1e3,avgConfidence:h!=null?Math.round(h*1e3)/1e3:null,avgDelta:x!=null?Math.round(x*1e3)/1e3:null,calibrationScore:f!=null?Math.round(f*1e3)/1e3:null,verdictBreakdown:c,...A?{groups:A}:{},insights:R},null,2)}}case "paradigm_lore_delete":{let t=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let s=await i$1(o.rootDir,t);return {handled:true,text:JSON.stringify({success:s,id:t,message:s?"Lore entry deleted":`Lore entry not found: ${t}`})}}default:return {handled:false,text:""}}}function wn(n){return n.task_ref||n.files_modified||n.commit?"work-log":n.learnings||n.confidence!==void 0?"journal":n.decisions?.some(o=>o.rationale)?"decision":"work-log"}function At(n){return {id:n.id,type:n.type,title:n.title,summary:n.summary,author:n.author,agent:n.agent,timestamp:n.timestamp,duration_minutes:n.duration_minutes,symbols_touched:n.symbols_touched,verification:n.verification?.status,review:n.review?{completeness:n.review.completeness,quality:n.review.quality}:null,confidence:n.confidence??null,assessment:n.assessment?n.assessment.verdict:null,assessment_delta:n.assessment_delta??null,tags:n.tags}}function hs(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_captain_board",description:"Cid's owned run-DAG board (#captain-board). action='read' (default, read-only) assembles the live orchestration DAG \u2014 each run's epic + ordered stage-children with status/claimant/dependsOn, plus ripple-ranked unclaimed open tasks and a summary. action='claim' writes a task's claimant (status stays open; human/peer claims override an archetype proposal). action='advance' records a blocked_on reason without changing status (orchestration owns in-progress/done). ~300 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["read","claim","advance"],description:"Board action. Default 'read'."},taskId:{type:"string",description:"Target task id (required for claim/advance)."},claimant:{type:"object",description:"For claim: the new owner { kind: 'archetype'|'human'|'peer', ref }.",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},blockedOn:{type:"string",description:"For advance: the blocking reason recorded on the task."}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function bs(n,e,o){return n==="paradigm_captain_brief"?Sn(e,o):n==="paradigm_captain_debrief"?xn(e,o):n==="paradigm_captain_board"?Cn(e,o):{handled:false,text:""}}async function Sn(n,e){let o=n.taskDescription,t=n.symbols||[],r=n.depth||"standard",s=I.join(e.rootDir,".paradigm"),i=I.join(s,".cid-session"),a=I.join(s,".cid-briefed");try{D.existsSync(a)&&D.unlinkSync(a);let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r};D.mkdirSync(s,{recursive:!0}),D.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let c=$n(o),l=[],d=new Set;for(let S of t)if(!d.has(S)){d.add(S);let b=$t(S);l.push({id:S,type:b,description:"Provided as anchor symbol"});}let p=[];try{for(let S of c.slice(0,3)){let g=m(e.index,S).slice(0,5);for(let y of g)if(!d.has(y.symbol)){d.add(y.symbol);let _=Tn(y.type);l.push({id:y.symbol,type:_,description:y.description||"",file:y.file}),p.push(y.symbol);}}}catch{}let m$1={directories:[],files:[]};try{let S=await lt("paradigm_navigate",{intent:"context",task:o,response_format:"concise"},e);if(S.handled){let b=JSON.parse(S.text);if(b.files)for(let g of b.files){let y=typeof g=="string"?g:g.path||g.file||"";y&&m$1.files.push(y);}if(b.directories)for(let g of b.directories){let y=typeof g=="string"?g:g.path||g.directory||"";y&&m$1.directories.push(y);}if(b.symbols)for(let g of b.symbols){let y=typeof g=="string"?g:g.id;y&&!d.has(y)&&(d.add(y),l.push({id:y,type:$t(y),description:typeof g=="object"&&g.description||""}));}}}catch{}let h=new Set(m$1.directories);for(let S of m$1.files){let b=I.dirname(S);b&&b!=="."&&h.add(b);}let x=l.slice(0,r==="deep"?5:3),f={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(r!=="quick"&&x.length>0)for(let S of x)try{let b=await le("paradigm_ripple",{symbol:S.id,depth:2,response_format:"concise"},e);if(b.handled){let g=JSON.parse(b.text);if(g.analysis){for(let y of g.analysis.directlyAffected||[]){let _=y.symbol||y;_&&!f.affectedSymbols.includes(_)&&f.affectedSymbols.push(_);}for(let y of g.analysis.indirectlyAffected||[])y&&!f.affectedSymbols.includes(y)&&f.affectedSymbols.push(y);}if(g.affectedFlows?.affectedFlows)for(let y of g.affectedFlows.affectedFlows){let _=y.flowId||y;_&&!f.affectedFlows.includes(_)&&f.affectedFlows.push(_);}if(g.affectedGates)for(let y of g.affectedGates){let _=y.gate||y;_&&!f.affectedGates.includes(_)&&f.affectedGates.push(_);}g.impact==="high"&&(f.fragileSymbols.includes(S.id)||f.fragileSymbols.push(S.id));}}catch{}let P=[],A=En(o);if(A.length>0)try{let{handleGatesForRoute:S}=await import('./tools-HNJ7D5IO.js').catch(()=>({handleGatesForRoute:null})),b=I.join(e.rootDir,"portal.yaml");if(D.existsSync(b)){let g=D.readFileSync(b,"utf8");for(let y of A){let _=g.includes(y);P.push({route:y,gate:"^authenticated",declared:_});}}else for(let g of A)P.push({route:g,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let R=[];if(r!=="quick"&&l.length>0)try{let S=l.slice(0,5).map(g=>g.id),b=await Pt("paradigm_wisdom_context",{symbols:S,include_global:!0},e);if(b.handled){let g=JSON.parse(b.text);if(g.antipatterns)for(let y of g.antipatterns.slice(0,3)){let _=y.pattern||y.description||y.text||String(y);_&&!R.includes(_)&&R.push(_);}if(g.wisdom?.antipatterns)for(let y of g.wisdom.antipatterns.slice(0,3)){let _=y.pattern||y.description||String(y);_&&!R.includes(_)&&R.push(_);}}}catch{}let $={matched:false};try{let S=await jt("paradigm_protocol_search",{task:o,limit:1},e);if(S.handled){let b=JSON.parse(S.text),g=b.matches||b.protocols||b.results||[];if(g.length>0){let y=g[0];$={matched:!0,id:y.id,name:y.name||y.title,steps:(y.steps||[]).slice(0,5).map(_=>typeof _=="string"?_:_.description||String(_))};}}}catch{}let F=[];if(r!=="quick")try{let S=l[0]?.id,b={limit:r==="deep"?5:3};S&&(b.symbol=S);let g=await je("paradigm_lore_search",b,e);if(g.handled){let _=JSON.parse(g.text).entries||[];for(let K of _.slice(0,3))F.push({id:K.id,summary:(K.summary||K.title||"").slice(0,100),relevance:S?`Related to ${S}`:"Recent project history"});}}catch{}let C=Array.from(h),O$1=0;for(let S of C){let b=I.join(e.rootDir,S,".purpose");if(D.existsSync(b))try{D.readFileSync(b,"utf8").trim().length>50&&O$1++;}catch{}}let E=C.length>0?O$1/C.length:.5,w=Wn(E),v=Ln(E,w,C.length),u=f.affectedSymbols.length+m$1.files.length,k=u>20?"large":u>8?"medium":u>2?"small":"tiny",N={territory:{directories:C.slice(0,10),files:m$1.files.slice(0,10),estimatedScope:k},symbols:l.slice(0,10),blastRadius:f,gates:P,protocol:$,warnings:R,coverage:{score:E,label:w,note:v},loreRefs:F,archMap:b$2(e.rootDir),renderedBrief:""};N.renderedBrief=Hn(N);try{let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r,coverageScore:E};D.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let T=JSON.stringify(N,null,2);return O(T.length,"paradigm_captain_brief"),{handled:true,text:T}}async function xn(n,e){let o=n.orchestrationId,t=n.sessionSummary,r=n.touchedFiles||[],s=n.newSymbols||[],i=n.notes,a=I.join(e.rootDir,".paradigm"),c=I.join(a,".cid-briefed"),l=I.join(a,".pending-review"),d=new Set;for(let u of r){let k=I.dirname(u);k&&k!=="."&&d.add(k);}let p=0,m=d.size;for(let u of d){let k=I.join(e.rootDir,u,".purpose");if(D.existsSync(k))try{D.readFileSync(k,"utf8").trim().length>50&&p++;}catch{}}let h=m>0?p/m:1,x=[],f=[];for(let u of d){let k=I.join(e.rootDir,u,".purpose"),N=I.join(e.rootDir,u),T=false;if(D.existsSync(k))try{T=D.readFileSync(k,"utf8").trim().length>50;}catch{}if(T){if(r.some(b=>I.dirname(b)===u&&s.length>0)){f.push(u);try{let b=JSON.stringify({path:u,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${o}: ${s.join(", ")}`,timestamp:new Date().toISOString()});D.appendFileSync(l,b+`
6
+ `,"utf8");}catch{}}}else try{if(!D.existsSync(N))continue;let S=I.basename(u),b=Bn(S,u,r);D.writeFileSync(k,b,"utf8"),x.push(u),f.push(u);try{let g=JSON.stringify({path:u,reason:"captain-debrief",priority:"high",context:`Touched during orchestration ${o}. Files: ${r.filter(y=>I.dirname(y)===u).join(", ")}`,timestamp:new Date().toISOString()});D.appendFileSync(l,g+`
7
+ `,"utf8");}catch{}}catch{}}let P=0;for(let u of d){let k=I.join(e.rootDir,u,".purpose");if(D.existsSync(k))try{D.readFileSync(k,"utf8").trim().length>50&&P++;}catch{}}let A=m>0?P/m:1,R="";try{let u=await je("paradigm_lore_record",{type:"agent-session",title:`Cid Debrief: ${t.slice(0,80)}`,summary:t,symbols_touched:s,files_modified:r,tags:["arc:cid-debrief",`orch:${o}`],meta:{orchestrationId:o,coverageScore:{before:h,after:A},coverageAdded:x,...i?{notes:i}:{}}},e);if(u.handled){let k=JSON.parse(u.text);R=k.id||k.entry?.id||"";}}catch{}let $={ranThisSession:false,selfHealed:false,blockProposed:false};if($.ranThisSession=_n(a),!$.ranThisSession)try{let{runPostflightLearning:u}=await import('./ambient-7HBJHJL2.js');await u(e.rootDir,{claimant:"navigation"}),$.selfHealed=!0,a$1.flow("$captain-board").info("Cid self-healed postflight (no prior liveness record)",{orchestrationId:o});}catch(u){$.selfHealError=u instanceof Error?u.message:String(u),a$1.flow("$captain-board").warn("Cid postflight self-heal threw \u2014 proposing advise block",{orchestrationId:o,error:$.selfHealError});try{let{handleProposeBlockTool:k}=await import('./propose-block-ZEMEWJQF.js');await k("paradigm_propose_block",{claimant:"navigation",severity:"advise",reason:`Postflight learning did not run and Cid's self-heal failed: ${$.selfHealError}`,unblock_hint:"Run `paradigm_ambient_learn_postflight` manually, or inspect .paradigm/events/settlement-liveness.jsonl for the severed stage."},e),$.blockProposed=!0;}catch{}}let F=false;try{let u={timestamp:new Date().toISOString(),sessionId:o,touchedFiles:r,coverageScore:A};D.mkdirSync(a,{recursive:!0}),D.writeFileSync(c,JSON.stringify(u,null,2),"utf8"),F=!0;}catch{}let C={taskDescription:t,orchestrationId:o,agentContributions:[],coverageDelta:{before:h,after:A},newSymbols:s,touchedFiles:r,notes:i||""};try{let u=I.join(a,"events","session-log.jsonl");if(D.existsSync(u)){let T=D.readFileSync(u,"utf8").split(`
8
+ `).filter(b=>b.trim().length>0).slice(-50),S=new Map;for(let b of T)try{let g=JSON.parse(b),y=g.agentId||g.agent||g.role||"";if(!y)continue;S.has(y)||S.set(y,{contributions:[],symbolsTouched:new Set,patternsObserved:[]});let _=S.get(y),K=g.action||g.event||g.message||"";if(K&&_.contributions.push(String(K).slice(0,120)),Array.isArray(g.symbols))for(let te of g.symbols)_.symbolsTouched.add(String(te));let De=g.symbol||"";if(De&&_.symbolsTouched.add(De),Array.isArray(g.patterns))for(let te of g.patterns)_.patternsObserved.includes(String(te))||_.patternsObserved.push(String(te));}catch{}for(let[b,g]of S.entries())C.agentContributions.push({agentId:b,contribution:g.contributions.slice(-3).join(" | "),symbolsTouched:Array.from(g.symbolsTouched).slice(0,10),patternsObserved:g.patternsObserved.slice(0,5)});}}catch{}C.agentContributions.length===0&&C.agentContributions.push({agentId:"session",contribution:t.slice(0,200),symbolsTouched:s.slice(0,10),patternsObserved:[]});let O$1={coverageAdded:x,delegatedToDocumentor:f,loreEntryId:R,coverageScore:{before:h,after:A,delta:A-h},stopHookCleared:F,postflight:$,sessionInsights:C},E=["","\u2501\u2501\u2501 LEARNING HANDOFF (\u2192 Loid) \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501","","Cid has prepared session insights for Loid's learning pass.","Call paradigm_ambient_learn_postflight with the sessionInsights","from this debrief to complete the session.","","sessionInsights available in: debrief.sessionInsights"].join(`
9
+ `),v=JSON.stringify(O$1,null,2)+`
10
+ `+E;return O(v.length,"paradigm_captain_debrief"),{handled:true,text:v}}var vn=I.join("events","settlement-liveness.jsonl"),kn=360*60*1e3;function _n(n){let e=I.join(n,vn);if(!D.existsSync(e))return false;try{let t=D.readFileSync(e,"utf8").split(`
11
+ `).filter(s=>s.trim().length>0),r=Date.now()-kn;for(let s of t.slice(-50))try{let i=JSON.parse(s),a=i.ts?new Date(i.ts).getTime():NaN;if(Number.isNaN(a)||a<r)continue;if(i.stages?.runPostflightLearning==="ok")return !0}catch{}}catch{return false}return false}async function Cn(n,e){let o=n.action||"read";if(o==="claim")return On(n,e);if(o==="advance")return Nn(n,e);let t=await In(e.rootDir,{},e),r=JSON.stringify(t,null,2);return O(r.length,"paradigm_captain_board"),{handled:true,text:r}}function Pn(n,e){return n.settledAt?n.crashed_at||e.some(t=>t.crashed_at)?"crashed":"settled":e.length===0?"pending":e.some(t=>t.status==="in-progress")||n.status==="in-progress"?"in-progress":"pending"}function jn(n){return [...n].sort((e,o)=>{let t=e.stage??0,r=o.stage??0;if(t!==r)return t-r;let s=e.dependsOn?.length??0,i=o.dependsOn?.length??0;return s!==i?s-i:e.id.localeCompare(o.id)})}async function Dn(n,e){let o=Et(n).slice(0,3),t=[];for(let r of o)try{let s=await le("paradigm_ripple",{symbol:r,depth:1,response_format:"concise"},e);s.handled&&JSON.parse(s.text).impact==="high"&&!t.includes(r)&&t.push(r);}catch{}return t}var Rn=/[#$^!~][a-z][a-z0-9-]*/gi;function Et(n){let e=new Set;for(let t of n.tags||[])/^[#$^!~]/.test(t)&&e.add(t);let o=n.blurb?.match(Rn)||[];for(let t of o)e.add(t);return Array.from(e)}async function Fn(n,e){let o=Et(n).slice(0,3),t=0,r=[];for(let s of o)try{let i=await le("paradigm_ripple",{symbol:s,depth:2,response_format:"concise"},e);if(i.handled){let a=JSON.parse(i.text),c=a.analysis?.directlyAffected?.length??0,l=a.analysis?.indirectlyAffected?.length??0;t+=c*2+l,a.impact==="high"&&!r.includes(s)&&r.push(s);}}catch{}return {score:t,fragile:r}}var Nt={high:0,medium:1,low:2};async function In(n,e={},o){let t=o,{loadTasks:r}=await import('./task-loader-IGQQ6ZFL.js'),s=[];try{s=await r(n,{status:"all",limit:9999});}catch(m){a$1.flow("$captain-board").warn("Board task load failed",{error:m instanceof Error?m.message:String(m)});}let i=s.filter(m=>m.external_ref?.kind==="orchestration"&&!m.parentTaskId&&!m.settledAt),a=[];for(let m of i){let h=jn(s.filter(f=>f.parentTaskId===m.id)),x=[];for(let f of h){let P=t?await Dn(f,t):[];x.push({taskId:f.id,blurb:f.blurb,stage:f.stage,status:f.status,claimant:f.claimant,dependsOn:f.dependsOn||[],fragileSymbols:P});}a.push({epicTaskId:m.id,blurb:m.blurb,runStatus:Pn(m,h),settledAt:m.settledAt,nodes:x});}let c=s.filter(m=>m.status==="open"&&!m.claimant),l=[];for(let m of c){let{score:h,fragile:x}=t?await Fn(m,t):{score:0,fragile:[]},f;e.proposeClaimants&&(f=await An(m,n)),l.push({taskId:m.id,blurb:m.blurb,priority:m.priority,tags:m.tags||[],rippleScore:h,fragileSymbols:x,proposedClaimant:f});}l.sort((m,h)=>{if(h.rippleScore!==m.rippleScore)return h.rippleScore-m.rippleScore;let x=(Nt[m.priority]??1)-(Nt[h.priority]??1);return x!==0?x:h.taskId.localeCompare(m.taskId)});let d=s.filter(m=>m.status==="in-progress").length,p=s.filter(m=>m.status==="open").length;return {runs:a,unclaimed:l,summary:{runs:a.length,open:p,inFlight:d,unclaimed:l.length}}}async function An(n,e){try{let{suggestAgentsForTask:o,loadAgentsManifest:t}=await import('./orchestration-G5MAY6IA.js'),r=t(e);if(!r?.agents)return;let s=[n.blurb,...n.tags||[]].join(" "),i=o(s,r.agents);return i.length===0?void 0:{kind:"archetype",ref:i[0].name}}catch{return}}async function On(n,e){let o=n.taskId,t=n.claimant;if(!o||!t?.kind||!t?.ref)return {handled:true,text:JSON.stringify({ok:false,error:"claim requires taskId and claimant {kind, ref}"})};let{loadTask:r,updateTask:s}=await import('./task-loader-IGQQ6ZFL.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a=i.claimant;if(a&&a.kind!=="archetype"&&t.kind==="archetype")return a$1.flow("$captain-board").info("Claim rejected: archetype cannot override human/peer claim",{taskId:o,existing:a.kind,proposed:t.kind}),{handled:true,text:JSON.stringify({ok:false,error:`task ${o} is claimed by ${a.kind}:${a.ref}; archetype proposal cannot override`,claimant:a})};let c=await s(e.rootDir,o,{claimant:t});return a$1.flow("$captain-board").info("Captain claim written",{taskId:o,claimant:t,ok:c}),{handled:true,text:JSON.stringify({ok:c,taskId:o,claimant:t,status:"open"})}}async function Nn(n,e){let o=n.taskId,t=n.blockedOn;if(!o||!t)return {handled:true,text:JSON.stringify({ok:false,error:"advance requires taskId and blockedOn (v7.0 has no 'blocked' status \u2014 advance records a reason only)"})};let{loadTask:r,updateTask:s}=await import('./task-loader-IGQQ6ZFL.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a=await s(e.rootDir,o,{blocked_on:t});return a$1.flow("$captain-board").info("Captain advance: blocked_on recorded (status unchanged)",{taskId:o,blockedOn:t,status:i.status,ok:a}),{handled:true,text:JSON.stringify({ok:a,taskId:o,blocked_on:t,status:i.status})}}function $n(n){let e=new Set(["the","a","an","to","of","in","and","or","for","with","that","this","is","it","be","as","at","by","from","add","create","update","fix","implement","make","build","change","modify","new","old","get","set","use","using"]),o=n.match(/[#$^!~@&%?][a-z][a-z0-9-]*/g)||[],t=n.replace(/[#$^!~@&%?]/g," ").split(/[\s\-_\/.,;:'"()\[\]{}!?]+/).map(s=>s.toLowerCase()).filter(s=>s.length>2&&!e.has(s));return [...new Set([...o,...t])].slice(0,6)}function En(n){let e=[],o=/(?:GET|POST|PUT|PATCH|DELETE)\s+(\/[a-z0-9\-\/:_{}]+)/gi,t;for(;(t=o.exec(n))!==null;)e.push(t[1]);let r=/\/api\/[a-z0-9\-\/:_{}]+/g;for(;(t=r.exec(n))!==null;)e.includes(t[0])||e.push(t[0]);return e}function $t(n){return n.startsWith("#")?"component":n.startsWith("$")?"flow":n.startsWith("^")?"gate":n.startsWith("!")?"signal":n.startsWith("~")?"aspect":"component"}function Tn(n){switch(n){case "component":return "component";case "flow":return "flow";case "gate":return "gate";case "signal":return "signal";case "aspect":return "aspect";default:return "component"}}function Wn(n){return n>=.85?"comprehensive":n>=.6?"reliable":n>=.3?"partial":"sparse"}function Ln(n,e,o){let t=Math.round(n*100);switch(e){case "sparse":return `${t}% of ${o} director(ies) covered. Brief may be significantly incomplete. Builder should explore directly.`;case "partial":return `${t}% of ${o} director(ies) covered. Brief covers key symbols. Some areas uncharted.`;case "reliable":return `${t}% of ${o} director(ies) covered. Brief is reliable for this task.`;case "comprehensive":return `${t}% of ${o} director(ies) covered. Area is fully mapped.`}}function Hn(n){let e=[],o="\u2501".repeat(52);e.push(`${o}`),e.push("");let t=n.territory.directories.slice(0,3).join(", ")||"(none detected)";e.push(`Territory: ${t}`);let r=n.symbols.slice(0,5).map(d=>d.id).join(", ")||"(none found)";e.push(`Symbols: ${r}`);let s=n.blastRadius.affectedFiles.length+n.territory.files.length,i=n.blastRadius.affectedFlows.length,a=n.blastRadius.affectedGates.length,c=n.blastRadius.fragileSymbols.length>0?` \xB7 \u26A0 ${n.blastRadius.fragileSymbols.slice(0,2).join(", ")} (fragile)`:"";if(e.push(`Blast Radius: ${s} files \xB7 ${i} flows \xB7 ${a} gates${c}`),n.gates.length>0){let d=n.gates.slice(0,2).map(p=>`${p.route} \u2192 ${p.gate} (${p.declared?"declared \u2713":"UNDECLARED \u2717"})`);e.push(`Gates: ${d.join("; ")}`);}if(n.protocol.matched){let d=n.protocol.steps?.length?` (${n.protocol.steps.length} steps)`:"";e.push(`Protocol: ${n.protocol.name||n.protocol.id}${d} \u2014 matched`);}else e.push("Protocol: (none matched)");n.warnings.length>0&&e.push(`Warnings: "${n.warnings[0].slice(0,80)}"`);let l=Math.round(n.coverage.score*100);return e.push(`Coverage: ${l}% \u2014 brief is ${n.coverage.label}`),e.push(""),e.push(`${o}`),e.join(`
12
+ `)}function Bn(n,e,o){let r=o.filter(s=>I.dirname(s)===e).slice(0,3).map(s=>`# - ${I.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{ss as A,je as B,hs as C,bs as D,In as E,An as F,dn as a,wt as b,wo as c,mn as d,So as e,un as f,xo as g,xe as h,Fo as i,fe as j,Io as k,Zn as l,lt as m,pt as n,mt as o,ut as p,mo as q,le as r,Bo as s,Pt as t,Go as u,jt as v,zo as w,Ce as x,Rt as y,Vo as z};
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import {j as j$1,a,c,b,k}from'./chunk-ACJWUOMA.js';import*as m from'fs';import*as y from'path';import*as j from'js-yaml';import {z as z$1}from'zod';var Z=class{cache=new Map;ttlMs;constructor(e=3e4){this.ttlMs=e;}async getOrCompute(e,o){let n=this.cache.get(e);if(n&&Date.now()-n.createdAt<this.ttlMs)return n.data;let s=await o();return this.cache.set(e,{data:s,createdAt:Date.now()}),s}invalidate(e){this.cache.delete(e);}invalidatePrefix(e){for(let o of this.cache.keys())o.startsWith(e)&&this.cache.delete(o);}clear(){this.cache.clear();}stats(){return {size:this.cache.size,ttlMs:this.ttlMs}}},Lt=new Z(3e4);var L=".paradigm/personas",Ke="index.yaml";async function z(t,e){let o=y.join(t,L);if(!m.existsSync(o))return [];let n=m.readdirSync(o).filter(i=>i.endsWith(".persona")),s=[];for(let i of n)try{let a=m.readFileSync(y.join(o,i),"utf8"),r=j.load(a);r&&r.id&&s.push(r);}catch{}return Qe(s,e)}async function W(t,e){let o=y.join(t,L,`${e}.persona`);if(!m.existsSync(o))return null;try{return j.load(m.readFileSync(o,"utf8"))}catch{return null}}function Qe(t,e){if(!e)return t;let o=t;return e.tag&&(o=o.filter(n=>n.tags?.includes(e.tag))),e.trigger_type&&(o=o.filter(n=>n.trigger.type===e.trigger_type)),e.gate&&(o=o.filter(n=>n.journey.some(s=>s.gates.includes(e.gate)))),e.flow&&(o=o.filter(n=>n.journey.some(s=>s.flow===e.flow))),e.limit&&(o=o.slice(0,e.limit)),o}async function Wt(t,e){let o=y.join(t,L);m.mkdirSync(o,{recursive:true});let n=y.join(o,`${e.id}.persona`);if(m.existsSync(n))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(n,j.dump(i,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await te(t),e.id}async function ye(t,e,o){let n=await W(t,e);if(!n)return false;let s=y.join(t,L,`${e}.persona`),i={...n,...o,id:n.id,version:n.version,created:n.created,updated:new Date().toISOString()};return m.writeFileSync(s,j.dump(i,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await te(t),true}async function Ut(t,e){let o=y.join(t,L,`${e}.persona`);if(!m.existsSync(o))return {deleted:false,warnings:[]};let n=[],s=await z(t);for(let i of s)if(i.id!==e){i.trigger.spawned_by?.startsWith(e+".")&&n.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)&&n.push(`Persona ${i.id} step ${a.id} spawns ${e} \u2014 spawn will break`);}return m.unlinkSync(o),await te(t),{deleted:true,warnings:n}}async function Ht(t,e,o,n){let s=await W(t,e);if(!s)return false;if(s.journey.some(i=>i.id===o.id))throw new Error(`Step ${o.id} already exists in persona ${e}`);if(n){let i=s.journey.findIndex(a=>a.id===n);if(i===-1)throw new Error(`Step ${n} not found in persona ${e}`);s.journey.splice(i+1,0,o);}else s.journey.push(o);return ye(t,e,{journey:s.journey})}async function qt(t,e,o){let n=await W(t,e);if(!n)return {removed:false,warnings:[]};let s=n.journey.findIndex(r=>r.id===o);if(s===-1)return {removed:false,warnings:[]};let i=n.journey[s],a=[];if(i.produces)for(let r of Object.keys(i.produces)){let l=`{{produces.${r}}}`;for(let d=s+1;d<n.journey.length;d++){let c=n.journey[d];JSON.stringify(c).includes(l)&&a.push(`Step ${c.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 n.journey.splice(s,1),await ye(t,e,{journey:n.journey}),{removed:true,warnings:a}}var Ve=/^[a-z][a-z0-9-]*$/,Ye=/^[a-z][a-z0-9-]*$/,Xe=/^(GET|POST|PUT|PATCH|DELETE)\s+\//;async function Gt(t,e,o=false){let n=[],s=[];Ve.test(e.id)||n.push({type:"invalid-id",detail:`ID "${e.id}" must match /^[a-z][a-z0-9-]*$/`}),(!e.name||e.name.trim()==="")&&n.push({type:"missing-name",detail:"Name is required"}),(!e.trigger||!e.trigger.type)&&n.push({type:"missing-trigger",detail:"Trigger with type is required"}),e.trigger.type!=="root"&&!e.trigger.spawned_by&&n.push({type:"missing-spawned-by",detail:`Non-root trigger type "${e.trigger.type}" requires spawned_by`}),(!e.journey||e.journey.length===0)&&n.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){Ye.test(r.id)||n.push({type:"invalid-step-id",step:r.id,detail:"Step ID must match /^[a-z][a-z0-9-]*$/"}),i.has(r.id)&&n.push({type:"duplicate-step-id",step:r.id,detail:`Duplicate step ID "${r.id}"`}),i.add(r.id),Xe.test(r.route)||n.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)&&n.push({type:"missing-gates",step:r.id,detail:"Step must have at least one gate"}),(!r.expect||r.expect.status===void 0)&&n.push({type:"missing-expect",step:r.id,detail:"Step must have expect with status"});let d=JSON.stringify(r).match(/\{\{produces\.([^}]+)\}\}/g)||[];for(let c of d){let u=c.replace("{{produces.","").replace("}}","");a.has(u)||n.push({type:"unresolved-produces",step:r.id,key:u,detail:`{{produces.${u}}} used but not produced by a prior step`});}if(r.produces)for(let c of Object.keys(r.produces))a.add(c);}if(o){let r=y.join(t,"portal.yaml"),l=[],d=[];if(m.existsSync(r))try{let u=j.load(m.readFileSync(r,"utf8"));u.gates&&typeof u.gates=="object"&&(l=Object.keys(u.gates)),u.routes&&typeof u.routes=="object"&&(d=Object.keys(u.routes));}catch{}for(let u of e.journey)for(let p of u.gates)l.length>0&&!l.includes(p)&&n.push({type:"gate-not-found",step:u.id,gate:p,detail:`Gate ${p} not defined in portal.yaml`});for(let u of e.journey)if(d.length>0){let p=u.route;d.some(f=>ee(f,p))||s.push({type:"route-not-in-portal",detail:`Route "${p}" (step ${u.id}) not found in portal.yaml`});}for(let u of e.journey)if(u.spawns)for(let p of u.spawns)await W(t,p.persona)||n.push({type:"spawn-target-missing",step:u.id,detail:`Spawn target persona "${p.persona}" does not exist`});let c=await Ze(t,e.id);if(c&&n.push({type:"spawn-cycle",detail:`Circular spawn dependency: ${c.join(" \u2192 ")}`}),d.length>0||l.length>0){let u=await z(t),p=new Set,h=new Set;for(let w of u)for(let I of w.journey){for(let P of I.gates)p.add(P);h.add(I.route);}let f=[],g=y.join(t,".paradigm","flow-index.json");if(m.existsSync(g))try{let w=JSON.parse(m.readFileSync(g,"utf8"));f=Object.keys(w.flows||{});}catch{}let b=new Set;for(let w of u)for(let I of w.journey)I.flow&&b.add(I.flow);return {persona:e.id,valid:n.length===0,errors:n,warnings:s,coverage:{routes:{covered:h.size,total:d.length,uncovered:d.filter(w=>!h.has(w))},gates:{covered:p.size,total:l.length,uncovered:l.filter(w=>!p.has(w))},flows:{covered:b.size,total:f.length,uncovered:f.filter(w=>!b.has(w))}}}}}return {persona:e.id,valid:n.length===0,errors:n,warnings:s}}function ee(t,e){let o=n=>n.replace(/:[a-zA-Z_]+/g,":param").replace(/\{\{[^}]+\}\}/g,":param");return o(t)===o(e)}async function Ze(t,e){let o=new Set,n=[];async function s(i){if(o.has(i)){let r=n.indexOf(i);return r!==-1?[...n.slice(r),i]:null}o.add(i),n.push(i);let a=await W(t,i);if(a){for(let r of a.journey)if(r.spawns)for(let l of r.spawns){let d=await s(l.persona);if(d)return d}}return n.pop(),null}return s(e)}async function te(t){let e=y.join(t,L);m.mkdirSync(e,{recursive:true});let o=await z(t),n={},s={},i={};for(let u of o){let p=new Set,h=new Set,f=[],g=new Set;for(let b of u.journey){for(let w of b.gates)p.add(w);if(b.flow&&h.add(b.flow),f.push(b.route),b.spawns)for(let w of b.spawns)g.add(w.persona);}n[u.id]={name:u.name,trigger:u.trigger.type,spawned_by:u.trigger.spawned_by,steps:u.journey.length,gates:[...p],flows:[...h],routes:f,spawns:[...g],tags:u.tags||[]};for(let b of p)s[b]||(s[b]=[]),s[b].push(u.id);for(let b of f)i[b]||(i[b]=[]),i[b].push(u.id);}let a=[],r=y.join(t,"portal.yaml");if(m.existsSync(r))try{let u=j.load(m.readFileSync(r,"utf8"));u.routes&&typeof u.routes=="object"&&(a=Object.keys(u.routes).filter(h=>!Object.keys(i).some(f=>ee(h,f))));}catch{}let l={},d=y.join(e,"chains");if(m.existsSync(d)){let u=m.readdirSync(d).filter(p=>p.endsWith(".yaml"));for(let p of u)try{let h=m.readFileSync(y.join(d,p),"utf8"),f=j.load(h);if(f&&f.id){let g=f.order.map(I=>I.persona),b=0,w=new Set;for(let I of g){let P=n[I];if(P){b+=P.steps;for(let R of P.gates)w.add(R);}}l[f.id]={description:f.description||"",order:g,total_steps:b,total_gates:w.size};}}catch{}}let c={version:"1.0",generated:new Date().toISOString(),personas:n,chains:l,gate_coverage:s,route_coverage:i,uncovered_routes:a};return m.writeFileSync(y.join(e,Ke),j.dump(c,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),c}async function Jt(t){let e=await z(t),o=new Set,n=new Set,s=new Set;for(let c of e)for(let u of c.journey){for(let p of u.gates)o.add(p);n.add(u.route),u.flow&&s.add(u.flow);}let i=[],a=[],r=y.join(t,"portal.yaml");if(m.existsSync(r))try{let c=j.load(m.readFileSync(r,"utf8"));c.gates&&typeof c.gates=="object"&&(i=Object.keys(c.gates)),c.routes&&typeof c.routes=="object"&&(a=Object.keys(c.routes));}catch{}let l=[],d=y.join(t,".paradigm","flow-index.json");if(m.existsSync(d))try{let c=JSON.parse(m.readFileSync(d,"utf8"));l=Object.keys(c.flows||{});}catch{}return {routes:{covered:n.size,total:a.length,uncovered:a.filter(c=>!Array.from(n).some(u=>ee(c,u)))},gates:{covered:o.size,total:i.length,uncovered:i.filter(c=>!o.has(c))},flows:{covered:s.size,total:l.length,uncovered:l.filter(c=>!s.has(c))},personas:e.length}}async function Bt(t,e){let o=await z(t),n=[];for(let s of o){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 d of r.spawns)a.push(d.persona);i.length>0&&n.push({persona:s.id,steps:i,spawns_blocked:a});}return n}function et(t,e){let o=e.split(/[.\[\]]+/).filter(Boolean),n=t;for(let s of o){if(n==null||typeof n!="object")return;n=n[s];}return n}function tt(t,e){let o=[];if(e.status!==t.expect.status&&o.push({type:"status",field:"status",expected:t.expect.status,actual:e.status,message:`Step ${t.id}: status is ${e.status}, expected ${t.expect.status}`}),t.expect.body?.has){let n=e.body;for(let s of t.expect.body.has)(!n||typeof n!="object"||!(s in n))&&o.push({type:"body.has",field:s,expected:true,actual:false,message:`Step ${t.id}: body missing key '${s}'`});}if(t.expect.body?.match){let n=e.body;for(let[s,i]of Object.entries(t.expect.body.match)){let a=n?et(n,s):void 0;JSON.stringify(a)!==JSON.stringify(i)&&o.push({type:"body.match",field:s,expected:i,actual:a??null,message:`Step ${t.id}: '${s}' is ${JSON.stringify(a??null)}, expected ${JSON.stringify(i)}`});}}if(t.signals&&t.signals.length>0){let n=e.signals_fired||[];for(let s of t.signals)n.includes(s)||o.push({type:"signal",field:"signals_fired",expected:s,actual:n,message:`Step ${t.id}: signal '${s}' was not fired`});}if(t.gates.length>0&&e.gates_traversed)for(let n of t.gates)e.gates_traversed.includes(n)||o.push({type:"gate",field:"gates_traversed",expected:n,actual:e.gates_traversed,message:`Step ${t.id}: gate '${n}' was not traversed`});return o}async function Kt(t,e={}){let o=[];try{let{SentinelStorage:r}=await import('./dist-W3XCATBJ.js'),l=new r,c=(l.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.complete",scopeValue:t.id,limit:500})||[]).filter(f=>{let g=JSON.parse(f.data_json||"{}");return !(e.run_id&&g.run_id!==e.run_id||e.chain_id&&g.chain_id!==e.chain_id||e.environment&&g.environment!==e.environment)}),p=(l.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.fail",scopeValue:t.id,limit:500})||[]).filter(f=>{let g=JSON.parse(f.data_json||"{}");return !(e.run_id&&g.run_id!==e.run_id||e.chain_id&&g.chain_id!==e.chain_id||e.environment&&g.environment!==e.environment)}),h=new Map;for(let f of [...c,...p]){let g=JSON.parse(f.data_json||"{}");g.step_id&&h.set(g.step_id,g);}for(let f of t.journey){let g=h.get(f.id);if(!g){o.push({step_id:f.id,matched:!1,assertions:[],message:`No Sentinel event found for step '${f.id}' \u2014 step was never exercised`});continue}let b=tt(f,{status:g.status,body:g.body,gates_traversed:g.gates_traversed,signals_fired:g.signals_fired});o.push({step_id:f.id,matched:!0,passed:b.length===0,assertions:b});}}catch{for(let r of t.journey)o.push({step_id:r.id,matched:false,assertions:[],message:"Sentinel unavailable \u2014 cannot validate events"});}let n=o.filter(r=>r.matched).length,s=o.filter(r=>r.passed).length,i=o.filter(r=>r.matched&&!r.passed).length,a=o.reduce((r,l)=>r+l.assertions.length,0);return {run_id:e.run_id,environment:e.environment,steps:o,summary:{total_steps:t.journey.length,matched:n,unmatched:t.journey.length-n,passed:s,failed:i,assertion_failures:a}}}var nt={warn(){}},be=nt;function Vt(t){be=t;}function U(){return be}var O="pack.yaml";var st="paradigm.universityPack";var we=/^[a-z0-9][a-z0-9-]{0,63}$/,he=["track","index","chronological","featured"],ge=64,ot=z$1.object({id:z$1.string().regex(we,"invalid section id"),name:z$1.string().min(1).max(120),order:z$1.number().int().min(0).max(9999),style:z$1.enum(he,{errorMap:()=>({message:`section.style must be one of ${he.join("|")}`})}),description:z$1.string().max(1e3).optional(),default:z$1.boolean({invalid_type_error:"section.default must be a boolean"}).optional()}).strict(),ve=z$1.array(ot).max(ge,`sections must contain \u2264${ge} entries`);z$1.object({sections:ve.optional()}).passthrough();z$1.object({section:z$1.string().regex(we).optional(),order:z$1.number().int().min(0).max(9999).optional()}).passthrough();var xe="@a-company/university",Pe=".paradigm/university",_e=".paradigm/cache/packs.json",C=class extends Error{constructor(t,e){super(`pack-load failed (${t}: ${e})`),this.errorClass=t,this.detail=e,this.name="PackLoadError";}},it=["id","name","version","schema_version","tenant_kind"],rt=new Set(["first-party","project","external"]),Se={id:"main",name:"Curriculum",order:1,style:"track",default:true};function $e(t){if(t==null)return [{...Se}];if(Array.isArray(t)&&t.length===0)return [{...Se}];let e=ve.safeParse(t);if(!e.success){let i=e.error.issues[0],a=i?`${i.path.join(".")||"sections"}: ${i.message}`:"sections failed schema validation";throw new C("manifest-invalid",a)}let o=e.data.map(i=>({...i})),n=new Set;for(let i of o){if(n.has(i.id))throw new C("manifest-invalid",`duplicate section id "${i.id}"`);n.add(i.id);}o.length===1&&!o[0].default&&(o[0]={...o[0],default:true});let s=o.filter(i=>i.default===true);if(s.length>1)throw new C("manifest-invalid",`at most one section may set default: true (found ${s.length})`);return o.sort((i,a)=>i.order-a.order||i.id.localeCompare(a.id)),o}function at(t){if(t&&typeof t=="object"&&"name"in t&&typeof t.name=="string"){let e=t.name;return e==="YAMLException"?"yaml syntax error":e}return "parse error"}function H(t){let e=y.join(t,O);if(!m.existsSync(e))throw new C("missing-manifest",`no ${O} at pack root`);let o;try{o=m.readFileSync(e,"utf-8");}catch{throw new C("manifest-unparseable","file read error")}let n;try{n=j.load(o);}catch(i){throw new C("manifest-unparseable",at(i))}let s=n;if(!s||typeof s!="object")throw new C("manifest-invalid","manifest is not an object");for(let i of it){let a=s[i];if(a==null||a==="")throw new C("missing-required-field",`required field ${String(i)} is missing or empty`)}if(!rt.has(String(s.tenant_kind)))throw new C("missing-required-field","tenant_kind must be one of first-party|project|external");return s.sections=$e(s.sections),s}function ct(t){let e=ut(t);if(e)return e;let o=[],n=y.join(t,"node_modules",xe);if(m.existsSync(y.join(n,O)))try{let i=H(n);o.push({manifest:i,rootDir:n,source:"first-party"});}catch(i){U().warn("first-party pack manifest invalid",{errorClass:i instanceof C?i.errorClass:"other"});}for(let i of dt(t))try{let a=H(i);o.push({manifest:a,rootDir:i,source:"npm"});}catch(a){U().warn("npm pack manifest invalid",{errorClass:a instanceof C?a.errorClass:"other"});}let s=y.join(t,Pe);if(m.existsSync(s)&&m.statSync(s).isDirectory()){let i=y.join(s,O),a;if(m.existsSync(i))try{a=H(s),o.push({manifest:a,rootDir:s,source:"local"});}catch(l){U().warn("local pack manifest invalid",{errorClass:l instanceof C?l.errorClass:"other"});}let r=a?.id??"project";for(let l of lt(s))try{let d=H(l);o.push({manifest:d,rootDir:l,source:"local",parentPackId:r});}catch(d){U().warn("discipline sub-pack manifest invalid",{errorClass:d instanceof C?d.errorClass:"other"});}}return ft(t,o),o}function dt(t){let e=y.join(t,"package.json");if(!m.existsSync(e))return [];let o;try{o=JSON.parse(m.readFileSync(e,"utf8"));}catch{return []}let n=new Set([...Object.keys(o.dependencies||{}),...Object.keys(o.devDependencies||{}),...Object.keys(o.peerDependencies||{})]);if(n.size===0)return [];let s=y.join(t,"node_modules");if(!m.existsSync(s))return [];let i=[];for(let a of n){if(a===xe)continue;let r=y.join(s,a,"package.json");if(!m.existsSync(r))continue;let l;try{l=JSON.parse(m.readFileSync(r,"utf8"));}catch{continue}let d=l.paradigm?.universityPack;if(typeof d!="string"||d.length===0)continue;let c=y.resolve(y.dirname(r),d);m.existsSync(y.join(c,O))&&i.push(c);}return i}function lt(t){let e=[],o;try{o=m.readdirSync(t,{withFileTypes:!0});}catch{return e}for(let n of o){if(!n.isDirectory()||n.name.startsWith("."))continue;let s=y.join(t,n.name);m.existsSync(y.join(s,O))&&e.push(s);}return e}function je(t){try{return m.statSync(y.join(t,"node_modules")).mtime.getTime()}catch{return}}function Ce(t){try{return m.statSync(y.join(t,Pe)).mtime.getTime()}catch{return}}function ut(t){let e=y.join(t,_e);if(!m.existsSync(e))return null;let o;try{o=JSON.parse(m.readFileSync(e,"utf8"));}catch{return null}if(o.version!==1||!Array.isArray(o.packs))return null;let n=je(t),s=Ce(t);return o.node_modules_mtime_ms!==n||o.local_university_mtime_ms!==s?null:o.packs.map(i=>({manifest:i.manifest,rootDir:i.rootDir,source:i.source,...i.parentPackId?{parentPackId:i.parentPackId}:{}}))}function ft(t,e){let o=y.join(t,_e);try{m.mkdirSync(y.dirname(o),{recursive:!0});let n={version:1,node_modules_mtime_ms:je(t),local_university_mtime_ms:Ce(t),packs:e.map(s=>({manifest:s.manifest,rootDir:s.rootDir,source:s.source,...s.parentPackId?{parentPackId:s.parentPackId}:{}}))};m.writeFileSync(o,JSON.stringify(n,null,2),"utf8");}catch{}}var F=".paradigm/university",N="content",V="notes",q="policies",G="quizzes",J="paths",Ie="diplomas",se="index.yaml",Te="config.yaml";function Ae(t){return typeof t=="string"?{packRoot:t,stampPackId:true,resolveDefaultPack:true}:{packRoot:t?.packRoot,stampPackId:t?.stampPackId??true,resolveDefaultPack:t?.resolveDefaultPack??true}}function Ee(t,e,o){return e||(o?oe(t):y.join(t,F))}function oe(t){let e=y.join(t,F);if(m.existsSync(e))return e;try{let n=ct(t).find(s=>s.manifest.tenant_kind==="first-party");if(n)return n.rootDir}catch{}return e}function B(t){if(!m.existsSync(t))return null;let e=y.join(t,O);if(m.existsSync(e))try{return H(t)}catch(n){U().warn("pack manifest invalid, using implicit manifest",{errorClass:n instanceof C?n.errorClass:"other"});}let o=y.basename(t)||"project";return {id:o,name:o,version:"0.0.0",schema_version:"1",tenant_kind:"project",description:"Implicit project pack (pack.yaml not present \u2014 v5 layout)",origin_hint:"authored",sections:$e(void 0)}}function pt(t,e,o){return e?{...t,...t.pack_id?{}:{pack_id:e.id},...t.discipline||!o?{}:{discipline:o}}:t}var ie={name:"Project University",tagline:"Learn the codebase",institution:"Paradigm"},re={primary:"#6366f1",secondary:"#8b5cf6",accent:"#f59e0b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",textMuted:"#94a3b8",success:"#22c55e",error:"#ef4444",font:"Inter, system-ui, sans-serif"},ne={branding:ie,theme:re,content:{categories:[],defaultDifficulty:"beginner",requireApproval:false},diplomas:{includeGlobalPLSAT:true,customCertStyle:null}};function Y(t){let e=y.join(t,F,Te);if(!m.existsSync(e))return {...ne};try{let o=m.readFileSync(e,"utf8"),n=j.load(o);return n?{branding:{...ie,...n.branding||{}},theme:{...re,...n.theme||{}},content:{categories:n.content?.categories||[],defaultDifficulty:n.content?.defaultDifficulty||"beginner",requireApproval:n.content?.requireApproval??!1,defaultCategory:n.content?.defaultCategory},diplomas:{includeGlobalPLSAT:n.diplomas?.includeGlobalPLSAT??!0,customCertStyle:n.diplomas?.customCertStyle??null}}:{...ne}}catch{return {...ne}}}function Oe(t){let e=y.join(t,Te);if(!m.existsSync(e))return null;try{let o=m.readFileSync(e,"utf8"),n=j.load(o);return n?{branding:{...ie,...n.branding||{}},theme:{...re,...n.theme||{}},content:{categories:n.content?.categories||[],defaultDifficulty:n.content?.defaultDifficulty||"beginner",requireApproval:n.content?.requireApproval??!1,defaultCategory:n.content?.defaultCategory},diplomas:{includeGlobalPLSAT:n.diplomas?.includeGlobalPLSAT??!0,customCertStyle:n.diplomas?.customCertStyle??null}}:null}catch{return null}}function Fe(t){let e=y.join(t,O);if(!m.existsSync(e))return false;try{let o=m.readFileSync(e,"utf8"),n=j.load(o);return !n||!Array.isArray(n.sections)?!1:n.sections.some(s=>s&&typeof s.id=="string"&&s.id.length>0)}catch{return false}}function K(t){let e=y.join(t,F,se);if(!m.existsSync(e))return null;try{let o=m.readFileSync(e,"utf8");return j.load(o)}catch{return null}}function Re(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:j.load(e[1]),body:e[2].trim()}}catch{return null}}function mt(t,e){return `---
3
+ ${j.dump(t,{lineWidth:-1,noRefs:true,sortKeys:false})}---
4
+
5
+ ${e}
6
+ `}function yt(t,e,o){let n=de(t,e,".md",o);if(!n)return null;try{let s=m.readFileSync(n,"utf8"),i=Re(s);if(!i)return null;let a=i.frontmatter;return {frontmatter:Ct(a),body:i.body}}catch{return null}}function ht(t,e,o,n){let{packRoot:s,stampPackId:i,resolveDefaultPack:a}=Ae(n),r=e.type==="policy"?q:V,l=Ee(t,s,a),d=y.join(l,N,r);m.mkdirSync(d,{recursive:true});let c=i?B(l):null,u=pt(e,c),p=y.join(d,`${u.id}.md`),h=mt(u,o);return m.writeFileSync(p,h,"utf8"),p}function Ne(t,e,o){let n=de(t,e,".yaml",o);if(!n)return null;try{let s=m.readFileSync(n,"utf8"),i=j.load(s);return !i||!i.id?null:It(i)}catch{return null}}function gt(t,e,o){let{packRoot:n,stampPackId:s,resolveDefaultPack:i}=Ae(o),a=Ee(t,n,i),r=y.join(a,N,G);m.mkdirSync(r,{recursive:true});let l=s?B(a):null,d={...e,...e.pack_id||!l?{}:{pack_id:l.id}},c=y.join(r,`${d.id}.yaml`);return m.writeFileSync(c,j.dump(d,{lineWidth:-1,noRefs:true}),"utf8"),c}function ae(t,e,o){let n=de(t,e,".yaml",o);if(!n)return null;try{let s=m.readFileSync(n,"utf8"),i=j.load(s);return !i||!i.id?null:i}catch{return null}}function St(t,e,o){let n=o??oe(t),s=y.join(n,N,J);m.mkdirSync(s,{recursive:true});let i=y.join(s,`${e.id}.yaml`);return m.writeFileSync(i,j.dump(e,{lineWidth:-1,noRefs:true}),"utf8"),i}function ce(t,e,o){let n=o??y.join(t,F),s=y.join(n,Ie);if(!m.existsSync(s))return [];let i=[];try{let a=m.readdirSync(s).filter(r=>r.endsWith(".yaml"));for(let r of a)try{let l=m.readFileSync(y.join(s,r),"utf8"),d=j.load(l);if(!d||!d.id||e?.student&&d.student!==e.student||e?.type&&d.type!==e.type)continue;i.push(d);}catch{}}catch{}return i.sort((a,r)=>r.earnedAt.localeCompare(a.earnedAt))}function bt(t,e,o){let n=o?X(o):K(t);if(!n)return {entries:[],total:0,returned:0};let s=[...n.entries];if(e.type&&(s=s.filter(l=>l.type===e.type)),e.tag&&(s=s.filter(l=>l.tags.some(d=>d.startsWith(e.tag)))),e.difficulty&&(s=s.filter(l=>l.difficulty===e.difficulty)),e.symbol&&(s=s.filter(l=>l.symbols.some(d=>d===e.symbol))),e.author&&(s=s.filter(l=>l.author===e.author)),e.query){let l=e.query.toLowerCase();s=s.filter(d=>d.title.toLowerCase().includes(l)||d.id.toLowerCase().includes(l)||d.tags.some(c=>c.toLowerCase().includes(l)));}if(e.category&&(s=s.filter(l=>l.category===e.category)),e.section&&(s=s.filter(l=>l.section===e.section)),e.track){let l=Y(t),d=new Map;for(let c of l.content.categories)d.set(c.id,c.track||"core");s=s.filter(c=>(c.category&&d.get(c.category)||"core")===e.track);}let i=s.length,a=e.limit||20,r=s.slice(0,a);return {entries:r,total:i,returned:r.length}}var Me=[N,"src/content"],De=[V,q,G,J];function wt(t){if(!m.existsSync(t))return false;for(let e of De){let o=y.join(t,e);if(m.existsSync(o))try{if(m.readdirSync(o).some(n=>n.endsWith(".md")||n.endsWith(".yaml")))return !0}catch{}}return false}function Le(t){let e=ze(t);return e?y.join(t,e):null}function ze(t){let e=null;for(let o of Me){let n=y.join(t,o);if(m.existsSync(n)&&(e===null&&(e=o),wt(n)))return o}return e}function vt(t){for(let e of Me){let o=y.join(t,e);if(!m.existsSync(o))continue;let n=0;for(let s of De){let i=y.join(o,s);if(m.existsSync(i))try{n+=m.readdirSync(i).filter(a=>a.endsWith(".md")||a.endsWith(".yaml")).length;}catch{}}if(n>0)return n}return 0}function We(t,e){let o=[];for(let i of [V,q]){let a=y.join(t,i);if(m.existsSync(a))try{for(let r of m.readdirSync(a).filter(l=>l.endsWith(".md")))try{let l=m.readFileSync(y.join(a,r),"utf8"),d=Re(l);if(!d)continue;let c=d.frontmatter;o.push({id:c.id||r.replace(".md",""),title:c.title||r,type:c.type||(i===q?"policy":"note"),author:c.author||"unknown",created:c.created||"",updated:c.updated||"",tags:Array.isArray(c.tags)?c.tags:[],symbols:Array.isArray(c.symbols)?c.symbols:[],difficulty:c.difficulty||"beginner",file:`${e}/${i}/${r}`,...c.category?{category:c.category}:{},...typeof c.section=="string"&&c.section?{section:c.section}:{},...typeof c.order=="number"&&Number.isFinite(c.order)?{order:c.order}:{}});}catch{}}catch{}}let n=y.join(t,G);if(m.existsSync(n))try{for(let i of m.readdirSync(n).filter(a=>a.endsWith(".yaml")))try{let a=m.readFileSync(y.join(n,i),"utf8"),r=j.load(a);if(!r||!r.id)continue;o.push({id:r.id,title:r.title||i,type:"quiz",author:r.author||"unknown",created:r.created||"",updated:r.updated||"",tags:r.tags||[],symbols:r.symbols||[],difficulty:r.difficulty||"beginner",file:`${e}/${G}/${i}`,...r.category?{category:r.category}:{},...typeof r.section=="string"&&r.section?{section:r.section}:{},...typeof r.order=="number"&&Number.isFinite(r.order)?{order:r.order}:{}});}catch{}}catch{}let s=y.join(t,J);if(m.existsSync(s))try{for(let i of m.readdirSync(s).filter(a=>a.endsWith(".yaml")))try{let a=m.readFileSync(y.join(s,i),"utf8"),r=j.load(a);if(!r||!r.id)continue;o.push({id:r.id,title:r.title||i,type:"path",author:r.author||"unknown",created:r.created||"",updated:r.updated||"",tags:r.tags||[],symbols:[],file:`${e}/${J}/${i}`,...r.category?{category:r.category}:{},...typeof r.section=="string"&&r.section?{section:r.section}:{},...typeof r.order=="number"&&Number.isFinite(r.order)?{order:r.order}:{}});}catch{}}catch{}return o}function Ue(t){let e=y.join(t,F),o=y.join(e,N),n=We(o,N),s=0,i=y.join(e,Ie);if(m.existsSync(i))try{s=m.readdirSync(i).filter(l=>l.endsWith(".yaml")).length;}catch{}let a={version:"1.0",generatedAt:new Date().toISOString(),totalContent:n.length,entries:n,diplomaCount:s};m.mkdirSync(e,{recursive:true});let r=y.join(e,se);return m.writeFileSync(r,j.dump(a,{lineWidth:-1,noRefs:true}),"utf8"),a}function X(t,e){let o=y.join(t,se);if(m.existsSync(o))try{let a=m.readFileSync(o,"utf8"),r=j.load(a);if(r)return r}catch{}let n=ze(t);if(!n)return {version:"1.0",generatedAt:new Date().toISOString(),totalContent:0,entries:[],diplomaCount:0};let s=y.join(t,n),i=We(s,n);return {version:"1.0",generatedAt:new Date().toISOString(),totalContent:i.length,entries:i,diplomaCount:0}}function kt(t,e,o){let n=o?X(o):K(t)||Ue(t),s=[],i=n.entries;e?.id&&(i=i.filter(c=>c.id===e.id));let a=null;e?.deep&&(a=He(t));let r=new Set(n.entries.map(c=>c.id));for(let c of i){if(c.title||s.push({contentId:c.id,severity:"error",check:"missing-title",message:"Content is missing a title",fix:"Add a title field to the content frontmatter"}),c.type==="quiz"&&xt(t,c.id,s,o),c.type==="path"&&Pt(t,c.id,r,s,o),a&&c.symbols.length>0){Y(t).content.categories.find(f=>f.id===c.category)?.validationStrictness==="relaxed";for(let f of c.symbols)a.has(f)||s.push({contentId:c.id,severity:"warning",check:"broken-symbol-ref",message:`Symbol "${f}" not found in scan-index`,fix:`Remove or update the symbol reference in ${c.id}`});}e?.deep&&c.symbols.length>0&&c.updated&&At(t,c,s);}_t(t,n,s,o);let l=ce(t);for(let c of l)if(c.total>0&&c.percentage!==Math.round(c.score/c.total*1e4)/100){let u=Math.round(c.score/c.total*1e4)/100;Math.abs(c.percentage-u)>.1&&s.push({contentId:c.id,severity:"warning",check:"diploma-score-mismatch",message:`Diploma percentage ${c.percentage} doesn't match score ${c.score}/${c.total} (expected ${u})`});}let d=Tt(t,n);return {status:s.some(c=>c.severity==="error")?"errors":s.length>0?"warnings":"healthy",totalContent:n.totalContent,checked:i.length,issues:s,symbolCoverage:d}}function xt(t,e,o,n){let s=Ne(t,e,n);if(!s){o.push({contentId:e,severity:"error",check:"unreadable-quiz",message:"Quiz file could not be parsed"});return}(!s.passThreshold||s.passThreshold<0||s.passThreshold>1)&&o.push({contentId:e,severity:"warning",check:"invalid-pass-threshold",message:`passThreshold should be between 0 and 1, got ${s.passThreshold}`,fix:"Set passThreshold to a value between 0.0 and 1.0"});for(let i of s.questions){if(!i.choices||typeof i.choices!="object"){o.push({contentId:e,severity:"error",check:"invalid-quiz-choices",message:`Question ${i.id} has no choices defined`});continue}(!i.correct||!(i.correct in i.choices))&&o.push({contentId:e,severity:"error",check:"invalid-quiz-answer",message:`Question ${i.id}: correct answer "${i.correct}" not found in choices [${Object.keys(i.choices).join(", ")}]`,fix:`Set correct to one of: ${Object.keys(i.choices).join(", ")}`});}}function Pt(t,e,o,n,s){let i=ae(t,e,s);if(!i){n.push({contentId:e,severity:"error",check:"unreadable-path",message:"Learning path file could not be parsed"});return}for(let a of i.steps)a.content.startsWith("plsat:")||o.has(a.content)||n.push({contentId:e,severity:"error",check:"broken-path-step",message:`Learning path step references "${a.content}" which doesn't exist`,fix:`Create content with id "${a.content}" or remove this step`});}function _t(t,e,o,n){let s=n??y.join(t,F),i=B(s);if(!i||!i.sections||i.sections.length===0)return;let a=new Set(i.sections.map(d=>d.id)),r=i.sections.find(d=>d.default===true);for(let d of e.entries)d.section&&!a.has(d.section)&&o.push({contentId:d.id,severity:"warning",check:"dangling-section-ref",message:`Entry references section "${d.section}" which is not declared in pack.yaml`,fix:`Add a section with id "${d.section}" to pack.yaml, or remove the section field`});let l=new Map;for(let d of i.sections)l.set(d.id,0);for(let d of e.entries)d.section&&a.has(d.section)?l.set(d.section,(l.get(d.section)||0)+1):!d.section&&r&&l.set(r.id,(l.get(r.id)||0)+1);for(let d of i.sections)(l.get(d.id)||0)===0&&o.push({contentId:d.id,severity:"warning",check:"empty-section",message:`Section "${d.id}" has zero entries`,fix:`Add at least one entry with section: "${d.id}", or remove the section from pack.yaml`});}function $t(t,e){let o=K(t);if(!o)return [];let n=[];for(let s of o.entries)if(s.symbols.includes(e)){let i=qe(t,s,e);n.push({id:s.id,title:s.title,type:s.type,stale:i});}return n}function jt(t,e,o){let n=o?X(o):K(t);if(!n)return {paths:[],suggestedContent:[],extracurricular:[],diplomaCount:0,totalContent:0};let s=o&&Oe(o)||Y(t),i=new Set;for(let f of s.content.categories)f.excludeFromOnboarding&&i.add(f.id);let a=n.entries.filter(f=>!f.category||!i.has(f.category)),r=n.entries.filter(f=>f.category&&i.has(f.category)),l=a.filter(f=>f.type==="path"),d=e?ce(t,{student:e},o):[],c=new Set(d.map(f=>f.source)),u=l.map(f=>{let g=ae(t,f.id,o);return {id:f.id,title:f.title,steps:g?.steps.length||0,completed:c.has(f.id)}}),p=a.filter(f=>f.type!=="path"&&(f.difficulty==="beginner"||f.tags.includes("onboarding"))).slice(0,10),h={paths:u,suggestedContent:p,extracurricular:r,diplomaCount:d.length,totalContent:n.totalContent};if(o&&Fe(o)){let g=(B(o)?.sections??[]).slice().sort((b,w)=>b.order-w.order||b.id.localeCompare(w.id));if(g.length>0){let b=g.find(P=>P.default===true)??g[0],w=new Map;for(let P of g)w.set(P.id,[]);for(let P of n.entries){let R=P.section&&w.has(P.section)?P.section:b.id,Q=w.get(R);Q&&Q.push(P);}let I=(P,R)=>{let Q=typeof P.order=="number"?P.order:Number.POSITIVE_INFINITY,Be=typeof R.order=="number"?R.order:Number.POSITIVE_INFINITY;return Q-Be||P.id.localeCompare(R.id)};h.sections=g.map(P=>({id:P.id,name:P.name,entries:(w.get(P.id)??[]).sort(I)}));}}return h}function de(t,e,o,n){let s=n??y.join(t,F),i=Le(s)??y.join(s,N);for(let a of [V,q,G,J]){let r=y.join(i,a,`${e}${o}`);if(m.existsSync(r))return r}return null}function Ct(t){return {id:t.id||"",title:t.title||"",type:t.type||"note",author:t.author||"unknown",created:t.created||"",updated:t.updated||"",tags:Array.isArray(t.tags)?t.tags:[],symbols:Array.isArray(t.symbols)?t.symbols:[],difficulty:t.difficulty||"beginner",estimatedMinutes:t.estimatedMinutes,prerequisites:Array.isArray(t.prerequisites)?t.prerequisites:[],...t.category?{category:t.category}:{},...t.origin?{origin:t.origin}:{},...t.source?{source:t.source}:{},...t.pack_id?{pack_id:t.pack_id}:{},...t.discipline?{discipline:t.discipline}:{},...t.section?{section:t.section}:{},...typeof t.order=="number"?{order:t.order}:{}}}function It(t){return {...t,tags:t.tags||[],symbols:t.symbols||[],difficulty:t.difficulty||"beginner",passThreshold:t.passThreshold??.7,questions:t.questions||[]}}function He(t){let e=new Set,o=y.join(t,".paradigm","scan-index.json");if(!m.existsSync(o))return e;try{let n=m.readFileSync(o,"utf8"),s=JSON.parse(n);if(s.symbols&&Array.isArray(s.symbols))for(let i of s.symbols)i.symbol&&e.add(i.symbol);}catch{}return e}function Tt(t,e){let o=He(t),n=new Set;for(let i of e.entries)for(let a of i.symbols)o.has(a)&&n.add(a);let s=o.size;return {totalSymbols:s,coveredByContent:n.size,percentage:s>0?Math.round(n.size/s*100):0}}function qe(t,e,o){if(!e.updated)return false;let n=new Date(e.updated).getTime();if(isNaN(n))return false;let s=y.join(t,".paradigm","scan-index.json");if(!m.existsSync(s))return false;try{let i=m.readFileSync(s,"utf8"),a=JSON.parse(i);if(a.symbols&&Array.isArray(a.symbols)){for(let r of a.symbols)if(r.symbol===o&&r.filePath){let l=y.join(t,r.filePath);if(m.existsSync(l)&&m.statSync(l).mtime.getTime()>n)return !0}}}catch{}return false}function At(t,e,o){for(let n of e.symbols)if(qe(t,e,n)){o.push({contentId:e.id,severity:"warning",check:"stale-content",message:`Content may be stale: symbol "${n}" was updated after content was last modified`,fix:`Review and update ${e.id} to reflect changes to ${n}`});break}}var M=".paradigm/protocols",Ge="index.yaml";async function le(t){let e=y.join(t,M);if(!m.existsSync(e))return [];let o=m.readdirSync(e).filter(s=>s.endsWith(".protocol")).sort(),n=[];for(let s of o)try{let i=m.readFileSync(y.join(e,s),"utf8"),a=j.load(i);a?.id&&a?.name&&n.push(a);}catch{}return n}async function Et(t,e){let o=e.replace(/^P-/,""),n=y.join(t,M,`${o}.protocol`);if(m.existsSync(n))try{let i=m.readFileSync(n,"utf8");return j.load(i)}catch{return null}return (await le(t)).find(i=>i.id===e)||null}async function cn(t){let e=y.join(t,M,Ge);if(!m.existsSync(e))return null;try{let o=m.readFileSync(e,"utf8");return j.load(o)}catch{return null}}async function dn(t,e,o=3){let n=await le(t);if(n.length===0)return [];let s=Ft(e);if(s.length===0)return [];let i=[];for(let a of n){let r=0;for(let c of a.trigger){let u=c.toLowerCase();for(let p of s)u.includes(p)&&(r+=3);}for(let c of a.tags){let u=c.toLowerCase();for(let p of s)(u.includes(p)||p.includes(u))&&(r+=2);}let l=a.name.toLowerCase(),d=a.description.toLowerCase();for(let c of s)l.includes(c)&&(r+=1),d.includes(c)&&(r+=1);for(let c of a.steps)if(c.notes){let u=c.notes.toLowerCase();for(let p of s)u.includes(p)&&(r+=.5);}r>0&&i.push({protocol:a,score:r});}return i.sort((a,r)=>r.score-a.score),i.slice(0,o)}async function ln(t,e){let o=y.join(t,M);m.existsSync(o)||m.mkdirSync(o,{recursive:true});let n=Nt(e.name),s=`P-${n}`,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=y.join(o,`${n}.protocol`);return m.writeFileSync(r,j.dump(a,{lineWidth:-1,noRefs:true}),"utf8"),s}async function un(t,e,o,n=false){let s=await Et(t,e);if(!s)return false;o.name!==void 0&&(s.name=o.name),o.description!==void 0&&(s.description=o.description),o.trigger!==void 0&&(s.trigger=o.trigger),o.tags!==void 0&&(s.tags=o.tags),o.symbols!==void 0&&(s.symbols=o.symbols),o.exemplar!==void 0&&(s.exemplar=o.exemplar),o.steps!==void 0&&(s.steps=o.steps),o.status!==void 0&&(s.status=o.status),o.verified_by!==void 0&&(s.verified_by=o.verified_by),n&&(s.last_verified=new Date().toISOString(),s.verified_by=o.verified_by||"claude-opus-4-6");let i=e.replace(/^P-/,""),a=y.join(t,M,`${i}.protocol`);return m.writeFileSync(a,j.dump(s,{lineWidth:-1,noRefs:true}),"utf8"),true}function Ot(t,e){let o=[],n="current";if(e.exemplar){let s=y.join(t,e.exemplar);m.existsSync(s)?m.statSync(s).mtime.toISOString()>e.last_verified&&(o.push(`Exemplar modified since last verified: ${e.exemplar}`),n!=="broken"&&(n="stale")):(o.push(`Exemplar missing: ${e.exemplar}`),n="broken");}for(let s of e.steps){if(s.template_from){let i=y.join(t,s.template_from);m.existsSync(i)||(o.push(`Template file missing: ${s.template_from}`),n="broken");}if(s.action==="modify"&&s.target){let i=y.join(t,s.target);!s.target.includes("{")&&!m.existsSync(i)&&(o.push(`Modify target missing: ${s.target}`),n="broken");}}return {status:n,issues:o}}async function fn(t){let e=await le(t),o=[],n=0,s=0,i=0;for(let l of e){let d=Ot(t,l);if(l.status!==d.status){l.status=d.status;let c=l.id.replace(/^P-/,""),u=y.join(t,M,`${c}.protocol`);m.existsSync(u)&&m.writeFileSync(u,j.dump(l,{lineWidth:-1,noRefs:true}),"utf8");}switch(d.status){case "current":n++;break;case "stale":s++;break;case "broken":i++;break}o.push({id:l.id,name:l.name,status:d.status,last_verified:l.last_verified,trigger:l.trigger,tags:l.tags});}let a={version:"1.0",generated:new Date().toISOString(),protocols:o,health:{total:e.length,current:n,stale:s,broken:i}},r=y.join(t,M);if(e.length>0){m.existsSync(r)||m.mkdirSync(r,{recursive:true});let l=y.join(r,Ge);m.writeFileSync(l,j.dump(a,{lineWidth:-1,noRefs:true}),"utf8");}return a}function pn(t,e,o){if(!e||e.length<2)return null;let n={};for(let s of e){let i=y.dirname(s);n[i]||(n[i]=[]),n[i].push(s);}for(let[s,i]of Object.entries(n)){if(i.length<2)continue;let a=y.join(t,s);if(!m.existsSync(a))continue;let l=m.readdirSync(a).filter(d=>{let c=y.extname(d);return [".ts",".tsx",".js",".jsx",".rs",".py"].includes(c)}).filter(d=>!i.some(c=>y.basename(c)===d));if(l.length>0){let d=y.join(s,l[0]),c=[...i.map(u=>({action:"create",target:u})),...o.map(u=>({action:"modify",target:u}))];return {hint:`This session created ${i.length} new files in ${s}/ following existing patterns. Consider recording a protocol.`,draft:{name:`Add a ${y.basename(s).replace(/s$/,"")}`,exemplar:d,steps:c}}}}return null}function Ft(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(e=>e.length>1).filter(e=>!Rt.has(e))}var Rt=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 Nt(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function gn(t,e="unknown"){j$1().trackToolCall(e,t);}function Sn(t,e="paradigm://unknown"){j$1().trackResourceRead(e,t);}function Mt(){k();}function Dt(t,e){switch(t){case "paradigm_search":return {summary:`Searched for "${e.query}"${e.type?` (type: ${e.type})`:""}`,symbol:e.query};case "paradigm_ripple":return {summary:`Ripple analysis on ${e.symbol}${e.depth?` (depth: ${e.depth})`:""}`,symbol:e.symbol};case "paradigm_related":return {summary:`Checked relations for ${e.symbol}`,symbol:e.symbol};case "paradigm_status":return {summary:"Checked project status"};case "paradigm_navigate":{let o=e.intent,n=e.target,s=e.task;return o==="context"&&s?{summary:`Navigate context: "${s}"`}:n?{summary:`Navigate ${o||"find"}: ${n}`,symbol:n}:{summary:`Navigate (${o||"unknown"})`}}case "paradigm_gates_for_route":return {summary:`Gate suggestions for ${e.method||"GET"} ${e.route}`};case "paradigm_wisdom_context":return {summary:`Checked wisdom for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_context":return {summary:`Checked history for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_record":return {summary:`Recorded ${e.type}: ${(e.description||"").slice(0,60)}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_fragility":return {summary:`Checked fragility for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_flows_affected":return {summary:`Checked flows affected by ${e.symbol}`,symbol:e.symbol};case "paradigm_reindex":return {summary:"Rebuilt static index files"};case "paradigm_session_checkpoint":return {summary:`Checkpoint: phase=${e.phase}, ${(e.context||"").slice(0,60)}`};case "paradigm_task_create":return {summary:`Created task: "${(e.blurb||"").slice(0,60)}"`};case "paradigm_task_done":return {summary:`Completed task ${e.id}`};case "paradigm_task_shelve":return {summary:`Shelved task ${e.id}`};case "paradigm_task_list":return {summary:`Listed tasks (status: ${e.status||"open"})`};case "paradigm_task_update":return {summary:`Updated task ${e.id}`};case "paradigm_assessment_record":return {summary:`Assessment: ${(e.title||"").slice(0,60)} \u2192 ${e.arc_id}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_assessment_list":return {summary:e.arc_id?`Listed entries in ${e.arc_id}`:"Listed assessment arcs"};case "paradigm_assessment_search":return {summary:`Searched assessments${e.symbol?` for ${e.symbol}`:""}`,symbol:e.symbol};case "paradigm_assessment_arc_create":return {summary:`Created arc: ${e.id}`};case "paradigm_assessment_arc_close":return {summary:`Closed arc: ${e.arc_id}`};default:{let o=t.replace(/^paradigm_/,""),n=Object.values(e).find(s=>typeof s=="string"&&s.length>0);return {summary:n?`${o}: ${n.slice(0,60)}`:o,symbol:e.symbol||void 0}}}}function bn(t,e){let o=j$1(),{summary:n,symbol:s}=Dt(t,e);o.addBreadcrumb("tool-call",n,{tool:t,symbol:s});}function wn(){return [{name:"paradigm_session_health",description:"Check if context handoff is recommended based on session activity. Call this periodically during long sessions. Returns usage percentage and recommendation (continue, consider-handoff, handoff-recommended, handoff-urgent). ~100 tokens.",inputSchema:{type:"object",properties:{estimatedTotalTokens:{type:"number",description:"Optional: Your estimate of total conversation tokens (if available)"},contextWindowSize:{type:"number",description:"Context window size in tokens (default: 200000)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_context_check",description:"DEPRECATED: renamed to paradigm_session_health. This alias will be removed in a future version.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_handoff_prepare",description:"Prepare a handoff summary. Generates a structured handoff file with markdown summary and recovery instructions. Returns structured markdown with summary, modified files, and next steps. ~300 tokens.",inputSchema:{type:"object",properties:{summary:{type:"string",description:"Brief summary of work done in this session"},nextSteps:{type:"array",items:{type:"string"},description:"List of next steps for the continuing session"},agent:{type:"string",description:'Target agent role (e.g., "builder", "architect")'},modifiedFiles:{type:"array",items:{type:"string"},description:"List of files modified in this session"},symbolsTouched:{type:"array",items:{type:"string"},description:"List of symbols (@feature, #component, etc.) touched"},openQuestions:{type:"array",items:{type:"string"},description:"Unresolved questions or decisions needed"}},required:["summary"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_session_stats",description:"Get current session statistics (MCP interactions, estimated tokens). Returns tool call count, estimated tokens used, and cost breakdown. ~100 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_session_recover",description:"Load previous session breadcrumbs for continuity. Call this at the start of a new session to understand what was done before. Returns symbols modified, files explored, recent actions, and suggestions for continuity. ~200 tokens. NOTE: Recovery data is automatically surfaced as a preamble on the first tool call of each session \u2014 explicit calls are retained for direct inspection or forcing a second recovery pass.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["resume","pick up","continue","what was I doing","last session","recover"]},{name:"paradigm_session_checkpoint",description:"Save a cognitive-transition checkpoint for crash recovery. Call when transitioning between phases (planning \u2192 implementing \u2192 validating \u2192 complete). ~100 tokens.",inputSchema:{type:"object",properties:{phase:{type:"string",enum:["planning","implementing","validating","complete"],description:"Current workflow phase"},context:{type:"string",description:"What's top-of-mind right now (1-3 sentences)"},externalId:{type:"string",description:'Optional: deterministic ID from external source for automatic session recovery (e.g. "linear:PROJ-123", "github:owner/repo#42")'},plan:{type:"string",description:"Optional: the current plan or approach"},modifiedFiles:{type:"array",items:{type:"string"},description:"Optional: files modified so far"},symbolsTouched:{type:"array",items:{type:"string"},description:"Optional: symbols touched so far"},decisions:{type:"array",items:{type:"string"},description:"Optional: key decisions made so far"}},required:["phase","context"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function vn(t,e,o){let n=j$1();if(t==="paradigm_session_health"||t==="paradigm_context_check"){let s=e.contextWindowSize||2e5,i=e.estimatedTotalTokens,a=n.getStats(),{recommendation:r,message:l,usagePercent:d,signals:c}=n.getHandoffRecommendation(s,i),u=n.getDurationMinutes();return {handled:true,text:JSON.stringify({recommendation:r,message:l,stats:{sessionDurationMinutes:u,mcpToolCalls:a.totals.toolCallCount,mcpResourceReads:a.totals.resourceReadCount,estimatedMcpTokens:a.totals.totalTokens,estimatedTotalTokens:i||Math.round(a.totals.totalTokens*5),contextWindowSize:s,usagePercent:d},signals:c,action:r==="continue"?null:"Call paradigm_handoff_prepare to create handoff file"},null,2)}}if(t==="paradigm_handoff_prepare"){let s=e.summary,i=e.nextSteps||[],a$1=e.agent||"builder",r=e.modifiedFiles||[],l=e.symbolsTouched||[],d=e.openQuestions||[],c=n.getStats(),u=n.getCostBreakdown(),p=`h${Date.now().toString(36)}`,h=new Date().toISOString(),f={id:p,timestamp:h,from:"current-session",to:a$1,summary:s,nextSteps:i,modifiedFiles:r,symbolsTouched:l,openQuestions:d,sessionStats:{duration:n.getDurationMinutes(),mcpCalls:c.totals.toolCallCount+c.totals.resourceReadCount,estimatedTokens:c.totals.totalTokens,estimatedCostUsd:u.total.costUsd,model:u.model},status:"pending"},g=false;try{a(o.rootDir,f),g=!0;}catch{}let b=`# Handoff: ${h}
7
+
8
+ ## Session Summary
9
+ ${s}
10
+
11
+ ## Next Steps
12
+ ${i.map((w,I)=>`${I+1}. ${w}`).join(`
13
+ `)||"(none specified)"}
14
+
15
+ ## Key Context
16
+ - Modified files: ${r.length>0?r.join(", "):"(not specified)"}
17
+ - Symbols touched: ${l.length>0?l.join(", "):"(not specified)"}
18
+ - Open questions: ${d.length>0?d.join(", "):"(none)"}
19
+ `;return Mt(),{handled:true,text:JSON.stringify({handoff:f,markdownSummary:b,persisted:g,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let s=n.getStats(),i=n.getCostBreakdown(),a=n.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(t==="paradigm_session_recover"){let{checkpoint:s,pendingHandoffs:i,previousSession:a}=Je(o.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 d=Date.now()-s.timestamp,c=Math.round(d/6e4),u=Math.round(d/36e5);r.checkpoint={phase:s.phase,context:s.context,age:u>1?`${u} hours ago`:`${c} 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(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}))};}if(a){let d=Date.now()-a.lastActivity,c=Math.round(d/6e4),u=Math.round(d/36e5),h=a.breadcrumbs.slice(-10).map(f=>({time:new Date(f.timestamp).toISOString(),action:f.action,tool:f.tool,symbol:f.symbol,summary:f.summary}));r.previousSession={sessionId:a.sessionId,startTime:new Date(a.startTime).toISOString(),lastActivity:new Date(a.lastActivity).toISOString(),age:u>1?`${u} hours ago`:`${c} minutes ago`},r.context={symbolsModified:a.symbolsModified,filesExplored:a.filesExplored},r.recentActions=h;}if(i.length>0){r.pendingHandoffs=i.map(d=>({id:d.id,timestamp:d.timestamp,from:d.from,to:d.to,summary:d.summary,nextSteps:d.nextSteps,modifiedFiles:d.modifiedFiles,symbolsTouched:d.symbolsTouched,openQuestions:d.openQuestions}));for(let d of i)try{c(o.rootDir,d.id);}catch{}}let l="Continue where the previous session left off.";if(s)l=`Previous session was in "${s.phase}" phase: ${s.context}`,s.decisions?.length&&(l+=` Key decisions: ${s.decisions.slice(0,2).join("; ")}`);else if(i.length>0){let d=i[i.length-1];l=`Handoff received: "${d.summary}". `,d.nextSteps.length>0&&(l+=`Start with: ${d.nextSteps[0]}`);}else if(a){let d=a.breadcrumbs.slice(-10);if(d.length>0){let c=d[d.length-1];c.symbol&&(l=`Last work involved ${c.symbol}. Consider checking its current state with paradigm_ripple.`);}}return r.suggestion=l,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.",n.markRecovered(),{handled:true,text:JSON.stringify(r,null,2)}}if(t==="paradigm_session_checkpoint"){n.setRootDir(o.rootDir);let s=e.phase,i=e.context,a=e.externalId,r=e.plan,l=e.modifiedFiles,d=e.symbolsTouched,c=e.decisions,{checkpoint:u,persisted:p}=n.saveCheckpoint({phase:s,context:i,externalId:a,plan:r,modifiedFiles:l,symbolsTouched:d,decisions:c}),h=p.local||p.global;return {handled:true,text:JSON.stringify({saved:h,persisted:p,checkpoint:{phase:u.phase,context:u.context,sessionId:u.sessionId,...u.externalId?{externalId:u.externalId}:{},timestamp:new Date(u.timestamp).toISOString(),modifiedFiles:u.modifiedFiles?.length||0,symbolsTouched:u.symbolsTouched?.length||0,decisions:u.decisions?.length||0,recentBreadcrumbs:u.recentBreadcrumbs?.length||0},...h?{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 Je(t){let e=j$1();e.setRootDir(t);let o=e.loadCheckpoint(),n=e.loadPreviousSession(),s=[];try{s=b(t);}catch{}return {checkpoint:o,pendingHandoffs:s,previousSession:n}}async function kn(t){let{checkpoint:e,pendingHandoffs:o}=Je(t);if(!e&&o.length===0)return null;let n=[];if(n.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`;n.push(`Previous session was in "${e.phase}" phase (${r}): ${e.context}`),e.modifiedFiles?.length&&n.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&n.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&n.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&n.push(`Plan: ${e.plan.slice(0,200)}`);}if(o.length>0){let s=o[o.length-1];n.push(`Pending handoff: "${s.summary}"`),s.nextSteps.length>0&&n.push(`Next steps: ${s.nextSteps.slice(0,3).join(", ")}`);}try{try{let{reapStaleInProgress:l}=await import('./task-settlement-NW4XMJGJ.js');await l(t);}catch{}let{assembleCaptainBoard:s,proposeClaimantFor:i}=await import('./captain-YUP3KVCA.js'),a=await s(t,{proposeClaimants:!0}),r=a.unclaimed.slice(0,5);if(a.summary.open>0||a.summary.inFlight>0||a.summary.runs>0){n.push(""),n.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:l,loadTask:d}=await import('./task-loader-IGQQ6ZFL.js');for(let c of r){let u=c.tags.length>0?` [${c.tags.join(", ")}]`:"",p=c.proposedClaimant;if(!p){let h=await d(t,c.taskId);h&&(p=await i(h,t));}if(p){try{let h=await d(t,c.taskId);h&&!h.claimant&&h.status==="open"&&await l(t,c.taskId,{claimant:p});}catch{}n.push(` [${c.priority}] ${c.taskId}: ${c.blurb}${u} \u2192 proposed ${p.ref}`);}else n.push(` [${c.priority}] ${c.taskId}: ${c.blurb}${u}`);}}}catch{try{let{loadTasks:s}=await import('./task-loader-IGQQ6ZFL.js'),i=await s(t,{status:"open",limit:5});if(i.length>0){n.push(""),n.push("Open tasks:");for(let a of i){let r=a.tags.length>0?` [${a.tags.join(", ")}]`:"";n.push(` [${a.priority}] ${a.id}: ${a.blurb}${r}`);}}}catch{}}try{let{loadLoreEntries:s}=await import('./lore-loader-PXFKMKAN.js'),a=(await s(t,{limit:10})).filter(r=>r.tags?.some(l=>l.startsWith("arc:")));if(a.length>0){let r=new Map;for(let c of a){let u=c.tags?.find(p=>p.startsWith("arc:"))||"";r.set(u,(r.get(u)||0)+1);}let l=e?.symbolsTouched||[];if((l.length>0?a.filter(c=>c.symbols_touched?.some(u=>l.includes(u))):a.slice(0,3)).length>0||r.size>0){n.push(""),n.push("Active lore arcs:");for(let[c,u]of r)n.push(` ${c} (${u} entries)`);}}}catch{}try{let{loadNominations:s}=await import('./nomination-engine-AQHU2KBU.js'),i=s(t,{pending_only:!0}).filter(a=>a.urgency==="critical"||a.urgency==="high");if(i.length>0){n.push(""),n.push("Ambient nominations (urgent):");for(let a of i.slice(0,5))n.push(` [${a.urgency}] ${a.brief}`);i.length>5&&n.push(` ... and ${i.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return n.push(""),n.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."),n.push("---"),n.join(`
20
+ `)}export{vt as A,Ue as B,kt as C,$t as D,jt as E,le as F,Et as G,cn as H,dn as I,ln as J,un as K,Ot as L,fn as M,pn as N,gn as O,Sn as P,bn as Q,wn as R,vn as S,kn as T,Lt as a,z as b,W as c,Wt as d,ye as e,Ut as f,Ht as g,qt as h,Gt as i,te as j,Jt as k,Bt as l,Kt as m,Vt as n,O as o,st as p,oe as q,B as r,Y as s,yt as t,ht as u,Ne as v,gt as w,ae as x,St as y,bt as z};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import {c,b as b$1}from'./chunk-5TAVYPOV.js';import*as i from'fs';import*as l from'path';import*as w from'os';import*as f from'js-yaml';var z={};c(z,{addNotebookEntry:()=>C,classifyNotebookScope:()=>E,incrementApplied:()=>v,loadNotebookEntries:()=>N,normalizeConcept:()=>u,promoteFromLore:()=>P,searchNotebooks:()=>$});function u(o){if(!o)return "";let t=o.trim();return t=t.replace(/^symbol:/i,""),t=t.replace(/^[#$^!~@&%?]/,""),t.trim().toLowerCase()}function N(o,t,n){let s=new Map,a=l.join(y,o);k(a,s);let e=l.join(t,b,o);k(e,s);let r=Array.from(s.values());if(n?.concepts&&n.concepts.length>0){let p=new Set(n.concepts.map(u));r=r.filter(c=>c.concepts.some(m=>p.has(u(m))));}if(n?.tags&&n.tags.length>0){let p=new Set(n.tags.map(c=>c.toLowerCase()));r=r.filter(c=>c.tags.some(m=>p.has(m.toLowerCase())));}return r.sort((p,c)=>c.appliedCount-p.appliedCount)}function k(o,t){if(i.existsSync(o))try{let n=i.readdirSync(o).filter(s=>s.startsWith(_)&&s.endsWith(h));for(let s of n)try{let a=i.readFileSync(l.join(o,s),"utf-8"),e=f.load(a);e?.id&&t.set(e.id,e);}catch{}}catch{}}function $(o,t,n){let s=N(o,n),a=t.toLowerCase();return s.filter(e=>e.context.toLowerCase().includes(a)||e.snippet.toLowerCase().includes(a)||e.concepts.some(r=>r.toLowerCase().includes(a))||e.tags.some(r=>r.toLowerCase().includes(a)))}function E(o){let t=[o.context,o.snippet,...o.concepts,...o.tags].join(" ").toLowerCase();return ["paradigm","mcp_","mcp tool",".paradigm/","lore entry","lore record","aspect","^gate","portal.yaml",".purpose","sentinel","symphony","ambient nomination","paradigm_"," pan ","agent notebook","concept anchor","symbol system","work log","knowledge stream","nevr.land","neverland"].some(s=>t.includes(s))?"platform-specific":/[#$^!~][a-z][a-z0-9-]{2,}/.test(t)||/\/[a-z0-9_-]{2,}\/[a-z0-9_-]/.test(t)?"project-specific":"generalizable"}function C(o,t,n,s){let a=new Date().toISOString(),e=(t.concepts[0]||t.context.split(" ").slice(0,4).join(" ")||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),p=`nb-${o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}-${e}`,c=t.scope??E({context:t.context,snippet:t.snippet,concepts:t.concepts,tags:t.tags}),m=Array.from(new Set((t.concepts||[]).map(u).filter(Boolean))),g={...t,concepts:m,id:p,scope:c,publishable:t.publishable??true,appliedCount:0,created:a,updated:a},d=n==="global"?l.join(y,o):l.join(s||process.cwd(),b,o);i.existsSync(d)||i.mkdirSync(d,{recursive:true});let j=`${p}${h}`,S=l.join(d,j),x=f.dump(g,{lineWidth:120,noRefs:true,sortKeys:false});return i.writeFileSync(S,x,"utf-8"),{entry:g,filePath:S}}async function P(o,t,n,s="global"){let{loadLoreEntry:a}=await import('./lore-loader-PXFKMKAN.js'),e=await a(n,t);if(!e)return null;let r=[];if(e.symbols_touched)for(let m of e.symbols_touched){let g=m.replace(/^[#$^!~]/,"").toLowerCase();r.push(g);}let p=e.summary||"";e.body&&(p+=`
3
+
4
+ `+e.body);let c={source:"lore",loreEntryId:t,originProject:l.basename(n),createdBy:o};return C(o,{context:e.title||`Promoted from ${t}`,snippet:p,provenance:c,confidence:e.confidence??.7,concepts:r,tags:e.tags||[]},s,n)}function v(o,t,n){let s=l.join(n,b,o),a=l.join(y,o);for(let e of [s,a]){let r=l.join(e,`${t}${h}`);if(i.existsSync(r))try{let p=i.readFileSync(r,"utf-8"),c=f.load(p);if(c)return c.appliedCount=(c.appliedCount||0)+1,c.updated=new Date().toISOString(),i.writeFileSync(r,f.dump(c,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var y,b,_,h,T=b$1(()=>{y=l.join(w.homedir(),".paradigm","notebooks"),b=".paradigm/notebooks",_="nb-",h=".yaml";});export{u as a,N as b,$ as c,E as d,C as e,P as f,v as g,z as h,T as i};
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import {v as v$1,b,q,p,o,s as s$1,i,k,l,a,m,t,u,j as j$1}from'./chunk-FRQRREJ6.js';import {e}from'./chunk-Q527BPUF.js';import {z,f,p as p$1}from'./chunk-KAFQA7HV.js';import {s,e as e$1,g as g$1,b as b$2,f as f$1,h}from'./chunk-33ERV2MW.js';import {g,b as b$1,a as a$1}from'./chunk-QGZRM6ZB.js';import*as v from'fs';import*as j from'path';v$1();b();z();g();s();function be(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function re(s){let e=Date.now(),t=s.match(/^(\d+)(m|h|d)$/);if(t){let r=parseInt(t[1],10),i=t[2],l=i==="m"?r*6e4:i==="h"?r*36e5:r*864e5;return new Date(e-l).toISOString()}return s}async function ve(s,e$1,t$1){let r=i=>JSON.stringify(i,null,2);switch(s){case "paradigm_ambient_nominations":{m(t$1.rootDir);let l=e$1.pending_only!==false,d=e$1.limit||20,o=i(t$1.rootDir,{agent:e$1.agent,urgency:e$1.urgency,pending_only:l,limit:d+20}),b=t(t$1.rootDir);o=u(o,b).slice(0,d);let y=j.join(t$1.rootDir,".paradigm/events/nominations.jsonl");if(v.existsSync(y))try{let a=v.readFileSync(y,"utf8"),c=new Set(o.map(m=>m.id)),g=a.trim().split(`
3
+ `).map(m=>{try{let f=JSON.parse(m);return c.has(f.id)?(f.surfaced=!0,JSON.stringify(f)):m}catch{return m}});v.writeFileSync(y,g.join(`
4
+ `)+`
5
+ `,"utf8");}catch{}let h={count:o.length,nominations:o.map(a=>({id:a.id,agent:a.agent,urgency:a.urgency,type:a.type,brief:a.brief,relevance:a.relevance,timestamp:a.timestamp,engaged:a.engaged,response:a.response}))};if(e$1.include_debates){let c=j$1(t$1.rootDir).filter(g=>!g.resolution);h.debates=c.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),h.debate_count=c.length;}return {text:r(h),handled:true}}case "paradigm_ambient_events":{let i=e$1.since?re(e$1.since):void 0,l=e$1.limit||50,d=a(t$1.rootDir,{type:e$1.type,source:e$1.source,symbol:e$1.symbol,agent:e$1.agent,since:i,limit:l});return {text:r({count:d.length,events:d.map(o=>({id:o.id,type:o.type,source:o.source,timestamp:o.timestamp,path:o.path,symbols:o.symbols,context:o.context,agent:o.agent,tool:o.tool,severity:o.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i$1=e$1.nomination_id,l$1=e$1.response,d=e$1.reason,o=k(t$1.rootDir,i$1,l$1,d);if(o)try{let{appendSessionWorkEntry:y,appendVerdictEntry:h}=await import('./session-work-log-T2IE4Y4T.js'),c=i(t$1.rootDir,{limit:500}).find(m=>m.id===i$1),g={timestamp:new Date().toISOString(),type:"user-verdict",agent:c?.agent,nominationId:i$1,verdict:l$1,reason:d};y(t$1.rootDir,g),h(t$1.rootDir,g);}catch{}let b=false;return e$1.resolve_debate&&o&&(b=l(t$1.rootDir,e$1.resolve_debate,i$1,e$1.reason)),{text:r({engaged:o,nomination_id:i$1,response:l$1,debate_resolved:b||void 0}),handled:true}}case "paradigm_context_compose":{let i$1=e$1.agent,l=e$1.symbols||[],d=e$1.include_nominations!==false,o=e$1.include_decisions!==false,b=e$1.include_journal!==false,y=e$1.max_decisions||5,h=e$1.max_journal||5,a=f(t$1.rootDir,i$1);if(!a)return {text:r({error:`Agent profile not found: ${i$1}`}),handled:true};let c=[],g=p$1(a,l);if(g.trim()&&c.push(g),o){let m=e(t$1.rootDir,{status:"active",limit:y});if(m.length>0){c.push("## Recent Team Decisions");for(let f of m)c.push(`- **${f.title}**: ${f.decision.slice(0,150)}${f.decision.length>150?"...":""}`);c.push("");}}if(b){let m=b$1(i$1,{transferable:true,limit:h});if(m.length>0){c.push("## Transferable Insights");for(let f of m)c.push(`- [${f.trigger}] ${f.insight.slice(0,150)}${f.insight.length>150?"...":""}`);c.push("");}}if(d){let m=i(t$1.rootDir,{pending_only:true,limit:10});if(m.length>0){c.push("## Pending Nominations");for(let f of m)c.push(`- [${f.urgency}] ${f.brief}`);c.push("");}}return {text:r({agent:i$1,context:c.join(`
6
+ `),sections_included:{profile:true,decisions:o,journal:b,nominations:d}}),handled:true}}case "paradigm_ambient_promote":{let i=e$1.agent,l=s$1(t$1.rootDir,i);return {text:r({agent:i,promoted:l.promoted,entries:l.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e$1.agent,l=e$1.dry_run===true,d=p(t$1.rootDir,i);if(l)return {text:r({agent:i,dry_run:true,stats:d,note:d.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(d.acceptRate*100).toFixed(0)}% \u2014 ${d.acceptRate>.8?"would lower threshold":d.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let o$1=o(t$1.rootDir,i);return {text:r({agent:i,...o$1,stats:d}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let i=q(t$1.rootDir);return {text:r(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:r(await de(t$1.rootDir,e$1)),handled:true};default:return {text:`Unknown ambient tool: ${s}`,handled:false}}}var ae={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function ce(s){try{let e=j.join(s,".paradigm","config.yaml");if(v.existsSync(e)){let r=v.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(r)return r[1].trim()}}catch{}return j.basename(s)}async function de(s,e={}){let t=e.dry_run===true,r=ce(s),i=e$1(s).filter(n=>n.verdict&&n.agent),l=g$1(s).filter(n=>n.agent&&n.corrections.length>0),d=b$2(s);if(i.length===0&&l.length===0)return {sessionEntries:d.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:t,details:[]};let o=new Map;for(let n of i){let u=n.agent;o.has(u)||o.set(u,[]),o.get(u).push(n);}let b=d.filter(n=>n.type==="agent-contribution"),y=new Map;for(let n of b)n.agent&&(y.has(n.agent)||y.set(n.agent,[]),y.get(n.agent).push(n));let h$1=[],a={},c=0;for(let[n,u]of o){a[n]=0;let _=u.filter(p=>p.verdict==="accepted").length;u.filter(p=>p.verdict==="dismissed").length;u.filter(p=>p.verdict==="revised").length;let R=u.length,K=R>0?_/R:0;for(let p of u){let I=ae[p.verdict];if(!I)continue;let X=y.get(n)?.shift(),A=le(p,X,{acceptRate:K,total:R,accepted:_}),Y=typeof p.confidence=="number"?p.confidence:p.verdict==="accepted"?.85:p.verdict==="revised"?.6:.4,Z={agent:n,verdict:p.verdict,trigger:I,insight:A,symbols:p.symbols};if(h$1.push(Z),t)a[n]++,c++;else try{a$1(n,{trigger:I,insight:A,confidence_before:p.verdict==="accepted"?.7:.8,confidence_after:Y,project:r,transferable:p.verdict==="dismissed",tags:["postflight",`verdict:${p.verdict}`,...(p.symbols||[]).map(ee=>`symbol:${ee}`)]}),a[n]++,c++;}catch{}}}let g=new Set;for(let n of l){let u=n.agent;g.add(u),a[u]===void 0&&(a[u]=0);let _=`Self-revision during iteration round ${n.round}: ${n.corrections.join("; ")}`;if(h$1.push({agent:u,verdict:"iteration-revision",trigger:"self_reflection",insight:_,symbols:n.symbols}),t)a[u]++,c++;else try{a$1(u,{trigger:"self_reflection",insight:_,confidence_before:.6,confidence_after:typeof n.confidence=="number"?n.confidence:.75,project:r,transferable:!1,tags:["postflight","iteration-revision",`round:${n.round}`,...(n.symbols||[]).map($=>`symbol:${$}`)]}),a[u]++,c++;}catch{}}let m={},f=0,k=new Set([...o.keys(),...g]);if(!t)for(let n of k)try{let u=s$1(s,n);u.promoted>0&&(m[n]=u.promoted,f+=u.promoted);}catch{}return !t&&i.length>0&&f$1(s,i.map(n=>n.nominationId).filter(Boolean)),!t&&l.length>0&&h(s,l.map(n=>n.id)),{sessionEntries:d.length,agentsProcessed:Array.from(k),journalsWritten:c,journalsByAgent:a,promoted:f,promotedByAgent:m,dryRun:t,details:h$1}}function le(s,e,t){let r=s.symbols?.length?` (symbols: ${s.symbols.join(", ")})`:"",i=s.reason?` Reason: ${s.reason}.`:"";switch(s.verdict){case "accepted":return `Contribution accepted by user${r}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "dismissed":return `Contribution dismissed by user${r}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "revised":return `Contribution revised by user${r}.${i}`+(s.revisionDelta?` Delta: "${s.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;default:return `Unknown verdict "${s.verdict}"${r}.${i}`}}export{be as a,ve as b,de as c};