@a-company/paradigm 5.37.4 → 5.37.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/ambient-76YMUA5Q.js +2 -0
  2. package/dist/ambient-WTLYUAQM.js +35 -0
  3. package/dist/{chunk-FILLU77P.js → chunk-3TR6LLXP.js} +2 -2
  4. package/dist/{chunk-WN74JUZA.js → chunk-3VF3CMCF.js} +40 -40
  5. package/dist/{chunk-22ISTMKI.js → chunk-46ZCEIF6.js} +1 -1
  6. package/dist/chunk-AGFPVSX5.js +14 -0
  7. package/dist/{chunk-4Q7XYPL4.js → chunk-BOYQAMGC.js} +3 -3
  8. package/dist/{chunk-D6ZXAI26.js → chunk-CHVQNRRT.js} +60 -20
  9. package/dist/{chunk-JOHAOLEC.js → chunk-G7XFK2GI.js} +4 -4
  10. package/dist/chunk-MQIG6SMF.js +3 -0
  11. package/dist/chunk-NEJ4ZLCY.js +14 -0
  12. package/dist/chunk-RLCH7DXQ.js +4 -0
  13. package/dist/{chunk-SXO7NC6A.js → chunk-SI6SV76D.js} +108 -23
  14. package/dist/{compliance-BPGQMQAX.js → compliance-WJINB5DM.js} +1 -1
  15. package/dist/doctor-QJ47XAUP.js +2 -0
  16. package/dist/{hooks-BNWRGACA.js → hooks-IG2GOAHP.js} +1 -1
  17. package/dist/index.js +4 -4
  18. package/dist/{init-EHVSM7YY.js → init-HIBRSVUB.js} +1 -1
  19. package/dist/mcp.js +1 -1
  20. package/dist/{migrate-YQG2FG3J.js → migrate-IBDE7VK4.js} +1 -1
  21. package/dist/{nomination-engine-KNSOAT4W.js → nomination-engine-EALA5MGI.js} +1 -1
  22. package/dist/notebook-loader-PXNRBBXD.js +2 -0
  23. package/dist/{promote-NJQDZBZA.js → promote-KU2ECEXX.js} +1 -1
  24. package/dist/reindex-FO5VMZVQ.js +2 -0
  25. package/dist/session-tracker-MWJAJA6Z.js +2 -0
  26. package/dist/session-work-log-PAKXOFGL.js +2 -0
  27. package/dist/session-work-log-ZP45TREI.js +2 -0
  28. package/dist/{setup-KPIMRZ4Q.js → setup-6SRJHDA7.js} +1 -1
  29. package/dist/{shift-RRNL6E4O.js → shift-CZMQWZWP.js} +2 -2
  30. package/dist/{switch-CTW4PDGI.js → switch-RXEXXIN7.js} +1 -1
  31. package/dist/tools-BZUAEUSQ.js +2 -0
  32. package/package.json +1 -1
  33. package/dist/ambient-GJAEXF7B.js +0 -35
  34. package/dist/chunk-4SCKMGTB.js +0 -9
  35. package/dist/chunk-UNHTQLYO.js +0 -9
  36. package/dist/chunk-UPFCBVXY.js +0 -3
  37. package/dist/chunk-VG7FN2TU.js +0 -4
  38. package/dist/doctor-G37LCXG5.js +0 -2
  39. package/dist/notebook-loader-CENTDDUJ.js +0 -2
  40. package/dist/reindex-O3WUCEE2.js +0 -2
  41. package/dist/session-tracker-D2CH7RJF.js +0 -2
  42. package/dist/session-work-log-BX434ZLK.js +0 -2
  43. package/dist/session-work-log-NQA7WJEC.js +0 -2
  44. package/dist/tools-ZHOHGFXD.js +0 -2
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import'./chunk-5TAVYPOV.js';import*as s from'path';import t from'chalk';async function g(n){let e=n.project?s.resolve(n.project):process.cwd(),r=n.dryRun===true,{readPendingVerdicts:a}=await import('./session-work-log-PAKXOFGL.js'),i=a(e);if(i.length===0){console.log(t.dim("[paradigm] No pending verdicts \u2014 postflight skipped."));return}console.log(t.cyan(`[paradigm] Running postflight \u2014 ${i.length} pending verdict(s)${r?" (dry run)":""}...`));let{runPostflightLearning:l}=await import('./ambient-WTLYUAQM.js'),o=await l(e,{dry_run:r});if(o.journalsWritten===0&&o.promoted===0){console.log(t.dim("[paradigm] Postflight complete \u2014 no new journals written."));return}console.log(t.green("[paradigm] Postflight complete:")),o.journalsWritten>0&&console.log(` ${t.bold(o.journalsWritten)} journal entries written across ${o.agentsProcessed.length} agent(s)`),o.promoted>0&&console.log(` ${t.bold(o.promoted)} entries auto-promoted to notebooks`);}export{g as ambientPostflightCommand};
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ import {f,p as p$1,i,c as c$1,j}from'./chunk-X3U3IGYT.js';import {e,b as b$2,f as f$1}from'./chunk-AGFPVSX5.js';import {b as b$3}from'./chunk-7SWEOPWF.js';import'./chunk-MBPLJKE5.js';import {c,b as b$1,d,a}from'./chunk-5TAVYPOV.js';import*as p from'fs';import*as b from'path';import*as R from'js-yaml';import*as Z from'os';var kt={};c(kt,{getJournalStats:()=>se,loadAllJournalEntries:()=>re,loadJournalEntries:()=>A,loadJournalEntry:()=>ie,recordJournalEntry:()=>V});function G(e){let t=process.env.HOME||process.env.USERPROFILE||"";return b.join(t,".paradigm","agents",e,"journal")}function oe(){let e=new Date,t=e.toISOString().slice(0,10),n=e.toISOString().slice(11,19).replace(/:/g,""),o=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `LJ-${t}-${n}-${o}`}function V(e,t){let n=new Date,o=oe(),r={id:o,agent:e,timestamp:n.toISOString(),...t},i=G(e);p.mkdirSync(i,{recursive:true});let s=b.join(i,`${o}.yaml`);return p.writeFileSync(s,R.dump(r,{lineWidth:120,noRefs:true}),"utf8"),r}function A(e,t){let n=G(e);if(!p.existsSync(n))return [];let o=[],r=p.readdirSync(n).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=p.readFileSync(b.join(n,s),"utf8"),c=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 ie(e,t){let n=G(e),o=b.join(n,`${t}.yaml`);if(!p.existsSync(o))return null;let r=p.readFileSync(o,"utf8");return R.load(r)}function re(e){let t=process.env.HOME||process.env.USERPROFILE||"",n=b.join(t,".paradigm","agents");if(!p.existsSync(n))return [];let o=[],r=p.readdirSync(n,{withFileTypes:true}).filter(i=>i.isDirectory());for(let i of r){if(e?.agent&&i.name!==e.agent)continue;let s=A(i.name,e);o.push(...s);}return o.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),e?.limit?o.slice(0,e.limit):o}function se(e){let t=A(e),n={},o={},r=0;for(let i of t)n[i.trigger]=(n[i.trigger]||0)+1,o[i.project]=(o[i.project]||0)+1,i.transferable&&r++;return {total:t.length,byTrigger:n,byProject:o,transferableCount:r,recentInsights:t.slice(0,5).map(i=>({id:i.id,trigger:i.trigger,insight:i.insight.slice(0,200),timestamp:i.timestamp}))}}var K=b$1(()=>{});var Rt={};c(Rt,{addNotebookEntry:()=>Tt,classifyNotebookScope:()=>$t,incrementApplied:()=>de,loadNotebookEntries:()=>Nt,promoteFromLore:()=>le,searchNotebooks:()=>ce});function Nt(e,t,n){let o=new Map,r=b.join(X,e);xt(r,o);let i=b.join(t,Y,e);xt(i,o);let s=Array.from(o.values());if(n?.concepts&&n.concepts.length>0){let a=new Set(n.concepts.map(c=>c.toLowerCase()));s=s.filter(c=>c.concepts.some(u=>a.has(u.toLowerCase())));}if(n?.tags&&n.tags.length>0){let a=new Set(n.tags.map(c=>c.toLowerCase()));s=s.filter(c=>c.tags.some(u=>a.has(u.toLowerCase())));}return s.sort((a,c)=>c.appliedCount-a.appliedCount)}function xt(e,t){if(p.existsSync(e))try{let n=p.readdirSync(e).filter(o=>o.startsWith(ae)&&o.endsWith(Q));for(let o of n)try{let r=p.readFileSync(b.join(e,o),"utf-8"),i=R.load(r);i?.id&&t.set(i.id,i);}catch{}}catch{}}function ce(e,t,n){let o=Nt(e,n),r=t.toLowerCase();return o.filter(i=>i.context.toLowerCase().includes(r)||i.snippet.toLowerCase().includes(r)||i.concepts.some(s=>s.toLowerCase().includes(r))||i.tags.some(s=>s.toLowerCase().includes(r)))}function $t(e){let t=[e.context,e.snippet,...e.concepts,...e.tags].join(" ").toLowerCase();return ["paradigm","mcp_","mcp tool",".paradigm/","lore entry","lore record","aspect","^gate","portal.yaml",".purpose","sentinel","symphony","ambient nomination","paradigm_"," pan ","agent notebook","concept anchor","symbol system","work log","knowledge stream","nevr.land","neverland"].some(o=>t.includes(o))?"platform-specific":/[#$^!~][a-z][a-z0-9-]{2,}/.test(t)||/\/[a-z0-9_-]{2,}\/[a-z0-9_-]/.test(t)?"project-specific":"generalizable"}function Tt(e,t,n,o){let r=new Date().toISOString(),i=(t.concepts[0]||t.context.split(" ").slice(0,4).join(" ")||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),a=`nb-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}-${i}`,c=t.scope??$t({context:t.context,snippet:t.snippet,concepts:t.concepts,tags:t.tags}),u={...t,id:a,scope:c,publishable:t.publishable??true,appliedCount:0,created:r,updated:r},d=n==="global"?b.join(X,e):b.join(o||process.cwd(),Y,e);p.existsSync(d)||p.mkdirSync(d,{recursive:true});let l=`${a}${Q}`,m=b.join(d,l),g=R.dump(u,{lineWidth:120,noRefs:true,sortKeys:false});return p.writeFileSync(m,g,"utf-8"),{entry:u,filePath:m}}async function le(e,t,n,o="global"){let{loadLoreEntry:r}=await import('./lore-loader-XY5MZRR2.js'),i=await r(n,t);if(!i)return null;let s=[];if(i.symbols_touched)for(let u of i.symbols_touched){let d=u.replace(/^[#$^!~]/,"").toLowerCase();s.push(d);}let a=i.summary||"";i.body&&(a+=`
3
+
4
+ `+i.body);let c={source:"lore",loreEntryId:t,originProject:b.basename(n),createdBy:e};return Tt(e,{context:i.title||`Promoted from ${t}`,snippet:a,provenance:c,confidence:i.confidence??.7,concepts:s,tags:i.tags||[]},o,n)}function de(e,t,n){let o=b.join(n,Y,e),r=b.join(X,e);for(let i of [o,r]){let s=b.join(i,`${t}${Q}`);if(p.existsSync(s))try{let a=p.readFileSync(s,"utf-8"),c=R.load(a);if(c)return c.appliedCount=(c.appliedCount||0)+1,c.updated=new Date().toISOString(),p.writeFileSync(s,R.dump(c,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var X,Y,ae,Q,Pt=b$1(()=>{X=b.join(Z.homedir(),".paradigm","notebooks"),Y=".paradigm/notebooks",ae="nb-",Q=".yaml";});var ht=".paradigm/events",Yt="stream.jsonl",J=1e3,$=[];function bt(e){return b.join(e,ht,Yt)}function Qt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${e}-${t}`}function M(e,t){let n={id:Qt(),timestamp:new Date().toISOString(),...t};$.push(n),$.length>J&&($=$.slice(-J));try{let o=b.join(e,ht);p.mkdirSync(o,{recursive:!0});let r=bt(e);p.appendFileSync(r,JSON.stringify(n)+`
5
+ `,"utf8"),Zt(r);}catch{}return n}function Zt(e){try{if(p.statSync(e).size>512*1024){let o=p.readFileSync(e,"utf8").trim().split(`
6
+ `);if(o.length>J){let r=o.slice(-J);p.writeFileSync(e,r.join(`
7
+ `)+`
8
+ `,"utf8");}}}catch{}}function St(e,t){let n=te(e);return t?.type&&(n=n.filter(o=>o.type===t.type)),t?.source&&(n=n.filter(o=>o.source===t.source)),t?.symbol&&(n=n.filter(o=>o.symbols?.includes(t.symbol))),t?.agent&&(n=n.filter(o=>o.agent===t.agent)),t?.since&&(n=n.filter(o=>o.timestamp>=t.since)),n.sort((o,r)=>r.timestamp.localeCompare(o.timestamp)),t?.limit&&(n=n.slice(0,t.limit)),n}function te(e){let t=bt(e);if(!p.existsSync(t))return [...$];try{return p.readFileSync(t,"utf8").trim().split(`
9
+ `).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return [...$]}}function wt(e,t,n){let o=0,r=0,i=0,s=0;if(n.symbols?.length&&e.symbols?.length)for(let d of n.symbols)for(let l of e.symbols)yt(d,l)&&(o=Math.max(o,1));if(n.paths?.length&&e.path){for(let d of n.paths)if(yt(d,e.path)){r=1;break}}if(n.concepts?.length){let d=[e.context||"",...e.keywords||[],e.type||""].join(" ").toLowerCase(),l=0;for(let m of n.concepts)m&&d.includes(m.toLowerCase())&&l++;n.concepts.length>0&&(i=l/n.concepts.length);}if(n.signals?.length){for(let d of n.signals)if(d.type===e.type){s=1;break}}let a=[o,r,i,s].sort((d,l)=>l-d),c=a[0]*.5+a[1]*.2+a[2]*.15+a[3]*.15,u=n.threshold??.6;return {agentId:t,score:c,breakdown:{symbolMatch:o,pathMatch:r,conceptMatch:i,signalMatch:s},shouldNominate:c>=u,quietReason:c<u?"below-threshold":void 0}}function yt(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var ee=".paradigm/data-policy.yaml";function jt(e){let t=b.join(e,ee);if(!p.existsSync(t))return {...b$3};try{let n=p.readFileSync(t,"utf8"),o=R.load(n);return ne(b$3,o)}catch{return {...b$3}}}function ne(e,t){let n={...e};if(t.version&&(n.version=t.version),t.default_ring&&(n.default_ring=t.default_ring),t.observation&&(n.observation={allow:t.observation.allow||e.observation?.allow,deny:[...e.observation?.deny||[],...t.observation.deny||[]].filter((o,r,i)=>i.indexOf(o)===r)}),t.streams){n.streams={...e.streams};for(let o of ["work_log","learning_journal","team_decisions"])t.streams[o]&&(n.streams[o]={...e.streams?.[o],...t.streams[o],deny_content:[...e.streams?.[o]?.deny_content||[],...t.streams[o]?.deny_content||[]].filter((r,i,s)=>s.indexOf(r)===i)});}return t.upstream&&(n.upstream={...e.upstream,...t.upstream}),t.network&&(n.network={...e.network,...t.network}),t.agent_overrides&&(n.agent_overrides={...e.agent_overrides,...t.agent_overrides}),t.deployment&&(n.deployment={...e.deployment,...t.deployment}),n}function Et(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(r=>z(r,t))||e.observation?.deny?.some(o=>z(o,t))?false:e.observation?.allow?.length?e.observation.allow.some(o=>z(o,t)):true}function z(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var N=".paradigm/events",ue="nominations.jsonl",me="debates.jsonl",fe=500,pe=200,ge=7,ye=14,he=100;function be(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function Se(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${e}-${t}`}function we(e,t){let n=i(e),o=jt(e),r=[];for(let u of n){if(!u.attention||!c$1(u.id,e)||t.path&&!Et(o,t.path,u.id))continue;let d=wt(t,u.id,u.attention);d.shouldNominate&&r.push({profile:u,score:d});}if(r.length===0)return {nominations:[],debates:[]};let i$1=E(e,{since:new Date(Date.now()-3e4).toISOString()}),s=r.filter(({profile:u})=>!i$1.find(l=>l.agent===u.id&&l.brief===At(u,t,{...r.find(m=>m.profile.id===u.id).score})));if(s.length===0)return {nominations:[],debates:[]};let a=s.map(({profile:u,score:d})=>{let l=_e(t,d),m=ve(u,t);return {id:be(),agent:u.id,relevance:d.score,urgency:l,type:m,brief:At(u,t,d),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});Ee(e,a);let c=je(e,a);return c.length>0&&ke(e,c),{nominations:a,debates:c}}function _e(e,t){return e.severity==="critical"?"critical":e.severity==="error"||e.type==="compliance-violation"||e.type==="error-encountered"?"high":e.type==="gate-added"||e.type==="route-created"||t.score>=.9?"medium":"low"}function ve(e,t){let n=e.collaboration?.stance;return t.type==="compliance-violation"||t.type==="error-encountered"?"warning":t.type==="gate-added"||t.type==="route-created"?"observation":n==="advisory"||n==="lead"?"suggestion":"observation"}function At(e,t,n){let o=e.role||e.id;switch(t.type){case "gate-checked":return `${o}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${o}: ${t.path||"File"} modified \u2014 review for ${e.id==="security"?"security implications":e.id==="tester"?"test coverage":e.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${o}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${o}: New route ${t.symbols?.join(", ")||""} \u2014 ${e.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${o}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${e.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${o}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${o}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${o}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let r=n.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:n.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${o}: ${r}`}}}function je(e,t){if(t.length<2)return [];let n=[],o=new Map;for(let r of t)for(let i of r.triggered_by){let s=o.get(i)||[];s.push(r),o.set(i,s);}for(let[r,i]of o){if(i.length<2||new Set(i.map(u=>u.agent)).size<2)continue;let a=new Set(i.map(u=>u.type)),c=a.size>1&&a.has("warning")&&a.has("suggestion");n.push({id:Se(),topic:`Multiple agents responded to event ${r}`,nominations:i.map(u=>u.id),type:c?"conflicting":"complementary",overlap_events:[r]});}return n}function tt(e){return b.join(e,N,ue)}function et(e){return b.join(e,N,me)}function Ee(e,t){try{let n=b.join(e,N);p.mkdirSync(n,{recursive:!0});let o=tt(e),r=t.map(s=>JSON.stringify(s)).join(`
10
+ `)+`
11
+ `;p.appendFileSync(o,r,"utf8"),Ot(o,fe);let{nominationTtlDays:i}=H(e);Ft(o,i*24*60*60*1e3);}catch{}}function ke(e,t){try{let n=b.join(e,N);p.mkdirSync(n,{recursive:!0});let o=et(e),r=t.map(s=>JSON.stringify(s)).join(`
12
+ `)+`
13
+ `;p.appendFileSync(o,r,"utf8"),Ot(o,pe);let{debateTtlDays:i}=H(e);Ft(o,i*24*60*60*1e3);}catch{}}function Ot(e,t){try{let o=p.readFileSync(e,"utf8").trim().split(`
14
+ `).filter(r=>r.trim());if(o.length>t){let r=o.slice(-t);p.writeFileSync(e,r.join(`
15
+ `)+`
16
+ `,"utf8");}}catch{}}function H(e){let t={nominationTtlDays:ge,debateTtlDays:ye};try{let n=b.join(e,".paradigm","config.yaml");if(!p.existsSync(n))return t;let o=a("js-yaml"),r=p.readFileSync(n,"utf8"),s=o.load(r)?.ambient;return s?{nominationTtlDays:typeof s["nomination-ttl-days"]=="number"?s["nomination-ttl-days"]:t.nominationTtlDays,debateTtlDays:typeof s["debate-ttl-days"]=="number"?s["debate-ttl-days"]:t.debateTtlDays}:t}catch{return t}}function Ft(e,t){try{if(!p.existsSync(e))return;let o=p.readFileSync(e,"utf8").trim().split(`
17
+ `).filter(s=>s.trim());if(o.length<=he)return;let r=Date.now()-t,i=o.filter(s=>{try{let a=JSON.parse(s);return (a.timestamp?new Date(a.timestamp).getTime():Date.now())>=r}catch{return !0}});i.length<o.length&&p.writeFileSync(e,i.join(`
18
+ `)+`
19
+ `,"utf8");}catch{}}function E(e,t){let n=tt(e);if(!p.existsSync(n))return [];try{let r=p.readFileSync(n,"utf8").trim().split(`
20
+ `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null);return t?.agent&&(r=r.filter(i=>i.agent===t.agent)),t?.urgency&&(r=r.filter(i=>i.urgency===t.urgency)),t?.surfaced!==void 0&&(r=r.filter(i=>i.surfaced===t.surfaced)),t?.pending_only&&(r=r.filter(i=>!i.engaged)),t?.since&&(r=r.filter(i=>i.timestamp>=t.since)),r.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),t?.limit&&(r=r.slice(0,t.limit)),r}catch{return []}}function Ct(e){let t=et(e);if(!p.existsSync(t))return [];try{return p.readFileSync(t,"utf8").trim().split(`
21
+ `).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return []}}function It(e,t,n,o){let r=tt(e);if(!p.existsSync(r))return false;try{let s=p.readFileSync(r,"utf8").trim().split(`
22
+ `),a=!1,c=s.map(u=>{try{let d=JSON.parse(u);return d.id===t?(d.engaged=!0,d.response=n,o&&(d.reason=o),a=!0,JSON.stringify(d)):u}catch{return u}});if(a&&(p.writeFileSync(r,c.join(`
23
+ `)+`
24
+ `,"utf8"),n==="accepted"||n==="dismissed")){let u=JSON.parse(s.find(l=>{try{return JSON.parse(l).id===t}catch{return !1}}));i(e).find(l=>l.id===u.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&M(e,{type:"work-completed",source:"agent-action",agent:u.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return a}catch{return false}}function Jt(e,t,n,o){let r=et(e);if(!p.existsSync(r))return false;try{let s=p.readFileSync(r,"utf8").trim().split(`
25
+ `),a=!1,c=s.map(u=>{try{let d=JSON.parse(u);if(d.id===t){d.resolution={chosen:n,reason:o,resolved_by:"human",resolved_at:new Date().toISOString()},a=!0;let l=d.nominations.filter(m=>m!==n);for(let m of l){let g=E(e).find(f=>f.id===m);g&&M(e,{type:"work-completed",source:"agent-action",agent:g.agent,context:`Debate ${t} resolved \u2014 nomination ${m} not chosen`,data:{debate_id:t,chosen:n,reason:o}});}return JSON.stringify(d)}return u}catch{return u}});return a&&p.writeFileSync(r,c.join(`
26
+ `)+`
27
+ `,"utf8"),a}catch{return false}}function Mt(e){let t=b.join(e,N,".last-processed"),n="";try{p.existsSync(t)&&(n=p.readFileSync(t,"utf8").trim());}catch{}let o=b.join(e,N,"stream.jsonl");if(!p.existsSync(o))return {processed:0,nominations:[]};let r=[];try{r=p.readFileSync(o,"utf8").trim().split(`
28
+ `).filter(l=>l.trim()).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(l=>l!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(n){let d=r.findIndex(l=>l.id===n);d>=0&&(i=d+1);}let s=r.slice(i);if(s.length===0)return {processed:0,nominations:[]};let a=[],c=s.slice(0,50);for(let d of c){let{nominations:l}=we(e,d);a.push(...l);}let u=c[c.length-1];try{p.mkdirSync(b.join(e,N),{recursive:!0}),p.writeFileSync(t,u.id,"utf8");}catch{}return {processed:c.length,nominations:a}}function Lt(e,t){let n=f(e,t);if(!n?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let o=n.attention.threshold??.6,{nominationTtlDays:r}=H(e),i=r*24*60*60*1e3,c=E(e,{agent:t}).filter(j=>j.engaged||Date.now()-new Date(j.timestamp).getTime()<i).filter(j=>j.engaged);if(c.length<5)return {adjusted:false,oldThreshold:o,newThreshold:o,reason:`Insufficient data (${c.length}/5 engaged nominations)`};let u=c.filter(j=>j.response==="accepted").length,d=c.filter(j=>j.response==="dismissed").length,l=u/c.length,m=d/c.length,g=o,f$1="No adjustment needed";if(m>.6?(g=Math.min(.95,o+.05),f$1=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):l>.8&&(g=Math.max(.2,o-.05),f$1=`High accept rate (${(l*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),g===o)return {adjusted:false,oldThreshold:o,newThreshold:g,reason:f$1};n.attention.threshold=g;let y=b.join(e,".paradigm/agents",`${t}.agent`),D=p.existsSync(y)?"project":"global";return j(t,n,D,e),M(e,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${o.toFixed(2)} \u2192 ${g.toFixed(2)} (${f$1})`,data:{old_threshold:o,new_threshold:g,accept_rate:l,dismiss_rate:m}}),{adjusted:true,oldThreshold:o,newThreshold:g,reason:f$1}}function nt(e,t){let{nominationTtlDays:n}=H(e),o=n*24*60*60*1e3,i=E(e,{agent:t}).filter(l=>l.engaged||Date.now()-new Date(l.timestamp).getTime()<o),s=i.filter(l=>l.response==="accepted").length,a=i.filter(l=>l.response==="dismissed").length,c=i.filter(l=>l.response==="deferred").length,u=i.filter(l=>!l.engaged).length,d=s+a+c;return {total:i.length,accepted:s,dismissed:a,deferred:c,pending:u,acceptRate:d>0?s/d:0}}function Ht(e){let n=i(e).filter(l=>c$1(l.id,e)).map(l=>{let m=nt(e,l.id),g=0;try{let f=b.join(Z.homedir(),".paradigm","notebooks",l.id);p.existsSync(f)&&(g=p.readdirSync(f).filter(y=>y.endsWith(".yaml")).length);}catch{}return {id:l.id,acceptRate:m.acceptRate,threshold:l.attention?.threshold??.5,expertiseCount:(l.expertise||[]).length,notebookCount:g,transferableCount:(l.transferable||[]).length,totalNominations:m.total}}),o=n.length||1,r=n.reduce((l,m)=>l+m.acceptRate,0)/o,i$1=n.reduce((l,m)=>l+m.threshold,0)/o,s=n.reduce((l,m)=>l+m.expertiseCount,0),a=n.reduce((l,m)=>l+m.notebookCount,0),c=n.reduce((l,m)=>l+m.transferableCount,0),u=n.reduce((l,m)=>l+m.totalNominations,0),d;return u<10?d="cold-start":r<.5?d="accumulating":r<.7?d="calibrating":d="mature",{agents:n,aggregate:{avgAcceptRate:r,avgThreshold:i$1,totalExpertise:s,totalNotebooks:a,totalTransferable:c},healthStatus:d}}function ot(e,t){let n,o;try{let c=(K(),d(kt)),u=(Pt(),d(Rt));n=c.loadJournalEntries,o=u.addNotebookEntry;}catch{return {promoted:0,entries:[]}}let r=n(t,{trigger:"pattern_discovered",limit:100}),i=n(t,{trigger:"human_feedback",limit:100}),s=[...r,...i],a=[];for(let c of s)if(!c.promoted_to_notebook&&!((c.confidence_after??0)<.8))try{let{entry:u}=o(t,{context:c.pattern?.applies_when||c.insight.slice(0,80),snippet:c.pattern?.correct_approach||c.insight,concepts:c.tags||[c.pattern?.id||"learned-pattern"],provenance:{source:"lore",loreEntryId:c.id,createdBy:t}},"global",e);a.push({journalId:c.id,notebookId:u.id});try{let d=b.join(Z.homedir(),".paradigm","agents",t,"journal");if(p.existsSync(d)){let l=p.readdirSync(d).filter(m=>m.endsWith(".yaml"));for(let m of l){let g=b.join(d,m),f=p.readFileSync(g,"utf8");if(f.includes(c.id)){let y=f.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${u.id}"`);if(y===f){let D=f.trimEnd().split(`
29
+ `);D.push(`promoted_to_notebook: "${u.id}"`),p.writeFileSync(g,D.join(`
30
+ `)+`
31
+ `,"utf8");}else p.writeFileSync(g,y,"utf8");break}}}}catch{}}catch{}return {promoted:a.length,entries:a}}var xe=".paradigm/surfacing.yaml";function Ut(e){let t=b.join(e,xe),n={default_min_urgency:"low",enable_debates:true};if(!p.existsSync(t))return n;try{let o=a("js-yaml"),r=p.readFileSync(t,"utf8"),i=o.load(r);return {...n,...i}}catch{return n}}function Bt(e,t){let n={critical:0,high:1,medium:2,low:3},o=n[t.default_min_urgency||"low"]??3;return e.filter(r=>{let i=n[r.urgency]??3;if(t.preferences){let s=t.preferences.find(a=>a.agent===r.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(c=>r.urgency===c||r.type===c))return false;if(s.min_urgency){let a=n[s.min_urgency]??3;return i<=a}}}return i<=o})}var De=".paradigm/decisions";function Wt(e,t){let n=b.join(e,De);if(!p.existsSync(n))return [];let o=[],r=p.readdirSync(n).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=p.readFileSync(b.join(n,s),"utf8"),c=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 Ke(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function Ne(e){let t=Date.now(),n=e.match(/^(\d+)(m|h|d)$/);if(n){let o=parseInt(n[1],10),r=n[2],i=r==="m"?o*6e4:r==="h"?o*36e5:o*864e5;return new Date(t-i).toISOString()}return e}async function Xe(e,t,n){let o=r=>JSON.stringify(r,null,2);switch(e){case "paradigm_ambient_nominations":{Mt(n.rootDir);let i=t.pending_only!==false,s=t.limit||20,a=E(n.rootDir,{agent:t.agent,urgency:t.urgency,pending_only:i,limit:s+20}),c=Ut(n.rootDir);a=Bt(a,c).slice(0,s);let u=b.join(n.rootDir,".paradigm/events/nominations.jsonl");if(p.existsSync(u))try{let l=p.readFileSync(u,"utf8"),m=new Set(a.map(f=>f.id)),g=l.trim().split(`
32
+ `).map(f=>{try{let y=JSON.parse(f);return m.has(y.id)?(y.surfaced=!0,JSON.stringify(y)):f}catch{return f}});p.writeFileSync(u,g.join(`
33
+ `)+`
34
+ `,"utf8");}catch{}let d={count:a.length,nominations:a.map(l=>({id:l.id,agent:l.agent,urgency:l.urgency,type:l.type,brief:l.brief,relevance:l.relevance,timestamp:l.timestamp,engaged:l.engaged,response:l.response}))};if(t.include_debates){let m=Ct(n.rootDir).filter(g=>!g.resolution);d.debates=m.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),d.debate_count=m.length;}return {text:o(d),handled:true}}case "paradigm_ambient_events":{let r=t.since?Ne(t.since):void 0,i=t.limit||50,s=St(n.rootDir,{type:t.type,source:t.source,symbol:t.symbol,agent:t.agent,since:r,limit:i});return {text:o({count:s.length,events:s.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let r=t.nomination_id,i=t.response,s=t.reason,a=It(n.rootDir,r,i,s);if(a)try{let{appendSessionWorkEntry:u,appendVerdictEntry:d}=await import('./session-work-log-PAKXOFGL.js'),m=E(n.rootDir,{limit:500}).find(f=>f.id===r),g={timestamp:new Date().toISOString(),type:"user-verdict",agent:m?.agent,nominationId:r,verdict:i,reason:s};u(n.rootDir,g),d(n.rootDir,g);}catch{}let c=false;return t.resolve_debate&&a&&(c=Jt(n.rootDir,t.resolve_debate,r,t.reason)),{text:o({engaged:a,nomination_id:r,response:i,debate_resolved:c||void 0}),handled:true}}case "paradigm_context_compose":{let r=t.agent,i=t.symbols||[],s=t.include_nominations!==false,a=t.include_decisions!==false,c=t.include_journal!==false,u=t.max_decisions||5,d=t.max_journal||5,l=f(n.rootDir,r);if(!l)return {text:o({error:`Agent profile not found: ${r}`}),handled:true};let m=[],g=p$1(l,i);if(g.trim()&&m.push(g),a){let f=Wt(n.rootDir,{status:"active",limit:u});if(f.length>0){m.push("## Recent Team Decisions");for(let y of f)m.push(`- **${y.title}**: ${y.decision.slice(0,150)}${y.decision.length>150?"...":""}`);m.push("");}}if(c){let f=A(r,{transferable:true,limit:d});if(f.length>0){m.push("## Transferable Insights");for(let y of f)m.push(`- [${y.trigger}] ${y.insight.slice(0,150)}${y.insight.length>150?"...":""}`);m.push("");}}if(s){let f=E(n.rootDir,{pending_only:true,limit:10});if(f.length>0){m.push("## Pending Nominations");for(let y of f)m.push(`- [${y.urgency}] ${y.brief}`);m.push("");}}return {text:o({agent:r,context:m.join(`
35
+ `),sections_included:{profile:true,decisions:a,journal:c,nominations:s}}),handled:true}}case "paradigm_ambient_promote":{let r=t.agent,i=ot(n.rootDir,r);return {text:o({agent:r,promoted:i.promoted,entries:i.entries}),handled:true}}case "paradigm_ambient_learn":{let r=t.agent,i=t.dry_run===true,s=nt(n.rootDir,r);if(i)return {text:o({agent:r,dry_run:true,stats:s,note:s.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(s.acceptRate*100).toFixed(0)}% \u2014 ${s.acceptRate>.8?"would lower threshold":s.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=Lt(n.rootDir,r);return {text:o({agent:r,...a,stats:s}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let r=Ht(n.rootDir);return {text:o(r),handled:true}}case "paradigm_ambient_learn_postflight":return {text:o(await Re(n.rootDir,t)),handled:true};default:return {text:`Unknown ambient tool: ${e}`,handled:false}}}var $e={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function Te(e){try{let t=b.join(e,".paradigm","config.yaml");if(p.existsSync(t)){let o=p.readFileSync(t,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(o)return o[1].trim()}}catch{}return b.basename(e)}async function Re(e$1,t={}){let n=t.dry_run===true,o=Te(e$1),r=e(e$1).filter(f=>f.verdict&&f.agent),i=b$2(e$1);if(r.length===0)return {sessionEntries:i.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:n,details:[]};let s=new Map;for(let f of r){let y=f.agent;s.has(y)||s.set(y,[]),s.get(y).push(f);}let a=i.filter(f=>f.type==="agent-contribution"),c=new Map;for(let f of a)f.agent&&(c.has(f.agent)||c.set(f.agent,[]),c.get(f.agent).push(f));let u=[],d={},l=0;for(let[f,y]of s){d[f]=0;let D=y.filter(h=>h.verdict==="accepted").length;y.filter(h=>h.verdict==="dismissed").length;y.filter(h=>h.verdict==="revised").length;let U=y.length,zt=U>0?D/U:0;for(let h of y){let B=$e[h.verdict];if(!B)continue;let Gt=c.get(f)?.shift(),st=Pe(h,Gt,{acceptRate:zt,total:U,accepted:D}),Vt=h.verdict==="accepted"?.85:h.verdict==="revised"?.6:.4,Kt={agent:f,verdict:h.verdict,trigger:B,insight:st,symbols:h.symbols};if(u.push(Kt),n)d[f]++,l++;else try{V(f,{trigger:B,insight:st,confidence_before:h.verdict==="accepted"?.7:.8,confidence_after:Vt,project:o,transferable:h.verdict==="dismissed",tags:["postflight",`verdict:${h.verdict}`,...(h.symbols||[]).map(Xt=>`symbol:${Xt}`)]}),d[f]++,l++;}catch{}}}let m={},g=0;if(!n)for(let f of s.keys())try{let y=ot(e$1,f);y.promoted>0&&(m[f]=y.promoted,g+=y.promoted);}catch{}return !n&&r.length>0&&f$1(e$1,r.map(f=>f.nominationId).filter(Boolean)),{sessionEntries:i.length,agentsProcessed:Array.from(s.keys()),journalsWritten:l,journalsByAgent:d,promoted:g,promotedByAgent:m,dryRun:n,details:u}}function Pe(e,t,n){let o=e.symbols?.length?` (symbols: ${e.symbols.join(", ")})`:"",r=e.reason?` Reason: ${e.reason}.`:"";switch(e.verdict){case "accepted":return `Contribution accepted by user${o}.${r}`+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(n.acceptRate*100).toFixed(0)}% (${n.accepted}/${n.total}).`;case "dismissed":return `Contribution dismissed by user${o}.${r}`+(t?.contribution?` Rejected contribution: "${t.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(n.acceptRate*100).toFixed(0)}% (${n.accepted}/${n.total}).`;case "revised":return `Contribution revised by user${o}.${r}`+(e.revisionDelta?` Delta: "${e.revisionDelta.slice(0,120)}".`:"")+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(n.acceptRate*100).toFixed(0)}% (${n.accepted}/${n.total}).`;default:return `Unknown verdict "${e.verdict}"${o}.${r}`}}export{Ke as getAmbientToolsList,Xe as handleAmbientTool,Re as runPostflightLearning};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a as a$1,b as b$3,c as c$2}from'./chunk-M4UMM6DC.js';import {j,b as b$2,a as a$2}from'./chunk-ODVKPZZ4.js';import {j as j$1,a,c as c$1,b as b$1,k as k$1}from'./chunk-UPFCBVXY.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as x from'fs';import*as k from'path';import*as J from'crypto';import {execSync}from'child_process';import*as F from'js-yaml';import {z}from'zod';import {glob}from'glob';import*as ye from'os';import hs from'sql.js';var Nt={};c(Nt,{contentSearch:()=>ms,detectFileRename:()=>Ot,generateFingerprint:()=>At,levenshteinDistance:()=>Lt,levenshteinSimilarity:()=>Fe,searchSiblingFiles:()=>Ft,slidingWindowSearch:()=>be});function At(t){let e=t.split(`
2
+ import {a as a$1,b as b$3,c as c$2}from'./chunk-M4UMM6DC.js';import {j,b as b$2,a as a$2}from'./chunk-ODVKPZZ4.js';import {j as j$1,a,c as c$1,b as b$1,k as k$1}from'./chunk-MQIG6SMF.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as x from'fs';import*as k from'path';import*as J from'crypto';import {execSync}from'child_process';import*as F from'js-yaml';import {z}from'zod';import {glob}from'glob';import*as ye from'os';import hs from'sql.js';var Nt={};c(Nt,{contentSearch:()=>ms,detectFileRename:()=>Ot,generateFingerprint:()=>At,levenshteinDistance:()=>Lt,levenshteinSimilarity:()=>Fe,searchSiblingFiles:()=>Ft,slidingWindowSearch:()=>be});function At(t){let e=t.split(`
3
3
  `).filter(s=>s.trim()!=="");return {firstLine:we(e[0]||""),lastLine:we(e[e.length-1]||""),lineCount:e.length,structuralHash:jt(e)}}function jt(t){let e=t.map(s=>s.trim()).filter(s=>Pt.test(s)).map(s=>{let n=s.match(Pt);return n?n[1].trim():""}).join("|");return J.createHash("sha256").update(e).digest("hex").slice(0,16)}function we(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function Lt(t,e){if(t===e)return 0;if(t.length===0)return e.length;if(e.length===0)return t.length;t.length>e.length&&([t,e]=[e,t]);let s=t.length,n=e.length;if(s>5e3||n>5e3)return Math.abs(s-n);let o=new Array(s+1),r=new Array(s+1);for(let i=0;i<=s;i++)o[i]=i;for(let i=1;i<=n;i++){r[0]=i;for(let a=1;a<=s;a++){let c=t[a-1]===e[i-1]?0:1;r[a]=Math.min(o[a]+1,r[a-1]+1,o[a-1]+c);}[o,r]=[r,o];}return o[s]}function Fe(t,e){if(t.length===0&&e.length===0)return 1;let s=Math.max(t.length,e.length);return 1-Lt(t,e)/s}function be(t,e,s,n=3){let{lineCount:o}=e,r=Math.max(1,Math.floor(o*.8)),i=Math.ceil(o*1.2),a=[],c=Oe(s);for(let d of [o,r,i])if(!(d>t.length))for(let u=0;u<=t.length-d;u++){let p=t.slice(u,u+d),m=gs(p,e,c);if(m>=.5){let g=p.join(`
4
4
  `);a.push({windowStart:u+1,windowEnd:u+d,similarity:Fe(Oe(g),c),score:m});}}let l=new Map;for(let d of a){let u=l.get(d.windowStart);(!u||d.score>u.score)&&l.set(d.windowStart,d);}return Array.from(l.values()).sort((d,u)=>u.score-d.score).slice(0,n)}function gs(t,e,s){let n=t.filter(p=>p.trim()!=="");if(n.length===0)return 0;let o=0,r=we(n[0]),i=we(n[n.length-1]),a=0;r===e.firstLine&&(a+=.5),i===e.lastLine&&(a+=.5),o+=a*ds,jt(n)===e.structuralHash&&(o+=us);let l=n.join(`
5
5
  `),d=Fe(Oe(l),s);d>=.8&&(o+=(d-.8)/.2*ps);let u=n.length/e.lineCount;if(u>=.8&&u<=1.2){let p=1-Math.abs(1-u)/.2;o+=p*fs;}return o}function Oe(t){return t.split(`
@@ -21,7 +21,7 @@ ${r.map((T,E)=>`${E+1}. ${T}`).join(`
21
21
  - Modified files: ${a$1.length>0?a$1.join(", "):"(not specified)"}
22
22
  - Symbols touched: ${c.length>0?c.join(", "):"(not specified)"}
23
23
  - Open questions: ${l.length>0?l.join(", "):"(none)"}
24
- `;return os(),{handled:true,text:JSON.stringify({handoff:g,markdownSummary:v,persisted:h,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let o=n.getStats(),r=n.getCostBreakdown(),i=n.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"){let{checkpoint:o,pendingHandoffs:r,previousSession:i}=$t(s.rootDir);if(!i&&r.length===0&&!o)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(o){let l=Date.now()-o.timestamp,d=Math.round(l/6e4),u=Math.round(l/36e5);a.checkpoint={phase:o.phase,context:o.context,age:u>1?`${u} hours ago`:`${d} minutes ago`,timestamp:new Date(o.timestamp).toISOString(),sessionId:o.sessionId,plan:o.plan,modifiedFiles:o.modifiedFiles,symbolsTouched:o.symbolsTouched,decisions:o.decisions,recentBreadcrumbs:o.recentBreadcrumbs?.map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}))};}if(i){let l=Date.now()-i.lastActivity,d=Math.round(l/6e4),u=Math.round(l/36e5),m=i.breadcrumbs.slice(-10).map(g=>({time:new Date(g.timestamp).toISOString(),action:g.action,tool:g.tool,symbol:g.symbol,summary:g.summary}));a.previousSession={sessionId:i.sessionId,startTime:new Date(i.startTime).toISOString(),lastActivity:new Date(i.lastActivity).toISOString(),age:u>1?`${u} hours ago`:`${d} minutes ago`},a.context={symbolsModified:i.symbolsModified,filesExplored:i.filesExplored},a.recentActions=m;}if(r.length>0){a.pendingHandoffs=r.map(l=>({id:l.id,timestamp:l.timestamp,from:l.from,to:l.to,summary:l.summary,nextSteps:l.nextSteps,modifiedFiles:l.modifiedFiles,symbolsTouched:l.symbolsTouched,openQuestions:l.openQuestions}));for(let l of r)try{c$1(s.rootDir,l.id);}catch{}}let c="Continue where the previous session left off.";if(o)c=`Previous session was in "${o.phase}" phase: ${o.context}`,o.decisions?.length&&(c+=` Key decisions: ${o.decisions.slice(0,2).join("; ")}`);else if(r.length>0){let l=r[r.length-1];c=`Handoff received: "${l.summary}". `,l.nextSteps.length>0&&(c+=`Start with: ${l.nextSteps[0]}`);}else if(i){let l=i.breadcrumbs.slice(-10);if(l.length>0){let d=l[l.length-1];d.symbol&&(c=`Last work involved ${d.symbol}. Consider checking its current state with paradigm_ripple.`);}}return a.suggestion=c,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.",n.markRecovered(),{handled:true,text:JSON.stringify(a,null,2)}}if(t==="paradigm_session_checkpoint"){n.setRootDir(s.rootDir);let o=e.phase,r=e.context,i=e.externalId,a=e.plan,c=e.modifiedFiles,l=e.symbolsTouched,d=e.decisions,{checkpoint:u,persisted:p}=n.saveCheckpoint({phase:o,context:r,externalId:i,plan:a,modifiedFiles:c,symbolsTouched:l,decisions:d}),m=p.local||p.global;return {handled:true,text:JSON.stringify({saved:m,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},...m?{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:""}}function $t(t){let e=j$1();e.setRootDir(t);let s=e.loadCheckpoint(),n=e.loadPreviousSession(),o=[];try{o=b$1(t);}catch{}return {checkpoint:s,pendingHandoffs:o,previousSession:n}}async function Go(t){let{checkpoint:e,pendingHandoffs:s}=$t(t);if(!e&&s.length===0)return null;let n=[];if(n.push("--- SESSION RECOVERY ---"),e){let o=Date.now()-e.timestamp,r=Math.round(o/6e4),i=Math.round(o/36e5),a=i>1?`${i}h ago`:`${r}m ago`;n.push(`Previous session was in "${e.phase}" phase (${a}): ${e.context}`),e.modifiedFiles?.length&&n.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&n.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&n.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&n.push(`Plan: ${e.plan.slice(0,200)}`);}if(s.length>0){let o=s[s.length-1];n.push(`Pending handoff: "${o.summary}"`),o.nextSteps.length>0&&n.push(`Next steps: ${o.nextSteps.slice(0,3).join(", ")}`);}try{let{loadTasks:o}=await import('./task-loader-NZFDTUQ5.js'),r=await o(t,{status:"open",limit:5});if(r.length>0){n.push(""),n.push("Open tasks:");for(let i of r){let a=i.tags.length>0?` [${i.tags.join(", ")}]`:"";n.push(` [${i.priority}] ${i.id}: ${i.blurb}${a}`);}}}catch{}try{let{loadLoreEntries:o}=await import('./lore-loader-RVQI5GXL.js'),i=(await o(t,{limit:10})).filter(a=>a.tags?.some(c=>c.startsWith("arc:")));if(i.length>0){let a=new Map;for(let d of i){let u=d.tags?.find(p=>p.startsWith("arc:"))||"";a.set(u,(a.get(u)||0)+1);}let c=e?.symbolsTouched||[];if((c.length>0?i.filter(d=>d.symbols_touched?.some(u=>c.includes(u))):i.slice(0,3)).length>0||a.size>0){n.push(""),n.push("Active lore arcs:");for(let[d,u]of a)n.push(` ${d} (${u} entries)`);}}}catch{}try{let{loadNominations:o}=await import('./nomination-engine-KNSOAT4W.js'),r=o(t,{pending_only:!0}).filter(i=>i.urgency==="critical"||i.urgency==="high");if(r.length>0){n.push(""),n.push("Ambient nominations (urgent):");for(let i of r.slice(0,5))n.push(` [${i.urgency}] ${i.brief}`);r.length>5&&n.push(` ... and ${r.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return n.push(""),n.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."),n.push("---"),n.join(`
24
+ `;return os(),{handled:true,text:JSON.stringify({handoff:g,markdownSummary:v,persisted:h,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let o=n.getStats(),r=n.getCostBreakdown(),i=n.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"){let{checkpoint:o,pendingHandoffs:r,previousSession:i}=$t(s.rootDir);if(!i&&r.length===0&&!o)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(o){let l=Date.now()-o.timestamp,d=Math.round(l/6e4),u=Math.round(l/36e5);a.checkpoint={phase:o.phase,context:o.context,age:u>1?`${u} hours ago`:`${d} minutes ago`,timestamp:new Date(o.timestamp).toISOString(),sessionId:o.sessionId,plan:o.plan,modifiedFiles:o.modifiedFiles,symbolsTouched:o.symbolsTouched,decisions:o.decisions,recentBreadcrumbs:o.recentBreadcrumbs?.map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}))};}if(i){let l=Date.now()-i.lastActivity,d=Math.round(l/6e4),u=Math.round(l/36e5),m=i.breadcrumbs.slice(-10).map(g=>({time:new Date(g.timestamp).toISOString(),action:g.action,tool:g.tool,symbol:g.symbol,summary:g.summary}));a.previousSession={sessionId:i.sessionId,startTime:new Date(i.startTime).toISOString(),lastActivity:new Date(i.lastActivity).toISOString(),age:u>1?`${u} hours ago`:`${d} minutes ago`},a.context={symbolsModified:i.symbolsModified,filesExplored:i.filesExplored},a.recentActions=m;}if(r.length>0){a.pendingHandoffs=r.map(l=>({id:l.id,timestamp:l.timestamp,from:l.from,to:l.to,summary:l.summary,nextSteps:l.nextSteps,modifiedFiles:l.modifiedFiles,symbolsTouched:l.symbolsTouched,openQuestions:l.openQuestions}));for(let l of r)try{c$1(s.rootDir,l.id);}catch{}}let c="Continue where the previous session left off.";if(o)c=`Previous session was in "${o.phase}" phase: ${o.context}`,o.decisions?.length&&(c+=` Key decisions: ${o.decisions.slice(0,2).join("; ")}`);else if(r.length>0){let l=r[r.length-1];c=`Handoff received: "${l.summary}". `,l.nextSteps.length>0&&(c+=`Start with: ${l.nextSteps[0]}`);}else if(i){let l=i.breadcrumbs.slice(-10);if(l.length>0){let d=l[l.length-1];d.symbol&&(c=`Last work involved ${d.symbol}. Consider checking its current state with paradigm_ripple.`);}}return a.suggestion=c,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.",n.markRecovered(),{handled:true,text:JSON.stringify(a,null,2)}}if(t==="paradigm_session_checkpoint"){n.setRootDir(s.rootDir);let o=e.phase,r=e.context,i=e.externalId,a=e.plan,c=e.modifiedFiles,l=e.symbolsTouched,d=e.decisions,{checkpoint:u,persisted:p}=n.saveCheckpoint({phase:o,context:r,externalId:i,plan:a,modifiedFiles:c,symbolsTouched:l,decisions:d}),m=p.local||p.global;return {handled:true,text:JSON.stringify({saved:m,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},...m?{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:""}}function $t(t){let e=j$1();e.setRootDir(t);let s=e.loadCheckpoint(),n=e.loadPreviousSession(),o=[];try{o=b$1(t);}catch{}return {checkpoint:s,pendingHandoffs:o,previousSession:n}}async function Go(t){let{checkpoint:e,pendingHandoffs:s}=$t(t);if(!e&&s.length===0)return null;let n=[];if(n.push("--- SESSION RECOVERY ---"),e){let o=Date.now()-e.timestamp,r=Math.round(o/6e4),i=Math.round(o/36e5),a=i>1?`${i}h ago`:`${r}m ago`;n.push(`Previous session was in "${e.phase}" phase (${a}): ${e.context}`),e.modifiedFiles?.length&&n.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&n.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&n.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&n.push(`Plan: ${e.plan.slice(0,200)}`);}if(s.length>0){let o=s[s.length-1];n.push(`Pending handoff: "${o.summary}"`),o.nextSteps.length>0&&n.push(`Next steps: ${o.nextSteps.slice(0,3).join(", ")}`);}try{let{loadTasks:o}=await import('./task-loader-NZFDTUQ5.js'),r=await o(t,{status:"open",limit:5});if(r.length>0){n.push(""),n.push("Open tasks:");for(let i of r){let a=i.tags.length>0?` [${i.tags.join(", ")}]`:"";n.push(` [${i.priority}] ${i.id}: ${i.blurb}${a}`);}}}catch{}try{let{loadLoreEntries:o}=await import('./lore-loader-RVQI5GXL.js'),i=(await o(t,{limit:10})).filter(a=>a.tags?.some(c=>c.startsWith("arc:")));if(i.length>0){let a=new Map;for(let d of i){let u=d.tags?.find(p=>p.startsWith("arc:"))||"";a.set(u,(a.get(u)||0)+1);}let c=e?.symbolsTouched||[];if((c.length>0?i.filter(d=>d.symbols_touched?.some(u=>c.includes(u))):i.slice(0,3)).length>0||a.size>0){n.push(""),n.push("Active lore arcs:");for(let[d,u]of a)n.push(` ${d} (${u} entries)`);}}}catch{}try{let{loadNominations:o}=await import('./nomination-engine-EALA5MGI.js'),r=o(t,{pending_only:!0}).filter(i=>i.urgency==="critical"||i.urgency==="high");if(r.length>0){n.push(""),n.push("Ambient nominations (urgent):");for(let i of r.slice(0,5))n.push(` [${i.urgency}] ${i.brief}`);r.length>5&&n.push(` ... and ${r.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return n.push(""),n.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."),n.push("---"),n.join(`
25
25
  `)}var Le=class{cache=new Map;ttlMs;constructor(e=3e4){this.ttlMs=e;}async getOrCompute(e,s){let n=this.cache.get(e);if(n&&Date.now()-n.createdAt<this.ttlMs)return n.data;let o=await s();return this.cache.set(e,{data:o,createdAt:Date.now()}),o}invalidate(e){this.cache.delete(e);}invalidatePrefix(e){for(let s of this.cache.keys())s.startsWith(e)&&this.cache.delete(s);}clear(){this.cache.clear();}stats(){return {size:this.cache.size,ttlMs:this.ttlMs}}},Rt=new Le(3e4);var is=300*1e3,ae=null;function kt(){ae=null;}function G(t,e){return x.existsSync(k.join(t,e))}function Y(t,e){return x.existsSync(k.join(t,e))}function as(t,e,s){let n=t;try{if(!x.existsSync(n))return !1;let o=x.readdirSync(n,{withFileTypes:!0});for(let r of o){if(r.isFile()&&r.name.endsWith(e))return !0;if(r.isDirectory())try{if(x.readdirSync(k.join(n,r.name)).some(a=>a.endsWith(e)))return !0}catch{}}}catch{}return false}var cs={wisdom:t=>G(t,".paradigm/wisdom"),history:t=>G(t,".paradigm/history"),lore:t=>G(t,".paradigm/lore"),habits:t=>Y(t,".paradigm/habits.yaml"),sentinel:t=>{try{let e=k.join(t,".paradigm","config.yaml");return x.existsSync(e)?x.readFileSync(e,"utf-8").includes("sentinel"):!1}catch{return false}},flows:t=>Y(t,".paradigm/flow-index.json")||Y(t,".paradigm/flows.yaml"),fixtures:t=>Y(t,".paradigm/fixtures.yaml"),orchestration:t=>Y(t,".paradigm/agents.yaml"),tasks:t=>G(t,".paradigm/tasks"),assessment:t=>G(t,".paradigm/lore"),personas:t=>as(t,".persona"),protocols:t=>G(t,".paradigm/protocols"),symphony:()=>{let t=k.join(ye.homedir(),".paradigm","score");return x.existsSync(t)},university:t=>G(t,".paradigm/university"),agents:t=>{let e=k.join(ye.homedir(),".paradigm","agents");return G(t,".paradigm/agents")||x.existsSync(e)},"aspect-graph":t=>Y(t,".paradigm/aspect-graph.db"),pan:t=>Y(t,".pan")||Y(t,"nevr.yaml"),notebooks:t=>{let e=k.join(ye.homedir(),".paradigm","notebooks");return G(t,".paradigm/notebooks")||x.existsSync(e)}},It=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 s of e)this.register(s);}detectActiveFeatures(){if(ae&&Date.now()-ae.timestamp<is)return ae.features;let e=new Set;for(let[s,n]of this.modules){if(n.tier==="core"){e.add(s);continue}if(n.tier==="advanced"){this.activatedAdvanced.has(s)&&e.add(s);continue}let o=n.detect||cs[s];if(o)try{o(this.rootDir)&&e.add(s);}catch{}else e.add(s);}return ae={features:e,timestamp:Date.now()},e}getActiveTools(){let e=this.detectActiveFeatures(),s=[];for(let[n,o]of this.modules)e.has(n)&&s.push(...o.getToolsList());return s}activateAdvanced(e){let s=this.modules.get(e);return !s||s.tier!=="advanced"?null:(this.activatedAdvanced.add(e),s.getToolsList())}getAvailableAdvanced(){let e=[];for(let[s,n]of this.modules)n.tier==="advanced"&&!this.activatedAdvanced.has(s)&&e.push({key:s,toolCount:n.getToolsList().length});return e}async dispatch(e,s,n,o){let r=this.detectActiveFeatures();for(let[i,a]of this.modules)if(r.has(i))try{let c=await a.handleTool(e,s,n,o);if(c.handled)return c}catch(c){return {handled:true,text:JSON.stringify({error:`Tool handler error in module "${i}"`,message:c.message},null,2)}}return null}get size(){return this.modules.size}getRegistryInfo(){let e=this.detectActiveFeatures(),s={core:0,feature:0,advanced:0};for(let n of this.modules.values())s[n.tier]++;return {total:this.modules.size,byTier:s,activeFeatures:[...e],availableAdvanced:[...this.modules.entries()].filter(([n,o])=>o.tier==="advanced"&&!this.activatedAdvanced.has(n)).map(([n])=>n)}}};var Ne=null;async function ys(){return Ne||(Ne=await hs()),Ne}var ws=[`CREATE TABLE IF NOT EXISTS aspects (
26
26
  id TEXT PRIMARY KEY,
27
27
  description TEXT NOT NULL,