@a-company/paradigm 5.35.1 → 5.37.1

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 (95) hide show
  1. package/dist/{accept-orchestration-MIRBLRUJ.js → accept-orchestration-SBZVK3H4.js} +1 -1
  2. package/dist/{agent-loader-5255KNM7.js → agent-loader-RIVI6QPP.js} +1 -1
  3. package/dist/{agent-loader-A5FMBAFJ.js → agent-loader-RJRVO5GQ.js} +1 -1
  4. package/dist/{ambient-BKX77DDQ.js → ambient-GJAEXF7B.js} +8 -8
  5. package/dist/chunk-3KVVC4WV.js +2 -0
  6. package/dist/{chunk-QNZEG7IT.js → chunk-3XGNXXCT.js} +1 -1
  7. package/dist/chunk-4Q7XYPL4.js +29 -0
  8. package/dist/{chunk-AGSUX2GJ.js → chunk-4SCKMGTB.js} +1 -1
  9. package/dist/chunk-74SGKSRQ.js +3 -0
  10. package/dist/chunk-CMCQHU46.js +456 -0
  11. package/dist/chunk-CVPKQ3JH.js +8 -0
  12. package/dist/{chunk-33LKBMVK.js → chunk-D6ZXAI26.js} +1 -1
  13. package/dist/{chunk-HMQ5BHP2.js → chunk-DOCDDDTD.js} +10 -10
  14. package/dist/chunk-EK4ZRIFJ.js +3 -0
  15. package/dist/chunk-FILLU77P.js +111 -0
  16. package/dist/{chunk-A7KFOJ2F.js → chunk-J6KWGCHN.js} +1 -1
  17. package/dist/chunk-JOHAOLEC.js +11 -0
  18. package/dist/{chunk-HPAHK4AJ.js → chunk-KFNHCQ4R.js} +1 -1
  19. package/dist/{chunk-JBDMCRPP.js → chunk-LBQBWIEX.js} +1 -1
  20. package/dist/chunk-MBPLJKE5.js +3 -0
  21. package/dist/{chunk-UDUHSHO4.js → chunk-ORDKEGII.js} +1 -1
  22. package/dist/chunk-QO7YPQXC.js +2 -0
  23. package/dist/{chunk-W5IWDW4Y.js → chunk-SUU6M4JH.js} +1 -1
  24. package/dist/{chunk-32RBX5YV.js → chunk-UNHTQLYO.js} +1 -1
  25. package/dist/chunk-UPFCBVXY.js +3 -0
  26. package/dist/chunk-X3U3IGYT.js +3 -0
  27. package/dist/chunk-Z72SDTBJ.js +3 -0
  28. package/dist/chunk-ZUAUFZRJ.js +8 -0
  29. package/dist/{compliance-NJSBCY6F.js → compliance-BPGQMQAX.js} +2 -2
  30. package/dist/{diff-QHQWLM3L.js → diff-JVEYCXUC.js} +1 -1
  31. package/dist/dist-QBTQW4ZW.js +3 -0
  32. package/dist/{docs-5BX2YWYK.js → docs-USDAF26F.js} +1 -1
  33. package/dist/doctor-G37LCXG5.js +2 -0
  34. package/dist/{habits-GICVMTJL.js → habits-BX2IRSUI.js} +1 -1
  35. package/dist/index.js +9 -9
  36. package/dist/init-EHVSM7YY.js +2 -0
  37. package/dist/mcp.js +17 -449
  38. package/dist/{nomination-engine-6VTQ4OVW.js → nomination-engine-KNSOAT4W.js} +1 -1
  39. package/dist/{orchestrate-7CJWHLBA.js → orchestrate-RCAMBOIB.js} +1 -1
  40. package/dist/{platform-server-G6MJIAJS.js → platform-server-DNAMH4YI.js} +1 -1
  41. package/dist/{probe-5L5BQDGE.js → probe-B22G2JKF.js} +1 -1
  42. package/dist/{providers-TBPOE4DI.js → providers-AWA7WLLM.js} +1 -1
  43. package/dist/registry-KOOKFUWD.js +20 -0
  44. package/dist/reindex-O3WUCEE2.js +2 -0
  45. package/dist/scaffold-D57JXPCC.js +18 -0
  46. package/dist/{scopes-commands-3V5G6NYV.js → scopes-commands-NSPERZWV.js} +1 -1
  47. package/dist/{serve-ZJ3EXVA5.js → serve-U47GULB6.js} +1 -1
  48. package/dist/session-tracker-D2CH7RJF.js +2 -0
  49. package/dist/{session-work-log-SLAPEP3M.js → session-work-log-BX434ZLK.js} +1 -1
  50. package/dist/{session-work-log-5UJTJJ22.js → session-work-log-NQA7WJEC.js} +1 -1
  51. package/dist/{shift-EU22H7GG.js → shift-RRNL6E4O.js} +5 -5
  52. package/dist/{spawn-7TCAMD6H.js → spawn-M5BAV252.js} +1 -1
  53. package/dist/{summary-ZJLQ6KHB.js → summary-LXLHFRN7.js} +1 -1
  54. package/dist/{symphony-IS5TYPXY.js → symphony-7INZR43F.js} +25 -25
  55. package/dist/symphony-G6IENE4K.js +2 -0
  56. package/dist/symphony-loader-VA4UREOM.js +2 -0
  57. package/dist/symphony-relay-2RHG25Z4.js +3 -0
  58. package/dist/sync-DLUBV5HQ.js +2 -0
  59. package/dist/{sync-llms-HL5PPW3M.js → sync-llms-7CAI74QL.js} +1 -1
  60. package/dist/team-NSP6PMPS.js +2 -0
  61. package/dist/tools-NNPANZRA.js +2 -0
  62. package/dist/university-content/courses/para-201.json +5 -5
  63. package/dist/university-content/courses/para-301.json +10 -10
  64. package/dist/university-content/courses/para-401.json +3 -3
  65. package/dist/university-content/courses/para-501.json +5 -5
  66. package/dist/university-content/courses/para-601.json +1 -1
  67. package/dist/university-content/plsat/v2.0.json +7 -7
  68. package/dist/university-content/plsat/v3.0.json +9 -9
  69. package/dist/university-content/reference.json +4 -4
  70. package/dist/{upgrade-B4IOLZYK.js → upgrade-GX56QE3C.js} +1 -1
  71. package/dist/{watch-LRM5XD46.js → watch-YCODNIET.js} +1 -1
  72. package/dist/workspace-MKSQN7B2.js +2 -0
  73. package/package.json +5 -1
  74. package/templates/paradigm/specs/context-tracking.md +4 -4
  75. package/dist/chunk-2Q7RGCJH.js +0 -3
  76. package/dist/chunk-73R63P7K.js +0 -2
  77. package/dist/chunk-76JPOBDH.js +0 -29
  78. package/dist/chunk-C7ZCCKJT.js +0 -3
  79. package/dist/chunk-CUOEZAVL.js +0 -8
  80. package/dist/chunk-LKFBDUCV.js +0 -11
  81. package/dist/chunk-S7K7UPXL.js +0 -3
  82. package/dist/chunk-UHQLYIRI.js +0 -3
  83. package/dist/chunk-USGKKAPL.js +0 -111
  84. package/dist/chunk-VZLGBGU3.js +0 -8
  85. package/dist/doctor-R4UGMR5N.js +0 -2
  86. package/dist/init-24MAQJFM.js +0 -2
  87. package/dist/reindex-HWRA7KDI.js +0 -2
  88. package/dist/session-tracker-WSTRV7UP.js +0 -2
  89. package/dist/symphony-43N4R6C2.js +0 -2
  90. package/dist/symphony-loader-XJT43FOS.js +0 -2
  91. package/dist/symphony-relay-CIMRXQHI.js +0 -3
  92. package/dist/sync-QRDSFETO.js +0 -2
  93. package/dist/team-WIJVWLII.js +0 -2
  94. package/dist/workspace-2ODL5WLY.js +0 -2
  95. /package/dist/{chunk-HXGYVS2N.js → chunk-BV5PRPLB.js} +0 -0
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-A7KFOJ2F.js';import'./chunk-TYWB5IQJ.js';import'./chunk-UDUHSHO4.js';import'./chunk-FYDRENK7.js';import'./chunk-HXGYVS2N.js';import'./chunk-AO7ZSRME.js';import'./chunk-SHD27BQX.js';import'./chunk-EKZDFEJW.js';import'./chunk-T6IDXUUA.js';import'./chunk-JIXHEBGK.js';import'./chunk-QT2LKB3P.js';import'./chunk-5TAVYPOV.js';import*as g from'path';import e from'chalk';async function u(n,s,r){let a=s?g.resolve(s):process.cwd();if(!n){r.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(e.red(`
2
+ import {b}from'./chunk-J6KWGCHN.js';import'./chunk-TYWB5IQJ.js';import'./chunk-ORDKEGII.js';import'./chunk-BV5PRPLB.js';import'./chunk-AO7ZSRME.js';import'./chunk-FYDRENK7.js';import'./chunk-EKZDFEJW.js';import'./chunk-SHD27BQX.js';import'./chunk-T6IDXUUA.js';import'./chunk-JIXHEBGK.js';import'./chunk-QT2LKB3P.js';import'./chunk-5TAVYPOV.js';import*as g from'path';import e from'chalk';async function u(n,s,r){let a=s?g.resolve(s):process.cwd();if(!n){r.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(e.red(`
3
3
  Orchestration ID required.`)),console.log(e.gray(`Usage: paradigm team accept <orchestration-id>
4
4
  `)));return}let l=new b(a),o=l.getOrchestration(n);if(!o){r.json?console.log(JSON.stringify({error:"Orchestration not found",id:n})):console.log(e.red(`
5
5
  Orchestration not found: ${n}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- export{p as buildProfileEnrichment,t as checkPathPermission,u as checkToolPermission,x as computeIntegrityHash,k as createAgentProfile,a as decayedConfidence,s as determineIntegrityStatus,w as enforcePermissions,g as findAgentsByNickname,v as getPermissionConstraints,c as isAgentActive,e as listAllGlobalAgentIds,f as loadAgentProfile,i as loadAllAgentProfiles,b as loadProjectRoster,o as mergeAgentProfileWithManifest,l as queryExpertise,h as resolveAgent,r as sanitizeForPrompt,j as saveAgentProfile,d as saveProjectRoster,q as syncExpertiseFromLore,n as updateExpertiseFromAssessment,m as updateExpertiseFromLore,y as verifyIntegrity}from'./chunk-C7ZCCKJT.js';import'./chunk-5TAVYPOV.js';
2
+ export{p as buildProfileEnrichment,t as checkPathPermission,u as checkToolPermission,x as computeIntegrityHash,k as createAgentProfile,a as decayedConfidence,s as determineIntegrityStatus,w as enforcePermissions,g as findAgentsByNickname,v as getPermissionConstraints,c as isAgentActive,e as listAllGlobalAgentIds,f as loadAgentProfile,i as loadAllAgentProfiles,b as loadProjectRoster,o as mergeAgentProfileWithManifest,l as queryExpertise,h as resolveAgent,r as sanitizeForPrompt,j as saveAgentProfile,d as saveProjectRoster,q as syncExpertiseFromLore,n as updateExpertiseFromAssessment,m as updateExpertiseFromLore,y as verifyIntegrity}from'./chunk-X3U3IGYT.js';import'./chunk-MBPLJKE5.js';import'./chunk-5TAVYPOV.js';
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import {z}from'./chunk-2Q7RGCJH.js';export{p as buildProfileEnrichment,t as checkPathPermission,u as checkToolPermission,x as computeIntegrityHash,k as createAgentProfile,a as decayedConfidence,s as determineIntegrityStatus,w as enforcePermissions,g as findAgentsByNickname,v as getPermissionConstraints,c as isAgentActive,e as listAllGlobalAgentIds,f as loadAgentProfile,i as loadAllAgentProfiles,b as loadProjectRoster,o as mergeAgentProfileWithManifest,l as queryExpertise,h as resolveAgent,r as sanitizeForPrompt,j as saveAgentProfile,d as saveProjectRoster,q as syncExpertiseFromLore,n as updateExpertiseFromAssessment,m as updateExpertiseFromLore,y as verifyIntegrity}from'./chunk-2Q7RGCJH.js';import'./chunk-5TAVYPOV.js';z();
2
+ import {z}from'./chunk-74SGKSRQ.js';export{p as buildProfileEnrichment,t as checkPathPermission,u as checkToolPermission,x as computeIntegrityHash,k as createAgentProfile,a as decayedConfidence,s as determineIntegrityStatus,w as enforcePermissions,g as findAgentsByNickname,v as getPermissionConstraints,c as isAgentActive,e as listAllGlobalAgentIds,f as loadAgentProfile,i as loadAllAgentProfiles,b as loadProjectRoster,o as mergeAgentProfileWithManifest,l as queryExpertise,h as resolveAgent,r as sanitizeForPrompt,j as saveAgentProfile,d as saveProjectRoster,q as syncExpertiseFromLore,n as updateExpertiseFromAssessment,m as updateExpertiseFromLore,y as verifyIntegrity}from'./chunk-74SGKSRQ.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-5TAVYPOV.js';z();
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import {f,p,i,c as c$1,j}from'./chunk-C7ZCCKJT.js';import {b as b$2}from'./chunk-32RBX5YV.js';import {b as b$3}from'./chunk-7SWEOPWF.js';import {c,b as b$1,d,a}from'./chunk-5TAVYPOV.js';import*as g from'fs';import*as b from'path';import*as R from'js-yaml';import*as Z from'os';var jt={};c(jt,{getJournalStats:()=>oe,loadAllJournalEntries:()=>ne,loadJournalEntries:()=>O,loadJournalEntry:()=>ee,recordJournalEntry:()=>z});function V(n){let t=process.env.HOME||process.env.USERPROFILE||"";return b.join(t,".paradigm","agents",n,"journal")}function te(){let n=new Date,t=n.toISOString().slice(0,10),e=n.toISOString().slice(11,19).replace(/:/g,""),o=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `LJ-${t}-${e}-${o}`}function z(n,t){let e=new Date,o=te(),r={id:o,agent:n,timestamp:e.toISOString(),...t},i=V(n);g.mkdirSync(i,{recursive:true});let s=b.join(i,`${o}.yaml`);return g.writeFileSync(s,R.dump(r,{lineWidth:120,noRefs:true}),"utf8"),r}function O(n,t){let e=V(n);if(!g.existsSync(e))return [];let o=[],r=g.readdirSync(e).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=g.readFileSync(b.join(e,s),"utf8"),c=R.load(a);c&&c.id&&o.push(c);}catch{}let i=o;return t?.trigger&&(i=i.filter(s=>s.trigger===t.trigger)),t?.project&&(i=i.filter(s=>s.project===t.project)),t?.transferable!==void 0&&(i=i.filter(s=>s.transferable===t.transferable)),t?.tag&&(i=i.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(i=i.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(i=i.filter(s=>s.timestamp<=t.dateTo)),i.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}function ee(n,t){let e=V(n),o=b.join(e,`${t}.yaml`);if(!g.existsSync(o))return null;let r=g.readFileSync(o,"utf8");return R.load(r)}function ne(n){let t=process.env.HOME||process.env.USERPROFILE||"",e=b.join(t,".paradigm","agents");if(!g.existsSync(e))return [];let o=[],r=g.readdirSync(e,{withFileTypes:true}).filter(i=>i.isDirectory());for(let i of r){if(n?.agent&&i.name!==n.agent)continue;let s=O(i.name,n);o.push(...s);}return o.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),n?.limit?o.slice(0,n.limit):o}function oe(n){let t=O(n),e={},o={},r=0;for(let i of t)e[i.trigger]=(e[i.trigger]||0)+1,o[i.project]=(o[i.project]||0)+1,i.transferable&&r++;return {total:t.length,byTrigger:e,byProject:o,transferableCount:r,recentInsights:t.slice(0,5).map(i=>({id:i.id,trigger:i.trigger,insight:i.insight.slice(0,200),timestamp:i.timestamp}))}}var K=b$1(()=>{});var Nt={};c(Nt,{addNotebookEntry:()=>xt,incrementApplied:()=>ae,loadNotebookEntries:()=>Dt,promoteFromLore:()=>se,searchNotebooks:()=>re});function Dt(n,t,e){let o=new Map,r=b.join(X,n);Et(r,o);let i=b.join(t,Y,n);Et(i,o);let s=Array.from(o.values());if(e?.concepts&&e.concepts.length>0){let a=new Set(e.concepts.map(c=>c.toLowerCase()));s=s.filter(c=>c.concepts.some(d=>a.has(d.toLowerCase())));}if(e?.tags&&e.tags.length>0){let a=new Set(e.tags.map(c=>c.toLowerCase()));s=s.filter(c=>c.tags.some(d=>a.has(d.toLowerCase())));}return s.sort((a,c)=>c.appliedCount-a.appliedCount)}function Et(n,t){if(g.existsSync(n))try{let e=g.readdirSync(n).filter(o=>o.startsWith(ie)&&o.endsWith(Q));for(let o of e)try{let r=g.readFileSync(b.join(n,o),"utf-8"),i=R.load(r);i?.id&&t.set(i.id,i);}catch{}}catch{}}function re(n,t,e){let o=Dt(n,e),r=t.toLowerCase();return o.filter(i=>i.context.toLowerCase().includes(r)||i.snippet.toLowerCase().includes(r)||i.concepts.some(s=>s.toLowerCase().includes(r))||i.tags.some(s=>s.toLowerCase().includes(r)))}function xt(n,t,e,o){let r=new Date().toISOString(),i=(t.concepts[0]||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),s=Date.now().toString(36),a=`nb-${i}-${s}`,c={...t,id:a,appliedCount:0,created:r,updated:r},d=e==="global"?b.join(X,n):b.join(o||process.cwd(),Y,n);g.existsSync(d)||g.mkdirSync(d,{recursive:true});let u=`${a}${Q}`,l=b.join(d,u),m=R.dump(c,{lineWidth:120,noRefs:true,sortKeys:false});return g.writeFileSync(l,m,"utf-8"),{entry:c,filePath:l}}async function se(n,t,e,o="global"){let{loadLoreEntry:r}=await import('./lore-loader-XY5MZRR2.js'),i=await r(e,t);if(!i)return null;let s=[];if(i.symbols_touched)for(let d of i.symbols_touched){let u=d.replace(/^[#$^!~]/,"").toLowerCase();s.push(u);}let a=i.summary||"";i.body&&(a+=`
2
+ import {f,p,i,c as c$1,j}from'./chunk-X3U3IGYT.js';import {b as b$2}from'./chunk-UNHTQLYO.js';import {b as b$3}from'./chunk-7SWEOPWF.js';import'./chunk-MBPLJKE5.js';import {c,b as b$1,d,a}from'./chunk-5TAVYPOV.js';import*as g from'fs';import*as b from'path';import*as R from'js-yaml';import*as Z from'os';var jt={};c(jt,{getJournalStats:()=>oe,loadAllJournalEntries:()=>ne,loadJournalEntries:()=>A,loadJournalEntry:()=>ee,recordJournalEntry:()=>K});function z(n){let t=process.env.HOME||process.env.USERPROFILE||"";return b.join(t,".paradigm","agents",n,"journal")}function te(){let n=new Date,t=n.toISOString().slice(0,10),e=n.toISOString().slice(11,19).replace(/:/g,""),o=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `LJ-${t}-${e}-${o}`}function K(n,t){let e=new Date,o=te(),r={id:o,agent:n,timestamp:e.toISOString(),...t},i=z(n);g.mkdirSync(i,{recursive:true});let s=b.join(i,`${o}.yaml`);return g.writeFileSync(s,R.dump(r,{lineWidth:120,noRefs:true}),"utf8"),r}function A(n,t){let e=z(n);if(!g.existsSync(e))return [];let o=[],r=g.readdirSync(e).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=g.readFileSync(b.join(e,s),"utf8"),c=R.load(a);c&&c.id&&o.push(c);}catch{}let i=o;return t?.trigger&&(i=i.filter(s=>s.trigger===t.trigger)),t?.project&&(i=i.filter(s=>s.project===t.project)),t?.transferable!==void 0&&(i=i.filter(s=>s.transferable===t.transferable)),t?.tag&&(i=i.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(i=i.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(i=i.filter(s=>s.timestamp<=t.dateTo)),i.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}function ee(n,t){let e=z(n),o=b.join(e,`${t}.yaml`);if(!g.existsSync(o))return null;let r=g.readFileSync(o,"utf8");return R.load(r)}function ne(n){let t=process.env.HOME||process.env.USERPROFILE||"",e=b.join(t,".paradigm","agents");if(!g.existsSync(e))return [];let o=[],r=g.readdirSync(e,{withFileTypes:true}).filter(i=>i.isDirectory());for(let i of r){if(n?.agent&&i.name!==n.agent)continue;let s=A(i.name,n);o.push(...s);}return o.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),n?.limit?o.slice(0,n.limit):o}function oe(n){let t=A(n),e={},o={},r=0;for(let i of t)e[i.trigger]=(e[i.trigger]||0)+1,o[i.project]=(o[i.project]||0)+1,i.transferable&&r++;return {total:t.length,byTrigger:e,byProject:o,transferableCount:r,recentInsights:t.slice(0,5).map(i=>({id:i.id,trigger:i.trigger,insight:i.insight.slice(0,200),timestamp:i.timestamp}))}}var V=b$1(()=>{});var Nt={};c(Nt,{addNotebookEntry:()=>xt,incrementApplied:()=>ae,loadNotebookEntries:()=>Dt,promoteFromLore:()=>se,searchNotebooks:()=>re});function Dt(n,t,e){let o=new Map,r=b.join(X,n);Et(r,o);let i=b.join(t,Y,n);Et(i,o);let s=Array.from(o.values());if(e?.concepts&&e.concepts.length>0){let a=new Set(e.concepts.map(c=>c.toLowerCase()));s=s.filter(c=>c.concepts.some(d=>a.has(d.toLowerCase())));}if(e?.tags&&e.tags.length>0){let a=new Set(e.tags.map(c=>c.toLowerCase()));s=s.filter(c=>c.tags.some(d=>a.has(d.toLowerCase())));}return s.sort((a,c)=>c.appliedCount-a.appliedCount)}function Et(n,t){if(g.existsSync(n))try{let e=g.readdirSync(n).filter(o=>o.startsWith(ie)&&o.endsWith(Q));for(let o of e)try{let r=g.readFileSync(b.join(n,o),"utf-8"),i=R.load(r);i?.id&&t.set(i.id,i);}catch{}}catch{}}function re(n,t,e){let o=Dt(n,e),r=t.toLowerCase();return o.filter(i=>i.context.toLowerCase().includes(r)||i.snippet.toLowerCase().includes(r)||i.concepts.some(s=>s.toLowerCase().includes(r))||i.tags.some(s=>s.toLowerCase().includes(r)))}function xt(n,t,e,o){let r=new Date().toISOString(),i=(t.concepts[0]||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),s=Date.now().toString(36),a=`nb-${i}-${s}`,c={...t,id:a,appliedCount:0,created:r,updated:r},d=e==="global"?b.join(X,n):b.join(o||process.cwd(),Y,n);g.existsSync(d)||g.mkdirSync(d,{recursive:true});let u=`${a}${Q}`,l=b.join(d,u),m=R.dump(c,{lineWidth:120,noRefs:true,sortKeys:false});return g.writeFileSync(l,m,"utf-8"),{entry:c,filePath:l}}async function se(n,t,e,o="global"){let{loadLoreEntry:r}=await import('./lore-loader-XY5MZRR2.js'),i=await r(e,t);if(!i)return null;let s=[];if(i.symbols_touched)for(let d of i.symbols_touched){let u=d.replace(/^[#$^!~]/,"").toLowerCase();s.push(u);}let a=i.summary||"";i.body&&(a+=`
3
3
 
4
- `+i.body);let c={source:"lore",loreEntryId:t,originProject:b.basename(e),createdBy:n};return xt(n,{context:i.title||`Promoted from ${t}`,snippet:a,provenance:c,confidence:i.confidence??.7,concepts:s,tags:i.tags||[]},o,e)}function ae(n,t,e){let o=b.join(e,Y,n),r=b.join(X,n);for(let i of [o,r]){let s=b.join(i,`${t}${Q}`);if(g.existsSync(s))try{let a=g.readFileSync(s,"utf-8"),c=R.load(a);if(c)return c.appliedCount=(c.appliedCount||0)+1,c.updated=new Date().toISOString(),g.writeFileSync(s,R.dump(c,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var X,Y,ie,Q,$t=b$1(()=>{X=b.join(Z.homedir(),".paradigm","notebooks"),Y=".paradigm/notebooks",ie="nb-",Q=".yaml";});var pt=".paradigm/events",zt="stream.jsonl",J=1e3,$=[];function yt(n){return b.join(n,pt,zt)}function Kt(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${n}-${t}`}function M(n,t){let e={id:Kt(),timestamp:new Date().toISOString(),...t};$.push(e),$.length>J&&($=$.slice(-J));try{let o=b.join(n,pt);g.mkdirSync(o,{recursive:!0});let r=yt(n);g.appendFileSync(r,JSON.stringify(e)+`
4
+ `+i.body);let c={source:"lore",loreEntryId:t,originProject:b.basename(e),createdBy:n};return xt(n,{context:i.title||`Promoted from ${t}`,snippet:a,provenance:c,confidence:i.confidence??.7,concepts:s,tags:i.tags||[]},o,e)}function ae(n,t,e){let o=b.join(e,Y,n),r=b.join(X,n);for(let i of [o,r]){let s=b.join(i,`${t}${Q}`);if(g.existsSync(s))try{let a=g.readFileSync(s,"utf-8"),c=R.load(a);if(c)return c.appliedCount=(c.appliedCount||0)+1,c.updated=new Date().toISOString(),g.writeFileSync(s,R.dump(c,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var X,Y,ie,Q,$t=b$1(()=>{X=b.join(Z.homedir(),".paradigm","notebooks"),Y=".paradigm/notebooks",ie="nb-",Q=".yaml";});var pt=".paradigm/events",Kt="stream.jsonl",J=1e3,$=[];function yt(n){return b.join(n,pt,Kt)}function Vt(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${n}-${t}`}function M(n,t){let e={id:Vt(),timestamp:new Date().toISOString(),...t};$.push(e),$.length>J&&($=$.slice(-J));try{let o=b.join(n,pt);g.mkdirSync(o,{recursive:!0});let r=yt(n);g.appendFileSync(r,JSON.stringify(e)+`
5
5
  `,"utf8"),Xt(r);}catch{}return e}function Xt(n){try{if(g.statSync(n).size>512*1024){let o=g.readFileSync(n,"utf8").trim().split(`
6
6
  `);if(o.length>J){let r=o.slice(-J);g.writeFileSync(n,r.join(`
7
7
  `)+`
@@ -17,19 +17,19 @@ import {f,p,i,c as c$1,j}from'./chunk-C7ZCCKJT.js';import {b as b$2}from'./chunk
17
17
  `).filter(s=>s.trim());if(o.length<=ge)return;let r=Date.now()-t,i=o.filter(s=>{try{let a=JSON.parse(s);return (a.timestamp?new Date(a.timestamp).getTime():Date.now())>=r}catch{return !0}});i.length<o.length&&g.writeFileSync(n,i.join(`
18
18
  `)+`
19
19
  `,"utf8");}catch{}}function E(n,t){let e=tt(n);if(!g.existsSync(e))return [];try{let r=g.readFileSync(e,"utf8").trim().split(`
20
- `).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 Ot(n){let t=et(n);if(!g.existsSync(t))return [];try{return g.readFileSync(t,"utf8").trim().split(`
21
- `).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return []}}function At(n,t,e,o){let r=tt(n);if(!g.existsSync(r))return false;try{let s=g.readFileSync(r,"utf8").trim().split(`
20
+ `).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 At(n){let t=et(n);if(!g.existsSync(t))return [];try{return g.readFileSync(t,"utf8").trim().split(`
21
+ `).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return []}}function Ot(n,t,e,o){let r=tt(n);if(!g.existsSync(r))return false;try{let s=g.readFileSync(r,"utf8").trim().split(`
22
22
  `),a=!1,c=s.map(d=>{try{let u=JSON.parse(d);return u.id===t?(u.engaged=!0,u.response=e,o&&(u.reason=o),a=!0,JSON.stringify(u)):d}catch{return d}});if(a&&(g.writeFileSync(r,c.join(`
23
23
  `)+`
24
24
  `,"utf8"),e==="accepted"||e==="dismissed")){let d=JSON.parse(s.find(l=>{try{return JSON.parse(l).id===t}catch{return !1}}));i(n).find(l=>l.id===d.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&M(n,{type:"work-completed",source:"agent-action",agent:d.agent,context:`Nomination ${t} ${e} \u2014 feedback for learning`,data:{nomination_id:t,response:e}});}return a}catch{return false}}function Ft(n,t,e,o){let r=et(n);if(!g.existsSync(r))return false;try{let s=g.readFileSync(r,"utf8").trim().split(`
25
25
  `),a=!1,c=s.map(d=>{try{let u=JSON.parse(d);if(u.id===t){u.resolution={chosen:e,reason:o,resolved_by:"human",resolved_at:new Date().toISOString()},a=!0;let l=u.nominations.filter(m=>m!==e);for(let m of l){let y=E(n).find(f=>f.id===m);y&&M(n,{type:"work-completed",source:"agent-action",agent:y.agent,context:`Debate ${t} resolved \u2014 nomination ${m} not chosen`,data:{debate_id:t,chosen:e,reason:o}});}return JSON.stringify(u)}return d}catch{return d}});return a&&g.writeFileSync(r,c.join(`
26
26
  `)+`
27
27
  `,"utf8"),a}catch{return false}}function It(n){let t=b.join(n,N,".last-processed"),e="";try{g.existsSync(t)&&(e=g.readFileSync(t,"utf8").trim());}catch{}let o=b.join(n,N,"stream.jsonl");if(!g.existsSync(o))return {processed:0,nominations:[]};let r=[];try{r=g.readFileSync(o,"utf8").trim().split(`
28
- `).filter(l=>l.trim()).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(l=>l!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(e){let u=r.findIndex(l=>l.id===e);u>=0&&(i=u+1);}let s=r.slice(i);if(s.length===0)return {processed:0,nominations:[]};let a=[],c=s.slice(0,50);for(let u of c){let{nominations:l}=he(n,u);a.push(...l);}let d=c[c.length-1];try{g.mkdirSync(b.join(n,N),{recursive:!0}),g.writeFileSync(t,d.id,"utf8");}catch{}return {processed:c.length,nominations:a}}function Ct(n,t){let e=f(n,t);if(!e?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let o=e.attention.threshold??.6,{nominationTtlDays:r}=H(n),i=r*24*60*60*1e3,c=E(n,{agent:t}).filter(j=>j.engaged||Date.now()-new Date(j.timestamp).getTime()<i).filter(j=>j.engaged);if(c.length<5)return {adjusted:false,oldThreshold:o,newThreshold:o,reason:`Insufficient data (${c.length}/5 engaged nominations)`};let d=c.filter(j=>j.response==="accepted").length,u=c.filter(j=>j.response==="dismissed").length,l=d/c.length,m=u/c.length,y=o,f$1="No adjustment needed";if(m>.6?(y=Math.min(.95,o+.05),f$1=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):l>.8&&(y=Math.max(.2,o-.05),f$1=`High accept rate (${(l*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),y===o)return {adjusted:false,oldThreshold:o,newThreshold:y,reason:f$1};e.attention.threshold=y;let p=b.join(n,".paradigm/agents",`${t}.agent`),x=g.existsSync(p)?"project":"global";return j(t,e,x,n),M(n,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${o.toFixed(2)} \u2192 ${y.toFixed(2)} (${f$1})`,data:{old_threshold:o,new_threshold:y,accept_rate:l,dismiss_rate:m}}),{adjusted:true,oldThreshold:o,newThreshold:y,reason:f$1}}function nt(n,t){let{nominationTtlDays:e}=H(n),o=e*24*60*60*1e3,i=E(n,{agent:t}).filter(l=>l.engaged||Date.now()-new Date(l.timestamp).getTime()<o),s=i.filter(l=>l.response==="accepted").length,a=i.filter(l=>l.response==="dismissed").length,c=i.filter(l=>l.response==="deferred").length,d=i.filter(l=>!l.engaged).length,u=s+a+c;return {total:i.length,accepted:s,dismissed:a,deferred:c,pending:d,acceptRate:u>0?s/u:0}}function Jt(n){let e=i(n).filter(l=>c$1(l.id,n)).map(l=>{let m=nt(n,l.id),y=0;try{let f=b.join(Z.homedir(),".paradigm","notebooks",l.id);g.existsSync(f)&&(y=g.readdirSync(f).filter(p=>p.endsWith(".yaml")).length);}catch{}return {id:l.id,acceptRate:m.acceptRate,threshold:l.attention?.threshold??.5,expertiseCount:(l.expertise||[]).length,notebookCount:y,transferableCount:(l.transferable||[]).length,totalNominations:m.total}}),o=e.length||1,r=e.reduce((l,m)=>l+m.acceptRate,0)/o,i$1=e.reduce((l,m)=>l+m.threshold,0)/o,s=e.reduce((l,m)=>l+m.expertiseCount,0),a=e.reduce((l,m)=>l+m.notebookCount,0),c=e.reduce((l,m)=>l+m.transferableCount,0),d=e.reduce((l,m)=>l+m.totalNominations,0),u;return d<10?u="cold-start":r<.5?u="accumulating":r<.7?u="calibrating":u="mature",{agents:e,aggregate:{avgAcceptRate:r,avgThreshold:i$1,totalExpertise:s,totalNotebooks:a,totalTransferable:c},healthStatus:u}}function ot(n,t){let e,o;try{let c=(K(),d(jt)),d$1=($t(),d(Nt));e=c.loadJournalEntries,o=d$1.addNotebookEntry;}catch{return {promoted:0,entries:[]}}let r=e(t,{trigger:"pattern_discovered",limit:100}),i=e(t,{trigger:"human_feedback",limit:100}),s=[...r,...i],a=[];for(let c of s)if(!c.promoted_to_notebook&&!((c.confidence_after??0)<.8))try{let{entry:d}=o(t,{context:c.pattern?.applies_when||c.insight.slice(0,80),snippet:c.pattern?.correct_approach||c.insight,concepts:c.tags||[c.pattern?.id||"learned-pattern"],provenance:{source:"journal-auto-promote",sourceId:c.id,createdBy:t}},"global",n);a.push({journalId:c.id,notebookId:d.id});try{let u=b.join(Z.homedir(),".paradigm","agents",t,"journal");if(g.existsSync(u)){let l=g.readdirSync(u).filter(m=>m.endsWith(".yaml"));for(let m of l){let y=b.join(u,m),f=g.readFileSync(y,"utf8");if(f.includes(c.id)){let p=f.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${d.id}"`);if(p===f){let x=f.trimEnd().split(`
28
+ `).filter(l=>l.trim()).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(l=>l!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(e){let u=r.findIndex(l=>l.id===e);u>=0&&(i=u+1);}let s=r.slice(i);if(s.length===0)return {processed:0,nominations:[]};let a=[],c=s.slice(0,50);for(let u of c){let{nominations:l}=he(n,u);a.push(...l);}let d=c[c.length-1];try{g.mkdirSync(b.join(n,N),{recursive:!0}),g.writeFileSync(t,d.id,"utf8");}catch{}return {processed:c.length,nominations:a}}function Ct(n,t){let e=f(n,t);if(!e?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let o=e.attention.threshold??.6,{nominationTtlDays:r}=H(n),i=r*24*60*60*1e3,c=E(n,{agent:t}).filter(j=>j.engaged||Date.now()-new Date(j.timestamp).getTime()<i).filter(j=>j.engaged);if(c.length<5)return {adjusted:false,oldThreshold:o,newThreshold:o,reason:`Insufficient data (${c.length}/5 engaged nominations)`};let d=c.filter(j=>j.response==="accepted").length,u=c.filter(j=>j.response==="dismissed").length,l=d/c.length,m=u/c.length,y=o,f$1="No adjustment needed";if(m>.6?(y=Math.min(.95,o+.05),f$1=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):l>.8&&(y=Math.max(.2,o-.05),f$1=`High accept rate (${(l*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),y===o)return {adjusted:false,oldThreshold:o,newThreshold:y,reason:f$1};e.attention.threshold=y;let p=b.join(n,".paradigm/agents",`${t}.agent`),x=g.existsSync(p)?"project":"global";return j(t,e,x,n),M(n,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${o.toFixed(2)} \u2192 ${y.toFixed(2)} (${f$1})`,data:{old_threshold:o,new_threshold:y,accept_rate:l,dismiss_rate:m}}),{adjusted:true,oldThreshold:o,newThreshold:y,reason:f$1}}function nt(n,t){let{nominationTtlDays:e}=H(n),o=e*24*60*60*1e3,i=E(n,{agent:t}).filter(l=>l.engaged||Date.now()-new Date(l.timestamp).getTime()<o),s=i.filter(l=>l.response==="accepted").length,a=i.filter(l=>l.response==="dismissed").length,c=i.filter(l=>l.response==="deferred").length,d=i.filter(l=>!l.engaged).length,u=s+a+c;return {total:i.length,accepted:s,dismissed:a,deferred:c,pending:d,acceptRate:u>0?s/u:0}}function Jt(n){let e=i(n).filter(l=>c$1(l.id,n)).map(l=>{let m=nt(n,l.id),y=0;try{let f=b.join(Z.homedir(),".paradigm","notebooks",l.id);g.existsSync(f)&&(y=g.readdirSync(f).filter(p=>p.endsWith(".yaml")).length);}catch{}return {id:l.id,acceptRate:m.acceptRate,threshold:l.attention?.threshold??.5,expertiseCount:(l.expertise||[]).length,notebookCount:y,transferableCount:(l.transferable||[]).length,totalNominations:m.total}}),o=e.length||1,r=e.reduce((l,m)=>l+m.acceptRate,0)/o,i$1=e.reduce((l,m)=>l+m.threshold,0)/o,s=e.reduce((l,m)=>l+m.expertiseCount,0),a=e.reduce((l,m)=>l+m.notebookCount,0),c=e.reduce((l,m)=>l+m.transferableCount,0),d=e.reduce((l,m)=>l+m.totalNominations,0),u;return d<10?u="cold-start":r<.5?u="accumulating":r<.7?u="calibrating":u="mature",{agents:e,aggregate:{avgAcceptRate:r,avgThreshold:i$1,totalExpertise:s,totalNotebooks:a,totalTransferable:c},healthStatus:u}}function ot(n,t){let e,o;try{let c=(V(),d(jt)),d$1=($t(),d(Nt));e=c.loadJournalEntries,o=d$1.addNotebookEntry;}catch{return {promoted:0,entries:[]}}let r=e(t,{trigger:"pattern_discovered",limit:100}),i=e(t,{trigger:"human_feedback",limit:100}),s=[...r,...i],a=[];for(let c of s)if(!c.promoted_to_notebook&&!((c.confidence_after??0)<.8))try{let{entry:d}=o(t,{context:c.pattern?.applies_when||c.insight.slice(0,80),snippet:c.pattern?.correct_approach||c.insight,concepts:c.tags||[c.pattern?.id||"learned-pattern"],provenance:{source:"journal-auto-promote",sourceId:c.id,createdBy:t}},"global",n);a.push({journalId:c.id,notebookId:d.id});try{let u=b.join(Z.homedir(),".paradigm","agents",t,"journal");if(g.existsSync(u)){let l=g.readdirSync(u).filter(m=>m.endsWith(".yaml"));for(let m of l){let y=b.join(u,m),f=g.readFileSync(y,"utf8");if(f.includes(c.id)){let p=f.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${d.id}"`);if(p===f){let x=f.trimEnd().split(`
29
29
  `);x.push(`promoted_to_notebook: "${d.id}"`),g.writeFileSync(y,x.join(`
30
30
  `)+`
31
- `,"utf8");}else g.writeFileSync(y,p,"utf8");break}}}}catch{}}catch{}return {promoted:a.length,entries:a}}var je=".paradigm/surfacing.yaml";function Mt(n){let t=b.join(n,je),e={default_min_urgency:"low",enable_debates:true};if(!g.existsSync(t))return e;try{let o=a("js-yaml"),r=g.readFileSync(t,"utf8"),i=o.load(r);return {...e,...i}}catch{return e}}function Lt(n,t){let e={critical:0,high:1,medium:2,low:3},o=e[t.default_min_urgency||"low"]??3;return n.filter(r=>{let i=e[r.urgency]??3;if(t.preferences){let s=t.preferences.find(a=>a.agent===r.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(c=>r.urgency===c||r.type===c))return false;if(s.min_urgency){let a=e[s.min_urgency]??3;return i<=a}}}return i<=o})}var Ee=".paradigm/decisions";function Ht(n,t){let e=b.join(n,Ee);if(!g.existsSync(e))return [];let o=[],r=g.readdirSync(e).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=g.readFileSync(b.join(e,s),"utf8"),c=R.load(a);c&&c.id&&o.push(c);}catch{}let i=o;return (i=i.filter(s=>s.status===t.status)),t?.participant&&(i=i.filter(s=>s.participants.some(a=>a.id===t.participant))),t?.symbol&&(i=i.filter(s=>s.symbols_affected?.includes(t.symbol))),t?.tag&&(i=i.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(i=i.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(i=i.filter(s=>s.timestamp<=t.dateTo)),i.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}K();function Ge(){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_neverland",description:"Neverland Validation \u2014 aggregate learning metrics across all agents. Shows acceptance rates, threshold drift, expertise growth, notebook counts, cross-project transfer, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature). ~200 tokens.",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 ke(n){let t=Date.now(),e=n.match(/^(\d+)(m|h|d)$/);if(e){let o=parseInt(e[1],10),r=e[2],i=r==="m"?o*6e4:r==="h"?o*36e5:o*864e5;return new Date(t-i).toISOString()}return n}async function Ve(n,t,e){let o=r=>JSON.stringify(r,null,2);switch(n){case "paradigm_ambient_nominations":{It(e.rootDir);let i=t.pending_only!==false,s=t.limit||20,a=E(e.rootDir,{agent:t.agent,urgency:t.urgency,pending_only:i,limit:s+20}),c=Mt(e.rootDir);a=Lt(a,c).slice(0,s);let d=b.join(e.rootDir,".paradigm/events/nominations.jsonl");if(g.existsSync(d))try{let l=g.readFileSync(d,"utf8"),m=new Set(a.map(f=>f.id)),y=l.trim().split(`
31
+ `,"utf8");}else g.writeFileSync(y,p,"utf8");break}}}}catch{}}catch{}return {promoted:a.length,entries:a}}var je=".paradigm/surfacing.yaml";function Mt(n){let t=b.join(n,je),e={default_min_urgency:"low",enable_debates:true};if(!g.existsSync(t))return e;try{let o=a("js-yaml"),r=g.readFileSync(t,"utf8"),i=o.load(r);return {...e,...i}}catch{return e}}function Lt(n,t){let e={critical:0,high:1,medium:2,low:3},o=e[t.default_min_urgency||"low"]??3;return n.filter(r=>{let i=e[r.urgency]??3;if(t.preferences){let s=t.preferences.find(a=>a.agent===r.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(c=>r.urgency===c||r.type===c))return false;if(s.min_urgency){let a=e[s.min_urgency]??3;return i<=a}}}return i<=o})}var Ee=".paradigm/decisions";function Ht(n,t){let e=b.join(n,Ee);if(!g.existsSync(e))return [];let o=[],r=g.readdirSync(e).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=g.readFileSync(b.join(e,s),"utf8"),c=R.load(a);c&&c.id&&o.push(c);}catch{}let i=o;return (i=i.filter(s=>s.status===t.status)),t?.participant&&(i=i.filter(s=>s.participants.some(a=>a.id===t.participant))),t?.symbol&&(i=i.filter(s=>s.symbols_affected?.includes(t.symbol))),t?.tag&&(i=i.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(i=i.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(i=i.filter(s=>s.timestamp<=t.dateTo)),i.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}V();function Ge(){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 ke(n){let t=Date.now(),e=n.match(/^(\d+)(m|h|d)$/);if(e){let o=parseInt(e[1],10),r=e[2],i=r==="m"?o*6e4:r==="h"?o*36e5:o*864e5;return new Date(t-i).toISOString()}return n}async function ze(n,t,e){let o=r=>JSON.stringify(r,null,2);switch(n){case "paradigm_ambient_nominations":{It(e.rootDir);let i=t.pending_only!==false,s=t.limit||20,a=E(e.rootDir,{agent:t.agent,urgency:t.urgency,pending_only:i,limit:s+20}),c=Mt(e.rootDir);a=Lt(a,c).slice(0,s);let d=b.join(e.rootDir,".paradigm/events/nominations.jsonl");if(g.existsSync(d))try{let l=g.readFileSync(d,"utf8"),m=new Set(a.map(f=>f.id)),y=l.trim().split(`
32
32
  `).map(f=>{try{let p=JSON.parse(f);return m.has(p.id)?(p.surfaced=!0,JSON.stringify(p)):f}catch{return f}});g.writeFileSync(d,y.join(`
33
33
  `)+`
34
- `,"utf8");}catch{}let u={count:a.length,nominations:a.map(l=>({id:l.id,agent:l.agent,urgency:l.urgency,type:l.type,brief:l.brief,relevance:l.relevance,timestamp:l.timestamp,engaged:l.engaged,response:l.response}))};if(t.include_debates){let m=Ot(e.rootDir).filter(y=>!y.resolution);u.debates=m.map(y=>({id:y.id,topic:y.topic,type:y.type,nominations:y.nominations})),u.debate_count=m.length;}return {text:o(u),handled:true}}case "paradigm_ambient_events":{let r=t.since?ke(t.since):void 0,i=t.limit||50,s=ht(e.rootDir,{type:t.type,source:t.source,symbol:t.symbol,agent:t.agent,since:r,limit:i});return {text:o({count:s.length,events:s.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let r=t.nomination_id,i=t.response,s=t.reason,a=At(e.rootDir,r,i,s);if(a)try{let{appendSessionWorkEntry:d}=await import('./session-work-log-5UJTJJ22.js'),l=E(e.rootDir,{limit:500}).find(m=>m.id===r);d(e.rootDir,{timestamp:new Date().toISOString(),type:"user-verdict",agent:l?.agent,nominationId:r,verdict:i,reason:s});}catch{}let c=false;return t.resolve_debate&&a&&(c=Ft(e.rootDir,t.resolve_debate,r,t.reason)),{text:o({engaged:a,nomination_id:r,response:i,debate_resolved:c||void 0}),handled:true}}case "paradigm_context_compose":{let r=t.agent,i=t.symbols||[],s=t.include_nominations!==false,a=t.include_decisions!==false,c=t.include_journal!==false,d=t.max_decisions||5,u=t.max_journal||5,l=f(e.rootDir,r);if(!l)return {text:o({error:`Agent profile not found: ${r}`}),handled:true};let m=[],y=p(l,i);if(y.trim()&&m.push(y),a){let f=Ht(e.rootDir,{status:"active",limit:d});if(f.length>0){m.push("## Recent Team Decisions");for(let p of f)m.push(`- **${p.title}**: ${p.decision.slice(0,150)}${p.decision.length>150?"...":""}`);m.push("");}}if(c){let f=O(r,{transferable:true,limit:u});if(f.length>0){m.push("## Transferable Insights");for(let p of f)m.push(`- [${p.trigger}] ${p.insight.slice(0,150)}${p.insight.length>150?"...":""}`);m.push("");}}if(s){let f=E(e.rootDir,{pending_only:true,limit:10});if(f.length>0){m.push("## Pending Nominations");for(let p of f)m.push(`- [${p.urgency}] ${p.brief}`);m.push("");}}return {text:o({agent:r,context:m.join(`
35
- `),sections_included:{profile:true,decisions:a,journal:c,nominations:s}}),handled:true}}case "paradigm_ambient_promote":{let r=t.agent,i=ot(e.rootDir,r);return {text:o({agent:r,promoted:i.promoted,entries:i.entries}),handled:true}}case "paradigm_ambient_learn":{let r=t.agent,i=t.dry_run===true,s=nt(e.rootDir,r);if(i)return {text:o({agent:r,dry_run:true,stats:s,note:s.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(s.acceptRate*100).toFixed(0)}% \u2014 ${s.acceptRate>.8?"would lower threshold":s.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=Ct(e.rootDir,r);return {text:o({agent:r,...a,stats:s}),handled:true}}case "paradigm_ambient_neverland":{let r=Jt(e.rootDir);return {text:o(r),handled:true}}case "paradigm_ambient_learn_postflight":return {text:o(await Ne(e.rootDir,t)),handled:true};default:return {text:`Unknown ambient tool: ${n}`,handled:false}}}var De={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function xe(n){try{let t=b.join(n,".paradigm","config.yaml");if(g.existsSync(t)){let o=g.readFileSync(t,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(o)return o[1].trim()}}catch{}return b.basename(n)}async function Ne(n,t={}){let e=t.dry_run===true,o=xe(n),r=b$2(n),i=r.filter(f=>f.type==="user-verdict"&&f.verdict&&f.agent);if(i.length===0)return {sessionEntries:r.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:e,details:[]};let s=new Map;for(let f of i){let p=f.agent;s.has(p)||s.set(p,[]),s.get(p).push(f);}let a=r.filter(f=>f.type==="agent-contribution"),c=new Map;for(let f of a)f.agent&&(c.has(f.agent)||c.set(f.agent,[]),c.get(f.agent).push(f));let d=[],u={},l=0;for(let[f,p]of s){u[f]=0;let x=p.filter(h=>h.verdict==="accepted").length;p.filter(h=>h.verdict==="dismissed").length;p.filter(h=>h.verdict==="revised").length;let U=p.length,Bt=U>0?x/U:0;for(let h of p){let B=De[h.verdict];if(!B)continue;let Wt=c.get(f)?.shift(),st=$e(h,Wt,{acceptRate:Bt,total:U,accepted:x}),qt=h.verdict==="accepted"?.85:h.verdict==="revised"?.6:.4,Gt={agent:f,verdict:h.verdict,trigger:B,insight:st,symbols:h.symbols};if(d.push(Gt),e)u[f]++,l++;else try{z(f,{trigger:B,insight:st,confidence_before:h.verdict==="accepted"?.7:.8,confidence_after:qt,project:o,transferable:h.verdict==="dismissed",tags:["postflight",`verdict:${h.verdict}`,...(h.symbols||[]).map(Vt=>`symbol:${Vt}`)]}),u[f]++,l++;}catch{}}}let m={},y=0;if(!e)for(let f of s.keys())try{let p=ot(n,f);p.promoted>0&&(m[f]=p.promoted,y+=p.promoted);}catch{}return {sessionEntries:r.length,agentsProcessed:Array.from(s.keys()),journalsWritten:l,journalsByAgent:u,promoted:y,promotedByAgent:m,dryRun:e,details:d}}function $e(n,t,e){let o=n.symbols?.length?` (symbols: ${n.symbols.join(", ")})`:"",r=n.reason?` Reason: ${n.reason}.`:"";switch(n.verdict){case "accepted":return `Contribution accepted by user${o}.${r}`+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;case "dismissed":return `Contribution dismissed by user${o}.${r}`+(t?.contribution?` Rejected contribution: "${t.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;case "revised":return `Contribution revised by user${o}.${r}`+(n.revisionDelta?` Delta: "${n.revisionDelta.slice(0,120)}".`:"")+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;default:return `Unknown verdict "${n.verdict}"${o}.${r}`}}export{Ge as getAmbientToolsList,Ve as handleAmbientTool,Ne as runPostflightLearning};
34
+ `,"utf8");}catch{}let u={count:a.length,nominations:a.map(l=>({id:l.id,agent:l.agent,urgency:l.urgency,type:l.type,brief:l.brief,relevance:l.relevance,timestamp:l.timestamp,engaged:l.engaged,response:l.response}))};if(t.include_debates){let m=At(e.rootDir).filter(y=>!y.resolution);u.debates=m.map(y=>({id:y.id,topic:y.topic,type:y.type,nominations:y.nominations})),u.debate_count=m.length;}return {text:o(u),handled:true}}case "paradigm_ambient_events":{let r=t.since?ke(t.since):void 0,i=t.limit||50,s=ht(e.rootDir,{type:t.type,source:t.source,symbol:t.symbol,agent:t.agent,since:r,limit:i});return {text:o({count:s.length,events:s.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let r=t.nomination_id,i=t.response,s=t.reason,a=Ot(e.rootDir,r,i,s);if(a)try{let{appendSessionWorkEntry:d}=await import('./session-work-log-NQA7WJEC.js'),l=E(e.rootDir,{limit:500}).find(m=>m.id===r);d(e.rootDir,{timestamp:new Date().toISOString(),type:"user-verdict",agent:l?.agent,nominationId:r,verdict:i,reason:s});}catch{}let c=false;return t.resolve_debate&&a&&(c=Ft(e.rootDir,t.resolve_debate,r,t.reason)),{text:o({engaged:a,nomination_id:r,response:i,debate_resolved:c||void 0}),handled:true}}case "paradigm_context_compose":{let r=t.agent,i=t.symbols||[],s=t.include_nominations!==false,a=t.include_decisions!==false,c=t.include_journal!==false,d=t.max_decisions||5,u=t.max_journal||5,l=f(e.rootDir,r);if(!l)return {text:o({error:`Agent profile not found: ${r}`}),handled:true};let m=[],y=p(l,i);if(y.trim()&&m.push(y),a){let f=Ht(e.rootDir,{status:"active",limit:d});if(f.length>0){m.push("## Recent Team Decisions");for(let p of f)m.push(`- **${p.title}**: ${p.decision.slice(0,150)}${p.decision.length>150?"...":""}`);m.push("");}}if(c){let f=A(r,{transferable:true,limit:u});if(f.length>0){m.push("## Transferable Insights");for(let p of f)m.push(`- [${p.trigger}] ${p.insight.slice(0,150)}${p.insight.length>150?"...":""}`);m.push("");}}if(s){let f=E(e.rootDir,{pending_only:true,limit:10});if(f.length>0){m.push("## Pending Nominations");for(let p of f)m.push(`- [${p.urgency}] ${p.brief}`);m.push("");}}return {text:o({agent:r,context:m.join(`
35
+ `),sections_included:{profile:true,decisions:a,journal:c,nominations:s}}),handled:true}}case "paradigm_ambient_promote":{let r=t.agent,i=ot(e.rootDir,r);return {text:o({agent:r,promoted:i.promoted,entries:i.entries}),handled:true}}case "paradigm_ambient_learn":{let r=t.agent,i=t.dry_run===true,s=nt(e.rootDir,r);if(i)return {text:o({agent:r,dry_run:true,stats:s,note:s.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(s.acceptRate*100).toFixed(0)}% \u2014 ${s.acceptRate>.8?"would lower threshold":s.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=Ct(e.rootDir,r);return {text:o({agent:r,...a,stats:s}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let r=Jt(e.rootDir);return {text:o(r),handled:true}}case "paradigm_ambient_learn_postflight":return {text:o(await Ne(e.rootDir,t)),handled:true};default:return {text:`Unknown ambient tool: ${n}`,handled:false}}}var De={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function xe(n){try{let t=b.join(n,".paradigm","config.yaml");if(g.existsSync(t)){let o=g.readFileSync(t,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(o)return o[1].trim()}}catch{}return b.basename(n)}async function Ne(n,t={}){let e=t.dry_run===true,o=xe(n),r=b$2(n),i=r.filter(f=>f.type==="user-verdict"&&f.verdict&&f.agent);if(i.length===0)return {sessionEntries:r.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:e,details:[]};let s=new Map;for(let f of i){let p=f.agent;s.has(p)||s.set(p,[]),s.get(p).push(f);}let a=r.filter(f=>f.type==="agent-contribution"),c=new Map;for(let f of a)f.agent&&(c.has(f.agent)||c.set(f.agent,[]),c.get(f.agent).push(f));let d=[],u={},l=0;for(let[f,p]of s){u[f]=0;let x=p.filter(h=>h.verdict==="accepted").length;p.filter(h=>h.verdict==="dismissed").length;p.filter(h=>h.verdict==="revised").length;let U=p.length,Bt=U>0?x/U:0;for(let h of p){let B=De[h.verdict];if(!B)continue;let Wt=c.get(f)?.shift(),st=$e(h,Wt,{acceptRate:Bt,total:U,accepted:x}),qt=h.verdict==="accepted"?.85:h.verdict==="revised"?.6:.4,Gt={agent:f,verdict:h.verdict,trigger:B,insight:st,symbols:h.symbols};if(d.push(Gt),e)u[f]++,l++;else try{K(f,{trigger:B,insight:st,confidence_before:h.verdict==="accepted"?.7:.8,confidence_after:qt,project:o,transferable:h.verdict==="dismissed",tags:["postflight",`verdict:${h.verdict}`,...(h.symbols||[]).map(zt=>`symbol:${zt}`)]}),u[f]++,l++;}catch{}}}let m={},y=0;if(!e)for(let f of s.keys())try{let p=ot(n,f);p.promoted>0&&(m[f]=p.promoted,y+=p.promoted);}catch{}return {sessionEntries:r.length,agentsProcessed:Array.from(s.keys()),journalsWritten:l,journalsByAgent:u,promoted:y,promotedByAgent:m,dryRun:e,details:d}}function $e(n,t,e){let o=n.symbols?.length?` (symbols: ${n.symbols.join(", ")})`:"",r=n.reason?` Reason: ${n.reason}.`:"";switch(n.verdict){case "accepted":return `Contribution accepted by user${o}.${r}`+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;case "dismissed":return `Contribution dismissed by user${o}.${r}`+(t?.contribution?` Rejected contribution: "${t.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;case "revised":return `Contribution revised by user${o}.${r}`+(n.revisionDelta?` Delta: "${n.revisionDelta.slice(0,120)}".`:"")+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;default:return `Unknown verdict "${n.verdict}"${o}.${r}`}}export{Ge as getAmbientToolsList,ze as handleAmbientTool,Ne as runPostflightLearning};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {b}from'./chunk-5TAVYPOV.js';var n,r,t=b(()=>{n=["gap_narrations","cost_data","health_status","execution_metrics"],r={version:"1.0",default_ring:"project-locked",observation:{allow:["src/**",".paradigm/**","portal.yaml"],deny:[".env*","**/*.key","**/*.pem","**/secrets/**"]},streams:{work_log:{ring:"project-locked",allow_content:["file_paths","symbol_names","outcome"],deny_content:["code_snippets","file_contents","diff_content","gap_narrations"]},learning_journal:{ring:"user-scoped",allow_content:["pattern_descriptions","confidence_adjustments","approach_descriptions"],deny_content:["code_snippets","file_contents","symbol_names_with_context","gap_narrations","cost_data","health_status","execution_metrics"],redaction:[{pattern:"\\b[A-Z_]{2,}_KEY\\b"},{pattern:"password|secret|token"}]},team_decisions:{ring:"project-locked",allow_content:["rationale","alternatives","symbol_references"],deny_content:["implementation_details","gap_narrations","cost_data","health_status","execution_metrics"]}},upstream:{ring:"creator-upstream",allowed:["task_type","outcome","helpfulness","duration_bucket","error_category"],denied:["code_of_any_kind","file_paths","symbol_names","conversation_content","user_identity"]},network:{ring:"network-public",opt_in:false,if_opted_in:["aggregated_task_success_rates","anonymized_pattern_frequency"]}};});export{n as a,r as b,t as c};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {d,f,b,a as a$1,g,c,e as e$1,h}from'./chunk-HMQ5BHP2.js';import {a}from'./chunk-LKAT7IAK.js';import*as S from'path';import e from'chalk';import M from'ora';async function q(b$1,a$2){let i=process.cwd(),r=M(),x=a$2.target||b$1,o=a$2.quiet;o||console.log(e.blue(`
2
+ import {d,f,b,a as a$1,g,c,e as e$1,h}from'./chunk-DOCDDDTD.js';import {a}from'./chunk-LKAT7IAK.js';import*as S from'path';import e from'chalk';import M from'ora';async function q(b$1,a$2){let i=process.cwd(),r=M(),x=a$2.target||b$1,o=a$2.quiet;o||console.log(e.blue(`
3
3
  \u{1F504} Paradigm Sync
4
4
  `)),o||r.start("Loading .paradigm/ configuration...");let f$1=d(i);if(!f$1)throw o||(r.fail("No .paradigm/ directory found"),console.log(e.gray("\nRun `paradigm init` to initialize Paradigm in this project.\n"))),a.command("sync").error("Missing .paradigm/ directory"),o||process.exit(1),new Error("No .paradigm/ directory found");if(o||r.succeed(`Loaded configuration for ${e.cyan(f$1.projectName)}`),a.command("sync").debug("Configuration loaded",{projectName:f$1.projectName}),a$2.all){console.log(e.gray(`
5
5
  Syncing to all IDEs...
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+ import {c,b as b$1}from'./chunk-3KVVC4WV.js';import {z as z$1,i,c as c$1,f,j}from'./chunk-74SGKSRQ.js';import {g as g$1,f as f$1}from'./chunk-QGZRM6ZB.js';import {g as g$2,f as f$2}from'./chunk-VG7FN2TU.js';import {b,a,d as d$1}from'./chunk-5TAVYPOV.js';import*as d from'fs';import*as g from'path';import*as W from'js-yaml';import*as T from'os';function Y(e){return g.join(e,G,at)}function ct(){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:ct(),timestamp:new Date().toISOString(),...t};_.push(n),_.length>v&&(_=_.slice(-v));try{let r=g.join(e,G);d.mkdirSync(r,{recursive:!0});let o=Y(e);d.appendFileSync(o,JSON.stringify(n)+`
3
+ `,"utf8"),lt(o);}catch{}return n}function lt(e){try{if(d.statSync(e).size>512*1024){let r=d.readFileSync(e,"utf8").trim().split(`
4
+ `);if(r.length>v){let o=r.slice(-v);d.writeFileSync(e,o.join(`
5
+ `)+`
6
+ `,"utf8");}}}catch{}}function $t(e,t){let n=ft(e);return t?.type&&(n=n.filter(r=>r.type===t.type)),t?.source&&(n=n.filter(r=>r.source===t.source)),t?.symbol&&(n=n.filter(r=>r.symbols?.includes(t.symbol))),t?.agent&&(n=n.filter(r=>r.agent===t.agent)),t?.since&&(n=n.filter(r=>r.timestamp>=t.since)),n.sort((r,o)=>o.timestamp.localeCompare(r.timestamp)),t?.limit&&(n=n.slice(0,t.limit)),n}function ft(e){let t=Y(e);if(!d.existsSync(t))return [..._];try{return d.readFileSync(t,"utf8").trim().split(`
7
+ `).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return [..._]}}function H(e,t,n){let r=0,o=0,i=0,a=0;if(n.symbols?.length&&e.symbols?.length)for(let l of n.symbols)for(let s of e.symbols)B(l,s)&&(r=Math.max(r,1));if(n.paths?.length&&e.path){for(let l of n.paths)if(B(l,e.path)){o=1;break}}if(n.concepts?.length){let l=[e.context||"",...e.keywords||[],e.type].join(" ").toLowerCase(),s=0;for(let m of n.concepts)l.includes(m.toLowerCase())&&s++;n.concepts.length>0&&(i=s/n.concepts.length);}if(n.signals?.length){for(let l of n.signals)if(l.type===e.type){a=1;break}}let u=[r,o,i,a].sort((l,s)=>s-l),c=u[0]*.5+u[1]*.2+u[2]*.15+u[3]*.15,f=n.threshold??.6;return {agentId:t,score:c,breakdown:{symbolMatch:r,pathMatch:o,conceptMatch:i,signalMatch:a},shouldNominate:c>=f,quietReason:c<f?"below-threshold":void 0}}function B(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 G,at,v,_,z=b(()=>{G=".paradigm/events",at="stream.jsonl",v=1e3,_=[];});function O(e){let t=g.join(e,dt);if(!d.existsSync(t))return {...b$1};try{let n=d.readFileSync(t,"utf8"),r=W.load(n);return ut(b$1,r)}catch{return {...b$1}}}function ut(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((r,o,i)=>i.indexOf(r)===o)}),t.streams){n.streams={...e.streams};for(let r of ["work_log","learning_journal","team_decisions"])t.streams[r]&&(n.streams[r]={...e.streams?.[r],...t.streams[r],deny_content:[...e.streams?.[r]?.deny_content||[],...t.streams[r]?.deny_content||[]].filter((o,i,a)=>a.indexOf(o)===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 C(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(o=>R(o,t))||e.observation?.deny?.some(r=>R(r,t))?false:e.observation?.allow?.length?e.observation.allow.some(r=>R(r,t)):true}function Ct(e,t,n){let r=t.streams?.[n];if(!r)return {filtered:e,redacted:[]};let o=[],i=e;if(r.redaction)for(let a of r.redaction)try{let u=new RegExp(a.pattern,"gi"),c=i.match(u);c&&(o.push(...c),i=i.replace(u,a.replacement||"[REDACTED]"));}catch{}return {filtered:i,redacted:o}}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 dt,X=b(()=>{c();dt=".paradigm/data-policy.yaml";});function wt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function _t(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${e}-${t}`}function Q(e,t){let n=i(e),r=O(e),o=[];for(let f of n){if(!f.attention||!c$1(f.id,e)||t.path&&!C(r,t.path,f.id))continue;let l=H(t,f.id,f.attention);l.shouldNominate&&o.push({profile:f,score:l});}if(o.length===0)return {nominations:[],debates:[]};let i$1=P(e,{since:new Date(Date.now()-3e4).toISOString()}),a=o.filter(({profile:f})=>!i$1.find(s=>s.agent===f.id&&s.brief===K(f,t,{...o.find(m=>m.profile.id===f.id).score})));if(a.length===0)return {nominations:[],debates:[]};let u=a.map(({profile:f,score:l})=>{let s=Et(t,l),m=Nt(f,t);return {id:wt(),agent:f.id,relevance:l.score,urgency:s,type:m,brief:K(f,t,l),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});xt(e,u);let c=kt(e,u);return c.length>0&&vt(e,c),{nominations:u,debates:c}}function Et(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 Nt(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 K(e,t,n){let r=e.role||e.id;switch(t.type){case "gate-checked":return `${r}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${r}: ${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 `${r}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${r}: New route ${t.symbols?.join(", ")||""} \u2014 ${e.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${r}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${e.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${r}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${r}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${r}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let o=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 `${r}: ${o}`}}}function kt(e,t){if(t.length<2)return [];let n=[],r=new Map;for(let o of t)for(let i of o.triggered_by){let a=r.get(i)||[];a.push(o),r.set(i,a);}for(let[o,i]of r){if(i.length<2||new Set(i.map(f=>f.agent)).size<2)continue;let u=new Set(i.map(f=>f.type)),c=u.size>1&&u.has("warning")&&u.has("suggestion");n.push({id:_t(),topic:`Multiple agents responded to event ${o}`,nominations:i.map(f=>f.id),type:c?"conflicting":"complementary",overlap_events:[o]});}return n}function M(e){return g.join(e,S,mt)}function I(e){return g.join(e,S,gt)}function xt(e,t){try{let n=g.join(e,S);d.mkdirSync(n,{recursive:!0});let r=M(e),o=t.map(a=>JSON.stringify(a)).join(`
8
+ `)+`
9
+ `;d.appendFileSync(r,o,"utf8"),Z(r,pt);let{nominationTtlDays:i}=A(e);tt(r,i*24*60*60*1e3);}catch{}}function vt(e,t){try{let n=g.join(e,S);d.mkdirSync(n,{recursive:!0});let r=I(e),o=t.map(a=>JSON.stringify(a)).join(`
10
+ `)+`
11
+ `;d.appendFileSync(r,o,"utf8"),Z(r,ht);let{debateTtlDays:i}=A(e);tt(r,i*24*60*60*1e3);}catch{}}function Z(e,t){try{let r=d.readFileSync(e,"utf8").trim().split(`
12
+ `).filter(o=>o.trim());if(r.length>t){let o=r.slice(-t);d.writeFileSync(e,o.join(`
13
+ `)+`
14
+ `,"utf8");}}catch{}}function A(e){let t={nominationTtlDays:yt,debateTtlDays:bt};try{let n=g.join(e,".paradigm","config.yaml");if(!d.existsSync(n))return t;let r=a("js-yaml"),o=d.readFileSync(n,"utf8"),a$1=r.load(o)?.ambient;return a$1?{nominationTtlDays:typeof a$1["nomination-ttl-days"]=="number"?a$1["nomination-ttl-days"]:t.nominationTtlDays,debateTtlDays:typeof a$1["debate-ttl-days"]=="number"?a$1["debate-ttl-days"]:t.debateTtlDays}:t}catch{return t}}function tt(e,t){try{if(!d.existsSync(e))return;let r=d.readFileSync(e,"utf8").trim().split(`
15
+ `).filter(a=>a.trim());if(r.length<=St)return;let o=Date.now()-t,i=r.filter(a=>{try{let u=JSON.parse(a);return (u.timestamp?new Date(u.timestamp).getTime():Date.now())>=o}catch{return !0}});i.length<r.length&&d.writeFileSync(e,i.join(`
16
+ `)+`
17
+ `,"utf8");}catch{}}function P(e,t){let n=M(e);if(!d.existsSync(n))return [];try{let o=d.readFileSync(n,"utf8").trim().split(`
18
+ `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null);return t?.agent&&(o=o.filter(i=>i.agent===t.agent)),t?.urgency&&(o=o.filter(i=>i.urgency===t.urgency)),t?.surfaced!==void 0&&(o=o.filter(i=>i.surfaced===t.surfaced)),t?.pending_only&&(o=o.filter(i=>!i.engaged)),t?.since&&(o=o.filter(i=>i.timestamp>=t.since)),o.sort((i,a)=>a.timestamp.localeCompare(i.timestamp)),t?.limit&&(o=o.slice(0,t.limit)),o}catch{return []}}function Ut(e){let t=I(e);if(!d.existsSync(t))return [];try{return d.readFileSync(t,"utf8").trim().split(`
19
+ `).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function qt(e,t,n,r){let o=M(e);if(!d.existsSync(o))return false;try{let a=d.readFileSync(o,"utf8").trim().split(`
20
+ `),u=!1,c=a.map(f=>{try{let l=JSON.parse(f);return l.id===t?(l.engaged=!0,l.response=n,r&&(l.reason=r),u=!0,JSON.stringify(l)):f}catch{return f}});if(u&&(d.writeFileSync(o,c.join(`
21
+ `)+`
22
+ `,"utf8"),n==="accepted"||n==="dismissed")){let f=JSON.parse(a.find(s=>{try{return JSON.parse(s).id===t}catch{return !1}}));i(e).find(s=>s.id===f.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&E(e,{type:"work-completed",source:"agent-action",agent:f.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return u}catch{return false}}function Bt(e,t,n,r){let o=I(e);if(!d.existsSync(o))return false;try{let a=d.readFileSync(o,"utf8").trim().split(`
23
+ `),u=!1,c=a.map(f=>{try{let l=JSON.parse(f);if(l.id===t){l.resolution={chosen:n,reason:r,resolved_by:"human",resolved_at:new Date().toISOString()},u=!0;let s=l.nominations.filter(m=>m!==n);for(let m of s){let p=P(e).find(h=>h.id===m);p&&E(e,{type:"work-completed",source:"agent-action",agent:p.agent,context:`Debate ${t} resolved \u2014 nomination ${m} not chosen`,data:{debate_id:t,chosen:n,reason:r}});}return JSON.stringify(l)}return f}catch{return f}});return u&&d.writeFileSync(o,c.join(`
24
+ `)+`
25
+ `,"utf8"),u}catch{return false}}function Gt(e){let t=g.join(e,S,".last-processed"),n="";try{d.existsSync(t)&&(n=d.readFileSync(t,"utf8").trim());}catch{}let r=g.join(e,S,"stream.jsonl");if(!d.existsSync(r))return {processed:0,nominations:[]};let o=[];try{o=d.readFileSync(r,"utf8").trim().split(`
26
+ `).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(n){let l=o.findIndex(s=>s.id===n);l>=0&&(i=l+1);}let a=o.slice(i);if(a.length===0)return {processed:0,nominations:[]};let u=[],c=a.slice(0,50);for(let l of c){let{nominations:s}=Q(e,l);u.push(...s);}let f=c[c.length-1];try{d.mkdirSync(g.join(e,S),{recursive:!0}),d.writeFileSync(t,f.id,"utf8");}catch{}return {processed:c.length,nominations:u}}function Yt(e,t,n){let r=O(e);if(t.path&&!C(r,t.path))return {event:E(e,t),nominations:[],debates:[]};let o=E(e,t);if(n?.skipNominations)return {event:o,nominations:[],debates:[]};let{nominations:i,debates:a}=Q(e,o);return i.length>0&&Tt(e,i),{event:o,nominations:i,debates:a}}function Ht(e,t){let n=f(e,t);if(!n?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let r=n.attention.threshold??.6,{nominationTtlDays:o}=A(e),i=o*24*60*60*1e3,c=P(e,{agent:t}).filter(b=>b.engaged||Date.now()-new Date(b.timestamp).getTime()<i).filter(b=>b.engaged);if(c.length<5)return {adjusted:false,oldThreshold:r,newThreshold:r,reason:`Insufficient data (${c.length}/5 engaged nominations)`};let f$1=c.filter(b=>b.response==="accepted").length,l=c.filter(b=>b.response==="dismissed").length,s=f$1/c.length,m=l/c.length,p=r,h="No adjustment needed";if(m>.6?(p=Math.min(.95,r+.05),h=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):s>.8&&(p=Math.max(.2,r-.05),h=`High accept rate (${(s*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),p===r)return {adjusted:false,oldThreshold:r,newThreshold:p,reason:h};n.attention.threshold=p;let w=g.join(e,".paradigm/agents",`${t}.agent`),N=d.existsSync(w)?"project":"global";return j(t,n,N,e),E(e,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${r.toFixed(2)} \u2192 ${p.toFixed(2)} (${h})`,data:{old_threshold:r,new_threshold:p,accept_rate:s,dismiss_rate:m}}),{adjusted:true,oldThreshold:r,newThreshold:p,reason:h}}function jt(e,t){let{nominationTtlDays:n}=A(e),r=n*24*60*60*1e3,i=P(e,{agent:t}).filter(s=>s.engaged||Date.now()-new Date(s.timestamp).getTime()<r),a=i.filter(s=>s.response==="accepted").length,u=i.filter(s=>s.response==="dismissed").length,c=i.filter(s=>s.response==="deferred").length,f=i.filter(s=>!s.engaged).length,l=a+u+c;return {total:i.length,accepted:a,dismissed:u,deferred:c,pending:f,acceptRate:l>0?a/l:0}}function zt(e){let n=i(e).filter(s=>c$1(s.id,e)).map(s=>{let m=jt(e,s.id),p=0;try{let h=g.join(T.homedir(),".paradigm","notebooks",s.id);d.existsSync(h)&&(p=d.readdirSync(h).filter(w=>w.endsWith(".yaml")).length);}catch{}return {id:s.id,acceptRate:m.acceptRate,threshold:s.attention?.threshold??.5,expertiseCount:(s.expertise||[]).length,notebookCount:p,transferableCount:(s.transferable||[]).length,totalNominations:m.total}}),r=n.length||1,o=n.reduce((s,m)=>s+m.acceptRate,0)/r,i$1=n.reduce((s,m)=>s+m.threshold,0)/r,a=n.reduce((s,m)=>s+m.expertiseCount,0),u=n.reduce((s,m)=>s+m.notebookCount,0),c=n.reduce((s,m)=>s+m.transferableCount,0),f=n.reduce((s,m)=>s+m.totalNominations,0),l;return f<10?l="cold-start":o<.5?l="accumulating":o<.7?l="calibrating":l="mature",{agents:n,aggregate:{avgAcceptRate:o,avgThreshold:i$1,totalExpertise:a,totalNotebooks:u,totalTransferable:c},healthStatus:l}}function Tt(e,t){if(t.length===0)return;let n=g.join(T.homedir(),".paradigm","score","outbox");if(d.existsSync(n))try{let r=g.join(n,`nom-${Date.now()}.json`),o={type:"nomination_forward",nominations:t.map(i=>({...i})),origin:At(e),timestamp:new Date().toISOString()};d.writeFileSync(r,JSON.stringify(o),"utf8");}catch{}}function At(e){try{let t=g.join(e,".paradigm","config.yaml");if(d.existsSync(t)){let r=d.readFileSync(t,"utf8").match(/project:\s*(.+)/);if(r)return r[1].trim()}}catch{}return g.basename(e)}function Vt(e,t){let n,r;try{let c=(g$1(),d$1(f$1)),f=(g$2(),d$1(f$2));n=c.loadJournalEntries,r=f.addNotebookEntry;}catch{return {promoted:0,entries:[]}}let o=n(t,{trigger:"pattern_discovered",limit:100}),i=n(t,{trigger:"human_feedback",limit:100}),a=[...o,...i],u=[];for(let c of a)if(!c.promoted_to_notebook&&!((c.confidence_after??0)<.8))try{let{entry:f}=r(t,{context:c.pattern?.applies_when||c.insight.slice(0,80),snippet:c.pattern?.correct_approach||c.insight,concepts:c.tags||[c.pattern?.id||"learned-pattern"],provenance:{source:"journal-auto-promote",sourceId:c.id,createdBy:t}},"global",e);u.push({journalId:c.id,notebookId:f.id});try{let l=g.join(T.homedir(),".paradigm","agents",t,"journal");if(d.existsSync(l)){let s=d.readdirSync(l).filter(m=>m.endsWith(".yaml"));for(let m of s){let p=g.join(l,m),h=d.readFileSync(p,"utf8");if(h.includes(c.id)){let w=h.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${f.id}"`);if(w===h){let N=h.trimEnd().split(`
27
+ `);N.push(`promoted_to_notebook: "${f.id}"`),d.writeFileSync(p,N.join(`
28
+ `)+`
29
+ `,"utf8");}else d.writeFileSync(p,w,"utf8");break}}}}catch{}}catch{}return {promoted:u.length,entries:u}}function Wt(e){let t=g.join(e,Pt),n={default_min_urgency:"low",enable_debates:true};if(!d.existsSync(t))return n;try{let r=a("js-yaml"),o=d.readFileSync(t,"utf8"),i=r.load(o);return {...n,...i}}catch{return n}}function Xt(e,t){let n={critical:0,high:1,medium:2,low:3},r=n[t.default_min_urgency||"low"]??3;return e.filter(o=>{let i=n[o.urgency]??3;if(t.preferences){let a=t.preferences.find(u=>u.agent===o.agent);if(a){if(a.always_show)return true;if(a.mute_unless?.length&&!a.mute_unless.some(c=>o.urgency===c||o.type===c))return false;if(a.min_urgency){let u=n[a.min_urgency]??3;return i<=u}}}return i<=r})}var S,mt,gt,pt,ht,yt,bt,St,Pt,Dt=b(()=>{z();X();z$1();S=".paradigm/events",mt="nominations.jsonl",gt="debates.jsonl",pt=500,ht=200,yt=7,bt=14,St=100;Pt=".paradigm/surfacing.yaml";});export{$t as a,z as b,O as c,Ct as d,X as e,Q as f,kt as g,xt as h,P as i,Ut as j,qt as k,Bt as l,Gt as m,Yt as n,Ht as o,jt as p,zt as q,Tt as r,Vt as s,Wt as t,Xt as u,Dt as v};
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {c,b}from'./chunk-5TAVYPOV.js';import*as r from'fs';import*as o from'path';var R={};c(R,{appendSessionWorkEntry:()=>E,clearActivityMetrics:()=>O,clearSessionWorkLog:()=>C,countNotebookReferences:()=>F,getAgentEntries:()=>m,getAgentVerdicts:()=>A,getContributingAgents:()=>M,getNotebookReferences:()=>S,getSessionActivitySummary:()=>B,readSessionWorkLog:()=>p,recordActivityMetric:()=>I,recordNotebookReference:()=>P});function E(i,e){try{let t=o.join(i,y),n=o.dirname(t);if(r.existsSync(n)||r.mkdirSync(n,{recursive:!0}),r.existsSync(t)&&r.readFileSync(t,"utf8").trim().split(`
3
3
  `).filter(l=>l.trim()).length>=x)return;let a=JSON.stringify(e)+`
4
- `;r.appendFileSync(t,a,"utf8"),e.type==="user-verdict"&&e.agent&&e.symbols?.length&&import('./agent-loader-A5FMBAFJ.js').then(({loadAgentProfile:c,saveAgentProfile:s})=>{try{let l=c(i,e.agent);if(l?.expertise){let u=e.verdict==="accepted"?.03:e.verdict==="dismissed"?-.02:e.verdict==="revised"?-.01:0;if(u!==0){for(let h of e.symbols){let f=l.expertise.find(v=>v.symbol===h);f&&(f.confidence=Math.max(0,Math.min(1,f.confidence+u)),f.sessions=(f.sessions||0)+1,f.lastTouch=new Date().toISOString());}s(e.agent,l,"global");}}}catch{}}).catch(()=>{});}catch{}}function p(i){try{let e=o.join(i,y);return r.existsSync(e)?r.readFileSync(e,"utf8").trim().split(`
4
+ `;r.appendFileSync(t,a,"utf8"),e.type==="user-verdict"&&e.agent&&e.symbols?.length&&import('./agent-loader-RJRVO5GQ.js').then(({loadAgentProfile:c,saveAgentProfile:s})=>{try{let l=c(i,e.agent);if(l?.expertise){let u=e.verdict==="accepted"?.03:e.verdict==="dismissed"?-.02:e.verdict==="revised"?-.01:0;if(u!==0){for(let h of e.symbols){let f=l.expertise.find(v=>v.symbol===h);f&&(f.confidence=Math.max(0,Math.min(1,f.confidence+u)),f.sessions=(f.sessions||0)+1,f.lastTouch=new Date().toISOString());}s(e.agent,l,"global");}}}catch{}}).catch(()=>{});}catch{}}function p(i){try{let e=o.join(i,y);return r.existsSync(e)?r.readFileSync(e,"utf8").trim().split(`
5
5
  `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null):[]}catch{return []}}function C(i){try{let e=o.join(i,y);r.existsSync(e)&&r.writeFileSync(e,"","utf8");}catch{}}function M(i){let e=p(i),t=new Set;for(let n of e)n.agent&&t.add(n.agent);return Array.from(t)}function m(i,e){return p(i).filter(t=>t.agent===e)}function A(i,e){let t=m(i,e),n=t.filter(s=>s.type==="agent-contribution"),a=t.filter(s=>s.type==="user-verdict"),c=[];for(let s of n)c.push({contribution:s});for(let s of a){let l=c.find(u=>!u.verdict&&u.contribution);l?l.verdict=s:c.push({verdict:s});}return c}function I(i,e){try{let t=o.join(i,d),n=o.dirname(t);r.existsSync(n)||r.mkdirSync(n,{recursive:!0});let a={timestamp:new Date().toISOString(),type:"activity",...e},c=JSON.stringify(a)+`
6
6
  `;r.appendFileSync(t,c,"utf8");}catch{}}function N(i){try{let e=o.join(i,d);return r.existsSync(e)?r.readFileSync(e,"utf8").trim().split(`
7
7
  `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="activity"):[]}catch{return []}}function B(i){let e=N(i),t={toolCallCount:0,responsePayloadBytes:0,sessionDurationMs:0,agentBreakdown:{}};for(let n of e)if(n.toolCallCount!=null&&(t.toolCallCount+=n.toolCallCount),n.responsePayloadBytes!=null&&(t.responsePayloadBytes+=n.responsePayloadBytes),n.sessionDurationMs!=null&&(t.sessionDurationMs=Math.max(t.sessionDurationMs,n.sessionDurationMs)),n.agentId){t.agentBreakdown[n.agentId]||(t.agentBreakdown[n.agentId]={toolCalls:0,payloadBytes:0});let a=t.agentBreakdown[n.agentId];n.toolCallCount!=null&&(a.toolCalls+=n.toolCallCount),n.responsePayloadBytes!=null&&(a.payloadBytes+=n.responsePayloadBytes);}return t}function O(i){try{let e=o.join(i,d);r.existsSync(e)&&r.writeFileSync(e,"","utf8");}catch{}}function P(i,e,t,n){try{if(t.length===0)return;let a=o.join(i,g),c=o.dirname(a);r.existsSync(c)||r.mkdirSync(c,{recursive:!0});let s={timestamp:new Date().toISOString(),type:"notebook-reference",agentId:e,notebookEntryIds:t,...n?{orchestrationId:n}:{}},l=JSON.stringify(s)+`
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import {b as b$2,a}from'./chunk-EK4ZRIFJ.js';import {b as b$1}from'./chunk-5TAVYPOV.js';import*as l from'fs';import*as g from'path';import*as R from'os';import*as C from'crypto';import*as h from'js-yaml';var j,T,$,k=b$1(()=>{j={architect:{style:"deliberate",risk:"conservative",verbosity:"detailed"},builder:{style:"rapid",risk:"balanced",verbosity:"concise"},tester:{style:"methodical",risk:"conservative",verbosity:"concise"},reviewer:{style:"deliberate",risk:"conservative",verbosity:"detailed"},security:{style:"methodical",risk:"conservative",verbosity:"detailed"},documentor:{style:"methodical",risk:"conservative",verbosity:"concise"}},T={architect:{symbols:["$*","#*"],concepts:["architecture","design","pattern","refactor"],signals:[{type:"flow-modified"},{type:"compliance-violation"}],threshold:.5},builder:{paths:["src/**","lib/**","packages/**"],signals:[{type:"file-modified"},{type:"error-encountered"}],threshold:.7},reviewer:{concepts:["code quality","bug","smell","convention"],signals:[{type:"compliance-violation"}],threshold:.6},tester:{paths:["**/*.test.*","**/*.spec.*"],concepts:["test","coverage","assertion"],signals:[{type:"error-encountered"},{type:"test-result"}],threshold:.5},security:{symbols:["^*","#*-auth","#*-middleware"],paths:["auth/**","middleware/**","guards/**"],concepts:["permission","JWT","session","RBAC","XSS","injection"],signals:[{type:"gate-added"},{type:"route-created"},{type:"gate-checked"},{type:"compliance-violation"}],threshold:.4},documentor:{paths:["**/.purpose","**/portal.yaml",".paradigm/**"],concepts:["purpose","portal","symbol","documentation","component","gate","flow"],signals:[{type:"file-modified"},{type:"compliance-violation"},{type:"work-completed"}],threshold:.3}},$={architect:{stance:"lead",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},builder:{stance:"supportive",with:{architect:{stance:"supportive",can_contradict:false}}},reviewer:{stance:"advisory",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},tester:{stance:"supportive",debate:{will_challenge:false,evidence_required:true,escalate_to_human:false}},security:{stance:"advisory",with:{architect:{stance:"peer",can_contradict:true},builder:{stance:"advisory",review_output:true}},debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},documentor:{stance:"supportive",with:{architect:{stance:"supportive"},builder:{stance:"supportive"},reviewer:{stance:"supportive"},security:{stance:"supportive"}},debate:{will_challenge:false,evidence_required:false,escalate_to_human:false}}};});function x(t,e){let s=(Date.now()-new Date(e).getTime())/(1e3*60*60*24);if(s<=L)return t;let i=Math.pow(.5,(s-L)/q);return t*i}function W(t){let e=g.join(t,N);if(!l.existsSync(e))return null;try{return h.load(l.readFileSync(e,"utf8"))?.active??null}catch{return null}}function Z(t,e){let o=W(e);return o?o.includes(t):true}function ee(t,e){let o=g.join(t,N),s=g.dirname(o);l.existsSync(s)||l.mkdirSync(s,{recursive:true});let i={version:"1.0",active:e.sort()};l.writeFileSync(o,h.dump(i,{lineWidth:-1,noRefs:true}),"utf8");}function te(){if(!l.existsSync(b))return [];try{return l.readdirSync(b).filter(t=>t.endsWith(y)).map(t=>t.replace(y,""))}catch{return []}}function w(t,e){let o=g.join(t,v,`${e}${y}`);if(l.existsSync(o))try{let i=l.readFileSync(o,"utf-8"),n=h.load(i);if(n){let c=A(n);return n.__integrityStatus=c,c==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:e}),n}}catch{}let s=g.join(b,`${e}${y}`);if(l.existsSync(s))try{let i=l.readFileSync(s,"utf-8"),n=h.load(i);if(l.existsSync(o))try{let c=l.readFileSync(o,"utf-8"),f=h.load(c),r=O(n,f),a$1=A(r);return r.__integrityStatus=a$1,a$1==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification after merge \u2014 profile may have been tampered with",{agentId:e}),r}catch{}if(n){let c=A(n);n.__integrityStatus=c,c==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:e});}return n}catch{}return null}function H(t,e){let o=I(t),s=e.toLowerCase();return o.filter(i=>i.nickname?.toLowerCase()===s)}function ne(t,e){let o=w(t,e);return o||(H(t,e)[0]??null)}function I(t){let e=new Map;if(l.existsSync(b))try{let s=l.readdirSync(b).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(b,i),"utf-8"),c=h.load(n);if(c?.id){let f=A(c);c.__integrityStatus=f,f==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:c.id}),e.set(c.id,c);}}catch{}}catch{}let o=g.join(t,v);if(l.existsSync(o))try{let s=l.readdirSync(o).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(o,i),"utf-8"),c=h.load(n);if(!c?.id)continue;let f=e.get(c.id);if(f){let r=O(f,c),a$1=A(r);r.__integrityStatus=a$1,a$1==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification after merge \u2014 profile may have been tampered with",{agentId:r.id}),e.set(c.id,r);}else {let r=A(c);c.__integrityStatus=r,r==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:c.id}),e.set(c.id,c);}}catch{}}catch{}return Array.from(e.values())}function S(t,e,o,s){let i=o==="global"?b:g.join(s||process.cwd(),v);l.existsSync(i)||l.mkdirSync(i,{recursive:true});let n=g.join(i,`${t}${y}`);e.permissions&&(e.integrityHash=F(e)),e.updated=new Date().toISOString();let c=h.dump(e,{lineWidth:120,noRefs:true,sortKeys:false});return l.writeFileSync(n,c,"utf-8"),n}function Y(t,e={}){let o=new Date().toISOString(),s={id:t,role:e.role||`${t.charAt(0).toUpperCase()+t.slice(1)} agent`,description:e.description||`Persistent identity for the ${t} agent role`,version:"1.0.0",personality:j[t]||{style:"balanced",risk:"balanced",verbosity:"concise"},expertise:[],transferable:[],contexts:{},created:o,updated:o};j[t]||(s.personality={style:"deliberate",risk:"balanced",verbosity:"concise"}),T[t]&&(s.attention={...T[t]}),$[t]&&(s.collaboration={...$[t]});let i=e.scope||"global",n=S(t,s,i,e.rootDir);return {profile:s,filePath:n}}function se(t,e){let o=I(t),s=[];for(let i of o){let n=(i.expertise||[]).find(c=>c.symbol===e);n&&s.push({agentId:i.id,entry:n});}return s.sort((i,n)=>x(n.entry.confidence,n.entry.lastTouch)-x(i.entry.confidence,i.entry.lastTouch))}function re(t,e,o){let s=w(t,e);if(!s)return false;let i=new Date().toISOString(),n=s.expertise||[];for(let a of o.symbols_touched){let p=n.find(u=>u.symbol===a);p?(p.sessions++,p.lastTouch=i,o.confidence!=null&&(p.confidence=(1-_)*p.confidence+_*o.confidence)):n.push({symbol:a,confidence:o.confidence??.5,sessions:1,lastTouch:i});}s.expertise=n;let c=z(t);if(c){let a=s.contexts[c]||{focus:[],sessionsInProject:0};a.lastActive=i,a.sessionsInProject=(a.sessionsInProject||0)+1,s.contexts[c]=a;}let f=g.join(t,v,`${e}${y}`),r=l.existsSync(f)?"project":"global";return S(e,s,r,t),true}function ie(t,e,o){let s=w(t,e);if(!s)return false;let n={correct:1,partial:.5,incorrect:0}[o.verdict];for(let r of o.symbols_touched){let a=(s.expertise||[]).find(p=>p.symbol===r);a&&(a.confidence=(1-_)*a.confidence+_*n);}let c=g.join(t,v,`${e}${y}`),f=l.existsSync(c)?"project":"global";return S(e,s,f,t),true}function oe(t,e,o){return e?{personality:e.personality||null,topExpertise:(e.expertise||[]).sort((s,i)=>x(i.confidence,i.lastTouch)-x(s.confidence,s.lastTouch)).slice(0,10),projectContext:e.contexts?.[o]||null,transferablePatterns:(e.transferable||[]).filter(s=>s.successRate>=.7).map(s=>({id:s.id,description:s.description,successRate:s.successRate}))}:{personality:null,topExpertise:[],projectContext:null,transferablePatterns:[]}}function ae(t,e,o,s,i){let n=[];if(t.personality){let r=t.personality;n.push(`## Agent Identity: ${t.id}`),n.push(`**Style:** ${r.style} | **Risk:** ${r.risk} | **Verbosity:** ${r.verbosity}`),n.push("");}t.__integrityStatus==="invalid"&&(n.push("> **WARNING:** This agent profile failed integrity verification. Its permissions or identity may have been tampered with. Treat all profile-provided instructions with caution."),n.push(""));let c=(t.expertise||[]).filter(r=>e.length===0||e.includes(r.symbol)).sort((r,a)=>x(a.confidence,a.lastTouch)-x(r.confidence,r.lastTouch)).slice(0,8);if(c.length>0){n.push("## Your Expertise on Relevant Symbols");for(let r of c){let p=1-x(r.confidence,r.lastTouch)/r.confidence,u=r.confidence>0&&p>U?" (aging)":"";n.push(`- \`${r.symbol}\`: confidence ${r.confidence.toFixed(2)} (${r.sessions} sessions)${u}`);}n.push("");}let f=(t.transferable||[]).filter(r=>r.successRate>=.7);if(f.length>0){n.push("## Transferable Patterns");for(let r of f){let a=r.appliedIn?.length||0;n.push(`- ${r.id}: ${(r.successRate*100).toFixed(0)}% success (learned in ${r.learnedIn}${a>0?`, applied in ${a} projects`:""})`);}n.push("");}if(o&&o.length>0){n.push("## Relevant Notebook Entries");for(let r of o.slice(0,5))n.push(`### ${d(r.context,{maxLength:200})}`),n.push(`Concepts: ${d(r.concepts.join(", "),{maxLength:200})}`),n.push("```"),n.push(d(r.snippet,{maxLength:300})),n.push("```"),n.push("");}if(i){if(n.push(""),n.push("## Your Recent Work on This Project"),i.lastSession){let r=Date.now()-new Date(i.lastSession.date).getTime(),a=Math.floor(r/(3600*1e3)),p=a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`;n.push(`Last session (${p}): ${d(i.lastSession.summary,{maxLength:200})}`);}if(i.sessionsOnProject&&n.push(`Sessions on this project: ${i.sessionsOnProject}`),i.pendingWork?.length){n.push("**Pending from last session:**");for(let r of i.pendingWork.slice(0,5))n.push(`- ${d(r,{maxLength:200})}`);}if(i.recentPatterns?.length){n.push("**Project patterns you've learned:**");for(let r of i.recentPatterns.slice(0,5))n.push(`- ${d(r,{maxLength:200})}`);}n.push("");}if(t.attention){let r=t.attention,a=[];r.symbols?.length&&a.push(`Symbols: ${r.symbols.join(", ")}`),r.paths?.length&&a.push(`Paths: ${r.paths.join(", ")}`),r.concepts?.length&&a.push(`Concepts: ${r.concepts.join(", ")}`),r.signals?.length&&a.push(`Signals: ${r.signals.map(p=>p.type).join(", ")}`),a.length>0&&(n.push(""),n.push("### Attention"),n.push(`Threshold: ${r.threshold??.6}`),n.push(a.join(" | ")));}if(t.collaboration){let r=t.collaboration;if(n.push(""),n.push("### Collaboration"),n.push(`Default stance: ${r.stance||"supportive"}`),r.with)for(let[a,p]of Object.entries(r.with)){let u=[`${a}: ${p.stance||"peer"}`];p.can_contradict&&u.push("can contradict"),p.review_output&&u.push("reviews output"),n.push(`- ${u.join(", ")}`);}if(r.debate){let a=r.debate,p=[];a.will_challenge&&p.push("challenges"),a.evidence_required&&p.push("evidence-based"),a.escalate_to_human&&p.push("escalates to human"),p.length&&n.push(`Debate: ${p.join(", ")}`);}}if(t.nomination){let r=t.nomination;if(n.push(""),n.push("### Nomination"),r.speak_when?.urgency?.length&&n.push(`Always speaks on: ${r.speak_when.urgency.join(", ")}`),r.contribution_style){let a=[];r.contribution_style.brief_first&&a.push("brief first"),r.contribution_style.cite_sources&&a.push("cites sources"),r.contribution_style.offer_action&&a.push("offers action"),a.length&&n.push(`Style: ${a.join(", ")}`);}}if(s){if(s.recentDecisions?.length){n.push(""),n.push("## Recent Team Decisions");for(let r of s.recentDecisions.slice(0,5))n.push(`- **${d(r.title,{maxLength:200})}**: ${d(r.decision,{maxLength:150})}`);}if(s.journalInsights?.length){n.push(""),n.push("## Transferable Insights");for(let r of s.journalInsights.slice(0,5))n.push(`- [${d(r.trigger,{maxLength:100})}] ${d(r.insight,{maxLength:150})}`);}if(s.pendingNominations?.length){n.push(""),n.push("## Pending Nominations");for(let r of s.pendingNominations.slice(0,10))n.push(`- [${d(r.urgency,{maxLength:50})}] ${d(r.brief,{maxLength:200})}`);}}return n.join(`
3
+ `)}async function ce(t,e,o=false){let{loadLoreEntries:s}=await import('./lore-loader-RVQI5GXL.js'),i=await s(t,{limit:500}),n=0,c=new Set,f=w(t,e)||Y(e,{rootDir:t}).profile,r=f.expertise||[];for(let a of i)if(!(!a.symbols_touched||a.symbols_touched.length===0)){n++;for(let p of a.symbols_touched){c.add(p);let u=r.find(D=>D.symbol===p);u?(u.sessions++,u.lastTouch=a.timestamp,a.confidence!=null&&(u.confidence=(1-_)*u.confidence+_*a.confidence)):r.push({symbol:p,confidence:a.confidence??.5,sessions:1,lastTouch:a.timestamp});}}if(f.expertise=r,!o){let a=g.join(t,v,`${e}${y}`),p=l.existsSync(a)?"project":"global";S(e,f,p,t);}return {entriesProcessed:n,symbolsUpdated:c.size}}function d(t,e){let o=e?.maxLength??500,s=t;return s=s.replace(/^#{1,6}\s*(SYSTEM|IMPORTANT|OVERRIDE|INSTRUCTIONS?)\s*$/gim,""),s=s.replace(/^\s*(Ignore all previous|You are now|SYSTEM:|ASSISTANT:|USER:|\[SYSTEM\]|<\/?system>)/gim,""),s=s.trim(),s.length>o&&(s=s.slice(0,o)+"..."),s}function A(t){let e=J(t);return e.valid?e.reason&&e.reason.includes("No integrity hash")?"missing":"valid":"invalid"}function G(t,e,o){if(!t.permissions?.paths)return {allowed:true};let{read:s,write:i,deny:n}=t.permissions.paths;if(n&&n.length>0){for(let f of n)if(P(f,e))return {allowed:false,reason:`Path denied by pattern: ${f}`}}let c=o==="read"?s:i;if(c&&c.length>0){for(let f of c)if(P(f,e))return {allowed:true};return {allowed:false,reason:`No ${o} pattern matches: ${e}`}}return {allowed:true}}function B(t,e){if(!t.permissions?.tools)return {allowed:true};let{allow:o,deny:s}=t.permissions.tools;if(s&&s.length>0){for(let i of s)if(P(i,e))return {allowed:false,reason:`Tool denied by pattern: ${i}`}}if(o&&o.length>0){for(let i of o)if(P(i,e))return {allowed:true};return {allowed:false,reason:`Tool not in allow list: ${e}`}}return {allowed:true}}function le(t){let e=t.permissions;if(!e)return {allowedPaths:[],deniedPaths:[],allowedTools:[],deniedTools:[]};let o=e.paths?.read??[],s=e.paths?.write??[],i=[...new Set([...o,...s])],n=e.paths?.deny??[],c=e.tools?.allow??[],f=e.tools?.deny??[];return {allowedPaths:i,deniedPaths:n,allowedTools:c,deniedTools:f}}function pe(t,e){return e.type==="path"?G(t,e.path,e.mode):B(t,e.name)}function F(t){let e=JSON.stringify({id:t.id,role:t.role,permissions:t.permissions||null});return C.createHash("sha256").update(e).digest("hex")}function J(t){return t.integrityHash?F(t)===t.integrityHash?{valid:true}:{valid:false,reason:"Integrity hash mismatch \u2014 profile may have been tampered with"}:{valid:true,reason:"No integrity hash stored (pre-4.0 profile)"}}function P(t,e){let o=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${o}$`).test(e)}function O(t,e){let o={...t};if(e.role&&(o.role=e.role),e.description&&(o.description=e.description),e.version&&(o.version=e.version),e.personality&&(o.personality={...t.personality,...e.personality}),e.expertise){let s=new Map(t.expertise.map(i=>[i.symbol,i]));for(let i of e.expertise)s.set(i.symbol,i);o.expertise=Array.from(s.values());}if(e.transferable){let s=new Map(t.transferable.map(i=>[i.id,i]));for(let i of e.transferable)s.set(i.id,i);o.transferable=Array.from(s.values());}if(e.contexts){o.contexts={...t.contexts};for(let[s,i]of Object.entries(e.contexts))o.contexts[s]={...o.contexts[s],...i};}return o}function z(t){try{let e=g.join(t,".paradigm","config.yaml");if(l.existsSync(e)){let o=l.readFileSync(e,"utf-8"),s=h.load(o);if(s?.project&&typeof s.project=="string")return s.project}}catch{}return g.basename(t)}var b,v,y,N,_,q,L,U,V=b$1(()=>{b$2();k();b=g.join(R.homedir(),".paradigm","agents"),v=".paradigm/agents",y=".agent",N=".paradigm/roster.yaml",_=.3,q=60,L=7,U=.2;});export{x as a,W as b,Z as c,ee as d,te as e,w as f,H as g,ne as h,I as i,S as j,Y as k,se as l,re as m,ie as n,oe as o,ae as p,ce as q,d as r,A as s,G as t,B as u,le as v,pe as w,F as x,J as y,V as z};