@a-company/paradigm 5.31.0 → 5.35.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/{accept-orchestration-CLT6SAYW.js → accept-orchestration-MIRBLRUJ.js} +1 -1
  2. package/dist/agent-X6I2YWOB.js +33 -0
  3. package/dist/agent-loader-5255KNM7.js +2 -0
  4. package/dist/agent-loader-A5FMBAFJ.js +2 -0
  5. package/dist/ambient-BKX77DDQ.js +35 -0
  6. package/dist/chunk-2Q7RGCJH.js +3 -0
  7. package/dist/chunk-32RBX5YV.js +9 -0
  8. package/dist/chunk-76JPOBDH.js +29 -0
  9. package/dist/chunk-7SWEOPWF.js +2 -0
  10. package/dist/{chunk-DG236EXP.js → chunk-A7KFOJ2F.js} +1 -1
  11. package/dist/chunk-AGSUX2GJ.js +9 -0
  12. package/dist/chunk-C7ZCCKJT.js +3 -0
  13. package/dist/chunk-GE3GQALR.js +2 -0
  14. package/dist/{chunk-VPMJWJ5R.js → chunk-HPAHK4AJ.js} +1 -1
  15. package/dist/chunk-LKFBDUCV.js +11 -0
  16. package/dist/chunk-S7K7UPXL.js +3 -0
  17. package/dist/{chunk-FSOI3CCD.js → chunk-SXO7NC6A.js} +18 -4
  18. package/dist/{chunk-WESTEMIM.js → chunk-UDUHSHO4.js} +1 -1
  19. package/dist/chunk-UHQLYIRI.js +3 -0
  20. package/dist/{chunk-VNQGILQU.js → chunk-USGKKAPL.js} +4 -4
  21. package/dist/{compliance-5OYNHE5D.js → compliance-NJSBCY6F.js} +1 -1
  22. package/dist/compliance-health-JNP3P35P.js +4 -0
  23. package/dist/{diff-YM6ZV3UI.js → diff-QHQWLM3L.js} +1 -1
  24. package/dist/doctor-R4UGMR5N.js +2 -0
  25. package/dist/gap-narrator-NTXLUI7I.js +3 -0
  26. package/dist/{hooks-E7HQQ57M.js → hooks-BNWRGACA.js} +1 -1
  27. package/dist/index.js +5 -5
  28. package/dist/mcp.js +53 -52
  29. package/dist/{migrate-WT56YYAM.js → migrate-YQG2FG3J.js} +1 -1
  30. package/dist/{nomination-engine-LMSZ2CAS.js → nomination-engine-6VTQ4OVW.js} +1 -1
  31. package/dist/{orchestrate-4L3NJCV5.js → orchestrate-7CJWHLBA.js} +1 -1
  32. package/dist/{project-type-AGO6VUKF.js → project-type-EUCFKEAZ.js} +1 -1
  33. package/dist/{providers-4PXMWA7V.js → providers-TBPOE4DI.js} +1 -1
  34. package/dist/reindex-HWRA7KDI.js +2 -0
  35. package/dist/{roster-TA2GFDR7.js → roster-HV5KYUOI.js} +1 -1
  36. package/dist/scopes-commands-3V5G6NYV.js +3 -0
  37. package/dist/session-tracker-WSTRV7UP.js +2 -0
  38. package/dist/session-work-log-5UJTJJ22.js +2 -0
  39. package/dist/session-work-log-SLAPEP3M.js +2 -0
  40. package/dist/shift-EU22H7GG.js +60 -0
  41. package/dist/{spawn-UH5RENSE.js → spawn-7TCAMD6H.js} +1 -1
  42. package/dist/{symphony-ZQ5OHJTP.js → symphony-IS5TYPXY.js} +2 -2
  43. package/dist/symphony-relay-CIMRXQHI.js +3 -0
  44. package/dist/{team-MKLPUTW7.js → team-WIJVWLII.js} +1 -1
  45. package/dist/university-ui/assets/{index-CGFJczb1.js → index-CecQrfSn.js} +2 -2
  46. package/dist/university-ui/assets/{index-CGFJczb1.js.map → index-CecQrfSn.js.map} +1 -1
  47. package/dist/university-ui/index.html +1 -1
  48. package/package.json +1 -1
  49. package/dist/agent-UUTYOFTH.js +0 -33
  50. package/dist/agent-loader-CZFB5BDP.js +0 -2
  51. package/dist/agent-loader-EBERCNMO.js +0 -2
  52. package/dist/ambient-S3CXHD7P.js +0 -35
  53. package/dist/chunk-5KSNYRT7.js +0 -29
  54. package/dist/chunk-AYYS2AMB.js +0 -3
  55. package/dist/chunk-CSXVL2U7.js +0 -9
  56. package/dist/chunk-QWL3LERH.js +0 -3
  57. package/dist/chunk-SL3RZQPW.js +0 -5
  58. package/dist/chunk-TZZNHUAR.js +0 -2
  59. package/dist/chunk-U4J5J7GG.js +0 -3
  60. package/dist/chunk-VKGY42FP.js +0 -5
  61. package/dist/doctor-HMQBF2WK.js +0 -2
  62. package/dist/reindex-BSD7ZIEY.js +0 -2
  63. package/dist/session-tracker-FDFL4PZI.js +0 -2
  64. package/dist/session-work-log-5PHOUEQ6.js +0 -2
  65. package/dist/session-work-log-LWEGZ5CN.js +0 -2
  66. package/dist/shift-BRZLKOH6.js +0 -11
  67. package/dist/symphony-relay-KBHN3ZMR.js +0 -3
  68. /package/dist/{chunk-IZSBGW6E.js → chunk-HXGYVS2N.js} +0 -0
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-DG236EXP.js';import'./chunk-TYWB5IQJ.js';import'./chunk-WESTEMIM.js';import'./chunk-FYDRENK7.js';import'./chunk-IZSBGW6E.js';import'./chunk-AO7ZSRME.js';import'./chunk-SHD27BQX.js';import'./chunk-EKZDFEJW.js';import'./chunk-T6IDXUUA.js';import'./chunk-JIXHEBGK.js';import'./chunk-QT2LKB3P.js';import'./chunk-5TAVYPOV.js';import*as g from'path';import e from'chalk';async function u(n,s,r){let a=s?g.resolve(s):process.cwd();if(!n){r.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(e.red(`
2
+ import {b}from'./chunk-A7KFOJ2F.js';import'./chunk-TYWB5IQJ.js';import'./chunk-UDUHSHO4.js';import'./chunk-FYDRENK7.js';import'./chunk-HXGYVS2N.js';import'./chunk-AO7ZSRME.js';import'./chunk-SHD27BQX.js';import'./chunk-EKZDFEJW.js';import'./chunk-T6IDXUUA.js';import'./chunk-JIXHEBGK.js';import'./chunk-QT2LKB3P.js';import'./chunk-5TAVYPOV.js';import*as g from'path';import e from'chalk';async function u(n,s,r){let a=s?g.resolve(s):process.cwd();if(!n){r.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(e.red(`
3
3
  Orchestration ID required.`)),console.log(e.gray(`Usage: paradigm team accept <orchestration-id>
4
4
  `)));return}let l=new b(a),o=l.getOrchestration(n);if(!o){r.json?console.log(JSON.stringify({error:"Orchestration not found",id:n})):console.log(e.red(`
5
5
  Orchestration not found: ${n}
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env node
2
+ import {a as a$1}from'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';import*as a from'fs';import*as y from'path';import*as R from'os';import o from'chalk';import*as m from'js-yaml';var h=y.join(R.homedir(),".paradigm","agents"),S=".paradigm/agents",$=".agent",k=".paradigm/roster.yaml";function j(e){let s=y.join(e,k);if(!a.existsSync(s))return null;try{return m.load(a.readFileSync(s,"utf8"))?.active??null}catch{return null}}function F(e,s){let c=y.join(e,k),n=y.dirname(c);a.existsSync(n)||a.mkdirSync(n,{recursive:true});let r={version:"1.0",active:s.sort()};a.writeFileSync(c,m.dump(r,{lineWidth:-1,noRefs:true}),"utf8");}function C(){if(!a.existsSync(h))return [];try{return a.readdirSync(h).filter(e=>e.endsWith($)).map(e=>e.replace($,""))}catch{return []}}var E={architect:{style:"deliberate",risk:"conservative",verbosity:"detailed"},builder:{style:"rapid",risk:"balanced",verbosity:"concise"},tester:{style:"methodical",risk:"conservative",verbosity:"concise"},reviewer:{style:"deliberate",risk:"conservative",verbosity:"detailed"},security:{style:"methodical",risk:"conservative",verbosity:"detailed"}};async function _(e={}){let s=process.cwd(),c=a$1.command("agent-list").start("Listing agent profiles",{cwd:s}),n=[];if(!e.project&&a.existsSync(h))try{let i=a.readdirSync(h).filter(d=>d.endsWith($));for(let d of i)try{let f=a.readFileSync(y.join(h,d),"utf-8"),t=m.load(f);t?.id&&n.push(t);}catch{}}catch{}let r=y.join(s,S);if(!e.global&&a.existsSync(r))try{let i=a.readdirSync(r).filter(d=>d.endsWith($));for(let d of i)try{let f=a.readFileSync(y.join(r,d),"utf-8"),t=m.load(f);if(t?.id){let l=n.findIndex(g=>g.id===t.id);l>=0?n[l]=t:n.push(t);}}catch{}}catch{}if(e.json){console.log(JSON.stringify({count:n.length,agents:n.map(O)},null,2)),c.success(`Found ${n.length} agents`);return}if(console.log(o.blue(`
3
+ \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510`)),console.log(o.blue("\u2502")+o.white.bold(" paradigm agent list ")+o.blue("\u2502")),console.log(o.blue("\u2502")+o.gray(" Persistent agent identity profiles ")+o.blue("\u2502")),console.log(o.blue(`\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
4
+ `)),n.length===0){console.log(o.yellow(" No .agent profiles found.")),console.log(o.gray(` Create one: paradigm agent create <id> --global
5
+ `)),c.success("No agents found");return}for(let i of n){let f=(i.expertise||[]).sort((t,l)=>l.confidence-t.confidence).slice(0,3).map(t=>`${t.symbol} (${(t.confidence*100).toFixed(0)}%)`).join(", ")||o.gray("none yet");console.log(` ${o.white.bold(i.id)} \u2014 ${o.gray(i.role)}`),console.log(` Style: ${i.personality?.style||"?"} | Risk: ${i.personality?.risk||"?"} | Verbosity: ${i.personality?.verbosity||"?"}`),console.log(` Top expertise: ${f}`),console.log(` Projects: ${Object.keys(i.contexts||{}).join(", ")||o.gray("none")}`),console.log("");}c.success(`Listed ${n.length} agents`);}async function D(e,s={}){let c=process.cwd(),n=a$1.command("agent-show").start(`Showing agent ${e}`,{cwd:c}),r=w(c,e);if(!r){s.json?console.log(JSON.stringify({error:`Agent "${e}" not found`})):(console.log(o.red(`
6
+ Agent "${e}" not found.`)),console.log(o.gray(` Create: paradigm agent create ${e} --global
7
+ `))),n.error(`Agent ${e} not found`);return}if(s.json){console.log(JSON.stringify(r,null,2)),n.success(`Showed agent ${e}`);return}if(console.log(o.blue(`
8
+ \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510`)),console.log(o.blue("\u2502")+o.white.bold(` Agent: ${e}`.padEnd(50))+o.blue("\u2502")),console.log(o.blue(`\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
9
+ `)),console.log(` ${o.white.bold("Role:")} ${r.role}`),console.log(` ${o.white.bold("Description:")} ${r.description}`),console.log(` ${o.white.bold("Version:")} ${r.version}`),console.log(` ${o.white.bold("Created:")} ${r.created}`),console.log(` ${o.white.bold("Updated:")} ${r.updated}`),console.log(""),r.personality){let l=r.personality;console.log(` ${o.white.bold("Personality")}`),console.log(` Style: ${l.style} | Risk: ${l.risk} | Verbosity: ${l.verbosity}`),console.log("");}let i=(r.expertise||[]).sort((l,g)=>g.confidence-l.confidence);if(i.length>0){console.log(` ${o.white.bold("Expertise")} (${i.length} symbols)`),console.log(` ${"Symbol".padEnd(30)} ${"Confidence".padEnd(12)} ${"Sessions".padEnd(10)} Last Touch`),console.log(` ${"-".repeat(70)}`);for(let l of i.slice(0,20)){let g=`${(l.confidence*100).toFixed(0)}%`.padEnd(12),p=String(l.sessions).padEnd(10),u=l.lastTouch?l.lastTouch.split("T")[0]:"\u2014";console.log(` ${l.symbol.padEnd(30)} ${g} ${p} ${u}`);}i.length>20&&console.log(o.gray(` ... and ${i.length-20} more`)),console.log("");}else console.log(o.gray(" No expertise recorded. Run `paradigm agent sync` to bootstrap from lore.\n"));let d=r.transferable||[];if(d.length>0){console.log(` ${o.white.bold("Transferable Patterns")} (${d.length})`);for(let l of d)console.log(` ${l.id}: ${(l.successRate*100).toFixed(0)}% success \u2014 ${l.description}`),console.log(o.gray(` Learned in: ${l.learnedIn} | Applied in: ${l.appliedIn.join(", ")||"none"}`));console.log("");}let f=Object.entries(r.contexts||{});if(f.length>0){console.log(` ${o.white.bold("Project Contexts")} (${f.length})`);for(let[l,g]of f)console.log(` ${o.white(l)}: ${g.sessionsInProject||0} sessions, last active ${g.lastActive?.split("T")[0]||"\u2014"}`),g.defaultModel&&console.log(` Model: ${g.defaultModel}`),g.focus?.length&&console.log(` Focus: ${g.focus.join(", ")}`);console.log("");}let t=r.permissions;t&&(console.log(` ${o.white.bold("Permissions")}`),t.paths?.read?.length&&console.log(` Read: ${t.paths.read.join(", ")}`),t.paths?.write?.length&&console.log(` Write: ${t.paths.write.join(", ")}`),t.paths?.deny?.length&&console.log(` Deny: ${o.red(t.paths.deny.join(", "))}`),t.tools?.allow?.length&&console.log(` Tools allow: ${t.tools.allow.join(", ")}`),t.tools?.deny?.length&&console.log(` Tools deny: ${o.red(t.tools.deny.join(", "))}`),t.dangerous_actions?.length&&console.log(` Requires approval: ${t.dangerous_actions.join(", ")}`),console.log("")),n.success(`Showed agent ${e}`);}async function L(e,s={}){let c=process.cwd(),n=s.global?"global":"project",r=a$1.command("agent-create").start(`Creating agent ${e} (${n})`,{cwd:c}),i=n==="global"?h:y.join(c,S);a.existsSync(i)||a.mkdirSync(i,{recursive:true});let d=y.join(i,`${e}${$}`);if(a.existsSync(d)){console.log(o.yellow(`
10
+ Agent "${e}" already exists at ${d}`)),console.log(o.gray(" Use `paradigm agent show` to view.\n")),r.error("Agent already exists");return}let f=new Date().toISOString(),t=E[e]||{style:"deliberate",risk:"balanced",verbosity:"concise"},l={id:e,role:s.role||`${e.charAt(0).toUpperCase()+e.slice(1)} agent`,description:s.description||`Persistent identity for the ${e} agent role`,version:"1.0.0",personality:t,expertise:[],transferable:[],contexts:{},created:f,updated:f};if(s.denyPaths){let p=s.denyPaths.split(",").map(u=>u.trim());l.permissions={paths:{deny:p}};}let g=m.dump(l,{lineWidth:120,noRefs:true,sortKeys:false});a.writeFileSync(d,g,"utf-8"),console.log(o.green(`
11
+ \u2713 Created agent "${e}" at ${d}`)),console.log(o.gray(" Run `paradigm agent sync` to bootstrap expertise from lore.\n")),r.success(`Created agent ${e}`);}async function W(e,s={}){let c=process.cwd(),n=a$1.command("agent-sync").start(`Syncing expertise for ${e}`,{cwd:c}),r=y.join(c,".paradigm","lore","entries");if(!a.existsSync(r)){console.log(o.yellow(`
12
+ No lore directory found. Nothing to sync from.
13
+ `)),n.error("No lore found");return}let i=w(c,e);if(!i){if(s.dryRun){console.log(o.yellow(`
14
+ Agent "${e}" not found. Would create with --no-dry-run.
15
+ `)),n.success("Dry run \u2014 would create");return}let p=(a.existsSync(y.join(h,`${e}${$}`))?"global":"project")==="global"?h:y.join(c,S);a.existsSync(p)||a.mkdirSync(p,{recursive:true});let u=new Date().toISOString(),x=E[e]||{style:"deliberate",risk:"balanced",verbosity:"concise"};i={id:e,role:`${e.charAt(0).toUpperCase()+e.slice(1)} agent`,description:`Persistent identity for the ${e} agent role`,version:"1.0.0",personality:x,expertise:[],transferable:[],contexts:{},created:u,updated:u};}let d=i.expertise||[],f=0,t=new Set,l=T(r);for(let g of l)if(!(!g.symbols_touched||g.symbols_touched.length===0)){f++;for(let p of g.symbols_touched){t.add(p);let u=d.find(x=>x.symbol===p);u?(u.sessions++,u.lastTouch=g.timestamp||u.lastTouch,g.confidence!=null&&(u.confidence=.7*u.confidence+.3*g.confidence)):d.push({symbol:p,confidence:g.confidence??.5,sessions:1,lastTouch:g.timestamp||new Date().toISOString()});}}if(i.expertise=d,s.json)console.log(JSON.stringify({agentId:e,entriesProcessed:f,symbolsUpdated:t.size,dryRun:!!s.dryRun,topExpertise:d.sort((g,p)=>p.confidence-g.confidence).slice(0,10)},null,2));else if(console.log(o.blue(`
16
+ Syncing expertise for "${e}" from ${f} lore entries...`)),console.log(` ${o.green("\u2713")} ${t.size} symbols updated`),console.log(` ${o.green("\u2713")} ${f} entries processed`),d.length>0){console.log(`
17
+ Top expertise:`);for(let g of d.sort((p,u)=>u.confidence-p.confidence).slice(0,5))console.log(` ${g.symbol}: ${(g.confidence*100).toFixed(0)}% (${g.sessions} sessions)`);}if(s.dryRun)s.json||console.log(o.yellow(`
18
+ Dry run \u2014 no changes written.
19
+ `));else {i.updated=new Date().toISOString();let g=y.join(c,S,`${e}${$}`),p=y.join(h,`${e}${$}`),u=a.existsSync(g)?"project":"global",x=u==="global"?h:y.join(c,S);a.existsSync(x)||a.mkdirSync(x,{recursive:true});let A=u==="global"?p:g;a.writeFileSync(A,m.dump(i,{lineWidth:120,noRefs:true,sortKeys:false}),"utf-8"),s.json||console.log(o.green(`
20
+ \u2713 Saved to ${A}
21
+ `));}n.success(`Synced ${t.size} symbols from ${f} entries`);}async function M(e={}){let s=process.cwd(),c=a$1.command("agent-roster").start("Agent roster",{cwd:s}),n=[];if(a.existsSync(h))for(let t of a.readdirSync(h).filter(l=>l.endsWith($)))try{let l=m.load(a.readFileSync(y.join(h,t),"utf-8"));l?.id&&n.push(l);}catch{}let r=y.join(s,S);if(a.existsSync(r))for(let t of a.readdirSync(r).filter(l=>l.endsWith($)))try{let l=m.load(a.readFileSync(y.join(r,t),"utf-8"));if(l?.id){let g=n.findIndex(p=>p.id===l.id);g>=0?n[g]=l:n.push(l);}}catch{}let i=j(s),d=i?n.filter(t=>i.includes(t.id)):n,f=i?n.filter(t=>!i.includes(t.id)):[];if(e.json){console.log(JSON.stringify({active:d.map(t=>P(t,false)),benched:f.map(t=>P(t,true))},null,2)),c.success(`${d.length} active, ${f.length} benched`);return}if(console.log(o.blue(`
22
+ \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510`)),console.log(o.blue("\u2502")+o.white.bold(" Agent Roster ")+o.blue("\u2502")),console.log(o.blue(`\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
23
+ `)),d.length>0){console.log(o.green.bold(" Active"));for(let t of d)v(t);}if(f.length>0){console.log(o.gray.bold(`
24
+ Benched`));for(let t of f)v(t,true);}n.length===0?console.log(o.yellow(` No agents found.
25
+ `)):console.log(""),c.success(`${d.length} active, ${f.length} benched`);}function v(e,s=false){let c=(e.expertise||[]).sort((t,l)=>l.confidence-t.confidence),n=c[0]?`${c[0].symbol} (${(c[0].confidence*100).toFixed(0)}%)`:o.gray("\u2014"),r=s?o.gray:o.white,i=e.nickname?` (${e.nickname})`:"",d=e.attention?.threshold,f=d!=null?` | thr: ${d.toFixed(2)}`:"";console.log(` ${r.bold(e.id)}${o.gray(i)} \u2014 ${o.gray(e.role)}`),console.log(` Top: ${n} | ${c.length} symbols${f}`);}function P(e,s=false){let c=(e.expertise||[]).sort((n,r)=>r.confidence-n.confidence);return {id:e.id,role:e.role,nickname:e.nickname,benched:s,expertiseCount:c.length,topExpertise:c.slice(0,3).map(n=>({symbol:n.symbol,confidence:parseFloat(n.confidence.toFixed(2))})),threshold:e.attention?.threshold}}async function U(e){let s=process.cwd(),c=a$1.command("agent-bench").start(`Benching agent ${e}`,{cwd:s}),n=w(s,e);if(!n){console.log(o.red(`
26
+ Agent "${e}" not found.
27
+ `)),c.error("Not found");return}let r=j(s);r?r=r.filter(i=>i!==n.id):r=C().filter(i=>i!==n.id),F(s,r),console.log(o.yellow(`
28
+ Agent "${n.id}" removed from this project's roster.`)),console.log(o.gray(` Maestro will skip this agent during orchestration. Still available globally.
29
+ `)),c.success(`Benched ${n.id} (roster: ${r.length} active)`);}async function J(e){let s=process.cwd(),c=a$1.command("agent-activate").start(`Activating agent ${e}`,{cwd:s}),n=w(s,e);if(!n){console.log(o.red(`
30
+ Agent "${e}" not found.
31
+ `)),c.error("Not found");return}let r=j(s);if(r)r.includes(n.id)||r.push(n.id);else {let i=C();r=i.includes(n.id)?i:[...i,n.id];}F(s,r),console.log(o.green(`
32
+ \u25B6 Agent "${n.id}" added to this project's roster.`)),console.log(o.gray(` Maestro will include this agent in orchestration. Roster is per-project.
33
+ `)),c.success(`Activated ${n.id} (roster: ${r.length} active)`);}function w(e,s){let c=y.join(e,S,`${s}${$}`);if(a.existsSync(c))try{return m.load(a.readFileSync(c,"utf-8"))}catch{}let n=y.join(h,`${s}${$}`);if(a.existsSync(n))try{return m.load(a.readFileSync(n,"utf-8"))}catch{}return null}function O(e){return {id:e.id,role:e.role,personality:e.personality,expertiseCount:(e.expertise||[]).length,topExpertise:(e.expertise||[]).sort((s,c)=>c.confidence-s.confidence).slice(0,3).map(s=>({symbol:s.symbol,confidence:parseFloat(s.confidence.toFixed(2))})),projectContexts:Object.keys(e.contexts||{}),transferableCount:(e.transferable||[]).length}}function T(e){let s=[];try{let c=a.readdirSync(e,{withFileTypes:!0});for(let n of c){if(!n.isDirectory())continue;let r=y.join(e,n.name);try{let i=a.readdirSync(r).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml"));for(let d of i)try{let f=a.readFileSync(y.join(r,d),"utf-8"),t=m.load(f);t?.symbols_touched&&Array.isArray(t.symbols_touched)&&s.push({symbols_touched:t.symbols_touched,confidence:typeof t.confidence=="number"?t.confidence:void 0,timestamp:t.timestamp||n.name});}catch{}}catch{}}}catch{}return s}export{J as agentActivateCommand,U as agentBenchCommand,L as agentCreateCommand,_ as agentListCommand,M as agentRosterCommand,D as agentShowCommand,W as agentSyncCommand};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export{p as buildProfileEnrichment,t as checkPathPermission,u as checkToolPermission,x as computeIntegrityHash,k as createAgentProfile,a as decayedConfidence,s as determineIntegrityStatus,w as enforcePermissions,g as findAgentsByNickname,v as getPermissionConstraints,c as isAgentActive,e as listAllGlobalAgentIds,f as loadAgentProfile,i as loadAllAgentProfiles,b as loadProjectRoster,o as mergeAgentProfileWithManifest,l as queryExpertise,h as resolveAgent,r as sanitizeForPrompt,j as saveAgentProfile,d as saveProjectRoster,q as syncExpertiseFromLore,n as updateExpertiseFromAssessment,m as updateExpertiseFromLore,y as verifyIntegrity}from'./chunk-C7ZCCKJT.js';import'./chunk-5TAVYPOV.js';
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {z}from'./chunk-2Q7RGCJH.js';export{p as buildProfileEnrichment,t as checkPathPermission,u as checkToolPermission,x as computeIntegrityHash,k as createAgentProfile,a as decayedConfidence,s as determineIntegrityStatus,w as enforcePermissions,g as findAgentsByNickname,v as getPermissionConstraints,c as isAgentActive,e as listAllGlobalAgentIds,f as loadAgentProfile,i as loadAllAgentProfiles,b as loadProjectRoster,o as mergeAgentProfileWithManifest,l as queryExpertise,h as resolveAgent,r as sanitizeForPrompt,j as saveAgentProfile,d as saveProjectRoster,q as syncExpertiseFromLore,n as updateExpertiseFromAssessment,m as updateExpertiseFromLore,y as verifyIntegrity}from'./chunk-2Q7RGCJH.js';import'./chunk-5TAVYPOV.js';z();
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ import {f,p,i,c as c$1,j}from'./chunk-C7ZCCKJT.js';import {b as b$2}from'./chunk-32RBX5YV.js';import {b as b$3}from'./chunk-7SWEOPWF.js';import {c,b as b$1,d,a}from'./chunk-5TAVYPOV.js';import*as g from'fs';import*as b from'path';import*as R from'js-yaml';import*as Z from'os';var jt={};c(jt,{getJournalStats:()=>oe,loadAllJournalEntries:()=>ne,loadJournalEntries:()=>O,loadJournalEntry:()=>ee,recordJournalEntry:()=>z});function V(n){let t=process.env.HOME||process.env.USERPROFILE||"";return b.join(t,".paradigm","agents",n,"journal")}function te(){let n=new Date,t=n.toISOString().slice(0,10),e=n.toISOString().slice(11,19).replace(/:/g,""),o=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `LJ-${t}-${e}-${o}`}function z(n,t){let e=new Date,o=te(),r={id:o,agent:n,timestamp:e.toISOString(),...t},i=V(n);g.mkdirSync(i,{recursive:true});let s=b.join(i,`${o}.yaml`);return g.writeFileSync(s,R.dump(r,{lineWidth:120,noRefs:true}),"utf8"),r}function O(n,t){let e=V(n);if(!g.existsSync(e))return [];let o=[],r=g.readdirSync(e).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=g.readFileSync(b.join(e,s),"utf8"),c=R.load(a);c&&c.id&&o.push(c);}catch{}let i=o;return t?.trigger&&(i=i.filter(s=>s.trigger===t.trigger)),t?.project&&(i=i.filter(s=>s.project===t.project)),t?.transferable!==void 0&&(i=i.filter(s=>s.transferable===t.transferable)),t?.tag&&(i=i.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(i=i.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(i=i.filter(s=>s.timestamp<=t.dateTo)),i.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}function ee(n,t){let e=V(n),o=b.join(e,`${t}.yaml`);if(!g.existsSync(o))return null;let r=g.readFileSync(o,"utf8");return R.load(r)}function ne(n){let t=process.env.HOME||process.env.USERPROFILE||"",e=b.join(t,".paradigm","agents");if(!g.existsSync(e))return [];let o=[],r=g.readdirSync(e,{withFileTypes:true}).filter(i=>i.isDirectory());for(let i of r){if(n?.agent&&i.name!==n.agent)continue;let s=O(i.name,n);o.push(...s);}return o.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),n?.limit?o.slice(0,n.limit):o}function oe(n){let t=O(n),e={},o={},r=0;for(let i of t)e[i.trigger]=(e[i.trigger]||0)+1,o[i.project]=(o[i.project]||0)+1,i.transferable&&r++;return {total:t.length,byTrigger:e,byProject:o,transferableCount:r,recentInsights:t.slice(0,5).map(i=>({id:i.id,trigger:i.trigger,insight:i.insight.slice(0,200),timestamp:i.timestamp}))}}var K=b$1(()=>{});var Nt={};c(Nt,{addNotebookEntry:()=>xt,incrementApplied:()=>ae,loadNotebookEntries:()=>Dt,promoteFromLore:()=>se,searchNotebooks:()=>re});function Dt(n,t,e){let o=new Map,r=b.join(X,n);Et(r,o);let i=b.join(t,Y,n);Et(i,o);let s=Array.from(o.values());if(e?.concepts&&e.concepts.length>0){let a=new Set(e.concepts.map(c=>c.toLowerCase()));s=s.filter(c=>c.concepts.some(d=>a.has(d.toLowerCase())));}if(e?.tags&&e.tags.length>0){let a=new Set(e.tags.map(c=>c.toLowerCase()));s=s.filter(c=>c.tags.some(d=>a.has(d.toLowerCase())));}return s.sort((a,c)=>c.appliedCount-a.appliedCount)}function Et(n,t){if(g.existsSync(n))try{let e=g.readdirSync(n).filter(o=>o.startsWith(ie)&&o.endsWith(Q));for(let o of e)try{let r=g.readFileSync(b.join(n,o),"utf-8"),i=R.load(r);i?.id&&t.set(i.id,i);}catch{}}catch{}}function re(n,t,e){let o=Dt(n,e),r=t.toLowerCase();return o.filter(i=>i.context.toLowerCase().includes(r)||i.snippet.toLowerCase().includes(r)||i.concepts.some(s=>s.toLowerCase().includes(r))||i.tags.some(s=>s.toLowerCase().includes(r)))}function xt(n,t,e,o){let r=new Date().toISOString(),i=(t.concepts[0]||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),s=Date.now().toString(36),a=`nb-${i}-${s}`,c={...t,id:a,appliedCount:0,created:r,updated:r},d=e==="global"?b.join(X,n):b.join(o||process.cwd(),Y,n);g.existsSync(d)||g.mkdirSync(d,{recursive:true});let u=`${a}${Q}`,l=b.join(d,u),m=R.dump(c,{lineWidth:120,noRefs:true,sortKeys:false});return g.writeFileSync(l,m,"utf-8"),{entry:c,filePath:l}}async function se(n,t,e,o="global"){let{loadLoreEntry:r}=await import('./lore-loader-XY5MZRR2.js'),i=await r(e,t);if(!i)return null;let s=[];if(i.symbols_touched)for(let d of i.symbols_touched){let u=d.replace(/^[#$^!~]/,"").toLowerCase();s.push(u);}let a=i.summary||"";i.body&&(a+=`
3
+
4
+ `+i.body);let c={source:"lore",loreEntryId:t,originProject:b.basename(e),createdBy:n};return xt(n,{context:i.title||`Promoted from ${t}`,snippet:a,provenance:c,confidence:i.confidence??.7,concepts:s,tags:i.tags||[]},o,e)}function ae(n,t,e){let o=b.join(e,Y,n),r=b.join(X,n);for(let i of [o,r]){let s=b.join(i,`${t}${Q}`);if(g.existsSync(s))try{let a=g.readFileSync(s,"utf-8"),c=R.load(a);if(c)return c.appliedCount=(c.appliedCount||0)+1,c.updated=new Date().toISOString(),g.writeFileSync(s,R.dump(c,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var X,Y,ie,Q,$t=b$1(()=>{X=b.join(Z.homedir(),".paradigm","notebooks"),Y=".paradigm/notebooks",ie="nb-",Q=".yaml";});var pt=".paradigm/events",zt="stream.jsonl",J=1e3,$=[];function yt(n){return b.join(n,pt,zt)}function Kt(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${n}-${t}`}function M(n,t){let e={id:Kt(),timestamp:new Date().toISOString(),...t};$.push(e),$.length>J&&($=$.slice(-J));try{let o=b.join(n,pt);g.mkdirSync(o,{recursive:!0});let r=yt(n);g.appendFileSync(r,JSON.stringify(e)+`
5
+ `,"utf8"),Xt(r);}catch{}return e}function Xt(n){try{if(g.statSync(n).size>512*1024){let o=g.readFileSync(n,"utf8").trim().split(`
6
+ `);if(o.length>J){let r=o.slice(-J);g.writeFileSync(n,r.join(`
7
+ `)+`
8
+ `,"utf8");}}}catch{}}function ht(n,t){let e=Yt(n);return t?.type&&(e=e.filter(o=>o.type===t.type)),t?.source&&(e=e.filter(o=>o.source===t.source)),t?.symbol&&(e=e.filter(o=>o.symbols?.includes(t.symbol))),t?.agent&&(e=e.filter(o=>o.agent===t.agent)),t?.since&&(e=e.filter(o=>o.timestamp>=t.since)),e.sort((o,r)=>r.timestamp.localeCompare(o.timestamp)),t?.limit&&(e=e.slice(0,t.limit)),e}function Yt(n){let t=yt(n);if(!g.existsSync(t))return [...$];try{return g.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 bt(n,t,e){let o=0,r=0,i=0,s=0;if(e.symbols?.length&&n.symbols?.length)for(let u of e.symbols)for(let l of n.symbols)gt(u,l)&&(o=Math.max(o,1));if(e.paths?.length&&n.path){for(let u of e.paths)if(gt(u,n.path)){r=1;break}}if(e.concepts?.length){let u=[n.context||"",...n.keywords||[],n.type].join(" ").toLowerCase(),l=0;for(let m of e.concepts)u.includes(m.toLowerCase())&&l++;e.concepts.length>0&&(i=l/e.concepts.length);}if(e.signals?.length){for(let u of e.signals)if(u.type===n.type){s=1;break}}let a=[o,r,i,s].sort((u,l)=>l-u),c=a[0]*.5+a[1]*.2+a[2]*.15+a[3]*.15,d=e.threshold??.6;return {agentId:t,score:c,breakdown:{symbolMatch:o,pathMatch:r,conceptMatch:i,signalMatch:s},shouldNominate:c>=d,quietReason:c<d?"below-threshold":void 0}}function gt(n,t){if(n===t)return true;let e=n.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${e}$`).test(t)}catch{return false}}var Qt=".paradigm/data-policy.yaml";function _t(n){let t=b.join(n,Qt);if(!g.existsSync(t))return {...b$3};try{let e=g.readFileSync(t,"utf8"),o=R.load(e);return Zt(b$3,o)}catch{return {...b$3}}}function Zt(n,t){let e={...n};if(t.version&&(e.version=t.version),t.default_ring&&(e.default_ring=t.default_ring),t.observation&&(e.observation={allow:t.observation.allow||n.observation?.allow,deny:[...n.observation?.deny||[],...t.observation.deny||[]].filter((o,r,i)=>i.indexOf(o)===r)}),t.streams){e.streams={...n.streams};for(let o of ["work_log","learning_journal","team_decisions"])t.streams[o]&&(e.streams[o]={...n.streams?.[o],...t.streams[o],deny_content:[...n.streams?.[o]?.deny_content||[],...t.streams[o]?.deny_content||[]].filter((r,i,s)=>s.indexOf(r)===i)});}return t.upstream&&(e.upstream={...n.upstream,...t.upstream}),t.network&&(e.network={...n.network,...t.network}),t.agent_overrides&&(e.agent_overrides={...n.agent_overrides,...t.agent_overrides}),t.deployment&&(e.deployment={...n.deployment,...t.deployment}),e}function vt(n,t,e){return e&&n.agent_overrides?.[e]?.observation&&n.agent_overrides[e].observation.deny?.some(r=>G(r,t))||n.observation?.deny?.some(o=>G(o,t))?false:n.observation?.allow?.length?n.observation.allow.some(o=>G(o,t)):true}function G(n,t){if(n===t)return true;let e=n.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${e}$`).test(t)}catch{return false}}var N=".paradigm/events",ce="nominations.jsonl",le="debates.jsonl",de=500,ue=200,me=7,fe=14,ge=100;function pe(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${n}-${t}`}function ye(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${n}-${t}`}function he(n,t){let e=i(n),o=_t(n),r=[];for(let d of e){if(!d.attention||!c$1(d.id,n)||t.path&&!vt(o,t.path,d.id))continue;let u=bt(t,d.id,d.attention);u.shouldNominate&&r.push({profile:d,score:u});}if(r.length===0)return {nominations:[],debates:[]};let i$1=E(n,{since:new Date(Date.now()-3e4).toISOString()}),s=r.filter(({profile:d})=>!i$1.find(l=>l.agent===d.id&&l.brief===Tt(d,t,{...r.find(m=>m.profile.id===d.id).score})));if(s.length===0)return {nominations:[],debates:[]};let a=s.map(({profile:d,score:u})=>{let l=be(t,u),m=Se(d,t);return {id:pe(),agent:d.id,relevance:u.score,urgency:l,type:m,brief:Tt(d,t,u),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});_e(n,a);let c=we(n,a);return c.length>0&&ve(n,c),{nominations:a,debates:c}}function be(n,t){return n.severity==="critical"?"critical":n.severity==="error"||n.type==="compliance-violation"||n.type==="error-encountered"?"high":n.type==="gate-added"||n.type==="route-created"||t.score>=.9?"medium":"low"}function Se(n,t){let e=n.collaboration?.stance;return t.type==="compliance-violation"||t.type==="error-encountered"?"warning":t.type==="gate-added"||t.type==="route-created"?"observation":e==="advisory"||e==="lead"?"suggestion":"observation"}function Tt(n,t,e){let o=n.role||n.id;switch(t.type){case "gate-checked":return `${o}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${o}: ${t.path||"File"} modified \u2014 review for ${n.id==="security"?"security implications":n.id==="tester"?"test coverage":n.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${o}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${o}: New route ${t.symbols?.join(", ")||""} \u2014 ${n.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${o}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${n.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${o}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${o}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${o}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let r=e.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:e.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${o}: ${r}`}}}function we(n,t){if(t.length<2)return [];let e=[],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(d=>d.agent)).size<2)continue;let a=new Set(i.map(d=>d.type)),c=a.size>1&&a.has("warning")&&a.has("suggestion");e.push({id:ye(),topic:`Multiple agents responded to event ${r}`,nominations:i.map(d=>d.id),type:c?"conflicting":"complementary",overlap_events:[r]});}return e}function tt(n){return b.join(n,N,ce)}function et(n){return b.join(n,N,le)}function _e(n,t){try{let e=b.join(n,N);g.mkdirSync(e,{recursive:!0});let o=tt(n),r=t.map(s=>JSON.stringify(s)).join(`
10
+ `)+`
11
+ `;g.appendFileSync(o,r,"utf8"),Rt(o,de);let{nominationTtlDays:i}=H(n);Pt(o,i*24*60*60*1e3);}catch{}}function ve(n,t){try{let e=b.join(n,N);g.mkdirSync(e,{recursive:!0});let o=et(n),r=t.map(s=>JSON.stringify(s)).join(`
12
+ `)+`
13
+ `;g.appendFileSync(o,r,"utf8"),Rt(o,ue);let{debateTtlDays:i}=H(n);Pt(o,i*24*60*60*1e3);}catch{}}function Rt(n,t){try{let o=g.readFileSync(n,"utf8").trim().split(`
14
+ `).filter(r=>r.trim());if(o.length>t){let r=o.slice(-t);g.writeFileSync(n,r.join(`
15
+ `)+`
16
+ `,"utf8");}}catch{}}function H(n){let t={nominationTtlDays:me,debateTtlDays:fe};try{let e=b.join(n,".paradigm","config.yaml");if(!g.existsSync(e))return t;let o=a("js-yaml"),r=g.readFileSync(e,"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 Pt(n,t){try{if(!g.existsSync(n))return;let o=g.readFileSync(n,"utf8").trim().split(`
17
+ `).filter(s=>s.trim());if(o.length<=ge)return;let r=Date.now()-t,i=o.filter(s=>{try{let a=JSON.parse(s);return (a.timestamp?new Date(a.timestamp).getTime():Date.now())>=r}catch{return !0}});i.length<o.length&&g.writeFileSync(n,i.join(`
18
+ `)+`
19
+ `,"utf8");}catch{}}function E(n,t){let e=tt(n);if(!g.existsSync(e))return [];try{let r=g.readFileSync(e,"utf8").trim().split(`
20
+ `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null);return t?.agent&&(r=r.filter(i=>i.agent===t.agent)),t?.urgency&&(r=r.filter(i=>i.urgency===t.urgency)),t?.surfaced!==void 0&&(r=r.filter(i=>i.surfaced===t.surfaced)),t?.pending_only&&(r=r.filter(i=>!i.engaged)),t?.since&&(r=r.filter(i=>i.timestamp>=t.since)),r.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),t?.limit&&(r=r.slice(0,t.limit)),r}catch{return []}}function Ot(n){let t=et(n);if(!g.existsSync(t))return [];try{return g.readFileSync(t,"utf8").trim().split(`
21
+ `).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return []}}function At(n,t,e,o){let r=tt(n);if(!g.existsSync(r))return false;try{let s=g.readFileSync(r,"utf8").trim().split(`
22
+ `),a=!1,c=s.map(d=>{try{let u=JSON.parse(d);return u.id===t?(u.engaged=!0,u.response=e,o&&(u.reason=o),a=!0,JSON.stringify(u)):d}catch{return d}});if(a&&(g.writeFileSync(r,c.join(`
23
+ `)+`
24
+ `,"utf8"),e==="accepted"||e==="dismissed")){let d=JSON.parse(s.find(l=>{try{return JSON.parse(l).id===t}catch{return !1}}));i(n).find(l=>l.id===d.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&M(n,{type:"work-completed",source:"agent-action",agent:d.agent,context:`Nomination ${t} ${e} \u2014 feedback for learning`,data:{nomination_id:t,response:e}});}return a}catch{return false}}function Ft(n,t,e,o){let r=et(n);if(!g.existsSync(r))return false;try{let s=g.readFileSync(r,"utf8").trim().split(`
25
+ `),a=!1,c=s.map(d=>{try{let u=JSON.parse(d);if(u.id===t){u.resolution={chosen:e,reason:o,resolved_by:"human",resolved_at:new Date().toISOString()},a=!0;let l=u.nominations.filter(m=>m!==e);for(let m of l){let y=E(n).find(f=>f.id===m);y&&M(n,{type:"work-completed",source:"agent-action",agent:y.agent,context:`Debate ${t} resolved \u2014 nomination ${m} not chosen`,data:{debate_id:t,chosen:e,reason:o}});}return JSON.stringify(u)}return d}catch{return d}});return a&&g.writeFileSync(r,c.join(`
26
+ `)+`
27
+ `,"utf8"),a}catch{return false}}function It(n){let t=b.join(n,N,".last-processed"),e="";try{g.existsSync(t)&&(e=g.readFileSync(t,"utf8").trim());}catch{}let o=b.join(n,N,"stream.jsonl");if(!g.existsSync(o))return {processed:0,nominations:[]};let r=[];try{r=g.readFileSync(o,"utf8").trim().split(`
28
+ `).filter(l=>l.trim()).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(l=>l!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(e){let u=r.findIndex(l=>l.id===e);u>=0&&(i=u+1);}let s=r.slice(i);if(s.length===0)return {processed:0,nominations:[]};let a=[],c=s.slice(0,50);for(let u of c){let{nominations:l}=he(n,u);a.push(...l);}let d=c[c.length-1];try{g.mkdirSync(b.join(n,N),{recursive:!0}),g.writeFileSync(t,d.id,"utf8");}catch{}return {processed:c.length,nominations:a}}function Ct(n,t){let e=f(n,t);if(!e?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let o=e.attention.threshold??.6,{nominationTtlDays:r}=H(n),i=r*24*60*60*1e3,c=E(n,{agent:t}).filter(j=>j.engaged||Date.now()-new Date(j.timestamp).getTime()<i).filter(j=>j.engaged);if(c.length<5)return {adjusted:false,oldThreshold:o,newThreshold:o,reason:`Insufficient data (${c.length}/5 engaged nominations)`};let d=c.filter(j=>j.response==="accepted").length,u=c.filter(j=>j.response==="dismissed").length,l=d/c.length,m=u/c.length,y=o,f$1="No adjustment needed";if(m>.6?(y=Math.min(.95,o+.05),f$1=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):l>.8&&(y=Math.max(.2,o-.05),f$1=`High accept rate (${(l*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),y===o)return {adjusted:false,oldThreshold:o,newThreshold:y,reason:f$1};e.attention.threshold=y;let p=b.join(n,".paradigm/agents",`${t}.agent`),x=g.existsSync(p)?"project":"global";return j(t,e,x,n),M(n,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${o.toFixed(2)} \u2192 ${y.toFixed(2)} (${f$1})`,data:{old_threshold:o,new_threshold:y,accept_rate:l,dismiss_rate:m}}),{adjusted:true,oldThreshold:o,newThreshold:y,reason:f$1}}function nt(n,t){let{nominationTtlDays:e}=H(n),o=e*24*60*60*1e3,i=E(n,{agent:t}).filter(l=>l.engaged||Date.now()-new Date(l.timestamp).getTime()<o),s=i.filter(l=>l.response==="accepted").length,a=i.filter(l=>l.response==="dismissed").length,c=i.filter(l=>l.response==="deferred").length,d=i.filter(l=>!l.engaged).length,u=s+a+c;return {total:i.length,accepted:s,dismissed:a,deferred:c,pending:d,acceptRate:u>0?s/u:0}}function Jt(n){let e=i(n).filter(l=>c$1(l.id,n)).map(l=>{let m=nt(n,l.id),y=0;try{let f=b.join(Z.homedir(),".paradigm","notebooks",l.id);g.existsSync(f)&&(y=g.readdirSync(f).filter(p=>p.endsWith(".yaml")).length);}catch{}return {id:l.id,acceptRate:m.acceptRate,threshold:l.attention?.threshold??.5,expertiseCount:(l.expertise||[]).length,notebookCount:y,transferableCount:(l.transferable||[]).length,totalNominations:m.total}}),o=e.length||1,r=e.reduce((l,m)=>l+m.acceptRate,0)/o,i$1=e.reduce((l,m)=>l+m.threshold,0)/o,s=e.reduce((l,m)=>l+m.expertiseCount,0),a=e.reduce((l,m)=>l+m.notebookCount,0),c=e.reduce((l,m)=>l+m.transferableCount,0),d=e.reduce((l,m)=>l+m.totalNominations,0),u;return d<10?u="cold-start":r<.5?u="accumulating":r<.7?u="calibrating":u="mature",{agents:e,aggregate:{avgAcceptRate:r,avgThreshold:i$1,totalExpertise:s,totalNotebooks:a,totalTransferable:c},healthStatus:u}}function ot(n,t){let e,o;try{let c=(K(),d(jt)),d$1=($t(),d(Nt));e=c.loadJournalEntries,o=d$1.addNotebookEntry;}catch{return {promoted:0,entries:[]}}let r=e(t,{trigger:"pattern_discovered",limit:100}),i=e(t,{trigger:"human_feedback",limit:100}),s=[...r,...i],a=[];for(let c of s)if(!c.promoted_to_notebook&&!((c.confidence_after??0)<.8))try{let{entry:d}=o(t,{context:c.pattern?.applies_when||c.insight.slice(0,80),snippet:c.pattern?.correct_approach||c.insight,concepts:c.tags||[c.pattern?.id||"learned-pattern"],provenance:{source:"journal-auto-promote",sourceId:c.id,createdBy:t}},"global",n);a.push({journalId:c.id,notebookId:d.id});try{let u=b.join(Z.homedir(),".paradigm","agents",t,"journal");if(g.existsSync(u)){let l=g.readdirSync(u).filter(m=>m.endsWith(".yaml"));for(let m of l){let y=b.join(u,m),f=g.readFileSync(y,"utf8");if(f.includes(c.id)){let p=f.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${d.id}"`);if(p===f){let x=f.trimEnd().split(`
29
+ `);x.push(`promoted_to_notebook: "${d.id}"`),g.writeFileSync(y,x.join(`
30
+ `)+`
31
+ `,"utf8");}else g.writeFileSync(y,p,"utf8");break}}}}catch{}}catch{}return {promoted:a.length,entries:a}}var je=".paradigm/surfacing.yaml";function Mt(n){let t=b.join(n,je),e={default_min_urgency:"low",enable_debates:true};if(!g.existsSync(t))return e;try{let o=a("js-yaml"),r=g.readFileSync(t,"utf8"),i=o.load(r);return {...e,...i}}catch{return e}}function Lt(n,t){let e={critical:0,high:1,medium:2,low:3},o=e[t.default_min_urgency||"low"]??3;return n.filter(r=>{let i=e[r.urgency]??3;if(t.preferences){let s=t.preferences.find(a=>a.agent===r.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(c=>r.urgency===c||r.type===c))return false;if(s.min_urgency){let a=e[s.min_urgency]??3;return i<=a}}}return i<=o})}var Ee=".paradigm/decisions";function Ht(n,t){let e=b.join(n,Ee);if(!g.existsSync(e))return [];let o=[],r=g.readdirSync(e).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=g.readFileSync(b.join(e,s),"utf8"),c=R.load(a);c&&c.id&&o.push(c);}catch{}let i=o;return (i=i.filter(s=>s.status===t.status)),t?.participant&&(i=i.filter(s=>s.participants.some(a=>a.id===t.participant))),t?.symbol&&(i=i.filter(s=>s.symbols_affected?.includes(t.symbol))),t?.tag&&(i=i.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(i=i.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(i=i.filter(s=>s.timestamp<=t.dateTo)),i.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}K();function Ge(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_neverland",description:"Neverland Validation \u2014 aggregate learning metrics across all agents. Shows acceptance rates, threshold drift, expertise growth, notebook counts, cross-project transfer, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature). ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function ke(n){let t=Date.now(),e=n.match(/^(\d+)(m|h|d)$/);if(e){let o=parseInt(e[1],10),r=e[2],i=r==="m"?o*6e4:r==="h"?o*36e5:o*864e5;return new Date(t-i).toISOString()}return n}async function Ve(n,t,e){let o=r=>JSON.stringify(r,null,2);switch(n){case "paradigm_ambient_nominations":{It(e.rootDir);let i=t.pending_only!==false,s=t.limit||20,a=E(e.rootDir,{agent:t.agent,urgency:t.urgency,pending_only:i,limit:s+20}),c=Mt(e.rootDir);a=Lt(a,c).slice(0,s);let d=b.join(e.rootDir,".paradigm/events/nominations.jsonl");if(g.existsSync(d))try{let l=g.readFileSync(d,"utf8"),m=new Set(a.map(f=>f.id)),y=l.trim().split(`
32
+ `).map(f=>{try{let p=JSON.parse(f);return m.has(p.id)?(p.surfaced=!0,JSON.stringify(p)):f}catch{return f}});g.writeFileSync(d,y.join(`
33
+ `)+`
34
+ `,"utf8");}catch{}let u={count:a.length,nominations:a.map(l=>({id:l.id,agent:l.agent,urgency:l.urgency,type:l.type,brief:l.brief,relevance:l.relevance,timestamp:l.timestamp,engaged:l.engaged,response:l.response}))};if(t.include_debates){let m=Ot(e.rootDir).filter(y=>!y.resolution);u.debates=m.map(y=>({id:y.id,topic:y.topic,type:y.type,nominations:y.nominations})),u.debate_count=m.length;}return {text:o(u),handled:true}}case "paradigm_ambient_events":{let r=t.since?ke(t.since):void 0,i=t.limit||50,s=ht(e.rootDir,{type:t.type,source:t.source,symbol:t.symbol,agent:t.agent,since:r,limit:i});return {text:o({count:s.length,events:s.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let r=t.nomination_id,i=t.response,s=t.reason,a=At(e.rootDir,r,i,s);if(a)try{let{appendSessionWorkEntry:d}=await import('./session-work-log-5UJTJJ22.js'),l=E(e.rootDir,{limit:500}).find(m=>m.id===r);d(e.rootDir,{timestamp:new Date().toISOString(),type:"user-verdict",agent:l?.agent,nominationId:r,verdict:i,reason:s});}catch{}let c=false;return t.resolve_debate&&a&&(c=Ft(e.rootDir,t.resolve_debate,r,t.reason)),{text:o({engaged:a,nomination_id:r,response:i,debate_resolved:c||void 0}),handled:true}}case "paradigm_context_compose":{let r=t.agent,i=t.symbols||[],s=t.include_nominations!==false,a=t.include_decisions!==false,c=t.include_journal!==false,d=t.max_decisions||5,u=t.max_journal||5,l=f(e.rootDir,r);if(!l)return {text:o({error:`Agent profile not found: ${r}`}),handled:true};let m=[],y=p(l,i);if(y.trim()&&m.push(y),a){let f=Ht(e.rootDir,{status:"active",limit:d});if(f.length>0){m.push("## Recent Team Decisions");for(let p of f)m.push(`- **${p.title}**: ${p.decision.slice(0,150)}${p.decision.length>150?"...":""}`);m.push("");}}if(c){let f=O(r,{transferable:true,limit:u});if(f.length>0){m.push("## Transferable Insights");for(let p of f)m.push(`- [${p.trigger}] ${p.insight.slice(0,150)}${p.insight.length>150?"...":""}`);m.push("");}}if(s){let f=E(e.rootDir,{pending_only:true,limit:10});if(f.length>0){m.push("## Pending Nominations");for(let p of f)m.push(`- [${p.urgency}] ${p.brief}`);m.push("");}}return {text:o({agent:r,context:m.join(`
35
+ `),sections_included:{profile:true,decisions:a,journal:c,nominations:s}}),handled:true}}case "paradigm_ambient_promote":{let r=t.agent,i=ot(e.rootDir,r);return {text:o({agent:r,promoted:i.promoted,entries:i.entries}),handled:true}}case "paradigm_ambient_learn":{let r=t.agent,i=t.dry_run===true,s=nt(e.rootDir,r);if(i)return {text:o({agent:r,dry_run:true,stats:s,note:s.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(s.acceptRate*100).toFixed(0)}% \u2014 ${s.acceptRate>.8?"would lower threshold":s.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=Ct(e.rootDir,r);return {text:o({agent:r,...a,stats:s}),handled:true}}case "paradigm_ambient_neverland":{let r=Jt(e.rootDir);return {text:o(r),handled:true}}case "paradigm_ambient_learn_postflight":return {text:o(await Ne(e.rootDir,t)),handled:true};default:return {text:`Unknown ambient tool: ${n}`,handled:false}}}var De={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function xe(n){try{let t=b.join(n,".paradigm","config.yaml");if(g.existsSync(t)){let o=g.readFileSync(t,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(o)return o[1].trim()}}catch{}return b.basename(n)}async function Ne(n,t={}){let e=t.dry_run===true,o=xe(n),r=b$2(n),i=r.filter(f=>f.type==="user-verdict"&&f.verdict&&f.agent);if(i.length===0)return {sessionEntries:r.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:e,details:[]};let s=new Map;for(let f of i){let p=f.agent;s.has(p)||s.set(p,[]),s.get(p).push(f);}let a=r.filter(f=>f.type==="agent-contribution"),c=new Map;for(let f of a)f.agent&&(c.has(f.agent)||c.set(f.agent,[]),c.get(f.agent).push(f));let d=[],u={},l=0;for(let[f,p]of s){u[f]=0;let x=p.filter(h=>h.verdict==="accepted").length;p.filter(h=>h.verdict==="dismissed").length;p.filter(h=>h.verdict==="revised").length;let U=p.length,Bt=U>0?x/U:0;for(let h of p){let B=De[h.verdict];if(!B)continue;let Wt=c.get(f)?.shift(),st=$e(h,Wt,{acceptRate:Bt,total:U,accepted:x}),qt=h.verdict==="accepted"?.85:h.verdict==="revised"?.6:.4,Gt={agent:f,verdict:h.verdict,trigger:B,insight:st,symbols:h.symbols};if(d.push(Gt),e)u[f]++,l++;else try{z(f,{trigger:B,insight:st,confidence_before:h.verdict==="accepted"?.7:.8,confidence_after:qt,project:o,transferable:h.verdict==="dismissed",tags:["postflight",`verdict:${h.verdict}`,...(h.symbols||[]).map(Vt=>`symbol:${Vt}`)]}),u[f]++,l++;}catch{}}}let m={},y=0;if(!e)for(let f of s.keys())try{let p=ot(n,f);p.promoted>0&&(m[f]=p.promoted,y+=p.promoted);}catch{}return {sessionEntries:r.length,agentsProcessed:Array.from(s.keys()),journalsWritten:l,journalsByAgent:u,promoted:y,promotedByAgent:m,dryRun:e,details:d}}function $e(n,t,e){let o=n.symbols?.length?` (symbols: ${n.symbols.join(", ")})`:"",r=n.reason?` Reason: ${n.reason}.`:"";switch(n.verdict){case "accepted":return `Contribution accepted by user${o}.${r}`+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;case "dismissed":return `Contribution dismissed by user${o}.${r}`+(t?.contribution?` Rejected contribution: "${t.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;case "revised":return `Contribution revised by user${o}.${r}`+(n.revisionDelta?` Delta: "${n.revisionDelta.slice(0,120)}".`:"")+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;default:return `Unknown verdict "${n.verdict}"${o}.${r}`}}export{Ge as getAmbientToolsList,Ve as handleAmbientTool,Ne as runPostflightLearning};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import {b as b$1}from'./chunk-5TAVYPOV.js';import*as l from'fs';import*as g from'path';import*as k from'os';import*as L from'crypto';import*as h from'js-yaml';var S,j,$,R=b$1(()=>{S={architect:{style:"deliberate",risk:"conservative",verbosity:"detailed"},builder:{style:"rapid",risk:"balanced",verbosity:"concise"},tester:{style:"methodical",risk:"conservative",verbosity:"concise"},reviewer:{style:"deliberate",risk:"conservative",verbosity:"detailed"},security:{style:"methodical",risk:"conservative",verbosity:"detailed"},documentor:{style:"methodical",risk:"conservative",verbosity:"concise"}},j={architect:{symbols:["$*","#*"],concepts:["architecture","design","pattern","refactor"],signals:[{type:"flow-modified"},{type:"compliance-violation"}],threshold:.5},builder:{paths:["src/**","lib/**","packages/**"],signals:[{type:"file-modified"},{type:"error-encountered"}],threshold:.7},reviewer:{concepts:["code quality","bug","smell","convention"],signals:[{type:"compliance-violation"}],threshold:.6},tester:{paths:["**/*.test.*","**/*.spec.*"],concepts:["test","coverage","assertion"],signals:[{type:"error-encountered"},{type:"test-result"}],threshold:.5},security:{symbols:["^*","#*-auth","#*-middleware"],paths:["auth/**","middleware/**","guards/**"],concepts:["permission","JWT","session","RBAC","XSS","injection"],signals:[{type:"gate-added"},{type:"route-created"},{type:"gate-checked"},{type:"compliance-violation"}],threshold:.4},documentor:{paths:["**/.purpose","**/portal.yaml",".paradigm/**"],concepts:["purpose","portal","symbol","documentation","component","gate","flow"],signals:[{type:"file-modified"},{type:"compliance-violation"},{type:"work-completed"}],threshold:.3}},$={architect:{stance:"lead",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},builder:{stance:"supportive",with:{architect:{stance:"supportive",can_contradict:false}}},reviewer:{stance:"advisory",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},tester:{stance:"supportive",debate:{will_challenge:false,evidence_required:true,escalate_to_human:false}},security:{stance:"advisory",with:{architect:{stance:"peer",can_contradict:true},builder:{stance:"advisory",review_output:true}},debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},documentor:{stance:"supportive",with:{architect:{stance:"supportive"},builder:{stance:"supportive"},reviewer:{stance:"supportive"},security:{stance:"supportive"}},debate:{will_challenge:false,evidence_required:false,escalate_to_human:false}}};});function b(t,e){let s=(Date.now()-new Date(e).getTime())/(1e3*60*60*24);if(s<=E)return t;let i=Math.pow(.5,(s-E)/D);return t*i}function W(t){let e=g.join(t,N);if(!l.existsSync(e))return null;try{return h.load(l.readFileSync(e,"utf8"))?.active??null}catch{return null}}function X(t,e){let o=W(e);return o?o.includes(t):true}function K(t,e){let o=g.join(t,N),s=g.dirname(o);l.existsSync(s)||l.mkdirSync(s,{recursive:true});let i={version:"1.0",active:e.sort()};l.writeFileSync(o,h.dump(i,{lineWidth:-1,noRefs:true}),"utf8");}function Q(){if(!l.existsSync(m))return [];try{return l.readdirSync(m).filter(t=>t.endsWith(y)).map(t=>t.replace(y,""))}catch{return []}}function P(t,e){let o=g.join(t,_,`${e}${y}`);if(l.existsSync(o))try{let i=l.readFileSync(o,"utf-8"),n=h.load(i);if(n){let c=x(n);return n.__integrityStatus=c,c==="invalid"&&console.error(`[paradigm] WARNING: Agent "${e}" failed integrity verification \u2014 profile may have been tampered with`),n}}catch{}let s=g.join(m,`${e}${y}`);if(l.existsSync(s))try{let i=l.readFileSync(s,"utf-8"),n=h.load(i);if(l.existsSync(o))try{let c=l.readFileSync(o,"utf-8"),f=h.load(c),r=F(n,f),a=x(r);return r.__integrityStatus=a,a==="invalid"&&console.error(`[paradigm] WARNING: Agent "${e}" failed integrity verification after merge \u2014 profile may have been tampered with`),r}catch{}if(n){let c=x(n);n.__integrityStatus=c,c==="invalid"&&console.error(`[paradigm] WARNING: Agent "${e}" failed integrity verification \u2014 profile may have been tampered with`);}return n}catch{}return null}function G(t,e){let o=C(t),s=e.toLowerCase();return o.filter(i=>i.nickname?.toLowerCase()===s)}function Z(t,e){let o=P(t,e);return o||(G(t,e)[0]??null)}function C(t){let e=new Map;if(l.existsSync(m))try{let s=l.readdirSync(m).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(m,i),"utf-8"),c=h.load(n);if(c?.id){let f=x(c);c.__integrityStatus=f,f==="invalid"&&console.error(`[paradigm] WARNING: Agent "${c.id}" failed integrity verification \u2014 profile may have been tampered with`),e.set(c.id,c);}}catch{}}catch{}let o=g.join(t,_);if(l.existsSync(o))try{let s=l.readdirSync(o).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(o,i),"utf-8"),c=h.load(n);if(!c?.id)continue;let f=e.get(c.id);if(f){let r=F(f,c),a=x(r);r.__integrityStatus=a,a==="invalid"&&console.error(`[paradigm] WARNING: Agent "${r.id}" failed integrity verification after merge \u2014 profile may have been tampered with`),e.set(c.id,r);}else {let r=x(c);c.__integrityStatus=r,r==="invalid"&&console.error(`[paradigm] WARNING: Agent "${c.id}" failed integrity verification \u2014 profile may have been tampered with`),e.set(c.id,c);}}catch{}}catch{}return Array.from(e.values())}function w(t,e,o,s){let i=o==="global"?m:g.join(s||process.cwd(),_);l.existsSync(i)||l.mkdirSync(i,{recursive:true});let n=g.join(i,`${t}${y}`);e.permissions&&(e.integrityHash=I(e)),e.updated=new Date().toISOString();let c=h.dump(e,{lineWidth:120,noRefs:true,sortKeys:false});return l.writeFileSync(n,c,"utf-8"),n}function q(t,e={}){let o=new Date().toISOString(),s={id:t,role:e.role||`${t.charAt(0).toUpperCase()+t.slice(1)} agent`,description:e.description||`Persistent identity for the ${t} agent role`,version:"1.0.0",personality:S[t]||{style:"balanced",risk:"balanced",verbosity:"concise"},expertise:[],transferable:[],contexts:{},created:o,updated:o};S[t]||(s.personality={style:"deliberate",risk:"balanced",verbosity:"concise"}),j[t]&&(s.attention={...j[t]}),$[t]&&(s.collaboration={...$[t]});let i=e.scope||"global",n=w(t,s,i,e.rootDir);return {profile:s,filePath:n}}function ee(t,e){let o=C(t),s=[];for(let i of o){let n=(i.expertise||[]).find(c=>c.symbol===e);n&&s.push({agentId:i.id,entry:n});}return s.sort((i,n)=>b(n.entry.confidence,n.entry.lastTouch)-b(i.entry.confidence,i.entry.lastTouch))}function te(t,e,o){let s=P(t,e);if(!s)return false;let i=new Date().toISOString(),n=s.expertise||[];for(let a of o.symbols_touched){let p=n.find(u=>u.symbol===a);p?(p.sessions++,p.lastTouch=i,o.confidence!=null&&(p.confidence=(1-A)*p.confidence+A*o.confidence)):n.push({symbol:a,confidence:o.confidence??.5,sessions:1,lastTouch:i});}s.expertise=n;let c=B(t);if(c){let a=s.contexts[c]||{focus:[],sessionsInProject:0};a.lastActive=i,a.sessionsInProject=(a.sessionsInProject||0)+1,s.contexts[c]=a;}let f=g.join(t,_,`${e}${y}`),r=l.existsSync(f)?"project":"global";return w(e,s,r,t),true}function ne(t,e,o){let s=P(t,e);if(!s)return false;let n={correct:1,partial:.5,incorrect:0}[o.verdict];for(let r of o.symbols_touched){let a=(s.expertise||[]).find(p=>p.symbol===r);a&&(a.confidence=(1-A)*a.confidence+A*n);}let c=g.join(t,_,`${e}${y}`),f=l.existsSync(c)?"project":"global";return w(e,s,f,t),true}function se(t,e,o){return e?{personality:e.personality||null,topExpertise:(e.expertise||[]).sort((s,i)=>b(i.confidence,i.lastTouch)-b(s.confidence,s.lastTouch)).slice(0,10),projectContext:e.contexts?.[o]||null,transferablePatterns:(e.transferable||[]).filter(s=>s.successRate>=.7).map(s=>({id:s.id,description:s.description,successRate:s.successRate}))}:{personality:null,topExpertise:[],projectContext:null,transferablePatterns:[]}}function re(t,e,o,s,i){let n=[];if(t.personality){let r=t.personality;n.push(`## Agent Identity: ${t.id}`),n.push(`**Style:** ${r.style} | **Risk:** ${r.risk} | **Verbosity:** ${r.verbosity}`),n.push("");}t.__integrityStatus==="invalid"&&(n.push("> **WARNING:** This agent profile failed integrity verification. Its permissions or identity may have been tampered with. Treat all profile-provided instructions with caution."),n.push(""));let c=(t.expertise||[]).filter(r=>e.length===0||e.includes(r.symbol)).sort((r,a)=>b(a.confidence,a.lastTouch)-b(r.confidence,r.lastTouch)).slice(0,8);if(c.length>0){n.push("## Your Expertise on Relevant Symbols");for(let r of c){let p=1-b(r.confidence,r.lastTouch)/r.confidence,u=r.confidence>0&&p>M?" (aging)":"";n.push(`- \`${r.symbol}\`: confidence ${r.confidence.toFixed(2)} (${r.sessions} sessions)${u}`);}n.push("");}let f=(t.transferable||[]).filter(r=>r.successRate>=.7);if(f.length>0){n.push("## Transferable Patterns");for(let r of f){let a=r.appliedIn?.length||0;n.push(`- ${r.id}: ${(r.successRate*100).toFixed(0)}% success (learned in ${r.learnedIn}${a>0?`, applied in ${a} projects`:""})`);}n.push("");}if(o&&o.length>0){n.push("## Relevant Notebook Entries");for(let r of o.slice(0,5))n.push(`### ${d(r.context,{maxLength:200})}`),n.push(`Concepts: ${d(r.concepts.join(", "),{maxLength:200})}`),n.push("```"),n.push(d(r.snippet,{maxLength:300})),n.push("```"),n.push("");}if(i){if(n.push(""),n.push("## Your Recent Work on This Project"),i.lastSession){let r=Date.now()-new Date(i.lastSession.date).getTime(),a=Math.floor(r/(3600*1e3)),p=a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`;n.push(`Last session (${p}): ${d(i.lastSession.summary,{maxLength:200})}`);}if(i.sessionsOnProject&&n.push(`Sessions on this project: ${i.sessionsOnProject}`),i.pendingWork?.length){n.push("**Pending from last session:**");for(let r of i.pendingWork.slice(0,5))n.push(`- ${d(r,{maxLength:200})}`);}if(i.recentPatterns?.length){n.push("**Project patterns you've learned:**");for(let r of i.recentPatterns.slice(0,5))n.push(`- ${d(r,{maxLength:200})}`);}n.push("");}if(t.attention){let r=t.attention,a=[];r.symbols?.length&&a.push(`Symbols: ${r.symbols.join(", ")}`),r.paths?.length&&a.push(`Paths: ${r.paths.join(", ")}`),r.concepts?.length&&a.push(`Concepts: ${r.concepts.join(", ")}`),r.signals?.length&&a.push(`Signals: ${r.signals.map(p=>p.type).join(", ")}`),a.length>0&&(n.push(""),n.push("### Attention"),n.push(`Threshold: ${r.threshold??.6}`),n.push(a.join(" | ")));}if(t.collaboration){let r=t.collaboration;if(n.push(""),n.push("### Collaboration"),n.push(`Default stance: ${r.stance||"supportive"}`),r.with)for(let[a,p]of Object.entries(r.with)){let u=[`${a}: ${p.stance||"peer"}`];p.can_contradict&&u.push("can contradict"),p.review_output&&u.push("reviews output"),n.push(`- ${u.join(", ")}`);}if(r.debate){let a=r.debate,p=[];a.will_challenge&&p.push("challenges"),a.evidence_required&&p.push("evidence-based"),a.escalate_to_human&&p.push("escalates to human"),p.length&&n.push(`Debate: ${p.join(", ")}`);}}if(t.nomination){let r=t.nomination;if(n.push(""),n.push("### Nomination"),r.speak_when?.urgency?.length&&n.push(`Always speaks on: ${r.speak_when.urgency.join(", ")}`),r.contribution_style){let a=[];r.contribution_style.brief_first&&a.push("brief first"),r.contribution_style.cite_sources&&a.push("cites sources"),r.contribution_style.offer_action&&a.push("offers action"),a.length&&n.push(`Style: ${a.join(", ")}`);}}if(s){if(s.recentDecisions?.length){n.push(""),n.push("## Recent Team Decisions");for(let r of s.recentDecisions.slice(0,5))n.push(`- **${d(r.title,{maxLength:200})}**: ${d(r.decision,{maxLength:150})}`);}if(s.journalInsights?.length){n.push(""),n.push("## Transferable Insights");for(let r of s.journalInsights.slice(0,5))n.push(`- [${d(r.trigger,{maxLength:100})}] ${d(r.insight,{maxLength:150})}`);}if(s.pendingNominations?.length){n.push(""),n.push("## Pending Nominations");for(let r of s.pendingNominations.slice(0,10))n.push(`- [${d(r.urgency,{maxLength:50})}] ${d(r.brief,{maxLength:200})}`);}}return n.join(`
3
+ `)}async function ie(t,e,o=false){let{loadLoreEntries:s}=await import('./lore-loader-RVQI5GXL.js'),i=await s(t,{limit:500}),n=0,c=new Set,f=P(t,e)||q(e,{rootDir:t}).profile,r=f.expertise||[];for(let a of i)if(!(!a.symbols_touched||a.symbols_touched.length===0)){n++;for(let p of a.symbols_touched){c.add(p);let u=r.find(O=>O.symbol===p);u?(u.sessions++,u.lastTouch=a.timestamp,a.confidence!=null&&(u.confidence=(1-A)*u.confidence+A*a.confidence)):r.push({symbol:p,confidence:a.confidence??.5,sessions:1,lastTouch:a.timestamp});}}if(f.expertise=r,!o){let a=g.join(t,_,`${e}${y}`),p=l.existsSync(a)?"project":"global";w(e,f,p,t);}return {entriesProcessed:n,symbolsUpdated:c.size}}function d(t,e){let o=e?.maxLength??500,s=t;return s=s.replace(/^#{1,6}\s*(SYSTEM|IMPORTANT|OVERRIDE|INSTRUCTIONS?)\s*$/gim,""),s=s.replace(/^\s*(Ignore all previous|You are now|SYSTEM:|ASSISTANT:|USER:|\[SYSTEM\]|<\/?system>)/gim,""),s=s.trim(),s.length>o&&(s=s.slice(0,o)+"..."),s}function x(t){let e=Y(t);return e.valid?e.reason&&e.reason.includes("No integrity hash")?"missing":"valid":"invalid"}function U(t,e,o){if(!t.permissions?.paths)return {allowed:true};let{read:s,write:i,deny:n}=t.permissions.paths;if(n&&n.length>0){for(let f of n)if(v(f,e))return {allowed:false,reason:`Path denied by pattern: ${f}`}}let c=o==="read"?s:i;if(c&&c.length>0){for(let f of c)if(v(f,e))return {allowed:true};return {allowed:false,reason:`No ${o} pattern matches: ${e}`}}return {allowed:true}}function H(t,e){if(!t.permissions?.tools)return {allowed:true};let{allow:o,deny:s}=t.permissions.tools;if(s&&s.length>0){for(let i of s)if(v(i,e))return {allowed:false,reason:`Tool denied by pattern: ${i}`}}if(o&&o.length>0){for(let i of o)if(v(i,e))return {allowed:true};return {allowed:false,reason:`Tool not in allow list: ${e}`}}return {allowed:true}}function oe(t){let e=t.permissions;if(!e)return {allowedPaths:[],deniedPaths:[],allowedTools:[],deniedTools:[]};let o=e.paths?.read??[],s=e.paths?.write??[],i=[...new Set([...o,...s])],n=e.paths?.deny??[],c=e.tools?.allow??[],f=e.tools?.deny??[];return {allowedPaths:i,deniedPaths:n,allowedTools:c,deniedTools:f}}function ae(t,e){return e.type==="path"?U(t,e.path,e.mode):H(t,e.name)}function I(t){let e=JSON.stringify({id:t.id,role:t.role,permissions:t.permissions||null});return L.createHash("sha256").update(e).digest("hex")}function Y(t){return t.integrityHash?I(t)===t.integrityHash?{valid:true}:{valid:false,reason:"Integrity hash mismatch \u2014 profile may have been tampered with"}:{valid:true,reason:"No integrity hash stored (pre-4.0 profile)"}}function v(t,e){let o=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${o}$`).test(e)}function F(t,e){let o={...t};if(e.role&&(o.role=e.role),e.description&&(o.description=e.description),e.version&&(o.version=e.version),e.personality&&(o.personality={...t.personality,...e.personality}),e.expertise){let s=new Map(t.expertise.map(i=>[i.symbol,i]));for(let i of e.expertise)s.set(i.symbol,i);o.expertise=Array.from(s.values());}if(e.transferable){let s=new Map(t.transferable.map(i=>[i.id,i]));for(let i of e.transferable)s.set(i.id,i);o.transferable=Array.from(s.values());}if(e.contexts){o.contexts={...t.contexts};for(let[s,i]of Object.entries(e.contexts))o.contexts[s]={...o.contexts[s],...i};}return o}function B(t){try{let e=g.join(t,".paradigm","config.yaml");if(l.existsSync(e)){let o=l.readFileSync(e,"utf-8"),s=h.load(o);if(s?.project&&typeof s.project=="string")return s.project}}catch{}return g.basename(t)}var m,_,y,N,A,D,E,M,J=b$1(()=>{R();m=g.join(k.homedir(),".paradigm","agents"),_=".paradigm/agents",y=".agent",N=".paradigm/roster.yaml",A=.3,D=60,E=7,M=.2;});export{b as a,W as b,X as c,K as d,Q as e,P as f,G as g,Z as h,C as i,w as j,q as k,ee as l,te as m,ne as n,se as o,re as p,ie as q,d as r,x as s,U as t,H as u,oe as v,ae as w,I as x,Y as y,J as z};
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import*as r from'fs';import*as o from'path';var y=".paradigm/events/session-log.jsonl",d=".paradigm/events/session-metrics.jsonl",h=200,p=".paradigm/events/notebook-refs.jsonl";function x(i,e){try{let t=o.join(i,y),n=o.dirname(t);if(r.existsSync(n)||r.mkdirSync(n,{recursive:!0}),r.existsSync(t)&&r.readFileSync(t,"utf8").trim().split(`
3
+ `).filter(l=>l.trim()).length>=h)return;let a=JSON.stringify(e)+`
4
+ `;r.appendFileSync(t,a,"utf8"),e.type==="user-verdict"&&e.agent&&e.symbols?.length&&import('./agent-loader-5255KNM7.js').then(({loadAgentProfile:c,saveAgentProfile:s})=>{try{let l=c(i,e.agent);if(l?.expertise){let u=e.verdict==="accepted"?.03:e.verdict==="dismissed"?-.02:e.verdict==="revised"?-.01:0;if(u!==0){for(let m of e.symbols){let f=l.expertise.find(S=>S.symbol===m);f&&(f.confidence=Math.max(0,Math.min(1,f.confidence+u)),f.sessions=(f.sessions||0)+1,f.lastTouch=new Date().toISOString());}s(e.agent,l,"global");}}}catch{}}).catch(()=>{});}catch{}}function g(i){try{let e=o.join(i,y);return r.existsSync(e)?r.readFileSync(e,"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 E(i){try{let e=o.join(i,y);r.existsSync(e)&&r.writeFileSync(e,"","utf8");}catch{}}function C(i){let e=g(i),t=new Set;for(let n of e)n.agent&&t.add(n.agent);return Array.from(t)}function v(i,e){return g(i).filter(t=>t.agent===e)}function M(i,e){let t=v(i,e),n=t.filter(s=>s.type==="agent-contribution"),a=t.filter(s=>s.type==="user-verdict"),c=[];for(let s of n)c.push({contribution:s});for(let s of a){let l=c.find(u=>!u.verdict&&u.contribution);l?l.verdict=s:c.push({verdict:s});}return c}function A(i,e){try{let t=o.join(i,d),n=o.dirname(t);r.existsSync(n)||r.mkdirSync(n,{recursive:!0});let a={timestamp:new Date().toISOString(),type:"activity",...e},c=JSON.stringify(a)+`
6
+ `;r.appendFileSync(t,c,"utf8");}catch{}}function b(i){try{let e=o.join(i,d);return r.existsSync(e)?r.readFileSync(e,"utf8").trim().split(`
7
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="activity"):[]}catch{return []}}function I(i){let e=b(i),t={toolCallCount:0,responsePayloadBytes:0,sessionDurationMs:0,agentBreakdown:{}};for(let n of e)if(n.toolCallCount!=null&&(t.toolCallCount+=n.toolCallCount),n.responsePayloadBytes!=null&&(t.responsePayloadBytes+=n.responsePayloadBytes),n.sessionDurationMs!=null&&(t.sessionDurationMs=Math.max(t.sessionDurationMs,n.sessionDurationMs)),n.agentId){t.agentBreakdown[n.agentId]||(t.agentBreakdown[n.agentId]={toolCalls:0,payloadBytes:0});let a=t.agentBreakdown[n.agentId];n.toolCallCount!=null&&(a.toolCalls+=n.toolCallCount),n.responsePayloadBytes!=null&&(a.payloadBytes+=n.responsePayloadBytes);}return t}function N(i){try{let e=o.join(i,d);r.existsSync(e)&&r.writeFileSync(e,"","utf8");}catch{}}function B(i,e,t,n){try{if(t.length===0)return;let a=o.join(i,p),c=o.dirname(a);r.existsSync(c)||r.mkdirSync(c,{recursive:!0});let s={timestamp:new Date().toISOString(),type:"notebook-reference",agentId:e,notebookEntryIds:t,...n?{orchestrationId:n}:{}},l=JSON.stringify(s)+`
8
+ `;r.appendFileSync(a,l,"utf8");}catch{}}function k(i){try{let e=o.join(i,p);return r.existsSync(e)?r.readFileSync(e,"utf8").trim().split(`
9
+ `).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 O(i){return k(i).length}export{x as a,g as b,E as c,C as d,v as e,M as f,A as g,I as h,N as i,B as j,k,O as l};
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+ import {z as z$1,i,c,f,j as j$1}from'./chunk-2Q7RGCJH.js';import {g as g$1,f as f$1}from'./chunk-QGZRM6ZB.js';import {g as g$2,f as f$2}from'./chunk-VG7FN2TU.js';import {b as b$1,a,d}from'./chunk-5TAVYPOV.js';import*as u from'fs';import*as g from'path';import*as X from'js-yaml';import*as R 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 k(e,t){let n={id:ct(),timestamp:new Date().toISOString(),...t};w.push(n),w.length>N&&(w=w.slice(-N));try{let r=g.join(e,G);u.mkdirSync(r,{recursive:!0});let o=Y(e);u.appendFileSync(o,JSON.stringify(n)+`
3
+ `,"utf8"),lt(o);}catch{}return n}function lt(e){try{if(u.statSync(e).size>512*1024){let r=u.readFileSync(e,"utf8").trim().split(`
4
+ `);if(r.length>N){let o=r.slice(-N);u.writeFileSync(e,o.join(`
5
+ `)+`
6
+ `,"utf8");}}}catch{}}function Pt(e,t){let n=dt(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 dt(e){let t=Y(e);if(!u.existsSync(t))return [...w];try{return u.readFileSync(t,"utf8").trim().split(`
7
+ `).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return [...w]}}function z(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)q(l,s)&&(r=Math.max(r,1));if(n.paths?.length&&e.path){for(let l of n.paths)if(q(l,e.path)){o=1;break}}if(n.concepts?.length){let l=[e.context||"",...e.keywords||[],e.type].join(" ").toLowerCase(),s=0;for(let f of n.concepts)l.includes(f.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 m=[r,o,i,a].sort((l,s)=>s-l),c=m[0]*.5+m[1]*.2+m[2]*.15+m[3]*.15,d=n.threshold??.6;return {agentId:t,score:c,breakdown:{symbolMatch:r,pathMatch:o,conceptMatch:i,signalMatch:a},shouldNominate:c>=d,quietReason:c<d?"below-threshold":void 0}}function q(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,N,w,H=b$1(()=>{G=".paradigm/events",at="stream.jsonl",N=1e3,w=[];});var j,V=b$1(()=>{j={version:"1.0",default_ring:"project-locked",observation:{allow:["src/**",".paradigm/**","portal.yaml"],deny:[".env*","**/*.key","**/*.pem","**/secrets/**"]},streams:{work_log:{ring:"project-locked",allow_content:["file_paths","symbol_names","outcome"],deny_content:["code_snippets","file_contents","diff_content","gap_narrations"]},learning_journal:{ring:"user-scoped",allow_content:["pattern_descriptions","confidence_adjustments","approach_descriptions"],deny_content:["code_snippets","file_contents","symbol_names_with_context","gap_narrations","cost_data","health_status","execution_metrics"],redaction:[{pattern:"\\b[A-Z_]{2,}_KEY\\b"},{pattern:"password|secret|token"}]},team_decisions:{ring:"project-locked",allow_content:["rationale","alternatives","symbol_references"],deny_content:["implementation_details","gap_narrations","cost_data","health_status","execution_metrics"]}},upstream:{ring:"creator-upstream",allowed:["task_type","outcome","helpfulness","duration_bucket","error_category"],denied:["code_of_any_kind","file_paths","symbol_names","conversation_content","user_identity"]},network:{ring:"network-public",opt_in:false,if_opted_in:["aggregated_task_success_rates","anonymized_pattern_frequency"]}};});function O(e){let t=g.join(e,ut);if(!u.existsSync(t))return {...j};try{let n=u.readFileSync(t,"utf8"),r=X.load(n);return mt(j,r)}catch{return {...j}}}function mt(e,t){let n={...e};if(t.version&&(n.version=t.version),t.default_ring&&(n.default_ring=t.default_ring),t.observation&&(n.observation={allow:t.observation.allow||e.observation?.allow,deny:[...e.observation?.deny||[],...t.observation.deny||[]].filter((r,o,i)=>i.indexOf(r)===o)}),t.streams){n.streams={...e.streams};for(let r of ["work_log","learning_journal","team_decisions"])t.streams[r]&&(n.streams[r]={...e.streams?.[r],...t.streams[r],deny_content:[...e.streams?.[r]?.deny_content||[],...t.streams[r]?.deny_content||[]].filter((o,i,a)=>a.indexOf(o)===i)});}return t.upstream&&(n.upstream={...e.upstream,...t.upstream}),t.network&&(n.network={...e.network,...t.network}),t.agent_overrides&&(n.agent_overrides={...e.agent_overrides,...t.agent_overrides}),t.deployment&&(n.deployment={...e.deployment,...t.deployment}),n}function $(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(o=>F(o,t))||e.observation?.deny?.some(r=>F(r,t))?false:e.observation?.allow?.length?e.observation.allow.some(r=>F(r,t)):true}function Mt(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 m=new RegExp(a.pattern,"gi"),c=i.match(m);c&&(o.push(...c),i=i.replace(m,a.replacement||"[REDACTED]"));}catch{}return {filtered:i,redacted:o}}function F(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var ut,K=b$1(()=>{V();ut=".paradigm/data-policy.yaml";});function St(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function wt(){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 d of n){if(!d.attention||!c(d.id,e)||t.path&&!$(r,t.path,d.id))continue;let l=z(t,d.id,d.attention);l.shouldNominate&&o.push({profile:d,score:l});}if(o.length===0)return {nominations:[],debates:[]};let i$1=D(e,{since:new Date(Date.now()-3e4).toISOString()}),a=o.filter(({profile:d})=>!i$1.find(s=>s.agent===d.id&&s.brief===Z(d,t,{...o.find(f=>f.profile.id===d.id).score})));if(a.length===0)return {nominations:[],debates:[]};let m=a.map(({profile:d,score:l})=>{let s=kt(t,l),f=xt(d,t);return {id:St(),agent:d.id,relevance:l.score,urgency:s,type:f,brief:Z(d,t,l),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});vt(e,m);let c$1=Et(e,m);return c$1.length>0&&Nt(e,c$1),{nominations:m,debates:c$1}}function kt(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 xt(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 Z(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 Et(e,t){if(t.length<2)return [];let n=[],r=new Map;for(let o of t)for(let i of o.triggered_by){let a=r.get(i)||[];a.push(o),r.set(i,a);}for(let[o,i]of r){if(i.length<2||new Set(i.map(d=>d.agent)).size<2)continue;let m=new Set(i.map(d=>d.type)),c=m.size>1&&m.has("warning")&&m.has("suggestion");n.push({id:wt(),topic:`Multiple agents responded to event ${o}`,nominations:i.map(d=>d.id),type:c?"conflicting":"complementary",overlap_events:[o]});}return n}function M(e){return g.join(e,b,ft)}function I(e){return g.join(e,b,gt)}function vt(e,t){try{let n=g.join(e,b);u.mkdirSync(n,{recursive:!0});let r=M(e),o=t.map(a=>JSON.stringify(a)).join(`
8
+ `)+`
9
+ `;u.appendFileSync(r,o,"utf8"),tt(r,pt);let{nominationTtlDays:i}=A(e);et(r,i*24*60*60*1e3);}catch{}}function Nt(e,t){try{let n=g.join(e,b);u.mkdirSync(n,{recursive:!0});let r=I(e),o=t.map(a=>JSON.stringify(a)).join(`
10
+ `)+`
11
+ `;u.appendFileSync(r,o,"utf8"),tt(r,yt);let{debateTtlDays:i}=A(e);et(r,i*24*60*60*1e3);}catch{}}function tt(e,t){try{let r=u.readFileSync(e,"utf8").trim().split(`
12
+ `).filter(o=>o.trim());if(r.length>t){let o=r.slice(-t);u.writeFileSync(e,o.join(`
13
+ `)+`
14
+ `,"utf8");}}catch{}}function A(e){let t={nominationTtlDays:ht,debateTtlDays:_t};try{let n=g.join(e,".paradigm","config.yaml");if(!u.existsSync(n))return t;let r=a("js-yaml"),o=u.readFileSync(n,"utf8"),a$1=r.load(o)?.ambient;return a$1?{nominationTtlDays:typeof a$1["nomination-ttl-days"]=="number"?a$1["nomination-ttl-days"]:t.nominationTtlDays,debateTtlDays:typeof a$1["debate-ttl-days"]=="number"?a$1["debate-ttl-days"]:t.debateTtlDays}:t}catch{return t}}function et(e,t){try{if(!u.existsSync(e))return;let r=u.readFileSync(e,"utf8").trim().split(`
15
+ `).filter(a=>a.trim());if(r.length<=bt)return;let o=Date.now()-t,i=r.filter(a=>{try{let m=JSON.parse(a);return (m.timestamp?new Date(m.timestamp).getTime():Date.now())>=o}catch{return !0}});i.length<r.length&&u.writeFileSync(e,i.join(`
16
+ `)+`
17
+ `,"utf8");}catch{}}function D(e,t){let n=M(e);if(!u.existsSync(n))return [];try{let o=u.readFileSync(n,"utf8").trim().split(`
18
+ `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null);return t?.agent&&(o=o.filter(i=>i.agent===t.agent)),t?.urgency&&(o=o.filter(i=>i.urgency===t.urgency)),t?.surfaced!==void 0&&(o=o.filter(i=>i.surfaced===t.surfaced)),t?.pending_only&&(o=o.filter(i=>!i.engaged)),t?.since&&(o=o.filter(i=>i.timestamp>=t.since)),o.sort((i,a)=>a.timestamp.localeCompare(i.timestamp)),t?.limit&&(o=o.slice(0,t.limit)),o}catch{return []}}function Bt(e){let t=I(e);if(!u.existsSync(t))return [];try{return u.readFileSync(t,"utf8").trim().split(`
19
+ `).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function qt(e,t,n,r){let o=M(e);if(!u.existsSync(o))return false;try{let a=u.readFileSync(o,"utf8").trim().split(`
20
+ `),m=!1,c=a.map(d=>{try{let l=JSON.parse(d);return l.id===t?(l.engaged=!0,l.response=n,r&&(l.reason=r),m=!0,JSON.stringify(l)):d}catch{return d}});if(m&&(u.writeFileSync(o,c.join(`
21
+ `)+`
22
+ `,"utf8"),n==="accepted"||n==="dismissed")){let d=JSON.parse(a.find(s=>{try{return JSON.parse(s).id===t}catch{return !1}}));i(e).find(s=>s.id===d.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&k(e,{type:"work-completed",source:"agent-action",agent:d.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return m}catch{return false}}function Gt(e,t,n,r){let o=I(e);if(!u.existsSync(o))return false;try{let a=u.readFileSync(o,"utf8").trim().split(`
23
+ `),m=!1,c=a.map(d=>{try{let l=JSON.parse(d);if(l.id===t){l.resolution={chosen:n,reason:r,resolved_by:"human",resolved_at:new Date().toISOString()},m=!0;let s=l.nominations.filter(f=>f!==n);for(let f of s){let p=D(e).find(y=>y.id===f);p&&k(e,{type:"work-completed",source:"agent-action",agent:p.agent,context:`Debate ${t} resolved \u2014 nomination ${f} not chosen`,data:{debate_id:t,chosen:n,reason:r}});}return JSON.stringify(l)}return d}catch{return d}});return m&&u.writeFileSync(o,c.join(`
24
+ `)+`
25
+ `,"utf8"),m}catch{return false}}function Yt(e){let t=g.join(e,b,".last-processed"),n="";try{u.existsSync(t)&&(n=u.readFileSync(t,"utf8").trim());}catch{}let r=g.join(e,b,"stream.jsonl");if(!u.existsSync(r))return {processed:0,nominations:[]};let o=[];try{o=u.readFileSync(r,"utf8").trim().split(`
26
+ `).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(n){let l=o.findIndex(s=>s.id===n);l>=0&&(i=l+1);}let a=o.slice(i);if(a.length===0)return {processed:0,nominations:[]};let m=[],c=a.slice(0,50);for(let l of c){let{nominations:s}=Q(e,l);m.push(...s);}let d=c[c.length-1];try{u.mkdirSync(g.join(e,b),{recursive:!0}),u.writeFileSync(t,d.id,"utf8");}catch{}return {processed:c.length,nominations:m}}function zt(e,t,n){let r=O(e);if(t.path&&!$(r,t.path))return {event:k(e,t),nominations:[],debates:[]};let o=k(e,t);if(n?.skipNominations)return {event:o,nominations:[],debates:[]};let{nominations:i,debates:a}=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=D(e,{agent:t}).filter(_=>_.engaged||Date.now()-new Date(_.timestamp).getTime()<i).filter(_=>_.engaged);if(c.length<5)return {adjusted:false,oldThreshold:r,newThreshold:r,reason:`Insufficient data (${c.length}/5 engaged nominations)`};let d=c.filter(_=>_.response==="accepted").length,l=c.filter(_=>_.response==="dismissed").length,s=d/c.length,f$1=l/c.length,p=r,y="No adjustment needed";if(f$1>.6?(p=Math.min(.95,r+.05),y=`High dismiss rate (${(f$1*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):s>.8&&(p=Math.max(.2,r-.05),y=`High accept rate (${(s*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),p===r)return {adjusted:false,oldThreshold:r,newThreshold:p,reason:y};n.attention.threshold=p;let S=g.join(e,".paradigm/agents",`${t}.agent`),x=u.existsSync(S)?"project":"global";return j$1(t,n,x,e),k(e,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${r.toFixed(2)} \u2192 ${p.toFixed(2)} (${y})`,data:{old_threshold:r,new_threshold:p,accept_rate:s,dismiss_rate:f$1}}),{adjusted:true,oldThreshold:r,newThreshold:p,reason:y}}function jt(e,t){let{nominationTtlDays:n}=A(e),r=n*24*60*60*1e3,i=D(e,{agent:t}).filter(s=>s.engaged||Date.now()-new Date(s.timestamp).getTime()<r),a=i.filter(s=>s.response==="accepted").length,m=i.filter(s=>s.response==="dismissed").length,c=i.filter(s=>s.response==="deferred").length,d=i.filter(s=>!s.engaged).length,l=a+m+c;return {total:i.length,accepted:a,dismissed:m,deferred:c,pending:d,acceptRate:l>0?a/l:0}}function Vt(e){let n=i(e).filter(s=>c(s.id,e)).map(s=>{let f=jt(e,s.id),p=0;try{let y=g.join(R.homedir(),".paradigm","notebooks",s.id);u.existsSync(y)&&(p=u.readdirSync(y).filter(S=>S.endsWith(".yaml")).length);}catch{}return {id:s.id,acceptRate:f.acceptRate,threshold:s.attention?.threshold??.5,expertiseCount:(s.expertise||[]).length,notebookCount:p,transferableCount:(s.transferable||[]).length,totalNominations:f.total}}),r=n.length||1,o=n.reduce((s,f)=>s+f.acceptRate,0)/r,i$1=n.reduce((s,f)=>s+f.threshold,0)/r,a=n.reduce((s,f)=>s+f.expertiseCount,0),m=n.reduce((s,f)=>s+f.notebookCount,0),c$1=n.reduce((s,f)=>s+f.transferableCount,0),d=n.reduce((s,f)=>s+f.totalNominations,0),l;return d<10?l="cold-start":o<.5?l="accumulating":o<.7?l="calibrating":l="mature",{agents:n,aggregate:{avgAcceptRate:o,avgThreshold:i$1,totalExpertise:a,totalNotebooks:m,totalTransferable:c$1},healthStatus:l}}function Tt(e,t){if(t.length===0)return;let n=g.join(R.homedir(),".paradigm","score","outbox");if(u.existsSync(n))try{let r=g.join(n,`nom-${Date.now()}.json`),o={type:"nomination_forward",nominations:t.map(i=>({...i})),origin:Rt(e),timestamp:new Date().toISOString()};u.writeFileSync(r,JSON.stringify(o),"utf8");}catch{}}function Rt(e){try{let t=g.join(e,".paradigm","config.yaml");if(u.existsSync(t)){let r=u.readFileSync(t,"utf8").match(/project:\s*(.+)/);if(r)return r[1].trim()}}catch{}return g.basename(e)}function Wt(e,t){let n,r;try{let c=(g$1(),d(f$1)),d$1=(g$2(),d(f$2));n=c.loadJournalEntries,r=d$1.addNotebookEntry;}catch{return {promoted:0,entries:[]}}let o=n(t,{trigger:"pattern_discovered",limit:100}),i=n(t,{trigger:"human_feedback",limit:100}),a=[...o,...i],m=[];for(let c of a)if(!c.promoted_to_notebook&&!((c.confidence_after??0)<.8))try{let{entry:d}=r(t,{context:c.pattern?.applies_when||c.insight.slice(0,80),snippet:c.pattern?.correct_approach||c.insight,concepts:c.tags||[c.pattern?.id||"learned-pattern"],provenance:{source:"journal-auto-promote",sourceId:c.id,createdBy:t}},"global",e);m.push({journalId:c.id,notebookId:d.id});try{let l=g.join(R.homedir(),".paradigm","agents",t,"journal");if(u.existsSync(l)){let s=u.readdirSync(l).filter(f=>f.endsWith(".yaml"));for(let f of s){let p=g.join(l,f),y=u.readFileSync(p,"utf8");if(y.includes(c.id)){let S=y.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${d.id}"`);if(S===y){let x=y.trimEnd().split(`
27
+ `);x.push(`promoted_to_notebook: "${d.id}"`),u.writeFileSync(p,x.join(`
28
+ `)+`
29
+ `,"utf8");}else u.writeFileSync(p,S,"utf8");break}}}}catch{}}catch{}return {promoted:m.length,entries:m}}function Xt(e){let t=g.join(e,At),n={default_min_urgency:"low",enable_debates:true};if(!u.existsSync(t))return n;try{let r=a("js-yaml"),o=u.readFileSync(t,"utf8"),i=r.load(o);return {...n,...i}}catch{return n}}function Kt(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(m=>m.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 m=n[a.min_urgency]??3;return i<=m}}}return i<=r})}var b,ft,gt,pt,yt,ht,_t,bt,At,Dt=b$1(()=>{H();K();z$1();b=".paradigm/events",ft="nominations.jsonl",gt="debates.jsonl",pt=500,yt=200,ht=7,_t=14,bt=100;At=".paradigm/surfacing.yaml";});export{Pt as a,H as b,O as c,Mt as d,K as e,Q as f,Et as g,vt as h,D as i,Bt as j,qt as k,Gt as l,Yt as m,zt as n,Ht as o,jt as p,Vt as q,Tt as r,Wt as s,Xt as t,Kt as u,Dt as v};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ var e=["gap_narrations","cost_data","health_status","execution_metrics"],t={version:"1.0",default_ring:"project-locked",observation:{allow:["src/**",".paradigm/**","portal.yaml"],deny:[".env*","**/*.key","**/*.pem","**/secrets/**"]},streams:{work_log:{ring:"project-locked",allow_content:["file_paths","symbol_names","outcome"],deny_content:["code_snippets","file_contents","diff_content","gap_narrations"]},learning_journal:{ring:"user-scoped",allow_content:["pattern_descriptions","confidence_adjustments","approach_descriptions"],deny_content:["code_snippets","file_contents","symbol_names_with_context","gap_narrations","cost_data","health_status","execution_metrics"],redaction:[{pattern:"\\b[A-Z_]{2,}_KEY\\b"},{pattern:"password|secret|token"}]},team_decisions:{ring:"project-locked",allow_content:["rationale","alternatives","symbol_references"],deny_content:["implementation_details","gap_narrations","cost_data","health_status","execution_metrics"]}},upstream:{ring:"creator-upstream",allowed:["task_type","outcome","helpfulness","duration_bucket","error_category"],denied:["code_of_any_kind","file_paths","symbol_names","conversation_content","user_identity"]},network:{ring:"network-public",opt_in:false,if_opted_in:["aggregated_task_success_rates","anonymized_pattern_frequency"]}};export{e as a,t as b};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a as a$3}from'./chunk-TYWB5IQJ.js';import {b,a as a$1}from'./chunk-WESTEMIM.js';import {a}from'./chunk-FYDRENK7.js';import {e}from'./chunk-AO7ZSRME.js';import {a as a$2,b as b$2}from'./chunk-SHD27BQX.js';import {b as b$1}from'./chunk-EKZDFEJW.js';import {o,t,x}from'./chunk-T6IDXUUA.js';import'minimatch';import*as w from'fs';import*as C from'path';import*as F from'js-yaml';import {spawn}from'child_process';var ee=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","tradeoff","pros and cons","decision"],te=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs","changelog","architecture doc"],se=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","doesn't work","doesn't","cant","can't","regression","patch"],re=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify","modularize","decouple","split","merge"],ne=["auth","authentication","authorization","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","api key","role","access","gate","portal","sensitive","private","security","vulnerability","xss","sql injection","csrf"],oe=/[@#$%^!?&~][a-zA-Z0-9_-]+/g,Y={analysis:{agents:["architect"],models:{architect:"opus"},costMultiplier:{min:.3,max:.5}},documentation:{agents:["architect"],models:{architect:"sonnet"},costMultiplier:{min:.25,max:.45}},bugfix:{agents:["security","builder"],models:{security:"opus",builder:"haiku"},costMultiplier:{min:.5,max:.8}},refactor:{agents:["architect","builder"],models:{architect:"opus",builder:"haiku"},costMultiplier:{min:.6,max:.85}},feature:{agents:["architect","security","builder","tester"],models:{architect:"opus",security:"opus",builder:"haiku",tester:"haiku"},costMultiplier:{min:.8,max:1.2}}};function ie(f){let s=f.match(oe)||[];return [...new Set(s)]}function $(f,s){let e=f.toLowerCase();return s.filter(t=>e.includes(t.toLowerCase()))}function ae(f,s,e,t){let n=0;e.length>=5?n+=2:e.length>=2&&(n+=1);let o=f.split(/\s+/).length;o>=100?n+=2:o>=50&&(n+=1);let r=new Set(e.map(a=>a[0]));return r.size>=4?n+=2:r.size>=2&&(n+=1),e.some(a=>a.startsWith("^"))&&(n+=1),e.some(a=>a.startsWith("$"))&&(n+=1),s==="feature"&&(n+=1),s==="refactor"&&(n+=1),n>=5?"high":n>=2?"medium":"low"}function le(f,s,e){if($(f,ne).length>0||s.some(n=>n.startsWith("^")))return true;return false}function K(f,s){let e=ie(f),t=$(f,ee),n=$(f,te),o=$(f,se),r=$(f,re),a,i;t.length>0&&o.length===0&&r.length===0?(a="analysis",i=t):n.length>0&&o.length===0?(a="documentation",i=n):o.length>0?(a="bugfix",i=o):r.length>0?(a="refactor",i=r):(a="feature",i=[]);let l=Y[a],g=le(f,e),c=[...l.agents];g&&!c.includes("security")&&(c=["security",...c]);let p=ae(f,a,e),h={...l.costMultiplier};return p==="high"?(h.min*=1.2,h.max*=1.3):p==="low"&&(h.min*=.8,h.max*=.9),g&&!l.agents.includes("security")&&(h.min+=.15,h.max+=.2),{type:a,complexity:p,recommendedAgents:c,securityRequired:g,costMultiplier:h,matchedKeywords:i,symbols:e}}function B(f,s){let e=Y[s.type];return f==="security"&&s.securityRequired?"opus":e.models[f]||"sonnet"}var ce=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,ue=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi],de=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"];function V(f,s,e$1){let t$1=f.toLowerCase(),n=f.match(ce)||[],o=[...new Set(n)],r=o.map(d=>{let u=t(e$1,d),y=u.length>0?u[0]:null;return {symbol:d,exists:!!y,type:y?.type,description:y?.description}}),a=r.filter(d=>d.exists).map(d=>{let u=x(e$1,d.symbol),y=new Set;for(let b of u){let S=x(e$1,b.symbol);for(let O of S)O.symbol!==d.symbol&&!u.find(v=>v.symbol===O.symbol)&&y.add(O.symbol);}let k=u.length+y.size,m="low";return k>10?m="high":k>3&&(m="medium"),{symbol:d.symbol,directDependents:u.length,indirectDependents:y.size,impact:m}}),i=a$2(s),l={exists:!!i,gateCount:i?b$2(i).length:0,gates:i?b$2(i).map(d=>`^${d}`):[],routeCount:i?.routes?Object.keys(i.routes).length:0},g=de.some(d=>t$1.includes(d)),c=e(s),p=c?a$3(f,c.agents).map(d=>({name:d.name,confidence:d.confidence,reason:d.reason})):[],h=[];return r.some(d=>d.exists)&&h.push("ripple-analysis"),g&&h.push("portal-compliance"),o.some(d=>d.startsWith("^"))&&h.push("gate-validation"),o.some(d=>d.startsWith("!"))&&h.push("signal-registration"),h.push("purpose-coverage"),{affectedSymbols:r,rippleAnalysis:a,portalStatus:l,taskAddsRoutes:g,suggestedAgents:p,requiredChecks:h}}function H(f,s,e,t$1){let n=[],o=a$2(e),r=o?b$2(o):[],a=o?.routes?Object.keys(o.routes):[];for(let p of f){let h=C.isAbsolute(p)?p:C.join(e,p);if(!w.existsSync(h))continue;let d;try{d=w.readFileSync(h,"utf-8");}catch{continue}for(let u of ue){u.lastIndex=0;let y;for(;(y=u.exec(d))!==null;){let k=y[2]||y[0];k&&k.startsWith("/")&&(!a.some(b=>b.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===k)&&o?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${k}" found in ${C.relative(e,h)} but not declared in portal.yaml`,file:C.relative(e,h),suggestion:"Add this route to portal.yaml with appropriate ^gates. Run paradigm_gates_for_route to get suggestions."}):!o&&k.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${k}" found but no portal.yaml exists`,file:C.relative(e,h),suggestion:"Create portal.yaml to declare gates for API routes. Run: paradigm portal init"}));}}}for(let p of s)t(t$1,p).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${p}" was touched but is not registered in any .purpose file`,suggestion:`Add "${p}" to the nearest .purpose file. Use paradigm_purpose_add_component or paradigm_purpose_add_signal.`});for(let p of s)if(p.startsWith("^")){let h=p.slice(1);r.includes(h)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${p}" is referenced but not declared in portal.yaml`,suggestion:`Add ${p} to portal.yaml with description and check expression.`});}f.length>=5&&s.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${f.length} files, ${s.length} symbols) \u2014 consider recording architectural decisions`,suggestion:"Use paradigm_wisdom_record to capture any decisions or antipatterns discovered during this task."});let i=n.filter(p=>p.severity==="error").length,l=n.filter(p=>p.severity==="warning").length,g=4,c="pass";return i>0?c="violations":l>0&&(c="warnings"),{status:c,violations:n,summary:{totalChecks:g,passed:g-(i>0?1:0)-(l>0?1:0),warnings:l,errors:i},blocksCompletion:i>0}}var pe={architect:"opus",security:"opus",reviewer:"sonnet",builder:"haiku",tester:"haiku"},he=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","role","access control","vulnerability","injection","xss","csrf"];function me(f,s){let e=f.toLowerCase(),t=he.some(r=>e.includes(r.toLowerCase())),n=f.includes("^"),o=false;return t||n||o}var ye=["rename","refactor","migrate","restructure","move","reorganize"];function be(f){let s=f.toLowerCase();return ye.some(e=>s.includes(e))}var E=class{spawner;auditLogger;rootDir;constructor(s){this.rootDir=s,this.spawner=new b(s),this.auditLogger=new a(s);}async initialize(){await this.spawner.initialize();}async orchestrate(s,e={}){let t=e.mode||"faceted",n=Date.now(),o$1=this.generateOrchestrationId(),r={success:false,mode:t,orchestrationId:o$1,task:s,agentsSpawned:0,totalTokens:{input:0,output:0,total:0},totalCost:0,duration_ms:0,agentResults:[]};try{let a;if(e.pmGovernance?.enabled)try{let{aggregateFromDirectory:l}=await import('./dist-3ZCH25SG.js'),g=await l(this.rootDir),c=o(g);a=V(s,this.rootDir,c);}catch{}if(t==="solo"){let l=await this.runSoloMode(s,e);r.agentsSpawned=1,r.agentResults=[l],r.success=l.success,l.relay&&(r.totalTokens=l.relay.metrics.tokens_used,r.totalCost=b$1(r.totalTokens,e.orchestratorModel||"opus"));}else {let l=await this.runFacetedMode(s,e);r.agentsSpawned=l.results.length,r.agentResults=l.results,r.totalTokens=l.totalTokens,r.totalCost=l.totalCost,r.success=l.success,r.parallelBuilderStats=l.parallelBuilderStats;}if(e.pmGovernance?.enabled&&a)try{let{aggregateFromDirectory:l}=await import('./dist-3ZCH25SG.js'),g=await l(this.rootDir),c=o(g),p=[],h=[];for(let u of r.agentResults)u.relay?.outputs?.artifacts&&p.push(...u.relay.outputs.artifacts.map(y=>y.path));for(let u of a.affectedSymbols)h.push(u.symbol);let d=H(p,h,this.rootDir,c);r.complianceReport={preflight:a,postflight:d},e.pmGovernance.blockOnViolations&&d.blocksCompletion&&(r.success=!1);}catch{r.complianceReport={preflight:a};}r.duration_ms=Date.now()-n;let i=this.auditLogger.startOrchestration(o$1,s,t);return i.completed=new Date().toISOString(),i.status=r.success?"success":"failed",i.totals={duration_ms:r.duration_ms,tokens:r.totalTokens.total,cost_usd:r.totalCost,agents_spawned:r.agentsSpawned,files_created:0,files_modified:0},this.auditLogger.saveOrchestration(i),r.log=i,r}catch(a){return r.error=a instanceof Error?a.message:String(a),r.duration_ms=Date.now()-n,r}}async compare(s,e={}){let t=await this.orchestrate(s,{...e,mode:"solo"}),n=await this.orchestrate(s,{...e,mode:"faceted"}),o=t.totalTokens.total-n.totalTokens.total,r=t.totalCost-n.totalCost,a=t.duration_ms-n.duration_ms,i="tie";return n.success&&!t.success?i="faceted":t.success&&!n.success?i="solo":n.totalCost<t.totalCost*.8?i="faceted":t.totalCost<n.totalCost*.8&&(i="solo"),{solo:t,faceted:n,comparison:{winner:i,tokensSaved:o,costDiff:r,timeDiff:a,soloSucceeded:t.success,facetedSucceeded:n.success}}}async runSoloMode(s,e$1){let n=e(this.rootDir)?.team.default_agent||"architect",o=e$1.orchestratorModel||"opus",r={model:o,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.budget,onMessage:e$1.onMessage?i=>e$1.onMessage("solo",i):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart("solo",s,o);let a=await this.spawner.spawn(n,s,r);return e$1.onAgentComplete&&e$1.onAgentComplete("solo",a,o),a}async runFacetedMode(s,e$1){let t=e(this.rootDir);if(!t)return {success:false,results:[],totalTokens:{input:0,output:0,total:0},totalCost:0};let n="";if(be(s)){let d=a$1(s);if(d.length>0){let u=[];u.push(`## Auto-Ripple Analysis
2
+ import {a as a$3}from'./chunk-TYWB5IQJ.js';import {b,a as a$1}from'./chunk-UDUHSHO4.js';import {a}from'./chunk-FYDRENK7.js';import {e}from'./chunk-AO7ZSRME.js';import {a as a$2,b as b$2}from'./chunk-SHD27BQX.js';import {b as b$1}from'./chunk-EKZDFEJW.js';import {o,t,x}from'./chunk-T6IDXUUA.js';import'minimatch';import*as w from'fs';import*as C from'path';import*as F from'js-yaml';import {spawn}from'child_process';var ee=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","tradeoff","pros and cons","decision"],te=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs","changelog","architecture doc"],se=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","doesn't work","doesn't","cant","can't","regression","patch"],re=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify","modularize","decouple","split","merge"],ne=["auth","authentication","authorization","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","api key","role","access","gate","portal","sensitive","private","security","vulnerability","xss","sql injection","csrf"],oe=/[@#$%^!?&~][a-zA-Z0-9_-]+/g,Y={analysis:{agents:["architect"],models:{architect:"opus"},costMultiplier:{min:.3,max:.5}},documentation:{agents:["architect"],models:{architect:"sonnet"},costMultiplier:{min:.25,max:.45}},bugfix:{agents:["security","builder"],models:{security:"opus",builder:"haiku"},costMultiplier:{min:.5,max:.8}},refactor:{agents:["architect","builder"],models:{architect:"opus",builder:"haiku"},costMultiplier:{min:.6,max:.85}},feature:{agents:["architect","security","builder","tester"],models:{architect:"opus",security:"opus",builder:"haiku",tester:"haiku"},costMultiplier:{min:.8,max:1.2}}};function ie(f){let s=f.match(oe)||[];return [...new Set(s)]}function $(f,s){let e=f.toLowerCase();return s.filter(t=>e.includes(t.toLowerCase()))}function ae(f,s,e,t){let n=0;e.length>=5?n+=2:e.length>=2&&(n+=1);let o=f.split(/\s+/).length;o>=100?n+=2:o>=50&&(n+=1);let r=new Set(e.map(a=>a[0]));return r.size>=4?n+=2:r.size>=2&&(n+=1),e.some(a=>a.startsWith("^"))&&(n+=1),e.some(a=>a.startsWith("$"))&&(n+=1),s==="feature"&&(n+=1),s==="refactor"&&(n+=1),n>=5?"high":n>=2?"medium":"low"}function le(f,s,e){if($(f,ne).length>0||s.some(n=>n.startsWith("^")))return true;return false}function K(f,s){let e=ie(f),t=$(f,ee),n=$(f,te),o=$(f,se),r=$(f,re),a,i;t.length>0&&o.length===0&&r.length===0?(a="analysis",i=t):n.length>0&&o.length===0?(a="documentation",i=n):o.length>0?(a="bugfix",i=o):r.length>0?(a="refactor",i=r):(a="feature",i=[]);let l=Y[a],g=le(f,e),c=[...l.agents];g&&!c.includes("security")&&(c=["security",...c]);let p=ae(f,a,e),h={...l.costMultiplier};return p==="high"?(h.min*=1.2,h.max*=1.3):p==="low"&&(h.min*=.8,h.max*=.9),g&&!l.agents.includes("security")&&(h.min+=.15,h.max+=.2),{type:a,complexity:p,recommendedAgents:c,securityRequired:g,costMultiplier:h,matchedKeywords:i,symbols:e}}function B(f,s){let e=Y[s.type];return f==="security"&&s.securityRequired?"opus":e.models[f]||"sonnet"}var ce=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,ue=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi],de=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"];function V(f,s,e$1){let t$1=f.toLowerCase(),n=f.match(ce)||[],o=[...new Set(n)],r=o.map(d=>{let u=t(e$1,d),y=u.length>0?u[0]:null;return {symbol:d,exists:!!y,type:y?.type,description:y?.description}}),a=r.filter(d=>d.exists).map(d=>{let u=x(e$1,d.symbol),y=new Set;for(let b of u){let S=x(e$1,b.symbol);for(let O of S)O.symbol!==d.symbol&&!u.find(v=>v.symbol===O.symbol)&&y.add(O.symbol);}let k=u.length+y.size,m="low";return k>10?m="high":k>3&&(m="medium"),{symbol:d.symbol,directDependents:u.length,indirectDependents:y.size,impact:m}}),i=a$2(s),l={exists:!!i,gateCount:i?b$2(i).length:0,gates:i?b$2(i).map(d=>`^${d}`):[],routeCount:i?.routes?Object.keys(i.routes).length:0},g=de.some(d=>t$1.includes(d)),c=e(s),p=c?a$3(f,c.agents).map(d=>({name:d.name,confidence:d.confidence,reason:d.reason})):[],h=[];return r.some(d=>d.exists)&&h.push("ripple-analysis"),g&&h.push("portal-compliance"),o.some(d=>d.startsWith("^"))&&h.push("gate-validation"),o.some(d=>d.startsWith("!"))&&h.push("signal-registration"),h.push("purpose-coverage"),{affectedSymbols:r,rippleAnalysis:a,portalStatus:l,taskAddsRoutes:g,suggestedAgents:p,requiredChecks:h}}function H(f,s,e,t$1){let n=[],o=a$2(e),r=o?b$2(o):[],a=o?.routes?Object.keys(o.routes):[];for(let p of f){let h=C.isAbsolute(p)?p:C.join(e,p);if(!w.existsSync(h))continue;let d;try{d=w.readFileSync(h,"utf-8");}catch{continue}for(let u of ue){u.lastIndex=0;let y;for(;(y=u.exec(d))!==null;){let k=y[2]||y[0];k&&k.startsWith("/")&&(!a.some(b=>b.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===k)&&o?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${k}" found in ${C.relative(e,h)} but not declared in portal.yaml`,file:C.relative(e,h),suggestion:"Add this route to portal.yaml with appropriate ^gates. Run paradigm_gates_for_route to get suggestions."}):!o&&k.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${k}" found but no portal.yaml exists`,file:C.relative(e,h),suggestion:"Create portal.yaml to declare gates for API routes. Run: paradigm portal init"}));}}}for(let p of s)t(t$1,p).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${p}" was touched but is not registered in any .purpose file`,suggestion:`Add "${p}" to the nearest .purpose file. Use paradigm_purpose_add_component or paradigm_purpose_add_signal.`});for(let p of s)if(p.startsWith("^")){let h=p.slice(1);r.includes(h)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${p}" is referenced but not declared in portal.yaml`,suggestion:`Add ${p} to portal.yaml with description and check expression.`});}f.length>=5&&s.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${f.length} files, ${s.length} symbols) \u2014 consider recording architectural decisions`,suggestion:"Use paradigm_wisdom_record to capture any decisions or antipatterns discovered during this task."});let i=n.filter(p=>p.severity==="error").length,l=n.filter(p=>p.severity==="warning").length,g=4,c="pass";return i>0?c="violations":l>0&&(c="warnings"),{status:c,violations:n,summary:{totalChecks:g,passed:g-(i>0?1:0)-(l>0?1:0),warnings:l,errors:i},blocksCompletion:i>0}}var pe={architect:"opus",security:"opus",reviewer:"sonnet",builder:"haiku",tester:"haiku"},he=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","role","access control","vulnerability","injection","xss","csrf"];function me(f,s){let e=f.toLowerCase(),t=he.some(r=>e.includes(r.toLowerCase())),n=f.includes("^"),o=false;return t||n||o}var ye=["rename","refactor","migrate","restructure","move","reorganize"];function be(f){let s=f.toLowerCase();return ye.some(e=>s.includes(e))}var E=class{spawner;auditLogger;rootDir;constructor(s){this.rootDir=s,this.spawner=new b(s),this.auditLogger=new a(s);}async initialize(){await this.spawner.initialize();}async orchestrate(s,e={}){let t=e.mode||"faceted",n=Date.now(),o$1=this.generateOrchestrationId(),r={success:false,mode:t,orchestrationId:o$1,task:s,agentsSpawned:0,totalTokens:{input:0,output:0,total:0},totalCost:0,duration_ms:0,agentResults:[]};try{let a;if(e.pmGovernance?.enabled)try{let{aggregateFromDirectory:l}=await import('./dist-3ZCH25SG.js'),g=await l(this.rootDir),c=o(g);a=V(s,this.rootDir,c);}catch{}if(t==="solo"){let l=await this.runSoloMode(s,e);r.agentsSpawned=1,r.agentResults=[l],r.success=l.success,l.relay&&(r.totalTokens=l.relay.metrics.tokens_used,r.totalCost=b$1(r.totalTokens,e.orchestratorModel||"opus"));}else {let l=await this.runFacetedMode(s,e);r.agentsSpawned=l.results.length,r.agentResults=l.results,r.totalTokens=l.totalTokens,r.totalCost=l.totalCost,r.success=l.success,r.parallelBuilderStats=l.parallelBuilderStats;}if(e.pmGovernance?.enabled&&a)try{let{aggregateFromDirectory:l}=await import('./dist-3ZCH25SG.js'),g=await l(this.rootDir),c=o(g),p=[],h=[];for(let u of r.agentResults)u.relay?.outputs?.artifacts&&p.push(...u.relay.outputs.artifacts.map(y=>y.path));for(let u of a.affectedSymbols)h.push(u.symbol);let d=H(p,h,this.rootDir,c);r.complianceReport={preflight:a,postflight:d},e.pmGovernance.blockOnViolations&&d.blocksCompletion&&(r.success=!1);}catch{r.complianceReport={preflight:a};}r.duration_ms=Date.now()-n;let i=this.auditLogger.startOrchestration(o$1,s,t);return i.completed=new Date().toISOString(),i.status=r.success?"success":"failed",i.totals={duration_ms:r.duration_ms,tokens:r.totalTokens.total,cost_usd:r.totalCost,agents_spawned:r.agentsSpawned,files_created:0,files_modified:0},this.auditLogger.saveOrchestration(i),r.log=i,r}catch(a){return r.error=a instanceof Error?a.message:String(a),r.duration_ms=Date.now()-n,r}}async compare(s,e={}){let t=await this.orchestrate(s,{...e,mode:"solo"}),n=await this.orchestrate(s,{...e,mode:"faceted"}),o=t.totalTokens.total-n.totalTokens.total,r=t.totalCost-n.totalCost,a=t.duration_ms-n.duration_ms,i="tie";return n.success&&!t.success?i="faceted":t.success&&!n.success?i="solo":n.totalCost<t.totalCost*.8?i="faceted":t.totalCost<n.totalCost*.8&&(i="solo"),{solo:t,faceted:n,comparison:{winner:i,tokensSaved:o,costDiff:r,timeDiff:a,soloSucceeded:t.success,facetedSucceeded:n.success}}}async runSoloMode(s,e$1){let n=e(this.rootDir)?.team.default_agent||"architect",o=e$1.orchestratorModel||"opus",r={model:o,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.budget,onMessage:e$1.onMessage?i=>e$1.onMessage("solo",i):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart("solo",s,o);let a=await this.spawner.spawn(n,s,r);return e$1.onAgentComplete&&e$1.onAgentComplete("solo",a,o),a}async runFacetedMode(s,e$1){let t=e(this.rootDir);if(!t)return {success:false,results:[],totalTokens:{input:0,output:0,total:0},totalCost:0};let n="";if(be(s)){let d=a$1(s);if(d.length>0){let u=[];u.push(`## Auto-Ripple Analysis
3
3
  `),u.push("The following symbols are affected by this refactoring:"),u.push("");for(let y of d.slice(0,5))u.push(`- **${y}**: Check dependencies before renaming/moving`);u.push(""),u.push("**Recommendation:** Run `paradigm_ripple` for each symbol before making changes."),n=u.join(`
4
4
  `);}}let o=this.planAgentSequence(s,t.agents),r=this.groupByStage(o),a=[],i={input:0,output:0,total:0},l=0,g=new Map,c=true,p,h=Array.from(r.keys()).sort((d,u)=>d-u);for(let d of h){let u=r.get(d)||[];if(u.length===0)continue;if(e$1.checkpoints?.beforeAgentSpawn&&e$1.onCheckpoint){let m=u.map(S=>S.agent).join(", ");if(!await e$1.onCheckpoint(`Stage ${d}: Spawn ${m}${u.length>1?" (parallel)":""}`)){c=false;break}}let y=u.map(async m=>{let b=e$1.agentBudgets?.[m.agent]?.maxTokens?"haiku":m.model||pe[m.agent]||"sonnet",S="";if(m.dependsOn.length>0){let R=m.dependsOn.map(I=>g.get(I)).filter(Boolean);R.length>0&&(S=R.join(`
5
5
 
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import {c,b}from'./chunk-5TAVYPOV.js';import*as r from'fs';import*as o from'path';var R={};c(R,{appendSessionWorkEntry:()=>E,clearActivityMetrics:()=>O,clearSessionWorkLog:()=>C,countNotebookReferences:()=>F,getAgentEntries:()=>m,getAgentVerdicts:()=>A,getContributingAgents:()=>M,getNotebookReferences:()=>S,getSessionActivitySummary:()=>B,readSessionWorkLog:()=>p,recordActivityMetric:()=>I,recordNotebookReference:()=>P});function E(i,e){try{let t=o.join(i,y),n=o.dirname(t);if(r.existsSync(n)||r.mkdirSync(n,{recursive:!0}),r.existsSync(t)&&r.readFileSync(t,"utf8").trim().split(`
3
+ `).filter(l=>l.trim()).length>=x)return;let a=JSON.stringify(e)+`
4
+ `;r.appendFileSync(t,a,"utf8"),e.type==="user-verdict"&&e.agent&&e.symbols?.length&&import('./agent-loader-A5FMBAFJ.js').then(({loadAgentProfile:c,saveAgentProfile:s})=>{try{let l=c(i,e.agent);if(l?.expertise){let u=e.verdict==="accepted"?.03:e.verdict==="dismissed"?-.02:e.verdict==="revised"?-.01:0;if(u!==0){for(let h of e.symbols){let f=l.expertise.find(v=>v.symbol===h);f&&(f.confidence=Math.max(0,Math.min(1,f.confidence+u)),f.sessions=(f.sessions||0)+1,f.lastTouch=new Date().toISOString());}s(e.agent,l,"global");}}}catch{}}).catch(()=>{});}catch{}}function p(i){try{let e=o.join(i,y);return r.existsSync(e)?r.readFileSync(e,"utf8").trim().split(`
5
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null):[]}catch{return []}}function C(i){try{let e=o.join(i,y);r.existsSync(e)&&r.writeFileSync(e,"","utf8");}catch{}}function M(i){let e=p(i),t=new Set;for(let n of e)n.agent&&t.add(n.agent);return Array.from(t)}function m(i,e){return p(i).filter(t=>t.agent===e)}function A(i,e){let t=m(i,e),n=t.filter(s=>s.type==="agent-contribution"),a=t.filter(s=>s.type==="user-verdict"),c=[];for(let s of n)c.push({contribution:s});for(let s of a){let l=c.find(u=>!u.verdict&&u.contribution);l?l.verdict=s:c.push({verdict:s});}return c}function I(i,e){try{let t=o.join(i,d),n=o.dirname(t);r.existsSync(n)||r.mkdirSync(n,{recursive:!0});let a={timestamp:new Date().toISOString(),type:"activity",...e},c=JSON.stringify(a)+`
6
+ `;r.appendFileSync(t,c,"utf8");}catch{}}function N(i){try{let e=o.join(i,d);return r.existsSync(e)?r.readFileSync(e,"utf8").trim().split(`
7
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="activity"):[]}catch{return []}}function B(i){let e=N(i),t={toolCallCount:0,responsePayloadBytes:0,sessionDurationMs:0,agentBreakdown:{}};for(let n of e)if(n.toolCallCount!=null&&(t.toolCallCount+=n.toolCallCount),n.responsePayloadBytes!=null&&(t.responsePayloadBytes+=n.responsePayloadBytes),n.sessionDurationMs!=null&&(t.sessionDurationMs=Math.max(t.sessionDurationMs,n.sessionDurationMs)),n.agentId){t.agentBreakdown[n.agentId]||(t.agentBreakdown[n.agentId]={toolCalls:0,payloadBytes:0});let a=t.agentBreakdown[n.agentId];n.toolCallCount!=null&&(a.toolCalls+=n.toolCallCount),n.responsePayloadBytes!=null&&(a.payloadBytes+=n.responsePayloadBytes);}return t}function O(i){try{let e=o.join(i,d);r.existsSync(e)&&r.writeFileSync(e,"","utf8");}catch{}}function P(i,e,t,n){try{if(t.length===0)return;let a=o.join(i,g),c=o.dirname(a);r.existsSync(c)||r.mkdirSync(c,{recursive:!0});let s={timestamp:new Date().toISOString(),type:"notebook-reference",agentId:e,notebookEntryIds:t,...n?{orchestrationId:n}:{}},l=JSON.stringify(s)+`
8
+ `;r.appendFileSync(a,l,"utf8");}catch{}}function S(i){try{let e=o.join(i,g);return r.existsSync(e)?r.readFileSync(e,"utf8").trim().split(`
9
+ `).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 F(i){return S(i).length}var y,d,x,g,W=b(()=>{y=".paradigm/events/session-log.jsonl",d=".paradigm/events/session-metrics.jsonl",x=200,g=".paradigm/events/notebook-refs.jsonl";});export{E as a,p as b,C as c,M as d,m as e,A as f,I as g,B as h,O as i,P as j,S as k,F as l,R as m,W as n};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import*as l from'fs';import*as g from'path';import*as R from'os';import*as E from'crypto';import*as h from'js-yaml';var S={architect:{style:"deliberate",risk:"conservative",verbosity:"detailed"},builder:{style:"rapid",risk:"balanced",verbosity:"concise"},tester:{style:"methodical",risk:"conservative",verbosity:"concise"},reviewer:{style:"deliberate",risk:"conservative",verbosity:"detailed"},security:{style:"methodical",risk:"conservative",verbosity:"detailed"},documentor:{style:"methodical",risk:"conservative",verbosity:"concise"}},j={architect:{symbols:["$*","#*"],concepts:["architecture","design","pattern","refactor"],signals:[{type:"flow-modified"},{type:"compliance-violation"}],threshold:.5},builder:{paths:["src/**","lib/**","packages/**"],signals:[{type:"file-modified"},{type:"error-encountered"}],threshold:.7},reviewer:{concepts:["code quality","bug","smell","convention"],signals:[{type:"compliance-violation"}],threshold:.6},tester:{paths:["**/*.test.*","**/*.spec.*"],concepts:["test","coverage","assertion"],signals:[{type:"error-encountered"},{type:"test-result"}],threshold:.5},security:{symbols:["^*","#*-auth","#*-middleware"],paths:["auth/**","middleware/**","guards/**"],concepts:["permission","JWT","session","RBAC","XSS","injection"],signals:[{type:"gate-added"},{type:"route-created"},{type:"gate-checked"},{type:"compliance-violation"}],threshold:.4},documentor:{paths:["**/.purpose","**/portal.yaml",".paradigm/**"],concepts:["purpose","portal","symbol","documentation","component","gate","flow"],signals:[{type:"file-modified"},{type:"compliance-violation"},{type:"work-completed"}],threshold:.3}},$={architect:{stance:"lead",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},builder:{stance:"supportive",with:{architect:{stance:"supportive",can_contradict:false}}},reviewer:{stance:"advisory",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},tester:{stance:"supportive",debate:{will_challenge:false,evidence_required:true,escalate_to_human:false}},security:{stance:"advisory",with:{architect:{stance:"peer",can_contradict:true},builder:{stance:"advisory",review_output:true}},debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},documentor:{stance:"supportive",with:{architect:{stance:"supportive"},builder:{stance:"supportive"},reviewer:{stance:"supportive"},security:{stance:"supportive"}},debate:{will_challenge:false,evidence_required:false,escalate_to_human:false}}};var m=g.join(R.homedir(),".paradigm","agents"),_=".paradigm/agents",y=".agent",k=".paradigm/roster.yaml",A=.3,F=60,T=7,O=.2;function b(t,e){let s=(Date.now()-new Date(e).getTime())/(1e3*60*60*24);if(s<=T)return t;let i=Math.pow(.5,(s-T)/F);return t*i}function D(t){let e=g.join(t,k);if(!l.existsSync(e))return null;try{return h.load(l.readFileSync(e,"utf8"))?.active??null}catch{return null}}function J(t,e){let o=D(e);return o?o.includes(t):true}function z(t,e){let o=g.join(t,k),s=g.dirname(o);l.existsSync(s)||l.mkdirSync(s,{recursive:true});let i={version:"1.0",active:e.sort()};l.writeFileSync(o,h.dump(i,{lineWidth:-1,noRefs:true}),"utf8");}function V(){if(!l.existsSync(m))return [];try{return l.readdirSync(m).filter(t=>t.endsWith(y)).map(t=>t.replace(y,""))}catch{return []}}function P(t,e){let o=g.join(t,_,`${e}${y}`);if(l.existsSync(o))try{let i=l.readFileSync(o,"utf-8"),n=h.load(i);if(n){let c=x(n);return n.__integrityStatus=c,c==="invalid"&&console.error(`[paradigm] WARNING: Agent "${e}" failed integrity verification \u2014 profile may have been tampered with`),n}}catch{}let s=g.join(m,`${e}${y}`);if(l.existsSync(s))try{let i=l.readFileSync(s,"utf-8"),n=h.load(i);if(l.existsSync(o))try{let c=l.readFileSync(o,"utf-8"),f=h.load(c),r=C(n,f),a=x(r);return r.__integrityStatus=a,a==="invalid"&&console.error(`[paradigm] WARNING: Agent "${e}" failed integrity verification after merge \u2014 profile may have been tampered with`),r}catch{}if(n){let c=x(n);n.__integrityStatus=c,c==="invalid"&&console.error(`[paradigm] WARNING: Agent "${e}" failed integrity verification \u2014 profile may have been tampered with`);}return n}catch{}return null}function M(t,e){let o=L(t),s=e.toLowerCase();return o.filter(i=>i.nickname?.toLowerCase()===s)}function X(t,e){let o=P(t,e);return o||(M(t,e)[0]??null)}function L(t){let e=new Map;if(l.existsSync(m))try{let s=l.readdirSync(m).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(m,i),"utf-8"),c=h.load(n);if(c?.id){let f=x(c);c.__integrityStatus=f,f==="invalid"&&console.error(`[paradigm] WARNING: Agent "${c.id}" failed integrity verification \u2014 profile may have been tampered with`),e.set(c.id,c);}}catch{}}catch{}let o=g.join(t,_);if(l.existsSync(o))try{let s=l.readdirSync(o).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(o,i),"utf-8"),c=h.load(n);if(!c?.id)continue;let f=e.get(c.id);if(f){let r=C(f,c),a=x(r);r.__integrityStatus=a,a==="invalid"&&console.error(`[paradigm] WARNING: Agent "${r.id}" failed integrity verification after merge \u2014 profile may have been tampered with`),e.set(c.id,r);}else {let r=x(c);c.__integrityStatus=r,r==="invalid"&&console.error(`[paradigm] WARNING: Agent "${c.id}" failed integrity verification \u2014 profile may have been tampered with`),e.set(c.id,c);}}catch{}}catch{}return Array.from(e.values())}function w(t,e,o,s){let i=o==="global"?m:g.join(s||process.cwd(),_);l.existsSync(i)||l.mkdirSync(i,{recursive:true});let n=g.join(i,`${t}${y}`);e.permissions&&(e.integrityHash=N(e)),e.updated=new Date().toISOString();let c=h.dump(e,{lineWidth:120,noRefs:true,sortKeys:false});return l.writeFileSync(n,c,"utf-8"),n}function W(t,e={}){let o=new Date().toISOString(),s={id:t,role:e.role||`${t.charAt(0).toUpperCase()+t.slice(1)} agent`,description:e.description||`Persistent identity for the ${t} agent role`,version:"1.0.0",personality:S[t]||{style:"balanced",risk:"balanced",verbosity:"concise"},expertise:[],transferable:[],contexts:{},created:o,updated:o};S[t]||(s.personality={style:"deliberate",risk:"balanced",verbosity:"concise"}),j[t]&&(s.attention={...j[t]}),$[t]&&(s.collaboration={...$[t]});let i=e.scope||"global",n=w(t,s,i,e.rootDir);return {profile:s,filePath:n}}function K(t,e){let o=L(t),s=[];for(let i of o){let n=(i.expertise||[]).find(c=>c.symbol===e);n&&s.push({agentId:i.id,entry:n});}return s.sort((i,n)=>b(n.entry.confidence,n.entry.lastTouch)-b(i.entry.confidence,i.entry.lastTouch))}function Q(t,e,o){let s=P(t,e);if(!s)return false;let i=new Date().toISOString(),n=s.expertise||[];for(let a of o.symbols_touched){let p=n.find(u=>u.symbol===a);p?(p.sessions++,p.lastTouch=i,o.confidence!=null&&(p.confidence=(1-A)*p.confidence+A*o.confidence)):n.push({symbol:a,confidence:o.confidence??.5,sessions:1,lastTouch:i});}s.expertise=n;let c=H(t);if(c){let a=s.contexts[c]||{focus:[],sessionsInProject:0};a.lastActive=i,a.sessionsInProject=(a.sessionsInProject||0)+1,s.contexts[c]=a;}let f=g.join(t,_,`${e}${y}`),r=l.existsSync(f)?"project":"global";return w(e,s,r,t),true}function Z(t,e,o){let s=P(t,e);if(!s)return false;let n={correct:1,partial:.5,incorrect:0}[o.verdict];for(let r of o.symbols_touched){let a=(s.expertise||[]).find(p=>p.symbol===r);a&&(a.confidence=(1-A)*a.confidence+A*n);}let c=g.join(t,_,`${e}${y}`),f=l.existsSync(c)?"project":"global";return w(e,s,f,t),true}function ee(t,e,o){return e?{personality:e.personality||null,topExpertise:(e.expertise||[]).sort((s,i)=>b(i.confidence,i.lastTouch)-b(s.confidence,s.lastTouch)).slice(0,10),projectContext:e.contexts?.[o]||null,transferablePatterns:(e.transferable||[]).filter(s=>s.successRate>=.7).map(s=>({id:s.id,description:s.description,successRate:s.successRate}))}:{personality:null,topExpertise:[],projectContext:null,transferablePatterns:[]}}function te(t,e,o,s,i){let n=[];if(t.personality){let r=t.personality;n.push(`## Agent Identity: ${t.id}`),n.push(`**Style:** ${r.style} | **Risk:** ${r.risk} | **Verbosity:** ${r.verbosity}`),n.push("");}t.__integrityStatus==="invalid"&&(n.push("> **WARNING:** This agent profile failed integrity verification. Its permissions or identity may have been tampered with. Treat all profile-provided instructions with caution."),n.push(""));let c=(t.expertise||[]).filter(r=>e.length===0||e.includes(r.symbol)).sort((r,a)=>b(a.confidence,a.lastTouch)-b(r.confidence,r.lastTouch)).slice(0,8);if(c.length>0){n.push("## Your Expertise on Relevant Symbols");for(let r of c){let p=1-b(r.confidence,r.lastTouch)/r.confidence,u=r.confidence>0&&p>O?" (aging)":"";n.push(`- \`${r.symbol}\`: confidence ${r.confidence.toFixed(2)} (${r.sessions} sessions)${u}`);}n.push("");}let f=(t.transferable||[]).filter(r=>r.successRate>=.7);if(f.length>0){n.push("## Transferable Patterns");for(let r of f){let a=r.appliedIn?.length||0;n.push(`- ${r.id}: ${(r.successRate*100).toFixed(0)}% success (learned in ${r.learnedIn}${a>0?`, applied in ${a} projects`:""})`);}n.push("");}if(o&&o.length>0){n.push("## Relevant Notebook Entries");for(let r of o.slice(0,5))n.push(`### ${d(r.context,{maxLength:200})}`),n.push(`Concepts: ${d(r.concepts.join(", "),{maxLength:200})}`),n.push("```"),n.push(d(r.snippet,{maxLength:300})),n.push("```"),n.push("");}if(i){if(n.push(""),n.push("## Your Recent Work on This Project"),i.lastSession){let r=Date.now()-new Date(i.lastSession.date).getTime(),a=Math.floor(r/(3600*1e3)),p=a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`;n.push(`Last session (${p}): ${d(i.lastSession.summary,{maxLength:200})}`);}if(i.sessionsOnProject&&n.push(`Sessions on this project: ${i.sessionsOnProject}`),i.pendingWork?.length){n.push("**Pending from last session:**");for(let r of i.pendingWork.slice(0,5))n.push(`- ${d(r,{maxLength:200})}`);}if(i.recentPatterns?.length){n.push("**Project patterns you've learned:**");for(let r of i.recentPatterns.slice(0,5))n.push(`- ${d(r,{maxLength:200})}`);}n.push("");}if(t.attention){let r=t.attention,a=[];r.symbols?.length&&a.push(`Symbols: ${r.symbols.join(", ")}`),r.paths?.length&&a.push(`Paths: ${r.paths.join(", ")}`),r.concepts?.length&&a.push(`Concepts: ${r.concepts.join(", ")}`),r.signals?.length&&a.push(`Signals: ${r.signals.map(p=>p.type).join(", ")}`),a.length>0&&(n.push(""),n.push("### Attention"),n.push(`Threshold: ${r.threshold??.6}`),n.push(a.join(" | ")));}if(t.collaboration){let r=t.collaboration;if(n.push(""),n.push("### Collaboration"),n.push(`Default stance: ${r.stance||"supportive"}`),r.with)for(let[a,p]of Object.entries(r.with)){let u=[`${a}: ${p.stance||"peer"}`];p.can_contradict&&u.push("can contradict"),p.review_output&&u.push("reviews output"),n.push(`- ${u.join(", ")}`);}if(r.debate){let a=r.debate,p=[];a.will_challenge&&p.push("challenges"),a.evidence_required&&p.push("evidence-based"),a.escalate_to_human&&p.push("escalates to human"),p.length&&n.push(`Debate: ${p.join(", ")}`);}}if(t.nomination){let r=t.nomination;if(n.push(""),n.push("### Nomination"),r.speak_when?.urgency?.length&&n.push(`Always speaks on: ${r.speak_when.urgency.join(", ")}`),r.contribution_style){let a=[];r.contribution_style.brief_first&&a.push("brief first"),r.contribution_style.cite_sources&&a.push("cites sources"),r.contribution_style.offer_action&&a.push("offers action"),a.length&&n.push(`Style: ${a.join(", ")}`);}}if(s){if(s.recentDecisions?.length){n.push(""),n.push("## Recent Team Decisions");for(let r of s.recentDecisions.slice(0,5))n.push(`- **${d(r.title,{maxLength:200})}**: ${d(r.decision,{maxLength:150})}`);}if(s.journalInsights?.length){n.push(""),n.push("## Transferable Insights");for(let r of s.journalInsights.slice(0,5))n.push(`- [${d(r.trigger,{maxLength:100})}] ${d(r.insight,{maxLength:150})}`);}if(s.pendingNominations?.length){n.push(""),n.push("## Pending Nominations");for(let r of s.pendingNominations.slice(0,10))n.push(`- [${d(r.urgency,{maxLength:50})}] ${d(r.brief,{maxLength:200})}`);}}return n.join(`
3
+ `)}async function ne(t,e,o=false){let{loadLoreEntries:s}=await import('./lore-loader-XY5MZRR2.js'),i=await s(t,{limit:500}),n=0,c=new Set,f=P(t,e)||W(e,{rootDir:t}).profile,r=f.expertise||[];for(let a of i)if(!(!a.symbols_touched||a.symbols_touched.length===0)){n++;for(let p of a.symbols_touched){c.add(p);let u=r.find(I=>I.symbol===p);u?(u.sessions++,u.lastTouch=a.timestamp,a.confidence!=null&&(u.confidence=(1-A)*u.confidence+A*a.confidence)):r.push({symbol:p,confidence:a.confidence??.5,sessions:1,lastTouch:a.timestamp});}}if(f.expertise=r,!o){let a=g.join(t,_,`${e}${y}`),p=l.existsSync(a)?"project":"global";w(e,f,p,t);}return {entriesProcessed:n,symbolsUpdated:c.size}}function d(t,e){let o=e?.maxLength??500,s=t;return s=s.replace(/^#{1,6}\s*(SYSTEM|IMPORTANT|OVERRIDE|INSTRUCTIONS?)\s*$/gim,""),s=s.replace(/^\s*(Ignore all previous|You are now|SYSTEM:|ASSISTANT:|USER:|\[SYSTEM\]|<\/?system>)/gim,""),s=s.trim(),s.length>o&&(s=s.slice(0,o)+"..."),s}function x(t){let e=U(t);return e.valid?e.reason&&e.reason.includes("No integrity hash")?"missing":"valid":"invalid"}function G(t,e,o){if(!t.permissions?.paths)return {allowed:true};let{read:s,write:i,deny:n}=t.permissions.paths;if(n&&n.length>0){for(let f of n)if(v(f,e))return {allowed:false,reason:`Path denied by pattern: ${f}`}}let c=o==="read"?s:i;if(c&&c.length>0){for(let f of c)if(v(f,e))return {allowed:true};return {allowed:false,reason:`No ${o} pattern matches: ${e}`}}return {allowed:true}}function q(t,e){if(!t.permissions?.tools)return {allowed:true};let{allow:o,deny:s}=t.permissions.tools;if(s&&s.length>0){for(let i of s)if(v(i,e))return {allowed:false,reason:`Tool denied by pattern: ${i}`}}if(o&&o.length>0){for(let i of o)if(v(i,e))return {allowed:true};return {allowed:false,reason:`Tool not in allow list: ${e}`}}return {allowed:true}}function se(t){let e=t.permissions;if(!e)return {allowedPaths:[],deniedPaths:[],allowedTools:[],deniedTools:[]};let o=e.paths?.read??[],s=e.paths?.write??[],i=[...new Set([...o,...s])],n=e.paths?.deny??[],c=e.tools?.allow??[],f=e.tools?.deny??[];return {allowedPaths:i,deniedPaths:n,allowedTools:c,deniedTools:f}}function re(t,e){return e.type==="path"?G(t,e.path,e.mode):q(t,e.name)}function N(t){let e=JSON.stringify({id:t.id,role:t.role,permissions:t.permissions||null});return E.createHash("sha256").update(e).digest("hex")}function U(t){return t.integrityHash?N(t)===t.integrityHash?{valid:true}:{valid:false,reason:"Integrity hash mismatch \u2014 profile may have been tampered with"}:{valid:true,reason:"No integrity hash stored (pre-4.0 profile)"}}function v(t,e){let o=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${o}$`).test(e)}function C(t,e){let o={...t};if(e.role&&(o.role=e.role),e.description&&(o.description=e.description),e.version&&(o.version=e.version),e.personality&&(o.personality={...t.personality,...e.personality}),e.expertise){let s=new Map(t.expertise.map(i=>[i.symbol,i]));for(let i of e.expertise)s.set(i.symbol,i);o.expertise=Array.from(s.values());}if(e.transferable){let s=new Map(t.transferable.map(i=>[i.id,i]));for(let i of e.transferable)s.set(i.id,i);o.transferable=Array.from(s.values());}if(e.contexts){o.contexts={...t.contexts};for(let[s,i]of Object.entries(e.contexts))o.contexts[s]={...o.contexts[s],...i};}return o}function H(t){try{let e=g.join(t,".paradigm","config.yaml");if(l.existsSync(e)){let o=l.readFileSync(e,"utf-8"),s=h.load(o);if(s?.project&&typeof s.project=="string")return s.project}}catch{}return g.basename(t)}export{b as a,D as b,J as c,z as d,V as e,P as f,M as g,X as h,L as i,w as j,W as k,K as l,Q as m,Z as n,ee as o,te as p,ne as q,d as r,x as s,G as t,q as u,se as v,re as w,N as x,U as y};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import*as a from'fs';import*as c from'path';import {Glob}from'glob';function n(t){let e=r=>{if(r.includes("*"))try{return new Glob(r,{cwd:t,nodir:!0}).walkSync().length>0}catch{return false}return a.existsSync(c.join(t,r))};return e("project.godot")||e("Assets/ProjectSettings")?"game":e("Package.swift")&&!e("package.json")?e("Sources/*/App")||e("**/AppDelegate.swift")?"macos-app":"ios-app":e("pubspec.yaml")?"flutter-app":e("supabase")&&(e("next.config.*")||e("vite.config.*"))?"saas-web-app":e("next.config.*")||e("vite.config.*")||e("nuxt.config.*")?"web-app":e("Dockerfile")||e("prisma")||e("drizzle.config.*")?"backend-api":e("Cargo.toml")?"rust-project":e("pyproject.toml")||e("setup.py")||e("requirements.txt")?"python-project":"generic"}var s={"saas-web-app":["advocate","architect","builder","compliance","reviewer","tester","security","documentor","designer","copywriter","performance","devops","dba","e2e","dx","seo","pm","product","sales","legal","a11y","qa","debugger","release","narrator","analyst"],"web-app":["advocate","architect","builder","compliance","reviewer","tester","security","documentor","designer","copywriter","performance","devops","e2e","seo","a11y","qa","debugger"],"backend-api":["advocate","architect","builder","compliance","reviewer","tester","security","documentor","devops","dba","performance","dx","qa","debugger","release","analyst"],"ios-app":["advocate","architect","builder","compliance","reviewer","tester","security","documentor","designer","mobile","performance","a11y","qa","debugger"],"macos-app":["advocate","architect","builder","compliance","reviewer","tester","security","documentor","designer","performance","qa","debugger"],"flutter-app":["advocate","architect","builder","compliance","reviewer","tester","security","documentor","designer","mobile","performance","a11y","debugger"],game:["advocate","architect","builder","compliance","reviewer","tester","documentor","gamedev","3d","audio","designer","performance","debugger"],"rust-project":["advocate","architect","builder","compliance","reviewer","tester","security","documentor","performance","debugger","qa"],"python-project":["advocate","architect","builder","compliance","reviewer","tester","security","documentor","performance","debugger","qa","analyst"],generic:["advocate","architect","builder","compliance","reviewer","tester","security","documentor","debugger","qa"]};export{n as a,s as b};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-DG236EXP.js';import {e,f,c,d,l,h,g,k,i,m as m$1,o,n,j,b as b$1,a as a$1}from'./chunk-AO7ZSRME.js';import {a}from'./chunk-Y4XFVDZC.js';import*as $ from'fs';import*as m from'path';import e$1 from'chalk';import E from'prompts';function F(){return process.env.CLAUDE_CODE==="1"||process.env.TERM_PROGRAM==="claude"?false:!!(process.env.TERM_PROGRAM==="cursor"||process.env.CURSOR_SESSION||process.env.CURSOR_TRACE_ID||process.env.VSCODE_CWD&&process.env.VSCODE_CWD.toLowerCase().includes("cursor")||process.env.VSCODE_NLS_CONFIG&&process.env.VSCODE_NLS_CONFIG.toLowerCase().includes("cursor")||process.env.TERM_PROGRAM==="vscode"&&process.env.VSCODE_GIT_ASKPASS_NODE?.toLowerCase().includes("cursor")||process.stdin.isTTY)}async function T(g){let n=new a(g),c=await n.discover();console.log(e$1.cyan(`
2
+ import {b}from'./chunk-A7KFOJ2F.js';import {e,f,c,d,l,h,g,k,i,m as m$1,o,n,j,b as b$1,a as a$1}from'./chunk-AO7ZSRME.js';import {a}from'./chunk-Y4XFVDZC.js';import*as $ from'fs';import*as m from'path';import e$1 from'chalk';import E from'prompts';function F(){return process.env.CLAUDE_CODE==="1"||process.env.TERM_PROGRAM==="claude"?false:!!(process.env.TERM_PROGRAM==="cursor"||process.env.CURSOR_SESSION||process.env.CURSOR_TRACE_ID||process.env.VSCODE_CWD&&process.env.VSCODE_CWD.toLowerCase().includes("cursor")||process.env.VSCODE_NLS_CONFIG&&process.env.VSCODE_NLS_CONFIG.toLowerCase().includes("cursor")||process.env.TERM_PROGRAM==="vscode"&&process.env.VSCODE_GIT_ASKPASS_NODE?.toLowerCase().includes("cursor")||process.stdin.isTTY)}async function T(g){let n=new a(g),c=await n.discover();console.log(e$1.cyan(`
3
3
  Configure Agent Models
4
4
  `)),console.log(e$1.gray(` Environment: ${c.source}`)),console.log(e$1.gray(` Available: ${c.models.length} models
5
5
  `));let i={},o=n.groupByTier(c.models),a$2=t=>{let r=a$1[t],s=r.tier==="high"?o.high:r.tier==="medium"?o.medium:o.low,l=[];for(let f of s){let P=l.length===0;l.push({title:P?`${f.name} (recommended)`:f.name,value:f.id,description:`${f.provider} - ${r.tier} tier`});}let u=o.high.filter(f=>!s.includes(f)),y=o.medium.filter(f=>!s.includes(f)),v=o.low.filter(f=>!s.includes(f));for(let f of u)l.push({title:f.name,value:f.id,description:`${f.provider} - high tier`});for(let f of y)l.push({title:f.name,value:f.id,description:`${f.provider} - medium tier`});for(let f of v)l.push({title:f.name,value:f.id,description:`${f.provider} - low tier`});return l};for(let t of ["architect","builder","tester","reviewer","security"]){let r=a$1[t],s=t.charAt(0).toUpperCase()+t.slice(1),l=a$2(t),u=await E({type:"select",name:"model",message:`${s} (${r.description})`,choices:l,initial:0},{onCancel:()=>{console.log(e$1.yellow(`
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import {c,a as a$1}from'./chunk-HMQ5BHP2.js';import {e as e$1}from'./chunk-JQKKVAAN.js';import {a}from'./chunk-LKAT7IAK.js';import*as e from'fs';import*as r from'path';import*as k from'js-yaml';import l from'chalk';async function rs(v={}){let p=v.rootDir||process.cwd(),s=[],y=v.quiet,E=v.context;y||(console.log(l.blue(`
3
+ \u{1FA7A} Paradigm Doctor
4
+ `)),console.log(E?l.gray(`Running context audit checks...
5
+ `):l.gray(`Checking Paradigm setup...
6
+ `)));let L=a.command("doctor").start("Running health checks");if(!E){let M=function(t){let a=[];try{let n=e.readdirSync(t,{withFileTypes:!0});for(let i of n){if(i.name==="node_modules"||i.name==="dist"||i.name===".git")continue;let f=r.join(t,i.name);i.isDirectory()?a.push(...M(f)):i.name===".purpose"&&a.push(f);}}catch{}return a};let o=r.join(p,".paradigm");if(e.existsSync(o))if(e.statSync(o).isFile())s.push({name:".paradigm",status:"warn",message:"Legacy file format (should be directory)",fix:"paradigm upgrade --all"});else {s.push({name:".paradigm/",status:"ok",message:"Directory exists"});let a=r.join(o,"config.yaml");if(e.existsSync(a))try{let u=e.readFileSync(a,"utf8");e$1(u),s.push({name:".paradigm/config.yaml",status:"ok",message:"Valid YAML"});}catch(u){s.push({name:".paradigm/config.yaml",status:"error",message:`Invalid YAML: ${u.message}`,fix:"Check YAML syntax"});}else s.push({name:".paradigm/config.yaml",status:"missing",message:"Config file not found",fix:"paradigm init --force"});let n=["logger.md","scan.md","symbols.md"],i=r.join(o,"specs");if(e.existsSync(i))for(let u of n){let w=r.join(i,u);e.existsSync(w)?s.push({name:`.paradigm/specs/${u}`,status:"ok",message:"Present"}):s.push({name:`.paradigm/specs/${u}`,status:"missing",message:"Spec file not found",fix:"paradigm upgrade --all"});}else s.push({name:".paradigm/specs/",status:"missing",message:"Specs directory not found",fix:"paradigm upgrade --all"});let f=r.join(o,"docs");e.existsSync(f)?s.push({name:".paradigm/docs/",status:"ok",message:"Directory exists"}):s.push({name:".paradigm/docs/",status:"missing",message:"Docs directory not found",fix:"paradigm upgrade --all"});let h=r.join(o,"prompts");e.existsSync(h)?s.push({name:".paradigm/prompts/",status:"ok",message:"Directory exists"}):s.push({name:".paradigm/prompts/",status:"missing",message:"Prompts directory not found",fix:"paradigm upgrade --all"});let g=r.join(o,"scan-index.json"),d=r.join(p,".paradigm-scan-index.json");if(e.existsSync(g)){let u=e.statSync(g),w=Date.now()-u.mtime.getTime(),x=Math.floor(w/(1e3*60*60));x>24?s.push({name:".paradigm/scan-index.json",status:"warn",message:`Stale (${x} hours old)`,fix:"paradigm index"}):s.push({name:".paradigm/scan-index.json",status:"ok",message:x>0?`${x} hours old`:"Fresh"});}else e.existsSync(d)?s.push({name:"scan-index",status:"warn",message:"Using legacy location",fix:"paradigm index"}):s.push({name:".paradigm/scan-index.json",status:"missing",message:"Not generated",fix:"paradigm index"});}else s.push({name:".paradigm/",status:"missing",message:"Not initialized",fix:"paradigm init"});let m=c(p);if(m.detected){let t=a$1(m.detected);if(t){let a=r.join(p,t.outputPath);e.existsSync(a)?s.push({name:t.outputPath,status:"ok",message:`Present (${m.detected})`}):s.push({name:t.outputPath,status:"missing",message:`Not generated for ${m.detected}`,fix:"paradigm sync"});}}let c$1=r.join(p,".premise");e.existsSync(c$1)?s.push({name:".premise",status:"ok",message:"Present"}):s.push({name:".premise",status:"missing",message:"Not found (optional)"});let j=r.join(p,".purpose");e.existsSync(j)?s.push({name:".purpose",status:"ok",message:"Present"}):s.push({name:".purpose",status:"warn",message:"Root .purpose not found",fix:"paradigm init"});let A=r.join(p,".paradigm","config.yaml");if(e.existsSync(A))try{let t=e.readFileSync(A,"utf8"),n=k.load(t)?.["purpose-required"];if(n&&Array.isArray(n)){let i=[];for(let f of n){if(!f.pattern)continue;let{glob:h}=await import('glob'),g=await h(f.pattern,{cwd:p,nodir:!1});for(let d of g){let u=r.join(p,d);try{e.statSync(u).isDirectory()&&!e.existsSync(r.join(u,".purpose"))&&i.push(d);}catch{}}}i.length>0?s.push({name:"Purpose-required",status:"warn",message:`${i.length} director${i.length===1?"y":"ies"} missing .purpose: ${i.join(", ")}`,fix:"Create .purpose files with paradigm_purpose_init + paradigm_purpose_add_component"}):s.push({name:"Purpose-required",status:"ok",message:"All required directories have .purpose files"});}}catch{}let F=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi,D=0,O=M(p);for(let t of O)try{let n=e.readFileSync(t,"utf8").match(F);n&&(D+=n.length);}catch{}D>0?s.push({name:"Clarification markers",status:"warn",message:`${D} [NEEDS CLARIFICATION] marker${D>1?"s":""} found in .purpose files`,fix:"Resolve open clarification markers before shipping"}):O.length>0&&s.push({name:"Clarification markers",status:"ok",message:"No unresolved markers"});let q=r.join(p,"portal.yaml");if(e.existsSync(q))try{let t=e.readFileSync(q,"utf8"),a=k.load(t);if(a?.version&&a?.gates){let n=Object.keys(a.gates||{}).length,i=Object.keys(a.routes||{}).length;s.push({name:"portal.yaml",status:"ok",message:`Valid (${n} gates, ${i} routes)`});}else s.push({name:"portal.yaml",status:"warn",message:"Missing version or gates section",fix:'Add version: "1.0" and gates: {} to portal.yaml'});}catch(t){s.push({name:"portal.yaml",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in portal.yaml"});}if(e.existsSync(q))try{let{checkPortalCompliance:t,getComplianceSummary:a}=await import('./portal-compliance-4MG5F2GI.js'),n=await t(p),i=a(n);s.push({name:"Portal compliance",status:i.status,message:i.message,fix:i.status!=="ok"?"paradigm portal check":void 0});}catch{}let T=r.join(p,".paradigm","flows.yaml");if(e.existsSync(T))try{let t=e.readFileSync(T,"utf8"),a=k.load(t);if(a?.version&&a?.flows){let n=Object.keys(a.flows||{}).length,i=Object.entries(a.flows||{}).filter(([,f])=>!f?.steps||(f.steps?.length??0)===0);i.length>0?s.push({name:".paradigm/flows.yaml",status:"warn",message:`${n} flows defined, ${i.length} have no steps`,fix:"Add steps to empty flow definitions"}):s.push({name:".paradigm/flows.yaml",status:"ok",message:`Valid (${n} flows)`});}else s.push({name:".paradigm/flows.yaml",status:"warn",message:"Missing version or flows section",fix:'Ensure flows.yaml has version: "1.0" and flows: {}'});}catch(t){s.push({name:".paradigm/flows.yaml",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in flows.yaml"});}let Y=r.join(p,".paradigm","lore");if(e.existsSync(Y))try{let t=e.readdirSync(Y).filter(a=>a.endsWith(".yaml"));t.length===0?s.push({name:"Lore entries",status:"warn",message:"Lore directory exists but no entries found",fix:"Record a lore entry: paradigm lore record"}):s.push({name:"Lore entries",status:"ok",message:`${t.length} lore file${t.length>1?"s":""}`});}catch{s.push({name:"Lore entries",status:"warn",message:"Could not read lore directory"});}let U=r.join(p,".paradigm","university");if(e.existsSync(U))try{let t=r.join(U,"content"),a=0,n=0;if(e.existsSync(t))for(let i of ["notes","policies","quizzes","paths"]){let f=r.join(t,i);e.existsSync(f)&&(a+=e.readdirSync(f).filter(h=>h.endsWith(".md")||h.endsWith(".yaml")).length);}if(a===0)s.push({name:"University content",status:"warn",message:"University directory exists but no content found",fix:'Add content: paradigm university add note --title "Getting Started"'});else {let i=r.join(t,"quizzes");if(e.existsSync(i))for(let h of e.readdirSync(i).filter(g=>g.endsWith(".yaml")))try{let g=k.load(e.readFileSync(r.join(i,h),"utf8"));if(g?.questions)for(let d of g.questions)d.choices&&d.correct&&!(d.correct in d.choices)&&n++;}catch{}let f=r.join(t,"paths");if(e.existsSync(f))for(let h of e.readdirSync(f).filter(g=>g.endsWith(".yaml")))try{let g=k.load(e.readFileSync(r.join(f,h),"utf8"));if(g?.steps){for(let d of g.steps)if(d.content&&!d.content.startsWith("plsat:")){let u=!1;for(let w of ["notes","policies","quizzes","paths"]){let x=r.join(t,w);if(e.existsSync(x)&&e.readdirSync(x).some(Z=>Z.startsWith(d.content))){u=!0;break}}u||n++;}}}catch{}n>0?s.push({name:"University content",status:"warn",message:`${a} items, ${n} issue${n>1?"s":""}`,fix:"Run: paradigm university validate --deep"}):s.push({name:"University content",status:"ok",message:`${a} content item${a>1?"s":""}`});}}catch{s.push({name:"University content",status:"warn",message:"Could not read university directory"});}let H=r.join(p,".claude","hooks.json"),X=r.join(p,"plugins","paradigm","hooks.json");if(e.existsSync(H)){let t=e.statSync(H),a=Date.now()-t.mtime.getTime(),n=Math.floor(a/(1e3*60*60*24));n>30?s.push({name:"Claude Code hooks",status:"warn",message:`Hooks are ${n} days old \u2014 may be outdated`,fix:"paradigm hooks install"}):s.push({name:"Claude Code hooks",status:"ok",message:n>0?`${n} days old`:"Fresh"});}else e.existsSync(X)?s.push({name:"Claude Code hooks",status:"ok",message:"Using plugin hooks"}):s.push({name:"Claude Code hooks",status:"missing",message:"No hooks installed",fix:"paradigm hooks install"});let G=r.join(p,".paradigm","habits.yaml");if(e.existsSync(G))try{let t=e.readFileSync(G,"utf8"),a=k.load(t);if(a?.version&&Array.isArray(a?.habits)){let n=a.habits.filter(i=>i.enabled!==!1).length;s.push({name:"Habits config",status:"ok",message:`Valid (${n}/${a.habits.length} enabled)`});}else s.push({name:"Habits config",status:"warn",message:"Missing version or habits array",fix:"Regenerate habits.yaml with paradigm habits init"});}catch(t){s.push({name:"Habits config",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in habits.yaml"});}let _=r.join(p,"AGENTS.md");if(e.existsSync(_)){let t=e.statSync(_),a=Date.now()-t.mtime.getTime(),n=Math.floor(a/(1e3*60*60*24));n>60?s.push({name:"AGENTS.md",status:"warn",message:`${n} days since last update \u2014 may be stale`,fix:"paradigm sync"}):s.push({name:"AGENTS.md",status:"ok",message:n>0?`Updated ${n} days ago`:"Fresh"});}}let N=0,I=0,S=0;for(let o of s){let m,c;switch(o.status){case "ok":m="\u2713",c=l.green;break;case "warn":m="\u26A0",c=l.yellow,I++;break;case "error":m="\u2717",c=l.red,N++;break;case "missing":m="\u25CB",c=l.gray,S++;break}if(!y){let j=o.name.padEnd(30);console.log(` ${c(m)} ${j} ${c(o.message)}`),o.fix&&console.log(l.gray(` \u2514\u2500 Fix: ${o.fix}`));}}let{runContextAudit:Q}=await import('./context-audit-XRPT3OU2.js'),R=await Q(p,{quiet:y}),W=0,z=0,$=0;!y&&R.length>0&&(console.log(""),console.log(l.blue(" Context Audit")),console.log(l.gray(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")));for(let o of R){let m,c;switch(o.status){case "ok":m="\u2713",c=l.green;break;case "warn":m="\u26A0",c=l.yellow,z++;break;case "error":m="\u2717",c=l.red,W++;break;case "advisory":m="\u2139",c=l.cyan,$++;break}if(!y){let j=o.check.padEnd(30);if(console.log(` ${c(m)} ${j} ${c(o.message)}`),o.details&&o.details.length>0){let A=o.details.slice(0,5);for(let F of A)console.log(l.gray(` \u2502 ${F}`));o.details.length>5&&console.log(l.gray(` \u2502 ... and ${o.details.length-5} more`));}o.fix&&console.log(l.gray(` \u2514\u2500 Fix: ${o.fix}`));}}let b=N+W,C=I+z,P=b+C+S===0;if(!y)if(console.log(""),P)console.log(l.green(`\u2728 All checks passed!
7
+ `));else {let o=[];b>0&&o.push(l.red(`${b} error${b>1?"s":""}`)),C>0&&o.push(l.yellow(`${C} warning${C>1?"s":""}`)),S>0&&o.push(l.gray(`${S} missing`)),$>0&&o.push(l.cyan(`${$} advisor${$>1?"ies":"y"}`)),console.log(`${o.join(", ")} found.
8
+ `),console.log(l.gray(`Run the suggested commands to fix issues.
9
+ `));}if(!y&&v.explain&&!P)try{let{narrateAllGaps:o}=await import('./gap-narrator-NTXLUI7I.js'),m=[];for(let c of s)c.status!=="ok"&&(c.name===".purpose"||c.name.startsWith("Purpose-required")?m.push({type:"missing-purpose",target:c.name,severity:"improvement"}):c.name===".paradigm/scan-index.json"&&c.status==="warn"?m.push({type:"index-stale",target:c.name,severity:"improvement"}):c.name==="Portal compliance"?m.push({type:"portal-mismatch",target:c.name,severity:c.status==="error"?"blocking":"improvement"}):c.name==="Clarification markers"&&m.push({type:"missing-description",target:c.name,severity:"improvement"}));if(m.length>0){let c=o(m);console.log(l.blue(`
10
+ Gap Narrations (--explain)
11
+ `)),console.log(l.gray(c.narrative)),console.log("");}}catch{}return P?L.success("All health checks passed",{total:s.length+R.length}):L.error("Health checks found issues",{errors:b,warnings:C,missing:S,advisories:$}),P}export{rs as a};