@a-company/paradigm 5.28.0 → 5.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/{accept-orchestration-CLT6SAYW.js → accept-orchestration-MIRBLRUJ.js} +1 -1
  2. package/dist/agent-loader-5255KNM7.js +2 -0
  3. package/dist/agent-loader-A5FMBAFJ.js +2 -0
  4. package/dist/ambient-2JZTNXUL.js +35 -0
  5. package/dist/chunk-2Q7RGCJH.js +3 -0
  6. package/dist/chunk-32RBX5YV.js +9 -0
  7. package/dist/chunk-7SWEOPWF.js +2 -0
  8. package/dist/{chunk-DG236EXP.js → chunk-A7KFOJ2F.js} +1 -1
  9. package/dist/chunk-AGSUX2GJ.js +9 -0
  10. package/dist/chunk-C7ZCCKJT.js +3 -0
  11. package/dist/chunk-EAZ3EMOZ.js +29 -0
  12. package/dist/{chunk-VPMJWJ5R.js → chunk-HPAHK4AJ.js} +1 -1
  13. package/dist/chunk-LKFBDUCV.js +11 -0
  14. package/dist/chunk-S7K7UPXL.js +3 -0
  15. package/dist/{chunk-FSOI3CCD.js → chunk-SXO7NC6A.js} +18 -4
  16. package/dist/{chunk-VNQGILQU.js → chunk-TXBSTT64.js} +4 -4
  17. package/dist/chunk-TZZNHUAR.js +2 -0
  18. package/dist/{chunk-WESTEMIM.js → chunk-UDUHSHO4.js} +1 -1
  19. package/dist/chunk-UHQLYIRI.js +3 -0
  20. package/dist/{compliance-5OYNHE5D.js → compliance-Q676YALK.js} +1 -1
  21. package/dist/compliance-health-JNP3P35P.js +4 -0
  22. package/dist/{diff-YM6ZV3UI.js → diff-QHQWLM3L.js} +1 -1
  23. package/dist/doctor-R4UGMR5N.js +2 -0
  24. package/dist/gap-narrator-NTXLUI7I.js +3 -0
  25. package/dist/{hooks-E7HQQ57M.js → hooks-BNWRGACA.js} +1 -1
  26. package/dist/index.js +5 -5
  27. package/dist/mcp.js +92 -53
  28. package/dist/{migrate-WT56YYAM.js → migrate-YQG2FG3J.js} +1 -1
  29. package/dist/{nomination-engine-LMSZ2CAS.js → nomination-engine-W6QTQX2P.js} +1 -1
  30. package/dist/{orchestrate-4L3NJCV5.js → orchestrate-7CJWHLBA.js} +1 -1
  31. package/dist/{project-type-4Y6CESWP.js → project-type-AGO6VUKF.js} +1 -1
  32. package/dist/{providers-4PXMWA7V.js → providers-TBPOE4DI.js} +1 -1
  33. package/dist/reindex-2MRCAIZG.js +2 -0
  34. package/dist/{roster-K2QILE7K.js → roster-TA2GFDR7.js} +1 -1
  35. package/dist/scopes-commands-3V5G6NYV.js +3 -0
  36. package/dist/session-tracker-WSTRV7UP.js +2 -0
  37. package/dist/session-work-log-5UJTJJ22.js +2 -0
  38. package/dist/session-work-log-SLAPEP3M.js +2 -0
  39. package/dist/shift-IKTWYSEQ.js +60 -0
  40. package/dist/{spawn-UH5RENSE.js → spawn-7TCAMD6H.js} +1 -1
  41. package/dist/{symphony-ZQ5OHJTP.js → symphony-IS5TYPXY.js} +2 -2
  42. package/dist/symphony-relay-CIMRXQHI.js +3 -0
  43. package/dist/{team-MKLPUTW7.js → team-WIJVWLII.js} +1 -1
  44. package/dist/university-content/courses/.purpose +52 -8
  45. package/dist/university-content/courses/para-001.json +166 -0
  46. package/dist/university-content/courses/para-101.json +88 -88
  47. package/dist/university-content/courses/para-201.json +27 -55
  48. package/dist/university-content/courses/para-301.json +114 -8
  49. package/dist/university-content/courses/para-401.json +90 -62
  50. package/dist/university-content/courses/para-501.json +55 -0
  51. package/dist/university-ui/assets/{index-CGFJczb1.js → index-DmiLQehB.js} +2 -2
  52. package/dist/university-ui/assets/{index-CGFJczb1.js.map → index-DmiLQehB.js.map} +1 -1
  53. package/dist/university-ui/index.html +1 -1
  54. package/package.json +1 -1
  55. package/dist/agent-loader-CZFB5BDP.js +0 -2
  56. package/dist/agent-loader-EBERCNMO.js +0 -2
  57. package/dist/ambient-S3CXHD7P.js +0 -35
  58. package/dist/chunk-4DVT5IEY.js +0 -2
  59. package/dist/chunk-5KSNYRT7.js +0 -29
  60. package/dist/chunk-AYYS2AMB.js +0 -3
  61. package/dist/chunk-CSXVL2U7.js +0 -9
  62. package/dist/chunk-QWL3LERH.js +0 -3
  63. package/dist/chunk-SL3RZQPW.js +0 -5
  64. package/dist/chunk-U4J5J7GG.js +0 -3
  65. package/dist/chunk-VKGY42FP.js +0 -5
  66. package/dist/doctor-HMQBF2WK.js +0 -2
  67. package/dist/reindex-BSD7ZIEY.js +0 -2
  68. package/dist/session-tracker-FDFL4PZI.js +0 -2
  69. package/dist/session-work-log-5PHOUEQ6.js +0 -2
  70. package/dist/session-work-log-LWEGZ5CN.js +0 -2
  71. package/dist/shift-WNP27SPB.js +0 -11
  72. package/dist/symphony-relay-KBHN3ZMR.js +0 -3
  73. /package/dist/{chunk-IZSBGW6E.js → chunk-HXGYVS2N.js} +0 -0
@@ -8,7 +8,7 @@
8
8
  <link rel="preconnect" href="https://fonts.googleapis.com">
9
9
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
10
  <link href="https://fonts.googleapis.com/css2?family=Crimson+Pro:ital,wght@0,400;0,500;0,600;0,700;1,400&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
11
- <script type="module" crossorigin src="/assets/index-CGFJczb1.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-DmiLQehB.js"></script>
12
12
  <link rel="stylesheet" crossorigin href="/assets/index-CMrxD7y5.css">
13
13
  </head>
14
14
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-company/paradigm",
3
- "version": "5.28.0",
3
+ "version": "5.34.0",
4
4
  "description": "Unified CLI for Paradigm developer tools",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import {v}from'./chunk-QWL3LERH.js';export{p as buildProfileEnrichment,r as checkPathPermission,s as checkToolPermission,t as computeIntegrityHash,k as createAgentProfile,a as decayedConfidence,g as findAgentsByNickname,c as isAgentActive,e as listAllGlobalAgentIds,f as loadAgentProfile,i as loadAllAgentProfiles,b as loadProjectRoster,o as mergeAgentProfileWithManifest,l as queryExpertise,h as resolveAgent,j as saveAgentProfile,d as saveProjectRoster,q as syncExpertiseFromLore,n as updateExpertiseFromAssessment,m as updateExpertiseFromLore,u as verifyIntegrity}from'./chunk-QWL3LERH.js';import'./chunk-5TAVYPOV.js';v();
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export{p as buildProfileEnrichment,r as checkPathPermission,s as checkToolPermission,t as computeIntegrityHash,k as createAgentProfile,a as decayedConfidence,g as findAgentsByNickname,c as isAgentActive,e as listAllGlobalAgentIds,f as loadAgentProfile,i as loadAllAgentProfiles,b as loadProjectRoster,o as mergeAgentProfileWithManifest,l as queryExpertise,h as resolveAgent,j as saveAgentProfile,d as saveProjectRoster,q as syncExpertiseFromLore,n as updateExpertiseFromAssessment,m as updateExpertiseFromLore,u as verifyIntegrity}from'./chunk-U4J5J7GG.js';import'./chunk-5TAVYPOV.js';
@@ -1,35 +0,0 @@
1
- #!/usr/bin/env node
2
- import {f as f$1,p,i,j}from'./chunk-U4J5J7GG.js';import {b as b$2}from'./chunk-VKGY42FP.js';import {c,b as b$1,d,a}from'./chunk-5TAVYPOV.js';import*as f from'fs';import*as b from'path';import*as P from'js-yaml';import*as Q from'os';var vt={};c(vt,{getJournalStats:()=>ne,loadAllJournalEntries:()=>ee,loadJournalEntries:()=>O,loadJournalEntry:()=>te,recordJournalEntry:()=>z});function G(n){let t=process.env.HOME||process.env.USERPROFILE||"";return b.join(t,".paradigm","agents",n,"journal")}function Zt(){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=Zt(),i={id:o,agent:n,timestamp:e.toISOString(),...t},r=G(n);f.mkdirSync(r,{recursive:true});let s=b.join(r,`${o}.yaml`);return f.writeFileSync(s,P.dump(i,{lineWidth:120,noRefs:true}),"utf8"),i}function O(n,t){let e=G(n);if(!f.existsSync(e))return [];let o=[],i=f.readdirSync(e).filter(s=>s.endsWith(".yaml"));for(let s of i)try{let a=f.readFileSync(b.join(e,s),"utf8"),c=P.load(a);c&&c.id&&o.push(c);}catch{}let r=o;return t?.trigger&&(r=r.filter(s=>s.trigger===t.trigger)),t?.project&&(r=r.filter(s=>s.project===t.project)),t?.transferable!==void 0&&(r=r.filter(s=>s.transferable===t.transferable)),t?.tag&&(r=r.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(r=r.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(r=r.filter(s=>s.timestamp<=t.dateTo)),r.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(r=r.slice(0,t.limit)),r}function te(n,t){let e=G(n),o=b.join(e,`${t}.yaml`);if(!f.existsSync(o))return null;let i=f.readFileSync(o,"utf8");return P.load(i)}function ee(n){let t=process.env.HOME||process.env.USERPROFILE||"",e=b.join(t,".paradigm","agents");if(!f.existsSync(e))return [];let o=[],i=f.readdirSync(e,{withFileTypes:true}).filter(r=>r.isDirectory());for(let r of i){if(n?.agent&&r.name!==n.agent)continue;let s=O(r.name,n);o.push(...s);}return o.sort((r,s)=>s.timestamp.localeCompare(r.timestamp)),n?.limit?o.slice(0,n.limit):o}function ne(n){let t=O(n),e={},o={},i=0;for(let r of t)e[r.trigger]=(e[r.trigger]||0)+1,o[r.project]=(o[r.project]||0)+1,r.transferable&&i++;return {total:t.length,byTrigger:e,byProject:o,transferableCount:i,recentInsights:t.slice(0,5).map(r=>({id:r.id,trigger:r.trigger,insight:r.insight.slice(0,200),timestamp:r.timestamp}))}}var K=b$1(()=>{});var Dt={};c(Dt,{addNotebookEntry:()=>xt,incrementApplied:()=>se,loadNotebookEntries:()=>Et,promoteFromLore:()=>ie,searchNotebooks:()=>re});function Et(n,t,e){let o=new Map,i=b.join(V,n);jt(i,o);let r=b.join(t,Y,n);jt(r,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 jt(n,t){if(f.existsSync(n))try{let e=f.readdirSync(n).filter(o=>o.startsWith(oe)&&o.endsWith(X));for(let o of e)try{let i=f.readFileSync(b.join(n,o),"utf-8"),r=P.load(i);r?.id&&t.set(r.id,r);}catch{}}catch{}}function re(n,t,e){let o=Et(n,e),i=t.toLowerCase();return o.filter(r=>r.context.toLowerCase().includes(i)||r.snippet.toLowerCase().includes(i)||r.concepts.some(s=>s.toLowerCase().includes(i))||r.tags.some(s=>s.toLowerCase().includes(i)))}function xt(n,t,e,o){let i=new Date().toISOString(),r=(t.concepts[0]||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),s=Date.now().toString(36),a=`nb-${r}-${s}`,c={...t,id:a,appliedCount:0,created:i,updated:i},d=e==="global"?b.join(V,n):b.join(o||process.cwd(),Y,n);f.existsSync(d)||f.mkdirSync(d,{recursive:true});let u=`${a}${X}`,l=b.join(d,u),m=P.dump(c,{lineWidth:120,noRefs:true,sortKeys:false});return f.writeFileSync(l,m,"utf-8"),{entry:c,filePath:l}}async function ie(n,t,e,o="global"){let{loadLoreEntry:i}=await import('./lore-loader-XY5MZRR2.js'),r=await i(e,t);if(!r)return null;let s=[];if(r.symbols_touched)for(let d of r.symbols_touched){let u=d.replace(/^[#$^!~]/,"").toLowerCase();s.push(u);}let a=r.summary||"";r.body&&(a+=`
3
-
4
- `+r.body);let c={source:"lore",loreEntryId:t,originProject:b.basename(e),createdBy:n};return xt(n,{context:r.title||`Promoted from ${t}`,snippet:a,provenance:c,confidence:r.confidence??.7,concepts:s,tags:r.tags||[]},o,e)}function se(n,t,e){let o=b.join(e,Y,n),i=b.join(V,n);for(let r of [o,i]){let s=b.join(r,`${t}${X}`);if(f.existsSync(s))try{let a=f.readFileSync(s,"utf-8"),c=P.load(a);if(c)return c.appliedCount=(c.appliedCount||0)+1,c.updated=new Date().toISOString(),f.writeFileSync(s,P.dump(c,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var V,Y,oe,X,Rt=b$1(()=>{V=b.join(Q.homedir(),".paradigm","notebooks"),Y=".paradigm/notebooks",oe="nb-",X=".yaml";});var ft=".paradigm/events",zt="stream.jsonl",I=1e3,N=[];function gt(n){return b.join(n,ft,zt)}function Kt(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${n}-${t}`}function J(n,t){let e={id:Kt(),timestamp:new Date().toISOString(),...t};N.push(e),N.length>I&&(N=N.slice(-I));try{let o=b.join(n,ft);f.mkdirSync(o,{recursive:!0});let i=gt(n);f.appendFileSync(i,JSON.stringify(e)+`
5
- `,"utf8"),Vt(i);}catch{}return e}function Vt(n){try{if(f.statSync(n).size>512*1024){let o=f.readFileSync(n,"utf8").trim().split(`
6
- `);if(o.length>I){let i=o.slice(-I);f.writeFileSync(n,i.join(`
7
- `)+`
8
- `,"utf8");}}}catch{}}function yt(n,t){let e=Yt(n);return t?.type&&(e=e.filter(o=>o.type===t.type)),t?.source&&(e=e.filter(o=>o.source===t.source)),t?.symbol&&(e=e.filter(o=>o.symbols?.includes(t.symbol))),t?.agent&&(e=e.filter(o=>o.agent===t.agent)),t?.since&&(e=e.filter(o=>o.timestamp>=t.since)),e.sort((o,i)=>i.timestamp.localeCompare(o.timestamp)),t?.limit&&(e=e.slice(0,t.limit)),e}function Yt(n){let t=gt(n);if(!f.existsSync(t))return [...N];try{return f.readFileSync(t,"utf8").trim().split(`
9
- `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null)}catch{return [...N]}}function ht(n,t,e){let o=0,i=0,r=0,s=0;if(e.symbols?.length&&n.symbols?.length)for(let u of e.symbols)for(let l of n.symbols)pt(u,l)&&(o=Math.max(o,1));if(e.paths?.length&&n.path){for(let u of e.paths)if(pt(u,n.path)){i=1;break}}if(e.concepts?.length){let u=[n.context||"",...n.keywords||[],n.type].join(" ").toLowerCase(),l=0;for(let m of e.concepts)u.includes(m.toLowerCase())&&l++;e.concepts.length>0&&(r=l/e.concepts.length);}if(e.signals?.length){for(let u of e.signals)if(u.type===n.type){s=1;break}}let a=[o,i,r,s].sort((u,l)=>l-u),c=a[0]*.5+a[1]*.2+a[2]*.15+a[3]*.15,d=e.threshold??.6;return {agentId:t,score:c,breakdown:{symbolMatch:o,pathMatch:i,conceptMatch:r,signalMatch:s},shouldNominate:c>=d,quietReason:c<d?"below-threshold":void 0}}function pt(n,t){if(n===t)return true;let e=n.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${e}$`).test(t)}catch{return false}}var M={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"]},learning_journal:{ring:"user-scoped",allow_content:["pattern_descriptions","confidence_adjustments","approach_descriptions"],deny_content:["code_snippets","file_contents","symbol_names_with_context"],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"]}},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"]}};var Xt=".paradigm/data-policy.yaml";function St(n){let t=b.join(n,Xt);if(!f.existsSync(t))return {...M};try{let e=f.readFileSync(t,"utf8"),o=P.load(e);return Qt(M,o)}catch{return {...M}}}function Qt(n,t){let e={...n};if(t.version&&(e.version=t.version),t.default_ring&&(e.default_ring=t.default_ring),t.observation&&(e.observation={allow:t.observation.allow||n.observation?.allow,deny:[...n.observation?.deny||[],...t.observation.deny||[]].filter((o,i,r)=>r.indexOf(o)===i)}),t.streams){e.streams={...n.streams};for(let o of ["work_log","learning_journal","team_decisions"])t.streams[o]&&(e.streams[o]={...n.streams?.[o],...t.streams[o],deny_content:[...n.streams?.[o]?.deny_content||[],...t.streams[o]?.deny_content||[]].filter((i,r,s)=>s.indexOf(i)===r)});}return t.upstream&&(e.upstream={...n.upstream,...t.upstream}),t.network&&(e.network={...n.network,...t.network}),t.agent_overrides&&(e.agent_overrides={...n.agent_overrides,...t.agent_overrides}),t.deployment&&(e.deployment={...n.deployment,...t.deployment}),e}function wt(n,t,e){return e&&n.agent_overrides?.[e]?.observation&&n.agent_overrides[e].observation.deny?.some(i=>q(i,t))||n.observation?.deny?.some(o=>q(o,t))?false:n.observation?.allow?.length?n.observation.allow.some(o=>q(o,t)):true}function q(n,t){if(n===t)return true;let e=n.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${e}$`).test(t)}catch{return false}}var R=".paradigm/events",ae="nominations.jsonl",ce="debates.jsonl",le=500,de=200,ue=7,me=14,pe=100;function fe(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${n}-${t}`}function ge(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${n}-${t}`}function ye(n,t){let e=i(n),o=St(n),i$1=[];for(let d of e){if(!d.attention||d.benched||t.path&&!wt(o,t.path,d.id))continue;let u=ht(t,d.id,d.attention);u.shouldNominate&&i$1.push({profile:d,score:u});}if(i$1.length===0)return {nominations:[],debates:[]};let r=k(n,{since:new Date(Date.now()-3e4).toISOString()}),s=i$1.filter(({profile:d})=>!r.find(l=>l.agent===d.id&&l.brief===Nt(d,t,{...i$1.find(m=>m.profile.id===d.id).score})));if(s.length===0)return {nominations:[],debates:[]};let a=s.map(({profile:d,score:u})=>{let l=he(t,u),m=be(d,t);return {id:fe(),agent:d.id,relevance:u.score,urgency:l,type:m,brief:Nt(d,t,u),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});Se(n,a);let c=_e(n,a);return c.length>0&&we(n,c),{nominations:a,debates:c}}function he(n,t){return n.severity==="critical"?"critical":n.severity==="error"||n.type==="compliance-violation"||n.type==="error-encountered"?"high":n.type==="gate-added"||n.type==="route-created"||t.score>=.9?"medium":"low"}function be(n,t){let e=n.collaboration?.stance;return t.type==="compliance-violation"||t.type==="error-encountered"?"warning":t.type==="gate-added"||t.type==="route-created"?"observation":e==="advisory"||e==="lead"?"suggestion":"observation"}function Nt(n,t,e){let o=n.role||n.id;switch(t.type){case "gate-checked":return `${o}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${o}: ${t.path||"File"} modified \u2014 review for ${n.id==="security"?"security implications":n.id==="tester"?"test coverage":n.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${o}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${o}: New route ${t.symbols?.join(", ")||""} \u2014 ${n.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${o}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${n.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${o}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${o}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${o}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let i=e.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:e.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${o}: ${i}`}}}function _e(n,t){if(t.length<2)return [];let e=[],o=new Map;for(let i of t)for(let r of i.triggered_by){let s=o.get(r)||[];s.push(i),o.set(r,s);}for(let[i,r]of o){if(r.length<2||new Set(r.map(d=>d.agent)).size<2)continue;let a=new Set(r.map(d=>d.type)),c=a.size>1&&a.has("warning")&&a.has("suggestion");e.push({id:ge(),topic:`Multiple agents responded to event ${i}`,nominations:r.map(d=>d.id),type:c?"conflicting":"complementary",overlap_events:[i]});}return e}function Z(n){return b.join(n,R,ae)}function tt(n){return b.join(n,R,ce)}function Se(n,t){try{let e=b.join(n,R);f.mkdirSync(e,{recursive:!0});let o=Z(n),i=t.map(s=>JSON.stringify(s)).join(`
10
- `)+`
11
- `;f.appendFileSync(o,i,"utf8"),Tt(o,le);let{nominationTtlDays:r}=U(n);Pt(o,r*24*60*60*1e3);}catch{}}function we(n,t){try{let e=b.join(n,R);f.mkdirSync(e,{recursive:!0});let o=tt(n),i=t.map(s=>JSON.stringify(s)).join(`
12
- `)+`
13
- `;f.appendFileSync(o,i,"utf8"),Tt(o,de);let{debateTtlDays:r}=U(n);Pt(o,r*24*60*60*1e3);}catch{}}function Tt(n,t){try{let o=f.readFileSync(n,"utf8").trim().split(`
14
- `).filter(i=>i.trim());if(o.length>t){let i=o.slice(-t);f.writeFileSync(n,i.join(`
15
- `)+`
16
- `,"utf8");}}catch{}}function U(n){let t={nominationTtlDays:ue,debateTtlDays:me};try{let e=b.join(n,".paradigm","config.yaml");if(!f.existsSync(e))return t;let o=a("js-yaml"),i=f.readFileSync(e,"utf8"),s=o.load(i)?.ambient;return s?{nominationTtlDays:typeof s["nomination-ttl-days"]=="number"?s["nomination-ttl-days"]:t.nominationTtlDays,debateTtlDays:typeof s["debate-ttl-days"]=="number"?s["debate-ttl-days"]:t.debateTtlDays}:t}catch{return t}}function Pt(n,t){try{if(!f.existsSync(n))return;let o=f.readFileSync(n,"utf8").trim().split(`
17
- `).filter(s=>s.trim());if(o.length<=pe)return;let i=Date.now()-t,r=o.filter(s=>{try{let a=JSON.parse(s);return (a.timestamp?new Date(a.timestamp).getTime():Date.now())>=i}catch{return !0}});r.length<o.length&&f.writeFileSync(n,r.join(`
18
- `)+`
19
- `,"utf8");}catch{}}function k(n,t){let e=Z(n);if(!f.existsSync(e))return [];try{let i=f.readFileSync(e,"utf8").trim().split(`
20
- `).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null);return t?.agent&&(i=i.filter(r=>r.agent===t.agent)),t?.urgency&&(i=i.filter(r=>r.urgency===t.urgency)),t?.surfaced!==void 0&&(i=i.filter(r=>r.surfaced===t.surfaced)),t?.pending_only&&(i=i.filter(r=>!r.engaged)),t?.since&&(i=i.filter(r=>r.timestamp>=t.since)),i.sort((r,s)=>s.timestamp.localeCompare(r.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}catch{return []}}function $t(n){let t=tt(n);if(!f.existsSync(t))return [];try{return f.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 i$1=Z(n);if(!f.existsSync(i$1))return false;try{let s=f.readFileSync(i$1,"utf8").trim().split(`
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&&(f.writeFileSync(i$1,c.join(`
23
- `)+`
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&&J(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 At(n,t,e,o){let i=tt(n);if(!f.existsSync(i))return false;try{let s=f.readFileSync(i,"utf8").trim().split(`
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=k(n).find(p=>p.id===m);y&&J(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&&f.writeFileSync(i,c.join(`
26
- `)+`
27
- `,"utf8"),a}catch{return false}}function Ft(n){let t=b.join(n,R,".last-processed"),e="";try{f.existsSync(t)&&(e=f.readFileSync(t,"utf8").trim());}catch{}let o=b.join(n,R,"stream.jsonl");if(!f.existsSync(o))return {processed:0,nominations:[]};let i=[];try{i=f.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 r=0;if(e){let u=i.findIndex(l=>l.id===e);u>=0&&(r=u+1);}let s=i.slice(r);if(s.length===0)return {processed:0,nominations:[]};let a=[],c=s.slice(0,50);for(let u of c){let{nominations:l}=ye(n,u);a.push(...l);}let d=c[c.length-1];try{f.mkdirSync(b.join(n,R),{recursive:!0}),f.writeFileSync(t,d.id,"utf8");}catch{}return {processed:c.length,nominations:a}}function Ct(n,t){let e=f$1(n,t);if(!e?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let o=e.attention.threshold??.6,{nominationTtlDays:i}=U(n),r=i*24*60*60*1e3,c=k(n,{agent:t}).filter(j=>j.engaged||Date.now()-new Date(j.timestamp).getTime()<r).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,p="No adjustment needed";if(m>.6?(y=Math.min(.95,o+.05),p=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):l>.8&&(y=Math.max(.2,o-.05),p=`High accept rate (${(l*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),y===o)return {adjusted:false,oldThreshold:o,newThreshold:y,reason:p};e.attention.threshold=y;let g=b.join(n,".paradigm/agents",`${t}.agent`),D=f.existsSync(g)?"project":"global";return j(t,e,D,n),J(n,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${o.toFixed(2)} \u2192 ${y.toFixed(2)} (${p})`,data:{old_threshold:o,new_threshold:y,accept_rate:l,dismiss_rate:m}}),{adjusted:true,oldThreshold:o,newThreshold:y,reason:p}}function et(n,t){let{nominationTtlDays:e}=U(n),o=e*24*60*60*1e3,r=k(n,{agent:t}).filter(l=>l.engaged||Date.now()-new Date(l.timestamp).getTime()<o),s=r.filter(l=>l.response==="accepted").length,a=r.filter(l=>l.response==="dismissed").length,c=r.filter(l=>l.response==="deferred").length,d=r.filter(l=>!l.engaged).length,u=s+a+c;return {total:r.length,accepted:s,dismissed:a,deferred:c,pending:d,acceptRate:u>0?s/u:0}}function It(n){let e=i(n).filter(l=>!l.benched).map(l=>{let m=et(n,l.id),y=0;try{let p=b.join(Q.homedir(),".paradigm","notebooks",l.id);f.existsSync(p)&&(y=f.readdirSync(p).filter(g=>g.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,i$1=e.reduce((l,m)=>l+m.acceptRate,0)/o,r=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":i$1<.5?u="accumulating":i$1<.7?u="calibrating":u="mature",{agents:e,aggregate:{avgAcceptRate:i$1,avgThreshold:r,totalExpertise:s,totalNotebooks:a,totalTransferable:c},healthStatus:u}}function nt(n,t){let e,o;try{let c=(K(),d(vt)),d$1=(Rt(),d(Dt));e=c.loadJournalEntries,o=d$1.addNotebookEntry;}catch{return {promoted:0,entries:[]}}let i=e(t,{trigger:"pattern_discovered",limit:100}),r=e(t,{trigger:"human_feedback",limit:100}),s=[...i,...r],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(Q.homedir(),".paradigm","agents",t,"journal");if(f.existsSync(u)){let l=f.readdirSync(u).filter(m=>m.endsWith(".yaml"));for(let m of l){let y=b.join(u,m),p=f.readFileSync(y,"utf8");if(p.includes(c.id)){let g=p.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${d.id}"`);if(g===p){let D=p.trimEnd().split(`
29
- `);D.push(`promoted_to_notebook: "${d.id}"`),f.writeFileSync(y,D.join(`
30
- `)+`
31
- `,"utf8");}else f.writeFileSync(y,g,"utf8");break}}}}catch{}}catch{}return {promoted:a.length,entries:a}}var ve=".paradigm/surfacing.yaml";function Jt(n){let t=b.join(n,ve),e={default_min_urgency:"low",enable_debates:true};if(!f.existsSync(t))return e;try{let o=a("js-yaml"),i=f.readFileSync(t,"utf8"),r=o.load(i);return {...e,...r}}catch{return e}}function Mt(n,t){let e={critical:0,high:1,medium:2,low:3},o=e[t.default_min_urgency||"low"]??3;return n.filter(i=>{let r=e[i.urgency]??3;if(t.preferences){let s=t.preferences.find(a=>a.agent===i.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(c=>i.urgency===c||i.type===c))return false;if(s.min_urgency){let a=e[s.min_urgency]??3;return r<=a}}}return r<=o})}var je=".paradigm/decisions";function Lt(n,t){let e=b.join(n,je);if(!f.existsSync(e))return [];let o=[],i=f.readdirSync(e).filter(s=>s.endsWith(".yaml"));for(let s of i)try{let a=f.readFileSync(b.join(e,s),"utf8"),c=P.load(a);c&&c.id&&o.push(c);}catch{}let r=o;return (r=r.filter(s=>s.status===t.status)),t?.participant&&(r=r.filter(s=>s.participants.some(a=>a.id===t.participant))),t?.symbol&&(r=r.filter(s=>s.symbols_affected?.includes(t.symbol))),t?.tag&&(r=r.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(r=r.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(r=r.filter(s=>s.timestamp<=t.dateTo)),r.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(r=r.slice(0,t.limit)),r}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),i=e[2],r=i==="m"?o*6e4:i==="h"?o*36e5:o*864e5;return new Date(t-r).toISOString()}return n}async function ze(n,t,e){let o=i=>JSON.stringify(i,null,2);switch(n){case "paradigm_ambient_nominations":{Ft(e.rootDir);let r=t.pending_only!==false,s=t.limit||20,a=k(e.rootDir,{agent:t.agent,urgency:t.urgency,pending_only:r,limit:s+20}),c=Jt(e.rootDir);a=Mt(a,c).slice(0,s);let d=b.join(e.rootDir,".paradigm/events/nominations.jsonl");if(f.existsSync(d))try{let l=f.readFileSync(d,"utf8"),m=new Set(a.map(p=>p.id)),y=l.trim().split(`
32
- `).map(p=>{try{let g=JSON.parse(p);return m.has(g.id)?(g.surfaced=!0,JSON.stringify(g)):p}catch{return p}});f.writeFileSync(d,y.join(`
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=$t(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 i=t.since?ke(t.since):void 0,r=t.limit||50,s=yt(e.rootDir,{type:t.type,source:t.source,symbol:t.symbol,agent:t.agent,since:i,limit:r});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 i=t.nomination_id,r=t.response,s=t.reason,a=Ot(e.rootDir,i,r,s);if(a)try{let{appendSessionWorkEntry:d}=await import('./session-work-log-LWEGZ5CN.js'),l=k(e.rootDir,{limit:500}).find(m=>m.id===i);d(e.rootDir,{timestamp:new Date().toISOString(),type:"user-verdict",agent:l?.agent,nominationId:i,verdict:r,reason:s});}catch{}let c=false;return t.resolve_debate&&a&&(c=At(e.rootDir,t.resolve_debate,i,t.reason)),{text:o({engaged:a,nomination_id:i,response:r,debate_resolved:c||void 0}),handled:true}}case "paradigm_context_compose":{let i=t.agent,r=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$1(e.rootDir,i);if(!l)return {text:o({error:`Agent profile not found: ${i}`}),handled:true};let m=[],y=p(l,r);if(y.trim()&&m.push(y),a){let p=Lt(e.rootDir,{status:"active",limit:d});if(p.length>0){m.push("## Recent Team Decisions");for(let g of p)m.push(`- **${g.title}**: ${g.decision.slice(0,150)}${g.decision.length>150?"...":""}`);m.push("");}}if(c){let p=O(i,{transferable:true,limit:u});if(p.length>0){m.push("## Transferable Insights");for(let g of p)m.push(`- [${g.trigger}] ${g.insight.slice(0,150)}${g.insight.length>150?"...":""}`);m.push("");}}if(s){let p=k(e.rootDir,{pending_only:true,limit:10});if(p.length>0){m.push("## Pending Nominations");for(let g of p)m.push(`- [${g.urgency}] ${g.brief}`);m.push("");}}return {text:o({agent:i,context:m.join(`
35
- `),sections_included:{profile:true,decisions:a,journal:c,nominations:s}}),handled:true}}case "paradigm_ambient_promote":{let i=t.agent,r=nt(e.rootDir,i);return {text:o({agent:i,promoted:r.promoted,entries:r.entries}),handled:true}}case "paradigm_ambient_learn":{let i=t.agent,r=t.dry_run===true,s=et(e.rootDir,i);if(r)return {text:o({agent:i,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,i);return {text:o({agent:i,...a,stats:s}),handled:true}}case "paradigm_ambient_neverland":{let i=It(e.rootDir);return {text:o(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:o(await De(e.rootDir,t)),handled:true};default:return {text:`Unknown ambient tool: ${n}`,handled:false}}}var Ee={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function xe(n){try{let t=b.join(n,".paradigm","config.yaml");if(f.existsSync(t)){let o=f.readFileSync(t,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(o)return o[1].trim()}}catch{}return b.basename(n)}async function De(n,t={}){let e=t.dry_run===true,o=xe(n),i=b$2(n),r=i.filter(p=>p.type==="user-verdict"&&p.verdict&&p.agent);if(r.length===0)return {sessionEntries:i.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:e,details:[]};let s=new Map;for(let p of r){let g=p.agent;s.has(g)||s.set(g,[]),s.get(g).push(p);}let a=i.filter(p=>p.type==="agent-contribution"),c=new Map;for(let p of a)p.agent&&(c.has(p.agent)||c.set(p.agent,[]),c.get(p.agent).push(p));let d=[],u={},l=0;for(let[p,g]of s){u[p]=0;let D=g.filter(h=>h.verdict==="accepted").length;g.filter(h=>h.verdict==="dismissed").length;g.filter(h=>h.verdict==="revised").length;let B=g.length,Bt=B>0?D/B:0;for(let h of g){let H=Ee[h.verdict];if(!H)continue;let Ht=c.get(p)?.shift(),it=Re(h,Ht,{acceptRate:Bt,total:B,accepted:D}),Wt=h.verdict==="accepted"?.85:h.verdict==="revised"?.6:.4,qt={agent:p,verdict:h.verdict,trigger:H,insight:it,symbols:h.symbols};if(d.push(qt),e)u[p]++,l++;else try{z(p,{trigger:H,insight:it,confidence_before:h.verdict==="accepted"?.7:.8,confidence_after:Wt,project:o,transferable:h.verdict==="dismissed",tags:["postflight",`verdict:${h.verdict}`,...(h.symbols||[]).map(Gt=>`symbol:${Gt}`)]}),u[p]++,l++;}catch{}}}let m={},y=0;if(!e)for(let p of s.keys())try{let g=nt(n,p);g.promoted>0&&(m[p]=g.promoted,y+=g.promoted);}catch{}return {sessionEntries:i.length,agentsProcessed:Array.from(s.keys()),journalsWritten:l,journalsByAgent:u,promoted:y,promotedByAgent:m,dryRun:e,details:d}}function Re(n,t,e){let o=n.symbols?.length?` (symbols: ${n.symbols.join(", ")})`:"",i=n.reason?` Reason: ${n.reason}.`:"";switch(n.verdict){case "accepted":return `Contribution accepted by user${o}.${i}`+(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}.${i}`+(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}.${i}`+(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}.${i}`}}export{Ge as getAmbientToolsList,ze as handleAmbientTool,De as runPostflightLearning};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as a from'fs';import*as c from'path';import {Glob}from'glob';function s(t){let e=r=>{if(r.includes("*"))try{return new Glob(r,{cwd:t,nodir:!0}).walkSync().length>0}catch{return false}return a.existsSync(c.join(t,r))};return e("project.godot")||e("Assets/ProjectSettings")?"game":e("Package.swift")&&!e("package.json")?e("Sources/*/App")||e("**/AppDelegate.swift")?"macos-app":"ios-app":e("pubspec.yaml")?"flutter-app":e("supabase")&&(e("next.config.*")||e("vite.config.*"))?"saas-web-app":e("next.config.*")||e("vite.config.*")||e("nuxt.config.*")?"web-app":e("Dockerfile")||e("prisma")||e("drizzle.config.*")?"backend-api":e("Cargo.toml")?"rust-project":e("pyproject.toml")||e("setup.py")||e("requirements.txt")?"python-project":"generic"}var n={"saas-web-app":["advocate","architect","builder","reviewer","tester","security","documentor","designer","copywriter","performance","devops","dba","e2e","dx","seo","pm","product","sales","legal","a11y","qa","debugger","release","narrator"],"web-app":["advocate","architect","builder","reviewer","tester","security","documentor","designer","copywriter","performance","devops","e2e","seo","a11y","qa","debugger"],"backend-api":["advocate","architect","builder","reviewer","tester","security","documentor","devops","dba","performance","dx","qa","debugger","release"],"ios-app":["advocate","architect","builder","reviewer","tester","security","documentor","designer","mobile","performance","a11y","qa","debugger"],"macos-app":["advocate","architect","builder","reviewer","tester","security","documentor","designer","performance","qa","debugger"],"flutter-app":["advocate","architect","builder","reviewer","tester","security","documentor","designer","mobile","performance","a11y","debugger"],game:["advocate","architect","builder","reviewer","tester","documentor","gamedev","3d","audio","designer","performance","debugger"],"rust-project":["advocate","architect","builder","reviewer","tester","security","documentor","performance","debugger","qa"],"python-project":["advocate","architect","builder","reviewer","tester","security","documentor","performance","debugger","qa"],generic:["advocate","architect","builder","reviewer","tester","security","documentor","debugger","qa"]};export{s as a,n as b};
@@ -1,29 +0,0 @@
1
- #!/usr/bin/env node
2
- import {v,i,f,j as j$1}from'./chunk-QWL3LERH.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}from'./chunk-5TAVYPOV.js';import*as u from'fs';import*as g from'path';import*as W from'js-yaml';import*as R from'os';function G(e){return g.join(e,q,st)}function at(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${e}-${t}`}function k(e,t){let n={id:at(),timestamp:new Date().toISOString(),...t};w.push(n),w.length>N&&(w=w.slice(-N));try{let r=g.join(e,q);u.mkdirSync(r,{recursive:!0});let o=G(e);u.appendFileSync(o,JSON.stringify(n)+`
3
- `,"utf8"),ct(o);}catch{}return n}function ct(e){try{if(u.statSync(e).size>512*1024){let r=u.readFileSync(e,"utf8").trim().split(`
4
- `);if(r.length>N){let o=r.slice(-N);u.writeFileSync(e,o.join(`
5
- `)+`
6
- `,"utf8");}}}catch{}}function Dt(e,t){let n=lt(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 lt(e){let t=G(e);if(!u.existsSync(t))return [...w];try{return u.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 [...w]}}function Y(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 f=[r,o,i,a].sort((l,s)=>s-l),c=f[0]*.5+f[1]*.2+f[2]*.15+f[3]*.15,d=n.threshold??.6;return {agentId:t,score:c,breakdown:{symbolMatch:r,pathMatch:o,conceptMatch:i,signalMatch:a},shouldNominate:c>=d,quietReason:c<d?"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 q,st,N,w,z=b(()=>{q=".paradigm/events",st="stream.jsonl",N=1e3,w=[];});var j,H=b(()=>{j={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"]},learning_journal:{ring:"user-scoped",allow_content:["pattern_descriptions","confidence_adjustments","approach_descriptions"],deny_content:["code_snippets","file_contents","symbol_names_with_context"],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"]}},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"]}};});function C(e){let t=g.join(e,dt);if(!u.existsSync(t))return {...j};try{let n=u.readFileSync(t,"utf8"),r=W.load(n);return ut(j,r)}catch{return {...j}}}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 $(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(o=>F(o,t))||e.observation?.deny?.some(r=>F(r,t))?false:e.observation?.allow?.length?e.observation.allow.some(r=>F(r,t)):true}function Ot(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 f=new RegExp(a.pattern,"gi"),c=i.match(f);c&&(o.push(...c),i=i.replace(f,a.replacement||"[REDACTED]"));}catch{}return {filtered:i,redacted:o}}function F(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(()=>{H();dt=".paradigm/data-policy.yaml";});function _t(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function St(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${e}-${t}`}function Z(e,t){let n=i(e),r=C(e),o=[];for(let d of n){if(!d.attention||d.benched||t.path&&!$(r,t.path,d.id))continue;let l=Y(t,d.id,d.attention);l.shouldNominate&&o.push({profile:d,score:l});}if(o.length===0)return {nominations:[],debates:[]};let i$1=D(e,{since:new Date(Date.now()-3e4).toISOString()}),a=o.filter(({profile:d})=>!i$1.find(s=>s.agent===d.id&&s.brief===K(d,t,{...o.find(m=>m.profile.id===d.id).score})));if(a.length===0)return {nominations:[],debates:[]};let f=a.map(({profile:d,score:l})=>{let s=wt(t,l),m=kt(d,t);return {id:_t(),agent:d.id,relevance:l.score,urgency:s,type:m,brief:K(d,t,l),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});vt(e,f);let c=xt(e,f);return c.length>0&&Et(e,c),{nominations:f,debates:c}}function wt(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 kt(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 xt(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(d=>d.agent)).size<2)continue;let f=new Set(i.map(d=>d.type)),c=f.size>1&&f.has("warning")&&f.has("suggestion");n.push({id:St(),topic:`Multiple agents responded to event ${o}`,nominations:i.map(d=>d.id),type:c?"conflicting":"complementary",overlap_events:[o]});}return n}function O(e){return g.join(e,_,ft)}function M(e){return g.join(e,_,mt)}function vt(e,t){try{let n=g.join(e,_);u.mkdirSync(n,{recursive:!0});let r=O(e),o=t.map(a=>JSON.stringify(a)).join(`
8
- `)+`
9
- `;u.appendFileSync(r,o,"utf8"),Q(r,gt);let{nominationTtlDays:i}=A(e);tt(r,i*24*60*60*1e3);}catch{}}function Et(e,t){try{let n=g.join(e,_);u.mkdirSync(n,{recursive:!0});let r=M(e),o=t.map(a=>JSON.stringify(a)).join(`
10
- `)+`
11
- `;u.appendFileSync(r,o,"utf8"),Q(r,pt);let{debateTtlDays:i}=A(e);tt(r,i*24*60*60*1e3);}catch{}}function Q(e,t){try{let r=u.readFileSync(e,"utf8").trim().split(`
12
- `).filter(o=>o.trim());if(r.length>t){let o=r.slice(-t);u.writeFileSync(e,o.join(`
13
- `)+`
14
- `,"utf8");}}catch{}}function A(e){let t={nominationTtlDays:yt,debateTtlDays:ht};try{let n=g.join(e,".paradigm","config.yaml");if(!u.existsSync(n))return t;let r=a("js-yaml"),o=u.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(!u.existsSync(e))return;let r=u.readFileSync(e,"utf8").trim().split(`
15
- `).filter(a=>a.trim());if(r.length<=bt)return;let o=Date.now()-t,i=r.filter(a=>{try{let f=JSON.parse(a);return (f.timestamp?new Date(f.timestamp).getTime():Date.now())>=o}catch{return !0}});i.length<r.length&&u.writeFileSync(e,i.join(`
16
- `)+`
17
- `,"utf8");}catch{}}function D(e,t){let n=O(e);if(!u.existsSync(n))return [];try{let o=u.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 Jt(e){let t=M(e);if(!u.existsSync(t))return [];try{return u.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 Bt(e,t,n,r){let o=O(e);if(!u.existsSync(o))return false;try{let a=u.readFileSync(o,"utf8").trim().split(`
20
- `),f=!1,c=a.map(d=>{try{let l=JSON.parse(d);return l.id===t?(l.engaged=!0,l.response=n,r&&(l.reason=r),f=!0,JSON.stringify(l)):d}catch{return d}});if(f&&(u.writeFileSync(o,c.join(`
21
- `)+`
22
- `,"utf8"),n==="accepted"||n==="dismissed")){let d=JSON.parse(a.find(s=>{try{return JSON.parse(s).id===t}catch{return !1}}));i(e).find(s=>s.id===d.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&k(e,{type:"work-completed",source:"agent-action",agent:d.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return f}catch{return false}}function qt(e,t,n,r){let o=M(e);if(!u.existsSync(o))return false;try{let a=u.readFileSync(o,"utf8").trim().split(`
23
- `),f=!1,c=a.map(d=>{try{let l=JSON.parse(d);if(l.id===t){l.resolution={chosen:n,reason:r,resolved_by:"human",resolved_at:new Date().toISOString()},f=!0;let s=l.nominations.filter(m=>m!==n);for(let m of s){let p=D(e).find(y=>y.id===m);p&&k(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 d}catch{return d}});return f&&u.writeFileSync(o,c.join(`
24
- `)+`
25
- `,"utf8"),f}catch{return false}}function Gt(e){let t=g.join(e,_,".last-processed"),n="";try{u.existsSync(t)&&(n=u.readFileSync(t,"utf8").trim());}catch{}let r=g.join(e,_,"stream.jsonl");if(!u.existsSync(r))return {processed:0,nominations:[]};let o=[];try{o=u.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 f=[],c=a.slice(0,50);for(let l of c){let{nominations:s}=Z(e,l);f.push(...s);}let d=c[c.length-1];try{u.mkdirSync(g.join(e,_),{recursive:!0}),u.writeFileSync(t,d.id,"utf8");}catch{}return {processed:c.length,nominations:f}}function Yt(e,t,n){let r=C(e);if(t.path&&!$(r,t.path))return {event:k(e,t),nominations:[],debates:[]};let o=k(e,t);if(n?.skipNominations)return {event:o,nominations:[],debates:[]};let{nominations:i,debates:a}=Z(e,o);return i.length>0&&jt(e,i),{event:o,nominations:i,debates:a}}function zt(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=D(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 d=c.filter(b=>b.response==="accepted").length,l=c.filter(b=>b.response==="dismissed").length,s=d/c.length,m=l/c.length,p=r,y="No adjustment needed";if(m>.6?(p=Math.min(.95,r+.05),y=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):s>.8&&(p=Math.max(.2,r-.05),y=`High accept rate (${(s*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),p===r)return {adjusted:false,oldThreshold:r,newThreshold:p,reason:y};n.attention.threshold=p;let S=g.join(e,".paradigm/agents",`${t}.agent`),x=u.existsSync(S)?"project":"global";return j$1(t,n,x,e),k(e,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${r.toFixed(2)} \u2192 ${p.toFixed(2)} (${y})`,data:{old_threshold:r,new_threshold:p,accept_rate:s,dismiss_rate:m}}),{adjusted:true,oldThreshold:r,newThreshold:p,reason:y}}function Nt(e,t){let{nominationTtlDays:n}=A(e),r=n*24*60*60*1e3,i=D(e,{agent:t}).filter(s=>s.engaged||Date.now()-new Date(s.timestamp).getTime()<r),a=i.filter(s=>s.response==="accepted").length,f=i.filter(s=>s.response==="dismissed").length,c=i.filter(s=>s.response==="deferred").length,d=i.filter(s=>!s.engaged).length,l=a+f+c;return {total:i.length,accepted:a,dismissed:f,deferred:c,pending:d,acceptRate:l>0?a/l:0}}function Ht(e){let n=i(e).filter(s=>!s.benched).map(s=>{let m=Nt(e,s.id),p=0;try{let y=g.join(R.homedir(),".paradigm","notebooks",s.id);u.existsSync(y)&&(p=u.readdirSync(y).filter(S=>S.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),f=n.reduce((s,m)=>s+m.notebookCount,0),c=n.reduce((s,m)=>s+m.transferableCount,0),d=n.reduce((s,m)=>s+m.totalNominations,0),l;return d<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:f,totalTransferable:c},healthStatus:l}}function jt(e,t){if(t.length===0)return;let n=g.join(R.homedir(),".paradigm","score","outbox");if(u.existsSync(n))try{let r=g.join(n,`nom-${Date.now()}.json`),o={type:"nomination_forward",nominations:t.map(i=>({...i})),origin:Tt(e),timestamp:new Date().toISOString()};u.writeFileSync(r,JSON.stringify(o),"utf8");}catch{}}function Tt(e){try{let t=g.join(e,".paradigm","config.yaml");if(u.existsSync(t)){let r=u.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(f$1)),d$1=(g$2(),d(f$2));n=c.loadJournalEntries,r=d$1.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],f=[];for(let c of a)if(!c.promoted_to_notebook&&!((c.confidence_after??0)<.8))try{let{entry:d}=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);f.push({journalId:c.id,notebookId:d.id});try{let l=g.join(R.homedir(),".paradigm","agents",t,"journal");if(u.existsSync(l)){let s=u.readdirSync(l).filter(m=>m.endsWith(".yaml"));for(let m of s){let p=g.join(l,m),y=u.readFileSync(p,"utf8");if(y.includes(c.id)){let S=y.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${d.id}"`);if(S===y){let x=y.trimEnd().split(`
27
- `);x.push(`promoted_to_notebook: "${d.id}"`),u.writeFileSync(p,x.join(`
28
- `)+`
29
- `,"utf8");}else u.writeFileSync(p,S,"utf8");break}}}}catch{}}catch{}return {promoted:f.length,entries:f}}function Wt(e){let t=g.join(e,Rt),n={default_min_urgency:"low",enable_debates:true};if(!u.existsSync(t))return n;try{let r=a("js-yaml"),o=u.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(f=>f.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 f=n[a.min_urgency]??3;return i<=f}}}return i<=r})}var _,ft,mt,gt,pt,yt,ht,bt,Rt,At=b(()=>{z();X();v();_=".paradigm/events",ft="nominations.jsonl",mt="debates.jsonl",gt=500,pt=200,yt=7,ht=14,bt=100;Rt=".paradigm/surfacing.yaml";});export{Dt as a,z as b,C as c,Ot as d,X as e,Z as f,xt as g,vt as h,D as i,Jt as j,Bt as k,qt as l,Gt as m,Yt as n,zt as o,Nt as p,Ht as q,jt as r,Vt as s,Wt as t,Xt as u,At as v};
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- import {h,g as g$1}from'./chunk-SL3RZQPW.js';import {d}from'./chunk-5TAVYPOV.js';import*as i from'fs';import*as a from'path';import*as D from'os';import*as x from'crypto';import*as p from'js-yaml';function T(){let n=a.join(D.homedir(),".paradigm");return i.existsSync(n)||i.mkdirSync(n,{recursive:true}),n}function N(n){let s=a.resolve(n);return x.createHash("sha256").update(s).digest("hex").slice(0,12)}function f(n){let s=N(n),t=a.join(T(),"sessions",s);i.existsSync(t)||i.mkdirSync(t,{recursive:true});let e=a.join(t,"pending-handoffs");return i.existsSync(e)||i.mkdirSync(e,{recursive:true}),t}function b(n){let s=f(n),t=a.join(s,"_project-meta.json"),o={name:a.basename(a.resolve(n)),path:a.resolve(n),lastSeen:new Date().toISOString()};i.writeFileSync(t,JSON.stringify(o,null,2));}function M(n,s){let t=f(n),e=a.join(t,"pending-handoffs",`${s.id}.json`);i.writeFileSync(e,JSON.stringify(s,null,2));}function E(n){let s=f(n),t=a.join(s,"pending-handoffs");if(!i.existsSync(t))return [];let e=[];try{let o=i.readdirSync(t);for(let l of o)if(l.endsWith(".json"))try{let u=i.readFileSync(a.join(t,l),"utf8"),m=JSON.parse(u);m.status==="pending"&&e.push(m);}catch{}}catch{}return e.sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime()),e}function O(n,s){let t=f(n),e=a.join(t,"pending-handoffs",`${s}.json`);if(i.existsSync(e))try{let o=i.readFileSync(e,"utf8"),l=JSON.parse(o);l.status="delivered",i.writeFileSync(e,JSON.stringify(l,null,2));}catch{}}function g(){let n=a.join(T(),"wisdom");return i.existsSync(n)||i.mkdirSync(n,{recursive:true}),n}function A(){let n=a.join(g(),"antipatterns.yaml");if(!i.existsSync(n))return [];try{let s=i.readFileSync(n,"utf8");return p.load(s)?.antipatterns||[]}catch{return []}}function W(){let n=a.join(g(),"decisions");if(!i.existsSync(n))return [];let s=[];try{let t=i.readdirSync(n);for(let e of t)if(!(!e.endsWith(".yaml")&&!e.endsWith(".yml")))try{let o=i.readFileSync(a.join(n,e),"utf8"),l=p.load(o);s.push(l);}catch{}}catch{}return s.sort((t,e)=>t.id.localeCompare(e.id)),s}function H(){let n=a.join(g(),"preferences.yaml");if(!i.existsSync(n))return null;try{let s=i.readFileSync(n,"utf8");return p.load(s)}catch{return null}}function L(n){let s=a.join(g(),"antipatterns.yaml"),t={version:"1.0",antipatterns:[]};if(i.existsSync(s))try{let e=i.readFileSync(s,"utf8");t=p.load(e),t.antipatterns||(t.antipatterns=[]);}catch{}t.antipatterns.push({...n,added:new Date().toISOString()}),i.writeFileSync(s,p.dump(t,{lineWidth:-1}));}function _(n){let s=a.join(g(),"decisions");i.existsSync(s)||i.mkdirSync(s,{recursive:true});let t=n.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),e=`${n.id}-${t}.yaml`,o=a.join(s,e);i.writeFileSync(o,p.dump(n,{lineWidth:-1}));}var S={"claude-opus-4":{input:15,output:75,name:"Claude Opus 4"},"claude-sonnet-4":{input:3,output:15,name:"Claude Sonnet 4"},"claude-haiku-3.5":{input:.8,output:4,name:"Claude Haiku 3.5"}},w=50,j=".paradigm/session-breadcrumbs.json",P=".paradigm/session-checkpoint.json",F=10080*60*1e3,k=class{session;rootDir=null;_recovered=false;lastLoreEntryId=null;constructor(){this.session=this.createNewSession();}setRootDir(s){this.rootDir=s;try{let{clearSessionWorkLog:t}=(h(),d(g$1));t(s);}catch{}}createNewSession(){return {sessionId:`s${Date.now().toString(36)}`,startTime:Date.now(),lastActivity:Date.now(),model:"claude-sonnet-4",resourceReads:[],toolCalls:[],breadcrumbs:[],totals:{resourceReadCount:0,toolCallCount:0,totalBytes:0,totalTokens:0,estimatedCostUsd:0}}}addBreadcrumb(s,t,e={}){this.session.breadcrumbs.push({timestamp:Date.now(),action:s,tool:e.tool,symbol:e.symbol,summary:t}),this.session.breadcrumbs.length>w&&(this.session.breadcrumbs=this.session.breadcrumbs.slice(-w)),this.persistBreadcrumbs();}getBreadcrumbs(s=20){return this.session.breadcrumbs.slice(-s)}persistBreadcrumbs(){if(!this.rootDir)return;let s={sessionId:this.session.sessionId,startTime:this.session.startTime,lastActivity:this.session.lastActivity,breadcrumbs:this.session.breadcrumbs,symbolsModified:this.extractSymbolsFromBreadcrumbs(),filesExplored:this.extractFilesFromBreadcrumbs()},t;try{t=JSON.stringify(s,null,2);}catch(e){console.error("[paradigm-mcp] persistBreadcrumbs: JSON.stringify failed:",e.message);return}try{let e=a.join(this.rootDir,j),o=a.dirname(e);i.existsSync(o)||i.mkdirSync(o,{recursive:!0}),i.writeFileSync(e,t);}catch(e){console.error("[paradigm-mcp] persistBreadcrumbs: local write failed:",e.message);}try{let e=f(this.rootDir);i.writeFileSync(a.join(e,"breadcrumbs.json"),t),b(this.rootDir);}catch(e){console.error("[paradigm-mcp] persistBreadcrumbs: global write failed:",e.message);}}loadPreviousSession(){if(!this.rootDir)return null;try{let s=f(this.rootDir),t=a.join(s,"breadcrumbs.json");if(i.existsSync(t)){let e=i.readFileSync(t,"utf8");return JSON.parse(e)}}catch{}try{let s=a.join(this.rootDir,j);if(!i.existsSync(s))return null;let t=i.readFileSync(s,"utf8");return JSON.parse(t)}catch{return null}}saveCheckpoint(s){let t={phase:s.phase,context:s.context,timestamp:Date.now(),sessionId:this.session.sessionId,externalId:s.externalId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:this.session.breadcrumbs.slice(-10)},e=this.persistCheckpoint(t);return {checkpoint:t,persisted:e}}loadCheckpoint(){if(!this.rootDir)return null;let s=null;try{let t=f(this.rootDir),e=a.join(t,"checkpoint.json");if(i.existsSync(e)){let o=i.readFileSync(e,"utf8");s=JSON.parse(o);}}catch{}if(!s)try{let t=a.join(this.rootDir,P);if(i.existsSync(t)){let e=i.readFileSync(t,"utf8");s=JSON.parse(e);}}catch{}if(s&&Date.now()-s.timestamp>F)return null;if(s)for(let t of ["modifiedFiles","symbolsTouched","decisions"]){let e=s[t];if(typeof e=="string")try{s[t]=JSON.parse(e);}catch{s[t]=[];}}return s}persistCheckpoint(s){let t={local:false,global:false};if(!this.rootDir)return console.error("[paradigm-mcp] persistCheckpoint: rootDir not set, skipping write"),t;let e;try{e=JSON.stringify(s,null,2);}catch(o){return console.error("[paradigm-mcp] persistCheckpoint: JSON.stringify failed:",o.message),t}try{let o=a.join(this.rootDir,P),l=a.dirname(o);i.existsSync(l)||i.mkdirSync(l,{recursive:!0}),i.writeFileSync(o,e),t.local=!0;}catch(o){console.error("[paradigm-mcp] persistCheckpoint: local write failed:",o.message);}try{let o=f(this.rootDir);i.writeFileSync(a.join(o,"checkpoint.json"),e),b(this.rootDir),t.global=!0;}catch(o){console.error("[paradigm-mcp] persistCheckpoint: global write failed:",o.message);}return t}setLastLoreEntryId(s){this.lastLoreEntryId=s;}getLastLoreEntryId(){return this.lastLoreEntryId}hasRecoveredThisSession(){return this._recovered}markRecovered(){this._recovered=true;}extractSymbolsFromBreadcrumbs(){let s=new Set;for(let t of this.session.breadcrumbs)t.symbol&&s.add(t.symbol);return Array.from(s)}extractFilesFromBreadcrumbs(){let s=new Set;for(let t of this.session.breadcrumbs){let e=t.summary.match(/\b[\w./]+\.(ts|js|tsx|jsx|py|go|rs|yaml|json|md)\b/g);if(e)for(let o of e)s.add(o);}return Array.from(s)}estimateTokens(s){let t=typeof s=="number"?s:s.length;return Math.ceil(t/3.5)}calculateCost(s,t=true){let e=S[this.session.model],o=t?e.output:e.input;return s/1e6*o}setModel(s){this.session.model=s,this.recalculateTotals();}getModel(){return this.session.model}trackResourceRead(s,t){let e=this.extractResourceType(s),o=this.estimateTokens(t);this.session.resourceReads.push({timestamp:Date.now(),resourceType:e,uri:s,bytes:t,tokens:o}),this.session.lastActivity=Date.now(),this.updateTotals(t,o);}trackToolCall(s,t){let e=this.estimateTokens(t);this.session.toolCalls.push({timestamp:Date.now(),toolName:s,responseBytes:t,responseTokens:e}),this.session.lastActivity=Date.now(),this.updateTotals(t,e);}updateTotals(s,t){this.session.totals.resourceReadCount=this.session.resourceReads.length,this.session.totals.toolCallCount=this.session.toolCalls.length,this.session.totals.totalBytes+=s,this.session.totals.totalTokens+=t,this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}recalculateTotals(){this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}extractResourceType(s){return s.replace("paradigm://","").split("/")[0]||"unknown"}getStats(){return {...this.session}}getCostBreakdown(){let s={},t=0,e=0;for(let r of this.session.resourceReads)s[r.resourceType]||(s[r.resourceType]={count:0,bytes:0,tokens:0}),s[r.resourceType].count++,s[r.resourceType].bytes+=r.bytes,s[r.resourceType].tokens+=r.tokens,t+=r.bytes,e+=r.tokens;let o={},l=0,u=0;for(let r of this.session.toolCalls)o[r.toolName]||(o[r.toolName]={count:0,bytes:0,tokens:0}),o[r.toolName].count++,o[r.toolName].bytes+=r.responseBytes,o[r.toolName].tokens+=r.responseTokens,l+=r.responseBytes,u+=r.responseTokens;let m=e+u,h=this.calculateCost(m);return {model:S[this.session.model].name,modelId:this.session.model,pricing:S[this.session.model],resources:{count:this.session.resourceReads.length,bytes:t,tokens:e,costUsd:this.calculateCost(e),byType:s},tools:{count:this.session.toolCalls.length,bytes:l,tokens:u,costUsd:this.calculateCost(u),byName:o},total:{tokens:m,costUsd:h}}}getHandoffRecommendation(s=2e5,t){let e=this.session.totals.totalTokens,o=e*4,l=t||e+o,u=Math.round(l/s*100),m,h;u>=85?(m="handoff-urgent",h="Context is nearly full. Initiate handoff immediately to preserve session continuity."):u>=70?(m="handoff-recommended",h="Context usage is high. Consider initiating handoff soon to ensure smooth transition."):u>=50?(m="consider-handoff",h="Context usage is moderate. Plan a good stopping point for potential handoff."):(m="continue",h="Context usage is healthy. Continue working.");let r=[],C=Math.round((Date.now()-this.session.startTime)/6e4),v=this.session.toolCalls.length+this.session.resourceReads.length;return v>50&&r.push(`High number of MCP interactions (${v})`),C>30&&r.push(`Session duration >30 min (${C} min)`),this.session.totals.totalBytes>5e5&&r.push(`Large data volume (${Math.round(this.session.totals.totalBytes/1024)}KB)`),{recommendation:m,message:h,usagePercent:u,signals:r}}getDurationMinutes(){return Math.round((Date.now()-this.session.startTime)/6e4)}reset(){this.session=this.createNewSession(),this._recovered=false,this.lastLoreEntryId=null;}},y=null;function G(){return y||(y=new k),y}function $(){y&&y.reset();}
3
- export{M as a,E as b,O as c,A as d,W as e,H as f,L as g,_ as h,S as i,G as j,$ as k};
@@ -1,9 +0,0 @@
1
- #!/usr/bin/env node
2
- import {c as c$1,a as a$1}from'./chunk-HMQ5BHP2.js';import {e as e$1}from'./chunk-JQKKVAAN.js';import {a}from'./chunk-LKAT7IAK.js';import*as e from'fs';import*as i from'path';import*as x from'js-yaml';import c from'chalk';async function rs(A={}){let l=A.rootDir||process.cwd(),s=[],k=A.quiet,q=A.context;k||(console.log(c.blue(`
3
- \u{1FA7A} Paradigm Doctor
4
- `)),console.log(q?c.gray(`Running context audit checks...
5
- `):c.gray(`Checking Paradigm setup...
6
- `)));let L=a.command("doctor").start("Running health checks");if(!q){let M=function(t){let a=[];try{let n=e.readdirSync(t,{withFileTypes:!0});for(let o of n){if(o.name==="node_modules"||o.name==="dist"||o.name===".git")continue;let m=i.join(t,o.name);o.isDirectory()?a.push(...M(m)):o.name===".purpose"&&a.push(m);}}catch{}return a};let r=i.join(l,".paradigm");if(e.existsSync(r))if(e.statSync(r).isFile())s.push({name:".paradigm",status:"warn",message:"Legacy file format (should be directory)",fix:"paradigm upgrade --all"});else {s.push({name:".paradigm/",status:"ok",message:"Directory exists"});let a=i.join(r,"config.yaml");if(e.existsSync(a))try{let d=e.readFileSync(a,"utf8");e$1(d),s.push({name:".paradigm/config.yaml",status:"ok",message:"Valid YAML"});}catch(d){s.push({name:".paradigm/config.yaml",status:"error",message:`Invalid YAML: ${d.message}`,fix:"Check YAML syntax"});}else s.push({name:".paradigm/config.yaml",status:"missing",message:"Config file not found",fix:"paradigm init --force"});let n=["logger.md","scan.md","symbols.md"],o=i.join(r,"specs");if(e.existsSync(o))for(let d of n){let w=i.join(o,d);e.existsSync(w)?s.push({name:`.paradigm/specs/${d}`,status:"ok",message:"Present"}):s.push({name:`.paradigm/specs/${d}`,status:"missing",message:"Spec file not found",fix:"paradigm upgrade --all"});}else s.push({name:".paradigm/specs/",status:"missing",message:"Specs directory not found",fix:"paradigm upgrade --all"});let m=i.join(r,"docs");e.existsSync(m)?s.push({name:".paradigm/docs/",status:"ok",message:"Directory exists"}):s.push({name:".paradigm/docs/",status:"missing",message:"Docs directory not found",fix:"paradigm upgrade --all"});let h=i.join(r,"prompts");e.existsSync(h)?s.push({name:".paradigm/prompts/",status:"ok",message:"Directory exists"}):s.push({name:".paradigm/prompts/",status:"missing",message:"Prompts directory not found",fix:"paradigm upgrade --all"});let u=i.join(r,"scan-index.json"),g=i.join(l,".paradigm-scan-index.json");if(e.existsSync(u)){let d=e.statSync(u),w=Date.now()-d.mtime.getTime(),y=Math.floor(w/(1e3*60*60));y>24?s.push({name:".paradigm/scan-index.json",status:"warn",message:`Stale (${y} hours old)`,fix:"paradigm index"}):s.push({name:".paradigm/scan-index.json",status:"ok",message:y>0?`${y} hours old`:"Fresh"});}else e.existsSync(g)?s.push({name:"scan-index",status:"warn",message:"Using legacy location",fix:"paradigm index"}):s.push({name:".paradigm/scan-index.json",status:"missing",message:"Not generated",fix:"paradigm index"});}else s.push({name:".paradigm/",status:"missing",message:"Not initialized",fix:"paradigm init"});let f=c$1(l);if(f.detected){let t=a$1(f.detected);if(t){let a=i.join(l,t.outputPath);e.existsSync(a)?s.push({name:t.outputPath,status:"ok",message:`Present (${f.detected})`}):s.push({name:t.outputPath,status:"missing",message:`Not generated for ${f.detected}`,fix:"paradigm sync"});}}let p=i.join(l,".premise");e.existsSync(p)?s.push({name:".premise",status:"ok",message:"Present"}):s.push({name:".premise",status:"missing",message:"Not found (optional)"});let j=i.join(l,".purpose");e.existsSync(j)?s.push({name:".purpose",status:"ok",message:"Present"}):s.push({name:".purpose",status:"warn",message:"Root .purpose not found",fix:"paradigm init"});let P=i.join(l,".paradigm","config.yaml");if(e.existsSync(P))try{let t=e.readFileSync(P,"utf8"),n=x.load(t)?.["purpose-required"];if(n&&Array.isArray(n)){let o=[];for(let m of n){if(!m.pattern)continue;let{glob:h}=await import('glob'),u=await h(m.pattern,{cwd:l,nodir:!1});for(let g of u){let d=i.join(l,g);try{e.statSync(d).isDirectory()&&!e.existsSync(i.join(d,".purpose"))&&o.push(g);}catch{}}}o.length>0?s.push({name:"Purpose-required",status:"warn",message:`${o.length} director${o.length===1?"y":"ies"} missing .purpose: ${o.join(", ")}`,fix:"Create .purpose files with paradigm_purpose_init + paradigm_purpose_add_component"}):s.push({name:"Purpose-required",status:"ok",message:"All required directories have .purpose files"});}}catch{}let F=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi,v=0,T=M(l);for(let t of T)try{let n=e.readFileSync(t,"utf8").match(F);n&&(v+=n.length);}catch{}v>0?s.push({name:"Clarification markers",status:"warn",message:`${v} [NEEDS CLARIFICATION] marker${v>1?"s":""} found in .purpose files`,fix:"Resolve open clarification markers before shipping"}):T.length>0&&s.push({name:"Clarification markers",status:"ok",message:"No unresolved markers"});let E=i.join(l,"portal.yaml");if(e.existsSync(E))try{let t=e.readFileSync(E,"utf8"),a=x.load(t);if(a?.version&&a?.gates){let n=Object.keys(a.gates||{}).length,o=Object.keys(a.routes||{}).length;s.push({name:"portal.yaml",status:"ok",message:`Valid (${n} gates, ${o} routes)`});}else s.push({name:"portal.yaml",status:"warn",message:"Missing version or gates section",fix:'Add version: "1.0" and gates: {} to portal.yaml'});}catch(t){s.push({name:"portal.yaml",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in portal.yaml"});}if(e.existsSync(E))try{let{checkPortalCompliance:t,getComplianceSummary:a}=await import('./portal-compliance-4MG5F2GI.js'),n=await t(l),o=a(n);s.push({name:"Portal compliance",status:o.status,message:o.message,fix:o.status!=="ok"?"paradigm portal check":void 0});}catch{}let W=i.join(l,".paradigm","flows.yaml");if(e.existsSync(W))try{let t=e.readFileSync(W,"utf8"),a=x.load(t);if(a?.version&&a?.flows){let n=Object.keys(a.flows||{}).length,o=Object.entries(a.flows||{}).filter(([,m])=>!m?.steps||(m.steps?.length??0)===0);o.length>0?s.push({name:".paradigm/flows.yaml",status:"warn",message:`${n} flows defined, ${o.length} have no steps`,fix:"Add steps to empty flow definitions"}):s.push({name:".paradigm/flows.yaml",status:"ok",message:`Valid (${n} flows)`});}else s.push({name:".paradigm/flows.yaml",status:"warn",message:"Missing version or flows section",fix:'Ensure flows.yaml has version: "1.0" and flows: {}'});}catch(t){s.push({name:".paradigm/flows.yaml",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in flows.yaml"});}let Y=i.join(l,".paradigm","lore");if(e.existsSync(Y))try{let t=e.readdirSync(Y).filter(a=>a.endsWith(".yaml"));t.length===0?s.push({name:"Lore entries",status:"warn",message:"Lore directory exists but no entries found",fix:"Record a lore entry: paradigm lore record"}):s.push({name:"Lore entries",status:"ok",message:`${t.length} lore file${t.length>1?"s":""}`});}catch{s.push({name:"Lore entries",status:"warn",message:"Could not read lore directory"});}let U=i.join(l,".paradigm","university");if(e.existsSync(U))try{let t=i.join(U,"content"),a=0,n=0;if(e.existsSync(t))for(let o of ["notes","policies","quizzes","paths"]){let m=i.join(t,o);e.existsSync(m)&&(a+=e.readdirSync(m).filter(h=>h.endsWith(".md")||h.endsWith(".yaml")).length);}if(a===0)s.push({name:"University content",status:"warn",message:"University directory exists but no content found",fix:'Add content: paradigm university add note --title "Getting Started"'});else {let o=i.join(t,"quizzes");if(e.existsSync(o))for(let h of e.readdirSync(o).filter(u=>u.endsWith(".yaml")))try{let u=x.load(e.readFileSync(i.join(o,h),"utf8"));if(u?.questions)for(let g of u.questions)g.choices&&g.correct&&!(g.correct in g.choices)&&n++;}catch{}let m=i.join(t,"paths");if(e.existsSync(m))for(let h of e.readdirSync(m).filter(u=>u.endsWith(".yaml")))try{let u=x.load(e.readFileSync(i.join(m,h),"utf8"));if(u?.steps){for(let g of u.steps)if(g.content&&!g.content.startsWith("plsat:")){let d=!1;for(let w of ["notes","policies","quizzes","paths"]){let y=i.join(t,w);if(e.existsSync(y)&&e.readdirSync(y).some(Z=>Z.startsWith(g.content))){d=!0;break}}d||n++;}}}catch{}n>0?s.push({name:"University content",status:"warn",message:`${a} items, ${n} issue${n>1?"s":""}`,fix:"Run: paradigm university validate --deep"}):s.push({name:"University content",status:"ok",message:`${a} content item${a>1?"s":""}`});}}catch{s.push({name:"University content",status:"warn",message:"Could not read university directory"});}let H=i.join(l,".claude","hooks.json"),X=i.join(l,"plugins","paradigm","hooks.json");if(e.existsSync(H)){let t=e.statSync(H),a=Date.now()-t.mtime.getTime(),n=Math.floor(a/(1e3*60*60*24));n>30?s.push({name:"Claude Code hooks",status:"warn",message:`Hooks are ${n} days old \u2014 may be outdated`,fix:"paradigm hooks install"}):s.push({name:"Claude Code hooks",status:"ok",message:n>0?`${n} days old`:"Fresh"});}else e.existsSync(X)?s.push({name:"Claude Code hooks",status:"ok",message:"Using plugin hooks"}):s.push({name:"Claude Code hooks",status:"missing",message:"No hooks installed",fix:"paradigm hooks install"});let _=i.join(l,".paradigm","habits.yaml");if(e.existsSync(_))try{let t=e.readFileSync(_,"utf8"),a=x.load(t);if(a?.version&&Array.isArray(a?.habits)){let n=a.habits.filter(o=>o.enabled!==!1).length;s.push({name:"Habits config",status:"ok",message:`Valid (${n}/${a.habits.length} enabled)`});}else s.push({name:"Habits config",status:"warn",message:"Missing version or habits array",fix:"Regenerate habits.yaml with paradigm habits init"});}catch(t){s.push({name:"Habits config",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in habits.yaml"});}let G=i.join(l,"AGENTS.md");if(e.existsSync(G)){let t=e.statSync(G),a=Date.now()-t.mtime.getTime(),n=Math.floor(a/(1e3*60*60*24));n>60?s.push({name:"AGENTS.md",status:"warn",message:`${n} days since last update \u2014 may be stale`,fix:"paradigm sync"}):s.push({name:"AGENTS.md",status:"ok",message:n>0?`Updated ${n} days ago`:"Fresh"});}}let I=0,N=0,S=0;for(let r of s){let f,p;switch(r.status){case "ok":f="\u2713",p=c.green;break;case "warn":f="\u26A0",p=c.yellow,N++;break;case "error":f="\u2717",p=c.red,I++;break;case "missing":f="\u25CB",p=c.gray,S++;break}if(!k){let j=r.name.padEnd(30);console.log(` ${p(f)} ${j} ${p(r.message)}`),r.fix&&console.log(c.gray(` \u2514\u2500 Fix: ${r.fix}`));}}let{runContextAudit:Q}=await import('./context-audit-XRPT3OU2.js'),D=await Q(l,{quiet:k}),z=0,O=0,$=0;!k&&D.length>0&&(console.log(""),console.log(c.blue(" Context Audit")),console.log(c.gray(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")));for(let r of D){let f,p;switch(r.status){case "ok":f="\u2713",p=c.green;break;case "warn":f="\u26A0",p=c.yellow,O++;break;case "error":f="\u2717",p=c.red,z++;break;case "advisory":f="\u2139",p=c.cyan,$++;break}if(!k){let j=r.check.padEnd(30);if(console.log(` ${p(f)} ${j} ${p(r.message)}`),r.details&&r.details.length>0){let P=r.details.slice(0,5);for(let F of P)console.log(c.gray(` \u2502 ${F}`));r.details.length>5&&console.log(c.gray(` \u2502 ... and ${r.details.length-5} more`));}r.fix&&console.log(c.gray(` \u2514\u2500 Fix: ${r.fix}`));}}let C=I+z,b=N+O,R=C+b+S===0;if(!k)if(console.log(""),R)console.log(c.green(`\u2728 All checks passed!
7
- `));else {let r=[];C>0&&r.push(c.red(`${C} error${C>1?"s":""}`)),b>0&&r.push(c.yellow(`${b} warning${b>1?"s":""}`)),S>0&&r.push(c.gray(`${S} missing`)),$>0&&r.push(c.cyan(`${$} advisor${$>1?"ies":"y"}`)),console.log(`${r.join(", ")} found.
8
- `),console.log(c.gray(`Run the suggested commands to fix issues.
9
- `));}return R?L.success("All health checks passed",{total:s.length+D.length}):L.error("Health checks found issues",{errors:C,warnings:b,missing:S,advisories:$}),R}export{rs as a};
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- import {b as b$1}from'./chunk-5TAVYPOV.js';import*as l from'fs';import*as u from'path';import*as T from'os';import*as E from'crypto';import*as d from'js-yaml';var v,w,j,S=b$1(()=>{v={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"}},w={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}},j={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 m(e,t){let o=(Date.now()-new Date(t).getTime())/(1e3*60*60*24);if(o<=k)return e;let r=Math.pow(.5,(o-k)/I);return e*r}function D(e){let t=u.join(e,R);if(!l.existsSync(t))return null;try{return d.load(l.readFileSync(t,"utf8"))?.active??null}catch{return null}}function Y(e,t){let i=D(t);return i?i.includes(e):true}function B(e,t){let i=u.join(e,R),o=u.dirname(i);l.existsSync(o)||l.mkdirSync(o,{recursive:true});let r={version:"1.0",active:t.sort()};l.writeFileSync(i,d.dump(r,{lineWidth:-1,noRefs:true}),"utf8");}function J(){if(!l.existsSync(y))return [];try{return l.readdirSync(y).filter(e=>e.endsWith(h)).map(e=>e.replace(h,""))}catch{return []}}function _(e,t){let i=u.join(e,x,`${t}${h}`);if(l.existsSync(i))try{let r=l.readFileSync(i,"utf-8");return d.load(r)}catch{}let o=u.join(y,`${t}${h}`);if(l.existsSync(o))try{let r=l.readFileSync(o,"utf-8"),n=d.load(r);if(l.existsSync(i))try{let a=l.readFileSync(i,"utf-8"),f=d.load(a);return N(n,f)}catch{}return n}catch{}return null}function M(e,t){let i=C(e),o=t.toLowerCase();return i.filter(r=>r.nickname?.toLowerCase()===o)}function z(e,t){let i=_(e,t);return i||(M(e,t)[0]??null)}function C(e){let t=new Map;if(l.existsSync(y))try{let o=l.readdirSync(y).filter(r=>r.endsWith(h));for(let r of o)try{let n=l.readFileSync(u.join(y,r),"utf-8"),a=d.load(n);a?.id&&t.set(a.id,a);}catch{}}catch{}let i=u.join(e,x);if(l.existsSync(i))try{let o=l.readdirSync(i).filter(r=>r.endsWith(h));for(let r of o)try{let n=l.readFileSync(u.join(i,r),"utf-8"),a=d.load(n);if(!a?.id)continue;let f=t.get(a.id);f?t.set(a.id,N(f,a)):t.set(a.id,a);}catch{}}catch{}return Array.from(t.values())}function P(e,t,i,o){let r=i==="global"?y:u.join(o||process.cwd(),x);l.existsSync(r)||l.mkdirSync(r,{recursive:true});let n=u.join(r,`${e}${h}`);t.permissions&&(t.integrityHash=L(t)),t.updated=new Date().toISOString();let a=d.dump(t,{lineWidth:120,noRefs:true,sortKeys:false});return l.writeFileSync(n,a,"utf-8"),n}function q(e,t={}){let i=new Date().toISOString(),o={id:e,role:t.role||`${e.charAt(0).toUpperCase()+e.slice(1)} agent`,description:t.description||`Persistent identity for the ${e} agent role`,version:"1.0.0",personality:v[e]||{style:"balanced",risk:"balanced",verbosity:"concise"},expertise:[],transferable:[],contexts:{},created:i,updated:i};v[e]||(o.personality={style:"deliberate",risk:"balanced",verbosity:"concise"}),w[e]&&(o.attention={...w[e]}),j[e]&&(o.collaboration={...j[e]});let r=t.scope||"global",n=P(e,o,r,t.rootDir);return {profile:o,filePath:n}}function X(e,t){let i=C(e),o=[];for(let r of i){let n=(r.expertise||[]).find(a=>a.symbol===t);n&&o.push({agentId:r.id,entry:n});}return o.sort((r,n)=>m(n.entry.confidence,n.entry.lastTouch)-m(r.entry.confidence,r.entry.lastTouch))}function K(e,t,i){let o=_(e,t);if(!o)return false;let r=new Date().toISOString(),n=o.expertise||[];for(let c of i.symbols_touched){let p=n.find(g=>g.symbol===c);p?(p.sessions++,p.lastTouch=r,i.confidence!=null&&(p.confidence=(1-b)*p.confidence+b*i.confidence)):n.push({symbol:c,confidence:i.confidence??.5,sessions:1,lastTouch:r});}o.expertise=n;let a=W(e);if(a){let c=o.contexts[a]||{focus:[],sessionsInProject:0};c.lastActive=r,c.sessionsInProject=(c.sessionsInProject||0)+1,o.contexts[a]=c;}let f=u.join(e,x,`${t}${h}`),s=l.existsSync(f)?"project":"global";return P(t,o,s,e),true}function V(e,t,i){let o=_(e,t);if(!o)return false;let n={correct:1,partial:.5,incorrect:0}[i.verdict];for(let s of i.symbols_touched){let c=(o.expertise||[]).find(p=>p.symbol===s);c&&(c.confidence=(1-b)*c.confidence+b*n);}let a=u.join(e,x,`${t}${h}`),f=l.existsSync(a)?"project":"global";return P(t,o,f,e),true}function Q(e,t,i){return t?{personality:t.personality||null,topExpertise:(t.expertise||[]).sort((o,r)=>m(r.confidence,r.lastTouch)-m(o.confidence,o.lastTouch)).slice(0,10),projectContext:t.contexts?.[i]||null,transferablePatterns:(t.transferable||[]).filter(o=>o.successRate>=.7).map(o=>({id:o.id,description:o.description,successRate:o.successRate}))}:{personality:null,topExpertise:[],projectContext:null,transferablePatterns:[]}}function Z(e,t,i,o,r){let n=[];if(e.personality){let s=e.personality;n.push(`## Agent Identity: ${e.id}`),n.push(`**Style:** ${s.style} | **Risk:** ${s.risk} | **Verbosity:** ${s.verbosity}`),n.push("");}let a=(e.expertise||[]).filter(s=>t.length===0||t.includes(s.symbol)).sort((s,c)=>m(c.confidence,c.lastTouch)-m(s.confidence,s.lastTouch)).slice(0,8);if(a.length>0){n.push("## Your Expertise on Relevant Symbols");for(let s of a){let p=1-m(s.confidence,s.lastTouch)/s.confidence,g=s.confidence>0&&p>O?" (aging)":"";n.push(`- \`${s.symbol}\`: confidence ${s.confidence.toFixed(2)} (${s.sessions} sessions)${g}`);}n.push("");}let f=(e.transferable||[]).filter(s=>s.successRate>=.7);if(f.length>0){n.push("## Transferable Patterns");for(let s of f){let c=s.appliedIn?.length||0;n.push(`- ${s.id}: ${(s.successRate*100).toFixed(0)}% success (learned in ${s.learnedIn}${c>0?`, applied in ${c} projects`:""})`);}n.push("");}if(i&&i.length>0){n.push("## Relevant Notebook Entries");for(let s of i.slice(0,5)){n.push(`### ${s.context}`),n.push(`Concepts: ${s.concepts.join(", ")}`),n.push("```");let c=s.snippet.length>300?s.snippet.slice(0,300)+"...":s.snippet;n.push(c),n.push("```"),n.push("");}}if(r){if(n.push(""),n.push("## Your Recent Work on This Project"),r.lastSession){let s=Date.now()-new Date(r.lastSession.date).getTime(),c=Math.floor(s/(3600*1e3)),p=c<24?`${c}h ago`:`${Math.floor(c/24)}d ago`;n.push(`Last session (${p}): ${r.lastSession.summary}`);}if(r.sessionsOnProject&&n.push(`Sessions on this project: ${r.sessionsOnProject}`),r.pendingWork?.length){n.push("**Pending from last session:**");for(let s of r.pendingWork.slice(0,5))n.push(`- ${s}`);}if(r.recentPatterns?.length){n.push("**Project patterns you've learned:**");for(let s of r.recentPatterns.slice(0,5))n.push(`- ${s}`);}n.push("");}if(e.attention){let s=e.attention,c=[];s.symbols?.length&&c.push(`Symbols: ${s.symbols.join(", ")}`),s.paths?.length&&c.push(`Paths: ${s.paths.join(", ")}`),s.concepts?.length&&c.push(`Concepts: ${s.concepts.join(", ")}`),s.signals?.length&&c.push(`Signals: ${s.signals.map(p=>p.type).join(", ")}`),c.length>0&&(n.push(""),n.push("### Attention"),n.push(`Threshold: ${s.threshold??.6}`),n.push(c.join(" | ")));}if(e.collaboration){let s=e.collaboration;if(n.push(""),n.push("### Collaboration"),n.push(`Default stance: ${s.stance||"supportive"}`),s.with)for(let[c,p]of Object.entries(s.with)){let g=[`${c}: ${p.stance||"peer"}`];p.can_contradict&&g.push("can contradict"),p.review_output&&g.push("reviews output"),n.push(`- ${g.join(", ")}`);}if(s.debate){let c=s.debate,p=[];c.will_challenge&&p.push("challenges"),c.evidence_required&&p.push("evidence-based"),c.escalate_to_human&&p.push("escalates to human"),p.length&&n.push(`Debate: ${p.join(", ")}`);}}if(e.nomination){let s=e.nomination;if(n.push(""),n.push("### Nomination"),s.speak_when?.urgency?.length&&n.push(`Always speaks on: ${s.speak_when.urgency.join(", ")}`),s.contribution_style){let c=[];s.contribution_style.brief_first&&c.push("brief first"),s.contribution_style.cite_sources&&c.push("cites sources"),s.contribution_style.offer_action&&c.push("offers action"),c.length&&n.push(`Style: ${c.join(", ")}`);}}if(o){if(o.recentDecisions?.length){n.push(""),n.push("## Recent Team Decisions");for(let s of o.recentDecisions.slice(0,5))n.push(`- **${s.title}**: ${s.decision.slice(0,150)}${s.decision.length>150?"...":""}`);}if(o.journalInsights?.length){n.push(""),n.push("## Transferable Insights");for(let s of o.journalInsights.slice(0,5))n.push(`- [${s.trigger}] ${s.insight.slice(0,150)}${s.insight.length>150?"...":""}`);}if(o.pendingNominations?.length){n.push(""),n.push("## Pending Nominations");for(let s of o.pendingNominations.slice(0,10))n.push(`- [${s.urgency}] ${s.brief}`);}}return n.join(`
3
- `)}async function ee(e,t,i=false){let{loadLoreEntries:o}=await import('./lore-loader-RVQI5GXL.js'),r=await o(e,{limit:500}),n=0,a=new Set,f=_(e,t)||q(t,{rootDir:e}).profile,s=f.expertise||[];for(let c of r)if(!(!c.symbols_touched||c.symbols_touched.length===0)){n++;for(let p of c.symbols_touched){a.add(p);let g=s.find(F=>F.symbol===p);g?(g.sessions++,g.lastTouch=c.timestamp,c.confidence!=null&&(g.confidence=(1-b)*g.confidence+b*c.confidence)):s.push({symbol:p,confidence:c.confidence??.5,sessions:1,lastTouch:c.timestamp});}}if(f.expertise=s,!i){let c=u.join(e,x,`${t}${h}`),p=l.existsSync(c)?"project":"global";P(t,f,p,e);}return {entriesProcessed:n,symbolsUpdated:a.size}}function te(e,t,i){if(!e.permissions?.paths)return {allowed:true};let{read:o,write:r,deny:n}=e.permissions.paths;if(n&&n.length>0){for(let f of n)if(A(f,t))return {allowed:false,reason:`Path denied by pattern: ${f}`}}let a=i==="read"?o:r;if(a&&a.length>0){for(let f of a)if(A(f,t))return {allowed:true};return {allowed:false,reason:`No ${i} pattern matches: ${t}`}}return {allowed:true}}function ne(e,t){if(!e.permissions?.tools)return {allowed:true};let{allow:i,deny:o}=e.permissions.tools;if(o&&o.length>0){for(let r of o)if(A(r,t))return {allowed:false,reason:`Tool denied by pattern: ${r}`}}if(i&&i.length>0){for(let r of i)if(A(r,t))return {allowed:true};return {allowed:false,reason:`Tool not in allow list: ${t}`}}return {allowed:true}}function L(e){let t=JSON.stringify({id:e.id,role:e.role,permissions:e.permissions||null});return E.createHash("sha256").update(t).digest("hex")}function se(e){return e.integrityHash?L(e)===e.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 A(e,t){let i=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}function N(e,t){let i={...e};if(t.role&&(i.role=t.role),t.description&&(i.description=t.description),t.version&&(i.version=t.version),t.personality&&(i.personality={...e.personality,...t.personality}),t.expertise){let o=new Map(e.expertise.map(r=>[r.symbol,r]));for(let r of t.expertise)o.set(r.symbol,r);i.expertise=Array.from(o.values());}if(t.transferable){let o=new Map(e.transferable.map(r=>[r.id,r]));for(let r of t.transferable)o.set(r.id,r);i.transferable=Array.from(o.values());}if(t.contexts){i.contexts={...e.contexts};for(let[o,r]of Object.entries(t.contexts))i.contexts[o]={...i.contexts[o],...r};}return i}function W(e){try{let t=u.join(e,".paradigm","config.yaml");if(l.existsSync(t)){let i=l.readFileSync(t,"utf-8"),o=d.load(i);if(o?.project&&typeof o.project=="string")return o.project}}catch{}return u.basename(e)}var y,x,h,R,b,I,k,O,U=b$1(()=>{S();y=u.join(T.homedir(),".paradigm","agents"),x=".paradigm/agents",h=".agent",R=".paradigm/roster.yaml",b=.3,I=60,k=7,O=.2;});export{m as a,D as b,Y as c,B as d,J as e,_ as f,M as g,z as h,C as i,P as j,q as k,X as l,K as m,V as n,Q as o,Z as p,ee as q,te as r,ne as s,L as t,se as u,U as v};
@@ -1,5 +0,0 @@
1
- #!/usr/bin/env node
2
- import {c,b as b$1}from'./chunk-5TAVYPOV.js';import*as i from'fs';import*as f from'path';var W={};c(W,{appendSessionWorkEntry:()=>b,clearSessionWorkLog:()=>E,getAgentEntries:()=>p,getAgentVerdicts:()=>k,getContributingAgents:()=>x,readSessionWorkLog:()=>l});function b(e,t){try{let n=f.join(e,u),o=f.dirname(n);if(i.existsSync(o)||i.mkdirSync(o,{recursive:!0}),i.existsSync(n)&&i.readFileSync(n,"utf8").trim().split(`
3
- `).filter(r=>r.trim()).length>=v)return;let g=JSON.stringify(t)+`
4
- `;i.appendFileSync(n,g,"utf8"),t.type==="user-verdict"&&t.agent&&t.symbols?.length&&import('./agent-loader-CZFB5BDP.js').then(({loadAgentProfile:c,saveAgentProfile:s})=>{try{let r=c(e,t.agent);if(r?.expertise){let d=t.verdict==="accepted"?.03:t.verdict==="dismissed"?-.02:t.verdict==="revised"?-.01:0;if(d!==0){for(let S of t.symbols){let a=r.expertise.find(y=>y.symbol===S);a&&(a.confidence=Math.max(0,Math.min(1,a.confidence+d)),a.sessions=(a.sessions||0)+1,a.lastTouch=new Date().toISOString());}s(t.agent,r,"global");}}}catch{}}).catch(()=>{});}catch{}}function l(e){try{let t=f.join(e,u);return i.existsSync(t)?i.readFileSync(t,"utf8").trim().split(`
5
- `).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null):[]}catch{return []}}function E(e){try{let t=f.join(e,u);i.existsSync(t)&&i.writeFileSync(t,"","utf8");}catch{}}function x(e){let t=l(e),n=new Set;for(let o of t)o.agent&&n.add(o.agent);return Array.from(n)}function p(e,t){return l(e).filter(n=>n.agent===t)}function k(e,t){let n=p(e,t),o=n.filter(s=>s.type==="agent-contribution"),g=n.filter(s=>s.type==="user-verdict"),c=[];for(let s of o)c.push({contribution:s});for(let s of g){let r=c.find(d=>!d.verdict&&d.contribution);r?r.verdict=s:c.push({verdict:s});}return c}var u,v,A=b$1(()=>{u=".paradigm/events/session-log.jsonl",v=200;});export{b as a,l as b,E as c,x as d,p as e,k as f,W as g,A as h};
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as l from'fs';import*as u from'path';import*as S from'os';import*as k from'crypto';import*as d from'js-yaml';var v={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"}},w={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}},j={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}}};var y=u.join(S.homedir(),".paradigm","agents"),x=".paradigm/agents",h=".agent",T=".paradigm/roster.yaml",b=.3,N=60,$=7,F=.2;function m(e,t){let o=(Date.now()-new Date(t).getTime())/(1e3*60*60*24);if(o<=$)return e;let r=Math.pow(.5,(o-$)/N);return e*r}function I(e){let t=u.join(e,T);if(!l.existsSync(t))return null;try{return d.load(l.readFileSync(t,"utf8"))?.active??null}catch{return null}}function U(e,t){let i=I(t);return i?i.includes(e):true}function H(e,t){let i=u.join(e,T),o=u.dirname(i);l.existsSync(o)||l.mkdirSync(o,{recursive:true});let r={version:"1.0",active:t.sort()};l.writeFileSync(i,d.dump(r,{lineWidth:-1,noRefs:true}),"utf8");}function G(){if(!l.existsSync(y))return [];try{return l.readdirSync(y).filter(e=>e.endsWith(h)).map(e=>e.replace(h,""))}catch{return []}}function _(e,t){let i=u.join(e,x,`${t}${h}`);if(l.existsSync(i))try{let r=l.readFileSync(i,"utf-8");return d.load(r)}catch{}let o=u.join(y,`${t}${h}`);if(l.existsSync(o))try{let r=l.readFileSync(o,"utf-8"),n=d.load(r);if(l.existsSync(i))try{let a=l.readFileSync(i,"utf-8"),f=d.load(a);return C(n,f)}catch{}return n}catch{}return null}function O(e,t){let i=E(e),o=t.toLowerCase();return i.filter(r=>r.nickname?.toLowerCase()===o)}function Y(e,t){let i=_(e,t);return i||(O(e,t)[0]??null)}function E(e){let t=new Map;if(l.existsSync(y))try{let o=l.readdirSync(y).filter(r=>r.endsWith(h));for(let r of o)try{let n=l.readFileSync(u.join(y,r),"utf-8"),a=d.load(n);a?.id&&t.set(a.id,a);}catch{}}catch{}let i=u.join(e,x);if(l.existsSync(i))try{let o=l.readdirSync(i).filter(r=>r.endsWith(h));for(let r of o)try{let n=l.readFileSync(u.join(i,r),"utf-8"),a=d.load(n);if(!a?.id)continue;let f=t.get(a.id);f?t.set(a.id,C(f,a)):t.set(a.id,a);}catch{}}catch{}return Array.from(t.values())}function P(e,t,i,o){let r=i==="global"?y:u.join(o||process.cwd(),x);l.existsSync(r)||l.mkdirSync(r,{recursive:true});let n=u.join(r,`${e}${h}`);t.permissions&&(t.integrityHash=R(t)),t.updated=new Date().toISOString();let a=d.dump(t,{lineWidth:120,noRefs:true,sortKeys:false});return l.writeFileSync(n,a,"utf-8"),n}function D(e,t={}){let i=new Date().toISOString(),o={id:e,role:t.role||`${e.charAt(0).toUpperCase()+e.slice(1)} agent`,description:t.description||`Persistent identity for the ${e} agent role`,version:"1.0.0",personality:v[e]||{style:"balanced",risk:"balanced",verbosity:"concise"},expertise:[],transferable:[],contexts:{},created:i,updated:i};v[e]||(o.personality={style:"deliberate",risk:"balanced",verbosity:"concise"}),w[e]&&(o.attention={...w[e]}),j[e]&&(o.collaboration={...j[e]});let r=t.scope||"global",n=P(e,o,r,t.rootDir);return {profile:o,filePath:n}}function B(e,t){let i=E(e),o=[];for(let r of i){let n=(r.expertise||[]).find(a=>a.symbol===t);n&&o.push({agentId:r.id,entry:n});}return o.sort((r,n)=>m(n.entry.confidence,n.entry.lastTouch)-m(r.entry.confidence,r.entry.lastTouch))}function J(e,t,i){let o=_(e,t);if(!o)return false;let r=new Date().toISOString(),n=o.expertise||[];for(let c of i.symbols_touched){let p=n.find(g=>g.symbol===c);p?(p.sessions++,p.lastTouch=r,i.confidence!=null&&(p.confidence=(1-b)*p.confidence+b*i.confidence)):n.push({symbol:c,confidence:i.confidence??.5,sessions:1,lastTouch:r});}o.expertise=n;let a=M(e);if(a){let c=o.contexts[a]||{focus:[],sessionsInProject:0};c.lastActive=r,c.sessionsInProject=(c.sessionsInProject||0)+1,o.contexts[a]=c;}let f=u.join(e,x,`${t}${h}`),s=l.existsSync(f)?"project":"global";return P(t,o,s,e),true}function z(e,t,i){let o=_(e,t);if(!o)return false;let n={correct:1,partial:.5,incorrect:0}[i.verdict];for(let s of i.symbols_touched){let c=(o.expertise||[]).find(p=>p.symbol===s);c&&(c.confidence=(1-b)*c.confidence+b*n);}let a=u.join(e,x,`${t}${h}`),f=l.existsSync(a)?"project":"global";return P(t,o,f,e),true}function X(e,t,i){return t?{personality:t.personality||null,topExpertise:(t.expertise||[]).sort((o,r)=>m(r.confidence,r.lastTouch)-m(o.confidence,o.lastTouch)).slice(0,10),projectContext:t.contexts?.[i]||null,transferablePatterns:(t.transferable||[]).filter(o=>o.successRate>=.7).map(o=>({id:o.id,description:o.description,successRate:o.successRate}))}:{personality:null,topExpertise:[],projectContext:null,transferablePatterns:[]}}function K(e,t,i,o,r){let n=[];if(e.personality){let s=e.personality;n.push(`## Agent Identity: ${e.id}`),n.push(`**Style:** ${s.style} | **Risk:** ${s.risk} | **Verbosity:** ${s.verbosity}`),n.push("");}let a=(e.expertise||[]).filter(s=>t.length===0||t.includes(s.symbol)).sort((s,c)=>m(c.confidence,c.lastTouch)-m(s.confidence,s.lastTouch)).slice(0,8);if(a.length>0){n.push("## Your Expertise on Relevant Symbols");for(let s of a){let p=1-m(s.confidence,s.lastTouch)/s.confidence,g=s.confidence>0&&p>F?" (aging)":"";n.push(`- \`${s.symbol}\`: confidence ${s.confidence.toFixed(2)} (${s.sessions} sessions)${g}`);}n.push("");}let f=(e.transferable||[]).filter(s=>s.successRate>=.7);if(f.length>0){n.push("## Transferable Patterns");for(let s of f){let c=s.appliedIn?.length||0;n.push(`- ${s.id}: ${(s.successRate*100).toFixed(0)}% success (learned in ${s.learnedIn}${c>0?`, applied in ${c} projects`:""})`);}n.push("");}if(i&&i.length>0){n.push("## Relevant Notebook Entries");for(let s of i.slice(0,5)){n.push(`### ${s.context}`),n.push(`Concepts: ${s.concepts.join(", ")}`),n.push("```");let c=s.snippet.length>300?s.snippet.slice(0,300)+"...":s.snippet;n.push(c),n.push("```"),n.push("");}}if(r){if(n.push(""),n.push("## Your Recent Work on This Project"),r.lastSession){let s=Date.now()-new Date(r.lastSession.date).getTime(),c=Math.floor(s/(3600*1e3)),p=c<24?`${c}h ago`:`${Math.floor(c/24)}d ago`;n.push(`Last session (${p}): ${r.lastSession.summary}`);}if(r.sessionsOnProject&&n.push(`Sessions on this project: ${r.sessionsOnProject}`),r.pendingWork?.length){n.push("**Pending from last session:**");for(let s of r.pendingWork.slice(0,5))n.push(`- ${s}`);}if(r.recentPatterns?.length){n.push("**Project patterns you've learned:**");for(let s of r.recentPatterns.slice(0,5))n.push(`- ${s}`);}n.push("");}if(e.attention){let s=e.attention,c=[];s.symbols?.length&&c.push(`Symbols: ${s.symbols.join(", ")}`),s.paths?.length&&c.push(`Paths: ${s.paths.join(", ")}`),s.concepts?.length&&c.push(`Concepts: ${s.concepts.join(", ")}`),s.signals?.length&&c.push(`Signals: ${s.signals.map(p=>p.type).join(", ")}`),c.length>0&&(n.push(""),n.push("### Attention"),n.push(`Threshold: ${s.threshold??.6}`),n.push(c.join(" | ")));}if(e.collaboration){let s=e.collaboration;if(n.push(""),n.push("### Collaboration"),n.push(`Default stance: ${s.stance||"supportive"}`),s.with)for(let[c,p]of Object.entries(s.with)){let g=[`${c}: ${p.stance||"peer"}`];p.can_contradict&&g.push("can contradict"),p.review_output&&g.push("reviews output"),n.push(`- ${g.join(", ")}`);}if(s.debate){let c=s.debate,p=[];c.will_challenge&&p.push("challenges"),c.evidence_required&&p.push("evidence-based"),c.escalate_to_human&&p.push("escalates to human"),p.length&&n.push(`Debate: ${p.join(", ")}`);}}if(e.nomination){let s=e.nomination;if(n.push(""),n.push("### Nomination"),s.speak_when?.urgency?.length&&n.push(`Always speaks on: ${s.speak_when.urgency.join(", ")}`),s.contribution_style){let c=[];s.contribution_style.brief_first&&c.push("brief first"),s.contribution_style.cite_sources&&c.push("cites sources"),s.contribution_style.offer_action&&c.push("offers action"),c.length&&n.push(`Style: ${c.join(", ")}`);}}if(o){if(o.recentDecisions?.length){n.push(""),n.push("## Recent Team Decisions");for(let s of o.recentDecisions.slice(0,5))n.push(`- **${s.title}**: ${s.decision.slice(0,150)}${s.decision.length>150?"...":""}`);}if(o.journalInsights?.length){n.push(""),n.push("## Transferable Insights");for(let s of o.journalInsights.slice(0,5))n.push(`- [${s.trigger}] ${s.insight.slice(0,150)}${s.insight.length>150?"...":""}`);}if(o.pendingNominations?.length){n.push(""),n.push("## Pending Nominations");for(let s of o.pendingNominations.slice(0,10))n.push(`- [${s.urgency}] ${s.brief}`);}}return n.join(`
3
- `)}async function V(e,t,i=false){let{loadLoreEntries:o}=await import('./lore-loader-XY5MZRR2.js'),r=await o(e,{limit:500}),n=0,a=new Set,f=_(e,t)||D(t,{rootDir:e}).profile,s=f.expertise||[];for(let c of r)if(!(!c.symbols_touched||c.symbols_touched.length===0)){n++;for(let p of c.symbols_touched){a.add(p);let g=s.find(L=>L.symbol===p);g?(g.sessions++,g.lastTouch=c.timestamp,c.confidence!=null&&(g.confidence=(1-b)*g.confidence+b*c.confidence)):s.push({symbol:p,confidence:c.confidence??.5,sessions:1,lastTouch:c.timestamp});}}if(f.expertise=s,!i){let c=u.join(e,x,`${t}${h}`),p=l.existsSync(c)?"project":"global";P(t,f,p,e);}return {entriesProcessed:n,symbolsUpdated:a.size}}function Q(e,t,i){if(!e.permissions?.paths)return {allowed:true};let{read:o,write:r,deny:n}=e.permissions.paths;if(n&&n.length>0){for(let f of n)if(A(f,t))return {allowed:false,reason:`Path denied by pattern: ${f}`}}let a=i==="read"?o:r;if(a&&a.length>0){for(let f of a)if(A(f,t))return {allowed:true};return {allowed:false,reason:`No ${i} pattern matches: ${t}`}}return {allowed:true}}function Z(e,t){if(!e.permissions?.tools)return {allowed:true};let{allow:i,deny:o}=e.permissions.tools;if(o&&o.length>0){for(let r of o)if(A(r,t))return {allowed:false,reason:`Tool denied by pattern: ${r}`}}if(i&&i.length>0){for(let r of i)if(A(r,t))return {allowed:true};return {allowed:false,reason:`Tool not in allow list: ${t}`}}return {allowed:true}}function R(e){let t=JSON.stringify({id:e.id,role:e.role,permissions:e.permissions||null});return k.createHash("sha256").update(t).digest("hex")}function ee(e){return e.integrityHash?R(e)===e.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 A(e,t){let i=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}function C(e,t){let i={...e};if(t.role&&(i.role=t.role),t.description&&(i.description=t.description),t.version&&(i.version=t.version),t.personality&&(i.personality={...e.personality,...t.personality}),t.expertise){let o=new Map(e.expertise.map(r=>[r.symbol,r]));for(let r of t.expertise)o.set(r.symbol,r);i.expertise=Array.from(o.values());}if(t.transferable){let o=new Map(e.transferable.map(r=>[r.id,r]));for(let r of t.transferable)o.set(r.id,r);i.transferable=Array.from(o.values());}if(t.contexts){i.contexts={...e.contexts};for(let[o,r]of Object.entries(t.contexts))i.contexts[o]={...i.contexts[o],...r};}return i}function M(e){try{let t=u.join(e,".paradigm","config.yaml");if(l.existsSync(t)){let i=l.readFileSync(t,"utf-8"),o=d.load(i);if(o?.project&&typeof o.project=="string")return o.project}}catch{}return u.basename(e)}export{m as a,I as b,U as c,H as d,G as e,_ as f,O as g,Y as h,E as i,P as j,D as k,B as l,J as m,z as n,X as o,K as p,V as q,Q as r,Z as s,R as t,ee as u};
@@ -1,5 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as i from'fs';import*as f from'path';var u=".paradigm/events/session-log.jsonl",y=200;function h(e,t){try{let n=f.join(e,u),o=f.dirname(n);if(i.existsSync(o)||i.mkdirSync(o,{recursive:!0}),i.existsSync(n)&&i.readFileSync(n,"utf8").trim().split(`
3
- `).filter(r=>r.trim()).length>=y)return;let g=JSON.stringify(t)+`
4
- `;i.appendFileSync(n,g,"utf8"),t.type==="user-verdict"&&t.agent&&t.symbols?.length&&import('./agent-loader-EBERCNMO.js').then(({loadAgentProfile:c,saveAgentProfile:s})=>{try{let r=c(e,t.agent);if(r?.expertise){let d=t.verdict==="accepted"?.03:t.verdict==="dismissed"?-.02:t.verdict==="revised"?-.01:0;if(d!==0){for(let p of t.symbols){let a=r.expertise.find(S=>S.symbol===p);a&&(a.confidence=Math.max(0,Math.min(1,a.confidence+d)),a.sessions=(a.sessions||0)+1,a.lastTouch=new Date().toISOString());}s(t.agent,r,"global");}}}catch{}}).catch(()=>{});}catch{}}function l(e){try{let t=f.join(e,u);return i.existsSync(t)?i.readFileSync(t,"utf8").trim().split(`
5
- `).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null):[]}catch{return []}}function v(e){try{let t=f.join(e,u);i.existsSync(t)&&i.writeFileSync(t,"","utf8");}catch{}}function b(e){let t=l(e),n=new Set;for(let o of t)o.agent&&n.add(o.agent);return Array.from(n)}function m(e,t){return l(e).filter(n=>n.agent===t)}function E(e,t){let n=m(e,t),o=n.filter(s=>s.type==="agent-contribution"),g=n.filter(s=>s.type==="user-verdict"),c=[];for(let s of o)c.push({contribution:s});for(let s of g){let r=c.find(d=>!d.verdict&&d.contribution);r?r.verdict=s:c.push({verdict:s});}return c}export{h as a,l as b,v as c,b as d,m as e,E as f};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export{a as doctorCommand}from'./chunk-CSXVL2U7.js';import'./chunk-HMQ5BHP2.js';import'./chunk-JQKKVAAN.js';import'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export{ma as getReindexToolsList,na as handleReindexTool,oa as rebuildStaticFiles}from'./chunk-VNQGILQU.js';import'./chunk-M4UMM6DC.js';import'./chunk-ODVKPZZ4.js';import'./chunk-AYYS2AMB.js';import'./chunk-SL3RZQPW.js';import'./chunk-5TAVYPOV.js';
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export{i as MODEL_PRICING,j as getSessionTracker,k as resetSessionTracker}from'./chunk-AYYS2AMB.js';import'./chunk-SL3RZQPW.js';import'./chunk-5TAVYPOV.js';
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import {h}from'./chunk-SL3RZQPW.js';export{a as appendSessionWorkEntry,c as clearSessionWorkLog,e as getAgentEntries,f as getAgentVerdicts,d as getContributingAgents,b as readSessionWorkLog}from'./chunk-SL3RZQPW.js';import'./chunk-5TAVYPOV.js';h();
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export{a as appendSessionWorkEntry,c as clearSessionWorkLog,e as getAgentEntries,f as getAgentVerdicts,d as getContributingAgents,b as readSessionWorkLog}from'./chunk-VKGY42FP.js';import'./chunk-5TAVYPOV.js';
@@ -1,11 +0,0 @@
1
- #!/usr/bin/env node
2
- import {b}from'./chunk-VPMJWJ5R.js';import'./chunk-DG236EXP.js';import'./chunk-TYWB5IQJ.js';import'./chunk-WESTEMIM.js';import'./chunk-FYDRENK7.js';import'./chunk-IZSBGW6E.js';import {d as d$1}from'./chunk-AO7ZSRME.js';import'./chunk-Y4XFVDZC.js';import {a as a$5}from'./chunk-FSOI3CCD.js';import {d}from'./chunk-W5IWDW4Y.js';import {a as a$3,b as b$1}from'./chunk-4DVT5IEY.js';import'./chunk-SHD27BQX.js';import {a as a$6}from'./chunk-CSXVL2U7.js';import'./chunk-EKZDFEJW.js';import {a as a$1}from'./chunk-33LKBMVK.js';import {b as b$2}from'./chunk-JBDMCRPP.js';import'./chunk-4TXOVRWD.js';import'./chunk-T6IDXUUA.js';import'./chunk-JIXHEBGK.js';import'./chunk-QT2LKB3P.js';import'./chunk-VCKKJDLP.js';import'./chunk-WR6D3SC6.js';import {a as a$2}from'./chunk-UIKLE3WD.js';import {a as a$4}from'./chunk-QNZEG7IT.js';import'./chunk-HMQ5BHP2.js';import'./chunk-JQKKVAAN.js';import {a}from'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';import*as r from'fs';import*as n from'path';import e from'chalk';import U from'ora';import*as g from'js-yaml';async function oe(l={}){let s=process.cwd(),h=n.basename(s),u=n.join(s,".paradigm"),k=r.existsSync(u)&&r.statSync(u).isDirectory();console.log(e.blue(`
3
- \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510`)),console.log(e.blue("\u2502")+e.white.bold(" paradigm shift ")+e.blue("\u2502")),console.log(e.blue("\u2502")+e.gray(" Full project setup in one command ")+e.blue("\u2502")),console.log(e.blue(`\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
4
- `)),console.log(e.white(` \u{1F4C1} Project: ${e.cyan(h)}`)),console.log(e.white(` \u{1F4CD} Status: ${k?e.green("Paradigm detected"):e.yellow("New project")}`)),console.log("");let j=a.command("shift").start("Running paradigm shift",{project:h}),i=U();if(!k||l.force){i.start("Step 1/6: Initializing Paradigm...");try{await a$1({force:l.force,quick:!0,name:h,stack:l.stack}),i.succeed(e.green("Paradigm initialized"));}catch(o){i.fail(e.red(`Init failed: ${o.message}`)),j.error("Shift failed at init",{error:o.message});return}}else {i.succeed(e.gray("Step 1/6: Already initialized (use --force to reinit)"));let o=n.join(u,"config.yaml");if(r.existsSync(o))try{let t=r.readFileSync(o,"utf8"),a=g.load(t);if(!a.discipline||a.discipline==="auto"){let c=a$2(s);if(c!=="backend"){let f=t.replace(/^discipline:\s*auto\b.*$/m,`discipline: ${c}`);f!==t&&(r.writeFileSync(o,f,"utf8"),console.log(e.green(` \u2713 Detected discipline: ${e.cyan(c)} (updated config.yaml)`)));}else if(!a.discipline){let f=t.replace(/^(project:\s*.+)$/m,`$1
5
- discipline: ${c}`);f!==t&&(r.writeFileSync(o,f,"utf8"),console.log(e.green(` \u2713 Added discipline: ${e.cyan(c)} to config.yaml`)));}}}catch(t){a.operation("shift").debug("Discipline detection failed",{error:t.message});}}if(k){i.start("Step 1b/6: Checking for migrations...");try{let{migrateCommand:o}=await import('./migrate-WT56YYAM.js');await o({apply:!0,quiet:!0,noSync:!0}),i.succeed(e.green("Migrations applied"));}catch(o){i.warn(e.yellow(`Migration warning: ${o.message}`));}}{let o=n.join(u,"config.yaml");if(l.workspace&&r.existsSync(o)){let t=l.workspacePath?n.resolve(s,l.workspacePath):n.join(n.dirname(s),".paradigm-workspace");if(r.existsSync(t))try{let a=g.load(r.readFileSync(t,"utf8")),c=n.basename(s),f=n.dirname(t),d$1="./"+n.relative(f,s);if(a.members.some(y=>n.resolve(f,y.path)===s))console.log(e.green(` \u2713 Already a member of workspace: ${e.cyan(a.name)}`));else {let y=d(c,s);a.members.push({name:c,path:d$1,...y&&{role:y}}),r.writeFileSync(t,g.dump(a,{indent:2,lineWidth:120,noRefs:!0,sortKeys:!1,quotingType:'"'}),"utf8"),console.log(e.green(` \u2713 Joined workspace: ${e.cyan(a.name)} (added as member)`));}}catch(a){console.log(e.yellow(` \u26A0 Failed to join workspace: ${a.message}`));}else try{let a=n.basename(s),c=n.dirname(t),f="./"+n.relative(c,s),d$1=d(a,s),p={version:"1.0",name:l.workspace,members:[{name:a,path:f,...d$1&&{role:d$1}}]};r.mkdirSync(n.dirname(t),{recursive:!0}),r.writeFileSync(t,g.dump(p,{indent:2,lineWidth:120,noRefs:!0,sortKeys:!1,quotingType:'"'}),"utf8"),console.log(e.green(` \u2713 Created workspace: ${e.cyan(l.workspace)} at ${e.gray(n.relative(s,t))}`));}catch(a){console.log(e.yellow(` \u26A0 Failed to create workspace: ${a.message}`));}try{let a=r.readFileSync(o,"utf8"),c=g.load(a),f=n.relative(s,t);if(c.workspace!==f){if(c.workspace){let d=a.replace(/^workspace:\s*.*$/m,`workspace: "${f}"`);r.writeFileSync(o,d,"utf8");}else {let d=a.trimEnd()+`
6
- workspace: "${f}"
7
- `;r.writeFileSync(o,d,"utf8");}console.log(e.green(" \u2713 Linked workspace in config.yaml"));}}catch(a$1){a.operation("shift").debug("Workspace config link failed",{error:a$1.message});}}else if(r.existsSync(o))try{let t=r.readFileSync(o,"utf8");if(!g.load(t).workspace){let c=n.dirname(s);for(let f=0;f<3;f++){let d=n.join(c,".paradigm-workspace");if(r.existsSync(d)){let y=n.relative(s,d),N=t.trimEnd()+`
8
- workspace: "${y}"
9
- `;r.writeFileSync(o,N,"utf8"),console.log(e.green(` \u2713 Found workspace: ${e.cyan(y)} (added to config.yaml)`));break}let p=n.dirname(c);if(p===c)break;c=p;}}}catch(t){a.operation("shift").debug("Workspace auto-detect failed",{error:t.message});}}if(!d$1(s)||l.force){console.log(e.cyan(" Step 2/6: Initializing team configuration..."));try{await b(s,{force:l.force,json:!1,configureModels:l.configureModels||!1,noConfigureModels:!l.configureModels}),console.log(e.green(` \u2713 Team configuration initialized
10
- `));}catch(o){console.log(e.yellow(` \u26A0 Team init warning: ${o.message}
11
- `));}}else i.succeed(e.gray("Step 2/6: Team already configured (use --force to reinit)"));let S=n.join(s,".paradigm","roster.yaml");if(!r.existsSync(S)||l.force)try{let o=a$3(s),t=b$1[o]||b$1.generic,a={version:"1.0",project:h,type:o,active:t.sort()};r.writeFileSync(S,g.dump(a,{lineWidth:-1,noRefs:!0}),"utf8"),console.log(e.green(` \u2713 Agent roster set: ${e.cyan(t.length)} agents for ${e.cyan(o)}`));}catch(o){a.operation("shift").debug("Roster setup failed",{error:o.message});}else try{let t=g.load(r.readFileSync(S,"utf8"))?.active?.length??0;console.log(e.gray(` \u2713 Agent roster exists (${t} agents active)`));}catch{console.log(e.gray(" \u2713 Agent roster exists"));}{let o=n.join(u,"config.yaml");if(r.existsSync(o))try{let t=r.readFileSync(o,"utf8"),a=g.load(t);if(!a["model-resolution"]||l.force){let{ModelDiscovery:c}=await import('./model-discovery-HMB3YI4L.js'),d=new c(s).detectEnvironment(),p;d==="claude-code"?p={"tier-1":"opus","tier-2":"sonnet","tier-3":"haiku"}:d==="cursor"?p={"tier-1":"sonnet","tier-2":"sonnet","tier-3":"haiku"}:p={"tier-1":"sonnet","tier-2":"sonnet","tier-3":"sonnet"},a["model-resolution"]=p,r.writeFileSync(o,g.dump(a,{lineWidth:-1,noRefs:!0}),"utf8"),console.log(e.green(` \u2713 Model tiers configured for ${e.cyan(d)}: tier-1=${p["tier-1"]}, tier-2=${p["tier-2"]}, tier-3=${p["tier-3"]}`));}}catch(t){a.operation("shift").debug("Model tier config failed",{error:t.message});}}try{let{ensureEnforcementDefaults:o}=await import('./enforcement-BEGPQIUN.js');o(s)&&console.log(e.green(` \u2713 Enforcement config initialized (${e.cyan("balanced")} preset)`));}catch(o){a.operation("shift").debug("Enforcement config setup failed",{error:o.message});}if(l.quick)i.succeed(e.gray("Step 3/6: Skipped scan (--quick mode)"));else {i.start("Step 3/6: Scanning and indexing symbols...");try{await b$2(s,{quiet:!0}),i.succeed(e.green("Symbols indexed"));}catch(o){i.warn(e.yellow(`Scan warning: ${o.message}`));}}{let o=n.join(u,"config.yaml");if(r.existsSync(o))try{if(g.load(r.readFileSync(o,"utf8")).workspace){i.start("Step 3b/6: Reindexing workspace members...");try{let{workspaceReindexCommand:a}=await import('./workspace-2ODL5WLY.js');await a({quiet:!0}),i.succeed(e.green("Workspace members reindexed"));}catch(a){i.warn(e.yellow(`Workspace reindex: ${a.message}`));}}}catch(t){a.operation("shift").debug("Workspace config read failed",{error:t.message});}}let v=n.join(s,"portal.yaml");r.existsSync(v)||r.writeFileSync(v,g.dump({version:"1.0.0",gates:{},routes:{}},{lineWidth:-1,noRefs:true}),"utf8");let C=n.join(s,".paradigm","lore");r.existsSync(C)||r.mkdirSync(C,{recursive:true});let P=n.join(s,".paradigm","university");for(let o of ["content/notes","content/policies","content/quizzes","content/paths","diplomas"]){let t=n.join(P,o);r.existsSync(t)||r.mkdirSync(t,{recursive:true});}let E=n.join(P,"config.yaml");if(!r.existsSync(E)){let o="Project";try{let a=n.join(s,".paradigm","config.yaml");if(r.existsSync(a)){let c=g.load(r.readFileSync(a,"utf8"));c.project&&typeof c.project=="string"&&(o=c.project);}}catch{}let t={branding:{name:`${o} University`,tagline:`Learn the ${o} codebase`,institution:o},theme:{primary:"#6366f1",secondary:"#8b5cf6",accent:"#f59e0b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",textMuted:"#94a3b8",success:"#22c55e",error:"#ef4444",font:"Inter, system-ui, sans-serif"},content:{categories:[],defaultDifficulty:"beginner",requireApproval:false},diplomas:{includeGlobalPLSAT:true}};r.writeFileSync(E,g.dump(t,{lineWidth:-1,noRefs:true}),"utf8");}i.start("Step 4/6: Syncing IDE configurations...");try{let o=l.ide?[l.ide]:["claude","cursor","copilot","windsurf","agents"],t=[];for(let a of o)try{await a$4(a,{quiet:!0,force:!0}),t.push(a);}catch{}t.length>0?i.succeed(e.green(`IDE configs synced: ${t.join(", ")}`)):i.warn(e.yellow("No IDE configs to sync"));}catch(o){i.warn(e.yellow(`Sync warning: ${o.message}`));}i.start("Step 5/6: Installing hooks...");try{await a$5({force:l.force}),i.succeed(e.green("Hooks installed (git + Claude Code + Cursor)"));}catch(o){i.warn(e.yellow(`Hooks warning: ${o.message}`));}if(l.verify){i.start("Step 6/6: Running health checks...");try{await a$6({quiet:!0})?i.succeed(e.green("All health checks passed")):i.warn(e.yellow("Some health checks need attention"));}catch(o){i.warn(e.yellow(`Doctor warning: ${o.message}`));}}else i.succeed(e.gray("Step 6/6: Skipped verify (use --verify to check health)"));console.log(""),console.log(e.blue("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510")),console.log(e.blue("\u2502")+e.white.bold(" \u2728 Paradigm shift complete! ")+e.blue("\u2502")),console.log(e.blue("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")),console.log(""),console.log(e.white(" Created/Updated:")),console.log(e.gray(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));let x=[{path:".paradigm/config.yaml",desc:"Project configuration"},{path:".paradigm/navigator.yaml",desc:"Symbol navigation map"},{path:".paradigm/agents.yaml",desc:"Team agent configuration"},{path:".purpose",desc:"Root feature definitions"},{path:".paradigm/lore/",desc:"Project lore timeline",isDir:true},{path:"portal.yaml",desc:"Authorization gates"},{path:".paradigm/roster.yaml",desc:"Agent roster for this project"},{path:"CLAUDE.md",desc:"Claude Code AI instructions"},{path:"AGENTS.md",desc:"Universal AI agent instructions"},{path:".cursor/rules/",desc:"Cursor AI instructions",isDir:true},{path:".claude/hooks/",desc:"Claude Code enforcement hooks",isDir:true,optional:true},{path:".cursor/hooks/",desc:"Cursor enforcement hooks",isDir:true,optional:true}],F=n.join(u,"config.yaml");if(r.existsSync(F))try{let o=g.load(r.readFileSync(F,"utf8"));if(typeof o.workspace=="string"){let t=n.resolve(s,o.workspace),a=n.relative(s,t);x.push({path:a,desc:"Multi-project workspace",optional:!0});}}catch(o){a.operation("shift").debug("Summary config read failed",{error:o.message});}for(let o of x){let t=n.join(s,o.path);r.existsSync(t)?console.log(e.green(" \u2713 ")+e.white(o.path.padEnd(28))+e.gray(o.desc)):o.optional||console.log(e.yellow(" \u25CB ")+e.gray(o.path.padEnd(28))+e.gray(`(${o.desc})`));}console.log(""),console.log(e.white(" AI agents will now:")),console.log(e.gray(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(e.cyan(" \u2022 ")+e.white("Use MCP tools for navigation (paradigm_search, etc.)")),console.log(e.cyan(" \u2022 ")+e.white("Check .purpose files before modifying features")),console.log(e.cyan(" \u2022 ")+e.white("Update Paradigm files when making structural changes")),console.log(e.cyan(" \u2022 ")+e.white("Follow antipatterns and team preferences")),console.log(e.cyan(" \u2022 ")+e.white("Record lore entries to capture work history")),console.log(""),console.log(e.white(" Next steps:")),console.log(e.gray(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));let w=1;l.workspace&&console.log(e.white(` ${w++}. `)+e.gray("Run ")+e.cyan(`paradigm shift --workspace "${l.workspace}"`)+e.gray(" in sibling projects")),console.log(e.white(` ${w++}. `)+e.gray("Edit ")+e.cyan(".purpose")+e.gray(" to define your features")),console.log(e.white(` ${w++}. `)+e.gray("Add ")+e.cyan(".purpose")+e.gray(" files to feature directories")),console.log(e.white(` ${w++}. `)+e.gray("Run ")+e.cyan("paradigm shift --verify")+e.gray(" to check health")),console.log(""),j.success("Paradigm shift complete",{project:h});}export{oe as shiftCommand};
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- import {k as k$1,l,n,f as f$1,m as m$1,c as c$1,j,i}from'./chunk-J32OPJEX.js';import {d,j as j$1,l as l$1,h}from'./chunk-CUOEZAVL.js';import'./chunk-5TAVYPOV.js';import*as v from'fs';import*as m from'path';import*as k from'os';import*as f from'crypto';import {WebSocketServer,WebSocket}from'ws';var X=m.join(k.homedir(),".paradigm","score"),O=2e3,x=3e4,D=1e4,N=3,L=6e4,E=1e3,H=3e4;function c(l,e){l.readyState===WebSocket.OPEN&&l.send(JSON.stringify(e));}function M(l){try{let e=typeof l=="string"?l:String(l);return JSON.parse(e)}catch{return null}}var C=class l$2{wss=null;wsClient=null;mode;pairingState=null;connectedPeers=new Map;seenMessageIds=new Set;outboxWatchInterval=null;keepaliveInterval=null;reconnectTimer=null;reconnectDelay=E;outboxPositions=new Map;events;myPeerId;port;stopped=false;failedAuthAttempts=new Map;pongTimers=new Map;serverAddress=null;serverCode=null;static MAX_SEEN_IDS=1e4;constructor(e){this.mode=e.mode,this.myPeerId=e.peerId,this.port=e.port??3939,this.events=e.events??{};}async startServer(){if(this.mode!=="server")throw new Error('startServer() requires mode "server"');return this.pairingState=k$1(),this.wss=new WebSocketServer({port:this.port}),this.wss.on("connection",(e,t)=>{let n=t.socket.remoteAddress??"unknown";if(this.isRateLimited(n)){c(e,{type:"auth_fail",reason:"Too many failed attempts \u2014 try again later"}),e.close();return}let i=f.randomBytes(32).toString("hex");c(e,{type:"hello",version:"1.0",peerId:this.myPeerId,challenge:i});let s=false;e.on("message",r=>{let o=M(r);if(o){if(!s){this.handleServerAuth(e,o,i,n).then(a=>{a&&(s=true,this.registerPeerConnection(a,e));}).catch(a=>{this.events.onError?.(a instanceof Error?a:new Error(String(a)));});return}this.handleAuthenticatedFrame(e,o);}}),e.on("close",()=>{s&&this.handlePeerDisconnect(e);}),e.on("error",r=>{this.events.onError?.(r);});}),this.wss.on("error",e=>{this.events.onError?.(e);}),await new Promise((e,t)=>{this.wss.on("listening",e),this.wss.on("error",t);}),this.startOutboxWatcher(),this.startKeepalive(),this.pairingState}async handleServerAuth(e,t,n$1,i){if(t.type!=="auth")return c(e,{type:"auth_fail",reason:"Expected auth frame"}),e.close(),null;if(!this.pairingState||!l(this.pairingState,t.code)){this.recordFailedAuth(i);let a="Invalid or expired pairing code";return c(e,{type:"auth_fail",reason:a}),this.events.onPeerAuthFailed?.(i,a),e.close(),null}let s=this.pairingState.codeHash;if(!n(n$1,s,t.proof)){this.recordFailedAuth(i);let a="HMAC proof verification failed";return c(e,{type:"auth_fail",reason:a}),this.events.onPeerAuthFailed?.(i,a),e.close(),null}let r=this.getLocalAgentSummaries(),o=this.myPeerId;return c(e,{type:"auth_ok",peerId:this.myPeerId,displayName:o,agents:r}),f$1({id:t.peerId,displayName:t.peerId,address:i,sharedSecret:this.pairingState.sharedSecret,connectedAt:new Date().toISOString(),lastSeen:new Date().toISOString(),revoked:false,agents:[]}),t.peerId}async connectToServer(e,t){if(this.mode!=="client")throw new Error('connectToServer() requires mode "client"');this.serverAddress=e,this.serverCode=t,await this.attemptConnection(e,t);}attemptConnection(e,t){return new Promise((n,i)=>{if(this.stopped){i(new Error("Relay has been stopped"));return}let s=e.includes("://")?e:`ws://${e}`,r=new WebSocket(s),o=false;r.on("open",()=>{this.wsClient=r;}),r.on("message",a=>{let d=M(a);if(d)switch(d.type){case "hello":{let R=f.createHash("sha256").update(t).digest("hex"),F=m$1(d.challenge,R);c(r,{type:"auth",peerId:this.myPeerId,code:t,proof:F});break}case "auth_ok":{f$1({id:d.peerId,displayName:d.displayName,address:e,sharedSecret:t,connectedAt:new Date().toISOString(),lastSeen:new Date().toISOString(),revoked:false,agents:d.agents}),c(r,{type:"agents_sync",agents:this.getLocalAgentSummaries()}),this.registerPeerConnection(d.peerId,r),this.startOutboxWatcher(),this.startKeepalive(),this.reconnectDelay=E,o||(o=true,n());break}case "auth_fail":{o||(o=true,i(new Error(`Auth failed: ${d.reason}`))),r.close();break}default:this.handleAuthenticatedFrame(r,d);break}}),r.on("close",()=>{this.handlePeerDisconnect(r),o?this.stopped||this.scheduleReconnect():(o=true,i(new Error("Connection closed before auth completed")));}),r.on("error",a=>{this.events.onError?.(a),o||(o=true,i(a));});})}handleAuthenticatedFrame(e,t){switch(t.type){case "message":this.handleIncomingMessage(e,t.message,t.origin);break;case "message_ack":break;case "nomination_forward":this.handleNominationForward(e,t.nomination,t.origin);break;case "agents_sync":this.handleAgentsSync(e,t.agents);break;case "agent_joined":{let n=this.peerIdForSocket(e);if(n){let s=c$1().find(r=>r.id===n);if(s){let r=[...s.agents||[],t.agent];j(n,r);}}break}case "agent_left":{let n=this.peerIdForSocket(e);if(n){let s=c$1().find(r=>r.id===n);if(s){let r=(s.agents||[]).filter(o=>o.id!==t.agentId);j(n,r);}}break}case "peer_leaving":this.handlePeerDisconnect(e),e.close();break;case "ping":c(e,{type:"pong"});break;case "pong":this.handlePong(e);break;}}handleIncomingMessage(e,t,n){if(this.seenMessageIds.has(t.id)){c(e,{type:"message_ack",messageId:t.id});return}this.addToSeenIds(t.id);let i=d();if(t.recipients&&t.recipients.length>0)for(let s of t.recipients){let r=i.find(o=>o.id===s.id);r&&(j$1(r.id,t),this.events.onMessageRelayed?.(t.id,n,r.id));}else for(let s of i)j$1(s.id,t),this.events.onMessageRelayed?.(t.id,n,s.id);if(this.mode==="server"){let s=this.peerIdForSocket(e);for(let[r,o]of this.connectedPeers)r!==s&&r!==n&&c(o,{type:"message",message:t,origin:n});}c(e,{type:"message_ack",messageId:t.id});}handleNominationForward(e,t,n){if(!t?.id)return;let i={...t,remote_origin:n,forwarded_at:new Date().toISOString()};try{let s=m.join(k.homedir(),".paradigm","events");v.mkdirSync(s,{recursive:!0});let r=m.join(s,"nominations.jsonl");v.appendFileSync(r,JSON.stringify(i)+`
3
- `,"utf8");}catch{}if(this.mode==="server")for(let[s,r]of this.connectedPeers)r!==e&&r.readyState===WebSocket.OPEN&&c(r,{type:"nomination_forward",nomination:i,origin:n});c(e,{type:"nomination_ack",nominationId:t.id});}handleAgentsSync(e,t){let n=this.peerIdForSocket(e);n&&(j(n,t),i(n));}startOutboxWatcher(){this.outboxWatchInterval||(this.outboxWatchInterval=setInterval(()=>{if(this.connectedPeers.size!==0)try{let e=d();for(let t of e){let n=l$1(t.id),i=this.outboxPositions.get(t.id)??0;if(n.length<=i)continue;let s=n.slice(i);for(let r of s){if(this.seenMessageIds.has(r.id))continue;this.addToSeenIds(r.id);let o={type:"message",message:r,origin:this.myPeerId};for(let[a,d]of this.connectedPeers)c(d,o);}this.outboxPositions.set(t.id,n.length);}}catch(e){this.events.onError?.(e instanceof Error?e:new Error(String(e)));}},O));}stopOutboxWatcher(){this.outboxWatchInterval&&(clearInterval(this.outboxWatchInterval),this.outboxWatchInterval=null);}startKeepalive(){this.keepaliveInterval||(this.keepaliveInterval=setInterval(()=>{for(let[e,t]of this.connectedPeers){c(t,{type:"ping"});let n=setTimeout(()=>{this.handlePeerDisconnect(t),t.terminate();},D);this.pongTimers.set(e,n);}},x));}stopKeepalive(){this.keepaliveInterval&&(clearInterval(this.keepaliveInterval),this.keepaliveInterval=null);for(let e of this.pongTimers.values())clearTimeout(e);this.pongTimers.clear();}handlePong(e){let t=this.peerIdForSocket(e);if(t){let n=this.pongTimers.get(t);n&&(clearTimeout(n),this.pongTimers.delete(t)),i(t);}}registerPeerConnection(e,t){let n=this.connectedPeers.get(e);n&&n!==t&&n.close(),this.connectedPeers.set(e,t),i(e),this.events.onPeerConnected?.(e,e);}handlePeerDisconnect(e){let t=this.peerIdForSocket(e);if(!t)return;this.connectedPeers.delete(t);let n=this.pongTimers.get(t);n&&(clearTimeout(n),this.pongTimers.delete(t)),this.events.onPeerDisconnected?.(t);}peerIdForSocket(e){for(let[t,n]of this.connectedPeers)if(n===e)return t;return null}scheduleReconnect(){if(this.stopped||this.mode!=="client"||!this.serverAddress||!this.serverCode)return;this.stopOutboxWatcher(),this.stopKeepalive(),this.wsClient=null;let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*2,H),this.reconnectTimer=setTimeout(()=>{this.stopped||this.attemptConnection(this.serverAddress,this.serverCode).catch(t=>{this.events.onError?.(t instanceof Error?t:new Error(String(t)));});},e);}isRateLimited(e){let t=this.failedAuthAttempts.get(e);return t?Date.now()<t.cooldownUntil?true:t.count>=N?(t.cooldownUntil=Date.now()+L,true):false:false}recordFailedAuth(e){let t=this.failedAuthAttempts.get(e);t?t.count++:this.failedAuthAttempts.set(e,{count:1,cooldownUntil:0});}addToSeenIds(e){if(this.seenMessageIds.add(e),this.seenMessageIds.size>l$2.MAX_SEEN_IDS){let t=Array.from(this.seenMessageIds),n=Math.floor(t.length/2);this.seenMessageIds=new Set(t.slice(n));}}getLocalAgentSummaries(){return d().map(e=>({id:e.id,project:e.project,role:e.role,status:h(e)?"asleep":"awake"}))}stop(){this.stopped=true;for(let[e,t]of this.connectedPeers)c(t,{type:"peer_leaving"}),t.close();this.connectedPeers.clear(),this.wsClient&&(this.wsClient.close(),this.wsClient=null),this.stopOutboxWatcher(),this.stopKeepalive(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.wss&&(this.wss.close(),this.wss=null);}getConnectedPeers(){return Array.from(this.connectedPeers.keys())}getRemoteAgents(){let e=[],t=c$1();for(let n of this.connectedPeers.keys()){let i=t.find(s=>s.id===n);if(i?.agents)for(let s of i.agents)e.push({...s,peerId:n});}return e}rotatePairingCode(){if(this.mode!=="server")throw new Error('rotatePairingCode() requires mode "server"');return this.pairingState=k$1(),this.pairingState}};export{X as SCORE_DIR,C as SymphonyRelay};
File without changes