@a-company/paradigm 5.34.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.
@@ -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};
@@ -1,35 +1,35 @@
1
1
  #!/usr/bin/env node
2
- import {f,p,i,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 Q from'os';var vt={};c(vt,{getJournalStats:()=>ne,loadAllJournalEntries:()=>ee,loadJournalEntries:()=>O,loadJournalEntry:()=>te,recordJournalEntry:()=>V});function G(n){let t=process.env.HOME||process.env.USERPROFILE||"";return b.join(t,".paradigm","agents",n,"journal")}function Zt(){let n=new Date,t=n.toISOString().slice(0,10),e=n.toISOString().slice(11,19).replace(/:/g,""),o=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `LJ-${t}-${e}-${o}`}function V(n,t){let e=new Date,o=Zt(),r={id:o,agent:n,timestamp:e.toISOString(),...t},i=G(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=G(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 te(n,t){let e=G(n),o=b.join(e,`${t}.yaml`);if(!g.existsSync(o))return null;let r=g.readFileSync(o,"utf8");return R.load(r)}function ee(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 ne(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 z=b$1(()=>{});var xt={};c(xt,{addNotebookEntry:()=>kt,incrementApplied:()=>se,loadNotebookEntries:()=>Dt,promoteFromLore:()=>re,searchNotebooks:()=>ie});function Dt(n,t,e){let o=new Map,r=b.join(K,n);jt(r,o);let i=b.join(t,X,n);jt(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 jt(n,t){if(g.existsSync(n))try{let e=g.readdirSync(n).filter(o=>o.startsWith(oe)&&o.endsWith(Y));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 ie(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 kt(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(K,n):b.join(o||process.cwd(),X,n);g.existsSync(d)||g.mkdirSync(d,{recursive:true});let u=`${a}${Y}`,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 re(n,t,e,o="global"){let{loadLoreEntry:r}=await import('./lore-loader-XY5MZRR2.js'),i=await r(e,t);if(!i)return null;let s=[];if(i.symbols_touched)for(let d of i.symbols_touched){let u=d.replace(/^[#$^!~]/,"").toLowerCase();s.push(u);}let a=i.summary||"";i.body&&(a+=`
2
+ import {f,p,i,c as c$1,j}from'./chunk-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
3
 
4
- `+i.body);let c={source:"lore",loreEntryId:t,originProject:b.basename(e),createdBy:n};return kt(n,{context:i.title||`Promoted from ${t}`,snippet:a,provenance:c,confidence:i.confidence??.7,concepts:s,tags:i.tags||[]},o,e)}function se(n,t,e){let o=b.join(e,X,n),r=b.join(K,n);for(let i of [o,r]){let s=b.join(i,`${t}${Y}`);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 K,X,oe,Y,Nt=b$1(()=>{K=b.join(Q.homedir(),".paradigm","notebooks"),X=".paradigm/notebooks",oe="nb-",Y=".yaml";});var gt=".paradigm/events",Vt="stream.jsonl",J=1e3,$=[];function pt(n){return b.join(n,gt,Vt)}function zt(){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:zt(),timestamp:new Date().toISOString(),...t};$.push(e),$.length>J&&($=$.slice(-J));try{let o=b.join(n,gt);g.mkdirSync(o,{recursive:!0});let r=pt(n);g.appendFileSync(r,JSON.stringify(e)+`
5
- `,"utf8"),Kt(r);}catch{}return e}function Kt(n){try{if(g.statSync(n).size>512*1024){let o=g.readFileSync(n,"utf8").trim().split(`
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
6
  `);if(o.length>J){let r=o.slice(-J);g.writeFileSync(n,r.join(`
7
7
  `)+`
8
- `,"utf8");}}}catch{}}function yt(n,t){let e=Xt(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 Xt(n){let t=pt(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 ht(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)ft(u,l)&&(o=Math.max(o,1));if(e.paths?.length&&n.path){for(let u of e.paths)if(ft(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 ft(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 Yt=".paradigm/data-policy.yaml";function wt(n){let t=b.join(n,Yt);if(!g.existsSync(t))return {...b$3};try{let e=g.readFileSync(t,"utf8"),o=R.load(e);return Qt(b$3,o)}catch{return {...b$3}}}function Qt(n,t){let e={...n};if(t.version&&(e.version=t.version),t.default_ring&&(e.default_ring=t.default_ring),t.observation&&(e.observation={allow:t.observation.allow||n.observation?.allow,deny:[...n.observation?.deny||[],...t.observation.deny||[]].filter((o,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 _t(n,t,e){return e&&n.agent_overrides?.[e]?.observation&&n.agent_overrides[e].observation.deny?.some(r=>q(r,t))||n.observation?.deny?.some(o=>q(o,t))?false:n.observation?.allow?.length?n.observation.allow.some(o=>q(o,t)):true}function q(n,t){if(n===t)return true;let e=n.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${e}$`).test(t)}catch{return false}}var N=".paradigm/events",ae="nominations.jsonl",ce="debates.jsonl",le=500,de=200,ue=7,me=14,fe=100;function ge(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${n}-${t}`}function pe(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${n}-${t}`}function ye(n,t){let e=i(n),o=wt(n),r=[];for(let d of e){if(!d.attention||d.benched||t.path&&!_t(o,t.path,d.id))continue;let u=ht(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===$t(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=he(t,u),m=be(d,t);return {id:ge(),agent:d.id,relevance:u.score,urgency:l,type:m,brief:$t(d,t,u),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});we(n,a);let c=Se(n,a);return c.length>0&&_e(n,c),{nominations:a,debates:c}}function he(n,t){return n.severity==="critical"?"critical":n.severity==="error"||n.type==="compliance-violation"||n.type==="error-encountered"?"high":n.type==="gate-added"||n.type==="route-created"||t.score>=.9?"medium":"low"}function be(n,t){let e=n.collaboration?.stance;return t.type==="compliance-violation"||t.type==="error-encountered"?"warning":t.type==="gate-added"||t.type==="route-created"?"observation":e==="advisory"||e==="lead"?"suggestion":"observation"}function $t(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 Se(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:pe(),topic:`Multiple agents responded to event ${r}`,nominations:i.map(d=>d.id),type:c?"conflicting":"complementary",overlap_events:[r]});}return e}function Z(n){return b.join(n,N,ae)}function tt(n){return b.join(n,N,ce)}function we(n,t){try{let e=b.join(n,N);g.mkdirSync(e,{recursive:!0});let o=Z(n),r=t.map(s=>JSON.stringify(s)).join(`
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
10
  `)+`
11
- `;g.appendFileSync(o,r,"utf8"),Tt(o,le);let{nominationTtlDays:i}=H(n);Rt(o,i*24*60*60*1e3);}catch{}}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(`
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
12
  `)+`
13
- `;g.appendFileSync(o,r,"utf8"),Tt(o,de);let{debateTtlDays:i}=H(n);Rt(o,i*24*60*60*1e3);}catch{}}function Tt(n,t){try{let o=g.readFileSync(n,"utf8").trim().split(`
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
14
  `).filter(r=>r.trim());if(o.length>t){let r=o.slice(-t);g.writeFileSync(n,r.join(`
15
15
  `)+`
16
- `,"utf8");}}catch{}}function H(n){let t={nominationTtlDays:ue,debateTtlDays:me};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 Rt(n,t){try{if(!g.existsSync(n))return;let o=g.readFileSync(n,"utf8").trim().split(`
17
- `).filter(s=>s.trim());if(o.length<=fe)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(`
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
18
  `)+`
19
- `,"utf8");}catch{}}function E(n,t){let e=Z(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 Pt(n){let t=tt(n);if(!g.existsSync(t))return [];try{return g.readFileSync(t,"utf8").trim().split(`
21
- `).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return []}}function Ot(n,t,e,o){let r=Z(n);if(!g.existsSync(r))return false;try{let s=g.readFileSync(r,"utf8").trim().split(`
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
22
  `),a=!1,c=s.map(d=>{try{let u=JSON.parse(d);return u.id===t?(u.engaged=!0,u.response=e,o&&(u.reason=o),a=!0,JSON.stringify(u)):d}catch{return d}});if(a&&(g.writeFileSync(r,c.join(`
23
23
  `)+`
24
- `,"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=tt(n);if(!g.existsSync(r))return false;try{let s=g.readFileSync(r,"utf8").trim().split(`
24
+ `,"utf8"),e==="accepted"||e==="dismissed")){let d=JSON.parse(s.find(l=>{try{return JSON.parse(l).id===t}catch{return !1}}));i(n).find(l=>l.id===d.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&M(n,{type:"work-completed",source:"agent-action",agent:d.agent,context:`Nomination ${t} ${e} \u2014 feedback for learning`,data:{nomination_id:t,response:e}});}return a}catch{return false}}function Ft(n,t,e,o){let r=et(n);if(!g.existsSync(r))return false;try{let s=g.readFileSync(r,"utf8").trim().split(`
25
25
  `),a=!1,c=s.map(d=>{try{let u=JSON.parse(d);if(u.id===t){u.resolution={chosen:e,reason:o,resolved_by:"human",resolved_at:new Date().toISOString()},a=!0;let l=u.nominations.filter(m=>m!==e);for(let m of l){let y=E(n).find(f=>f.id===m);y&&M(n,{type:"work-completed",source:"agent-action",agent:y.agent,context:`Debate ${t} resolved \u2014 nomination ${m} not chosen`,data:{debate_id:t,chosen:e,reason:o}});}return JSON.stringify(u)}return d}catch{return d}});return a&&g.writeFileSync(r,c.join(`
26
26
  `)+`
27
- `,"utf8"),a}catch{return false}}function At(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}=ye(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 It(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 et(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 Ct(n){let e=i(n).filter(l=>!l.benched).map(l=>{let m=et(n,l.id),y=0;try{let f=b.join(Q.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 nt(n,t){let e,o;try{let c=(z(),d(vt)),d$1=(Nt(),d(xt));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(Q.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(`
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
29
  `);x.push(`promoted_to_notebook: "${d.id}"`),g.writeFileSync(y,x.join(`
30
30
  `)+`
31
- `,"utf8");}else g.writeFileSync(y,p,"utf8");break}}}}catch{}}catch{}return {promoted:a.length,entries:a}}var ve=".paradigm/surfacing.yaml";function Jt(n){let t=b.join(n,ve),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 Mt(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 je=".paradigm/decisions";function Lt(n,t){let e=b.join(n,je);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}z();function qe(){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 Ee(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 Ge(n,t,e){let o=r=>JSON.stringify(r,null,2);switch(n){case "paradigm_ambient_nominations":{At(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=Jt(e.rootDir);a=Mt(a,c).slice(0,s);let d=b.join(e.rootDir,".paradigm/events/nominations.jsonl");if(g.existsSync(d))try{let l=g.readFileSync(d,"utf8"),m=new Set(a.map(f=>f.id)),y=l.trim().split(`
31
+ `,"utf8");}else g.writeFileSync(y,p,"utf8");break}}}}catch{}}catch{}return {promoted:a.length,entries:a}}var je=".paradigm/surfacing.yaml";function Mt(n){let t=b.join(n,je),e={default_min_urgency:"low",enable_debates:true};if(!g.existsSync(t))return e;try{let o=a("js-yaml"),r=g.readFileSync(t,"utf8"),i=o.load(r);return {...e,...i}}catch{return e}}function Lt(n,t){let e={critical:0,high:1,medium:2,low:3},o=e[t.default_min_urgency||"low"]??3;return n.filter(r=>{let i=e[r.urgency]??3;if(t.preferences){let s=t.preferences.find(a=>a.agent===r.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(c=>r.urgency===c||r.type===c))return false;if(s.min_urgency){let a=e[s.min_urgency]??3;return i<=a}}}return i<=o})}var Ee=".paradigm/decisions";function Ht(n,t){let e=b.join(n,Ee);if(!g.existsSync(e))return [];let o=[],r=g.readdirSync(e).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=g.readFileSync(b.join(e,s),"utf8"),c=R.load(a);c&&c.id&&o.push(c);}catch{}let i=o;return (i=i.filter(s=>s.status===t.status)),t?.participant&&(i=i.filter(s=>s.participants.some(a=>a.id===t.participant))),t?.symbol&&(i=i.filter(s=>s.symbols_affected?.includes(t.symbol))),t?.tag&&(i=i.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(i=i.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(i=i.filter(s=>s.timestamp<=t.dateTo)),i.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}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
32
  `).map(f=>{try{let p=JSON.parse(f);return m.has(p.id)?(p.surfaced=!0,JSON.stringify(p)):f}catch{return f}});g.writeFileSync(d,y.join(`
33
33
  `)+`
34
- `,"utf8");}catch{}let u={count:a.length,nominations:a.map(l=>({id:l.id,agent:l.agent,urgency:l.urgency,type:l.type,brief:l.brief,relevance:l.relevance,timestamp:l.timestamp,engaged:l.engaged,response:l.response}))};if(t.include_debates){let m=Pt(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?Ee(t.since):void 0,i=t.limit||50,s=yt(e.rootDir,{type:t.type,source:t.source,symbol:t.symbol,agent:t.agent,since:r,limit:i});return {text:o({count:s.length,events:s.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let r=t.nomination_id,i=t.response,s=t.reason,a=Ot(e.rootDir,r,i,s);if(a)try{let{appendSessionWorkEntry:d}=await import('./session-work-log-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=Lt(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=nt(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=et(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=It(e.rootDir,r);return {text:o({agent:r,...a,stats:s}),handled:true}}case "paradigm_ambient_neverland":{let r=Ct(e.rootDir);return {text:o(r),handled:true}}case "paradigm_ambient_learn_postflight":return {text:o(await xe(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 ke(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 xe(n,t={}){let e=t.dry_run===true,o=ke(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,Ut=U>0?x/U:0;for(let h of p){let B=De[h.verdict];if(!B)continue;let Bt=c.get(f)?.shift(),rt=Ne(h,Bt,{acceptRate:Ut,total:U,accepted:x}),Wt=h.verdict==="accepted"?.85:h.verdict==="revised"?.6:.4,qt={agent:f,verdict:h.verdict,trigger:B,insight:rt,symbols:h.symbols};if(d.push(qt),e)u[f]++,l++;else try{V(f,{trigger:B,insight:rt,confidence_before:h.verdict==="accepted"?.7:.8,confidence_after:Wt,project:o,transferable:h.verdict==="dismissed",tags:["postflight",`verdict:${h.verdict}`,...(h.symbols||[]).map(Gt=>`symbol:${Gt}`)]}),u[f]++,l++;}catch{}}}let m={},y=0;if(!e)for(let f of s.keys())try{let p=nt(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 Ne(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{qe as getAmbientToolsList,Ge as handleAmbientTool,xe as runPostflightLearning};
34
+ `,"utf8");}catch{}let u={count:a.length,nominations:a.map(l=>({id:l.id,agent:l.agent,urgency:l.urgency,type:l.type,brief:l.brief,relevance:l.relevance,timestamp:l.timestamp,engaged:l.engaged,response:l.response}))};if(t.include_debates){let m=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,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
+ 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};
@@ -21,7 +21,7 @@ ${r.map((h,w)=>`${w+1}. ${h}`).join(`
21
21
  - Modified files: ${a$1.length>0?a$1.join(", "):"(not specified)"}
22
22
  - Symbols touched: ${l.length>0?l.join(", "):"(not specified)"}
23
23
  - Open questions: ${c.length>0?c.join(", "):"(none)"}
24
- `;return ss(),{handled:true,text:JSON.stringify({handoff:m,markdownSummary:y,persisted:true,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let o=s.getStats(),r=s.getCostBreakdown(),i=s.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(o.startTime).toISOString(),durationMinutes:i,lastActivity:new Date(o.lastActivity).toISOString()},model:{name:r.model,id:r.modelId,pricing:{inputPerMillion:`$${r.pricing.input.toFixed(2)}`,outputPerMillion:`$${r.pricing.output.toFixed(2)}`}},interactions:{toolCalls:o.totals.toolCallCount,resourceReads:o.totals.resourceReadCount,totalInteractions:o.totals.toolCallCount+o.totals.resourceReadCount},tokens:{total:o.totals.totalTokens,byCategory:{resources:r.resources.tokens,tools:r.tools.tokens}},cost:{totalUsd:`$${r.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${r.resources.costUsd.toFixed(4)}`,tools:`$${r.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:r.resources.byType,toolsByName:r.tools.byName}},null,2)}}if(t==="paradigm_session_recover"){s.setRootDir(n.rootDir);let o=s.loadPreviousSession(),r=s.loadCheckpoint(),i=[];try{i=b$1(n.rootDir);}catch{}if(!o&&i.length===0&&!r)return {handled:true,text:JSON.stringify({found:false,message:"No previous session breadcrumbs, checkpoints, or pending handoffs found.",tip:"Breadcrumbs persist to ~/.paradigm/sessions/ and handoffs persist via paradigm_handoff_prepare. Checkpoints persist via paradigm_session_checkpoint."},null,2)};let a={found:true};if(r){let c=Date.now()-r.timestamp,d=Math.round(c/6e4),u=Math.round(c/36e5);a.checkpoint={phase:r.phase,context:r.context,age:u>1?`${u} hours ago`:`${d} minutes ago`,timestamp:new Date(r.timestamp).toISOString(),sessionId:r.sessionId,plan:r.plan,modifiedFiles:r.modifiedFiles,symbolsTouched:r.symbolsTouched,decisions:r.decisions,recentBreadcrumbs:r.recentBreadcrumbs?.map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}))};}if(o){let c=Date.now()-o.lastActivity,d=Math.round(c/6e4),u=Math.round(c/36e5),g=o.breadcrumbs.slice(-10).map(m=>({time:new Date(m.timestamp).toISOString(),action:m.action,tool:m.tool,symbol:m.symbol,summary:m.summary}));a.previousSession={sessionId:o.sessionId,startTime:new Date(o.startTime).toISOString(),lastActivity:new Date(o.lastActivity).toISOString(),age:u>1?`${u} hours ago`:`${d} minutes ago`},a.context={symbolsModified:o.symbolsModified,filesExplored:o.filesExplored},a.recentActions=g;}if(i.length>0){a.pendingHandoffs=i.map(c=>({id:c.id,timestamp:c.timestamp,from:c.from,to:c.to,summary:c.summary,nextSteps:c.nextSteps,modifiedFiles:c.modifiedFiles,symbolsTouched:c.symbolsTouched,openQuestions:c.openQuestions}));for(let c of i)try{c$1(n.rootDir,c.id);}catch{}}let l="Continue where the previous session left off.";if(r)l=`Previous session was in "${r.phase}" phase: ${r.context}`,r.decisions?.length&&(l+=` Key decisions: ${r.decisions.slice(0,2).join("; ")}`);else if(i.length>0){let c=i[i.length-1];l=`Handoff received: "${c.summary}". `,c.nextSteps.length>0&&(l+=`Start with: ${c.nextSteps[0]}`);}else if(o){let c=o.breadcrumbs.slice(-10);if(c.length>0){let d=c[c.length-1];d.symbol&&(l=`Last work involved ${d.symbol}. Consider checking its current state with paradigm_ripple.`);}}return a.suggestion=l,a.agentInstruction="Present a brief summary of the previous session, then ask the user what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking.",s.markRecovered(),{handled:true,text:JSON.stringify(a,null,2)}}if(t==="paradigm_session_checkpoint"){s.setRootDir(n.rootDir);let o=e.phase,r=e.context,i=e.externalId,a=e.plan,l=e.modifiedFiles,c=e.symbolsTouched,d=e.decisions,{checkpoint:u,persisted:p}=s.saveCheckpoint({phase:o,context:r,externalId:i,plan:a,modifiedFiles:l,symbolsTouched:c,decisions:d}),g=p.local||p.global;return {handled:true,text:JSON.stringify({saved:g,persisted:p,checkpoint:{phase:u.phase,context:u.context,sessionId:u.sessionId,...u.externalId?{externalId:u.externalId}:{},timestamp:new Date(u.timestamp).toISOString(),modifiedFiles:u.modifiedFiles?.length||0,symbolsTouched:u.symbolsTouched?.length||0,decisions:u.decisions?.length||0,recentBreadcrumbs:u.recentBreadcrumbs?.length||0},...g?{note:"Checkpoint saved. Recovery data will be auto-surfaced on the first tool call of the next session."}:{warning:"Checkpoint was NOT persisted to disk. Both local and global writes failed. Check MCP server stderr for details."}},null,2)}}return {handled:false,text:""}}async function Wo(t){let e=j$1();e.setRootDir(t);let n=e.loadCheckpoint(),s=[];try{s=b$1(t);}catch{}if(!n&&s.length===0)return null;let o=[];if(o.push("--- SESSION RECOVERY ---"),n){let r=Date.now()-n.timestamp,i=Math.round(r/6e4),a=Math.round(r/36e5),l=a>1?`${a}h ago`:`${i}m ago`;o.push(`Previous session was in "${n.phase}" phase (${l}): ${n.context}`),n.modifiedFiles?.length&&o.push(`Modified files: ${n.modifiedFiles.join(", ")}`),n.symbolsTouched?.length&&o.push(`Symbols: ${n.symbolsTouched.join(", ")}`),n.decisions?.length&&o.push(`Decisions: ${n.decisions.join("; ")}`),n.plan&&o.push(`Plan: ${n.plan.slice(0,200)}`);}if(s.length>0){let r=s[s.length-1];o.push(`Pending handoff: "${r.summary}"`),r.nextSteps.length>0&&o.push(`Next steps: ${r.nextSteps.slice(0,3).join(", ")}`);}try{let{loadTasks:r}=await import('./task-loader-NZFDTUQ5.js'),i=await r(t,{status:"open",limit:5});if(i.length>0){o.push(""),o.push("Open tasks:");for(let a of i){let l=a.tags.length>0?` [${a.tags.join(", ")}]`:"";o.push(` [${a.priority}] ${a.id}: ${a.blurb}${l}`);}}}catch{}try{let{loadLoreEntries:r}=await import('./lore-loader-RVQI5GXL.js'),a=(await r(t,{limit:10})).filter(l=>l.tags?.some(c=>c.startsWith("arc:")));if(a.length>0){let l=new Map;for(let u of a){let p=u.tags?.find(g=>g.startsWith("arc:"))||"";l.set(p,(l.get(p)||0)+1);}let c=n?.symbolsTouched||[];if((c.length>0?a.filter(u=>u.symbols_touched?.some(p=>c.includes(p))):a.slice(0,3)).length>0||l.size>0){o.push(""),o.push("Active lore arcs:");for(let[u,p]of l)o.push(` ${u} (${p} entries)`);}}}catch{}try{let{loadNominations:r}=await import('./nomination-engine-W6QTQX2P.js'),i=r(t,{pending_only:!0}).filter(a=>a.urgency==="critical"||a.urgency==="high");if(i.length>0){o.push(""),o.push("Ambient nominations (urgent):");for(let a of i.slice(0,5))o.push(` [${a.urgency}] ${a.brief}`);i.length>5&&o.push(` ... and ${i.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return o.push(""),o.push("IMPORTANT: Present a brief summary of this recovery data to the user, then ask what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking."),o.push("---"),o.join(`
24
+ `;return ss(),{handled:true,text:JSON.stringify({handoff:m,markdownSummary:y,persisted:true,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let o=s.getStats(),r=s.getCostBreakdown(),i=s.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(o.startTime).toISOString(),durationMinutes:i,lastActivity:new Date(o.lastActivity).toISOString()},model:{name:r.model,id:r.modelId,pricing:{inputPerMillion:`$${r.pricing.input.toFixed(2)}`,outputPerMillion:`$${r.pricing.output.toFixed(2)}`}},interactions:{toolCalls:o.totals.toolCallCount,resourceReads:o.totals.resourceReadCount,totalInteractions:o.totals.toolCallCount+o.totals.resourceReadCount},tokens:{total:o.totals.totalTokens,byCategory:{resources:r.resources.tokens,tools:r.tools.tokens}},cost:{totalUsd:`$${r.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${r.resources.costUsd.toFixed(4)}`,tools:`$${r.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:r.resources.byType,toolsByName:r.tools.byName}},null,2)}}if(t==="paradigm_session_recover"){s.setRootDir(n.rootDir);let o=s.loadPreviousSession(),r=s.loadCheckpoint(),i=[];try{i=b$1(n.rootDir);}catch{}if(!o&&i.length===0&&!r)return {handled:true,text:JSON.stringify({found:false,message:"No previous session breadcrumbs, checkpoints, or pending handoffs found.",tip:"Breadcrumbs persist to ~/.paradigm/sessions/ and handoffs persist via paradigm_handoff_prepare. Checkpoints persist via paradigm_session_checkpoint."},null,2)};let a={found:true};if(r){let c=Date.now()-r.timestamp,d=Math.round(c/6e4),u=Math.round(c/36e5);a.checkpoint={phase:r.phase,context:r.context,age:u>1?`${u} hours ago`:`${d} minutes ago`,timestamp:new Date(r.timestamp).toISOString(),sessionId:r.sessionId,plan:r.plan,modifiedFiles:r.modifiedFiles,symbolsTouched:r.symbolsTouched,decisions:r.decisions,recentBreadcrumbs:r.recentBreadcrumbs?.map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}))};}if(o){let c=Date.now()-o.lastActivity,d=Math.round(c/6e4),u=Math.round(c/36e5),g=o.breadcrumbs.slice(-10).map(m=>({time:new Date(m.timestamp).toISOString(),action:m.action,tool:m.tool,symbol:m.symbol,summary:m.summary}));a.previousSession={sessionId:o.sessionId,startTime:new Date(o.startTime).toISOString(),lastActivity:new Date(o.lastActivity).toISOString(),age:u>1?`${u} hours ago`:`${d} minutes ago`},a.context={symbolsModified:o.symbolsModified,filesExplored:o.filesExplored},a.recentActions=g;}if(i.length>0){a.pendingHandoffs=i.map(c=>({id:c.id,timestamp:c.timestamp,from:c.from,to:c.to,summary:c.summary,nextSteps:c.nextSteps,modifiedFiles:c.modifiedFiles,symbolsTouched:c.symbolsTouched,openQuestions:c.openQuestions}));for(let c of i)try{c$1(n.rootDir,c.id);}catch{}}let l="Continue where the previous session left off.";if(r)l=`Previous session was in "${r.phase}" phase: ${r.context}`,r.decisions?.length&&(l+=` Key decisions: ${r.decisions.slice(0,2).join("; ")}`);else if(i.length>0){let c=i[i.length-1];l=`Handoff received: "${c.summary}". `,c.nextSteps.length>0&&(l+=`Start with: ${c.nextSteps[0]}`);}else if(o){let c=o.breadcrumbs.slice(-10);if(c.length>0){let d=c[c.length-1];d.symbol&&(l=`Last work involved ${d.symbol}. Consider checking its current state with paradigm_ripple.`);}}return a.suggestion=l,a.agentInstruction="Present a brief summary of the previous session, then ask the user what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking.",s.markRecovered(),{handled:true,text:JSON.stringify(a,null,2)}}if(t==="paradigm_session_checkpoint"){s.setRootDir(n.rootDir);let o=e.phase,r=e.context,i=e.externalId,a=e.plan,l=e.modifiedFiles,c=e.symbolsTouched,d=e.decisions,{checkpoint:u,persisted:p}=s.saveCheckpoint({phase:o,context:r,externalId:i,plan:a,modifiedFiles:l,symbolsTouched:c,decisions:d}),g=p.local||p.global;return {handled:true,text:JSON.stringify({saved:g,persisted:p,checkpoint:{phase:u.phase,context:u.context,sessionId:u.sessionId,...u.externalId?{externalId:u.externalId}:{},timestamp:new Date(u.timestamp).toISOString(),modifiedFiles:u.modifiedFiles?.length||0,symbolsTouched:u.symbolsTouched?.length||0,decisions:u.decisions?.length||0,recentBreadcrumbs:u.recentBreadcrumbs?.length||0},...g?{note:"Checkpoint saved. Recovery data will be auto-surfaced on the first tool call of the next session."}:{warning:"Checkpoint was NOT persisted to disk. Both local and global writes failed. Check MCP server stderr for details."}},null,2)}}return {handled:false,text:""}}async function Wo(t){let e=j$1();e.setRootDir(t);let n=e.loadCheckpoint(),s=[];try{s=b$1(t);}catch{}if(!n&&s.length===0)return null;let o=[];if(o.push("--- SESSION RECOVERY ---"),n){let r=Date.now()-n.timestamp,i=Math.round(r/6e4),a=Math.round(r/36e5),l=a>1?`${a}h ago`:`${i}m ago`;o.push(`Previous session was in "${n.phase}" phase (${l}): ${n.context}`),n.modifiedFiles?.length&&o.push(`Modified files: ${n.modifiedFiles.join(", ")}`),n.symbolsTouched?.length&&o.push(`Symbols: ${n.symbolsTouched.join(", ")}`),n.decisions?.length&&o.push(`Decisions: ${n.decisions.join("; ")}`),n.plan&&o.push(`Plan: ${n.plan.slice(0,200)}`);}if(s.length>0){let r=s[s.length-1];o.push(`Pending handoff: "${r.summary}"`),r.nextSteps.length>0&&o.push(`Next steps: ${r.nextSteps.slice(0,3).join(", ")}`);}try{let{loadTasks:r}=await import('./task-loader-NZFDTUQ5.js'),i=await r(t,{status:"open",limit:5});if(i.length>0){o.push(""),o.push("Open tasks:");for(let a of i){let l=a.tags.length>0?` [${a.tags.join(", ")}]`:"";o.push(` [${a.priority}] ${a.id}: ${a.blurb}${l}`);}}}catch{}try{let{loadLoreEntries:r}=await import('./lore-loader-RVQI5GXL.js'),a=(await r(t,{limit:10})).filter(l=>l.tags?.some(c=>c.startsWith("arc:")));if(a.length>0){let l=new Map;for(let u of a){let p=u.tags?.find(g=>g.startsWith("arc:"))||"";l.set(p,(l.get(p)||0)+1);}let c=n?.symbolsTouched||[];if((c.length>0?a.filter(u=>u.symbols_touched?.some(p=>c.includes(p))):a.slice(0,3)).length>0||l.size>0){o.push(""),o.push("Active lore arcs:");for(let[u,p]of l)o.push(` ${u} (${p} entries)`);}}}catch{}try{let{loadNominations:r}=await import('./nomination-engine-6VTQ4OVW.js'),i=r(t,{pending_only:!0}).filter(a=>a.urgency==="critical"||a.urgency==="high");if(i.length>0){o.push(""),o.push("Ambient nominations (urgent):");for(let a of i.slice(0,5))o.push(` [${a.urgency}] ${a.brief}`);i.length>5&&o.push(` ... and ${i.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return o.push(""),o.push("IMPORTANT: Present a brief summary of this recovery data to the user, then ask what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking."),o.push("---"),o.join(`
25
25
  `)}var Oe=class{cache=new Map;ttlMs;constructor(e=3e4){this.ttlMs=e;}async getOrCompute(e,n){let s=this.cache.get(e);if(s&&Date.now()-s.createdAt<this.ttlMs)return s.data;let o=await n();return this.cache.set(e,{data:o,createdAt:Date.now()}),o}invalidate(e){this.cache.delete(e);}invalidatePrefix(e){for(let n of this.cache.keys())n.startsWith(e)&&this.cache.delete(n);}clear(){this.cache.clear();}stats(){return {size:this.cache.size,ttlMs:this.ttlMs}}},$t=new Oe(3e4);var rs=300*1e3,ae=null;function It(){ae=null;}function W(t,e){return v.existsSync($.join(t,e))}function J(t,e){return v.existsSync($.join(t,e))}function is(t,e,n){let s=t;try{if(!v.existsSync(s))return !1;let o=v.readdirSync(s,{withFileTypes:!0});for(let r of o){if(r.isFile()&&r.name.endsWith(e))return !0;if(r.isDirectory())try{if(v.readdirSync($.join(s,r.name)).some(a=>a.endsWith(e)))return !0}catch{}}}catch{}return false}var as={wisdom:t=>W(t,".paradigm/wisdom"),history:t=>W(t,".paradigm/history"),lore:t=>W(t,".paradigm/lore"),habits:t=>J(t,".paradigm/habits.yaml"),sentinel:t=>{try{let e=$.join(t,".paradigm","config.yaml");return v.existsSync(e)?v.readFileSync(e,"utf-8").includes("sentinel"):!1}catch{return false}},flows:t=>J(t,".paradigm/flow-index.json")||J(t,".paradigm/flows.yaml"),fixtures:t=>J(t,".paradigm/fixtures.yaml"),orchestration:t=>J(t,".paradigm/agents.yaml"),tasks:t=>W(t,".paradigm/tasks"),assessment:t=>W(t,".paradigm/lore"),personas:t=>is(t,".persona"),protocols:t=>W(t,".paradigm/protocols"),symphony:()=>{let t=$.join(he.homedir(),".paradigm","score");return v.existsSync(t)},university:t=>W(t,".paradigm/university"),agents:t=>{let e=$.join(he.homedir(),".paradigm","agents");return W(t,".paradigm/agents")||v.existsSync(e)},"aspect-graph":t=>J(t,".paradigm/aspect-graph.db"),pan:t=>J(t,".pan")||J(t,"nevr.yaml"),notebooks:t=>{let e=$.join(he.homedir(),".paradigm","notebooks");return W(t,".paradigm/notebooks")||v.existsSync(e)}},Rt=class{modules=new Map;activatedAdvanced=new Set;rootDir;constructor(e){this.rootDir=e;}register(e){this.modules.set(e.key,e);}registerAll(e){for(let n of e)this.register(n);}detectActiveFeatures(){if(ae&&Date.now()-ae.timestamp<rs)return ae.features;let e=new Set;for(let[n,s]of this.modules){if(s.tier==="core"){e.add(n);continue}if(s.tier==="advanced"){this.activatedAdvanced.has(n)&&e.add(n);continue}let o=s.detect||as[n];if(o)try{o(this.rootDir)&&e.add(n);}catch{}else e.add(n);}return ae={features:e,timestamp:Date.now()},e}getActiveTools(){let e=this.detectActiveFeatures(),n=[];for(let[s,o]of this.modules)e.has(s)&&n.push(...o.getToolsList());return n}activateAdvanced(e){let n=this.modules.get(e);return !n||n.tier!=="advanced"?null:(this.activatedAdvanced.add(e),n.getToolsList())}getAvailableAdvanced(){let e=[];for(let[n,s]of this.modules)s.tier==="advanced"&&!this.activatedAdvanced.has(n)&&e.push({key:n,toolCount:s.getToolsList().length});return e}async dispatch(e,n,s,o){let r=this.detectActiveFeatures();for(let[i,a]of this.modules)if(r.has(i))try{let l=await a.handleTool(e,n,s,o);if(l.handled)return l}catch(l){return {handled:true,text:JSON.stringify({error:`Tool handler error in module "${i}"`,message:l.message},null,2)}}return null}get size(){return this.modules.size}getRegistryInfo(){let e=this.detectActiveFeatures(),n={core:0,feature:0,advanced:0};for(let s of this.modules.values())n[s.tier]++;return {total:this.modules.size,byTier:n,activeFeatures:[...e],availableAdvanced:[...this.modules.entries()].filter(([s,o])=>o.tier==="advanced"&&!this.activatedAdvanced.has(s)).map(([s])=>s)}}};var Ne=null;async function hs(){return Ne||(Ne=await ms()),Ne}var ys=[`CREATE TABLE IF NOT EXISTS aspects (
26
26
  id TEXT PRIMARY KEY,
27
27
  description TEXT NOT NULL,
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import {a,e,d}from'./chunk-73R63P7K.js';import'./chunk-5TAVYPOV.js';import*as c from'fs';import*as p from'path';import {execSync}from'child_process';import n from'chalk';import*as w from'js-yaml';function R(s){return s.match(/(?:^|\s)((?:\/|\.\/|[a-zA-Z0-9_-]+\/)[^\s,;:'"]+\.[a-zA-Z]{1,10})\b/)?.[1]}async function $(s,l){try{let a$1=a(s),f=[];try{f=execSync("git diff --name-only HEAD",{cwd:s,encoding:"utf8",timeout:5e3}).trim().split(`
3
3
  `).filter(Boolean);}catch{}let i;try{i=execSync("git status --porcelain",{cwd:s,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let u=p.join(s,"portal.yaml"),g=!1;if(c.existsSync(u))try{let t=c.readFileSync(u,"utf8"),e=w.load(t);g=e?.routes!=null&&Object.keys(e.routes).length>0;}catch{}let r=e({toolsCalled:[],filesModified:f,symbolsTouched:[],loreRecorded:!1,hasPortalRoutes:g,taskAddsRoutes:!1,gitClean:i}),o=d(a$1,l,r),d$1=0;if(o.evaluations.length>0)try{let t=p.join(s,".paradigm","sentinel");if(c.existsSync(t)){let{SentinelStorage:e}=await import('./dist-VGFSP3XM.js'),m=new e(t);for(let b of o.evaluations)m.recordPracticeEvent({habitId:b.habit.id,habitCategory:b.habit.category,result:b.result,engineer:"agent",sessionId:`cli-${Date.now().toString(36)}`,symbolsTouched:[],filesModified:f,notes:b.reason}),d$1++;}}catch{}let h=p.join(s,".paradigm",".habits-blocking");try{if(l==="on-stop"&&o.blocksCompletion){let t=o.evaluations.filter(e=>e.result==="skipped"&&e.habit.severity==="block").map(e=>`${e.habit.name}: ${e.reason}`);c.writeFileSync(h,t.join(`
4
- `),"utf8");}else l==="on-stop"&&c.existsSync(h)&&c.unlinkSync(h);}catch{}return {trigger:l,evaluation:{total:o.summary.total,followed:o.summary.followed,skipped:o.summary.skipped,partial:o.summary.partial,blockingViolations:o.summary.blockingViolations,blocksCompletion:o.blocksCompletion},habits:o.evaluations.map(t=>({id:t.habit.id,name:t.habit.name,category:t.habit.category,severity:t.habit.severity,result:t.result,reason:t.reason,evidence:t.evidence})),recorded:d$1}}catch{return null}}async function P(s,l){let a=p.join(s,".paradigm","aspect-graph.db");if(!c.existsSync(a))return {driftedCount:0,healedCount:0,cleanCount:0,missingCount:0,details:[]};try{let{driftCheckCommand:f}=await import('./drift-ILZE5BFJ.js'),i="",u=console.log;console.log=g=>{i=g;};try{await f({json:!0,autoHeal:l});}finally{console.log=u;}return i?JSON.parse(i):null}catch{return null}}async function B(s){if(!c.existsSync(p.join(s,"portal.yaml")))return null;try{let{checkPortalCompliance:l}=await import('./portal-compliance-4MG5F2GI.js'),a=await l(s);return {status:a.status,declaredButUnusedCount:a.declaredButUnused.length,usedButUndeclaredCount:a.usedButUndeclared.length,properlyDeclaredCount:a.properlyDeclared.length,declaredButUnused:a.declaredButUnused,usedButUndeclared:a.usedButUndeclared,properlyDeclared:a.properlyDeclared}}catch{return null}}async function j(s){try{let{runPostflightLearning:l}=await import('./ambient-2JZTNXUL.js');return await l(s)}catch{return null}}async function A(s){let l=process.cwd(),a=s.trigger||"on-stop",f=s.autoHeal!==false,i=[],u=[],g=await $(l,a),r=await P(l,f),o=await B(l);if(g?.evaluation.blocksCompletion){let t=g.habits.filter(e=>e.result==="skipped"&&e.severity==="block");for(let e of t){let m=`Blocking habit not satisfied: ${e.name} \u2014 ${e.reason}`;i.push(m),u.push({message:m,source:"habits",file:R(e.reason),severity:"blocking"});}}if(r&&r.driftedCount>0){let t=`${r.driftedCount} aspect anchor(s) have drifted (content genuinely changed). Run paradigm_aspect_check to review.`;i.push(t);for(let e of r.details.filter(m=>m.status==="drifted"))u.push({message:`Aspect ~${e.aspectId} drifted at lines ${e.startLine}-${e.endLine}`,source:"drift",file:e.path,severity:"advisory"});u.filter(e=>e.source==="drift").length===0&&u.push({message:t,source:"drift",severity:"advisory"});}if(o&&o.usedButUndeclaredCount>0){let t=`${o.usedButUndeclaredCount} gate(s) used in code but not declared in portal.yaml: ${o.usedButUndeclared.join(", ")}`;i.push(t);for(let e of o.usedButUndeclared)u.push({message:`Gate ^${e} used in code but not declared in portal.yaml`,source:"portal",file:"portal.yaml",severity:"blocking"});}let d=null;s.learn&&(d=await j(l));let h={habits:g,drift:r,portal:o,violations:i,structuredViolations:u,postflight:s.learn?d:void 0};if(s.json)console.log(JSON.stringify(h));else {if(console.log(n.magenta(`
4
+ `),"utf8");}else l==="on-stop"&&c.existsSync(h)&&c.unlinkSync(h);}catch{}return {trigger:l,evaluation:{total:o.summary.total,followed:o.summary.followed,skipped:o.summary.skipped,partial:o.summary.partial,blockingViolations:o.summary.blockingViolations,blocksCompletion:o.blocksCompletion},habits:o.evaluations.map(t=>({id:t.habit.id,name:t.habit.name,category:t.habit.category,severity:t.habit.severity,result:t.result,reason:t.reason,evidence:t.evidence})),recorded:d$1}}catch{return null}}async function P(s,l){let a=p.join(s,".paradigm","aspect-graph.db");if(!c.existsSync(a))return {driftedCount:0,healedCount:0,cleanCount:0,missingCount:0,details:[]};try{let{driftCheckCommand:f}=await import('./drift-ILZE5BFJ.js'),i="",u=console.log;console.log=g=>{i=g;};try{await f({json:!0,autoHeal:l});}finally{console.log=u;}return i?JSON.parse(i):null}catch{return null}}async function B(s){if(!c.existsSync(p.join(s,"portal.yaml")))return null;try{let{checkPortalCompliance:l}=await import('./portal-compliance-4MG5F2GI.js'),a=await l(s);return {status:a.status,declaredButUnusedCount:a.declaredButUnused.length,usedButUndeclaredCount:a.usedButUndeclared.length,properlyDeclaredCount:a.properlyDeclared.length,declaredButUnused:a.declaredButUnused,usedButUndeclared:a.usedButUndeclared,properlyDeclared:a.properlyDeclared}}catch{return null}}async function j(s){try{let{runPostflightLearning:l}=await import('./ambient-BKX77DDQ.js');return await l(s)}catch{return null}}async function A(s){let l=process.cwd(),a=s.trigger||"on-stop",f=s.autoHeal!==false,i=[],u=[],g=await $(l,a),r=await P(l,f),o=await B(l);if(g?.evaluation.blocksCompletion){let t=g.habits.filter(e=>e.result==="skipped"&&e.severity==="block");for(let e of t){let m=`Blocking habit not satisfied: ${e.name} \u2014 ${e.reason}`;i.push(m),u.push({message:m,source:"habits",file:R(e.reason),severity:"blocking"});}}if(r&&r.driftedCount>0){let t=`${r.driftedCount} aspect anchor(s) have drifted (content genuinely changed). Run paradigm_aspect_check to review.`;i.push(t);for(let e of r.details.filter(m=>m.status==="drifted"))u.push({message:`Aspect ~${e.aspectId} drifted at lines ${e.startLine}-${e.endLine}`,source:"drift",file:e.path,severity:"advisory"});u.filter(e=>e.source==="drift").length===0&&u.push({message:t,source:"drift",severity:"advisory"});}if(o&&o.usedButUndeclaredCount>0){let t=`${o.usedButUndeclaredCount} gate(s) used in code but not declared in portal.yaml: ${o.usedButUndeclared.join(", ")}`;i.push(t);for(let e of o.usedButUndeclared)u.push({message:`Gate ^${e} used in code but not declared in portal.yaml`,source:"portal",file:"portal.yaml",severity:"blocking"});}let d=null;s.learn&&(d=await j(l));let h={habits:g,drift:r,portal:o,violations:i,structuredViolations:u,postflight:s.learn?d:void 0};if(s.json)console.log(JSON.stringify(h));else {if(console.log(n.magenta(`
5
5
  Paradigm Compliance Check
6
6
  `)),g){let{evaluation:t}=g,e=t.blocksCompletion?n.red:n.green;console.log(n.white(" Habits:")),console.log(` ${e(`${t.followed} followed, ${t.skipped} skipped, ${t.partial} partial`)}`),t.blockingViolations>0&&console.log(n.red(` ${t.blockingViolations} blocking violation(s)`)),console.log();}if(r&&(console.log(n.white(" Drift:")),r.healedCount>0&&console.log(n.green(` Auto-healed: ${r.healedCount} shifted anchor(s)`)),r.cleanCount>0&&console.log(n.green(` Clean: ${r.cleanCount} anchor(s)`)),r.driftedCount>0&&console.log(n.red(` Drifted: ${r.driftedCount} anchor(s)`)),r.missingCount>0&&console.log(n.yellow(` Missing: ${r.missingCount} anchor file(s)`)),console.log()),o){console.log(n.white(" Portal:"));let t=o.status==="compliant"?n.green:o.status==="warnings"?n.yellow:n.red;console.log(` Status: ${t(o.status)}`),o.usedButUndeclaredCount>0&&console.log(n.red(` ${o.usedButUndeclaredCount} undeclared gate(s)`)),console.log();}if(d){if(console.log(n.white(" Postflight Learning:")),d.journalsWritten>0){console.log(n.green(` Journals written: ${d.journalsWritten}`));for(let[t,e]of Object.entries(d.journalsByAgent))e>0&&console.log(n.gray(` ${t}: ${e} entries`));}else console.log(n.gray(" No verdicts to learn from"));d.promoted>0&&console.log(n.green(` Promoted to notebooks: ${d.promoted}`)),console.log();}if(i.length>0){console.log(n.red(` ${i.length} violation(s):`));for(let t of i)console.log(n.red(` - ${t}`));}else console.log(n.green(" All checks passed."));console.log();}i.length>0&&(process.exitCode=1);}export{A as complianceCheckCommand};