@a-company/paradigm 7.1.0 → 7.2.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 (131) hide show
  1. package/dist/{accept-orchestration-WMGFGYDK.js → accept-orchestration-XW44LF5Y.js} +1 -1
  2. package/dist/add-CBDU23S2.js +12 -0
  3. package/dist/{aggregate-KZICPVT3.js → aggregate-H7SB2UYT.js} +1 -1
  4. package/dist/{ambient-HAXPDIWK.js → ambient-TFLZFV5Y.js} +1 -1
  5. package/dist/ambient-VCTUHHIG.js +2 -0
  6. package/dist/arch-loader-YVOS3QRY.js +2 -0
  7. package/dist/{beacon-52EWNZPK.js → beacon-WVN264OT.js} +1 -1
  8. package/dist/captain-CAXGHC2V.js +2 -0
  9. package/dist/captain-CWCLFOXV.js +2 -0
  10. package/dist/{chunk-QDP4G53M.js → chunk-27EK3OQZ.js} +4 -4
  11. package/dist/chunk-2KK4JQ55.js +17 -0
  12. package/dist/chunk-3I3TITBA.js +25 -0
  13. package/dist/chunk-3YM5ABNX.js +2 -0
  14. package/dist/{chunk-RDWWSQGH.js → chunk-6HYRS3PH.js} +14 -14
  15. package/dist/{chunk-S3UVQ5RV.js → chunk-6VZSOQ7Y.js} +1 -1
  16. package/dist/chunk-727PXENG.js +2 -0
  17. package/dist/chunk-A5EEY6NO.js +3 -0
  18. package/dist/{chunk-DLMDHS2X.js → chunk-ASBK55FU.js} +1 -1
  19. package/dist/{chunk-4GC35IFF.js → chunk-D6BSCELB.js} +1 -1
  20. package/dist/{chunk-G6DK3ND3.js → chunk-DH7QVZDI.js} +9 -0
  21. package/dist/chunk-FG3M6VVO.js +30 -0
  22. package/dist/chunk-FNYYQNJY.js +2 -0
  23. package/dist/chunk-K6TLYNRQ.js +7 -0
  24. package/dist/chunk-K7KT6FL3.js +25 -0
  25. package/dist/chunk-M7JHVVDW.js +6 -0
  26. package/dist/chunk-NFN5UUJB.js +2 -0
  27. package/dist/{chunk-EG22HDXI.js → chunk-NRP2KJ6I.js} +12 -12
  28. package/dist/{chunk-VPNJL4LS.js → chunk-QPQBXRXX.js} +1 -1
  29. package/dist/chunk-RZRFYGND.js +504 -0
  30. package/dist/chunk-UNSI6DVD.js +93 -0
  31. package/dist/{chunk-W4BW7GXA.js → chunk-USYV5QYU.js} +1 -1
  32. package/dist/chunk-VOPJ47QY.js +2 -0
  33. package/dist/{chunk-KP5VOYAH.js → chunk-W3VWORQZ.js} +1 -1
  34. package/dist/chunk-WMTES556.js +2 -0
  35. package/dist/chunk-XBK244QR.js +6 -0
  36. package/dist/{chunk-YQK3XU63.js → chunk-XSKIXXFW.js} +12 -12
  37. package/dist/{chunk-MBSY57RN.js → chunk-Y76OIMDO.js} +1 -1
  38. package/dist/chunk-YYRP7FLC.js +2 -0
  39. package/dist/{compliance-4P3EE5OA.js → compliance-3M6COUCO.js} +3 -3
  40. package/dist/{constellation-RHZAEFV7.js → constellation-TIKNCZWR.js} +1 -1
  41. package/dist/{cost-24UZSS2P.js → cost-VTHZQKO4.js} +2 -2
  42. package/dist/{diff-VBVIUNL5.js → diff-Z2YSIRC4.js} +1 -1
  43. package/dist/{dist-TNE4GFT7.js → dist-PW5YPGFF.js} +1 -1
  44. package/dist/{docs-NTP6UENF.js → docs-OWJ7EPD7.js} +1 -1
  45. package/dist/github-4X4MYINS.js +4 -0
  46. package/dist/{habits-BX2IRSUI.js → habits-UA7YT3CG.js} +3 -3
  47. package/dist/{hooks-AXBWYJ5V.js → hooks-XXJ7CSGJ.js} +1 -1
  48. package/dist/index.js +9 -9
  49. package/dist/{init-F4MSKZIW.js → init-QPMLEQWQ.js} +1 -1
  50. package/dist/{integrity-7TKX3DZ4.js → integrity-FRGF5BFS.js} +1 -1
  51. package/dist/lint-Y4P3MHBV.js +26 -0
  52. package/dist/list-5XRLWD7K.js +12 -0
  53. package/dist/mcp.js +1 -1
  54. package/dist/{migrate-5M4KUQ2L.js → migrate-LIVXILOO.js} +1 -1
  55. package/dist/nomination-engine-EFXDEPZN.js +2 -0
  56. package/dist/{orchestrate-MLUGQOEJ.js → orchestrate-C5NM5MFN.js} +1 -1
  57. package/dist/orchestration-EVWQWTOV.js +2 -0
  58. package/dist/orchestration-UP3KFUJT.js +2 -0
  59. package/dist/{platform-server-Y6TLEXR2.js → platform-server-FXF3XFHM.js} +1 -1
  60. package/dist/{probe-27ARJKRO.js → probe-G3TKOJYW.js} +1 -1
  61. package/dist/quiz-QKIKAVL7.js +10 -0
  62. package/dist/registry-NEW4OJ44.js +2 -0
  63. package/dist/reindex-QZYOD5K4.js +2 -0
  64. package/dist/{reindex-ZLDQBFUR.js → reindex-W67B2LQP.js} +1 -1
  65. package/dist/remember-KZYAY77S.js +14 -0
  66. package/dist/{review-BRO2UP4M.js → review-WHRNLW2W.js} +1 -1
  67. package/dist/{ripple-KCVDS3WE.js → ripple-B6U7263T.js} +1 -1
  68. package/dist/{serve-2PKJP65E.js → serve-6RNZYK2I.js} +2 -2
  69. package/dist/{serve-XZ6GBUS3.js → serve-ZT2Z54NK.js} +1 -1
  70. package/dist/{setup-5V2AGLQ6.js → setup-L5OP24US.js} +3 -3
  71. package/dist/{shift-PM4GI736.js → shift-UDKXCIW7.js} +3 -3
  72. package/dist/{show-N5LGB5B2.js → show-VXNGIJE4.js} +3 -3
  73. package/dist/{snapshot-YMX5QRBM.js → snapshot-MT5L6XE4.js} +1 -1
  74. package/dist/{spawn-PHA2SVQ3.js → spawn-I6XG57S2.js} +1 -1
  75. package/dist/status-45KIG32R.js +6 -0
  76. package/dist/{status-3GJXI4IK.js → status-4QGKLOP6.js} +4 -4
  77. package/dist/{summary-RPU2BS3Q.js → summary-6QNVQZJV.js} +1 -1
  78. package/dist/symphony-KQJ6HIXB.js +53 -0
  79. package/dist/symphony-VDNDFK7H.js +2 -0
  80. package/dist/symphony-relay-ASMKPDEE.js +3 -0
  81. package/dist/task-KFND4HLF.js +3 -0
  82. package/dist/task-loader-HBZ3KRH2.js +2 -0
  83. package/dist/task-loader-IO4UVFUD.js +2 -0
  84. package/dist/task-settlement-NF7PFSNE.js +3 -0
  85. package/dist/task-settlement-TATNPY6L.js +3 -0
  86. package/dist/team-6WNNLBAO.js +2 -0
  87. package/dist/thread-2A7QKU72.js +41 -0
  88. package/dist/tools-GDWT74O6.js +2 -0
  89. package/dist/tools-SDWAFQMQ.js +142 -0
  90. package/dist/validate-OZTX3FYX.js +13 -0
  91. package/dist/validate-RIMSY3RP.js +9 -0
  92. package/dist/{workspace-6POCBPDY.js → workspace-4D4TQ637.js} +1 -1
  93. package/package.json +1 -1
  94. package/dist/add-V6XR7DU5.js +0 -12
  95. package/dist/agent-loader-Z753DQWH.js +0 -2
  96. package/dist/ambient-QB7V4TBR.js +0 -6
  97. package/dist/captain-3COP6YTD.js +0 -2
  98. package/dist/chunk-4CGPLLWQ.js +0 -30
  99. package/dist/chunk-7SWEOPWF.js +0 -2
  100. package/dist/chunk-CHSU6LTR.js +0 -2
  101. package/dist/chunk-EKNLG73M.js +0 -6
  102. package/dist/chunk-H55W26AR.js +0 -3
  103. package/dist/chunk-HE2NA5QF.js +0 -8
  104. package/dist/chunk-JIXHEBGK.js +0 -7
  105. package/dist/chunk-MBPLJKE5.js +0 -3
  106. package/dist/chunk-OIYJUU6T.js +0 -25
  107. package/dist/chunk-QO7YPQXC.js +0 -2
  108. package/dist/chunk-XPPFILCM.js +0 -2
  109. package/dist/chunk-YCDOA5IQ.js +0 -18
  110. package/dist/lint-IGKE6UPS.js +0 -26
  111. package/dist/list-NC3QGT75.js +0 -12
  112. package/dist/lore-loader-HAZ5FRLP.js +0 -2
  113. package/dist/nomination-engine-ORHH4L2W.js +0 -2
  114. package/dist/orchestration-O2OVPTIZ.js +0 -2
  115. package/dist/quiz-TNV6APBM.js +0 -10
  116. package/dist/remember-MJRNTXYS.js +0 -14
  117. package/dist/session-work-log-FF7CKMWP.js +0 -2
  118. package/dist/status-ENAI35NL.js +0 -6
  119. package/dist/symphony-CFAYJGLF.js +0 -2
  120. package/dist/symphony-L56O5ZG3.js +0 -53
  121. package/dist/symphony-relay-Y2UR3YNR.js +0 -3
  122. package/dist/task-loader-H7HQAYGL.js +0 -2
  123. package/dist/task-loader-YZME4RKE.js +0 -2
  124. package/dist/task-settlement-HINBVZBE.js +0 -3
  125. package/dist/task-settlement-XC6E6JNT.js +0 -3
  126. package/dist/team-25LK6CWM.js +0 -2
  127. package/dist/thread-HFXK65D4.js +0 -41
  128. package/dist/tools-GAU5WOEI.js +0 -2
  129. package/dist/validate-IQG7DBFC.js +0 -9
  130. package/dist/validate-LSCDOLBO.js +0 -13
  131. package/dist/work-log-loader-CRVTOMVB.js +0 -2
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-MBSY57RN.js';import {a}from'./chunk-LKAT7IAK.js';import*as r from'fs';import*as i from'path';import e from'chalk';import W from'ora';import*as u from'js-yaml';async function v(l={}){let c=process.cwd(),o=i.join(c,".paradigm-workspace");console.log(e.blue(`
2
+ import {b}from'./chunk-Y76OIMDO.js';import {a}from'./chunk-LKAT7IAK.js';import*as r from'fs';import*as i from'path';import e from'chalk';import W from'ora';import*as u from'js-yaml';async function v(l={}){let c=process.cwd(),o=i.join(c,".paradigm-workspace");console.log(e.blue(`
3
3
  \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510`)),console.log(e.blue("\u2502")+e.white.bold(" paradigm workspace init ")+e.blue("\u2502")),console.log(e.blue("\u2502")+e.gray(" Create a multi-project workspace ")+e.blue("\u2502")),console.log(e.blue(`\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
4
4
  `));let n=a.command("workspace-init").start("Creating workspace",{cwd:c});if(r.existsSync(o)&&!l.force){console.log(e.yellow(` .paradigm-workspace already exists. Use --force to overwrite.
5
5
  `)),n.success("Workspace already exists");return}let s=c,t=r.readdirSync(s,{withFileTypes:true}),a$1=[];for(let p of t){if(!p.isDirectory()||p.name.startsWith(".")||p.name==="node_modules")continue;let g=i.join(s,p.name),k=r.existsSync(i.join(g,".paradigm")),y=r.existsSync(i.join(g,".purpose"));if(k||y){let w=j(p.name,g);a$1.push({name:p.name,path:`./${p.name}`,...w&&{role:w}});}}if(a$1.length===0){console.log(e.yellow(" No sibling projects with .paradigm/ or .purpose found.")),console.log(e.gray(` Create .purpose files in sibling directories first.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import*as i from'fs';import*as o from'path';import*as f from'js-yaml';b$1();var g=".paradigm/tasks",T="entries",F="index.yaml";function k(e){if(e&&e.session_link&&!e.external_ref){let s=e.session_link,n=s.toLowerCase(),r;n.includes("github")?r="github":n.includes("session")?r="session":r="url",e.external_ref={provider:r,ref:s},delete e.session_link;}let t=e?.external_ref;return t&&t.kind!==void 0&&t.provider===void 0&&(t.provider=t.kind,delete t.kind),e}function j(e,t){let s=o.join(e,g,T,t);if(!i.existsSync(s))return `T-${t}-001`;let n=i.readdirSync(s).filter(a=>a.startsWith("T-")&&a.endsWith(".yaml")).map(a=>{let d=a.match(/T-\d{4}-\d{2}-\d{2}-(\d+)\.yaml/);return d?parseInt(d[1],10):0}),r=n.length>0?Math.max(...n)+1:1;return `T-${t}-${String(r).padStart(3,"0")}`}function O(e,t){return e===t?true:({open:["in-progress","done","shelved"],"in-progress":["done","open","shelved"],shelved:["open"],done:[]}[e]??[]).includes(t)}var _={high:0,medium:1,low:2},E=["open","in-progress"];function N(e,t){return t==="all"?true:t==="active"?E.includes(e.status):e.status===t}function b(e){let t=e.created?new Date(e.created).getTime():NaN;if(!Number.isNaN(t))return t;let s=e.id?.match(/^T-(\d{4}-\d{2}-\d{2})-/);if(s){let n=new Date(s[1]).getTime();if(!Number.isNaN(n))return n}return 0}function C(e,t){let s=e;return t.status&&t.status!=="all"&&(s=s.filter(n=>N(n,t.status))),t.priority&&(s=s.filter(n=>n.priority===t.priority)),t.tag&&(s=s.filter(n=>n.tags.includes(t.tag))),s.sort((n,r)=>{let a=(_[n.priority]??1)-(_[r.priority]??1);return a!==0?a:b(r)-b(n)}),t.limit&&(s=s.slice(0,t.limit)),s}async function D(e,t){let s=o.join(e,g,T);if(!i.existsSync(s))return [];let n={status:"open",limit:20,...t},r=[],a=i.readdirSync(s).filter(d=>/^\d{4}-\d{2}-\d{2}$/.test(d)).sort().reverse();for(let d of a){let m=o.join(s,d),l=i.readdirSync(m).filter(c=>c.endsWith(".yaml")).sort();for(let c of l)try{let u=i.readFileSync(o.join(m,c),"utf8"),h=k(f.load(u));r.push(h);}catch{}}return C(r,n)}async function $(e,t){let s=t.match(/^T-(\d{4}-\d{2}-\d{2})-/);if(s){let r=o.join(e,g,T,s[1],`${t}.yaml`);if(i.existsSync(r))try{return k(f.load(i.readFileSync(r,"utf8")))}catch{return null}}return (await D(e,{status:"all",limit:9999})).find(r=>r.id===t)||null}async function K(e,t){let s=new Date,n=s.toISOString().slice(0,10),r=o.join(e,g,T,n);i.mkdirSync(r,{recursive:true});let a=j(e,n),d={id:a,blurb:t.blurb,priority:t.priority||"medium",status:"open",tags:t.tags||[],created:s.toISOString(),related_lore:t.related_lore,claimant:t.claimant,parentTaskId:t.parentTaskId,dependsOn:t.dependsOn,stage:t.stage,external_ref:t.external_ref,session_link:t.session_link};return k(d),i.writeFileSync(o.join(r,`${a}.yaml`),f.dump(w(d),{lineWidth:-1,noRefs:true})),await I(e),a}async function v(e,t,s){let n=await $(e,t);if(!n)return false;let r=n.created.slice(0,10),a$1=o.join(e,g,T,r,`${t}.yaml`);if(!i.existsSync(a$1))return false;let{id:d,created:m,...l}=s;if(l.status!==void 0&&l.status!==n.status){if(!O(n.status,l.status))return a.component("#task-loader").warn("Illegal task status transition rejected",{taskId:t,from:n.status,to:l.status}),false;l.status==="in-progress"&&!n.started_at&&l.started_at===void 0&&(l.started_at=new Date().toISOString());}let c={...n,...l};if(i.writeFileSync(a$1,f.dump(w(c),{lineWidth:-1,noRefs:true})),await I(e),W(c.status)&&c.parentTaskId)try{let{settleParentIfComplete:u}=await import('./task-settlement-NF7PFSNE.js');await u(e,c.parentTaskId,c.id);}catch(u){a.component("#task-loader").warn("Settlement after updateTask failed (non-fatal)",{taskId:t,parentTaskId:c.parentTaskId,error:u instanceof Error?u.message:String(u)});}return true}function W(e){return e==="done"||e==="shelved"}async function L(e,t){return v(e,t,{status:"done",completed:new Date().toISOString()})}async function M(e,t){return v(e,t,{status:"shelved",shelved:new Date().toISOString()})}async function I(e){let t=o.join(e,g,T),s=o.join(e,g),n=0,r=0,a=0,d=0,m=0,l=[];if(i.existsSync(t)){let u=i.readdirSync(t).filter(h=>/^\d{4}-\d{2}-\d{2}$/.test(h));for(let h of u){let x=o.join(t,h),P=i.readdirSync(x).filter(y=>y.endsWith(".yaml"));for(let y of P)try{let p=k(f.load(i.readFileSync(o.join(x,y),"utf8")));n++,p.status==="open"?r++:p.status==="in-progress"?a++:p.status==="done"?d++:p.status==="shelved"&&m++,!p.parentTaskId&&p.id&&l.push(p.id);}catch{}}}let c={version:"1.1",total:n,open:r,in_progress:a,done:d,shelved:m,roots:l,last_updated:new Date().toISOString()};return i.mkdirSync(s,{recursive:true}),i.writeFileSync(o.join(s,F),f.dump(c,{lineWidth:-1,noRefs:true})),c}function w(e){let t={};for(let[s,n]of Object.entries(e))n!==void 0&&(t[s]=n);return t}export{k as a,j as b,O as c,D as d,$ as e,K as f,v as g,L as h,M as i,I as j};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import {r}from'./chunk-D6BSCELB.js';import*as i from'fs';import*as c from'path';import*as f from'js-yaml';b$1();var g=".paradigm/arch.yaml";function u(e){let n=c.join(e,g);if(!i.existsSync(n))return null;try{let t=i.readFileSync(n,"utf8");return f.load(t)}catch{return null}}function S(e,n){let t=c.join(e,g),r=c.dirname(t);i.existsSync(r)||i.mkdirSync(r,{recursive:true}),i.writeFileSync(t,f.dump(n,{lineWidth:-1,noRefs:true}),"utf8");}function b(e,n){let t=u(e);if(!t)return {unassigned:[],missing_purpose:[]};let r$1=new Set;for(let o of t.tiers)for(let p of o.components)r$1.add(p);let s=new Set;try{let o=r(n.index,"component");for(let p of o)s.add(p.symbol);}catch(o){a.component("#arch-loader").warn("Could not load symbol index for drift check",{error:String(o)});}let a$1=Array.from(s).filter(o=>!r$1.has(o)),h=Array.from(r$1).filter(o=>!s.has(o));return {unassigned:a$1,missing_purpose:h}}function k(e){let n=r=>r.replace(/[^a-zA-Z0-9_-]/g,"-"),t=["graph TD"];for(let r of e.tiers){let s=n(r.id);t.push(` ${s}["${r.label}\\n(${r.responsibility})"]`);}for(let r of e.links){let s=n(r.from),a=n(r.to);r.via?t.push(` ${s} -->|"${r.via}"| ${a}`):t.push(` ${s} --> ${a}`);}return t.join(`
3
+ `)}export{g as a,u as b,S as c,b as d,k as e};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a as a$1}from'./chunk-FYDRENK7.js';import {f,a}from'./chunk-ECLUYHAR.js';import {e}from'./chunk-YXLGVOZO.js';import {b,d,c}from'./chunk-EKZDFEJW.js';import*as h from'fs';import*as P from'path';import*as M from'js-yaml';import {glob}from'glob';import {EventEmitter}from'events';var W=/[#$^!~][a-zA-Z0-9_-]+/g;function G(a){let e=a.match(W)||[];return [...new Set(e)]}function K(a){let e=a.charAt(0);return {"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"}[e]||"unknown"}async function j(a,e,s,t){let o=P.join(s,".paradigm"),n=G(e),c=J(a,t),u=N(c.include||[],n),l=c.exclude||[],p=await X(s,u,l);return {systemPrompt:await Y(a,o,n),files:p,symbols:n}}function J(a,e){return e?.contextInclude||e?.contextExclude?{include:e.contextInclude,exclude:e.contextExclude}:{architect:{include:["specs/*.md",".purpose","**/.purpose","portal.yaml",".paradigm/config.yaml"],exclude:["src/**","tests/**","node_modules/**","dist/**"]},builder:{include:["src/**","tests/**","{feature}.purpose","specs/{feature}.md"],exclude:["specs/*.md","node_modules/**","dist/**"]},reviewer:{include:["src/**","specs/*.md","portal.yaml",".purpose"],exclude:["tests/**","node_modules/**","dist/**"]},tester:{include:["tests/**","health.yaml","{feature}.purpose"],exclude:["src/**","specs/**","node_modules/**","dist/**"]},security:{include:["portal.yaml","src/middleware/**","src/auth/**",".paradigm/wisdom/antipatterns.yaml"],exclude:["src/routes/**","tests/**","node_modules/**","dist/**"]}}[a.name]||{include:[".purpose","portal.yaml"],exclude:["node_modules/**","dist/**"]}}function N(a,e){let s=[];for(let t of a)if(t.includes("{feature}")||t.includes("{symbol}"))for(let o of e){let n=o.substring(1);s.push(t.replace(/\{feature\}/g,n).replace(/\{symbol\}/g,n));}else s.push(t);return s}async function X(a,e,s){let t=new Set;for(let o of e)try{let n=await glob(o,{cwd:a,ignore:s,nodir:!0,absolute:!1});for(let c of n)t.add(c);}catch{}return Array.from(t)}async function Y(a,e,s){let t=[],o=P.join(e,"config.yaml"),n=null;if(h.existsSync(o))try{n=M.load(h.readFileSync(o,"utf-8"));}catch{}if(t.push(`# ${a.name.charAt(0).toUpperCase()+a.name.slice(1)} Agent Context
2
+ import {f,a}from'./chunk-ECLUYHAR.js';import {e}from'./chunk-YXLGVOZO.js';import {a as a$1}from'./chunk-FYDRENK7.js';import {b,d,c}from'./chunk-EKZDFEJW.js';import*as h from'fs';import*as P from'path';import*as M from'js-yaml';import {glob}from'glob';import {EventEmitter}from'events';var W=/[#$^!~][a-zA-Z0-9_-]+/g;function G(a){let e=a.match(W)||[];return [...new Set(e)]}function K(a){let e=a.charAt(0);return {"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"}[e]||"unknown"}async function j(a,e,s,t){let o=P.join(s,".paradigm"),n=G(e),c=J(a,t),u=N(c.include||[],n),l=c.exclude||[],p=await X(s,u,l);return {systemPrompt:await Y(a,o,n),files:p,symbols:n}}function J(a,e){return e?.contextInclude||e?.contextExclude?{include:e.contextInclude,exclude:e.contextExclude}:{architect:{include:["specs/*.md",".purpose","**/.purpose","portal.yaml",".paradigm/config.yaml"],exclude:["src/**","tests/**","node_modules/**","dist/**"]},builder:{include:["src/**","tests/**","{feature}.purpose","specs/{feature}.md"],exclude:["specs/*.md","node_modules/**","dist/**"]},reviewer:{include:["src/**","specs/*.md","portal.yaml",".purpose"],exclude:["tests/**","node_modules/**","dist/**"]},tester:{include:["tests/**","health.yaml","{feature}.purpose"],exclude:["src/**","specs/**","node_modules/**","dist/**"]},security:{include:["portal.yaml","src/middleware/**","src/auth/**",".paradigm/wisdom/antipatterns.yaml"],exclude:["src/routes/**","tests/**","node_modules/**","dist/**"]}}[a.name]||{include:[".purpose","portal.yaml"],exclude:["node_modules/**","dist/**"]}}function N(a,e){let s=[];for(let t of a)if(t.includes("{feature}")||t.includes("{symbol}"))for(let o of e){let n=o.substring(1);s.push(t.replace(/\{feature\}/g,n).replace(/\{symbol\}/g,n));}else s.push(t);return s}async function X(a,e,s){let t=new Set;for(let o of e)try{let n=await glob(o,{cwd:a,ignore:s,nodir:!0,absolute:!1});for(let c of n)t.add(c);}catch{}return Array.from(t)}async function Y(a,e,s){let t=[],o=P.join(e,"config.yaml"),n=null;if(h.existsSync(o))try{n=M.load(h.readFileSync(o,"utf-8"));}catch{}if(t.push(`# ${a.name.charAt(0).toUpperCase()+a.name.slice(1)} Agent Context
3
3
  `),n?.project&&(t.push(`> Project: ${n.project}`),n.discipline&&n.discipline!=="auto"&&t.push(`> Discipline: ${n.discipline}`),t.push("")),n?.["agent-guidelines"]?.overview&&(t.push(`## Project Overview
4
4
  `),t.push(n["agent-guidelines"].overview),t.push("")),n?.["symbol-system"]){t.push(`## Symbol System
5
5
  `),t.push("| Symbol | Meaning | Description |"),t.push("|--------|---------|-------------|");for(let[u,l]of Object.entries(n["symbol-system"]))t.push(`| \`${u}\` | ${l.name} | ${l.description} |`);t.push("");}if(n?.conventions){let u=Z(n.conventions,a.name);if(u.length>0){t.push(`## Conventions
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import {f,g,h,i,j,k,l,m,n}from'./chunk-JIXHEBGK.js';import {a,e}from'./chunk-ZJQY5PPP.js';import*as $ from'fs';import*as A from'js-yaml';import {z}from'zod';import*as b from'path';var H={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},ee={"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"},te=["#","$","^","!","~"];function oe(e){return te.includes(e)}var se=z.object({x:z.number(),y:z.number()}),ne=z.object({x:z.number(),y:z.number(),zoom:z.number()}),G=z.object({path:z.string(),include:z.array(z.string()).optional(),exclude:z.array(z.string()).optional()}),V=z.object({id:z.string(),symbol:z.string(),type:z.enum(["feature","component","flow","state","aspect","gate","signal","idea"]),content:z.string().optional(),position:se,tags:z.array(z.string()).optional(),created:z.string(),modified:z.string().optional()}),W=z.object({from:z.string(),to:z.string(),label:z.string().optional(),type:z.string().optional()}),re=z.object({id:z.string(),name:z.string(),nodes:z.array(z.string()),color:z.string().optional()}),Y=z.object({viewport:ne,groups:z.array(re).optional()}),ae=z.object({nodes:z.array(V),connections:z.array(W),layout:Y}),ie=z.object({id:z.string(),name:z.string(),timestamp:z.string(),description:z.string().optional(),state:ae}),ce=z.object({version:z.string(),metadata:z.object({name:z.string(),created:z.string(),modified:z.string()}),sources:z.object({purpose:z.array(G).optional(),portal:z.array(G).optional()}),nodes:z.array(V),connections:z.array(W),layout:Y,snapshots:z.array(ie).optional()});function we(e){let o=[],t;try{t=$.readFileSync(e,"utf8");}catch(s){return o.push(`Cannot read file: ${s.message}`),{data:null,errors:o,rawContent:void 0}}return pe(t)}function pe(e){let o=[],t=null;try{t=A.load(e);}catch(r){let l=r,c=l.mark?.line?l.mark.line+1:void 0;return o.push(`YAML syntax error: ${l.reason||r.message}${c?` (line ${c})`:""}`),{data:null,errors:o,rawContent:e}}if(t==null)return {data:X(),errors:[],rawContent:e};let s=ce.safeParse(t);if(!s.success){for(let r of s.error.issues){let l=r.path.join(".");o.push(`Schema error at ${l||"/"}: ${r.message}`);}return {data:t,errors:o,rawContent:e}}return {data:s.data,errors:[],rawContent:e}}function X(e="Untitled"){let o=new Date().toISOString();return {version:"1.0.0",metadata:{name:e,created:o,modified:o},sources:{purpose:[{path:"./"}],portal:[{path:"./portal.yaml"}]},nodes:[],connections:[],layout:{viewport:{x:0,y:0,zoom:1}}}}function ue(e){return e.metadata.modified=new Date().toISOString(),A.dump(e,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function Pe(e="My Project"){return ue(X(e))}function ve(e,o){return {...e,nodes:[...e.nodes,o],metadata:{...e.metadata,modified:new Date().toISOString()}}}function xe(e,o,t){return {...e,nodes:e.nodes.map(s=>s.id===o?{...s,position:t,modified:new Date().toISOString()}:s),metadata:{...e.metadata,modified:new Date().toISOString()}}}function Ce(e,o){return e.connections.some(s=>s.from===o.from&&s.to===o.to)?e:{...e,connections:[...e.connections,o],metadata:{...e.metadata,modified:new Date().toISOString()}}}function Te(e,o,t){let s={id:`snap-${Date.now()}`,name:o,timestamp:new Date().toISOString(),description:t,state:{nodes:[...e.nodes],connections:[...e.connections],layout:{...e.layout}}};return {...e,snapshots:[...e.snapshots||[],s],metadata:{...e.metadata,modified:new Date().toISOString()}}}async function le(e$1,o){let t=[],s=[],r=[],l$1=[];if(e$1.sources.purpose)for(let p of e$1.sources.purpose){let f$1=b.resolve(o,p.path);try{let u=await f(f$1);r.push(...u.map(a=>a.filePath));let m$1=g(u);for(let[a,{item:i,filePath:d}]of m$1){let P=["feature",...i.tags||[]];t.push(y({id:`purpose-feature-${a}`,symbol:`#${a}`,type:"component",source:"purpose",filePath:d,data:i,description:i.description,tags:P,componentType:i.type,parentSymbol:i.parent,anchors:i.anchors?.map(q=>R(q))}));}let h$1=h(u);for(let[a,{item:i,filePath:d}]of h$1)t.push(y({id:`purpose-component-${a}`,symbol:`#${a}`,type:"component",source:"purpose",filePath:d,data:i,description:i.description,tags:i.tags,componentType:i.type,parentSymbol:i.parent,anchors:i.anchors?.map(P=>R(P))}));let S=i(u);for(let[a,{item:i,filePath:d}]of S)t.push(y({id:`purpose-gate-${a}`,symbol:`^${a}`,type:"gate",source:"purpose",filePath:d,data:i,description:i.description}));let C=j(u);for(let[a,{item:i,filePath:d}]of C)t.push(y({id:`purpose-state-${a}`,symbol:`#${a}`,type:"component",source:"purpose",filePath:d,data:i,description:i.description,tags:["state"]}));let j$1=k(u);for(let[a,{item:i,filePath:d}]of j$1)t.push(y({id:`purpose-flow-${a}`,symbol:`$${a}`,type:"flow",source:"purpose",filePath:d,data:i,description:i.description}));let J=l(u);for(let[a,{item:i,filePath:d}]of J)t.push(y({id:`purpose-signal-${a}`,symbol:`!${a}`,type:"signal",source:"purpose",filePath:d,data:i,description:i.description}));let Q=m(u);for(let[a,{item:i,filePath:d}]of Q)t.push(y({id:`purpose-aspect-${a}`,symbol:`~${a}`,type:"aspect",source:"purpose",filePath:d,data:i,description:i.description,anchors:i.anchors?.map(P=>R(P)),appliesTo:i["applies-to"],tags:i.tags,enforcement:i.enforcement}));let Z=n(u),O=new Set(t.map(a=>a.symbol));for(let a of Z)O.has(a.symbol)||(O.add(a.symbol),t.push(y({id:`purpose-ref-${a.type}-${a.symbol.slice(1)}`,symbol:a.symbol,type:a.type,source:"purpose",filePath:a.filePath,data:{referencedFrom:a.sourceSymbol},description:`Referenced from ${a.sourceSymbol}`})));}catch(u){s.push({source:"purpose",filePath:f$1,message:u.message});}}if(e$1.sources.portal)for(let p of e$1.sources.portal){let f=b.resolve(o,p.path);try{let u;if(f.endsWith(".yaml")||f.endsWith(".yml"))u=await a(f),l$1.push(f);else {let m=await e(f);if(l$1.push(...m),m.length>0){u=await a(m[0]);for(let h=1;h<m.length;h++){let S=await a(m[h]);u.gates.push(...S.gates),u.flows.push(...S.flows);}}else continue}for(let m of u.gates){t.push(fe(m,f));for(let h of m.prizes)t.push(y({id:`gate-signal-${m.id}-${h.id}`,symbol:`!${h.id}`,type:"signal",source:"portal",filePath:f,data:h,description:`Signal from gate ${m.id}`}));}for(let m of u.flows)t.push(me(m,f));}catch(u){s.push({source:"portal",filePath:f,message:u.message});}}for(let p of e$1.nodes){let f=p.tags?.includes("idea");if(!p.content&&!f){let u=t.find(m=>m.symbol===p.symbol);if(u){u.position=p.position,u.tags=p.tags;continue}}t.push(y({id:p.id,symbol:p.symbol,type:p.type,source:"premise",filePath:".premise",data:p,description:p.content,position:p.position,tags:p.tags,created:p.created,modified:p.modified}));}ye(t);let c=new Map;for(let p of t){let f=c.get(p.symbol)||[];f.includes(p.filePath)||f.push(p.filePath),c.set(p.symbol,f);}let g$1=[];for(let[p,f]of c)f.length>1&&g$1.push({symbol:p,files:f});return {symbols:t,purposeFiles:r,portalFiles:l$1,errors:s,timestamp:Date.now(),...g$1.length>0?{duplicateSymbols:g$1}:{}}}function y(e){return {...e,data:e.data??null,references:e.references??[],referencedBy:e.referencedBy??[]}}function fe(e,o){let t=e.id.startsWith("^")?e.id.slice(1):e.id;return y({id:`gate-${t}`,symbol:`^${t}`,type:"gate",source:"portal",filePath:o,data:e,description:e.description,position:e.position})}function me(e,o){return y({id:`gate-flow-${e.id}`,symbol:`$${e.id}`,type:"flow",source:"portal",filePath:o,data:e,description:e.description})}function R(e){let o=e.lastIndexOf(":");if(o===-1||o===e.length-1)return {path:e,lines:0,raw:e};let t=e.slice(o+1),s=e.slice(0,o);if(!/^[\d,\- ]+$/.test(t))return {path:e,lines:0,raw:e};if(t.includes("-")){let[r,l]=t.split("-").map(Number);return {path:s,lines:[r,l],raw:e}}else if(t.includes(",")){let r=t.split(",").map(Number);return {path:s,lines:r,raw:e}}else return {path:s,lines:Number(t),raw:e}}var de=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function ye(e){let o=new Map(e.map(t=>[t.symbol,t]));for(let t of e){let s=JSON.stringify(t.data),r=/(?:\?[@#$%~^!]|[@#$%~^!?])[a-zA-Z][\w-]*/g,l=(s.match(r)||[]).filter(c=>!de.has(c));for(let c of l)if(c!==t.symbol&&o.has(c)){t.references.includes(c)||t.references.push(c);let g=o.get(c);g&&!g.referencedBy.includes(t.symbol)&&g.referencedBy.push(t.symbol);}}}async function Re(e){let o={metadata:{name:b.basename(e),created:new Date().toISOString(),modified:new Date().toISOString()},sources:{purpose:[{path:"./"}],portal:[{path:"./"}]},nodes:[]};return le(o,e)}function he(){return {entries:new Map,byType:new Map,bySource:new Map,timestamp:0}}function je(e){let o=he();o.timestamp=e.timestamp;for(let t of e.symbols)o.entries.set(t.id,t),o.byType.has(t.type)||o.byType.set(t.type,[]),o.byType.get(t.type).push(t),o.bySource.has(t.source)||o.bySource.set(t.source,[]),o.bySource.get(t.source).push(t);return o}function I(e,o){for(let t of e.entries.values())if(t.symbol===o)return t}function Oe(e,o){return e.entries.get(o)}function x(e,o){return e.byType.get(o)||[]}function Be(e,o){return e.bySource.get(o)||[]}function ge(e,o){let t=o.toLowerCase(),s=[];for(let r of e.entries.values()){if(r.symbol.toLowerCase().includes(t)){s.push(r);continue}if(r.description?.toLowerCase().includes(t)){s.push(r);continue}if(r.tags?.some(l=>l.toLowerCase().includes(t))){s.push(r);continue}if(r.componentType?.toLowerCase().includes(t)){s.push(r);continue}}return s}function Le(e,o){return x(e,"component").filter(s=>s.componentType===o)}function Me(e){let o=new Set,t=x(e,"component");for(let s of t)s.componentType&&o.add(s.componentType);return Array.from(o).sort()}function De(e,o){return x(e,"component").filter(s=>s.parentSymbol===o)}function Ee(e,o){let t=I(e,o);return t?t.referencedBy.map(s=>I(e,s)).filter(s=>s!==void 0):[]}function _e(e,o){let t=I(e,o);return t?t.references.map(s=>I(e,s)).filter(s=>s!==void 0):[]}function ke(e,o){let t=[];for(let s of e.entries.values())s.tags?.includes(o)&&t.push(s);return t}function ze(e){let o=new Set;for(let t of e.entries.values())for(let s of t.tags||[])o.add(s);return Array.from(o).sort()}function Ne(e){let o={component:0,flow:0,gate:0,signal:0,aspect:0};for(let[t,s]of e.byType)t in o&&(o[t]=s.length);return o}function Fe(e){return Array.from(e.entries.values())}function K(e){if(e.length<2)return null;let o=e[0],t=e.slice(1);return oe(o)?{type:ee[o],name:t}:null}function Ge(e,o){return `${H[e]}${o}`}function Ue(e){return K(e)!==null}function Ve(e,o,t=10){let s=o.toLowerCase(),r=K(o);return r?x(e,r.type).filter(c=>c.symbol.toLowerCase().includes(s)).slice(0,t):ge(e,o).slice(0,t)}function be(e,o,t){if(b.isAbsolute(e))return {resolvedPath:e,baseUsed:"absolute",exists:$.existsSync(e)};let s=b.join(t,e);if($.existsSync(s))return {resolvedPath:s,baseUsed:"project-root",exists:true};let r=b.resolve(o,e);return $.existsSync(r)?{resolvedPath:r,baseUsed:"purpose-dir",exists:true}:{resolvedPath:s,baseUsed:"project-root",exists:false}}function We(e,o,t){if(b.isAbsolute(e)){let l=$.existsSync(e);return {rootResolves:l,purposeResolves:l,mismatch:false}}let s=$.existsSync(b.join(t,e)),r=$.existsSync(b.resolve(o,e));return {rootResolves:s,purposeResolves:r,mismatch:s!==r}}function Se(e,o){return e.includes("*")?new RegExp("^"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(o):e===o}function Ye(e,o,t){let s=[],r=x(e,"aspect"),l=new Set;for(let c of r){let g=c.appliesTo||[];if(g.length!==0)for(let p of g)for(let f of o){if(!Se(p,f))continue;let u=c.anchors||[];if(u.length===0){let m=`${c.symbol}::__no-anchors__`;l.has(m)||(l.add(m),s.push({aspectSymbol:c.symbol,anchorRaw:null,kind:"no-anchors"}));}else {let m=c.filePath?b.isAbsolute(c.filePath)?c.filePath:b.resolve(t,c.filePath):t,h=c.filePath?b.dirname(m):t;for(let S of u){let C=`${c.symbol}::${S.raw}`;if(l.has(C))continue;be(S.path,h,t).exists||(l.add(C),s.push({aspectSymbol:c.symbol,anchorRaw:S.raw,kind:"missing-file"}));}}}}return s}export{ze as A,Ne as B,Fe as C,K as D,Ge as E,Ue as F,Ve as G,be as H,We as I,Ye as J,H as a,ee as b,we as c,pe as d,X as e,ue as f,Pe as g,ve as h,xe as i,Ce as j,Te as k,le as l,Re as m,he as n,je as o,I as p,Oe as q,x as r,Be as s,ge as t,Le as u,Me as v,De as w,Ee as x,_e as y,ke as z};
2
+ import {g,h,i,j,k,l,m,n,o}from'./chunk-K6TLYNRQ.js';import {a,e}from'./chunk-ZJQY5PPP.js';import*as $ from'fs';import*as A from'js-yaml';import {z}from'zod';import*as b from'path';var H={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},ee={"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"},te=["#","$","^","!","~"];function oe(e){return te.includes(e)}var se=z.object({x:z.number(),y:z.number()}),ne=z.object({x:z.number(),y:z.number(),zoom:z.number()}),G=z.object({path:z.string(),include:z.array(z.string()).optional(),exclude:z.array(z.string()).optional()}),V=z.object({id:z.string(),symbol:z.string(),type:z.enum(["feature","component","flow","state","aspect","gate","signal","idea"]),content:z.string().optional(),position:se,tags:z.array(z.string()).optional(),created:z.string(),modified:z.string().optional()}),W=z.object({from:z.string(),to:z.string(),label:z.string().optional(),type:z.string().optional()}),re=z.object({id:z.string(),name:z.string(),nodes:z.array(z.string()),color:z.string().optional()}),Y=z.object({viewport:ne,groups:z.array(re).optional()}),ae=z.object({nodes:z.array(V),connections:z.array(W),layout:Y}),ie=z.object({id:z.string(),name:z.string(),timestamp:z.string(),description:z.string().optional(),state:ae}),ce=z.object({version:z.string(),metadata:z.object({name:z.string(),created:z.string(),modified:z.string()}),sources:z.object({purpose:z.array(G).optional(),portal:z.array(G).optional()}),nodes:z.array(V),connections:z.array(W),layout:Y,snapshots:z.array(ie).optional()});function we(e){let o=[],t;try{t=$.readFileSync(e,"utf8");}catch(s){return o.push(`Cannot read file: ${s.message}`),{data:null,errors:o,rawContent:void 0}}return pe(t)}function pe(e){let o=[],t=null;try{t=A.load(e);}catch(r){let l=r,c=l.mark?.line?l.mark.line+1:void 0;return o.push(`YAML syntax error: ${l.reason||r.message}${c?` (line ${c})`:""}`),{data:null,errors:o,rawContent:e}}if(t==null)return {data:X(),errors:[],rawContent:e};let s=ce.safeParse(t);if(!s.success){for(let r of s.error.issues){let l=r.path.join(".");o.push(`Schema error at ${l||"/"}: ${r.message}`);}return {data:t,errors:o,rawContent:e}}return {data:s.data,errors:[],rawContent:e}}function X(e="Untitled"){let o=new Date().toISOString();return {version:"1.0.0",metadata:{name:e,created:o,modified:o},sources:{purpose:[{path:"./"}],portal:[{path:"./portal.yaml"}]},nodes:[],connections:[],layout:{viewport:{x:0,y:0,zoom:1}}}}function ue(e){return e.metadata.modified=new Date().toISOString(),A.dump(e,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function Pe(e="My Project"){return ue(X(e))}function ve(e,o){return {...e,nodes:[...e.nodes,o],metadata:{...e.metadata,modified:new Date().toISOString()}}}function xe(e,o,t){return {...e,nodes:e.nodes.map(s=>s.id===o?{...s,position:t,modified:new Date().toISOString()}:s),metadata:{...e.metadata,modified:new Date().toISOString()}}}function Ce(e,o){return e.connections.some(s=>s.from===o.from&&s.to===o.to)?e:{...e,connections:[...e.connections,o],metadata:{...e.metadata,modified:new Date().toISOString()}}}function Te(e,o,t){let s={id:`snap-${Date.now()}`,name:o,timestamp:new Date().toISOString(),description:t,state:{nodes:[...e.nodes],connections:[...e.connections],layout:{...e.layout}}};return {...e,snapshots:[...e.snapshots||[],s],metadata:{...e.metadata,modified:new Date().toISOString()}}}async function le(e$1,o$1){let t=[],s=[],r=[],l$1=[];if(e$1.sources.purpose)for(let p of e$1.sources.purpose){let f=b.resolve(o$1,p.path);try{let u=await g(f);r.push(...u.map(a=>a.filePath));let m$1=h(u);for(let[a,{item:i,filePath:d}]of m$1){let P=["feature",...i.tags||[]];t.push(y({id:`purpose-feature-${a}`,symbol:`#${a}`,type:"component",source:"purpose",filePath:d,data:i,description:i.description,tags:P,componentType:i.type,parentSymbol:i.parent,anchors:i.anchors?.map(q=>R(q))}));}let h$1=i(u);for(let[a,{item:i,filePath:d}]of h$1)t.push(y({id:`purpose-component-${a}`,symbol:`#${a}`,type:"component",source:"purpose",filePath:d,data:i,description:i.description,tags:i.tags,componentType:i.type,parentSymbol:i.parent,anchors:i.anchors?.map(P=>R(P))}));let S=j(u);for(let[a,{item:i,filePath:d}]of S)t.push(y({id:`purpose-gate-${a}`,symbol:`^${a}`,type:"gate",source:"purpose",filePath:d,data:i,description:i.description}));let C=k(u);for(let[a,{item:i,filePath:d}]of C)t.push(y({id:`purpose-state-${a}`,symbol:`#${a}`,type:"component",source:"purpose",filePath:d,data:i,description:i.description,tags:["state"]}));let j$1=l(u);for(let[a,{item:i,filePath:d}]of j$1)t.push(y({id:`purpose-flow-${a}`,symbol:`$${a}`,type:"flow",source:"purpose",filePath:d,data:i,description:i.description}));let J=m(u);for(let[a,{item:i,filePath:d}]of J)t.push(y({id:`purpose-signal-${a}`,symbol:`!${a}`,type:"signal",source:"purpose",filePath:d,data:i,description:i.description}));let Q=n(u);for(let[a,{item:i,filePath:d}]of Q)t.push(y({id:`purpose-aspect-${a}`,symbol:`~${a}`,type:"aspect",source:"purpose",filePath:d,data:i,description:i.description,anchors:i.anchors?.map(P=>R(P)),appliesTo:i["applies-to"],tags:i.tags,enforcement:i.enforcement}));let Z=o(u),O=new Set(t.map(a=>a.symbol));for(let a of Z)O.has(a.symbol)||(O.add(a.symbol),t.push(y({id:`purpose-ref-${a.type}-${a.symbol.slice(1)}`,symbol:a.symbol,type:a.type,source:"purpose",filePath:a.filePath,data:{referencedFrom:a.sourceSymbol},description:`Referenced from ${a.sourceSymbol}`})));}catch(u){s.push({source:"purpose",filePath:f,message:u.message});}}if(e$1.sources.portal)for(let p of e$1.sources.portal){let f=b.resolve(o$1,p.path);try{let u;if(f.endsWith(".yaml")||f.endsWith(".yml"))u=await a(f),l$1.push(f);else {let m=await e(f);if(l$1.push(...m),m.length>0){u=await a(m[0]);for(let h=1;h<m.length;h++){let S=await a(m[h]);u.gates.push(...S.gates),u.flows.push(...S.flows);}}else continue}for(let m of u.gates){t.push(fe(m,f));for(let h of m.prizes)t.push(y({id:`gate-signal-${m.id}-${h.id}`,symbol:`!${h.id}`,type:"signal",source:"portal",filePath:f,data:h,description:`Signal from gate ${m.id}`}));}for(let m of u.flows)t.push(me(m,f));}catch(u){s.push({source:"portal",filePath:f,message:u.message});}}for(let p of e$1.nodes){let f=p.tags?.includes("idea");if(!p.content&&!f){let u=t.find(m=>m.symbol===p.symbol);if(u){u.position=p.position,u.tags=p.tags;continue}}t.push(y({id:p.id,symbol:p.symbol,type:p.type,source:"premise",filePath:".premise",data:p,description:p.content,position:p.position,tags:p.tags,created:p.created,modified:p.modified}));}ye(t);let c=new Map;for(let p of t){let f=c.get(p.symbol)||[];f.includes(p.filePath)||f.push(p.filePath),c.set(p.symbol,f);}let g$1=[];for(let[p,f]of c)f.length>1&&g$1.push({symbol:p,files:f});return {symbols:t,purposeFiles:r,portalFiles:l$1,errors:s,timestamp:Date.now(),...g$1.length>0?{duplicateSymbols:g$1}:{}}}function y(e){return {...e,data:e.data??null,references:e.references??[],referencedBy:e.referencedBy??[]}}function fe(e,o){let t=e.id.startsWith("^")?e.id.slice(1):e.id;return y({id:`gate-${t}`,symbol:`^${t}`,type:"gate",source:"portal",filePath:o,data:e,description:e.description,position:e.position})}function me(e,o){return y({id:`gate-flow-${e.id}`,symbol:`$${e.id}`,type:"flow",source:"portal",filePath:o,data:e,description:e.description})}function R(e){let o=e.lastIndexOf(":");if(o===-1||o===e.length-1)return {path:e,lines:0,raw:e};let t=e.slice(o+1),s=e.slice(0,o);if(!/^[\d,\- ]+$/.test(t))return {path:e,lines:0,raw:e};if(t.includes("-")){let[r,l]=t.split("-").map(Number);return {path:s,lines:[r,l],raw:e}}else if(t.includes(",")){let r=t.split(",").map(Number);return {path:s,lines:r,raw:e}}else return {path:s,lines:Number(t),raw:e}}var de=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function ye(e){let o=new Map(e.map(t=>[t.symbol,t]));for(let t of e){let s=JSON.stringify(t.data),r=/(?:\?[@#$%~^!]|[@#$%~^!?])[a-zA-Z][\w-]*/g,l=(s.match(r)||[]).filter(c=>!de.has(c));for(let c of l)if(c!==t.symbol&&o.has(c)){t.references.includes(c)||t.references.push(c);let g=o.get(c);g&&!g.referencedBy.includes(t.symbol)&&g.referencedBy.push(t.symbol);}}}async function Re(e){let o={metadata:{name:b.basename(e),created:new Date().toISOString(),modified:new Date().toISOString()},sources:{purpose:[{path:"./"}],portal:[{path:"./"}]},nodes:[]};return le(o,e)}function he(){return {entries:new Map,byType:new Map,bySource:new Map,timestamp:0}}function je(e){let o=he();o.timestamp=e.timestamp;for(let t of e.symbols)o.entries.set(t.id,t),o.byType.has(t.type)||o.byType.set(t.type,[]),o.byType.get(t.type).push(t),o.bySource.has(t.source)||o.bySource.set(t.source,[]),o.bySource.get(t.source).push(t);return o}function I(e,o){for(let t of e.entries.values())if(t.symbol===o)return t}function Oe(e,o){return e.entries.get(o)}function x(e,o){return e.byType.get(o)||[]}function Be(e,o){return e.bySource.get(o)||[]}function ge(e,o){let t=o.toLowerCase(),s=[];for(let r of e.entries.values()){if(r.symbol.toLowerCase().includes(t)){s.push(r);continue}if(r.description?.toLowerCase().includes(t)){s.push(r);continue}if(r.tags?.some(l=>l.toLowerCase().includes(t))){s.push(r);continue}if(r.componentType?.toLowerCase().includes(t)){s.push(r);continue}}return s}function Le(e,o){return x(e,"component").filter(s=>s.componentType===o)}function Me(e){let o=new Set,t=x(e,"component");for(let s of t)s.componentType&&o.add(s.componentType);return Array.from(o).sort()}function De(e,o){return x(e,"component").filter(s=>s.parentSymbol===o)}function Ee(e,o){let t=I(e,o);return t?t.referencedBy.map(s=>I(e,s)).filter(s=>s!==void 0):[]}function _e(e,o){let t=I(e,o);return t?t.references.map(s=>I(e,s)).filter(s=>s!==void 0):[]}function ke(e,o){let t=[];for(let s of e.entries.values())s.tags?.includes(o)&&t.push(s);return t}function ze(e){let o=new Set;for(let t of e.entries.values())for(let s of t.tags||[])o.add(s);return Array.from(o).sort()}function Ne(e){let o={component:0,flow:0,gate:0,signal:0,aspect:0};for(let[t,s]of e.byType)t in o&&(o[t]=s.length);return o}function Fe(e){return Array.from(e.entries.values())}function K(e){if(e.length<2)return null;let o=e[0],t=e.slice(1);return oe(o)?{type:ee[o],name:t}:null}function Ge(e,o){return `${H[e]}${o}`}function Ue(e){return K(e)!==null}function Ve(e,o,t=10){let s=o.toLowerCase(),r=K(o);return r?x(e,r.type).filter(c=>c.symbol.toLowerCase().includes(s)).slice(0,t):ge(e,o).slice(0,t)}function be(e,o,t){if(b.isAbsolute(e))return {resolvedPath:e,baseUsed:"absolute",exists:$.existsSync(e)};let s=b.join(t,e);if($.existsSync(s))return {resolvedPath:s,baseUsed:"project-root",exists:true};let r=b.resolve(o,e);return $.existsSync(r)?{resolvedPath:r,baseUsed:"purpose-dir",exists:true}:{resolvedPath:s,baseUsed:"project-root",exists:false}}function We(e,o,t){if(b.isAbsolute(e)){let l=$.existsSync(e);return {rootResolves:l,purposeResolves:l,mismatch:false}}let s=$.existsSync(b.join(t,e)),r=$.existsSync(b.resolve(o,e));return {rootResolves:s,purposeResolves:r,mismatch:s!==r}}function Se(e,o){return e.includes("*")?new RegExp("^"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(o):e===o}function Ye(e,o,t){let s=[],r=x(e,"aspect"),l=new Set;for(let c of r){let g=c.appliesTo||[];if(g.length!==0)for(let p of g)for(let f of o){if(!Se(p,f))continue;let u=c.anchors||[];if(u.length===0){let m=`${c.symbol}::__no-anchors__`;l.has(m)||(l.add(m),s.push({aspectSymbol:c.symbol,anchorRaw:null,kind:"no-anchors"}));}else {let m=c.filePath?b.isAbsolute(c.filePath)?c.filePath:b.resolve(t,c.filePath):t,h=c.filePath?b.dirname(m):t;for(let S of u){let C=`${c.symbol}::${S.raw}`;if(l.has(C))continue;be(S.path,h,t).exists||(l.add(C),s.push({aspectSymbol:c.symbol,anchorRaw:S.raw,kind:"missing-file"}));}}}}return s}export{ze as A,Ne as B,Fe as C,K as D,Ge as E,Ue as F,Ve as G,be as H,We as I,Ye as J,H as a,ee as b,we as c,pe as d,X as e,ue as f,Pe as g,ve as h,xe as i,Ce as j,Te as k,le as l,Re as m,he as n,je as o,I as p,Oe as q,x as r,Be as s,ge as t,Le as u,Me as v,De as w,Ee as x,_e as y,ke as z};
@@ -1998,6 +1998,7 @@ exit 0
1998
1998
  `)[0]||"unknown error"}`}finally{try{e.unlinkSync(c);}catch{}}}catch{return null}}var J=`#!/bin/sh
1999
1999
  # Paradigm post-commit hook - captures history from commits
2000
2000
  # Installed by: paradigm hooks install
2001
+ # paradigm-hook-version: 2 (v2 adds the provider-agnostic sync-commit delegate)
2001
2002
 
2002
2003
  # Get the commit message and hash
2003
2004
  COMMIT_HASH=$(git rev-parse HEAD)
@@ -2041,6 +2042,14 @@ if [ -n "$MSG_SYMBOLS" ]; then
2041
2042
  SYMBOLS=$(echo "$SYMBOLS" | tr ',' '\\n' | sort -u | tr '\\n' ',' | sed 's/,$//')
2042
2043
  fi
2043
2044
 
2045
+ # Provider-agnostic sync delegate (Phase 2b). A touched symbol drops a comment
2046
+ # on any linked external item. ENTIRELY best-effort: redirected + '|| true' so a
2047
+ # commit is NEVER slowed-to-notice or blocked. The hook NEVER names a provider \u2014
2048
+ # sync-commit resolves it abstractly from the task's external_ref via the registry.
2049
+ if [ -n "$MSG_SYMBOLS" ]; then
2050
+ npx paradigm task sync-commit --hash "$COMMIT_HASH" --symbols "$MSG_SYMBOLS" >/dev/null 2>&1 || true
2051
+ fi
2052
+
2044
2053
  # Determine intent from commit message
2045
2054
  determine_intent() {
2046
2055
  case "$COMMIT_MSG" in
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ import {c,b as b$2}from'./chunk-3KVVC4WV.js';import {j,a as a$1,d,g as g$1}from'./chunk-KAUGQMXU.js';import {z,i,c as c$1,f as f$1,j as j$1}from'./chunk-KAFQA7HV.js';import {b as b$1,a as a$2}from'./chunk-EK4ZRIFJ.js';import {f,b as b$3}from'./chunk-ECO3LHCE.js';import {b,a}from'./chunk-5TAVYPOV.js';import*as l from'fs';import*as g from'path';import*as nt from'js-yaml';import*as T from'os';function Q(e){return g.join(e,K,ut)}function gt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${e}-${t}`}function E(e,t){let n={id:gt(),timestamp:new Date().toISOString(),...t};_.push(n),_.length>k&&(_=_.slice(-k));try{let o=g.join(e,K);l.mkdirSync(o,{recursive:!0});let r=Q(e);l.appendFileSync(r,JSON.stringify(n)+`
3
+ `,"utf8"),pt(r);}catch{}return n}function pt(e){try{if(l.statSync(e).size>512*1024){let o=l.readFileSync(e,"utf8").trim().split(`
4
+ `);if(o.length>k){let r=o.slice(-k);l.writeFileSync(e,r.join(`
5
+ `)+`
6
+ `,"utf8");}}}catch{}}function Lt(e,t){let n=ht(e);return t?.type&&(n=n.filter(o=>o.type===t.type)),t?.source&&(n=n.filter(o=>o.source===t.source)),t?.symbol&&(n=n.filter(o=>o.symbols?.includes(t.symbol))),t?.agent&&(n=n.filter(o=>o.agent===t.agent)),t?.since&&(n=n.filter(o=>o.timestamp>=t.since)),n.sort((o,r)=>r.timestamp.localeCompare(o.timestamp)),t?.limit&&(n=n.slice(0,t.limit)),n}function ht(e){let t=Q(e);if(!l.existsSync(t))return [..._];try{return l.readFileSync(t,"utf8").trim().split(`
7
+ `).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return [..._]}}function Z(e,t,n){let o=0,r=0,i=0,s=0;if(n.symbols?.length&&e.symbols?.length)for(let c of n.symbols)for(let a of e.symbols)X(c,a)&&(o=Math.max(o,1));if(n.paths?.length&&e.path){for(let c of n.paths)if(X(c,e.path)){r=1;break}}if(n.concepts?.length){let c=[e.context||"",...e.keywords||[],e.type||""].join(" ").toLowerCase(),a=0;for(let u of n.concepts)u&&c.includes(u.toLowerCase())&&a++;n.concepts.length>0&&(i=a/n.concepts.length);}if(n.signals?.length){for(let c of n.signals)if(c.type===e.type){s=1;break}}let f=[o,r,i,s].sort((c,a)=>a-c),d=f[0]*.5+f[1]*.2+f[2]*.15+f[3]*.15,m=n.threshold??.6;return {agentId:t,score:d,breakdown:{symbolMatch:o,pathMatch:r,conceptMatch:i,signalMatch:s},shouldNominate:d>=m,quietReason:d<m?"below-threshold":void 0}}function X(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var K,ut,k,_,tt=b(()=>{K=".paradigm/events",ut="stream.jsonl",k=1e3,_=[];});function C(e){let t=g.join(e,yt);if(!l.existsSync(t))return {...b$2};try{let n=l.readFileSync(t,"utf8"),o=nt.load(n);return bt(b$2,o)}catch{return {...b$2}}}function bt(e,t){let n={...e};if(t.version&&(n.version=t.version),t.default_ring&&(n.default_ring=t.default_ring),t.observation&&(n.observation={allow:t.observation.allow||e.observation?.allow,deny:[...e.observation?.deny||[],...t.observation.deny||[]].filter((o,r,i)=>i.indexOf(o)===r)}),t.streams){n.streams={...e.streams};for(let o of ["work_log","learning_journal","team_decisions"])t.streams[o]&&(n.streams[o]={...e.streams?.[o],...t.streams[o],deny_content:[...e.streams?.[o]?.deny_content||[],...t.streams[o]?.deny_content||[]].filter((r,i,s)=>s.indexOf(r)===i)});}return t.upstream&&(n.upstream={...e.upstream,...t.upstream}),t.network&&(n.network={...e.network,...t.network}),t.agent_overrides&&(n.agent_overrides={...e.agent_overrides,...t.agent_overrides}),t.deployment&&(n.deployment={...e.deployment,...t.deployment}),n}function M(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(r=>R(r,t))||e.observation?.deny?.some(o=>R(o,t))?false:e.observation?.allow?.length?e.observation.allow.some(o=>R(o,t)):true}function Gt(e,t,n){let o=t.streams?.[n];if(!o)return {filtered:e,redacted:[]};let r=[],i=e;if(o.redaction)for(let s of o.redaction)try{let f=new RegExp(s.pattern,"gi"),d=i.match(f);d&&(r.push(...d),i=i.replace(f,s.replacement||"[REDACTED]"));}catch{}return {filtered:i,redacted:r}}function R(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var yt,ot=b(()=>{c();yt=".paradigm/data-policy.yaml";});function kt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function jt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${e}-${t}`}function st(e,t){let n=i(e),o=C(e),r=[];for(let m of n){if(!m.attention||!c$1(m.id,e)||t.path&&!M(o,t.path,m.id))continue;let c=Z(t,m.id,m.attention);c.shouldNominate&&r.push({profile:m,score:c});}if(r.length===0)return {nominations:[],debates:[]};let i$1=A(e,{since:new Date(Date.now()-3e4).toISOString()}),s=r.filter(({profile:m})=>!i$1.find(a=>a.agent===m.id&&a.brief===rt(m,t,{...r.find(u=>u.profile.id===m.id).score})));if(s.length===0)return {nominations:[],debates:[]};let f=s.map(({profile:m,score:c})=>{let a=Tt(t,c),u=Pt(m,t);return {id:kt(),agent:m.id,relevance:c.score,urgency:a,type:u,brief:rt(m,t,c),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});Dt(e,f);let d=At(e,f);return d.length>0&&Ft(e,d),{nominations:f,debates:d}}function Tt(e,t){return e.severity==="critical"?"critical":e.severity==="error"||e.type==="compliance-violation"||e.type==="error-encountered"?"high":e.type==="gate-added"||e.type==="route-created"||t.score>=.9?"medium":"low"}function Pt(e,t){let n=e.collaboration?.stance;return t.type==="compliance-violation"||t.type==="error-encountered"?"warning":t.type==="gate-added"||t.type==="route-created"?"observation":n==="advisory"||n==="lead"?"suggestion":"observation"}function rt(e,t,n){let o=e.role||e.id;switch(t.type){case "gate-checked":return `${o}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${o}: ${t.path||"File"} modified \u2014 review for ${e.id==="security"?"security implications":e.id==="tester"?"test coverage":e.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${o}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${o}: New route ${t.symbols?.join(", ")||""} \u2014 ${e.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${o}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${e.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${o}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${o}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${o}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let r=n.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:n.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${o}: ${r}`}}}function At(e,t){if(t.length<2)return [];let n=[],o=new Map;for(let r of t)for(let i of r.triggered_by){let s=o.get(i)||[];s.push(r),o.set(i,s);}for(let[r,i]of o){if(i.length<2||new Set(i.map(m=>m.agent)).size<2)continue;let f=new Set(i.map(m=>m.type)),d=f.size>1&&f.has("warning")&&f.has("suggestion");n.push({id:jt(),topic:`Multiple agents responded to event ${r}`,nominations:i.map(m=>m.id),type:d?"conflicting":"complementary",overlap_events:[r]});}return n}function I(e){return g.join(e,S,St)}function L(e){return g.join(e,S,_t)}function Dt(e,t){try{let n=g.join(e,S);l.mkdirSync(n,{recursive:!0});let o=I(e),r=t.map(s=>JSON.stringify(s)).join(`
8
+ `)+`
9
+ `;l.appendFileSync(o,r,"utf8"),J(o,it);let{nominationTtlDays:i}=P(e);at(o,i*24*60*60*1e3);}catch{}}function Ft(e,t){try{let n=g.join(e,S);l.mkdirSync(n,{recursive:!0});let o=L(e),r=t.map(s=>JSON.stringify(s)).join(`
10
+ `)+`
11
+ `;l.appendFileSync(o,r,"utf8"),J(o,Et);let{debateTtlDays:i}=P(e);at(o,i*24*60*60*1e3);}catch{}}function $t(e,t){try{let n=g.join(e,S);l.mkdirSync(n,{recursive:!0});let o=g.join(n,wt);l.appendFileSync(o,JSON.stringify(t)+`
12
+ `,"utf8"),J(o,it);}catch(n){a$2.component("#promotion-decisions").warn("failed to record promotion decision",{agent:t.agent,error:n instanceof Error?n.message:String(n)});}}function J(e,t){try{let o=l.readFileSync(e,"utf8").trim().split(`
13
+ `).filter(r=>r.trim());if(o.length>t){let r=o.slice(-t);l.writeFileSync(e,r.join(`
14
+ `)+`
15
+ `,"utf8");}}catch{}}function P(e){let t={nominationTtlDays:Nt,debateTtlDays:vt};try{let n=g.join(e,".paradigm","config.yaml");if(!l.existsSync(n))return t;let o=a("js-yaml"),r=l.readFileSync(n,"utf8"),s=o.load(r)?.ambient;return s?{nominationTtlDays:typeof s["nomination-ttl-days"]=="number"?s["nomination-ttl-days"]:t.nominationTtlDays,debateTtlDays:typeof s["debate-ttl-days"]=="number"?s["debate-ttl-days"]:t.debateTtlDays}:t}catch{return t}}function at(e,t){try{if(!l.existsSync(e))return;let o=l.readFileSync(e,"utf8").trim().split(`
16
+ `).filter(s=>s.trim());if(o.length<=xt)return;let r=Date.now()-t,i=o.filter(s=>{try{let f=JSON.parse(s);return (f.timestamp?new Date(f.timestamp).getTime():Date.now())>=r}catch{return !0}});i.length<o.length&&l.writeFileSync(e,i.join(`
17
+ `)+`
18
+ `,"utf8");}catch{}}function A(e,t){let n=I(e);if(!l.existsSync(n))return [];try{let r=l.readFileSync(n,"utf8").trim().split(`
19
+ `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null);return t?.agent&&(r=r.filter(i=>i.agent===t.agent)),t?.urgency&&(r=r.filter(i=>i.urgency===t.urgency)),t?.surfaced!==void 0&&(r=r.filter(i=>i.surfaced===t.surfaced)),t?.pending_only&&(r=r.filter(i=>!i.engaged)),t?.since&&(r=r.filter(i=>i.timestamp>=t.since)),r.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),t?.limit&&(r=r.slice(0,t.limit)),r}catch{return []}}function Kt(e){let t=L(e);if(!l.existsSync(t))return [];try{return l.readFileSync(t,"utf8").trim().split(`
20
+ `).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return []}}function Qt(e,t,n,o){let r=I(e);if(!l.existsSync(r))return false;try{let s=l.readFileSync(r,"utf8").trim().split(`
21
+ `),f=!1,d=s.map(m=>{try{let c=JSON.parse(m);return c.id===t?(c.engaged=!0,c.response=n,o&&(c.reason=o),f=!0,JSON.stringify(c)):m}catch{return m}});if(f&&(l.writeFileSync(r,d.join(`
22
+ `)+`
23
+ `,"utf8"),n==="accepted"||n==="dismissed")){let m=JSON.parse(s.find(a=>{try{return JSON.parse(a).id===t}catch{return !1}}));i(e).find(a=>a.id===m.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&E(e,{type:"work-completed",source:"agent-action",agent:m.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return f}catch{return false}}function Zt(e,t,n,o){let r=L(e);if(!l.existsSync(r))return false;try{let s=l.readFileSync(r,"utf8").trim().split(`
24
+ `),f=!1,d=s.map(m=>{try{let c=JSON.parse(m);if(c.id===t){c.resolution={chosen:n,reason:o,resolved_by:"human",resolved_at:new Date().toISOString()},f=!0;let a=c.nominations.filter(u=>u!==n);for(let u of a){let p=A(e).find(b=>b.id===u);p&&E(e,{type:"work-completed",source:"agent-action",agent:p.agent,context:`Debate ${t} resolved \u2014 nomination ${u} not chosen`,data:{debate_id:t,chosen:n,reason:o}});}return JSON.stringify(c)}return m}catch{return m}});return f&&l.writeFileSync(r,d.join(`
25
+ `)+`
26
+ `,"utf8"),f}catch{return false}}function te(e){let t=g.join(e,S,".last-processed"),n="";try{l.existsSync(t)&&(n=l.readFileSync(t,"utf8").trim());}catch{}let o=g.join(e,S,"stream.jsonl");if(!l.existsSync(o))return {processed:0,nominations:[]};let r=[];try{r=l.readFileSync(o,"utf8").trim().split(`
27
+ `).filter(a=>a.trim()).map(a=>{try{return JSON.parse(a)}catch{return null}}).filter(a=>a!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(n){let c=r.findIndex(a=>a.id===n);c>=0&&(i=c+1);}let s=r.slice(i);if(s.length===0)return {processed:0,nominations:[]};let f=[],d=s.slice(0,50);for(let c of d){let{nominations:a}=st(e,c);f.push(...a);}let m=d[d.length-1];try{l.mkdirSync(g.join(e,S),{recursive:!0}),l.writeFileSync(t,m.id,"utf8");}catch{}return {processed:d.length,nominations:f}}function ee(e,t,n){let o=C(e);if(t.path&&!M(o,t.path))return {event:E(e,t),nominations:[],debates:[]};let r=E(e,t);if(n?.skipNominations)return {event:r,nominations:[],debates:[]};let{nominations:i,debates:s}=st(e,r);return i.length>0&&Rt(e,i),{event:r,nominations:i,debates:s}}function ne(e,t){let n=f$1(e,t);if(!n?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let o=n.attention.threshold??.6,{nominationTtlDays:r}=P(e),i=r*24*60*60*1e3,d=A(e,{agent:t}).filter(h=>h.engaged||Date.now()-new Date(h.timestamp).getTime()<i).filter(h=>h.engaged);if(d.length<5)return {adjusted:false,oldThreshold:o,newThreshold:o,reason:`Insufficient data (${d.length}/5 engaged nominations)`};let m=d.filter(h=>h.response==="accepted").length,c=d.filter(h=>h.response==="dismissed").length,a=m/d.length,u=c/d.length,p=o,b="No adjustment needed";if(u>.6?(p=Math.min(.95,o+.05),b=`High dismiss rate (${(u*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):a>.8&&(p=Math.max(.2,o-.05),b=`High accept rate (${(a*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),p===o)return {adjusted:false,oldThreshold:o,newThreshold:p,reason:b};n.attention.threshold=p;let w=g.join(e,".paradigm/agents",`${t}.agent`),N=l.existsSync(w)?"project":"global";return j$1(t,n,N,e),E(e,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${o.toFixed(2)} \u2192 ${p.toFixed(2)} (${b})`,data:{old_threshold:o,new_threshold:p,accept_rate:a,dismiss_rate:u}}),{adjusted:true,oldThreshold:o,newThreshold:p,reason:b}}function Ot(e,t){let{nominationTtlDays:n}=P(e),o=n*24*60*60*1e3,i=A(e,{agent:t}).filter(a=>a.engaged||Date.now()-new Date(a.timestamp).getTime()<o),s=i.filter(a=>a.response==="accepted").length,f=i.filter(a=>a.response==="dismissed").length,d=i.filter(a=>a.response==="deferred").length,m=i.filter(a=>!a.engaged).length,c=s+f+d;return {total:i.length,accepted:s,dismissed:f,deferred:d,pending:m,acceptRate:c>0?s/c:0}}function oe(e){let n=i(e).filter(a=>c$1(a.id,e)).map(a=>{let u=Ot(e,a.id),p=0;try{let b=g.join(T.homedir(),".paradigm","notebooks",a.id);l.existsSync(b)&&(p=l.readdirSync(b).filter(w=>w.endsWith(".yaml")).length);}catch{}return {id:a.id,acceptRate:u.acceptRate,threshold:a.attention?.threshold??.5,expertiseCount:(a.expertise||[]).length,notebookCount:p,transferableCount:(a.transferable||[]).length,totalNominations:u.total}}),o=n.length||1,r=n.reduce((a,u)=>a+u.acceptRate,0)/o,i$1=n.reduce((a,u)=>a+u.threshold,0)/o,s=n.reduce((a,u)=>a+u.expertiseCount,0),f=n.reduce((a,u)=>a+u.notebookCount,0),d=n.reduce((a,u)=>a+u.transferableCount,0),m=n.reduce((a,u)=>a+u.totalNominations,0),c;return m<10?c="cold-start":r<.5?c="accumulating":r<.7?c="calibrating":c="mature",{agents:n,aggregate:{avgAcceptRate:r,avgThreshold:i$1,totalExpertise:s,totalNotebooks:f,totalTransferable:d},healthStatus:c}}function Rt(e,t){if(t.length===0)return;let n=g.join(T.homedir(),".paradigm","score","outbox");if(l.existsSync(n))try{let o=g.join(n,`nom-${Date.now()}.json`),r={type:"nomination_forward",nominations:t.map(i=>({...i})),origin:Ct(e),timestamp:new Date().toISOString()};l.writeFileSync(o,JSON.stringify(r),"utf8");}catch{}}function Ct(e){try{let t=g.join(e,".paradigm","config.yaml");if(l.existsSync(t)){let o=l.readFileSync(t,"utf8").match(/project:\s*(.+)/);if(o)return o[1].trim()}}catch{}return g.basename(e)}function re(e,t){let n=b$3(t,{trigger:"pattern_discovered",limit:100}),o=b$3(t,{trigger:"human_feedback",limit:100}),r=[...n,...o],i=[];for(let s of r){if(s.promoted_to_notebook)continue;let f=(s.tags||[s.pattern?.id||"learned-pattern"]).map(a$1).filter(Boolean),d$1=s.confidence_after??0,m=d$1>=.8,c=.5,a=false;try{let u=d(t,f,e);c=u.value,a=u.found;}catch{}if($t(e,{ts:new Date().toISOString(),agent:t,concepts:f,before:c,after:d$1,delta:d$1-c,promoted:m,priorFound:a,gate:"absolute-0.8"}),!((s.confidence_after??0)<.8))try{let{entry:u}=g$1(t,{context:s.pattern?.applies_when||s.insight.slice(0,80),snippet:s.pattern?.correct_approach||s.insight,confidence:s.confidence_after??.5,concepts:f,tags:s.tags??[],provenance:{source:"lore",loreEntryId:s.id,createdBy:t}},"global",e);i.push({journalId:s.id,notebookId:u.id});try{let p=g.join(T.homedir(),".paradigm","agents",t,"journal");if(l.existsSync(p)){let b=l.readdirSync(p).filter(w=>w.endsWith(".yaml"));for(let w of b){let N=g.join(p,w),h=l.readFileSync(N,"utf8");if(h.includes(s.id)){let U=h.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${u.id}"`);if(U===h){let B=h.trimEnd().split(`
28
+ `);B.push(`promoted_to_notebook: "${u.id}"`),l.writeFileSync(N,B.join(`
29
+ `)+`
30
+ `,"utf8");}else l.writeFileSync(N,U,"utf8");break}}}}catch{}}catch(u){console.error("PROMOTE_THREW",u.message);}}return {promoted:i.length,entries:i}}function ie(e){let t=g.join(e,Mt),n={default_min_urgency:"low",enable_debates:true};if(!l.existsSync(t))return n;try{let o=a("js-yaml"),r=l.readFileSync(t,"utf8"),i=o.load(r);return {...n,...i}}catch{return n}}function se(e,t){let n={critical:0,high:1,medium:2,low:3},o=n[t.default_min_urgency||"low"]??3;return e.filter(r=>{let i=n[r.urgency]??3;if(t.preferences){let s=t.preferences.find(f=>f.agent===r.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(d=>r.urgency===d||r.type===d))return false;if(s.min_urgency){let f=n[s.min_urgency]??3;return i<=f}}}return i<=o})}var S,St,wt,_t,it,Et,Nt,vt,xt,Mt,It=b(()=>{tt();ot();z();f();j();b$1();S=".paradigm/events",St="nominations.jsonl",wt="promotion-decisions.jsonl",_t="debates.jsonl",it=500,Et=200,Nt=7,vt=14,xt=100;Mt=".paradigm/surfacing.yaml";});export{Lt as a,tt as b,C as c,Gt as d,ot as e,st as f,At as g,Dt as h,A as i,Kt as j,Qt as k,Zt as l,te as m,ee as n,ne as o,Ot as p,oe as q,Rt as r,re as s,ie as t,se as u,It as v};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import*as s from'fs';import*as r from'path';import*as l from'js-yaml';var p=[{id:"explore-before-implement",name:"Explore Before Implementing",description:"Call ripple/navigate/search before modifying existing symbols to understand impact",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple","paradigm_navigate","paradigm_search","paradigm_related"]}},enabled:true},{id:"ripple-before-modify",name:"Ripple Before Modifying",description:"Run ripple analysis before modifying symbols with dependents",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple"]}},enabled:true},{id:"check-fragility",name:"Check Fragility",description:"Check history fragility for symbols before modifying frequently-broken code",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_history_fragility"]}},enabled:true},{id:"wisdom-before-implement",name:"Check Team Wisdom",description:"Check team wisdom (preferences, antipatterns, decisions) before implementing",category:"collaboration",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_wisdom_context","paradigm_wisdom_expert"]}},enabled:true},{id:"verify-before-done",name:"Verify Before Done",description:"Run postflight compliance checks before finishing a session",category:"verification",trigger:"on-stop",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight"]}},enabled:true},{id:"postflight-compliance",name:"Postflight Compliance",description:"Ensure postflight checks pass without errors before finishing",category:"verification",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight","paradigm_reindex"]}},enabled:true},{id:"test-new-components",name:"Test New Components",description:"New components should have associated tests or test plan documented",category:"testing",trigger:"postflight",severity:"advisory",check:{type:"tests-exist",params:{patterns:["**/*.test.*","**/*.spec.*","**/tests/**"]}},enabled:true},{id:"purpose-coverage",name:"Purpose File Coverage",description:"All modified source directories should have .purpose file coverage",category:"documentation",trigger:"postflight",severity:"warn",check:{type:"file-exists",params:{patterns:["**/.purpose"]}},enabled:true},{id:"record-lore-for-significant",name:"Record Lore for Significant Changes",description:"Sessions modifying 3+ files should record a lore entry",category:"documentation",trigger:"on-stop",severity:"warn",check:{type:"lore-recorded",params:{}},enabled:true},{id:"gates-for-routes",name:"Gates for Routes",description:"API routes should have corresponding gate declarations in portal.yaml",category:"security",trigger:"postflight",severity:"warn",check:{type:"gates-declared",params:{requireRoutes:true}},enabled:true},{id:"commit-message-symbols",name:"Commit Message Format",description:"Commit messages should follow type(#symbol): format and include a Symbols: trailer",category:"documentation",trigger:"on-commit",severity:"advisory",check:{type:"commit-message-format",params:{messagePatterns:["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"]}},enabled:true},{id:"flow-coverage-for-multi-component",name:"Flow Coverage",description:"Changes spanning 3+ components should have a documented $flow",category:"documentation",trigger:"postflight",severity:"advisory",check:{type:"flow-coverage",params:{minSteps:3}},enabled:true},{id:"context-session-awareness",name:"Context Awareness",description:"Use session recovery or context check tools for session continuity",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"context-checked",params:{contextTools:["paradigm_session_health","paradigm_session_recover","paradigm_session_checkpoint"]}},enabled:true},{id:"aspect-anchors-valid",name:"Aspect Anchors Valid",description:"Aspects touched during the session should have their code anchors validated",category:"verification",trigger:"postflight",severity:"advisory",check:{type:"aspect-anchored",params:{checkAnchors:true}},enabled:true}];var y=p,u=30*1e3;function v(t){try{let e=r.join(t,".paradigm","config.yaml");if(s.existsSync(e)){let i=s.readFileSync(e,"utf8"),a=l.load(i)?.limits;if(a?.habitsCacheTtlMs&&typeof a.habitsCacheTtlMs=="number")return a.habitsCacheTtlMs}}catch{}return u}var d=new Map;function H(t){let e=r.resolve(t),i=d.get(e),o=v(e);if(i&&Date.now()-i.loadedAt<o)return i.habits;let a=C(e);return d.set(e,{habits:a,loadedAt:Date.now()}),a}function C(t){let e=new Map;for(let n of y)e.set(n.id,{...n});let i=process.env.HOME||process.env.USERPROFILE||"~",o=g(r.join(i,".paradigm","habits.yaml"));o&&m(e,o);let a=f(r.join(i,".paradigm","habits"));for(let n of a)e.set(n.id,n);let c=g(r.join(t,".paradigm","habits.yaml"));c&&m(e,c);let b=f(r.join(t,".paradigm","habits"));for(let n of b)e.set(n.id,n);return Array.from(e.values())}function f(t){if(!s.existsSync(t))return [];try{let e=s.readdirSync(t).filter(o=>o.endsWith(".habit")).sort(),i=[];for(let o of e)try{let a=s.readFileSync(r.join(t,o),"utf8"),c=l.load(a);c?.id&&c?.name&&i.push(c);}catch{}return i}catch{return []}}function g(t){if(!s.existsSync(t))return null;try{let e=s.readFileSync(t,"utf8");return l.load(e)}catch{return null}}function m(t,e){if(e.habits)for(let i of e.habits)t.set(i.id,{...i});if(e.overrides)for(let[i,o]of Object.entries(e.overrides)){let a=t.get(i);a&&k(a,o);}}function k(t,e){e.severity!==void 0&&(t.severity=e.severity),e.enabled!==void 0&&(t.enabled=e.enabled);}function x(t){return t.filter(e=>e.enabled)}function w(t){let e=r.resolve(t);d.delete(e);}export{H as a,x as b,w as c};
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import*as A from'fs';import*as $ from'js-yaml';import {z as z$1}from'zod';import*as d from'path';import {glob}from'glob';var j=z$1.object({description:z$1.string(),type:z$1.string().optional(),parent:z$1.string().optional(),anchors:z$1.array(z$1.string()).optional(),tags:z$1.array(z$1.string()).optional(),endpoints:z$1.array(z$1.string()).optional(),tests:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),aspects:z$1.array(z$1.string()).optional(),flows:z$1.array(z$1.string()).optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),states:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),location:z$1.string().optional(),locations:z$1.array(z$1.string()).optional(),uses:z$1.array(z$1.string()).optional(),"used-by":z$1.array(z$1.string()).optional(),"used-for":z$1.array(z$1.string()).optional(),exports:z$1.array(z$1.string()).optional(),status:z$1.string().optional(),properties:z$1.record(z$1.unknown()).optional(),handles:z$1.array(z$1.string()).optional()}).passthrough(),v=j.extend({id:z$1.string()}),P=z$1.object({description:z$1.string().optional(),category:z$1.string().optional(),severity:z$1.enum(["info","warn","error"]).optional(),emitters:z$1.array(z$1.string()).optional(),related:z$1.array(z$1.string()).optional(),data:z$1.record(z$1.unknown()).optional()}),E=z$1.union([P,z$1.string().transform(n=>({description:n}))]),O=z$1.object({from:z$1.string(),to:z$1.string(),type:z$1.string(),description:z$1.string().optional()}),C=z$1.union([O,z$1.string()]),F=z$1.object({component:z$1.string(),action:z$1.string(),description:z$1.string().optional()}),k=z$1.union([F,z$1.string()]),I=z$1.object({name:z$1.string(),description:z$1.string().optional(),steps:z$1.array(k)}),R=z$1.object({description:z$1.string().optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),steps:z$1.array(k).optional()}),D=z$1.object({description:z$1.string().optional(),requires:z$1.array(z$1.string()).optional(),keys:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional()}),M=z$1.object({description:z$1.string().optional(),default:z$1.unknown().optional(),type:z$1.string().optional()}),Y=z$1.object({description:z$1.string().optional(),tags:z$1.array(z$1.string()).optional(),anchors:z$1.array(z$1.string()).optional(),"applies-to":z$1.array(z$1.string()).optional(),enforcement:z$1.string().optional()}),V=z$1.object({target:z$1.string(),type:z$1.string(),path:z$1.string()}),W=z$1.object({version:z$1.string().optional(),description:z$1.string().optional(),apiSpec:z$1.string().optional(),context:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),features:z$1.union([z$1.array(v),z$1.record(j)]).optional(),components:z$1.union([z$1.array(v),z$1.record(j)]).optional(),gates:z$1.record(D).optional(),states:z$1.record(M).optional(),signals:z$1.record(E).optional(),aspects:z$1.record(Y).optional(),relationships:z$1.array(C).optional(),flows:z$1.union([z$1.array(I),z$1.record(R)]).optional(),references:z$1.array(V).optional()});function T(n){let e=z(n);return {data:e.data,errors:e.errors}}function z(n){let e=[],r=[],s;try{s=A.readFileSync(n,"utf8");}catch(i){let p=`Cannot read file: ${i.message}`;return e.push(p),r.push({message:p,type:"file"}),{data:null,errors:e,detailedErrors:r,rawContent:void 0,isYamlValid:false}}let c=s.replace(/^([#~!$^][\w-]+):/gm,'"$1":').replace(/^(\s*-\s+)([!#][\w-]+)$/gm,'$1"$2"'),a=null;try{a=$.load(c);}catch(i){let p=i,f=p.mark?.line?p.mark.line+1:void 0,l=`YAML syntax error: ${p.reason||i.message}`;return e.push(`${l}${f?` (line ${f})`:""}`),r.push({message:l,line:f,type:"yaml"}),{data:null,errors:e,detailedErrors:r,rawContent:s,isYamlValid:false}}if(a==null)return {data:{},errors:[],detailedErrors:[],rawContent:s,isYamlValid:true};if(typeof a=="object"&&a!==null){let i=a,p={"#":"components",$:"flows","^":"gates","!":"signals","~":"aspects"};for(let f of Object.keys(i)){let l=f[0],u=p[l];if(!u||f.length<2)continue;let g=f.slice(1),y=i[f];if(typeof y!="object"||y===null)continue;let w=i[u]||{};u in i||(i[u]=w),g in w||(w[g]=y),delete i[f];}}let o=W.safeParse(a);if(!o.success){for(let i of o.error.issues){let p=i.path.join("."),f=i.message;e.push(`Schema error at ${p||"/"}: ${f}`),r.push({message:f,path:p||"/",type:"schema"});}return {data:a,errors:e,detailedErrors:r,rawContent:s,isYamlValid:true}}return {data:o.data,errors:[],detailedErrors:[],rawContent:s,isYamlValid:true}}function L(n){return $.dump(n,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function H(){return L({version:"1.0.0",description:"Project purpose and context",context:["Add contextual notes for AI agents here"],features:{},components:{}})}function m(n){return n?Array.isArray(n)?n.map(e=>[e.id,e]):Object.entries(n):[]}function N(n){let e={description:"",context:[],rules:{},features:{},components:{},referencedItems:{},ruleConflicts:[]};if(!n||n.length===0)return e;n.forEach(({data:s})=>{let c=new Set(e.context);for(let i of s.context||[])c.has(i)||(e.context.push(i),c.add(i));if(s.rules)for(let[i,p]of Object.entries(s.rules))e.rules[i]!==void 0&&e.rules[i]!==p&&e.ruleConflicts.push(`Conflict on rule "${i}": existing value "${e.rules[i]}" overwritten with "${p}"`),e.rules[i]=p;let a=m(s.features);for(let[i,p]of a)e.features[i]=p;let o=m(s.components);for(let[i,p]of o)e.components[i]=p;});let r=n[n.length-1];return e.description=r.data.description||e.description,e.apiSpec=r.data.apiSpec||e.apiSpec,e}async function Z(n){let e=d.resolve(n);return (await glob("**/.purpose",{cwd:e,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})).sort((s,c)=>{let a=s.split(d.sep).length,o=c.split(d.sep).length;return a-o})}async function U(n){let e=await Z(n),r=[];for(let s of e){let{data:c,errors:a}=T(s);c&&(r.push({filePath:s,data:c}),a.length>0&&console.warn(`Warnings parsing ${s}:`,a));}return r}function J(n){let e=new Map;for(let{filePath:r,data:s}of n){let c=m(s.features);for(let[a,o]of c)e.set(a,{item:o,filePath:r});}return e}function Q(n){let e=new Map;for(let{filePath:r,data:s}of n){let c=m(s.components);for(let[a,o]of c)e.set(a,{item:o,filePath:r});}return e}function X(n){let e=new Map;for(let{filePath:r,data:s}of n)if(s.gates)for(let[c,a]of Object.entries(s.gates))e.set(c,{item:a,filePath:r});return e}function tt(n){let e=new Map;for(let{filePath:r,data:s}of n)if(s.states)for(let[c,a]of Object.entries(s.states))e.set(c,{item:a,filePath:r});return e}function et(n){let e=new Map;for(let{filePath:r,data:s}of n)if(s.flows)if(Array.isArray(s.flows))for(let c of s.flows)e.set(c.name,{item:{id:c.name,description:c.description,steps:c.steps},filePath:r});else for(let[c,a]of Object.entries(s.flows))e.set(c,{item:{id:c,description:a.description,gates:a.gates,signals:a.signals,components:a.components,steps:a.steps},filePath:r});return e}function ot(n){let e=new Map;for(let{filePath:r,data:s}of n)if(s.signals)for(let[c,a]of Object.entries(s.signals))e.set(c,{item:a,filePath:r});return e}function st(n){let e=new Map;for(let{filePath:r,data:s}of n)if(s.aspects)for(let[c,a]of Object.entries(s.aspects))e.set(c,{item:a,filePath:r});return e}function nt(n){let e=[],r=new Set;for(let{filePath:s,data:c}of n){let a=m(c.features);for(let[i,p]of a)S(`#${i}`,p,s,e,r);let o=m(c.components);for(let[i,p]of o)S(`#${i}`,p,s,e,r);}return e}function S(n,e,r,s,c){if(e.flows)for(let a of e.flows){let o=a.startsWith("$")?a:`$${a}`;c.has(o)||(c.add(o),s.push({symbol:o,type:"flow",sourceSymbol:n,filePath:r}));}if(e.gates)for(let a of e.gates){let o=a.startsWith("^")?a:`^${a}`;c.has(o)||(c.add(o),s.push({symbol:o,type:"gate",sourceSymbol:n,filePath:r}));}if(e.signals)for(let a of e.signals){let o=a.startsWith("!")?a:`!${a}`;c.has(o)||(c.add(o),s.push({symbol:o,type:"signal",sourceSymbol:n,filePath:r}));}if(e.states)for(let a of e.states){let o=a.startsWith("#")?a:a.startsWith("%")?`#${a.slice(1)}`:`#${a}`;c.has(o)||(c.add(o),s.push({symbol:o,type:"component",sourceSymbol:n,filePath:r}));}if(e.components)for(let a of e.components){let o=a.startsWith("#")?a:`#${a}`;c.has(o)||(c.add(o),s.push({symbol:o,type:"component",sourceSymbol:n,filePath:r}));}if(e.aspects)for(let a of e.aspects){let o=a.startsWith("~")?a:`~${a}`;c.has(o)||(c.add(o),s.push({symbol:o,type:"aspect",sourceSymbol:n,filePath:r}));}if(e.description){let a=_(e.description);for(let{symbol:o,type:i}of a)c.has(o)||(c.add(o),s.push({symbol:o,type:i,sourceSymbol:n,filePath:r}));}}var B=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function _(n){let e=[],r=/([$^!#~%])([a-zA-Z][a-zA-Z0-9._-]*)/g,s;for(;(s=r.exec(n))!==null;){let c=s[1],a=s[2],o,i;switch(c){case "#":i="component",o=`#${a}`;break;case "$":i="flow",o=`$${a}`;break;case "^":i="gate",o=`^${a}`;break;case "!":i="signal",o=`!${a}`;break;case "~":i="aspect",o=`~${a}`;break;case "%":i="component",o=`#${a}`;break;default:continue}B.has(o)||e.push({symbol:o,type:i});}return e}function h(n){return n?Array.isArray(n)?n.map(e=>[e.id,e]):Object.entries(n):[]}function b(n){return n?Array.isArray(n)?n.map(e=>e.id):Object.keys(n):[]}function rt(n,e){let r=[],s=e?`${e}: `:"",c=h(n.features);for(let[o,i]of c)x(o,i,"feature",s,r);let a=h(n.components);for(let[o,i]of a)x(o,i,"component",s,r);if(n.relationships){let o=new Set([...b(n.features),...b(n.components)]);for(let i of n.relationships){if(typeof i=="string"||!i||!i.from||!i.to)continue;let p=i.from.replace(/^[@#$%~^!?]/,"");!o.has(p)&&!i.from.includes(".")&&r.push({type:"warning",message:`${s}Relationship references unknown source: "${i.from}"`,path:"relationships"});let f=i.to.replace(/^[@#$%~^!?]/,"");!o.has(f)&&!i.to.includes(".")&&r.push({type:"warning",message:`${s}Relationship references unknown target: "${i.to}"`,path:"relationships"});}}if(n.flows){let o=new Set(b(n.components));if(Array.isArray(n.flows)){for(let i of n.flows)if(!(!i||typeof i!="object")&&(i.name||r.push({type:"error",message:`${s}Flow missing required "name" field`,path:"flows"}),i.steps&&Array.isArray(i.steps)))for(let p of i.steps){if(typeof p=="string"||!p||!p.component)continue;let f=p.component.replace(/^#/,"");o.has(f)||r.push({type:"warning",message:`${s}Flow "${i.name}" references unknown component: "${p.component}"`,path:`flows.${i.name}`});}}else for(let[i,p]of Object.entries(n.flows))if(!(!p||typeof p!="object")&&p.steps&&Array.isArray(p.steps))for(let f of p.steps){if(typeof f=="string"||!f||!f.component)continue;let l=f.component.replace(/^#/,"");o.has(l)||r.push({type:"warning",message:`${s}Flow "${i}" references unknown component: "${f.component}"`,path:`flows.${i}`});}}return {valid:r.filter(o=>o.type==="error").length===0,issues:r}}function x(n,e,r,s,c){let a=`${r}s.${n}`;if(/^[a-zA-Z][a-zA-Z0-9-]*$/.test(n)||c.push({type:"warning",message:`${s}${r} ID "${n}" should use alphanumeric characters and hyphens`,path:a}),(!e.description||e.description.trim()==="")&&c.push({type:"warning",message:`${s}${r} "${n}" has no description`,path:a}),e.endpoints)for(let o of e.endpoints)/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+\//.test(o)||c.push({type:"warning",message:`${s}Endpoint "${o}" in ${r} "${n}" may not be in standard format (e.g., "GET /api/users")`,path:`${a}.endpoints`});}function at(n){let e=[],r=new Set;for(let{data:s}of n){let c=h(s.components);for(let[o]of c)r.add(`#${o}`),r.add(o);let a=h(s.features);for(let[o]of a)r.add(`#${o}`),r.add(o);if(s.gates)for(let o of Object.keys(s.gates))r.add(`^${o}`),r.add(o);if(s.signals)for(let o of Object.keys(s.signals))r.add(`!${o}`),r.add(o);if(s.flows)if(Array.isArray(s.flows))for(let o of s.flows)o?.name&&(r.add(`$${o.name}`),r.add(o.name));else for(let o of Object.keys(s.flows))r.add(`$${o}`),r.add(o);if(s.aspects)for(let o of Object.keys(s.aspects))r.add(`~${o}`),r.add(o);if(s.states)for(let o of Object.keys(s.states))r.add(`#${o}`),r.add(o);}for(let{filePath:s,data:c}of n){let a=s?`${s}: `:"",o=[...h(c.components),...h(c.features)];for(let[i,p]of o){if(p.parent){let l=p.parent.replace(/^["']|["']$/g,""),u=l.replace(/^[#$^!~@%?&]/,"");!r.has(l)&&!r.has(u)&&e.push({type:"warning",message:`${a}Component "${i}" references parent "${l}" which is not defined in any .purpose file`,path:`components.${i}.parent`});}let f=[{field:"gates",refs:p.gates},{field:"signals",refs:p.signals},{field:"flows",refs:p.flows},{field:"components",refs:p.components},{field:"aspects",refs:p.aspects}];for(let{field:l,refs:u}of f)if(u)for(let g of u){let y=g.replace(/^[#$^!~@%?&]/,"");!r.has(g)&&!r.has(y)&&e.push({type:"warning",message:`${a}Symbol "${i}" references ${l} "${g}" which is not defined`,path:`components.${i}.${l}`});}}if(c.flows){if(Array.isArray(c.flows)){for(let i of c.flows)if(i?.steps)for(let p of i.steps){if(typeof p=="string"||!p?.component)continue;let f=p.component.replace(/^#/,"");!r.has(p.component)&&!r.has(f)&&e.push({type:"warning",message:`${a}Flow "${i.name}" step references "${p.component}" which is not defined`,path:`flows.${i.name}.steps`});}}else for(let[i,p]of Object.entries(c.flows))if(p?.steps)for(let f of p.steps){if(typeof f=="string"||!f?.component)continue;let l=f.component.replace(/^#/,"");!r.has(f.component)&&!r.has(l)&&e.push({type:"warning",message:`${a}Flow "${i}" step references "${f.component}" which is not defined`,path:`flows.${i}.steps`});}}}return {valid:e.filter(s=>s.type==="error").length===0,issues:e}}function it(n){if(n.valid&&n.issues.length===0)return "\u2705 Purpose file is valid";let e=[],r=n.issues.filter(c=>c.type==="error"),s=n.issues.filter(c=>c.type==="warning");if(r.length>0){e.push(`
3
+ \u274C ${r.length} error(s):`);for(let c of r)e.push(` \u2022 ${c.message}${c.path?` (${c.path})`:""}`);}if(s.length>0){e.push(`
4
+ \u26A0\uFE0F ${s.length} warning(s):`);for(let c of s)e.push(` \u2022 ${c.message}${c.path?` (${c.path})`:""}`);}return n.valid?e.push(`
5
+ \u2705 Purpose file is valid (with warnings)`):e.push(`
6
+ \u274C Purpose file is invalid`),e.join(`
7
+ `)}export{T as a,z as b,L as c,H as d,N as e,Z as f,U as g,J as h,Q as i,X as j,tt as k,et as l,ot as m,st as n,nt as o,rt as p,at as q,it as r};
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import {a,O,l as l$1,D,G,L,F,K,J,I,N}from'./chunk-W3VWORQZ.js';import {a as a$2,d as d$1}from'./chunk-Q527BPUF.js';import {a as a$4}from'./chunk-VOPJ47QY.js';import {b as b$2}from'./chunk-RGSFU2YW.js';import {m,q as q$1,k,n,o,l,i,j as j$1,g}from'./chunk-TMDPDIWA.js';import {f}from'./chunk-KLBH26PA.js';import {j,a as a$3,i as i$1,b as b$1,h as h$1,g as g$2,c,d as d$2}from'./chunk-GRZQIKST.js';import {d,g as g$1,e,h,j as j$2,f as f$1}from'./chunk-ACJWUOMA.js';import {b,a as a$1}from'./chunk-EK4ZRIFJ.js';import*as R from'fs';import*as A from'path';import*as q from'js-yaml';import {execSync}from'child_process';import*as $t from'os';b();b();var Lt=".paradigm/navigator.yaml";async function st(n){let e=A.join(n,Lt);if(!R.existsSync(e))return {config:null,configPath:null};try{let o=R.readFileSync(e,"utf8");return {config:q.load(o),configPath:e}}catch(o){return a$1.component("#navigator-loader").error("Error parsing navigator.yaml",{error:o}),{config:null,configPath:e}}}function rt(n,e,o){switch(e.intent){case "find":return Ht(n,e.target||"");case "explore":return Bt(n,e.target||"");case "context":return Mt(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Ht(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=Jt(n,e);s?(t.paths=s.paths,t.explanation=`Found ${e} in structure: ${s.paths.join(", ")}`):t.explanation=`No matches found for "${e}"`;}}return t.suggested_order=we(t.paths,n),t}function Bt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase();for(let[s,i]of Object.entries(n.structure))if(i&&(s.toLowerCase().includes(r)||r.includes(s.toLowerCase()))){t.paths.push(...i.paths);let a=Object.entries(n.symbols).filter(([c])=>c.startsWith(i.symbol)).slice(0,10);t.symbols.push(...a.map(([c])=>c));}for(let[s,i]of Object.entries(n.key_files))s.toLowerCase().includes(r)&&t.paths.push(...i);if(t.paths.length===0){let s=Object.entries(n.symbols).filter(([i,a])=>i.toLowerCase().includes(r)||a.toLowerCase().includes(r)).slice(0,10);t.paths=[...new Set(s.map(([,i])=>i))],t.symbols=s.map(([i])=>i);}return t.explanation=`Exploration paths for "${e}": ${t.paths.length} locations, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Mt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase(),s=Gt(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 Jt(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 Gt(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 qt(n){let e=A.resolve(n),o=R.readFileSync(e,"utf8"),t=q.load(o);if(!t||typeof t!="object")throw new Error(`Invalid workspace file: ${n}`);let r={version:String(t.version||"1.0"),name:String(t.name||"unnamed-workspace"),members:[]};if(Array.isArray(t.members)){for(let s of t.members)if(typeof s=="object"&&s!==null){let i=s;r.members.push({name:String(i.name||""),path:String(i.path||""),role:i.role,exports:Array.isArray(i.exports)?i.exports.map(String):void 0});}}return r}function at(n,e){let o=A.resolve(n),t=A.resolve(o,e);if(!R.existsSync(t))return a$1.component("#workspace-loader").warn("Workspace file not found",{workspacePath:t}),null;let r;try{r=qt(t);}catch(c){return a$1.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let s=A.dirname(t),i="";for(let c of r.members){let l=A.resolve(s,c.path);if(it(l)===it(o)){i=c.name;break}}if(!i)return a$1.component("#workspace-loader").warn("Current directory is not a member of workspace",{workspace:r.name}),null;let a=new Map;for(let c of r.members){if(c.name===i)continue;let l=A.resolve(s,c.path),d=A.join(l,".paradigm","scan-index.json");if(!R.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(R.readFileSync(d,"utf8")),u=Vt(p);c.exports&&c.exports.length>0&&(u=Ut(u,c.exports));let y=null,x=A.join(l,"portal.yaml");if(R.existsSync(x))try{let m=R.readFileSync(x,"utf8"),C=q.load(m);C&&(y=C);}catch{}a.set(c.name,{index:u,gateConfig:y});}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 Ut(n,e){let t=q$1(n).filter(r=>{let s=r.symbol;return e.some(i=>zt(i,s))});return Kt(t)}function zt(n,e){let o=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${o}$`,"i").test(e)}function xe(n,e){let o=[];for(let[t,r]of n.siblingIndices){let s=m(r.index,e);for(let i of s)o.push({project:t,symbol:`${t}/${i.symbol}`,type:i.type,description:i.description,filePath:i.filePath});}return o}function ct(n,e){let o=[],t=e.includes("/")?e.split("/").pop():e;for(let[r,s]of n.siblingIndices){let i=[],a=q$1(s.index);for(let c of a){let l=c.references||[],d=c.description||"",p=l.some(y=>y===t||y===e||y.endsWith(`/${t}`)),u=d.includes(t);(p||u)&&i.push({symbol:c.symbol,type:c.type,description:c.description});}i.length>0&&o.push({project:r,references:i});}return o}function it(n){return A.resolve(n).replace(/\/+$/,"")}function Vt(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 Kt(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 Qt={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function to(){return [Qt]}async function pt(n,e,o){if(n!=="paradigm_navigate")return {handled:false,text:""};let t={intent:e.intent||"find",target:e.target,task:e.task},r=await st(o.rootDir);if(r.config||(r={config:Yt(o),configPath:null}),false);if(t.intent==="context"&&!t.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((t.intent==="find"||t.intent==="explore")&&!t.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${t.intent} intent`,example:t.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let s=`navigate:${t.intent}:${t.target||""}:${t.task||""}`,i=await a.getOrCompute(s,()=>{let c=rt(r.config,t,o.rootDir),l={intent:t.intent,...t.target&&{target:t.target},...t.task&&{task:t.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(r.config?.auto_generated&&(l.auto_generated=true,l.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(l.note="No paths found.",l.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(l.tip=l.tip||"Many paths returned. Start with suggested_order for efficient exploration."),o.workspace){if(t.intent==="find"&&t.target&&c.paths.length===0){let 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=A.join(o.rootDir,".paradigm",".nav-called");R.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a$1}}function Yt(n){let e={},o={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},t=q$1(n.index),r=new Set;for(let a of t)if(a.filePath){e[a.symbol]=a.filePath,r.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":o.features.paths.includes(c)||o.features.paths.push(c);break;case "component":o.components.paths.includes(c)||o.components.paths.push(c);break;case "gate":o.gates.paths.includes(c)||o.gates.paths.push(c);break;case "flow":o.flows.paths.includes(c)||o.flows.paths.push(c);break}}let s=[],i=[];for(let a of n.aggregation.purposeFiles)s.push(a.filePath);return s.push(".paradigm/config.yaml"),n.gateConfig&&s.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:o,key_files:{config:s.slice(0,10),entry:i,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}function mt(n,e,o={}){let{maxResults:t=20}=o,r=[],s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=[`rg -n --no-heading "${s}" "${n}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${s}" "${n}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of i)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return r;let c=a.trim().split(`
3
+ `);for(let l of c.slice(0,t)){let d=l.match(/^(.+?):(\d+):(.*)$/);if(d){let[,p,u,y]=d,x=A.relative(n,p),m="unknown";x.includes(".purpose")||x.includes("portal.yaml")?m="purpose":y.includes("//")||y.includes("#")||y.includes("*")?m="comment":m="code",r.push({filePath:x,line:parseInt(u,10),content:y.trim().slice(0,200),context:m});}}return r}b();var Zt=30*1e3,ut=new Map;async function gt(n){let e=A.resolve(n),o=ut.get(e);if(o&&Date.now()-o.loadedAt<Zt)return o.index;let t=await en(e);return t&&ut.set(e,{index:t,loadedAt:Date.now()}),t}async function en(n){let e=A.join(n,".paradigm","flow-index.json");if(!R.existsSync(e))return null;try{let o=R.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 tn(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 yt(n,e){let o=tn(n,e),t=new Set;for(let i of o)i.validation?.command&&t.add(i.validation.command);let r="low",s=o.reduce((i,a)=>i+a.downstreamSteps.length,0);return o.length>3||s>10?r="high":(o.length>1||s>3)&&(r="medium"),{symbol:e,totalFlows:o.length,impactLevel:r,affectedFlows:o,validationCommands:Array.from(t),suggestion:o.length>0?`Changes to ${e} may affect ${o.length} flow(s). ${t.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function go(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["dependencies","impact","blast radius","what would break","dependents","affects"]}]}async function le(n$1,e,o$1){if(n$1!=="paradigm_ripple")return {handled:false,text:""};let{symbol:t,depth:r=3,includeWorkspace:s=false,response_format:i}=e,a=k(o$1.index,t);if(!a){let h=nn(o$1.rootDir,t);return O(h.length,n$1),{handled:true,text:h}}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 u(h,P){if(P>=c)return;let v=[];for(let w of h){if(d.has(w))continue;d.add(w);let j=n(o$1.index,w);for(let T of j)d.has(T.symbol)||v.push(T.symbol);}v.length>0&&(p.set(P+1,v),u(v,P+1));}u(l$2.map(h=>h.symbol),1);let y=new Set;for(let[,h]of p)for(let P of h)P!==t&&!l$2.find(v=>v.symbol===P)&&y.add(P);let x=o(o$1.index,t),m=l$2.length+y.size,C="low";m>10?C="high":m>3&&(C="medium");let N=await gt(o$1.rootDir),F=null;if(N){let h=yt(N,t);h.totalFlows>0&&(h.impactLevel==="high"&&C==="low"?C="medium":h.impactLevel==="high"&&(C="high"),F={totalFlows:h.totalFlows,affectedFlows:h.affectedFlows.map(P=>({flowId:P.flowId,impactLevel:P.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${P.stepAffected.position}, affects ${P.downstreamSteps.length} downstream steps`})),validationSuggestion:h.validationCommands.length>0?`Run: ${h.validationCommands[0]}`:void 0});}let $=new Set([t,...l$2.map(h=>h.symbol),...y]),I=[];try{let h=l(o$1.index,"gate");for(let P of h)$.has(P.symbol)&&I.push({gate:P.symbol,description:P.description});for(let P of l$2)P.type==="gate"&&!I.find(v=>v.gate===P.symbol)&&I.push({gate:P.symbol,description:P.description});}catch{}let _={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:C,analysis:{directlyAffected:l$2.map(h=>({symbol:h.symbol,type:h.type,description:h.description})),indirectlyAffected:Array.from(y),indirectByLevel:Object.fromEntries(p),dependsOn:x.map(h=>({symbol:h.symbol,type:h.type}))},summary:{directCount:l$2.length,indirectCount:y.size,totalAffected:m,dependsOnCount:x.length,levelsAnalyzed:c},recommendation:on(C)};F&&(_.affectedFlows=F),I.length>0&&(_.affectedGates=I),_.suggestedReviewScope=sn(C,l$2.length,y.size,I.length,F?.totalFlows??0);try{let h=await l$1(o$1.rootDir,t);h.length>0&&(_.personas_affected=h,h.length>2&&C==="low"&&(_.impact="medium"));}catch{}try{let h=D(o$1.rootDir,t);h.length>0&&(_.university_content_affected=h.map(P=>({id:P.id,title:P.title,type:P.type,stale:P.stale})));}catch{}if(s&&o$1.workspace){let h=ct(o$1.workspace,t);if(h.length>0){_.workspaceImpact={siblings:h.map(v=>({project:v.project,references:v.references.map(w=>({symbol:w.symbol,type:w.type,description:w.description}))}))};let P=h.reduce((v,w)=>v+w.references.length,0);P>0&&C==="low"&&(_.impact="medium"),P>5&&(_.impact="high");}}let O$1=i==="concise"?{symbol:_.symbol,impact:_.impact,summary:_.summary}:_,E=JSON.stringify(O$1,null,2);return O(E.length,n$1),{handled:true,text:E}}function nn(n,e){let o=mt(n,e,{maxResults:20});if(o.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let t=[...new Set(o.map(i=>i.filePath))],r={};for(let i of o)r[i.context]=(r[i.context]||0)+1;let s="low";return t.length>10||o.length>20?s="high":(t.length>3||o.length>5)&&(s="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:s,analysis:{filesAffected:t.slice(0,10),totalFilesAffected:t.length,totalReferences:o.length,contextBreakdown:r,sampleReferences:o.slice(0,5).map(i=>({file:i.filePath,line:i.line,preview:i.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function on(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 sn(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 rn=30*1e3,ve=new Map,bt=".paradigm/wisdom";async function wt(n){let e=A.resolve(n),o=ve.get(e);if(o&&Date.now()-o.loadedAt<rn)return o.context;let t=await an(e);return ve.set(e,{context:t,loadedAt:Date.now()}),t}async function an(n){let e$1=A.join(n,bt),o=R.existsSync(e$1),[t,r,s,i]=o?await Promise.all([cn(e$1),ln(e$1),dn(e$1),pn(e$1)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e(),l=f$1();}catch{}let d$1=new Set(r.map(m=>m.id)),p=r.map(m=>({...m,scope:"project"}));for(let m of a)d$1.has(m.id)||p.push({...m,scope:"global"});let u=new Set(i.map(m=>m.id)),y=i.map(m=>({...m,scope:"project"}));for(let m of c)u.has(m.id)||y.push({...m,scope:"global"});let x=t;if(l&&!t)x=l;else if(l&&t){let m={...t.by_symbol};if(l.by_symbol)for(let[C,N]of Object.entries(l.by_symbol))m[C]||(m[C]=N);x={...t,by_symbol:m,global:{...l.global,...t.global}};}return {preferences:x,antipatterns:p,decisions:y,expertise:s}}function V(n){let e=A.resolve(n);ve.delete(e);}async function cn(n){let e=A.join(n,"preferences.yaml");if(!R.existsSync(e))return null;try{let o=R.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#wisdom-loader").error("Error parsing preferences.yaml",{error:o}),null}}async function ln(n){let e=A.join(n,"antipatterns.yaml");if(!R.existsSync(e))return [];try{let o=R.readFileSync(e,"utf8");return q.load(o).antipatterns||[]}catch(o){return a$1.component("#wisdom-loader").error("Error parsing antipatterns.yaml",{error:o}),[]}}async function dn(n){let e=A.join(n,"expertise.yaml");if(!R.existsSync(e))return null;try{let o=R.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#wisdom-loader").error("Error parsing expertise.yaml",{error:o}),null}}var ht=new Set;async function pn(n){let e=A.join(n,"decisions");if(!R.existsSync(e))return [];let o=[];try{let t=R.readdirSync(e);t.some(s=>s.endsWith(".yaml")||s.endsWith(".yml"))&&!ht.has(e)&&(ht.add(e),a$1.component("#wisdom-loader").warn("wisdom-decisions found; run `paradigm migrate decisions` in v6.0. In v5.39.0 wisdom-decisions are still read but will be migrated to TD-streams in v6.0."));for(let s of t){if(!s.endsWith(".yaml")&&!s.endsWith(".yml"))continue;let i=A.join(e,s);try{let a=R.readFileSync(i,"utf8"),c=q.load(a);o.push(c);}catch(a){a$1.component("#wisdom-loader").error(`Error parsing ${s}`,{error:a});}}}catch(t){a$1.component("#wisdom-loader").error("Error reading decisions directory",{error:t});}return o.sort((t,r)=>t.id.localeCompare(r.id)),o}function St(n,e){return e.map(o=>fn(n,o))}function fn(n,e){let o=n.preferences?.by_symbol?.[e]||null,t=n.antipatterns.filter(i=>i.symbols.some(a=>a===e||de(e,a))),r=n.decisions.filter(i=>i.symbols.some(a=>a===e||de(e,a))),s=n.expertise?.experts.filter(i=>i.symbols?.some(a=>a===e||de(e,a)))||[];return {symbol:e,preferences:o,antipatterns:t,decisions:r,experts:s}}function xt(n,e){return n.expertise?n.expertise.experts.filter(o=>!!(e.symbol&&o.symbols&&o.symbols.some(t=>t===e.symbol||de(e.symbol,t))||e.area&&o.areas&&o.areas.some(t=>t.toLowerCase().includes(e.area.toLowerCase())))):[]}function de(n,e){if(e.endsWith("*")){let o=e.slice(0,-1);return n.startsWith(o)}return n===e}async function vt(n,e){let o=A.join(n,bt),t=A.join(o,"antipatterns.yaml");R.existsSync(o)||R.mkdirSync(o,{recursive:true});let r={version:"1.0",antipatterns:[]};if(R.existsSync(t))try{let s=R.readFileSync(t,"utf8"),i=q.load(s);i&&typeof i=="object"&&(r={version:i.version||"1.0",antipatterns:Array.isArray(i.antipatterns)?i.antipatterns:[]});}catch{}r.antipatterns.push({...e,added:new Date().toISOString()}),R.writeFileSync(t,q.dump(r,{lineWidth:-1})),V(n);}b();var kt=".paradigm/history";async function _t(n){let e=A.join(n,kt);if(!R.existsSync(e))return {index:null,validation:null};let[o,t]=await Promise.all([mn(e),un(e)]);return {index:o,validation:t}}async function mn(n){let e=A.join(n,"index.yaml");if(!R.existsSync(e))return null;try{let o=R.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#history-loader").error("Error parsing index.yaml",{error:o.message}),null}}async function un(n){let e=A.join(n,"validation.yaml");if(!R.existsSync(e))return null;try{let o=R.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#history-loader").error("Error parsing validation.yaml",{error:o.message}),null}}function xo(n,e){return e.map(o=>gn(n,o))}function gn(n,e){let o=n.index?.by_symbol?.[e]||null,t=[];if(n.index?.co_changes){for(let s of n.index.co_changes)if(s.symbols.includes(e))for(let i of s.symbols)i!==e&&!t.includes(i)&&t.push(i);}let r=n.validation?.by_symbol?.[e]||null;return {symbol:e,summary:o,recent:o?.recent||[],co_changes:t,validation:r}}function vo(n,e){let o=[],t=[];if(!n.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let i of e){let a=n.index.by_symbol?.[i];a&&(a.fragility==="high"||a.fragility==="critical")&&o.push({symbol:i,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=n.index.fragile_symbols?.find(l=>l.symbol===i);c&&!o.find(l=>l.symbol===i)&&o.push(c);}for(let i of e){let a=n.index.co_changes?.filter(c=>c.symbols.includes(i));if(a?.length)for(let c of a){let l=c.symbols.filter(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 yn(n,e){let o=A.join(n,kt),t=A.join(o,"log.jsonl");R.existsSync(o)||R.mkdirSync(o,{recursive:true});let r=hn(t),s=new Date().toISOString(),i={id:r,ts:s,...e},a=JSON.stringify(i)+`
4
+ `;return R.appendFileSync(t,a),r}async function ko(n,e,o,t){return yn(n,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:o,tests:t})}function hn(n){let e=1;return R.existsSync(n)&&(e=R.readFileSync(n,"utf8").split(`
5
+ `).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}async function Ao(n){let e=A.resolve(n),o=await i(e),t=j$1(o),r=null,s=A.join(e,"portal.yaml");if(R.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=A.basename(e),a=A.join(e,".premise");if(R.existsSync(a))try{let p=R.readFileSync(a,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);p&&(i$1=p[1].trim());}catch{}let c=null,l=A.join(e,".paradigm","config.yaml");if(R.existsSync(l))try{let d=R.readFileSync(l,"utf8"),p=q.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=at(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 wt(n.rootDir)),n.wisdom}async function Oo(n){return n.history||(n.history=await _t(n.rootDir)),n.history}j();b();var Pt=false;function Jo(){return [{name:"paradigm_wisdom_context",description:"Get team wisdom (preferences, antipatterns, decisions) for symbols before implementing. Call this before making changes to understand team patterns. Returns preferences, antipatterns, and decisions relevant to the specified symbols. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get wisdom for (e.g., ["@checkout", "#payment-form"])'},include_global:{type:"boolean",description:"Include global preferences (default: true)"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_wisdom_record",description:"Record a new team learning: antipattern (what not to do) or decision (architectural choice). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to record"},id:{type:"string",description:'Unique ID (for antipattern: e.g., "api-001", for decision: e.g., "001")'},symbols:{type:"array",items:{type:"string"},description:"Related symbols"},description:{type:"string",description:"What not to do (antipattern) or the decision made (decision)"},reason:{type:"string",description:"Why this is an antipattern / context for decision"},alternative:{type:"string",description:"What to do instead (for antipatterns)"},title:{type:"string",description:"Decision title (for decisions)"},status:{type:"string",enum:["proposed","accepted","deprecated","superseded"],description:"Decision status (for decisions)"},rationale:{type:"object",properties:{factors:{type:"array",items:{type:"string"}},conclusion:{type:"string"}},description:"Decision rationale (for decisions)"},consequences:{type:"object",properties:{positive:{type:"array",items:{type:"string"}},negative:{type:"array",items:{type:"string"}},mitigations:{type:"array",items:{type:"string"}}},description:"Expected consequences (for decisions)"},scope:{type:"string",enum:["project","global"],description:'Where to store: "project" (default) writes to .paradigm/wisdom/, "global" writes to ~/.paradigm/wisdom/'}},required:["type","id","symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]}},{name:"paradigm_wisdom_expert",description:"Find human experts who know about specific symbols or areas. Returns names and contact info for relevant experts. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to find experts for (e.g., "@checkout")'},area:{type:"string",description:'General area to find experts for (e.g., "payments", "auth")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Dt(n,e$1,o){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:r=true}=e$1,s=await fe(o),i=St(s,t),a={symbols:t,wisdom:i.map(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 u of t){let y=await a$3(o.rootDir,{symbol:u,hasAssessment:!0,limit:100});if(y.length===0)continue;let x={correct:0,partial:0,incorrect:0},m=0,C=0;for(let F of y){let $=F.assessment.verdict;x[$]++,F.confidence!=null&&(m+=F.confidence,C++);}d[u]={total:y.length,...x,avgConfidence:C>0?Math.round(m/C*1e3)/1e3:null};let N=(x.correct+x.partial*.5)/y.length;N<.6&&y.length>=3&&p.push(`Low historical accuracy for ${u}: ${Math.round(N*100)}% across ${y.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:u,scope:y="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 y==="global"?g$1(x):await vt(o.rootDir,x),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,scope:y,message:`Antipattern recorded to ${y} scope`})}}if(t==="decision"){if(!l||!i||!p||!u)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};if(Pt||(Pt=true,a$1.component("#wisdom").warn('paradigm_wisdom_record({type:"decision"}) is deprecated. Use paradigm_decision_record instead.',{deprecation:"v6.0",canonical_tool:"paradigm_decision_record"})),y==="global"){let C={id:r,title:l,status:d||"proposed",date:new Date().toISOString().split("T")[0],symbols:s,context:a||"",decision:i,rationale:p,consequences:u};return h(C),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,scope:"global",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record for project-scoped decisions.',message:"Decision recorded to global scope"})}}let x=a$2(o.rootDir,{title:l,decision:i,rationale:{factors: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:u,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),m=d$1(o.rootDir,x.id);return V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:x.id,legacy_id:r,scope:"project",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record going forward.',message:`Decision recorded (routed to decisions stream as ${x.id})`,...m?{companion_lore_id:m}:{}})}}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=A.basename(o.rootDir);if(t==="antipattern"){let a=s.antipatterns.find(l=>l.id===r);return a?d().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Antipattern "${r}" already exists in global scope`})}:(g$1({...a,learned_from:`promoted from ${i}`}),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,promoted_from:i,message:`Antipattern "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${r}" not found in project`})}}if(t==="decision"){let a=s.decisions.find(l=>l.id===r);return a?e().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Decision "${r}" already exists in global scope`})}:(h(a),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,promoted_from:i,message:`Decision "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${r}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_expert":{let{symbol:t,area:r}=e$1;if(!t&&!r)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let s=await fe(o),i=xt(s,{symbol:t,area:r});return {handled:true,text:JSON.stringify({query:{symbol:t,area:r},count:i.length,experts:i.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:i.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function Uo(){return [{name:"paradigm_protocol_search",description:"Search for protocols matching a task description. Call BEFORE exploring the codebase \u2014 if a matching protocol exists, follow its steps instead of discovering the pattern from scratch. Returns top matches with steps, exemplar, and freshness info. ~200 tokens.",inputSchema:{type:"object",properties:{task:{type:"string",description:'Task description to search for (e.g., "add a new page", "add API route")'},limit:{type:"number",description:"Maximum results (default: 3)"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_get",description:"Get a specific protocol by ID with full details and freshness check. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID (e.g., "P-add-view")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_record",description:"Record a new protocol after completing repeatable work. Captures the steps you followed so future agents can skip exploration. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Protocol name (e.g., "Add a new view")'},description:{type:"string",description:"What this protocol accomplishes"},trigger:{type:"array",items:{type:"string"},description:'Phrases that should match this protocol (e.g., ["add view", "new page"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g., ["ui", "frontend"])'},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols involved (e.g., ["#logs-view"])'},exemplar:{type:"string",description:'Canonical file to study for this pattern (e.g., "ui/src/views/LogsView.tsx")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"],description:"Step action type"},target:{type:"string",description:"File path (supports {Name}/{name} placeholders)"},template_from:{type:"string",description:"File to use as template (for create actions)"},reference:{type:"string",description:"Where in the file to make changes (for modify actions)"},command:{type:"string",description:"Command to execute (for run actions)"},notes:{type:"string",description:"Additional guidance for this step"}},required:["action"]},description:"Ordered steps to follow"},recorded_from:{type:"string",description:'Lore entry ID this protocol was learned from (e.g., "L-2026-03-01-001")'}},required:["name","description","trigger","tags","steps"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_update",description:"Update an existing protocol. Use refresh:true after successfully following a protocol to bump last_verified. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID to update (e.g., "P-add-view")'},refresh:{type:"boolean",description:"Set true to bump last_verified to now (use after successfully following the protocol)"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},trigger:{type:"array",items:{type:"string"},description:"Updated trigger phrases"},tags:{type:"array",items:{type:"string"},description:"Updated tags"},symbols:{type:"array",items:{type:"string"},description:"Updated symbols"},exemplar:{type:"string",description:"Updated exemplar path"},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"]},target:{type:"string"},template_from:{type:"string"},reference:{type:"string"},command:{type:"string"},notes:{type:"string"}},required:["action"]},description:"Updated steps"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_validate",description:"Validate protocol references \u2014 check that referenced files exist, exemplars haven't drifted. Validates all protocols if no ID given. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Protocol ID to validate (omit to validate all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Rt(n,e,o){switch(n){case "paradigm_protocol_search":{let t=e.task,r=e.limit||3,s=await I(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(bn)}))},null,2)}}case "paradigm_protocol_get":{let t=e.id,r=await G(o.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let s=L(o.rootDir,r);return {handled:true,text:JSON.stringify({...r,freshness:{status:s.status,issues:s.issues}},null,2)}}case "paradigm_protocol_record":{let t=e.steps||[],r=await J(o.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:t,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:r,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let t=e.id,r=e.refresh,s={};e.name!==void 0&&(s.name=e.name),e.description!==void 0&&(s.description=e.description),e.trigger!==void 0&&(s.trigger=e.trigger),e.tags!==void 0&&(s.tags=e.tags),e.symbols!==void 0&&(s.symbols=e.symbols),e.exemplar!==void 0&&(s.exemplar=e.exemplar),e.steps!==void 0&&(s.steps=e.steps);let i=await K(o.rootDir,t,s,r===true);return {handled:true,text:JSON.stringify({success:i,id:t,refreshed:r===true,message:i?r?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${t}`})}}case "paradigm_protocol_validate":{let t=e.id;if(t){let a=await G(o.rootDir,t);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let c=L(o.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let s=(await F(o.rootDir)).map(a=>{let c=L(o.rootDir,a);return {id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified}}),i={total:s.length,current:s.filter(a=>a.status==="current").length,stale:s.filter(a=>a.status==="stale").length,broken:s.filter(a=>a.status==="broken").length};return {handled:true,text:JSON.stringify({protocols:s,health:i},null,2)}}default:return {handled:false,text:""}}}function bn(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=A.join(n,".paradigm","sentinel","sentinel.db");ee=new f(e),await ee.ensureReady(),ke=true;}return ee}async function wn(n,e){return (await _e(n)).recordPracticeEvent(e)}async function Ko(n,e){return (await _e(n)).getPracticeEvents(e)}async function Ce(n,e){return (await _e(n)).getComplianceRate(e)}async function It(n,e){let o=["discovery","verification","testing","documentation","collaboration","security"],t=[];for(let r of o){let s=await Ce(n,{...e,habitCategory:r});s.total>0&&t.push({category:r,...s});}return t}async function Qo(n,e,o){let t=[];for(let r of e){let s=await wn(n,{habitId:r.habitId,habitCategory:r.habitCategory,result:r.result,engineer:o.engineer,sessionId:o.sessionId,loreEntryId:o.loreEntryId,taskDescription:o.taskDescription,symbolsTouched:o.symbolsTouched,filesModified:o.filesModified,notes:r.notes});t.push(s);}return t}b();function At(n){return {handled:true,text:JSON.stringify({error:n},null,2)}}var me={code:"lore_type_decision_removed",message:"lore type 'decision' was removed in v6.0. Use paradigm_decision_record instead. The decision will be stored in .paradigm/decisions/ and a companion lore insight entry (type:'insight' with references.decision_id) will be written automatically so the timeline stays complete. For narrative-only references, use paradigm_lore_record({type:'insight', references:{decision_id}}).",successor_tool:"paradigm_decision_record",doc:"docs/private/plans/v6.0-decisions-locked.md",removed_in:"6.0.0"};function Ot(){let n=process.env.PARADIGM_AUTHOR;if(n)return Pe(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Pe(e)}catch{}try{let e=$t.userInfo().username;if(e)return Pe(e)}catch{}return "unknown"}function Pe(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function is(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, milestone, retro, insight, etc.). Call after completing significant work. Returns the created entry ID and file path. For decisions, use paradigm_decision_record (a companion lore insight is auto-written). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function je(n,e,o){switch(n){case "paradigm_lore_search":{let t={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},r=await a$3(o.rootDir,t);return {handled:true,text:JSON.stringify({count:r.length,filter:Object.fromEntries(Object.entries(t).filter(([,s])=>s!==void 0)),entries:r.map(Nt)},null,2)}}case "paradigm_lore_record":{let{type:t,title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:u,duration_minutes:y,decisions:x,errors_encountered:m,learnings:C,verification:N$1,tags:F,meta:$,body:I,linked_lore:_,linked_tasks:O,linked_commits:E,confidence:h}=e;if(t==="decision")return a$1.component("#lore").warn("rejected paradigm_lore_record({type:'decision'}) \u2014 removed in v6.0",{removed_in:me.removed_in,successor_tool:me.successor_tool}),At(me);let P;try{let S=new Date(Date.now()-2592e6).toISOString(),b=await Ce(o.rootDir,{dateFrom:S});if(b.total>0){let f=(await It(o.rootDir,{dateFrom:S})).filter(k=>k.rate<60).map(k=>k.category);P={rate:b.rate,followed:b.followed,skipped:b.skipped,partial:b.partial,weakAreas:f.length>0?f:void 0};}}catch{}let v={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:y,author:Ot(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:u,decisions:x,errors_encountered:m,learnings:C,verification:N$1,tags:F,meta:$||void 0,habit_compliance:P,body:I,linked_lore:_,linked_tasks:O,linked_commits:E,confidence:h!=null&&h>=0&&h<=1?h:void 0},w=await d$2(o.rootDir,v);j$2().setLastLoreEntryId(w);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:h!=null&&h>=0&&h<=1?h:void 0});}}catch{}let j=null;try{c&&c.length>=2&&(j=N(o.rootDir,c,l||[]));}catch{}let T;if(e.stream){let S=e.stream,b=S==="auto"?xn(e):S;try{if(b==="work-log"){let{recordWorkLog:g}=await import('./work-log-loader-DL5GZ2BQ.js');g(o.rootDir,{agent:v.agent?.model||"unknown",summary:v.summary,outcome:v.verification?.status==="pass"?"pass":v.verification?.status==="fail"?"fail":"partial",files_modified:v.files_modified,symbols_touched:v.symbols_touched,commit:v.commit,linked_lore:v.id||w}),T="work-log";}else if(b==="journal"&&v.learnings?.length){let{recordJournalEntry:g}=await import('./journal-loader-CNNA4EAU.js');for(let f of v.learnings)g(v.agent?.model||"unknown",{trigger:"self_reflection",insight:f,project:o.projectName||"unknown",transferable:!1,linked_work_log:v.id||w});T="journal";}else if(b==="decision"&&v.decisions?.length){let{recordDecision:g}=await import('./decision-loader-HELL2AMX.js');for(let f of v.decisions)g(o.rootDir,{title:f.decision.slice(0,100),decision:f.decision,rationale:f.rationale,participants:[{id:`agent/${v.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:v.symbols_touched,status:"active",linked_lore:v.id||w});T="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:w,type:t,title:r,message:"Lore entry recorded successfully",...T?{stream:T}:{},...j?{protocol_suggestion:j}:{}})}}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(Nt),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:Ot(),assessed_at:new Date().toISOString(),notes:s},c=await h$1(o.rootDir,t,a);try{let u=process.env.PARADIGM_AGENT_ID;if(u&&c&&i.symbols_touched?.length){let{updateExpertiseFromAssessment:y}=await import('./agent-loader-W3RQJVW7.js');y(o.rootDir,u,{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(I=>I.confidence!=null),i=r.length,a=s.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,p=0;for(let I of r){let _=I.assessment.verdict;c[_]++;let O=_==="correct"?1:_==="partial"?.5:0;l+=O,I.confidence!=null&&(d+=I.confidence,p+=Math.abs(O-I.confidence));}let u=i>0?l/i:0,y=a>0?d/a:null,x=a>0?l/i-d/a:null,m=a>0?1-p/a:null,C=e.groupBy,N;if(C&&i>0){let I=new Map;for(let _ of r){let O=[];C==="symbol"?O=_.symbols_touched||[]:C==="tag"?O=_.tags||[]:C==="type"&&(O=[_.type||"agent-session"]);for(let E of O)I.has(E)||I.set(E,[]),I.get(E).push(_);}N=Array.from(I.entries()).map(([_,O])=>{let E=O.filter(j=>j.confidence!=null),h={correct:0,partial:0,incorrect:0},P=0,v=0,w=0;for(let j of O){let T=j.assessment.verdict;h[T]++;let S=T==="correct"?1:T==="partial"?.5:0;P+=S,j.confidence!=null&&(v+=j.confidence,w+=Math.abs(S-j.confidence));}return {key:_,total:O.length,accuracyRate:P/O.length,avgConfidence:E.length>0?v/E.length:null,calibrationScore:E.length>0?1-w/E.length:null,verdictBreakdown:h}}).sort((_,O)=>O.total-_.total);}let F=[],$=i<5?`Low sample size (N=${i}). Stats may not be representative.`:i<15?`Moderate sample (N=${i}). Trends are directional, not conclusive.`:null;return $&&F.push($),m!=null&&(m>=.9?F.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):m>=.7?F.push("Good calibration \u2014 some room for improvement in confidence estimates."):m>=.5?F.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):F.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),x!=null&&(x>.15?F.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):x<-0.15&&F.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>i*.3&&i>=5&&F.push(`High error rate: ${c.incorrect}/${i} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:i,totalWithConfidence:a,accuracyRate:Math.round(u*1e3)/1e3,avgConfidence:y!=null?Math.round(y*1e3)/1e3:null,avgDelta:x!=null?Math.round(x*1e3)/1e3:null,calibrationScore:m!=null?Math.round(m*1e3)/1e3:null,verdictBreakdown:c,...N?{groups:N}:{},insights:F},null,2)}}case "paradigm_lore_delete":{let t=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let s=await i$1(o.rootDir,t);return {handled:true,text:JSON.stringify({success:s,id:t,message:s?"Lore entry deleted":`Lore entry not found: ${t}`})}}default:return {handled:false,text:""}}}function xn(n){return n.task_ref||n.files_modified||n.commit?"work-log":n.learnings||n.confidence!==void 0?"journal":n.decisions?.some(o=>o.rationale)?"decision":"work-log"}function Nt(n){return {id:n.id,type:n.type,title:n.title,summary:n.summary,author:n.author,agent:n.agent,timestamp:n.timestamp,duration_minutes:n.duration_minutes,symbols_touched:n.symbols_touched,verification:n.verification?.status,review:n.review?{completeness:n.review.completeness,quality:n.review.quality}:null,confidence:n.confidence??null,assessment:n.assessment?n.assessment.verdict:null,assessment_delta:n.assessment_delta??null,tags:n.tags}}function Ss(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_captain_board",description:"Cid's owned run-DAG board (#captain-board). action='read' (default, read-only) assembles the live orchestration DAG \u2014 each run's epic + ordered stage-children with status/claimant/dependsOn, plus ripple-ranked unclaimed open tasks and a summary. action='claim' writes a task's claimant (status stays open; human/peer claims override an archetype proposal). action='advance' records a blocked_on reason without changing status (orchestration owns in-progress/done). ~300 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["read","claim","advance"],description:"Board action. Default 'read'."},taskId:{type:"string",description:"Target task id (required for claim/advance)."},claimant:{type:"object",description:"For claim: the new owner { kind: 'archetype'|'human'|'peer', ref }.",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},blockedOn:{type:"string",description:"For advance: the blocking reason recorded on the task."}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function xs(n,e,o){return n==="paradigm_captain_brief"?vn(e,o):n==="paradigm_captain_debrief"?kn(e,o):n==="paradigm_captain_board"?jn(e,o):{handled:false,text:""}}async function vn(n,e){let o=n.taskDescription,t=n.symbols||[],r=n.depth||"standard",s=A.join(e.rootDir,".paradigm"),i=A.join(s,".cid-session"),a=A.join(s,".cid-briefed");try{R.existsSync(a)&&R.unlinkSync(a);let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r};R.mkdirSync(s,{recursive:!0}),R.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let c=Tn(o),l=[],d=new Set;for(let S of t)if(!d.has(S)){d.add(S);let b=Tt(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 f of g)if(!d.has(f.symbol)){d.add(f.symbol);let k=Ln(f.type);l.push({id:f.symbol,type:k,description:f.description||"",file:f.file}),p.push(f.symbol);}}}catch{}let u={directories:[],files:[]};try{let S=await pt("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 f=typeof g=="string"?g:g.path||g.file||"";f&&u.files.push(f);}if(b.directories)for(let g of b.directories){let f=typeof g=="string"?g:g.path||g.directory||"";f&&u.directories.push(f);}if(b.symbols)for(let g of b.symbols){let f=typeof g=="string"?g:g.id;f&&!d.has(f)&&(d.add(f),l.push({id:f,type:Tt(f),description:typeof g=="object"&&g.description||""}));}}}catch{}let y=new Set(u.directories);for(let S of u.files){let b=A.dirname(S);b&&b!=="."&&y.add(b);}let x=l.slice(0,r==="deep"?5:3),m$1={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 f of g.analysis.directlyAffected||[]){let k=f.symbol||f;k&&!m$1.affectedSymbols.includes(k)&&m$1.affectedSymbols.push(k);}for(let f of g.analysis.indirectlyAffected||[])f&&!m$1.affectedSymbols.includes(f)&&m$1.affectedSymbols.push(f);}if(g.affectedFlows?.affectedFlows)for(let f of g.affectedFlows.affectedFlows){let k=f.flowId||f;k&&!m$1.affectedFlows.includes(k)&&m$1.affectedFlows.push(k);}if(g.affectedGates)for(let f of g.affectedGates){let k=f.gate||f;k&&!m$1.affectedGates.includes(k)&&m$1.affectedGates.push(k);}g.impact==="high"&&(m$1.fragileSymbols.includes(S.id)||m$1.fragileSymbols.push(S.id));}}catch{}let C=[],N=Wn(o);if(N.length>0)try{let{handleGatesForRoute:S}=await import('./tools-GDWT74O6.js').catch(()=>({handleGatesForRoute:null})),b=A.join(e.rootDir,"portal.yaml");if(R.existsSync(b)){let g=R.readFileSync(b,"utf8");for(let f of N){let k=g.includes(f);C.push({route:f,gate:"^authenticated",declared:k});}}else for(let g of N)C.push({route:g,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let F=[];if(r!=="quick"&&l.length>0)try{let S=l.slice(0,5).map(g=>g.id),b=await Dt("paradigm_wisdom_context",{symbols:S,include_global:!0},e);if(b.handled){let g=JSON.parse(b.text);if(g.antipatterns)for(let f of g.antipatterns.slice(0,3)){let k=f.pattern||f.description||f.text||String(f);k&&!F.includes(k)&&F.push(k);}if(g.wisdom?.antipatterns)for(let f of g.wisdom.antipatterns.slice(0,3)){let k=f.pattern||f.description||String(f);k&&!F.includes(k)&&F.push(k);}}}catch{}let $={matched:false};try{let S=await Rt("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 f=g[0];$={matched:!0,id:f.id,name:f.name||f.title,steps:(f.steps||[]).slice(0,5).map(k=>typeof k=="string"?k:k.description||String(k))};}}}catch{}let I=[];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 k=JSON.parse(g.text).entries||[];for(let M of k.slice(0,3))I.push({id:M.id,summary:(M.summary||M.title||"").slice(0,100),relevance:S?`Related to ${S}`:"Recent project history"});}}catch{}let _=Array.from(y),O$1=0;for(let S of _){let b=A.join(e.rootDir,S,".purpose");if(R.existsSync(b))try{R.readFileSync(b,"utf8").trim().length>50&&O$1++;}catch{}}let E=_.length>0?O$1/_.length:.5,h=Hn(E),P=Bn(E,h,_.length),v=m$1.affectedSymbols.length+u.files.length,w=v>20?"large":v>8?"medium":v>2?"small":"tiny",j={territory:{directories:_.slice(0,10),files:u.files.slice(0,10),estimatedScope:w},symbols:l.slice(0,10),blastRadius:m$1,gates:C,protocol:$,warnings:F,coverage:{score:E,label:h,note:P},loreRefs:I,archMap:b$2(e.rootDir),renderedBrief:""};j.renderedBrief=Mn(j);try{let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r,coverageScore:E};R.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let T=JSON.stringify(j,null,2);return O(T.length,"paradigm_captain_brief"),{handled:true,text:T}}async function kn(n,e){let o=n.orchestrationId,t=n.sessionSummary,r=n.touchedFiles||[],s=n.newSymbols||[],i=n.notes,a=A.join(e.rootDir,".paradigm"),c=A.join(a,".cid-briefed"),l=A.join(a,".pending-review"),d=new Set;for(let w of r){let j=A.dirname(w);j&&j!=="."&&d.add(j);}let p=0,u=d.size;for(let w of d){let j=A.join(e.rootDir,w,".purpose");if(R.existsSync(j))try{R.readFileSync(j,"utf8").trim().length>50&&p++;}catch{}}let y=u>0?p/u:1,x=[],m=[];for(let w of d){let j=A.join(e.rootDir,w,".purpose"),T=A.join(e.rootDir,w),S=false;if(R.existsSync(j))try{S=R.readFileSync(j,"utf8").trim().length>50;}catch{}if(S){if(r.some(g=>A.dirname(g)===w&&s.length>0)){m.push(w);try{let g=JSON.stringify({path:w,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${o}: ${s.join(", ")}`,timestamp:new Date().toISOString()});R.appendFileSync(l,g+`
6
+ `,"utf8");}catch{}}}else try{if(!R.existsSync(T))continue;let b=A.basename(w),g=Jn(b,w,r);R.writeFileSync(j,g,"utf8"),x.push(w),m.push(w);try{let f=JSON.stringify({path:w,reason:"captain-debrief",priority:"high",context:`Touched during orchestration ${o}. Files: ${r.filter(k=>A.dirname(k)===w).join(", ")}`,timestamp:new Date().toISOString()});R.appendFileSync(l,f+`
7
+ `,"utf8");}catch{}}catch{}}let C=0;for(let w of d){let j=A.join(e.rootDir,w,".purpose");if(R.existsSync(j))try{R.readFileSync(j,"utf8").trim().length>50&&C++;}catch{}}let N=u>0?C/u:1,F="";try{let w=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:y,after:N},coverageAdded:x,...i?{notes:i}:{}}},e);if(w.handled){let j=JSON.parse(w.text);F=j.id||j.entry?.id||"";}}catch{}let $={ranThisSession:false,selfHealed:false,blockProposed:false};if($.ranThisSession=Pn(a),!$.ranThisSession)try{let{runPostflightLearning:w}=await import('./ambient-OW5M5LVN.js');await w(e.rootDir,{claimant:"navigation"}),$.selfHealed=!0,a$1.flow("$captain-board").info("Cid self-healed postflight (no prior liveness record)",{orchestrationId:o});}catch(w){$.selfHealError=w instanceof Error?w.message:String(w),a$1.flow("$captain-board").warn("Cid postflight self-heal threw \u2014 proposing advise block",{orchestrationId:o,error:$.selfHealError});try{let{handleProposeBlockTool:j}=await import('./propose-block-ZEMEWJQF.js');await j("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 I=false;try{let w={timestamp:new Date().toISOString(),sessionId:o,touchedFiles:r,coverageScore:N};R.mkdirSync(a,{recursive:!0}),R.writeFileSync(c,JSON.stringify(w,null,2),"utf8"),I=!0;}catch{}let _={taskDescription:t,orchestrationId:o,agentContributions:[],coverageDelta:{before:y,after:N},newSymbols:s,touchedFiles:r,notes:i||""};try{let w=A.join(a,"events","session-log.jsonl");if(R.existsSync(w)){let S=R.readFileSync(w,"utf8").split(`
8
+ `).filter(g=>g.trim().length>0).slice(-50),b=new Map;for(let g of S)try{let f=JSON.parse(g),k=f.agentId||f.agent||f.role||"";if(!k)continue;b.has(k)||b.set(k,{contributions:[],symbolsTouched:new Set,patternsObserved:[]});let M=b.get(k),De=f.action||f.event||f.message||"";if(De&&M.contributions.push(String(De).slice(0,120)),Array.isArray(f.symbols))for(let te of f.symbols)M.symbolsTouched.add(String(te));let Re=f.symbol||"";if(Re&&M.symbolsTouched.add(Re),Array.isArray(f.patterns))for(let te of f.patterns)M.patternsObserved.includes(String(te))||M.patternsObserved.push(String(te));}catch{}for(let[g,f]of b.entries())_.agentContributions.push({agentId:g,contribution:f.contributions.slice(-3).join(" | "),symbolsTouched:Array.from(f.symbolsTouched).slice(0,10),patternsObserved:f.patternsObserved.slice(0,5)});}}catch{}let O$1=_.agentContributions.length;_.agentContributions.length===0&&_.agentContributions.push({agentId:"session",contribution:t.slice(0,200),symbolsTouched:s.slice(0,10),patternsObserved:[]}),O$1>0&&a$4(e.rootDir,{verdicts:O$1,source:"debrief"});let E={coverageAdded:x,delegatedToDocumentor:m,loreEntryId:F,coverageScore:{before:y,after:N,delta:N-y},stopHookCleared:I,postflight:$,sessionInsights:_},h=["","\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(E,null,2)+`
10
+ `+h;return O(v.length,"paradigm_captain_debrief"),{handled:true,text:v}}var _n=A.join("events","settlement-liveness.jsonl"),Cn=360*60*1e3;function Pn(n){let e=A.join(n,_n);if(!R.existsSync(e))return false;try{let t=R.readFileSync(e,"utf8").split(`
11
+ `).filter(s=>s.trim().length>0),r=Date.now()-Cn;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 jn(n,e){let o=n.action||"read";if(o==="claim")return $n(n,e);if(o==="advance")return En(n,e);let t=await On(e.rootDir,{},e),r=JSON.stringify(t,null,2);return O(r.length,"paradigm_captain_board"),{handled:true,text:r}}function Dn(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 Rn(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 Fn(n,e){let o=Wt(n).slice(0,3),t=[];for(let r of o)try{let s=await le("paradigm_ripple",{symbol:r,depth:1,response_format:"concise"},e);s.handled&&JSON.parse(s.text).impact==="high"&&!t.includes(r)&&t.push(r);}catch{}return t}var In=/[#$^!~][a-z][a-z0-9-]*/gi;function Wt(n){let e=new Set;for(let t of n.tags||[])/^[#$^!~]/.test(t)&&e.add(t);let o=n.blurb?.match(In)||[];for(let t of o)e.add(t);return Array.from(e)}async function An(n,e){let o=Wt(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 Et={high:0,medium:1,low:2};async function On(n,e={},o){let t=o,{loadTasks:r}=await import('./task-loader-IO4UVFUD.js'),s=[];try{s=await r(n,{status:"all",limit:9999});}catch(u){a$1.flow("$captain-board").warn("Board task load failed",{error:u instanceof Error?u.message:String(u)});}let i=s.filter(u=>u.external_ref?.provider==="orchestration"&&!u.parentTaskId&&!u.settledAt),a=[];for(let u of i){let y=Rn(s.filter(m=>m.parentTaskId===u.id)),x=[];for(let m of y){let C=t?await Fn(m,t):[];x.push({taskId:m.id,blurb:m.blurb,stage:m.stage,status:m.status,claimant:m.claimant,dependsOn:m.dependsOn||[],fragileSymbols:C});}a.push({epicTaskId:u.id,blurb:u.blurb,runStatus:Dn(u,y),settledAt:u.settledAt,nodes:x});}let c=s.filter(u=>u.status==="open"&&!u.claimant),l=[];for(let u of c){let{score:y,fragile:x}=t?await An(u,t):{score:0,fragile:[]},m;e.proposeClaimants&&(m=await Nn(u,n)),l.push({taskId:u.id,blurb:u.blurb,priority:u.priority,tags:u.tags||[],rippleScore:y,fragileSymbols:x,proposedClaimant:m});}l.sort((u,y)=>{if(y.rippleScore!==u.rippleScore)return y.rippleScore-u.rippleScore;let x=(Et[u.priority]??1)-(Et[y.priority]??1);return x!==0?x:y.taskId.localeCompare(u.taskId)});let d=s.filter(u=>u.status==="in-progress").length,p=s.filter(u=>u.status==="open").length;return {runs:a,unclaimed:l,summary:{runs:a.length,open:p,inFlight:d,unclaimed:l.length}}}async function Nn(n,e){try{let{suggestAgentsForTask:o,loadAgentsManifest:t}=await import('./orchestration-UP3KFUJT.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 $n(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-IO4UVFUD.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 En(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-IO4UVFUD.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a=await s(e.rootDir,o,{blocked_on:t});return a$1.flow("$captain-board").info("Captain advance: blocked_on recorded (status unchanged)",{taskId:o,blockedOn:t,status:i.status,ok:a}),{handled:true,text:JSON.stringify({ok:a,taskId:o,blocked_on:t,status:i.status})}}function Tn(n){let e=new Set(["the","a","an","to","of","in","and","or","for","with","that","this","is","it","be","as","at","by","from","add","create","update","fix","implement","make","build","change","modify","new","old","get","set","use","using"]),o=n.match(/[#$^!~@&%?][a-z][a-z0-9-]*/g)||[],t=n.replace(/[#$^!~@&%?]/g," ").split(/[\s\-_\/.,;:'"()\[\]{}!?]+/).map(s=>s.toLowerCase()).filter(s=>s.length>2&&!e.has(s));return [...new Set([...o,...t])].slice(0,6)}function Wn(n){let e=[],o=/(?:GET|POST|PUT|PATCH|DELETE)\s+(\/[a-z0-9\-\/:_{}]+)/gi,t;for(;(t=o.exec(n))!==null;)e.push(t[1]);let r=/\/api\/[a-z0-9\-\/:_{}]+/g;for(;(t=r.exec(n))!==null;)e.includes(t[0])||e.push(t[0]);return e}function Tt(n){return n.startsWith("#")?"component":n.startsWith("$")?"flow":n.startsWith("^")?"gate":n.startsWith("!")?"signal":n.startsWith("~")?"aspect":"component"}function Ln(n){switch(n){case "component":return "component";case "flow":return "flow";case "gate":return "gate";case "signal":return "signal";case "aspect":return "aspect";default:return "component"}}function Hn(n){return n>=.85?"comprehensive":n>=.6?"reliable":n>=.3?"partial":"sparse"}function Bn(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 Mn(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 Jn(n,e,o){let r=o.filter(s=>A.dirname(s)===e).slice(0,3).map(s=>`# - ${A.basename(s)}`).join(`
13
+ `);return `# Auto-generated .purpose stub \u2014 created by Cid (captain debrief)
14
+ # Delegate to Scribe (Documentor) for rich documentation
15
+ name: ${n}
16
+ description: "TODO: describe what this directory/module does"
17
+ context:
18
+ - "Stub created by Cid during coverage audit \u2014 update with real context"
19
+ ${r?`# Key files touched:
20
+ ${r}`:""}
21
+ components:
22
+ ${n}:
23
+ description: "TODO: describe this component"
24
+ tags: []
25
+ `}export{is as A,je as B,Ss as C,xs as D,On as E,Nn as F,fn as a,xt as b,xo as c,gn as d,vo as e,yn as f,ko as g,xe as h,Ao as i,fe as j,Oo as k,to as l,pt as m,mt as n,gt as o,yt as p,go as q,le as r,Jo as s,Dt as t,Uo as u,Rt as v,Ko as w,Ce as x,It as y,Qo as z};