@a-company/paradigm 6.6.3 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/dist/{accept-orchestration-JHDCVHB2.js → accept-orchestration-YO2V2WYA.js} +1 -1
  2. package/dist/add-V6XR7DU5.js +12 -0
  3. package/dist/{agents-suggest-IKY6VD2R.js → agents-suggest-WZEGQT5E.js} +1 -1
  4. package/dist/ambient-7HBJHJL2.js +2 -0
  5. package/dist/{ambient-FNNFB4AP.js → ambient-OX7YJ4PJ.js} +1 -1
  6. package/dist/ambient-SST5CLEC.js +35 -0
  7. package/dist/captain-YUP3KVCA.js +2 -0
  8. package/dist/chunk-33ERV2MW.js +18 -0
  9. package/dist/chunk-3MZ4J2LF.js +2 -0
  10. package/dist/chunk-47YPID6H.js +142 -0
  11. package/dist/chunk-6AKNXD22.js +32 -0
  12. package/dist/chunk-6HVOZANP.js +4 -0
  13. package/dist/chunk-ACJWUOMA.js +3 -0
  14. package/dist/chunk-B5KLSBOZ.js +2 -0
  15. package/dist/chunk-DLMDHS2X.js +10 -0
  16. package/dist/chunk-EKNLG73M.js +6 -0
  17. package/dist/chunk-FRQRREJ6.js +29 -0
  18. package/dist/{chunk-5RFISGUW.js → chunk-G6DK3ND3.js} +250 -25
  19. package/dist/{chunk-XKNJSPB5.js → chunk-JCGCPAHF.js} +1 -1
  20. package/dist/chunk-K54L6CFR.js +25 -0
  21. package/dist/chunk-QBIQ2FYB.js +20 -0
  22. package/dist/chunk-QEQCPVF5.js +4 -0
  23. package/dist/chunk-ROU3F2HZ.js +6 -0
  24. package/dist/chunk-S4J337EQ.js +504 -0
  25. package/dist/chunk-V6MIKLMY.js +18 -0
  26. package/dist/chunk-WROJSWAO.js +93 -0
  27. package/dist/{chunk-TQOT2LBO.js → chunk-YXLGVOZO.js} +1 -1
  28. package/dist/chunk-ZSWXLFN7.js +12 -0
  29. package/dist/{compliance-J3VOV445.js → compliance-MLG4W6S4.js} +1 -1
  30. package/dist/{diff-ANKTFDRA.js → diff-MC6AXLKX.js} +1 -1
  31. package/dist/{docs-TSAAS4W3.js → docs-3YFNNZRV.js} +1 -1
  32. package/dist/doctor-CBZYYQQH.js +2 -0
  33. package/dist/{hooks-45WDP6QS.js → hooks-AXBWYJ5V.js} +1 -1
  34. package/dist/index.js +6 -6
  35. package/dist/list-NC3QGT75.js +12 -0
  36. package/dist/mcp.js +3 -3
  37. package/dist/{migrate-R64OQGSM.js → migrate-5M4KUQ2L.js} +1 -1
  38. package/dist/{nomination-engine-NCLTGMAK.js → nomination-engine-AQHU2KBU.js} +1 -1
  39. package/dist/notebook-loader-6DYFMNJ2.js +2 -0
  40. package/dist/orchestrate-GMYEBA5T.js +8 -0
  41. package/dist/orchestration-G5MAY6IA.js +2 -0
  42. package/dist/propose-block-ZEMEWJQF.js +2 -0
  43. package/dist/{providers-TBPOE4DI.js → providers-5EHD45C6.js} +1 -1
  44. package/dist/quiz-TNV6APBM.js +10 -0
  45. package/dist/reindex-XTRF23F7.js +2 -0
  46. package/dist/serve-2PKJP65E.js +12 -0
  47. package/dist/{serve-3FMUWW5K.js → serve-SMGWGJLM.js} +1 -1
  48. package/dist/server-4SYOUF6D.js +7 -0
  49. package/dist/session-tracker-BZ7FU4AT.js +2 -0
  50. package/dist/session-work-log-QXPAXY5K.js +2 -0
  51. package/dist/session-work-log-T2IE4Y4T.js +2 -0
  52. package/dist/{shift-TNA2E5O7.js → shift-JBCEDCGA.js} +2 -2
  53. package/dist/show-N5LGB5B2.js +7 -0
  54. package/dist/solo-OWR3MX74.js +3 -0
  55. package/dist/{spawn-KKDDR6UR.js → spawn-PHA2SVQ3.js} +1 -1
  56. package/dist/status-ENAI35NL.js +6 -0
  57. package/dist/task-loader-IGQQ6ZFL.js +2 -0
  58. package/dist/task-settlement-NW4XMJGJ.js +3 -0
  59. package/dist/{team-PEGP6F7S.js → team-J2YXPEGX.js} +1 -1
  60. package/dist/team-funnel-RAJ6EDG3.js +2 -0
  61. package/dist/tools-HNJ7D5IO.js +2 -0
  62. package/dist/university-content/notes/N-para-801-cid-becomes-real.md +60 -0
  63. package/dist/university-content/notes/N-para-801-falsifiable-self-improvement.md +66 -0
  64. package/dist/university-content/notes/N-para-801-honest-routing-and-the-method.md +57 -0
  65. package/dist/university-content/notes/N-para-801-orchestration-emits-dag.md +60 -0
  66. package/dist/university-content/notes/N-para-801-settlement-closes-the-loop.md +64 -0
  67. package/dist/university-content/notes/N-para-801-the-task-dag.md +93 -0
  68. package/dist/university-content/paths/LP-para-801.yaml +43 -0
  69. package/dist/university-content/quizzes/Q-para-801-cid-becomes-real.yaml +54 -0
  70. package/dist/university-content/quizzes/Q-para-801-falsifiable-self-improvement.yaml +54 -0
  71. package/dist/university-content/quizzes/Q-para-801-honest-routing-and-the-method.yaml +54 -0
  72. package/dist/university-content/quizzes/Q-para-801-orchestration-emits-dag.yaml +54 -0
  73. package/dist/university-content/quizzes/Q-para-801-settlement-closes-the-loop.yaml +54 -0
  74. package/dist/university-content/quizzes/Q-para-801-the-task-dag.yaml +54 -0
  75. package/dist/university-ui/assets/{index-BIQeax_b.js → index-B8hm_MdR.js} +2 -2
  76. package/dist/university-ui/assets/{index-BIQeax_b.js.map → index-B8hm_MdR.js.map} +1 -1
  77. package/dist/university-ui/index.html +1 -1
  78. package/dist/validate-IQG7DBFC.js +9 -0
  79. package/package.json +2 -1
  80. package/dist/add-CBDFTWST.js +0 -12
  81. package/dist/ambient-AI42BOM5.js +0 -35
  82. package/dist/chunk-4N56FRNE.js +0 -29
  83. package/dist/chunk-6QXBXZF6.js +0 -3
  84. package/dist/chunk-AMLD7IYC.js +0 -10
  85. package/dist/chunk-DVZWCXB6.js +0 -2
  86. package/dist/chunk-ERO4MJSH.js +0 -6
  87. package/dist/chunk-F6E3HW45.js +0 -14
  88. package/dist/chunk-FI66YM6G.js +0 -666
  89. package/dist/chunk-K7X3Z3GL.js +0 -4
  90. package/dist/chunk-LAYBUKMB.js +0 -14
  91. package/dist/chunk-MU5YWTNE.js +0 -24
  92. package/dist/chunk-P344HV6Z.js +0 -2
  93. package/dist/chunk-QALPEMCU.js +0 -111
  94. package/dist/chunk-XQLO5URP.js +0 -11
  95. package/dist/doctor-L5XZENCF.js +0 -2
  96. package/dist/list-AXKTBXKJ.js +0 -12
  97. package/dist/notebook-loader-3J2OFMS3.js +0 -2
  98. package/dist/orchestrate-UG5QXNAU.js +0 -8
  99. package/dist/quiz-G56CUN45.js +0 -10
  100. package/dist/reindex-F7BZCG4W.js +0 -2
  101. package/dist/serve-TJQ5BNKR.js +0 -12
  102. package/dist/server-QOCW5RU6.js +0 -7
  103. package/dist/session-tracker-HHNY6J4I.js +0 -2
  104. package/dist/session-work-log-MEJ33TYD.js +0 -2
  105. package/dist/session-work-log-ZVVJGO7X.js +0 -2
  106. package/dist/show-MTPEQFXK.js +0 -7
  107. package/dist/status-REA6HUXE.js +0 -6
  108. package/dist/task-loader-NZFDTUQ5.js +0 -2
  109. package/dist/tools-HQKF4Q3P.js +0 -2
  110. package/dist/validate-742XMB42.js +0 -9
  111. /package/dist/{chunk-HXGYVS2N.js → chunk-ECLUYHAR.js} +0 -0
  112. /package/dist/{platform-server-ANOALDPL.js → platform-server-WIBVYHIV.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-BIQeax_b.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-B8hm_MdR.js"></script>
12
12
  <link rel="stylesheet" crossorigin href="/assets/index-C9zUgT5x.css">
13
13
  </head>
14
14
  <body>
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import {k,l,n,a,c,d}from'./chunk-EKNLG73M.js';import'./chunk-5TAVYPOV.js';import u from'chalk';import*as h from'fs';import*as p from'path';import*as C from'js-yaml';var P=/^[a-z0-9][a-z0-9-]{0,63}$/,v=new Set(["track","index","chronological","featured"]);function j(n){let d=p.join(n,"pack.yaml");if(!h.existsSync(d))return null;try{let s=h.readFileSync(d,"utf8"),i=C.load(s);return Array.isArray(i?.sections)?i.sections:null}catch{return null}}function z(n,d,s){let i=new Set,r=false;if(!n||n.length===0)return i.add("main"),{knownIds:i,hadValidationError:r};let t=new Set,f=0;for(let c=0;c<n.length;c++){let l=n[c],y=`sections[${c}]`;if(typeof l.id!="string"||!P.test(l.id)){s.push({contentId:"pack.yaml",severity:"error",check:"section-bad-id",message:`${y}.id must be kebab-case matching /^[a-z0-9][a-z0-9-]{0,63}$/`,fix:"Use lowercase letters, digits, and hyphens; start with a letter or digit"}),r=true;continue}if(t.has(l.id)){s.push({contentId:"pack.yaml",severity:"error",check:"section-duplicate-id",message:`duplicate section id "${l.id}"`,fix:"Each section id must be unique within the pack"}),r=true;continue}t.add(l.id),i.add(l.id),(typeof l.style!="string"||!v.has(l.style))&&(s.push({contentId:"pack.yaml",severity:"error",check:"section-bad-style",message:`${y}.style must be one of: ${Array.from(v).join(", ")}`}),r=true),l.default===true&&f++;}f>1&&(s.push({contentId:"pack.yaml",severity:"error",check:"section-multiple-defaults",message:`at most one section may set default: true (found ${f})`,fix:"Set default: true on exactly one section"}),r=true);for(let c of d)i.has(c)||s.push({contentId:"pack.yaml",severity:"warning",check:"section-unknown-ref",message:`entries reference unknown section "${c}"`,fix:`Declare section "${c}" in pack.yaml, or remove the section: field from those entries`});return {knownIds:i,hadValidationError:r}}async function E(n$1){let d$1=process.cwd(),s=k(d$1,n$1),i=l(n$1)?s.subPackRoot??s.packRoot:void 0,r=i?n(i):a(d$1);if(!r||r.totalContent===0){console.log(u.yellow(`
3
+ No university content to validate.
4
+ `));return}let t=[],f=r.entries;n$1.id&&(f=f.filter(e=>e.id===n$1.id),f.length===0&&(console.error(u.red(`
5
+ Content "${n$1.id}" not found
6
+ `)),process.exit(1)));let c$1=null;if(n$1.deep){c$1=new Set;let e=p.join(d$1,".paradigm","scan-index.json");if(h.existsSync(e))try{let a=JSON.parse(h.readFileSync(e,"utf8"));if(a.symbols&&Array.isArray(a.symbols))for(let o of a.symbols)o.symbol&&c$1.add(o.symbol);}catch{}}let l$1=new Set(r.entries.map(e=>e.id)),y=s.subPackRoot??s.packRoot,R=j(y),k$1=new Set;for(let e of r.entries)e.section&&typeof e.section=="string"&&e.section.length>0&&k$1.add(e.section);z(R,k$1,t);for(let e of f){if(e.title||t.push({contentId:e.id,severity:"error",check:"missing-title",message:"Content is missing a title"}),e.type==="quiz"){let a=c(d$1,e.id,i);if(!a)t.push({contentId:e.id,severity:"error",check:"unreadable-quiz",message:"Quiz file could not be parsed"});else for(let o of a.questions)(!o.choices||!(o.correct in o.choices))&&t.push({contentId:e.id,severity:"error",check:"invalid-quiz-answer",message:`Question ${o.id}: correct "${o.correct}" not in choices [${Object.keys(o.choices||{}).join(", ")}]`,fix:`Set correct to one of: ${Object.keys(o.choices||{}).join(", ")}`});}if(e.type==="path"){let a=d(d$1,e.id,i);if(!a)t.push({contentId:e.id,severity:"error",check:"unreadable-path",message:"Learning path file could not be parsed"});else for(let o of a.steps)!o.content.startsWith("plsat:")&&!l$1.has(o.content)&&t.push({contentId:e.id,severity:"error",check:"broken-path-step",message:`Step references "${o.content}" which doesn't exist`,fix:`Create content with id "${o.content}"`});}if(c$1&&e.symbols.length>0)for(let a of e.symbols)c$1.has(a)||t.push({contentId:e.id,severity:"warning",check:"broken-symbol-ref",message:`Symbol "${a}" not found in scan-index`});}if(n$1.json){console.log(JSON.stringify({status:t.some(e=>e.severity==="error")?"errors":t.length>0?"warnings":"healthy",totalContent:r.totalContent,checked:f.length,issues:t},null,2));return}if(console.log(u.blue(`
7
+ University Validation \u2014 pack: ${s.subPackId??s.packId} (${f.length} items${n$1.deep?", deep mode":""})
8
+ `)),t.length===0){console.log(u.green(` All checks passed.
9
+ `));return}let g=t.filter(e=>e.severity==="error"),m=t.filter(e=>e.severity==="warning");for(let e of g)console.log(u.red(` x ${e.contentId}: ${e.message}`)),e.fix&&console.log(u.gray(` Fix: ${e.fix}`));for(let e of m)console.log(u.yellow(` ! ${e.contentId}: ${e.message}`)),e.fix&&console.log(u.gray(` Fix: ${e.fix}`));console.log(),g.length>0&&console.log(u.red(` ${g.length} error${g.length>1?"s":""}`)),m.length>0&&console.log(u.yellow(` ${m.length} warning${m.length>1?"s":""}`)),console.log();}export{E as universityValidateCommand};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-company/paradigm",
3
- "version": "6.6.3",
3
+ "version": "7.0.0",
4
4
  "description": "Unified CLI for Paradigm developer tools",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -36,6 +36,7 @@
36
36
  "dependencies": {
37
37
  "@a-company/portal-core": "*",
38
38
  "@a-company/registry-client": "^0.1.0",
39
+ "@a-company/university-core": "*",
39
40
  "@modelcontextprotocol/sdk": "^1.0.0",
40
41
  "chalk": "^5.3.0",
41
42
  "commander": "^11.1.0",
@@ -1,12 +0,0 @@
1
- #!/usr/bin/env node
2
- import {g,i,f}from'./chunk-ERO4MJSH.js';import {c,a}from'./chunk-P344HV6Z.js';import'./chunk-5TAVYPOV.js';import r from'chalk';import {execSync}from'child_process';import*as $ from'os';function S(){try{return execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").slice(0,20)||"unknown"}catch{try{return $.userInfo().username}catch{return "unknown"}}}async function P(n,e){let s=process.cwd(),x=e.pack||e.project||e.discipline?e:{...e,project:true},c$1=c(s,x);if(e.title||(console.error(r.red(`
3
- Error: --title is required
4
- `)),process.exit(1)),e.section){let t=a(c$1.subPackRoot??c$1.packRoot);if(t.length>0&&!new Set(t.map(a=>a.id)).has(e.section)){let a=t.map(z=>z.id).join(", "),w=c$1.subPackId??c$1.packId;console.error(r.red(`
5
- Error: section "${e.section}" not declared in pack "${w}". Available: ${a}
6
- `)),process.exit(1);}}let i$1=e.order!==void 0?parseInt(e.order,10):void 0;e.order!==void 0&&(i$1===void 0||Number.isNaN(i$1))&&(console.error(r.red(`
7
- Error: --order must be an integer (got "${e.order}")
8
- `)),process.exit(1));let u=S(),o=new Date().toISOString().slice(0,10),f$1=e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),m=e.tags?e.tags.split(",").map(t=>t.trim()):[],g$1=e.symbols?e.symbols.split(",").map(t=>t.trim()):[];if(n==="quiz"){let t=`Q-${f$1}`,y={id:t,title:e.title,description:e.body||"",author:u,created:o,updated:o,tags:m,symbols:g$1,difficulty:e.difficulty||"beginner",passThreshold:.7,questions:[],...e.section?{section:e.section}:{},...i$1!==void 0?{order:i$1}:{}};g(s,y),i(s),console.log(r.green(`
9
- Created quiz: ${t}`)),console.log(r.gray(` Add questions by editing the YAML file
10
- `));return}let d=`${n==="policy"?"P":"N"}-${f$1}`,h={id:d,title:e.title,type:n,author:u,created:o,updated:o,tags:m,symbols:g$1,difficulty:e.difficulty||"beginner",estimatedMinutes:e.minutes?parseInt(e.minutes,10):void 0,prerequisites:[],...e.section?{section:e.section}:{},...i$1!==void 0?{order:i$1}:{}};f(s,h,e.body||""),i(s),console.log(r.green(`
11
- Created ${n}: ${d}`)),console.log(r.gray(` Edit at .paradigm/university/content/${n==="policy"?"policies":"notes"}/${d}.md
12
- `));}export{P as universityAddCommand};
@@ -1,35 +0,0 @@
1
- #!/usr/bin/env node
2
- import {f,p as p$1,i,c as c$1,j}from'./chunk-GD4F2HC6.js';import {e,b as b$2,f as f$1}from'./chunk-F6E3HW45.js';import {b as b$3}from'./chunk-7SWEOPWF.js';import'./chunk-MBPLJKE5.js';import {c,b as b$1,d,a}from'./chunk-5TAVYPOV.js';import*as p from'fs';import*as b from'path';import*as T from'js-yaml';import*as Z from'os';var kt={};c(kt,{getJournalStats:()=>se,loadAllJournalEntries:()=>re,loadJournalEntries:()=>O,loadJournalEntry:()=>ie,recordJournalEntry:()=>V});function G(e){let t=process.env.HOME||process.env.USERPROFILE||"";return b.join(t,".paradigm","agents",e,"journal")}function oe(){let e=new Date,t=e.toISOString().slice(0,10),n=e.toISOString().slice(11,19).replace(/:/g,""),o=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `LJ-${t}-${n}-${o}`}function V(e,t){let n=new Date,o=oe(),r={id:o,agent:e,timestamp:n.toISOString(),...t},i=G(e);p.mkdirSync(i,{recursive:true});let s=b.join(i,`${o}.yaml`);return p.writeFileSync(s,T.dump(r,{lineWidth:120,noRefs:true}),"utf8"),r}function O(e,t){let n=G(e);if(!p.existsSync(n))return [];let o=[],r=p.readdirSync(n).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=p.readFileSync(b.join(n,s),"utf8"),c=T.load(a);c&&c.id&&o.push(c);}catch{}let i=o;return t?.trigger&&(i=i.filter(s=>s.trigger===t.trigger)),t?.project&&(i=i.filter(s=>s.project===t.project)),t?.transferable!==void 0&&(i=i.filter(s=>s.transferable===t.transferable)),t?.tag&&(i=i.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(i=i.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(i=i.filter(s=>s.timestamp<=t.dateTo)),i.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}function ie(e,t){let n=G(e),o=b.join(n,`${t}.yaml`);if(!p.existsSync(o))return null;let r=p.readFileSync(o,"utf8");return T.load(r)}function re(e){let t=process.env.HOME||process.env.USERPROFILE||"",n=b.join(t,".paradigm","agents");if(!p.existsSync(n))return [];let o=[],r=p.readdirSync(n,{withFileTypes:true}).filter(i=>i.isDirectory());for(let i of r){if(e?.agent&&i.name!==e.agent)continue;let s=O(i.name,e);o.push(...s);}return o.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),e?.limit?o.slice(0,e.limit):o}function se(e){let t=O(e),n={},o={},r=0;for(let i of t)n[i.trigger]=(n[i.trigger]||0)+1,o[i.project]=(o[i.project]||0)+1,i.transferable&&r++;return {total:t.length,byTrigger:n,byProject:o,transferableCount:r,recentInsights:t.slice(0,5).map(i=>({id:i.id,trigger:i.trigger,insight:i.insight.slice(0,200),timestamp:i.timestamp}))}}var K=b$1(()=>{});var Tt={};c(Tt,{addNotebookEntry:()=>Rt,classifyNotebookScope:()=>$t,incrementApplied:()=>de,loadNotebookEntries:()=>Nt,promoteFromLore:()=>le,searchNotebooks:()=>ce});function Nt(e,t,n){let o=new Map,r=b.join(X,e);xt(r,o);let i=b.join(t,Y,e);xt(i,o);let s=Array.from(o.values());if(n?.concepts&&n.concepts.length>0){let a=new Set(n.concepts.map(c=>c.toLowerCase()));s=s.filter(c=>c.concepts.some(u=>a.has(u.toLowerCase())));}if(n?.tags&&n.tags.length>0){let a=new Set(n.tags.map(c=>c.toLowerCase()));s=s.filter(c=>c.tags.some(u=>a.has(u.toLowerCase())));}return s.sort((a,c)=>c.appliedCount-a.appliedCount)}function xt(e,t){if(p.existsSync(e))try{let n=p.readdirSync(e).filter(o=>o.startsWith(ae)&&o.endsWith(Q));for(let o of n)try{let r=p.readFileSync(b.join(e,o),"utf-8"),i=T.load(r);i?.id&&t.set(i.id,i);}catch{}}catch{}}function ce(e,t,n){let o=Nt(e,n),r=t.toLowerCase();return o.filter(i=>i.context.toLowerCase().includes(r)||i.snippet.toLowerCase().includes(r)||i.concepts.some(s=>s.toLowerCase().includes(r))||i.tags.some(s=>s.toLowerCase().includes(r)))}function $t(e){let t=[e.context,e.snippet,...e.concepts,...e.tags].join(" ").toLowerCase();return ["paradigm","mcp_","mcp tool",".paradigm/","lore entry","lore record","aspect","^gate","portal.yaml",".purpose","sentinel","symphony","ambient nomination","paradigm_"," pan ","agent notebook","concept anchor","symbol system","work log","knowledge stream","nevr.land","neverland"].some(o=>t.includes(o))?"platform-specific":/[#$^!~][a-z][a-z0-9-]{2,}/.test(t)||/\/[a-z0-9_-]{2,}\/[a-z0-9_-]/.test(t)?"project-specific":"generalizable"}function Rt(e,t,n,o){let r=new Date().toISOString(),i=(t.concepts[0]||t.context.split(" ").slice(0,4).join(" ")||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),a=`nb-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}-${i}`,c=t.scope??$t({context:t.context,snippet:t.snippet,concepts:t.concepts,tags:t.tags}),u={...t,id:a,scope:c,publishable:t.publishable??true,appliedCount:0,created:r,updated:r},d=n==="global"?b.join(X,e):b.join(o||process.cwd(),Y,e);p.existsSync(d)||p.mkdirSync(d,{recursive:true});let l=`${a}${Q}`,m=b.join(d,l),g=T.dump(u,{lineWidth:120,noRefs:true,sortKeys:false});return p.writeFileSync(m,g,"utf-8"),{entry:u,filePath:m}}async function le(e,t,n,o="global"){let{loadLoreEntry:r}=await import('./lore-loader-D2ISOASW.js'),i=await r(n,t);if(!i)return null;let s=[];if(i.symbols_touched)for(let u of i.symbols_touched){let d=u.replace(/^[#$^!~]/,"").toLowerCase();s.push(d);}let a=i.summary||"";i.body&&(a+=`
3
-
4
- `+i.body);let c={source:"lore",loreEntryId:t,originProject:b.basename(n),createdBy:e};return Rt(e,{context:i.title||`Promoted from ${t}`,snippet:a,provenance:c,confidence:i.confidence??.7,concepts:s,tags:i.tags||[]},o,n)}function de(e,t,n){let o=b.join(n,Y,e),r=b.join(X,e);for(let i of [o,r]){let s=b.join(i,`${t}${Q}`);if(p.existsSync(s))try{let a=p.readFileSync(s,"utf-8"),c=T.load(a);if(c)return c.appliedCount=(c.appliedCount||0)+1,c.updated=new Date().toISOString(),p.writeFileSync(s,T.dump(c,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var X,Y,ae,Q,Pt=b$1(()=>{X=b.join(Z.homedir(),".paradigm","notebooks"),Y=".paradigm/notebooks",ae="nb-",Q=".yaml";});var ht=".paradigm/events",Yt="stream.jsonl",J=1e3,$=[];function bt(e){return b.join(e,ht,Yt)}function Qt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${e}-${t}`}function M(e,t){let n={id:Qt(),timestamp:new Date().toISOString(),...t};$.push(n),$.length>J&&($=$.slice(-J));try{let o=b.join(e,ht);p.mkdirSync(o,{recursive:!0});let r=bt(e);p.appendFileSync(r,JSON.stringify(n)+`
5
- `,"utf8"),Zt(r);}catch{}return n}function Zt(e){try{if(p.statSync(e).size>512*1024){let o=p.readFileSync(e,"utf8").trim().split(`
6
- `);if(o.length>J){let r=o.slice(-J);p.writeFileSync(e,r.join(`
7
- `)+`
8
- `,"utf8");}}}catch{}}function St(e,t){let n=te(e);return t?.type&&(n=n.filter(o=>o.type===t.type)),t?.source&&(n=n.filter(o=>o.source===t.source)),t?.symbol&&(n=n.filter(o=>o.symbols?.includes(t.symbol))),t?.agent&&(n=n.filter(o=>o.agent===t.agent)),t?.since&&(n=n.filter(o=>o.timestamp>=t.since)),n.sort((o,r)=>r.timestamp.localeCompare(o.timestamp)),t?.limit&&(n=n.slice(0,t.limit)),n}function te(e){let t=bt(e);if(!p.existsSync(t))return [...$];try{return p.readFileSync(t,"utf8").trim().split(`
9
- `).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return [...$]}}function wt(e,t,n){let o=0,r=0,i=0,s=0;if(n.symbols?.length&&e.symbols?.length)for(let d of n.symbols)for(let l of e.symbols)yt(d,l)&&(o=Math.max(o,1));if(n.paths?.length&&e.path){for(let d of n.paths)if(yt(d,e.path)){r=1;break}}if(n.concepts?.length){let d=[e.context||"",...e.keywords||[],e.type||""].join(" ").toLowerCase(),l=0;for(let m of n.concepts)m&&d.includes(m.toLowerCase())&&l++;n.concepts.length>0&&(i=l/n.concepts.length);}if(n.signals?.length){for(let d of n.signals)if(d.type===e.type){s=1;break}}let a=[o,r,i,s].sort((d,l)=>l-d),c=a[0]*.5+a[1]*.2+a[2]*.15+a[3]*.15,u=n.threshold??.6;return {agentId:t,score:c,breakdown:{symbolMatch:o,pathMatch:r,conceptMatch:i,signalMatch:s},shouldNominate:c>=u,quietReason:c<u?"below-threshold":void 0}}function yt(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 ee=".paradigm/data-policy.yaml";function jt(e){let t=b.join(e,ee);if(!p.existsSync(t))return {...b$3};try{let n=p.readFileSync(t,"utf8"),o=T.load(n);return ne(b$3,o)}catch{return {...b$3}}}function ne(e,t){let n={...e};if(t.version&&(n.version=t.version),t.default_ring&&(n.default_ring=t.default_ring),t.observation&&(n.observation={allow:t.observation.allow||e.observation?.allow,deny:[...e.observation?.deny||[],...t.observation.deny||[]].filter((o,r,i)=>i.indexOf(o)===r)}),t.streams){n.streams={...e.streams};for(let o of ["work_log","learning_journal","team_decisions"])t.streams[o]&&(n.streams[o]={...e.streams?.[o],...t.streams[o],deny_content:[...e.streams?.[o]?.deny_content||[],...t.streams[o]?.deny_content||[]].filter((r,i,s)=>s.indexOf(r)===i)});}return t.upstream&&(n.upstream={...e.upstream,...t.upstream}),t.network&&(n.network={...e.network,...t.network}),t.agent_overrides&&(n.agent_overrides={...e.agent_overrides,...t.agent_overrides}),t.deployment&&(n.deployment={...e.deployment,...t.deployment}),n}function Et(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(r=>z(r,t))||e.observation?.deny?.some(o=>z(o,t))?false:e.observation?.allow?.length?e.observation.allow.some(o=>z(o,t)):true}function z(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 N=".paradigm/events",ue="nominations.jsonl",me="debates.jsonl",fe=500,pe=200,ge=7,ye=14,he=100;function be(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function Se(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${e}-${t}`}function we(e,t){let n=i(e),o=jt(e),r=[];for(let u of n){if(!u.attention||!c$1(u.id,e)||t.path&&!Et(o,t.path,u.id))continue;let d=wt(t,u.id,u.attention);d.shouldNominate&&r.push({profile:u,score:d});}if(r.length===0)return {nominations:[],debates:[]};let i$1=E(e,{since:new Date(Date.now()-3e4).toISOString()}),s=r.filter(({profile:u})=>!i$1.find(l=>l.agent===u.id&&l.brief===Ot(u,t,{...r.find(m=>m.profile.id===u.id).score})));if(s.length===0)return {nominations:[],debates:[]};let a=s.map(({profile:u,score:d})=>{let l=_e(t,d),m=ve(u,t);return {id:be(),agent:u.id,relevance:d.score,urgency:l,type:m,brief:Ot(u,t,d),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});Ee(e,a);let c=je(e,a);return c.length>0&&ke(e,c),{nominations:a,debates:c}}function _e(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 ve(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 Ot(e,t,n){let o=e.role||e.id;switch(t.type){case "gate-checked":return `${o}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${o}: ${t.path||"File"} modified \u2014 review for ${e.id==="security"?"security implications":e.id==="tester"?"test coverage":e.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${o}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${o}: New route ${t.symbols?.join(", ")||""} \u2014 ${e.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${o}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${e.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${o}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${o}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${o}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let r=n.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:n.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${o}: ${r}`}}}function je(e,t){if(t.length<2)return [];let n=[],o=new Map;for(let r of t)for(let i of r.triggered_by){let s=o.get(i)||[];s.push(r),o.set(i,s);}for(let[r,i]of o){if(i.length<2||new Set(i.map(u=>u.agent)).size<2)continue;let a=new Set(i.map(u=>u.type)),c=a.size>1&&a.has("warning")&&a.has("suggestion");n.push({id:Se(),topic:`Multiple agents responded to event ${r}`,nominations:i.map(u=>u.id),type:c?"conflicting":"complementary",overlap_events:[r]});}return n}function tt(e){return b.join(e,N,ue)}function et(e){return b.join(e,N,me)}function Ee(e,t){try{let n=b.join(e,N);p.mkdirSync(n,{recursive:!0});let o=tt(e),r=t.map(s=>JSON.stringify(s)).join(`
10
- `)+`
11
- `;p.appendFileSync(o,r,"utf8"),At(o,fe);let{nominationTtlDays:i}=U(e);Ft(o,i*24*60*60*1e3);}catch{}}function ke(e,t){try{let n=b.join(e,N);p.mkdirSync(n,{recursive:!0});let o=et(e),r=t.map(s=>JSON.stringify(s)).join(`
12
- `)+`
13
- `;p.appendFileSync(o,r,"utf8"),At(o,pe);let{debateTtlDays:i}=U(e);Ft(o,i*24*60*60*1e3);}catch{}}function At(e,t){try{let o=p.readFileSync(e,"utf8").trim().split(`
14
- `).filter(r=>r.trim());if(o.length>t){let r=o.slice(-t);p.writeFileSync(e,r.join(`
15
- `)+`
16
- `,"utf8");}}catch{}}function U(e){let t={nominationTtlDays:ge,debateTtlDays:ye};try{let n=b.join(e,".paradigm","config.yaml");if(!p.existsSync(n))return t;let o=a("js-yaml"),r=p.readFileSync(n,"utf8"),s=o.load(r)?.ambient;return s?{nominationTtlDays:typeof s["nomination-ttl-days"]=="number"?s["nomination-ttl-days"]:t.nominationTtlDays,debateTtlDays:typeof s["debate-ttl-days"]=="number"?s["debate-ttl-days"]:t.debateTtlDays}:t}catch{return t}}function Ft(e,t){try{if(!p.existsSync(e))return;let o=p.readFileSync(e,"utf8").trim().split(`
17
- `).filter(s=>s.trim());if(o.length<=he)return;let r=Date.now()-t,i=o.filter(s=>{try{let a=JSON.parse(s);return (a.timestamp?new Date(a.timestamp).getTime():Date.now())>=r}catch{return !0}});i.length<o.length&&p.writeFileSync(e,i.join(`
18
- `)+`
19
- `,"utf8");}catch{}}function E(e,t){let n=tt(e);if(!p.existsSync(n))return [];try{let r=p.readFileSync(n,"utf8").trim().split(`
20
- `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null);return t?.agent&&(r=r.filter(i=>i.agent===t.agent)),t?.urgency&&(r=r.filter(i=>i.urgency===t.urgency)),t?.surfaced!==void 0&&(r=r.filter(i=>i.surfaced===t.surfaced)),t?.pending_only&&(r=r.filter(i=>!i.engaged)),t?.since&&(r=r.filter(i=>i.timestamp>=t.since)),r.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),t?.limit&&(r=r.slice(0,t.limit)),r}catch{return []}}function It(e){let t=et(e);if(!p.existsSync(t))return [];try{return p.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 Ct(e,t,n,o){let r=tt(e);if(!p.existsSync(r))return false;try{let s=p.readFileSync(r,"utf8").trim().split(`
22
- `),a=!1,c=s.map(u=>{try{let d=JSON.parse(u);return d.id===t?(d.engaged=!0,d.response=n,o&&(d.reason=o),a=!0,JSON.stringify(d)):u}catch{return u}});if(a&&(p.writeFileSync(r,c.join(`
23
- `)+`
24
- `,"utf8"),n==="accepted"||n==="dismissed")){let u=JSON.parse(s.find(l=>{try{return JSON.parse(l).id===t}catch{return !1}}));i(e).find(l=>l.id===u.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&M(e,{type:"work-completed",source:"agent-action",agent:u.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return a}catch{return false}}function Jt(e,t,n,o){let r=et(e);if(!p.existsSync(r))return false;try{let s=p.readFileSync(r,"utf8").trim().split(`
25
- `),a=!1,c=s.map(u=>{try{let d=JSON.parse(u);if(d.id===t){d.resolution={chosen:n,reason:o,resolved_by:"human",resolved_at:new Date().toISOString()},a=!0;let l=d.nominations.filter(m=>m!==n);for(let m of l){let g=E(e).find(f=>f.id===m);g&&M(e,{type:"work-completed",source:"agent-action",agent:g.agent,context:`Debate ${t} resolved \u2014 nomination ${m} not chosen`,data:{debate_id:t,chosen:n,reason:o}});}return JSON.stringify(d)}return u}catch{return u}});return a&&p.writeFileSync(r,c.join(`
26
- `)+`
27
- `,"utf8"),a}catch{return false}}function Mt(e){let t=b.join(e,N,".last-processed"),n="";try{p.existsSync(t)&&(n=p.readFileSync(t,"utf8").trim());}catch{}let o=b.join(e,N,"stream.jsonl");if(!p.existsSync(o))return {processed:0,nominations:[]};let r=[];try{r=p.readFileSync(o,"utf8").trim().split(`
28
- `).filter(l=>l.trim()).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(l=>l!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(n){let d=r.findIndex(l=>l.id===n);d>=0&&(i=d+1);}let s=r.slice(i);if(s.length===0)return {processed:0,nominations:[]};let a=[],c=s.slice(0,50);for(let d of c){let{nominations:l}=we(e,d);a.push(...l);}let u=c[c.length-1];try{p.mkdirSync(b.join(e,N),{recursive:!0}),p.writeFileSync(t,u.id,"utf8");}catch{}return {processed:c.length,nominations:a}}function Lt(e,t){let n=f(e,t);if(!n?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let o=n.attention.threshold??.6,{nominationTtlDays:r}=U(e),i=r*24*60*60*1e3,c=E(e,{agent:t}).filter(j=>j.engaged||Date.now()-new Date(j.timestamp).getTime()<i).filter(j=>j.engaged);if(c.length<5)return {adjusted:false,oldThreshold:o,newThreshold:o,reason:`Insufficient data (${c.length}/5 engaged nominations)`};let u=c.filter(j=>j.response==="accepted").length,d=c.filter(j=>j.response==="dismissed").length,l=u/c.length,m=d/c.length,g=o,f$1="No adjustment needed";if(m>.6?(g=Math.min(.95,o+.05),f$1=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):l>.8&&(g=Math.max(.2,o-.05),f$1=`High accept rate (${(l*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),g===o)return {adjusted:false,oldThreshold:o,newThreshold:g,reason:f$1};n.attention.threshold=g;let y=b.join(e,".paradigm/agents",`${t}.agent`),D=p.existsSync(y)?"project":"global";return j(t,n,D,e),M(e,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${o.toFixed(2)} \u2192 ${g.toFixed(2)} (${f$1})`,data:{old_threshold:o,new_threshold:g,accept_rate:l,dismiss_rate:m}}),{adjusted:true,oldThreshold:o,newThreshold:g,reason:f$1}}function nt(e,t){let{nominationTtlDays:n}=U(e),o=n*24*60*60*1e3,i=E(e,{agent:t}).filter(l=>l.engaged||Date.now()-new Date(l.timestamp).getTime()<o),s=i.filter(l=>l.response==="accepted").length,a=i.filter(l=>l.response==="dismissed").length,c=i.filter(l=>l.response==="deferred").length,u=i.filter(l=>!l.engaged).length,d=s+a+c;return {total:i.length,accepted:s,dismissed:a,deferred:c,pending:u,acceptRate:d>0?s/d:0}}function Ut(e){let n=i(e).filter(l=>c$1(l.id,e)).map(l=>{let m=nt(e,l.id),g=0;try{let f=b.join(Z.homedir(),".paradigm","notebooks",l.id);p.existsSync(f)&&(g=p.readdirSync(f).filter(y=>y.endsWith(".yaml")).length);}catch{}return {id:l.id,acceptRate:m.acceptRate,threshold:l.attention?.threshold??.5,expertiseCount:(l.expertise||[]).length,notebookCount:g,transferableCount:(l.transferable||[]).length,totalNominations:m.total}}),o=n.length||1,r=n.reduce((l,m)=>l+m.acceptRate,0)/o,i$1=n.reduce((l,m)=>l+m.threshold,0)/o,s=n.reduce((l,m)=>l+m.expertiseCount,0),a=n.reduce((l,m)=>l+m.notebookCount,0),c=n.reduce((l,m)=>l+m.transferableCount,0),u=n.reduce((l,m)=>l+m.totalNominations,0),d;return u<10?d="cold-start":r<.5?d="accumulating":r<.7?d="calibrating":d="mature",{agents:n,aggregate:{avgAcceptRate:r,avgThreshold:i$1,totalExpertise:s,totalNotebooks:a,totalTransferable:c},healthStatus:d}}function ot(e,t){let n,o;try{let c=(K(),d(kt)),u=(Pt(),d(Tt));n=c.loadJournalEntries,o=u.addNotebookEntry;}catch{return {promoted:0,entries:[]}}let r=n(t,{trigger:"pattern_discovered",limit:100}),i=n(t,{trigger:"human_feedback",limit:100}),s=[...r,...i],a=[];for(let c of s)if(!c.promoted_to_notebook&&!((c.confidence_after??0)<.8))try{let{entry:u}=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:"lore",loreEntryId:c.id,createdBy:t}},"global",e);a.push({journalId:c.id,notebookId:u.id});try{let d=b.join(Z.homedir(),".paradigm","agents",t,"journal");if(p.existsSync(d)){let l=p.readdirSync(d).filter(m=>m.endsWith(".yaml"));for(let m of l){let g=b.join(d,m),f=p.readFileSync(g,"utf8");if(f.includes(c.id)){let y=f.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${u.id}"`);if(y===f){let D=f.trimEnd().split(`
29
- `);D.push(`promoted_to_notebook: "${u.id}"`),p.writeFileSync(g,D.join(`
30
- `)+`
31
- `,"utf8");}else p.writeFileSync(g,y,"utf8");break}}}}catch{}}catch{}return {promoted:a.length,entries:a}}var xe=".paradigm/surfacing.yaml";function Ht(e){let t=b.join(e,xe),n={default_min_urgency:"low",enable_debates:true};if(!p.existsSync(t))return n;try{let o=a("js-yaml"),r=p.readFileSync(t,"utf8"),i=o.load(r);return {...n,...i}}catch{return n}}function Bt(e,t){let n={critical:0,high:1,medium:2,low:3},o=n[t.default_min_urgency||"low"]??3;return e.filter(r=>{let i=n[r.urgency]??3;if(t.preferences){let s=t.preferences.find(a=>a.agent===r.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(c=>r.urgency===c||r.type===c))return false;if(s.min_urgency){let a=n[s.min_urgency]??3;return i<=a}}}return i<=o})}var De=".paradigm/decisions";function Wt(e,t){let n=b.join(e,De);if(!p.existsSync(n))return [];let o=[],r=p.readdirSync(n).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=p.readFileSync(b.join(n,s),"utf8"),c=T.load(a);c&&c.id&&o.push(c);}catch{}let i=o;return (i=i.filter(s=>s.status===t.status)),t?.participant&&(i=i.filter(s=>s.participants.some(a=>a.id===t.participant))),t?.symbol&&(i=i.filter(s=>s.symbols_affected?.includes(t.symbol))),t?.tag&&(i=i.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(i=i.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(i=i.filter(s=>s.timestamp<=t.dateTo)),i.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}K();function Ye(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function Ne(e){let t=Date.now(),n=e.match(/^(\d+)(m|h|d)$/);if(n){let o=parseInt(n[1],10),r=n[2],i=r==="m"?o*6e4:r==="h"?o*36e5:o*864e5;return new Date(t-i).toISOString()}return e}async function Qe(e,t,n){let o=r=>JSON.stringify(r,null,2);switch(e){case "paradigm_ambient_nominations":{Mt(n.rootDir);let i=t.pending_only!==false,s=t.limit||20,a=E(n.rootDir,{agent:t.agent,urgency:t.urgency,pending_only:i,limit:s+20}),c=Ht(n.rootDir);a=Bt(a,c).slice(0,s);let u=b.join(n.rootDir,".paradigm/events/nominations.jsonl");if(p.existsSync(u))try{let l=p.readFileSync(u,"utf8"),m=new Set(a.map(f=>f.id)),g=l.trim().split(`
32
- `).map(f=>{try{let y=JSON.parse(f);return m.has(y.id)?(y.surfaced=!0,JSON.stringify(y)):f}catch{return f}});p.writeFileSync(u,g.join(`
33
- `)+`
34
- `,"utf8");}catch{}let d={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=It(n.rootDir).filter(g=>!g.resolution);d.debates=m.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),d.debate_count=m.length;}return {text:o(d),handled:true}}case "paradigm_ambient_events":{let r=t.since?Ne(t.since):void 0,i=t.limit||50,s=St(n.rootDir,{type:t.type,source:t.source,symbol:t.symbol,agent:t.agent,since:r,limit:i});return {text:o({count:s.length,events:s.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let r=t.nomination_id,i=t.response,s=t.reason,a=Ct(n.rootDir,r,i,s);if(a)try{let{appendSessionWorkEntry:u,appendVerdictEntry:d}=await import('./session-work-log-ZVVJGO7X.js'),m=E(n.rootDir,{limit:500}).find(f=>f.id===r),g={timestamp:new Date().toISOString(),type:"user-verdict",agent:m?.agent,nominationId:r,verdict:i,reason:s};u(n.rootDir,g),d(n.rootDir,g);}catch{}let c=false;return t.resolve_debate&&a&&(c=Jt(n.rootDir,t.resolve_debate,r,t.reason)),{text:o({engaged:a,nomination_id:r,response:i,debate_resolved:c||void 0}),handled:true}}case "paradigm_context_compose":{let r=t.agent,i=t.symbols||[],s=t.include_nominations!==false,a=t.include_decisions!==false,c=t.include_journal!==false,u=t.max_decisions||5,d=t.max_journal||5,l=f(n.rootDir,r);if(!l)return {text:o({error:`Agent profile not found: ${r}`}),handled:true};let m=[],g=p$1(l,i);if(g.trim()&&m.push(g),a){let f=Wt(n.rootDir,{status:"active",limit:u});if(f.length>0){m.push("## Recent Team Decisions");for(let y of f)m.push(`- **${y.title}**: ${y.decision.slice(0,150)}${y.decision.length>150?"...":""}`);m.push("");}}if(c){let f=O(r,{transferable:true,limit:d});if(f.length>0){m.push("## Transferable Insights");for(let y of f)m.push(`- [${y.trigger}] ${y.insight.slice(0,150)}${y.insight.length>150?"...":""}`);m.push("");}}if(s){let f=E(n.rootDir,{pending_only:true,limit:10});if(f.length>0){m.push("## Pending Nominations");for(let y of f)m.push(`- [${y.urgency}] ${y.brief}`);m.push("");}}return {text:o({agent:r,context:m.join(`
35
- `),sections_included:{profile:true,decisions:a,journal:c,nominations:s}}),handled:true}}case "paradigm_ambient_promote":{let r=t.agent,i=ot(n.rootDir,r);return {text:o({agent:r,promoted:i.promoted,entries:i.entries}),handled:true}}case "paradigm_ambient_learn":{let r=t.agent,i=t.dry_run===true,s=nt(n.rootDir,r);if(i)return {text:o({agent:r,dry_run:true,stats:s,note:s.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(s.acceptRate*100).toFixed(0)}% \u2014 ${s.acceptRate>.8?"would lower threshold":s.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=Lt(n.rootDir,r);return {text:o({agent:r,...a,stats:s}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let r=Ut(n.rootDir);return {text:o(r),handled:true}}case "paradigm_ambient_learn_postflight":return {text:o(await Te(n.rootDir,t)),handled:true};default:return {text:`Unknown ambient tool: ${e}`,handled:false}}}var $e={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function Re(e){try{let t=b.join(e,".paradigm","config.yaml");if(p.existsSync(t)){let o=p.readFileSync(t,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(o)return o[1].trim()}}catch{}return b.basename(e)}async function Te(e$1,t={}){let n=t.dry_run===true,o=Re(e$1),r=e(e$1).filter(f=>f.verdict&&f.agent),i=b$2(e$1);if(r.length===0)return {sessionEntries:i.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:n,details:[]};let s=new Map;for(let f of r){let y=f.agent;s.has(y)||s.set(y,[]),s.get(y).push(f);}let a=i.filter(f=>f.type==="agent-contribution"),c=new Map;for(let f of a)f.agent&&(c.has(f.agent)||c.set(f.agent,[]),c.get(f.agent).push(f));let u=[],d={},l=0;for(let[f,y]of s){d[f]=0;let D=y.filter(h=>h.verdict==="accepted").length;y.filter(h=>h.verdict==="dismissed").length;y.filter(h=>h.verdict==="revised").length;let H=y.length,zt=H>0?D/H:0;for(let h of y){let B=$e[h.verdict];if(!B)continue;let Gt=c.get(f)?.shift(),st=Pe(h,Gt,{acceptRate:zt,total:H,accepted:D}),Vt=h.verdict==="accepted"?.85:h.verdict==="revised"?.6:.4,Kt={agent:f,verdict:h.verdict,trigger:B,insight:st,symbols:h.symbols};if(u.push(Kt),n)d[f]++,l++;else try{V(f,{trigger:B,insight:st,confidence_before:h.verdict==="accepted"?.7:.8,confidence_after:Vt,project:o,transferable:h.verdict==="dismissed",tags:["postflight",`verdict:${h.verdict}`,...(h.symbols||[]).map(Xt=>`symbol:${Xt}`)]}),d[f]++,l++;}catch{}}}let m={},g=0;if(!n)for(let f of s.keys())try{let y=ot(e$1,f);y.promoted>0&&(m[f]=y.promoted,g+=y.promoted);}catch{}return !n&&r.length>0&&f$1(e$1,r.map(f=>f.nominationId).filter(Boolean)),{sessionEntries:i.length,agentsProcessed:Array.from(s.keys()),journalsWritten:l,journalsByAgent:d,promoted:g,promotedByAgent:m,dryRun:n,details:u}}function Pe(e,t,n){let o=e.symbols?.length?` (symbols: ${e.symbols.join(", ")})`:"",r=e.reason?` Reason: ${e.reason}.`:"";switch(e.verdict){case "accepted":return `Contribution accepted by user${o}.${r}`+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(n.acceptRate*100).toFixed(0)}% (${n.accepted}/${n.total}).`;case "dismissed":return `Contribution dismissed by user${o}.${r}`+(t?.contribution?` Rejected contribution: "${t.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(n.acceptRate*100).toFixed(0)}% (${n.accepted}/${n.total}).`;case "revised":return `Contribution revised by user${o}.${r}`+(e.revisionDelta?` Delta: "${e.revisionDelta.slice(0,120)}".`:"")+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(n.acceptRate*100).toFixed(0)}% (${n.accepted}/${n.total}).`;default:return `Unknown verdict "${e.verdict}"${o}.${r}`}}export{Ye as getAmbientToolsList,Qe as handleAmbientTool,Te as runPostflightLearning};
@@ -1,29 +0,0 @@
1
- #!/usr/bin/env node
2
- import {c,b as b$1}from'./chunk-3KVVC4WV.js';import {z as z$1,i,c as c$1,f,j}from'./chunk-KAFQA7HV.js';import {g as g$1,f as f$1}from'./chunk-QGZRM6ZB.js';import {h,g as g$2}from'./chunk-K7X3Z3GL.js';import {b,a,d as d$1}from'./chunk-5TAVYPOV.js';import*as d from'fs';import*as g from'path';import*as W from'js-yaml';import*as T from'os';function Y(e){return g.join(e,G,at)}function ct(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${e}-${t}`}function E(e,t){let n={id:ct(),timestamp:new Date().toISOString(),...t};_.push(n),_.length>v&&(_=_.slice(-v));try{let r=g.join(e,G);d.mkdirSync(r,{recursive:!0});let o=Y(e);d.appendFileSync(o,JSON.stringify(n)+`
3
- `,"utf8"),lt(o);}catch{}return n}function lt(e){try{if(d.statSync(e).size>512*1024){let r=d.readFileSync(e,"utf8").trim().split(`
4
- `);if(r.length>v){let o=r.slice(-v);d.writeFileSync(e,o.join(`
5
- `)+`
6
- `,"utf8");}}}catch{}}function $t(e,t){let n=ft(e);return t?.type&&(n=n.filter(r=>r.type===t.type)),t?.source&&(n=n.filter(r=>r.source===t.source)),t?.symbol&&(n=n.filter(r=>r.symbols?.includes(t.symbol))),t?.agent&&(n=n.filter(r=>r.agent===t.agent)),t?.since&&(n=n.filter(r=>r.timestamp>=t.since)),n.sort((r,o)=>o.timestamp.localeCompare(r.timestamp)),t?.limit&&(n=n.slice(0,t.limit)),n}function ft(e){let t=Y(e);if(!d.existsSync(t))return [..._];try{return d.readFileSync(t,"utf8").trim().split(`
7
- `).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return [..._]}}function H(e,t,n){let r=0,o=0,i=0,a=0;if(n.symbols?.length&&e.symbols?.length)for(let l of n.symbols)for(let s of e.symbols)B(l,s)&&(r=Math.max(r,1));if(n.paths?.length&&e.path){for(let l of n.paths)if(B(l,e.path)){o=1;break}}if(n.concepts?.length){let l=[e.context||"",...e.keywords||[],e.type||""].join(" ").toLowerCase(),s=0;for(let m of n.concepts)m&&l.includes(m.toLowerCase())&&s++;n.concepts.length>0&&(i=s/n.concepts.length);}if(n.signals?.length){for(let l of n.signals)if(l.type===e.type){a=1;break}}let u=[r,o,i,a].sort((l,s)=>s-l),c=u[0]*.5+u[1]*.2+u[2]*.15+u[3]*.15,f=n.threshold??.6;return {agentId:t,score:c,breakdown:{symbolMatch:r,pathMatch:o,conceptMatch:i,signalMatch:a},shouldNominate:c>=f,quietReason:c<f?"below-threshold":void 0}}function B(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var G,at,v,_,z=b(()=>{G=".paradigm/events",at="stream.jsonl",v=1e3,_=[];});function O(e){let t=g.join(e,dt);if(!d.existsSync(t))return {...b$1};try{let n=d.readFileSync(t,"utf8"),r=W.load(n);return ut(b$1,r)}catch{return {...b$1}}}function ut(e,t){let n={...e};if(t.version&&(n.version=t.version),t.default_ring&&(n.default_ring=t.default_ring),t.observation&&(n.observation={allow:t.observation.allow||e.observation?.allow,deny:[...e.observation?.deny||[],...t.observation.deny||[]].filter((r,o,i)=>i.indexOf(r)===o)}),t.streams){n.streams={...e.streams};for(let r of ["work_log","learning_journal","team_decisions"])t.streams[r]&&(n.streams[r]={...e.streams?.[r],...t.streams[r],deny_content:[...e.streams?.[r]?.deny_content||[],...t.streams[r]?.deny_content||[]].filter((o,i,a)=>a.indexOf(o)===i)});}return t.upstream&&(n.upstream={...e.upstream,...t.upstream}),t.network&&(n.network={...e.network,...t.network}),t.agent_overrides&&(n.agent_overrides={...e.agent_overrides,...t.agent_overrides}),t.deployment&&(n.deployment={...e.deployment,...t.deployment}),n}function C(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(o=>R(o,t))||e.observation?.deny?.some(r=>R(r,t))?false:e.observation?.allow?.length?e.observation.allow.some(r=>R(r,t)):true}function Ct(e,t,n){let r=t.streams?.[n];if(!r)return {filtered:e,redacted:[]};let o=[],i=e;if(r.redaction)for(let a of r.redaction)try{let u=new RegExp(a.pattern,"gi"),c=i.match(u);c&&(o.push(...c),i=i.replace(u,a.replacement||"[REDACTED]"));}catch{}return {filtered:i,redacted:o}}function R(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var dt,X=b(()=>{c();dt=".paradigm/data-policy.yaml";});function wt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function _t(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${e}-${t}`}function Q(e,t){let n=i(e),r=O(e),o=[];for(let f of n){if(!f.attention||!c$1(f.id,e)||t.path&&!C(r,t.path,f.id))continue;let l=H(t,f.id,f.attention);l.shouldNominate&&o.push({profile:f,score:l});}if(o.length===0)return {nominations:[],debates:[]};let i$1=P(e,{since:new Date(Date.now()-3e4).toISOString()}),a=o.filter(({profile:f})=>!i$1.find(s=>s.agent===f.id&&s.brief===K(f,t,{...o.find(m=>m.profile.id===f.id).score})));if(a.length===0)return {nominations:[],debates:[]};let u=a.map(({profile:f,score:l})=>{let s=Et(t,l),m=Nt(f,t);return {id:wt(),agent:f.id,relevance:l.score,urgency:s,type:m,brief:K(f,t,l),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});xt(e,u);let c=kt(e,u);return c.length>0&&vt(e,c),{nominations:u,debates:c}}function Et(e,t){return e.severity==="critical"?"critical":e.severity==="error"||e.type==="compliance-violation"||e.type==="error-encountered"?"high":e.type==="gate-added"||e.type==="route-created"||t.score>=.9?"medium":"low"}function Nt(e,t){let n=e.collaboration?.stance;return t.type==="compliance-violation"||t.type==="error-encountered"?"warning":t.type==="gate-added"||t.type==="route-created"?"observation":n==="advisory"||n==="lead"?"suggestion":"observation"}function K(e,t,n){let r=e.role||e.id;switch(t.type){case "gate-checked":return `${r}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${r}: ${t.path||"File"} modified \u2014 review for ${e.id==="security"?"security implications":e.id==="tester"?"test coverage":e.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${r}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${r}: New route ${t.symbols?.join(", ")||""} \u2014 ${e.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${r}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${e.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${r}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${r}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${r}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let o=n.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:n.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${r}: ${o}`}}}function kt(e,t){if(t.length<2)return [];let n=[],r=new Map;for(let o of t)for(let i of o.triggered_by){let a=r.get(i)||[];a.push(o),r.set(i,a);}for(let[o,i]of r){if(i.length<2||new Set(i.map(f=>f.agent)).size<2)continue;let u=new Set(i.map(f=>f.type)),c=u.size>1&&u.has("warning")&&u.has("suggestion");n.push({id:_t(),topic:`Multiple agents responded to event ${o}`,nominations:i.map(f=>f.id),type:c?"conflicting":"complementary",overlap_events:[o]});}return n}function M(e){return g.join(e,S,mt)}function I(e){return g.join(e,S,gt)}function xt(e,t){try{let n=g.join(e,S);d.mkdirSync(n,{recursive:!0});let r=M(e),o=t.map(a=>JSON.stringify(a)).join(`
8
- `)+`
9
- `;d.appendFileSync(r,o,"utf8"),Z(r,pt);let{nominationTtlDays:i}=A(e);tt(r,i*24*60*60*1e3);}catch{}}function vt(e,t){try{let n=g.join(e,S);d.mkdirSync(n,{recursive:!0});let r=I(e),o=t.map(a=>JSON.stringify(a)).join(`
10
- `)+`
11
- `;d.appendFileSync(r,o,"utf8"),Z(r,ht);let{debateTtlDays:i}=A(e);tt(r,i*24*60*60*1e3);}catch{}}function Z(e,t){try{let r=d.readFileSync(e,"utf8").trim().split(`
12
- `).filter(o=>o.trim());if(r.length>t){let o=r.slice(-t);d.writeFileSync(e,o.join(`
13
- `)+`
14
- `,"utf8");}}catch{}}function A(e){let t={nominationTtlDays:yt,debateTtlDays:bt};try{let n=g.join(e,".paradigm","config.yaml");if(!d.existsSync(n))return t;let r=a("js-yaml"),o=d.readFileSync(n,"utf8"),a$1=r.load(o)?.ambient;return a$1?{nominationTtlDays:typeof a$1["nomination-ttl-days"]=="number"?a$1["nomination-ttl-days"]:t.nominationTtlDays,debateTtlDays:typeof a$1["debate-ttl-days"]=="number"?a$1["debate-ttl-days"]:t.debateTtlDays}:t}catch{return t}}function tt(e,t){try{if(!d.existsSync(e))return;let r=d.readFileSync(e,"utf8").trim().split(`
15
- `).filter(a=>a.trim());if(r.length<=St)return;let o=Date.now()-t,i=r.filter(a=>{try{let u=JSON.parse(a);return (u.timestamp?new Date(u.timestamp).getTime():Date.now())>=o}catch{return !0}});i.length<r.length&&d.writeFileSync(e,i.join(`
16
- `)+`
17
- `,"utf8");}catch{}}function P(e,t){let n=M(e);if(!d.existsSync(n))return [];try{let o=d.readFileSync(n,"utf8").trim().split(`
18
- `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null);return t?.agent&&(o=o.filter(i=>i.agent===t.agent)),t?.urgency&&(o=o.filter(i=>i.urgency===t.urgency)),t?.surfaced!==void 0&&(o=o.filter(i=>i.surfaced===t.surfaced)),t?.pending_only&&(o=o.filter(i=>!i.engaged)),t?.since&&(o=o.filter(i=>i.timestamp>=t.since)),o.sort((i,a)=>a.timestamp.localeCompare(i.timestamp)),t?.limit&&(o=o.slice(0,t.limit)),o}catch{return []}}function Ut(e){let t=I(e);if(!d.existsSync(t))return [];try{return d.readFileSync(t,"utf8").trim().split(`
19
- `).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function qt(e,t,n,r){let o=M(e);if(!d.existsSync(o))return false;try{let a=d.readFileSync(o,"utf8").trim().split(`
20
- `),u=!1,c=a.map(f=>{try{let l=JSON.parse(f);return l.id===t?(l.engaged=!0,l.response=n,r&&(l.reason=r),u=!0,JSON.stringify(l)):f}catch{return f}});if(u&&(d.writeFileSync(o,c.join(`
21
- `)+`
22
- `,"utf8"),n==="accepted"||n==="dismissed")){let f=JSON.parse(a.find(s=>{try{return JSON.parse(s).id===t}catch{return !1}}));i(e).find(s=>s.id===f.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&E(e,{type:"work-completed",source:"agent-action",agent:f.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return u}catch{return false}}function Bt(e,t,n,r){let o=I(e);if(!d.existsSync(o))return false;try{let a=d.readFileSync(o,"utf8").trim().split(`
23
- `),u=!1,c=a.map(f=>{try{let l=JSON.parse(f);if(l.id===t){l.resolution={chosen:n,reason:r,resolved_by:"human",resolved_at:new Date().toISOString()},u=!0;let s=l.nominations.filter(m=>m!==n);for(let m of s){let p=P(e).find(h=>h.id===m);p&&E(e,{type:"work-completed",source:"agent-action",agent:p.agent,context:`Debate ${t} resolved \u2014 nomination ${m} not chosen`,data:{debate_id:t,chosen:n,reason:r}});}return JSON.stringify(l)}return f}catch{return f}});return u&&d.writeFileSync(o,c.join(`
24
- `)+`
25
- `,"utf8"),u}catch{return false}}function Gt(e){let t=g.join(e,S,".last-processed"),n="";try{d.existsSync(t)&&(n=d.readFileSync(t,"utf8").trim());}catch{}let r=g.join(e,S,"stream.jsonl");if(!d.existsSync(r))return {processed:0,nominations:[]};let o=[];try{o=d.readFileSync(r,"utf8").trim().split(`
26
- `).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(n){let l=o.findIndex(s=>s.id===n);l>=0&&(i=l+1);}let a=o.slice(i);if(a.length===0)return {processed:0,nominations:[]};let u=[],c=a.slice(0,50);for(let l of c){let{nominations:s}=Q(e,l);u.push(...s);}let f=c[c.length-1];try{d.mkdirSync(g.join(e,S),{recursive:!0}),d.writeFileSync(t,f.id,"utf8");}catch{}return {processed:c.length,nominations:u}}function Yt(e,t,n){let r=O(e);if(t.path&&!C(r,t.path))return {event:E(e,t),nominations:[],debates:[]};let o=E(e,t);if(n?.skipNominations)return {event:o,nominations:[],debates:[]};let{nominations:i,debates:a}=Q(e,o);return i.length>0&&Tt(e,i),{event:o,nominations:i,debates:a}}function Ht(e,t){let n=f(e,t);if(!n?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let r=n.attention.threshold??.6,{nominationTtlDays:o}=A(e),i=o*24*60*60*1e3,c=P(e,{agent:t}).filter(b=>b.engaged||Date.now()-new Date(b.timestamp).getTime()<i).filter(b=>b.engaged);if(c.length<5)return {adjusted:false,oldThreshold:r,newThreshold:r,reason:`Insufficient data (${c.length}/5 engaged nominations)`};let f$1=c.filter(b=>b.response==="accepted").length,l=c.filter(b=>b.response==="dismissed").length,s=f$1/c.length,m=l/c.length,p=r,h="No adjustment needed";if(m>.6?(p=Math.min(.95,r+.05),h=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):s>.8&&(p=Math.max(.2,r-.05),h=`High accept rate (${(s*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),p===r)return {adjusted:false,oldThreshold:r,newThreshold:p,reason:h};n.attention.threshold=p;let w=g.join(e,".paradigm/agents",`${t}.agent`),N=d.existsSync(w)?"project":"global";return j(t,n,N,e),E(e,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${r.toFixed(2)} \u2192 ${p.toFixed(2)} (${h})`,data:{old_threshold:r,new_threshold:p,accept_rate:s,dismiss_rate:m}}),{adjusted:true,oldThreshold:r,newThreshold:p,reason:h}}function jt(e,t){let{nominationTtlDays:n}=A(e),r=n*24*60*60*1e3,i=P(e,{agent:t}).filter(s=>s.engaged||Date.now()-new Date(s.timestamp).getTime()<r),a=i.filter(s=>s.response==="accepted").length,u=i.filter(s=>s.response==="dismissed").length,c=i.filter(s=>s.response==="deferred").length,f=i.filter(s=>!s.engaged).length,l=a+u+c;return {total:i.length,accepted:a,dismissed:u,deferred:c,pending:f,acceptRate:l>0?a/l:0}}function zt(e){let n=i(e).filter(s=>c$1(s.id,e)).map(s=>{let m=jt(e,s.id),p=0;try{let h=g.join(T.homedir(),".paradigm","notebooks",s.id);d.existsSync(h)&&(p=d.readdirSync(h).filter(w=>w.endsWith(".yaml")).length);}catch{}return {id:s.id,acceptRate:m.acceptRate,threshold:s.attention?.threshold??.5,expertiseCount:(s.expertise||[]).length,notebookCount:p,transferableCount:(s.transferable||[]).length,totalNominations:m.total}}),r=n.length||1,o=n.reduce((s,m)=>s+m.acceptRate,0)/r,i$1=n.reduce((s,m)=>s+m.threshold,0)/r,a=n.reduce((s,m)=>s+m.expertiseCount,0),u=n.reduce((s,m)=>s+m.notebookCount,0),c=n.reduce((s,m)=>s+m.transferableCount,0),f=n.reduce((s,m)=>s+m.totalNominations,0),l;return f<10?l="cold-start":o<.5?l="accumulating":o<.7?l="calibrating":l="mature",{agents:n,aggregate:{avgAcceptRate:o,avgThreshold:i$1,totalExpertise:a,totalNotebooks:u,totalTransferable:c},healthStatus:l}}function Tt(e,t){if(t.length===0)return;let n=g.join(T.homedir(),".paradigm","score","outbox");if(d.existsSync(n))try{let r=g.join(n,`nom-${Date.now()}.json`),o={type:"nomination_forward",nominations:t.map(i=>({...i})),origin:At(e),timestamp:new Date().toISOString()};d.writeFileSync(r,JSON.stringify(o),"utf8");}catch{}}function At(e){try{let t=g.join(e,".paradigm","config.yaml");if(d.existsSync(t)){let r=d.readFileSync(t,"utf8").match(/project:\s*(.+)/);if(r)return r[1].trim()}}catch{}return g.basename(e)}function Vt(e,t){let n,r;try{let c=(g$1(),d$1(f$1)),f=(h(),d$1(g$2));n=c.loadJournalEntries,r=f.addNotebookEntry;}catch{return {promoted:0,entries:[]}}let o=n(t,{trigger:"pattern_discovered",limit:100}),i=n(t,{trigger:"human_feedback",limit:100}),a=[...o,...i],u=[];for(let c of a)if(!c.promoted_to_notebook&&!((c.confidence_after??0)<.8))try{let{entry:f}=r(t,{context:c.pattern?.applies_when||c.insight.slice(0,80),snippet:c.pattern?.correct_approach||c.insight,concepts:c.tags||[c.pattern?.id||"learned-pattern"],provenance:{source:"lore",loreEntryId:c.id,createdBy:t}},"global",e);u.push({journalId:c.id,notebookId:f.id});try{let l=g.join(T.homedir(),".paradigm","agents",t,"journal");if(d.existsSync(l)){let s=d.readdirSync(l).filter(m=>m.endsWith(".yaml"));for(let m of s){let p=g.join(l,m),h=d.readFileSync(p,"utf8");if(h.includes(c.id)){let w=h.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${f.id}"`);if(w===h){let N=h.trimEnd().split(`
27
- `);N.push(`promoted_to_notebook: "${f.id}"`),d.writeFileSync(p,N.join(`
28
- `)+`
29
- `,"utf8");}else d.writeFileSync(p,w,"utf8");break}}}}catch{}}catch{}return {promoted:u.length,entries:u}}function Wt(e){let t=g.join(e,Pt),n={default_min_urgency:"low",enable_debates:true};if(!d.existsSync(t))return n;try{let r=a("js-yaml"),o=d.readFileSync(t,"utf8"),i=r.load(o);return {...n,...i}}catch{return n}}function Xt(e,t){let n={critical:0,high:1,medium:2,low:3},r=n[t.default_min_urgency||"low"]??3;return e.filter(o=>{let i=n[o.urgency]??3;if(t.preferences){let a=t.preferences.find(u=>u.agent===o.agent);if(a){if(a.always_show)return true;if(a.mute_unless?.length&&!a.mute_unless.some(c=>o.urgency===c||o.type===c))return false;if(a.min_urgency){let u=n[a.min_urgency]??3;return i<=u}}}return i<=r})}var S,mt,gt,pt,ht,yt,bt,St,Pt,Dt=b(()=>{z();X();z$1();S=".paradigm/events",mt="nominations.jsonl",gt="debates.jsonl",pt=500,ht=200,yt=7,bt=14,St=100;Pt=".paradigm/surfacing.yaml";});export{$t as a,z as b,O as c,Ct as d,X as e,Q as f,kt as g,xt as h,P as i,Ut as j,qt as k,Bt as l,Gt as m,Yt as n,Ht as o,jt as p,zt as q,Tt as r,Vt as s,Wt as t,Xt as u,Dt as v};
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- import {b as b$1,a as a$1}from'./chunk-EK4ZRIFJ.js';import {q as q$1,p}from'./chunk-LAYBUKMB.js';import {d}from'./chunk-5TAVYPOV.js';import*as r from'fs';import*as a from'path';import*as x from'os';import*as T from'crypto';import*as h from'js-yaml';function w(){let n=a.join(x.homedir(),".paradigm");return r.existsSync(n)||r.mkdirSync(n,{recursive:true}),n}function M(n){let s=a.resolve(n);return T.createHash("sha256").update(s).digest("hex").slice(0,12)}function f(n){let s=M(n),e=a.join(w(),"sessions",s);r.existsSync(e)||r.mkdirSync(e,{recursive:true});let t=a.join(e,"pending-handoffs");return r.existsSync(t)||r.mkdirSync(t,{recursive:true}),e}function S(n){let s=f(n),e=a.join(s,"_project-meta.json"),o={name:a.basename(a.resolve(n)),path:a.resolve(n),lastSeen:new Date().toISOString()};r.writeFileSync(e,JSON.stringify(o,null,2));}function O(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s.id}.json`);r.writeFileSync(t,JSON.stringify(s,null,2));}function A(n){let s=f(n),e=a.join(s,"pending-handoffs");if(!r.existsSync(e))return [];let t=[];try{let o=r.readdirSync(e);for(let l of o)if(l.endsWith(".json"))try{let u=r.readFileSync(a.join(e,l),"utf8"),m=JSON.parse(u);m.status==="pending"&&t.push(m);}catch{}}catch{}return t.sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime()),t}function W(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s}.json`);if(r.existsSync(t))try{let o=r.readFileSync(t,"utf8"),l=JSON.parse(o);l.status="delivered",r.writeFileSync(t,JSON.stringify(l,null,2));}catch{}}function y(){let n=a.join(w(),"wisdom");return r.existsSync(n)||r.mkdirSync(n,{recursive:true}),n}function H(){let n=a.join(y(),"antipatterns.yaml");if(!r.existsSync(n))return [];try{let s=r.readFileSync(n,"utf8");return h.load(s)?.antipatterns||[]}catch{return []}}function L(){let n=a.join(y(),"decisions");if(!r.existsSync(n))return [];let s=[];try{let e=r.readdirSync(n);for(let t of e)if(!(!t.endsWith(".yaml")&&!t.endsWith(".yml")))try{let o=r.readFileSync(a.join(n,t),"utf8"),l=h.load(o);s.push(l);}catch{}}catch{}return s.sort((e,t)=>e.id.localeCompare(t.id)),s}function _(){let n=a.join(y(),"preferences.yaml");if(!r.existsSync(n))return null;try{let s=r.readFileSync(n,"utf8");return h.load(s)}catch{return null}}function J(n){let s=a.join(y(),"antipatterns.yaml"),e={version:"1.0",antipatterns:[]};if(r.existsSync(s))try{let t=r.readFileSync(s,"utf8");e=h.load(t),e.antipatterns||(e.antipatterns=[]);}catch{}e.antipatterns.push({...n,added:new Date().toISOString()}),r.writeFileSync(s,h.dump(e,{lineWidth:-1}));}function U(n){let s=a.join(y(),"decisions");r.existsSync(s)||r.mkdirSync(s,{recursive:true});let e=n.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),t=`${n.id}-${e}.yaml`,o=a.join(s,t);r.writeFileSync(o,h.dump(n,{lineWidth:-1}));}b$1();var k={"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"}},j=50,P=".paradigm/session-breadcrumbs.json",I=".paradigm/session-checkpoint.json",E=10080*60*1e3,C=class{session;rootDir=null;_recovered=false;lastLoreEntryId=null;constructor(){this.session=this.createNewSession();}setRootDir(s){this.rootDir=s;try{let{clearSessionWorkLog:e}=(q$1(),d(p));e(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,e,t={}){this.session.breadcrumbs.push({timestamp:Date.now(),action:s,tool:t.tool,symbol:t.symbol,summary:e}),this.session.breadcrumbs.length>j&&(this.session.breadcrumbs=this.session.breadcrumbs.slice(-j)),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()},e;try{e=JSON.stringify(s,null,2);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: JSON.stringify failed",{error:t.message});return}try{let t=a.join(this.rootDir,P),o=a.dirname(t);r.existsSync(o)||r.mkdirSync(o,{recursive:!0}),r.writeFileSync(t,e);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: local write failed",{error:t.message});}try{let t=f(this.rootDir);r.writeFileSync(a.join(t,"breadcrumbs.json"),e),S(this.rootDir);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: global write failed",{error:t.message});}}loadPreviousSession(){if(!this.rootDir)return null;try{let s=f(this.rootDir),e=a.join(s,"breadcrumbs.json");if(r.existsSync(e)){let t=r.readFileSync(e,"utf8");return JSON.parse(t)}}catch{}try{let s=a.join(this.rootDir,P);if(!r.existsSync(s))return null;let e=r.readFileSync(s,"utf8");return JSON.parse(e)}catch{return null}}saveCheckpoint(s){let e={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)},t=this.persistCheckpoint(e);return {checkpoint:e,persisted:t}}loadCheckpoint(){if(!this.rootDir)return null;let s=null;try{let e=f(this.rootDir),t=a.join(e,"checkpoint.json");if(r.existsSync(t)){let o=r.readFileSync(t,"utf8");s=JSON.parse(o);}}catch{}if(!s)try{let e=a.join(this.rootDir,I);if(r.existsSync(e)){let t=r.readFileSync(e,"utf8");s=JSON.parse(t);}}catch{}if(s&&Date.now()-s.timestamp>E)return null;if(s)for(let e of ["modifiedFiles","symbolsTouched","decisions"]){let t=s[e];if(typeof t=="string")try{s[e]=JSON.parse(t);}catch{s[e]=[];}}return s}persistCheckpoint(s){let e={local:false,global:false};if(!this.rootDir)return a$1.component("#session-tracker").warn("persistCheckpoint: rootDir not set, skipping write"),e;let t;try{t=JSON.stringify(s,null,2);}catch(o){return a$1.component("#session-tracker").error("persistCheckpoint: JSON.stringify failed",{error:o.message}),e}try{let o=a.join(this.rootDir,I),l=a.dirname(o);r.existsSync(l)||r.mkdirSync(l,{recursive:!0}),r.writeFileSync(o,t),e.local=!0;}catch(o){a$1.component("#session-tracker").error("persistCheckpoint: local write failed",{error:o.message});}try{let o=f(this.rootDir);r.writeFileSync(a.join(o,"checkpoint.json"),t),S(this.rootDir),e.global=!0;}catch(o){a$1.component("#session-tracker").error("persistCheckpoint: global write failed",{error:o.message});}return e}setLastLoreEntryId(s){this.lastLoreEntryId=s;}getLastLoreEntryId(){return this.lastLoreEntryId}hasRecoveredThisSession(){return this._recovered}markRecovered(){this._recovered=true;}extractSymbolsFromBreadcrumbs(){let s=new Set;for(let e of this.session.breadcrumbs)e.symbol&&s.add(e.symbol);return Array.from(s)}extractFilesFromBreadcrumbs(){let s=new Set;for(let e of this.session.breadcrumbs){let t=e.summary.match(/\b[\w./]+\.(ts|js|tsx|jsx|py|go|rs|yaml|json|md)\b/g);if(t)for(let o of t)s.add(o);}return Array.from(s)}estimateTokens(s){let e=typeof s=="number"?s:s.length;return Math.ceil(e/3.5)}calculateCost(s,e=true){let t=k[this.session.model],o=e?t.output:t.input;return s/1e6*o}setModel(s){this.session.model=s,this.recalculateTotals();}getModel(){return this.session.model}trackResourceRead(s,e){let t=this.extractResourceType(s),o=this.estimateTokens(e);this.session.resourceReads.push({timestamp:Date.now(),resourceType:t,uri:s,bytes:e,tokens:o}),this.session.lastActivity=Date.now(),this.updateTotals(e,o);}trackToolCall(s,e){let t=this.estimateTokens(e);this.session.toolCalls.push({timestamp:Date.now(),toolName:s,responseBytes:e,responseTokens:t}),this.session.lastActivity=Date.now(),this.updateTotals(e,t);}updateTotals(s,e){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+=e,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={},e=0,t=0;for(let i of this.session.resourceReads)s[i.resourceType]||(s[i.resourceType]={count:0,bytes:0,tokens:0}),s[i.resourceType].count++,s[i.resourceType].bytes+=i.bytes,s[i.resourceType].tokens+=i.tokens,e+=i.bytes,t+=i.tokens;let o={},l=0,u=0;for(let i of this.session.toolCalls)o[i.toolName]||(o[i.toolName]={count:0,bytes:0,tokens:0}),o[i.toolName].count++,o[i.toolName].bytes+=i.responseBytes,o[i.toolName].tokens+=i.responseTokens,l+=i.responseBytes,u+=i.responseTokens;let m=t+u,g=this.calculateCost(m);return {model:k[this.session.model].name,modelId:this.session.model,pricing:k[this.session.model],resources:{count:this.session.resourceReads.length,bytes:e,tokens:t,costUsd:this.calculateCost(t),byType:s},tools:{count:this.session.toolCalls.length,bytes:l,tokens:u,costUsd:this.calculateCost(u),byName:o},total:{tokens:m,costUsd:g}}}getHandoffRecommendation(s=2e5,e){let t=this.session.totals.totalTokens,o=t*4,l=e||t+o,u=Math.round(l/s*100),m,g;u>=85?(m="handoff-urgent",g="Context is nearly full. Initiate handoff immediately to preserve session continuity."):u>=70?(m="handoff-recommended",g="Context usage is high. Consider initiating handoff soon to ensure smooth transition."):u>=50?(m="consider-handoff",g="Context usage is moderate. Plan a good stopping point for potential handoff."):(m="continue",g="Context usage is healthy. Continue working.");let i=[],v=Math.round((Date.now()-this.session.startTime)/6e4),D=this.session.toolCalls.length+this.session.resourceReads.length;return D>50&&i.push(`High number of MCP interactions (${D})`),v>30&&i.push(`Session duration >30 min (${v} min)`),this.session.totals.totalBytes>5e5&&i.push(`Large data volume (${Math.round(this.session.totals.totalBytes/1024)}KB)`),{recommendation:m,message:g,usagePercent:u,signals:i}}getDurationMinutes(){return Math.round((Date.now()-this.session.startTime)/6e4)}reset(){this.session=this.createNewSession(),this._recovered=false,this.lastLoreEntryId=null;}},b=null;function X(){return b||(b=new C),b}function q(){b&&b.reset();}
3
- export{O as a,A as b,W as c,H as d,L as e,_ as f,J as g,U as h,k as i,X as j,q as k};
@@ -1,10 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a as a$1}from'./chunk-FYDRENK7.js';import {f,a}from'./chunk-HXGYVS2N.js';import {e}from'./chunk-TQOT2LBO.js';import {b,d,c}from'./chunk-EKZDFEJW.js';import*as h from'fs';import*as A from'path';import*as R from'js-yaml';import {glob}from'glob';import {EventEmitter}from'events';var H=/[#$^!~][a-zA-Z0-9_-]+/g;function V(r){let e=r.match(H)||[];return [...new Set(e)]}function G(r){let e=r.charAt(0);return {"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"}[e]||"unknown"}async function M(r,e,s,t){let o=A.join(s,".paradigm"),n=V(e),a=K(r,t),c=W(a.include||[],n),l=a.exclude||[],p=await J(s,c,l);return {systemPrompt:await Y(r,o,n),files:p,symbols:n}}function K(r,e){return e?.contextInclude||e?.contextExclude?{include:e.contextInclude,exclude:e.contextExclude}:{architect:{include:["specs/*.md",".purpose","**/.purpose","portal.yaml",".paradigm/config.yaml"],exclude:["src/**","tests/**","node_modules/**","dist/**"]},builder:{include:["src/**","tests/**","{feature}.purpose","specs/{feature}.md"],exclude:["specs/*.md","node_modules/**","dist/**"]},reviewer:{include:["src/**","specs/*.md","portal.yaml",".purpose"],exclude:["tests/**","node_modules/**","dist/**"]},tester:{include:["tests/**","health.yaml","{feature}.purpose"],exclude:["src/**","specs/**","node_modules/**","dist/**"]},security:{include:["portal.yaml","src/middleware/**","src/auth/**",".paradigm/wisdom/antipatterns.yaml"],exclude:["src/routes/**","tests/**","node_modules/**","dist/**"]}}[r.name]||{include:[".purpose","portal.yaml"],exclude:["node_modules/**","dist/**"]}}function W(r,e){let s=[];for(let t of r)if(t.includes("{feature}")||t.includes("{symbol}"))for(let o of e){let n=o.substring(1);s.push(t.replace(/\{feature\}/g,n).replace(/\{symbol\}/g,n));}else s.push(t);return s}async function J(r,e,s){let t=new Set;for(let o of e)try{let n=await glob(o,{cwd:r,ignore:s,nodir:!0,absolute:!1});for(let a of n)t.add(a);}catch{}return Array.from(t)}async function Y(r,e,s){let t=[],o=A.join(e,"config.yaml"),n=null;if(h.existsSync(o))try{n=R.load(h.readFileSync(o,"utf-8"));}catch{}if(t.push(`# ${r.name.charAt(0).toUpperCase()+r.name.slice(1)} Agent Context
3
- `),n?.project&&(t.push(`> Project: ${n.project}`),n.discipline&&n.discipline!=="auto"&&t.push(`> Discipline: ${n.discipline}`),t.push("")),n?.["agent-guidelines"]?.overview&&(t.push(`## Project Overview
4
- `),t.push(n["agent-guidelines"].overview),t.push("")),n?.["symbol-system"]){t.push(`## Symbol System
5
- `),t.push("| Symbol | Meaning | Description |"),t.push("|--------|---------|-------------|");for(let[c,l]of Object.entries(n["symbol-system"]))t.push(`| \`${c}\` | ${l.name} | ${l.description} |`);t.push("");}if(n?.conventions){let c=Z(n.conventions,r.name);if(c.length>0){t.push(`## Conventions
6
- `);for(let l of c)t.push(`- ${l}`);t.push("");}}if(s.length>0){t.push(`## Symbols in Scope
7
- `);for(let c of s){let l=G(c);t.push(`- \`${c}\` (${l})`);}t.push("");}let a=q(r.name);if(a.length>0){t.push(`## Tips for This Role
8
- `);for(let c of a)t.push(`- ${c}`);t.push("");}return t.join(`
9
- `)}function Z(r,e){let t={architect:["design","spec","document","flow","symbol","reference"],builder:["code","implement","component","logger","test"],reviewer:["review","portal","gate","check","validate"],tester:["test","verify","health","validate"],security:["portal","gate","auth","security","vulnerability"]}[e]||[];return r.filter(o=>t.some(n=>o.toLowerCase().includes(n)))}function q(r){return {architect:["Focus on design decisions, not implementation details","Use paradigm symbols to reference features and components","Document flows that span 3+ components","Hand off to builder when spec is ready"],builder:["Follow the spec from architect exactly","If spec is unclear, ask for clarification or hand back","Use the Paradigm logger, not raw console.log","Hand off to reviewer when implementation is ready"],reviewer:["Check that all ^gate requirements are met","Verify adherence to specs","Do NOT implement fixes - hand back to builder","Approve or request changes with clear feedback"],tester:["Run tests and verify health status","Check portal validations","Update health.yaml when verified","Report issues with reproduction steps"],security:["Focus on ^gate implementations","Check for OWASP top 10 vulnerabilities","Flag issues but do NOT implement fixes","Review auth flows and session handling"]}[r]||[]}var w=class extends EventEmitter{config;usage;records=[];configPath;constructor(e){super(),this.configPath=A.join(e,".paradigm","config.yaml"),this.config=this.loadConfig(),this.usage=this.initializeUsage();}checkBudget(e,s){let t=this.estimateCost(s,"sonnet");if(this.config.maxTokens){let a=this.usage.tokens.total+s;if(a>this.config.maxTokens)return {allowed:false,reason:`Global token limit exceeded: ${d(a)} > ${d(this.config.maxTokens)}`,usage:this.usage,warningLevel:"exceeded"}}if(this.config.maxCostUsd){let a=this.usage.cost+t;if(a>this.config.maxCostUsd)return {allowed:false,reason:`Cost ceiling exceeded: ${c(a)} > ${c(this.config.maxCostUsd)}`,usage:this.usage,warningLevel:"exceeded"}}let o=this.config.agentLimits?.[e];if(o){let a=this.usage.byAgent[e]||{tokens:{total:0},cost:0};if(o.maxTokens){let c=a.tokens.total+s;if(c>o.maxTokens)return {allowed:false,reason:`Agent '${e}' token limit exceeded: ${d(c)} > ${d(o.maxTokens)}`,usage:this.usage,warningLevel:"exceeded"}}if(o.maxCostUsd){let c$1=a.cost+t;if(c$1>o.maxCostUsd)return {allowed:false,reason:`Agent '${e}' cost limit exceeded: ${c(c$1)} > ${c(o.maxCostUsd)}`,usage:this.usage,warningLevel:"exceeded"}}}let n="none";return this.config.warnAtPercent&&this.config.maxTokens&&(this.usage.tokens.total+s)/this.config.maxTokens*100>=this.config.warnAtPercent&&(n="approaching"),{allowed:true,usage:this.usage,warningLevel:n}}recordUsage(e,s,t,o){let n=b(s,t);this.usage.tokens.input+=s.input,this.usage.tokens.output+=s.output,this.usage.tokens.total+=s.total,this.usage.cost+=n,this.config.maxTokens&&(this.usage.percentage=this.usage.tokens.total/this.config.maxTokens*100),this.usage.byAgent[e]||(this.usage.byAgent[e]={tokens:{input:0,output:0,total:0},cost:0}),this.usage.byAgent[e].tokens.input+=s.input,this.usage.byAgent[e].tokens.output+=s.output,this.usage.byAgent[e].tokens.total+=s.total,this.usage.byAgent[e].cost+=n;let a={timestamp:new Date().toISOString(),agent:e,model:t,tokens:s,cost:n,orchestrationId:o};this.records.push(a),this.emit("usage",{agent:e,tokens:s,cost:n,total:this.usage}),this.config.warnAtPercent&&this.usage.percentage>=this.config.warnAtPercent&&this.emit("warning",{type:"budget_approaching",percentage:this.usage.percentage,usage:this.usage});}getUsage(){return {...this.usage}}getRecords(){return [...this.records]}getRemaining(){return {tokens:this.config.maxTokens?this.config.maxTokens-this.usage.tokens.total:null,cost:this.config.maxCostUsd?this.config.maxCostUsd-this.usage.cost:null}}reset(){this.usage=this.initializeUsage(),this.records=[];}estimateCost(e,s){let t={input:Math.floor(e/2),output:Math.ceil(e/2),total:e};return b(t,s)}estimateTime(e,s){return Math.ceil(e/{opus:50,sonnet:100,haiku:200}[s])*1e3}getSummary(){let e=[];if(e.push("Budget Summary:"),e.push(` Tokens: ${d(this.usage.tokens.total)}`),e.push(` Cost: ${c(this.usage.cost)}`),this.config.maxTokens&&e.push(` Token limit: ${d(this.config.maxTokens)} (${this.usage.percentage.toFixed(1)}% used)`),this.config.maxCostUsd){let s=this.usage.cost/this.config.maxCostUsd*100;e.push(` Cost limit: ${c(this.config.maxCostUsd)} (${s.toFixed(1)}% used)`);}if(Object.keys(this.usage.byAgent).length>0){e.push(" By agent:");for(let[s,t]of Object.entries(this.usage.byAgent))e.push(` ${s}: ${d(t.tokens.total)} (${c(t.cost)})`);}return e.join(`
10
- `)}loadConfig(){let e={maxTokens:5e5,maxCostUsd:5,warnAtPercent:80};if(!h.existsSync(this.configPath))return e;try{let s=h.readFileSync(this.configPath,"utf-8"),o=R.load(s).orchestration;if(o?.budget){let n=o.budget;return {maxTokens:n.max_tokens,maxCostUsd:n.max_cost_usd,warnAtPercent:n.warn_at_percent,agentLimits:o.agent_limits}}return e}catch{return e}}initializeUsage(){return {tokens:{input:0,output:0,total:0},cost:0,percentage:0,byAgent:{}}}};var F=class{provider=null;budgetTracker=null;auditLogger=null;rootDir;constructor(e){this.rootDir=e;}async initialize(){await f(),this.provider=a(),this.budgetTracker=new w(this.rootDir),this.auditLogger=new a$1(this.rootDir);}isReady(){return this.provider!==null}getProvider(){return this.provider}async spawn(e$1,s,t={}){if(!this.provider)return {success:false,error:"Spawner not initialized",sessionId:""};let o=e(this.rootDir);if(!o)return {success:false,error:"Team not configured. Run `paradigm team init` first.",sessionId:""};let n=o.agents[e$1];if(!n)return {success:false,error:`Unknown agent: ${e$1}. Available: ${Object.keys(o.agents).join(", ")}`,sessionId:""};let a$1=t.provider||this.provider.name,c=a(a$1);if(!c)return {success:false,error:`Provider '${a$1}' not available`,sessionId:""};if(!await c.isAvailable())return {success:false,error:`Provider '${a$1}' not configured (missing API key?)`,sessionId:""};let p=this.generateSessionId(e$1),k=this.loadFacetConfig(e$1),P=await M(n,s,this.rootDir,k),y=t.model||k?.defaultModel||"sonnet",O={model:y,task:s,context:P,budget:t.budget,mcpServerPath:t.mcpServerPath,workingDirectory:t.workingDirectory||this.rootDir,checkpoints:t.checkpoints,timeout:t.timeout},S=Date.now(),B=new Date().toISOString(),i={agent:e$1,task:s,status:"success",completionVerified:false,outputs:{artifacts:[],symbols:P.symbols,decisions:[]},metrics:{tokens_used:{input:0,output:0,total:0},duration_ms:0,files_read:0,files_written:0}};try{for await(let u of c.spawn(n,O)){if(u.usage&&(i.metrics.tokens_used=u.usage),u.type==="tool_use"){if(u.toolName==="read_file")i.metrics.files_read++;else if(u.toolName==="write_file"){i.metrics.files_written++;let f=u.toolInput?.path;f&&i.outputs.artifacts.push({path:f,action:"modified"});}}if(t.checkpoints&&u.type==="tool_use"&&this.shouldPauseForCheckpoint(u,t.checkpoints)&&t.onCheckpoint&&!await t.onCheckpoint(`Agent wants to ${u.toolName}: ${JSON.stringify(u.toolInput)}`)){i.status="blocked";break}if(t.onMessage&&t.onMessage(u),u.type==="error"&&(i.status="failed"),this.budgetTracker&&u.usage&&!this.budgetTracker.checkBudget(e$1,u.usage.total).allowed){i.status="failed";break}}if(i.metrics.duration_ms=Date.now()-S,this.budgetTracker&&this.budgetTracker.recordUsage(e$1,i.metrics.tokens_used,y),i.status==="success"){let u=i.outputs.artifacts.length>0,f=i.outputs.decisions.length>0,C=!!i.handoff,T=i.metrics.files_written>0,z=e$1==="architect";(e$1==="builder"&&!T&&!C||!u&&!f&&!C&&!T)&&(i.status="partial"),i.completionVerified=!0,i.status==="partial"&&!z&&t.onMessage&&t.onMessage({type:"text",content:`[completion-check] Agent "${e$1}" downgraded from success \u2192 partial: no meaningful output detected.`,timestamp:new Date().toISOString()});}if(this.auditLogger){let u={name:e$1,model:y,started:B,completed:new Date().toISOString(),duration_ms:i.metrics.duration_ms,tokens:i.metrics.tokens_used,cost_usd:b(i.metrics.tokens_used,y),status:i.status,artifacts:i.outputs.artifacts,symbols:i.outputs.symbols};this.auditLogger.logAgentCompletion(p,u);}return {success:i.status==="success"||i.status==="partial",relay:i,sessionId:p}}catch(u){return {success:false,error:u instanceof Error?u.message:String(u),sessionId:p,relay:{...i,status:"failed",metrics:{...i.metrics,duration_ms:Date.now()-S}}}}}async spawnParallel(e){let s=e.map(({name:t,task:o,options:n})=>this.spawn(t,o,n));return Promise.all(s)}generateSessionId(e){let s=Date.now(),t=Math.random().toString(36).substring(2,8);return `${e}-${s}-${t}`}loadFacetConfig(e){let s=A.join(this.rootDir,".paradigm","facets.yaml");if(!h.existsSync(s))return {architect:{defaultModel:"opus"},security:{defaultModel:"opus"},reviewer:{defaultModel:"sonnet"},builder:{defaultModel:"haiku"},tester:{defaultModel:"haiku"}}[e];try{let t=h.readFileSync(s,"utf-8");return R.load(t)[e]}catch{return}}shouldPauseForCheckpoint(e,s){if(!s.beforeActions||e.type!=="tool_use")return false;let t={write:["write_file","edit_file"],delete:["delete_file","rm"],execute:["run_command","bash"],external_api:["mcp_call","http_request"]};for(let o of s.beforeActions){let n=t[o]||[];if(e.toolName&&n.includes(e.toolName))return true}return false}};export{V as a,F as b};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as i from'fs';import*as o from'path';import*as d from'js-yaml';var u=".paradigm/tasks",m="entries",P="index.yaml";function b(n,t){let s=o.join(n,u,m,t);if(!i.existsSync(s))return `T-${t}-001`;let e=i.readdirSync(s).filter(a=>a.startsWith("T-")&&a.endsWith(".yaml")).map(a=>{let l=a.match(/T-\d{4}-\d{2}-\d{2}-(\d+)\.yaml/);return l?parseInt(l[1],10):0}),r=e.length>0?Math.max(...e)+1:1;return `T-${t}-${String(r).padStart(3,"0")}`}var k={high:0,medium:1,low:2};function w(n,t){let s=n;return t.status&&t.status!=="all"&&(s=s.filter(e=>e.status===t.status)),t.priority&&(s=s.filter(e=>e.priority===t.priority)),t.tag&&(s=s.filter(e=>e.tags.includes(t.tag))),s.sort((e,r)=>{let a=(k[e.priority]??1)-(k[r.priority]??1);return a!==0?a:new Date(r.created).getTime()-new Date(e.created).getTime()}),t.limit&&(s=s.slice(0,t.limit)),s}async function _(n,t){let s=o.join(n,u,m);if(!i.existsSync(s))return [];let e={status:"open",limit:20,...t},r=[],a=i.readdirSync(s).filter(l=>/^\d{4}-\d{2}-\d{2}$/.test(l)).sort().reverse();for(let l of a){let f=o.join(s,l),p=i.readdirSync(f).filter(c=>c.endsWith(".yaml")).sort();for(let c of p)try{let g=i.readFileSync(o.join(f,c),"utf8"),y=d.load(g);r.push(y);}catch{}}return w(r,e)}async function v(n,t){let s=t.match(/^T-(\d{4}-\d{2}-\d{2})-/);if(s){let r=o.join(n,u,m,s[1],`${t}.yaml`);if(i.existsSync(r))try{return d.load(i.readFileSync(r,"utf8"))}catch{return null}}return (await _(n,{status:"all",limit:9999})).find(r=>r.id===t)||null}async function I(n,t){let s=new Date,e=s.toISOString().slice(0,10),r=o.join(n,u,m,e);i.mkdirSync(r,{recursive:true});let a=b(n,e),l={id:a,blurb:t.blurb,priority:t.priority||"medium",status:"open",tags:t.tags||[],created:s.toISOString(),session_link:t.session_link,related_lore:t.related_lore};return i.writeFileSync(o.join(r,`${a}.yaml`),d.dump(l,{lineWidth:-1,noRefs:true})),await x(n),a}async function S(n,t,s){let e=await v(n,t);if(!e)return false;let r=e.created.slice(0,10),a=o.join(n,u,m,r,`${t}.yaml`);if(!i.existsSync(a))return false;let{id:l,created:f,...p}=s,c={...e,...p};return i.writeFileSync(a,d.dump(c,{lineWidth:-1,noRefs:true})),await x(n),true}async function j(n,t){return S(n,t,{status:"done",completed:new Date().toISOString()})}async function F(n,t){return S(n,t,{status:"shelved",shelved:new Date().toISOString()})}async function x(n){let t=o.join(n,u,m),s=o.join(n,u),e=0,r=0,a=0,l=0;if(i.existsSync(t)){let p=i.readdirSync(t).filter(c=>/^\d{4}-\d{2}-\d{2}$/.test(c));for(let c of p){let g=o.join(t,c),y=i.readdirSync(g).filter(h=>h.endsWith(".yaml"));for(let h of y)try{let T=d.load(i.readFileSync(o.join(g,h),"utf8"));e++,T.status==="open"?r++:T.status==="done"?a++:T.status==="shelved"&&l++;}catch{}}}let f={version:"1.0",total:e,open:r,done:a,shelved:l,last_updated:new Date().toISOString()};return i.mkdirSync(s,{recursive:true}),i.writeFileSync(o.join(s,P),d.dump(f,{lineWidth:-1,noRefs:true})),f}export{_ as a,v as b,I as c,S as d,j as e,F as f,x as g};
@@ -1,6 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as i from'fs';import*as l from'path';import*as c from'js-yaml';var f=".paradigm/university",y="content";function U(s){let t=s.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!t)return null;try{return {frontmatter:c.load(t[1]),body:t[2].trim()}}catch{return null}}function j(s,t){return `---
3
- ${c.dump(s,{lineWidth:-1,noRefs:true,sortKeys:false})}---
4
-
5
- ${t}
6
- `}function b(s){let t=l.join(s,f,"index.yaml");if(!i.existsSync(t))return null;try{return c.load(i.readFileSync(t,"utf8"))}catch{return null}}function h(s,t,e){let n=l.join(s,f,y);for(let r of ["notes","policies","quizzes","paths"]){let a=l.join(n,r,`${t}${e}`);if(i.existsSync(a))return a}return null}function F(s,t){let e=h(s,t,".md");if(!e)return null;try{let n=U(i.readFileSync(e,"utf8"));if(!n)return null;let r=n.frontmatter;return {frontmatter:{...r,tags:r.tags||[],symbols:r.symbols||[],prerequisites:r.prerequisites||[]},body:n.body}}catch{return null}}function z(s,t){let e=h(s,t,".yaml");if(!e)return null;try{let n=c.load(i.readFileSync(e,"utf8"));return n?.id?{...n,tags:n.tags||[],symbols:n.symbols||[],questions:n.questions||[]}:null}catch{return null}}function D(s,t){let e=h(s,t,".yaml");if(!e)return null;try{let n=c.load(i.readFileSync(e,"utf8"));return n?.id?n:null}catch{return null}}function w(s,t){let e=l.join(s,f,"diplomas");if(!i.existsSync(e))return [];let n=[];try{for(let r of i.readdirSync(e).filter(a=>a.endsWith(".yaml")))try{let a=c.load(i.readFileSync(l.join(e,r),"utf8"));if(!a?.id||t?.student&&a.student!==t.student||t?.type&&a.type!==t.type)continue;n.push(a);}catch{}}catch{}return n.sort((r,a)=>a.earnedAt.localeCompare(r.earnedAt))}function I(s,t,e){let n=t.type==="policy"?"policies":"notes",r=l.join(s,f,y,n);i.mkdirSync(r,{recursive:true});let a=l.join(r,`${t.id}.md`);return i.writeFileSync(a,j(t,e),"utf8"),a}function $(s,t){let e=l.join(s,f,y,"quizzes");i.mkdirSync(e,{recursive:true});let n=l.join(e,`${t.id}.yaml`);return i.writeFileSync(n,c.dump(t,{lineWidth:-1,noRefs:true}),"utf8"),n}function k(s,t){let e=l.join(s,f,"diplomas");i.mkdirSync(e,{recursive:true});let n=l.join(e,`${t.id}.yaml`);return i.writeFileSync(n,c.dump(t,{lineWidth:-1,noRefs:true}),"utf8"),n}function q(s){let t=l.join(s,f),e=l.join(t,y),n=[];for(let u of ["notes","policies"]){let o=l.join(e,u);if(i.existsSync(o))try{for(let p of i.readdirSync(o).filter(m=>m.endsWith(".md")))try{let m=i.readFileSync(l.join(o,p),"utf8"),S=U(m);if(!S)continue;let d=S.frontmatter;n.push({id:d.id||p.replace(".md",""),title:d.title||p,type:d.type||(u==="policies"?"policy":"note"),author:d.author||"unknown",created:d.created||"",updated:d.updated||"",tags:Array.isArray(d.tags)?d.tags:[],symbols:Array.isArray(d.symbols)?d.symbols:[],difficulty:d.difficulty||"beginner",file:`${y}/${u}/${p}`});}catch{}}catch{}}let r=l.join(e,"quizzes");if(i.existsSync(r))try{for(let u of i.readdirSync(r).filter(o=>o.endsWith(".yaml")))try{let o=c.load(i.readFileSync(l.join(r,u),"utf8"));if(!o?.id)continue;n.push({id:o.id,title:o.title||u,type:"quiz",author:o.author||"unknown",created:o.created||"",updated:o.updated||"",tags:o.tags||[],symbols:o.symbols||[],difficulty:o.difficulty||"beginner",file:`${y}/quizzes/${u}`});}catch{}}catch{}let a=l.join(e,"paths");if(i.existsSync(a))try{for(let u of i.readdirSync(a).filter(o=>o.endsWith(".yaml")))try{let o=c.load(i.readFileSync(l.join(a,u),"utf8"));if(!o?.id)continue;n.push({id:o.id,title:o.title||u,type:"path",author:o.author||"unknown",created:o.created||"",updated:o.updated||"",tags:o.tags||[],symbols:[],file:`${y}/paths/${u}`});}catch{}}catch{}let g=0,v=l.join(t,"diplomas");if(i.existsSync(v))try{g=i.readdirSync(v).filter(u=>u.endsWith(".yaml")).length;}catch{}let x={version:"1.0",generatedAt:new Date().toISOString(),totalContent:n.length,entries:n,diplomaCount:g};return i.mkdirSync(t,{recursive:true}),i.writeFileSync(l.join(t,"index.yaml"),c.dump(x,{lineWidth:-1,noRefs:true}),"utf8"),x}function Q(s,t){let e=b(s);if(!e)return [];let n=[...e.entries];if(t.type&&(n=n.filter(r=>r.type===t.type)),t.tag&&(n=n.filter(r=>r.tags.some(a=>a.startsWith(t.tag)))),t.difficulty&&(n=n.filter(r=>r.difficulty===t.difficulty)),t.symbol&&(n=n.filter(r=>r.symbols.includes(t.symbol))),t.section&&(n=n.filter(r=>r.section===t.section)),t.query){let r=t.query.toLowerCase();n=n.filter(a=>a.title.toLowerCase().includes(r)||a.id.toLowerCase().includes(r));}return n.slice(0,t.limit||20)}export{b as a,F as b,z as c,D as d,w as e,I as f,$ as g,k as h,q as i,Q as j};
@@ -1,14 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as e from'fs';import*as o from'path';var y=".paradigm/events/session-log.jsonl",d=".paradigm/events/session-metrics.jsonl",p=".paradigm/events/verdicts.jsonl",v=200,g=".paradigm/events/notebook-refs.jsonl";function x(i,n){try{let t=o.join(i,y),r=o.dirname(t);if(e.existsSync(r)||e.mkdirSync(r,{recursive:!0}),e.existsSync(t)&&e.readFileSync(t,"utf8").trim().split(`
3
- `).filter(a=>a.trim()).length>=v)return;let f=JSON.stringify(n)+`
4
- `;e.appendFileSync(t,f,"utf8"),n.type==="user-verdict"&&n.agent&&n.symbols?.length&&import('./agent-loader-VGBPL3TH.js').then(({loadAgentProfile:c,saveAgentProfile:s})=>{try{let a=c(i,n.agent);if(a?.expertise){let u=n.verdict==="accepted"?.03:n.verdict==="dismissed"?-.02:n.verdict==="revised"?-.01:0;if(u!==0){for(let S of n.symbols){let l=a.expertise.find(h=>h.symbol===S);l&&(l.confidence=Math.max(0,Math.min(1,l.confidence+u)),l.sessions=(l.sessions||0)+1,l.lastTouch=new Date().toISOString());}s(n.agent,a,"global");}}}catch{}}).catch(()=>{});}catch{}}function m(i){try{let n=o.join(i,y);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
5
- `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null):[]}catch{return []}}function C(i){try{let n=o.join(i,y);e.existsSync(n)&&e.writeFileSync(n,"","utf8");}catch{}}function I(i,n){try{let t=o.join(i,p),r=o.dirname(t);e.existsSync(r)||e.mkdirSync(r,{recursive:!0}),e.appendFileSync(t,JSON.stringify(n)+`
6
- `,"utf8");}catch{}}function N(i){try{let n=o.join(i,p);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
7
- `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&!t.consumed):[]}catch{return []}}function M(i,n){try{let t=o.join(i,p);if(!e.existsSync(t))return;let r=new Set(n),c=e.readFileSync(t,"utf8").trim().split(`
8
- `).filter(s=>s.trim()).map(s=>{try{let a=JSON.parse(s);return a.nominationId&&r.has(a.nominationId)?JSON.stringify({...a,consumed:!0}):s}catch{return s}});e.writeFileSync(t,c.join(`
9
- `)+`
10
- `,"utf8");}catch{}}function O(i){let n=m(i),t=new Set;for(let r of n)r.agent&&t.add(r.agent);return Array.from(t)}function k(i,n){return m(i).filter(t=>t.agent===n)}function A(i,n){let t=k(i,n),r=t.filter(s=>s.type==="agent-contribution"),f=t.filter(s=>s.type==="user-verdict"),c=[];for(let s of r)c.push({contribution:s});for(let s of f){let a=c.find(u=>!u.verdict&&u.contribution);a?a.verdict=s:c.push({verdict:s});}return c}function P(i,n){try{let t=o.join(i,d),r=o.dirname(t);e.existsSync(r)||e.mkdirSync(r,{recursive:!0});let f={timestamp:new Date().toISOString(),type:"activity",...n},c=JSON.stringify(f)+`
11
- `;e.appendFileSync(t,c,"utf8");}catch{}}function b(i){try{let n=o.join(i,d);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
12
- `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="activity"):[]}catch{return []}}function F(i){let n=b(i),t={toolCallCount:0,responsePayloadBytes:0,sessionDurationMs:0,agentBreakdown:{}};for(let r of n)if(r.toolCallCount!=null&&(t.toolCallCount+=r.toolCallCount),r.responsePayloadBytes!=null&&(t.responsePayloadBytes+=r.responsePayloadBytes),r.sessionDurationMs!=null&&(t.sessionDurationMs=Math.max(t.sessionDurationMs,r.sessionDurationMs)),r.agentId){t.agentBreakdown[r.agentId]||(t.agentBreakdown[r.agentId]={toolCalls:0,payloadBytes:0});let f=t.agentBreakdown[r.agentId];r.toolCallCount!=null&&(f.toolCalls+=r.toolCallCount),r.responsePayloadBytes!=null&&(f.payloadBytes+=r.responsePayloadBytes);}return t}function B(i){try{let n=o.join(i,d);e.existsSync(n)&&e.writeFileSync(n,"","utf8");}catch{}}function W(i,n,t,r){try{if(t.length===0)return;let f=o.join(i,g),c=o.dirname(f);e.existsSync(c)||e.mkdirSync(c,{recursive:!0});let s={timestamp:new Date().toISOString(),type:"notebook-reference",agentId:n,notebookEntryIds:t,...r?{orchestrationId:r}:{}},a=JSON.stringify(s)+`
13
- `;e.appendFileSync(f,a,"utf8");}catch{}}function E(i){try{let n=o.join(i,g);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
14
- `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="notebook-reference"):[]}catch{return []}}function j(i){return E(i).length}export{x as a,m as b,C as c,I as d,N as e,M as f,O as g,k as h,A as i,P as j,F as k,B as l,W as m,E as n,j as o};