@a-company/paradigm 7.0.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 (145) hide show
  1. package/dist/{accept-orchestration-YO2V2WYA.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-OW5M5LVN.js +2 -0
  5. package/dist/{ambient-OX7YJ4PJ.js → ambient-TFLZFV5Y.js} +1 -1
  6. package/dist/ambient-VCTUHHIG.js +2 -0
  7. package/dist/arch-loader-YVOS3QRY.js +2 -0
  8. package/dist/{beacon-52EWNZPK.js → beacon-WVN264OT.js} +1 -1
  9. package/dist/calibrate-PHVP7RPH.js +4 -0
  10. package/dist/captain-CAXGHC2V.js +2 -0
  11. package/dist/captain-CWCLFOXV.js +2 -0
  12. package/dist/{chunk-QDP4G53M.js → chunk-27EK3OQZ.js} +4 -4
  13. package/dist/chunk-2KK4JQ55.js +17 -0
  14. package/dist/chunk-3I3TITBA.js +25 -0
  15. package/dist/chunk-3YM5ABNX.js +2 -0
  16. package/dist/{chunk-47YPID6H.js → chunk-6HYRS3PH.js} +21 -21
  17. package/dist/{chunk-S3UVQ5RV.js → chunk-6VZSOQ7Y.js} +1 -1
  18. package/dist/chunk-727PXENG.js +2 -0
  19. package/dist/chunk-A5EEY6NO.js +3 -0
  20. package/dist/{chunk-DLMDHS2X.js → chunk-ASBK55FU.js} +1 -1
  21. package/dist/{chunk-4GC35IFF.js → chunk-D6BSCELB.js} +1 -1
  22. package/dist/{chunk-G6DK3ND3.js → chunk-DH7QVZDI.js} +9 -0
  23. package/dist/chunk-ECO3LHCE.js +2 -0
  24. package/dist/chunk-FG3M6VVO.js +30 -0
  25. package/dist/chunk-FNYYQNJY.js +2 -0
  26. package/dist/{chunk-ROU3F2HZ.js → chunk-HSY75GRR.js} +3 -3
  27. package/dist/chunk-K6TLYNRQ.js +7 -0
  28. package/dist/chunk-K7KT6FL3.js +25 -0
  29. package/dist/chunk-KAUGQMXU.js +4 -0
  30. package/dist/chunk-M7JHVVDW.js +6 -0
  31. package/dist/chunk-NFN5UUJB.js +2 -0
  32. package/dist/chunk-NRP2KJ6I.js +33 -0
  33. package/dist/{chunk-WROJSWAO.js → chunk-QPQBXRXX.js} +1 -1
  34. package/dist/chunk-RVXQNS6K.js +30 -0
  35. package/dist/chunk-RZRFYGND.js +504 -0
  36. package/dist/chunk-UNSI6DVD.js +93 -0
  37. package/dist/{chunk-JCGCPAHF.js → chunk-USYV5QYU.js} +1 -1
  38. package/dist/chunk-VOPJ47QY.js +2 -0
  39. package/dist/{chunk-QBIQ2FYB.js → chunk-W3VWORQZ.js} +1 -1
  40. package/dist/chunk-WMTES556.js +2 -0
  41. package/dist/chunk-XBK244QR.js +6 -0
  42. package/dist/chunk-XSKIXXFW.js +504 -0
  43. package/dist/{chunk-MBSY57RN.js → chunk-Y76OIMDO.js} +1 -1
  44. package/dist/chunk-YYRP7FLC.js +2 -0
  45. package/dist/{compliance-MLG4W6S4.js → compliance-3M6COUCO.js} +3 -3
  46. package/dist/{constellation-RHZAEFV7.js → constellation-TIKNCZWR.js} +1 -1
  47. package/dist/{cost-24UZSS2P.js → cost-VTHZQKO4.js} +2 -2
  48. package/dist/{diff-MC6AXLKX.js → diff-Z2YSIRC4.js} +1 -1
  49. package/dist/{dist-TNE4GFT7.js → dist-PW5YPGFF.js} +1 -1
  50. package/dist/{docs-3YFNNZRV.js → docs-OWJ7EPD7.js} +1 -1
  51. package/dist/github-4X4MYINS.js +4 -0
  52. package/dist/{habits-BX2IRSUI.js → habits-UA7YT3CG.js} +3 -3
  53. package/dist/{hooks-AXBWYJ5V.js → hooks-XXJ7CSGJ.js} +1 -1
  54. package/dist/index.js +9 -9
  55. package/dist/{init-F4MSKZIW.js → init-QPMLEQWQ.js} +1 -1
  56. package/dist/{integrity-7TKX3DZ4.js → integrity-FRGF5BFS.js} +1 -1
  57. package/dist/journal-loader-CNNA4EAU.js +2 -0
  58. package/dist/lint-Y4P3MHBV.js +26 -0
  59. package/dist/list-5XRLWD7K.js +12 -0
  60. package/dist/mcp.js +1 -1
  61. package/dist/{migrate-5M4KUQ2L.js → migrate-LIVXILOO.js} +1 -1
  62. package/dist/{nomination-engine-AQHU2KBU.js → nomination-engine-EFXDEPZN.js} +1 -1
  63. package/dist/nomination-engine-YRHZZZUN.js +2 -0
  64. package/dist/notebook-loader-TZVIMNDJ.js +2 -0
  65. package/dist/{orchestrate-GMYEBA5T.js → orchestrate-C5NM5MFN.js} +1 -1
  66. package/dist/orchestration-EVWQWTOV.js +2 -0
  67. package/dist/orchestration-UP3KFUJT.js +2 -0
  68. package/dist/{platform-server-WIBVYHIV.js → platform-server-FXF3XFHM.js} +1 -1
  69. package/dist/{probe-27ARJKRO.js → probe-G3TKOJYW.js} +1 -1
  70. package/dist/quiz-QKIKAVL7.js +10 -0
  71. package/dist/registry-NEW4OJ44.js +2 -0
  72. package/dist/reindex-QZYOD5K4.js +2 -0
  73. package/dist/{reindex-XTRF23F7.js → reindex-W67B2LQP.js} +1 -1
  74. package/dist/remember-KZYAY77S.js +14 -0
  75. package/dist/{review-BRO2UP4M.js → review-WHRNLW2W.js} +1 -1
  76. package/dist/{ripple-KCVDS3WE.js → ripple-B6U7263T.js} +1 -1
  77. package/dist/{serve-2PKJP65E.js → serve-6RNZYK2I.js} +2 -2
  78. package/dist/{serve-SMGWGJLM.js → serve-ZT2Z54NK.js} +1 -1
  79. package/dist/{setup-5V2AGLQ6.js → setup-L5OP24US.js} +3 -3
  80. package/dist/{shift-JBCEDCGA.js → shift-UDKXCIW7.js} +3 -3
  81. package/dist/{show-N5LGB5B2.js → show-VXNGIJE4.js} +3 -3
  82. package/dist/{snapshot-YMX5QRBM.js → snapshot-MT5L6XE4.js} +1 -1
  83. package/dist/{spawn-PHA2SVQ3.js → spawn-I6XG57S2.js} +1 -1
  84. package/dist/status-45KIG32R.js +6 -0
  85. package/dist/{status-3GJXI4IK.js → status-4QGKLOP6.js} +4 -4
  86. package/dist/{summary-RPU2BS3Q.js → summary-6QNVQZJV.js} +1 -1
  87. package/dist/symphony-KQJ6HIXB.js +53 -0
  88. package/dist/symphony-VDNDFK7H.js +2 -0
  89. package/dist/symphony-relay-ASMKPDEE.js +3 -0
  90. package/dist/task-KFND4HLF.js +3 -0
  91. package/dist/task-loader-HBZ3KRH2.js +2 -0
  92. package/dist/task-loader-IO4UVFUD.js +2 -0
  93. package/dist/task-settlement-NF7PFSNE.js +3 -0
  94. package/dist/task-settlement-TATNPY6L.js +3 -0
  95. package/dist/team-6WNNLBAO.js +2 -0
  96. package/dist/thread-2A7QKU72.js +41 -0
  97. package/dist/tools-GDWT74O6.js +2 -0
  98. package/dist/tools-SDWAFQMQ.js +142 -0
  99. package/dist/university-ui/assets/{index-B8hm_MdR.js → index-AbTjHBCf.js} +2 -2
  100. package/dist/university-ui/assets/{index-B8hm_MdR.js.map → index-AbTjHBCf.js.map} +1 -1
  101. package/dist/university-ui/index.html +1 -1
  102. package/dist/validate-OZTX3FYX.js +13 -0
  103. package/dist/validate-RIMSY3RP.js +9 -0
  104. package/dist/{workspace-6POCBPDY.js → workspace-4D4TQ637.js} +1 -1
  105. package/package.json +1 -1
  106. package/dist/add-V6XR7DU5.js +0 -12
  107. package/dist/agent-loader-VGBPL3TH.js +0 -2
  108. package/dist/ambient-7HBJHJL2.js +0 -2
  109. package/dist/ambient-SST5CLEC.js +0 -35
  110. package/dist/captain-YUP3KVCA.js +0 -2
  111. package/dist/chunk-3MZ4J2LF.js +0 -2
  112. package/dist/chunk-6AKNXD22.js +0 -32
  113. package/dist/chunk-7SWEOPWF.js +0 -2
  114. package/dist/chunk-CVPKQ3JH.js +0 -8
  115. package/dist/chunk-EKNLG73M.js +0 -6
  116. package/dist/chunk-FRQRREJ6.js +0 -29
  117. package/dist/chunk-GD4F2HC6.js +0 -3
  118. package/dist/chunk-JIXHEBGK.js +0 -7
  119. package/dist/chunk-K54L6CFR.js +0 -25
  120. package/dist/chunk-MBPLJKE5.js +0 -3
  121. package/dist/chunk-QEQCPVF5.js +0 -4
  122. package/dist/chunk-QGZRM6ZB.js +0 -2
  123. package/dist/chunk-QO7YPQXC.js +0 -2
  124. package/dist/chunk-S4J337EQ.js +0 -504
  125. package/dist/chunk-V6MIKLMY.js +0 -18
  126. package/dist/journal-loader-GLH7XFTK.js +0 -2
  127. package/dist/lint-IGKE6UPS.js +0 -26
  128. package/dist/list-NC3QGT75.js +0 -12
  129. package/dist/lore-loader-D2ISOASW.js +0 -2
  130. package/dist/notebook-loader-6DYFMNJ2.js +0 -2
  131. package/dist/orchestration-G5MAY6IA.js +0 -2
  132. package/dist/quiz-TNV6APBM.js +0 -10
  133. package/dist/remember-MJRNTXYS.js +0 -14
  134. package/dist/session-work-log-QXPAXY5K.js +0 -2
  135. package/dist/status-ENAI35NL.js +0 -6
  136. package/dist/symphony-7INZR43F.js +0 -53
  137. package/dist/symphony-G6IENE4K.js +0 -2
  138. package/dist/symphony-relay-2RHG25Z4.js +0 -3
  139. package/dist/task-loader-IGQQ6ZFL.js +0 -2
  140. package/dist/task-settlement-NW4XMJGJ.js +0 -3
  141. package/dist/team-J2YXPEGX.js +0 -2
  142. package/dist/thread-HFXK65D4.js +0 -41
  143. package/dist/tools-HNJ7D5IO.js +0 -2
  144. package/dist/validate-IQG7DBFC.js +0 -9
  145. package/dist/validate-LSCDOLBO.js +0 -13
@@ -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,2 @@
1
+ #!/usr/bin/env node
2
+ import {b}from'./chunk-5TAVYPOV.js';import*as s from'fs';import*as c from'path';import*as g from'js-yaml';function m(e){let r=process.env.HOME||process.env.USERPROFILE||"";return c.join(r,".paradigm","agents",e,"journal")}function d(){let e=new Date,r=e.toISOString().slice(0,10),i=e.toISOString().slice(11,19).replace(/:/g,""),o=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `LJ-${r}-${i}-${o}`}function h(e,r){let i=new Date,o=d(),a={id:o,agent:e,timestamp:i.toISOString(),...r},t=m(e);s.mkdirSync(t,{recursive:true});let n=c.join(t,`${o}.yaml`);return s.writeFileSync(n,g.dump(a,{lineWidth:120,noRefs:true}),"utf8"),a}function f(e,r){let i=m(e);if(!s.existsSync(i))return [];let o=[],a=s.readdirSync(i).filter(n=>n.endsWith(".yaml"));for(let n of a)try{let l=s.readFileSync(c.join(i,n),"utf8"),u=g.load(l);u&&u.id&&o.push(u);}catch{}let t=o;return r?.trigger&&(t=t.filter(n=>n.trigger===r.trigger)),r?.project&&(t=t.filter(n=>n.project===r.project)),r?.transferable!==void 0&&(t=t.filter(n=>n.transferable===r.transferable)),r?.tag&&(t=t.filter(n=>n.tags?.some(l=>l.startsWith(r.tag)))),r?.dateFrom&&(t=t.filter(n=>n.timestamp>=r.dateFrom)),r?.dateTo&&(t=t.filter(n=>n.timestamp<=r.dateTo)),t.sort((n,l)=>l.timestamp.localeCompare(n.timestamp)),r?.limit&&(t=t.slice(0,r.limit)),t}function J(e,r){let i=m(e),o=c.join(i,`${r}.yaml`);if(!s.existsSync(o))return null;let a=s.readFileSync(o,"utf8");return g.load(a)}function E(e){let r=process.env.HOME||process.env.USERPROFILE||"",i=c.join(r,".paradigm","agents");if(!s.existsSync(i))return [];let o=[],a=s.readdirSync(i,{withFileTypes:true}).filter(t=>t.isDirectory());for(let t of a){if(e?.agent&&t.name!==e.agent)continue;let n=f(t.name,e);o.push(...n);}return o.sort((t,n)=>n.timestamp.localeCompare(t.timestamp)),e?.limit?o.slice(0,e.limit):o}function S(e){let r=f(e),i={},o={},a=0;for(let t of r)i[t.trigger]=(i[t.trigger]||0)+1,o[t.project]=(o[t.project]||0)+1,t.transferable&&a++;return {total:r.length,byTrigger:i,byProject:o,transferableCount:a,recentInsights:r.slice(0,5).map(t=>({id:t.id,trigger:t.trigger,insight:t.insight.slice(0,200),timestamp:t.timestamp}))}}var y=b(()=>{});export{h as a,f as b,J as c,E as d,S as e,y as f};
@@ -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};
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import {v as v$1,b,q,p,o,s as s$1,i,k,l,a,m,t,u,j as j$1}from'./chunk-FRQRREJ6.js';import {e}from'./chunk-Q527BPUF.js';import {z,f,p as p$1}from'./chunk-KAFQA7HV.js';import {s,e as e$1,g as g$1,b as b$2,f as f$1,h}from'./chunk-33ERV2MW.js';import {g,b as b$1,a as a$1}from'./chunk-QGZRM6ZB.js';import*as v from'fs';import*as j from'path';v$1();b();z();g();s();function be(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function re(s){let e=Date.now(),t=s.match(/^(\d+)(m|h|d)$/);if(t){let r=parseInt(t[1],10),i=t[2],l=i==="m"?r*6e4:i==="h"?r*36e5:r*864e5;return new Date(e-l).toISOString()}return s}async function ve(s,e$1,t$1){let r=i=>JSON.stringify(i,null,2);switch(s){case "paradigm_ambient_nominations":{m(t$1.rootDir);let l=e$1.pending_only!==false,d=e$1.limit||20,o=i(t$1.rootDir,{agent:e$1.agent,urgency:e$1.urgency,pending_only:l,limit:d+20}),b=t(t$1.rootDir);o=u(o,b).slice(0,d);let y=j.join(t$1.rootDir,".paradigm/events/nominations.jsonl");if(v.existsSync(y))try{let a=v.readFileSync(y,"utf8"),c=new Set(o.map(m=>m.id)),g=a.trim().split(`
2
+ import {v as v$1,b,q,p,o,s as s$1,i,k,l,a,m,t,u,j as j$1}from'./chunk-RVXQNS6K.js';import {e}from'./chunk-Q527BPUF.js';import {z,f as f$1,p as p$1}from'./chunk-KAFQA7HV.js';import {s,e as e$1,g,b as b$2,f as f$2,h}from'./chunk-33ERV2MW.js';import {f,b as b$1,a as a$1}from'./chunk-ECO3LHCE.js';import*as v from'fs';import*as j from'path';v$1();b();z();f();s();function be(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function re(s){let e=Date.now(),t=s.match(/^(\d+)(m|h|d)$/);if(t){let r=parseInt(t[1],10),i=t[2],l=i==="m"?r*6e4:i==="h"?r*36e5:r*864e5;return new Date(e-l).toISOString()}return s}async function ve(s,e$1,t$1){let r=i=>JSON.stringify(i,null,2);switch(s){case "paradigm_ambient_nominations":{m(t$1.rootDir);let l=e$1.pending_only!==false,d=e$1.limit||20,o=i(t$1.rootDir,{agent:e$1.agent,urgency:e$1.urgency,pending_only:l,limit:d+20}),b=t(t$1.rootDir);o=u(o,b).slice(0,d);let y=j.join(t$1.rootDir,".paradigm/events/nominations.jsonl");if(v.existsSync(y))try{let a=v.readFileSync(y,"utf8"),c=new Set(o.map(m=>m.id)),g=a.trim().split(`
3
3
  `).map(m=>{try{let f=JSON.parse(m);return c.has(f.id)?(f.surfaced=!0,JSON.stringify(f)):m}catch{return m}});v.writeFileSync(y,g.join(`
4
4
  `)+`
5
- `,"utf8");}catch{}let h={count:o.length,nominations:o.map(a=>({id:a.id,agent:a.agent,urgency:a.urgency,type:a.type,brief:a.brief,relevance:a.relevance,timestamp:a.timestamp,engaged:a.engaged,response:a.response}))};if(e$1.include_debates){let c=j$1(t$1.rootDir).filter(g=>!g.resolution);h.debates=c.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),h.debate_count=c.length;}return {text:r(h),handled:true}}case "paradigm_ambient_events":{let i=e$1.since?re(e$1.since):void 0,l=e$1.limit||50,d=a(t$1.rootDir,{type:e$1.type,source:e$1.source,symbol:e$1.symbol,agent:e$1.agent,since:i,limit:l});return {text:r({count:d.length,events:d.map(o=>({id:o.id,type:o.type,source:o.source,timestamp:o.timestamp,path:o.path,symbols:o.symbols,context:o.context,agent:o.agent,tool:o.tool,severity:o.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i$1=e$1.nomination_id,l$1=e$1.response,d=e$1.reason,o=k(t$1.rootDir,i$1,l$1,d);if(o)try{let{appendSessionWorkEntry:y,appendVerdictEntry:h}=await import('./session-work-log-T2IE4Y4T.js'),c=i(t$1.rootDir,{limit:500}).find(m=>m.id===i$1),g={timestamp:new Date().toISOString(),type:"user-verdict",agent:c?.agent,nominationId:i$1,verdict:l$1,reason:d};y(t$1.rootDir,g),h(t$1.rootDir,g);}catch{}let b=false;return e$1.resolve_debate&&o&&(b=l(t$1.rootDir,e$1.resolve_debate,i$1,e$1.reason)),{text:r({engaged:o,nomination_id:i$1,response:l$1,debate_resolved:b||void 0}),handled:true}}case "paradigm_context_compose":{let i$1=e$1.agent,l=e$1.symbols||[],d=e$1.include_nominations!==false,o=e$1.include_decisions!==false,b=e$1.include_journal!==false,y=e$1.max_decisions||5,h=e$1.max_journal||5,a=f(t$1.rootDir,i$1);if(!a)return {text:r({error:`Agent profile not found: ${i$1}`}),handled:true};let c=[],g=p$1(a,l);if(g.trim()&&c.push(g),o){let m=e(t$1.rootDir,{status:"active",limit:y});if(m.length>0){c.push("## Recent Team Decisions");for(let f of m)c.push(`- **${f.title}**: ${f.decision.slice(0,150)}${f.decision.length>150?"...":""}`);c.push("");}}if(b){let m=b$1(i$1,{transferable:true,limit:h});if(m.length>0){c.push("## Transferable Insights");for(let f of m)c.push(`- [${f.trigger}] ${f.insight.slice(0,150)}${f.insight.length>150?"...":""}`);c.push("");}}if(d){let m=i(t$1.rootDir,{pending_only:true,limit:10});if(m.length>0){c.push("## Pending Nominations");for(let f of m)c.push(`- [${f.urgency}] ${f.brief}`);c.push("");}}return {text:r({agent:i$1,context:c.join(`
6
- `),sections_included:{profile:true,decisions:o,journal:b,nominations:d}}),handled:true}}case "paradigm_ambient_promote":{let i=e$1.agent,l=s$1(t$1.rootDir,i);return {text:r({agent:i,promoted:l.promoted,entries:l.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e$1.agent,l=e$1.dry_run===true,d=p(t$1.rootDir,i);if(l)return {text:r({agent:i,dry_run:true,stats:d,note:d.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(d.acceptRate*100).toFixed(0)}% \u2014 ${d.acceptRate>.8?"would lower threshold":d.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let o$1=o(t$1.rootDir,i);return {text:r({agent:i,...o$1,stats:d}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let i=q(t$1.rootDir);return {text:r(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:r(await de(t$1.rootDir,e$1)),handled:true};default:return {text:`Unknown ambient tool: ${s}`,handled:false}}}var ae={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function ce(s){try{let e=j.join(s,".paradigm","config.yaml");if(v.existsSync(e)){let r=v.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(r)return r[1].trim()}}catch{}return j.basename(s)}async function de(s,e={}){let t=e.dry_run===true,r=ce(s),i=e$1(s).filter(n=>n.verdict&&n.agent),l=g$1(s).filter(n=>n.agent&&n.corrections.length>0),d=b$2(s);if(i.length===0&&l.length===0)return {sessionEntries:d.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:t,details:[]};let o=new Map;for(let n of i){let u=n.agent;o.has(u)||o.set(u,[]),o.get(u).push(n);}let b=d.filter(n=>n.type==="agent-contribution"),y=new Map;for(let n of b)n.agent&&(y.has(n.agent)||y.set(n.agent,[]),y.get(n.agent).push(n));let h$1=[],a={},c=0;for(let[n,u]of o){a[n]=0;let _=u.filter(p=>p.verdict==="accepted").length;u.filter(p=>p.verdict==="dismissed").length;u.filter(p=>p.verdict==="revised").length;let R=u.length,K=R>0?_/R:0;for(let p of u){let I=ae[p.verdict];if(!I)continue;let X=y.get(n)?.shift(),A=le(p,X,{acceptRate:K,total:R,accepted:_}),Y=typeof p.confidence=="number"?p.confidence:p.verdict==="accepted"?.85:p.verdict==="revised"?.6:.4,Z={agent:n,verdict:p.verdict,trigger:I,insight:A,symbols:p.symbols};if(h$1.push(Z),t)a[n]++,c++;else try{a$1(n,{trigger:I,insight:A,confidence_before:p.verdict==="accepted"?.7:.8,confidence_after:Y,project:r,transferable:p.verdict==="dismissed",tags:["postflight",`verdict:${p.verdict}`,...(p.symbols||[]).map(ee=>`symbol:${ee}`)]}),a[n]++,c++;}catch{}}}let g=new Set;for(let n of l){let u=n.agent;g.add(u),a[u]===void 0&&(a[u]=0);let _=`Self-revision during iteration round ${n.round}: ${n.corrections.join("; ")}`;if(h$1.push({agent:u,verdict:"iteration-revision",trigger:"self_reflection",insight:_,symbols:n.symbols}),t)a[u]++,c++;else try{a$1(u,{trigger:"self_reflection",insight:_,confidence_before:.6,confidence_after:typeof n.confidence=="number"?n.confidence:.75,project:r,transferable:!1,tags:["postflight","iteration-revision",`round:${n.round}`,...(n.symbols||[]).map($=>`symbol:${$}`)]}),a[u]++,c++;}catch{}}let m={},f=0,k=new Set([...o.keys(),...g]);if(!t)for(let n of k)try{let u=s$1(s,n);u.promoted>0&&(m[n]=u.promoted,f+=u.promoted);}catch{}return !t&&i.length>0&&f$1(s,i.map(n=>n.nominationId).filter(Boolean)),!t&&l.length>0&&h(s,l.map(n=>n.id)),{sessionEntries:d.length,agentsProcessed:Array.from(k),journalsWritten:c,journalsByAgent:a,promoted:f,promotedByAgent:m,dryRun:t,details:h$1}}function le(s,e,t){let r=s.symbols?.length?` (symbols: ${s.symbols.join(", ")})`:"",i=s.reason?` Reason: ${s.reason}.`:"";switch(s.verdict){case "accepted":return `Contribution accepted by user${r}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "dismissed":return `Contribution dismissed by user${r}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "revised":return `Contribution revised by user${r}.${i}`+(s.revisionDelta?` Delta: "${s.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;default:return `Unknown verdict "${s.verdict}"${r}.${i}`}}export{be as a,ve as b,de as c};
5
+ `,"utf8");}catch{}let h={count:o.length,nominations:o.map(a=>({id:a.id,agent:a.agent,urgency:a.urgency,type:a.type,brief:a.brief,relevance:a.relevance,timestamp:a.timestamp,engaged:a.engaged,response:a.response}))};if(e$1.include_debates){let c=j$1(t$1.rootDir).filter(g=>!g.resolution);h.debates=c.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),h.debate_count=c.length;}return {text:r(h),handled:true}}case "paradigm_ambient_events":{let i=e$1.since?re(e$1.since):void 0,l=e$1.limit||50,d=a(t$1.rootDir,{type:e$1.type,source:e$1.source,symbol:e$1.symbol,agent:e$1.agent,since:i,limit:l});return {text:r({count:d.length,events:d.map(o=>({id:o.id,type:o.type,source:o.source,timestamp:o.timestamp,path:o.path,symbols:o.symbols,context:o.context,agent:o.agent,tool:o.tool,severity:o.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i$1=e$1.nomination_id,l$1=e$1.response,d=e$1.reason,o=k(t$1.rootDir,i$1,l$1,d);if(o)try{let{appendSessionWorkEntry:y,appendVerdictEntry:h}=await import('./session-work-log-T2IE4Y4T.js'),c=i(t$1.rootDir,{limit:500}).find(m=>m.id===i$1),g={timestamp:new Date().toISOString(),type:"user-verdict",agent:c?.agent,nominationId:i$1,verdict:l$1,reason:d};y(t$1.rootDir,g),h(t$1.rootDir,g);}catch{}let b=false;return e$1.resolve_debate&&o&&(b=l(t$1.rootDir,e$1.resolve_debate,i$1,e$1.reason)),{text:r({engaged:o,nomination_id:i$1,response:l$1,debate_resolved:b||void 0}),handled:true}}case "paradigm_context_compose":{let i$1=e$1.agent,l=e$1.symbols||[],d=e$1.include_nominations!==false,o=e$1.include_decisions!==false,b=e$1.include_journal!==false,y=e$1.max_decisions||5,h=e$1.max_journal||5,a=f$1(t$1.rootDir,i$1);if(!a)return {text:r({error:`Agent profile not found: ${i$1}`}),handled:true};let c=[],g=p$1(a,l);if(g.trim()&&c.push(g),o){let m=e(t$1.rootDir,{status:"active",limit:y});if(m.length>0){c.push("## Recent Team Decisions");for(let f of m)c.push(`- **${f.title}**: ${f.decision.slice(0,150)}${f.decision.length>150?"...":""}`);c.push("");}}if(b){let m=b$1(i$1,{transferable:true,limit:h});if(m.length>0){c.push("## Transferable Insights");for(let f of m)c.push(`- [${f.trigger}] ${f.insight.slice(0,150)}${f.insight.length>150?"...":""}`);c.push("");}}if(d){let m=i(t$1.rootDir,{pending_only:true,limit:10});if(m.length>0){c.push("## Pending Nominations");for(let f of m)c.push(`- [${f.urgency}] ${f.brief}`);c.push("");}}return {text:r({agent:i$1,context:c.join(`
6
+ `),sections_included:{profile:true,decisions:o,journal:b,nominations:d}}),handled:true}}case "paradigm_ambient_promote":{let i=e$1.agent,l=s$1(t$1.rootDir,i);return {text:r({agent:i,promoted:l.promoted,entries:l.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e$1.agent,l=e$1.dry_run===true,d=p(t$1.rootDir,i);if(l)return {text:r({agent:i,dry_run:true,stats:d,note:d.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(d.acceptRate*100).toFixed(0)}% \u2014 ${d.acceptRate>.8?"would lower threshold":d.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let o$1=o(t$1.rootDir,i);return {text:r({agent:i,...o$1,stats:d}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let i=q(t$1.rootDir);return {text:r(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:r(await de(t$1.rootDir,e$1)),handled:true};default:return {text:`Unknown ambient tool: ${s}`,handled:false}}}var ae={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function ce(s){try{let e=j.join(s,".paradigm","config.yaml");if(v.existsSync(e)){let r=v.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(r)return r[1].trim()}}catch{}return j.basename(s)}async function de(s,e={}){let t=e.dry_run===true,r=ce(s),i=e$1(s).filter(n=>n.verdict&&n.agent),l=g(s).filter(n=>n.agent&&n.corrections.length>0),d=b$2(s);if(i.length===0&&l.length===0)return {sessionEntries:d.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:t,details:[]};let o=new Map;for(let n of i){let u=n.agent;o.has(u)||o.set(u,[]),o.get(u).push(n);}let b=d.filter(n=>n.type==="agent-contribution"),y=new Map;for(let n of b)n.agent&&(y.has(n.agent)||y.set(n.agent,[]),y.get(n.agent).push(n));let h$1=[],a={},c=0;for(let[n,u]of o){a[n]=0;let _=u.filter(p=>p.verdict==="accepted").length;u.filter(p=>p.verdict==="dismissed").length;u.filter(p=>p.verdict==="revised").length;let R=u.length,K=R>0?_/R:0;for(let p of u){let I=ae[p.verdict];if(!I)continue;let X=y.get(n)?.shift(),A=le(p,X,{acceptRate:K,total:R,accepted:_}),Y=typeof p.confidence=="number"?p.confidence:p.verdict==="accepted"?.85:p.verdict==="revised"?.6:.4,Z={agent:n,verdict:p.verdict,trigger:I,insight:A,symbols:p.symbols};if(h$1.push(Z),t)a[n]++,c++;else try{a$1(n,{trigger:I,insight:A,confidence_before:p.verdict==="accepted"?.7:.8,confidence_after:Y,project:r,transferable:p.verdict==="dismissed",tags:["postflight",`verdict:${p.verdict}`,...(p.symbols||[]).map(ee=>`symbol:${ee}`)]}),a[n]++,c++;}catch{}}}let g$1=new Set;for(let n of l){let u=n.agent;g$1.add(u),a[u]===void 0&&(a[u]=0);let _=`Self-revision during iteration round ${n.round}: ${n.corrections.join("; ")}`;if(h$1.push({agent:u,verdict:"iteration-revision",trigger:"self_reflection",insight:_,symbols:n.symbols}),t)a[u]++,c++;else try{a$1(u,{trigger:"self_reflection",insight:_,confidence_before:.6,confidence_after:typeof n.confidence=="number"?n.confidence:.75,project:r,transferable:!1,tags:["postflight","iteration-revision",`round:${n.round}`,...(n.symbols||[]).map($=>`symbol:${$}`)]}),a[u]++,c++;}catch{}}let m={},f=0,k=new Set([...o.keys(),...g$1]);if(!t)for(let n of k)try{let u=s$1(s,n);u.promoted>0&&(m[n]=u.promoted,f+=u.promoted);}catch{}return !t&&i.length>0&&f$2(s,i.map(n=>n.nominationId).filter(Boolean)),!t&&l.length>0&&h(s,l.map(n=>n.id)),{sessionEntries:d.length,agentsProcessed:Array.from(k),journalsWritten:c,journalsByAgent:a,promoted:f,promotedByAgent:m,dryRun:t,details:h$1}}function le(s,e,t){let r=s.symbols?.length?` (symbols: ${s.symbols.join(", ")})`:"",i=s.reason?` Reason: ${s.reason}.`:"";switch(s.verdict){case "accepted":return `Contribution accepted by user${r}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "dismissed":return `Contribution dismissed by user${r}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "revised":return `Contribution revised by user${r}.${i}`+(s.revisionDelta?` Delta: "${s.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;default:return `Unknown verdict "${s.verdict}"${r}.${i}`}}export{be as a,ve as b,de as c};
@@ -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};