@a-company/paradigm 5.27.1 → 5.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-loader-CZFB5BDP.js +2 -0
- package/dist/agent-loader-EBERCNMO.js +2 -0
- package/dist/{ambient-2RAKMUC7.js → ambient-S3CXHD7P.js} +9 -9
- package/dist/{chunk-DJERXYEL.js → chunk-5KSNYRT7.js} +5 -5
- package/dist/{chunk-HBGRP73K.js → chunk-AYYS2AMB.js} +1 -1
- package/dist/chunk-QWL3LERH.js +3 -0
- package/dist/{chunk-UELDOSWH.js → chunk-SL3RZQPW.js} +1 -1
- package/dist/chunk-U4J5J7GG.js +3 -0
- package/dist/{chunk-PBVBTHGE.js → chunk-VKGY42FP.js} +1 -1
- package/dist/{chunk-4YIKDQRB.js → chunk-VNQGILQU.js} +2 -2
- package/dist/{compliance-LM2NN2S6.js → compliance-5OYNHE5D.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/mcp.js +41 -41
- package/dist/{nomination-engine-K7MQD53E.js → nomination-engine-LMSZ2CAS.js} +1 -1
- package/dist/reindex-BSD7ZIEY.js +2 -0
- package/dist/session-tracker-FDFL4PZI.js +2 -0
- package/dist/{session-work-log-IEYBPFUC.js → session-work-log-5PHOUEQ6.js} +1 -1
- package/dist/{session-work-log-HFOD7LEG.js → session-work-log-LWEGZ5CN.js} +1 -1
- package/package.json +1 -1
- package/dist/agent-loader-MQMXCI3D.js +0 -2
- package/dist/agent-loader-RGPE3LRD.js +0 -2
- package/dist/chunk-XGAOYG77.js +0 -3
- package/dist/chunk-ZMQXXFG2.js +0 -3
- package/dist/reindex-HA3CJG7S.js +0 -2
- package/dist/session-tracker-G7VOLRMR.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {v}from'./chunk-QWL3LERH.js';export{p as buildProfileEnrichment,r as checkPathPermission,s as checkToolPermission,t as computeIntegrityHash,k as createAgentProfile,a as decayedConfidence,g as findAgentsByNickname,c as isAgentActive,e as listAllGlobalAgentIds,f as loadAgentProfile,i as loadAllAgentProfiles,b as loadProjectRoster,o as mergeAgentProfileWithManifest,l as queryExpertise,h as resolveAgent,j as saveAgentProfile,d as saveProjectRoster,q as syncExpertiseFromLore,n as updateExpertiseFromAssessment,m as updateExpertiseFromLore,u as verifyIntegrity}from'./chunk-QWL3LERH.js';import'./chunk-5TAVYPOV.js';v();
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
export{p as buildProfileEnrichment,r as checkPathPermission,s as checkToolPermission,t as computeIntegrityHash,k as createAgentProfile,a as decayedConfidence,g as findAgentsByNickname,c as isAgentActive,e as listAllGlobalAgentIds,f as loadAgentProfile,i as loadAllAgentProfiles,b as loadProjectRoster,o as mergeAgentProfileWithManifest,l as queryExpertise,h as resolveAgent,j as saveAgentProfile,d as saveProjectRoster,q as syncExpertiseFromLore,n as updateExpertiseFromAssessment,m as updateExpertiseFromLore,u as verifyIntegrity}from'./chunk-U4J5J7GG.js';import'./chunk-5TAVYPOV.js';
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {f as f$1,
|
|
2
|
+
import {f as f$1,p,i,j}from'./chunk-U4J5J7GG.js';import {b as b$2}from'./chunk-VKGY42FP.js';import {c,b as b$1,d,a}from'./chunk-5TAVYPOV.js';import*as f from'fs';import*as b from'path';import*as P from'js-yaml';import*as Q from'os';var vt={};c(vt,{getJournalStats:()=>ne,loadAllJournalEntries:()=>ee,loadJournalEntries:()=>O,loadJournalEntry:()=>te,recordJournalEntry:()=>z});function G(n){let t=process.env.HOME||process.env.USERPROFILE||"";return b.join(t,".paradigm","agents",n,"journal")}function Zt(){let n=new Date,t=n.toISOString().slice(0,10),e=n.toISOString().slice(11,19).replace(/:/g,""),o=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `LJ-${t}-${e}-${o}`}function z(n,t){let e=new Date,o=Zt(),i={id:o,agent:n,timestamp:e.toISOString(),...t},r=G(n);f.mkdirSync(r,{recursive:true});let s=b.join(r,`${o}.yaml`);return f.writeFileSync(s,P.dump(i,{lineWidth:120,noRefs:true}),"utf8"),i}function O(n,t){let e=G(n);if(!f.existsSync(e))return [];let o=[],i=f.readdirSync(e).filter(s=>s.endsWith(".yaml"));for(let s of i)try{let a=f.readFileSync(b.join(e,s),"utf8"),c=P.load(a);c&&c.id&&o.push(c);}catch{}let r=o;return t?.trigger&&(r=r.filter(s=>s.trigger===t.trigger)),t?.project&&(r=r.filter(s=>s.project===t.project)),t?.transferable!==void 0&&(r=r.filter(s=>s.transferable===t.transferable)),t?.tag&&(r=r.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(r=r.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(r=r.filter(s=>s.timestamp<=t.dateTo)),r.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(r=r.slice(0,t.limit)),r}function te(n,t){let e=G(n),o=b.join(e,`${t}.yaml`);if(!f.existsSync(o))return null;let i=f.readFileSync(o,"utf8");return P.load(i)}function ee(n){let t=process.env.HOME||process.env.USERPROFILE||"",e=b.join(t,".paradigm","agents");if(!f.existsSync(e))return [];let o=[],i=f.readdirSync(e,{withFileTypes:true}).filter(r=>r.isDirectory());for(let r of i){if(n?.agent&&r.name!==n.agent)continue;let s=O(r.name,n);o.push(...s);}return o.sort((r,s)=>s.timestamp.localeCompare(r.timestamp)),n?.limit?o.slice(0,n.limit):o}function ne(n){let t=O(n),e={},o={},i=0;for(let r of t)e[r.trigger]=(e[r.trigger]||0)+1,o[r.project]=(o[r.project]||0)+1,r.transferable&&i++;return {total:t.length,byTrigger:e,byProject:o,transferableCount:i,recentInsights:t.slice(0,5).map(r=>({id:r.id,trigger:r.trigger,insight:r.insight.slice(0,200),timestamp:r.timestamp}))}}var K=b$1(()=>{});var Dt={};c(Dt,{addNotebookEntry:()=>xt,incrementApplied:()=>se,loadNotebookEntries:()=>Et,promoteFromLore:()=>ie,searchNotebooks:()=>re});function Et(n,t,e){let o=new Map,i=b.join(V,n);jt(i,o);let r=b.join(t,Y,n);jt(r,o);let s=Array.from(o.values());if(e?.concepts&&e.concepts.length>0){let a=new Set(e.concepts.map(c=>c.toLowerCase()));s=s.filter(c=>c.concepts.some(d=>a.has(d.toLowerCase())));}if(e?.tags&&e.tags.length>0){let a=new Set(e.tags.map(c=>c.toLowerCase()));s=s.filter(c=>c.tags.some(d=>a.has(d.toLowerCase())));}return s.sort((a,c)=>c.appliedCount-a.appliedCount)}function jt(n,t){if(f.existsSync(n))try{let e=f.readdirSync(n).filter(o=>o.startsWith(oe)&&o.endsWith(X));for(let o of e)try{let i=f.readFileSync(b.join(n,o),"utf-8"),r=P.load(i);r?.id&&t.set(r.id,r);}catch{}}catch{}}function re(n,t,e){let o=Et(n,e),i=t.toLowerCase();return o.filter(r=>r.context.toLowerCase().includes(i)||r.snippet.toLowerCase().includes(i)||r.concepts.some(s=>s.toLowerCase().includes(i))||r.tags.some(s=>s.toLowerCase().includes(i)))}function xt(n,t,e,o){let i=new Date().toISOString(),r=(t.concepts[0]||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),s=Date.now().toString(36),a=`nb-${r}-${s}`,c={...t,id:a,appliedCount:0,created:i,updated:i},d=e==="global"?b.join(V,n):b.join(o||process.cwd(),Y,n);f.existsSync(d)||f.mkdirSync(d,{recursive:true});let u=`${a}${X}`,l=b.join(d,u),m=P.dump(c,{lineWidth:120,noRefs:true,sortKeys:false});return f.writeFileSync(l,m,"utf-8"),{entry:c,filePath:l}}async function ie(n,t,e,o="global"){let{loadLoreEntry:i}=await import('./lore-loader-XY5MZRR2.js'),r=await i(e,t);if(!r)return null;let s=[];if(r.symbols_touched)for(let d of r.symbols_touched){let u=d.replace(/^[#$^!~]/,"").toLowerCase();s.push(u);}let a=r.summary||"";r.body&&(a+=`
|
|
3
3
|
|
|
4
4
|
`+r.body);let c={source:"lore",loreEntryId:t,originProject:b.basename(e),createdBy:n};return xt(n,{context:r.title||`Promoted from ${t}`,snippet:a,provenance:c,confidence:r.confidence??.7,concepts:s,tags:r.tags||[]},o,e)}function se(n,t,e){let o=b.join(e,Y,n),i=b.join(V,n);for(let r of [o,i]){let s=b.join(r,`${t}${X}`);if(f.existsSync(s))try{let a=f.readFileSync(s,"utf-8"),c=P.load(a);if(c)return c.appliedCount=(c.appliedCount||0)+1,c.updated=new Date().toISOString(),f.writeFileSync(s,P.dump(c,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var V,Y,oe,X,Rt=b$1(()=>{V=b.join(Q.homedir(),".paradigm","notebooks"),Y=".paradigm/notebooks",oe="nb-",X=".yaml";});var ft=".paradigm/events",zt="stream.jsonl",I=1e3,N=[];function gt(n){return b.join(n,ft,zt)}function Kt(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${n}-${t}`}function J(n,t){let e={id:Kt(),timestamp:new Date().toISOString(),...t};N.push(e),N.length>I&&(N=N.slice(-I));try{let o=b.join(n,ft);f.mkdirSync(o,{recursive:!0});let i=gt(n);f.appendFileSync(i,JSON.stringify(e)+`
|
|
5
5
|
`,"utf8"),Vt(i);}catch{}return e}function Vt(n){try{if(f.statSync(n).size>512*1024){let o=f.readFileSync(n,"utf8").trim().split(`
|
|
6
6
|
`);if(o.length>I){let i=o.slice(-I);f.writeFileSync(n,i.join(`
|
|
7
7
|
`)+`
|
|
8
8
|
`,"utf8");}}}catch{}}function yt(n,t){let e=Yt(n);return t?.type&&(e=e.filter(o=>o.type===t.type)),t?.source&&(e=e.filter(o=>o.source===t.source)),t?.symbol&&(e=e.filter(o=>o.symbols?.includes(t.symbol))),t?.agent&&(e=e.filter(o=>o.agent===t.agent)),t?.since&&(e=e.filter(o=>o.timestamp>=t.since)),e.sort((o,i)=>i.timestamp.localeCompare(o.timestamp)),t?.limit&&(e=e.slice(0,t.limit)),e}function Yt(n){let t=gt(n);if(!f.existsSync(t))return [...N];try{return f.readFileSync(t,"utf8").trim().split(`
|
|
9
|
-
`).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null)}catch{return [...N]}}function ht(n,t,e){let o=0,i=0,r=0,s=0;if(e.symbols?.length&&n.symbols?.length)for(let u of e.symbols)for(let l of n.symbols)pt(u,l)&&(o=Math.max(o,1));if(e.paths?.length&&n.path){for(let u of e.paths)if(pt(u,n.path)){i=1;break}}if(e.concepts?.length){let u=[n.context||"",...n.keywords||[],n.type].join(" ").toLowerCase(),l=0;for(let m of e.concepts)u.includes(m.toLowerCase())&&l++;e.concepts.length>0&&(r=l/e.concepts.length);}if(e.signals?.length){for(let u of e.signals)if(u.type===n.type){s=1;break}}let a=[o,i,r,s].sort((u,l)=>l-u),c=a[0]*.5+a[1]*.2+a[2]*.15+a[3]*.15,d=e.threshold??.6;return {agentId:t,score:c,breakdown:{symbolMatch:o,pathMatch:i,conceptMatch:r,signalMatch:s},shouldNominate:c>=d,quietReason:c<d?"below-threshold":void 0}}function pt(n,t){if(n===t)return true;let e=n.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${e}$`).test(t)}catch{return false}}var M={version:"1.0",default_ring:"project-locked",observation:{allow:["src/**",".paradigm/**","portal.yaml"],deny:[".env*","**/*.key","**/*.pem","**/secrets/**"]},streams:{work_log:{ring:"project-locked",allow_content:["file_paths","symbol_names","outcome"],deny_content:["code_snippets","file_contents","diff_content"]},learning_journal:{ring:"user-scoped",allow_content:["pattern_descriptions","confidence_adjustments","approach_descriptions"],deny_content:["code_snippets","file_contents","symbol_names_with_context"],redaction:[{pattern:"\\b[A-Z_]{2,}_KEY\\b"},{pattern:"password|secret|token"}]},team_decisions:{ring:"project-locked",allow_content:["rationale","alternatives","symbol_references"],deny_content:["implementation_details"]}},upstream:{ring:"creator-upstream",allowed:["task_type","outcome","helpfulness","duration_bucket","error_category"],denied:["code_of_any_kind","file_paths","symbol_names","conversation_content","user_identity"]},network:{ring:"network-public",opt_in:false,if_opted_in:["aggregated_task_success_rates","anonymized_pattern_frequency"]}};var Xt=".paradigm/data-policy.yaml";function St(n){let t=b.join(n,Xt);if(!f.existsSync(t))return {...M};try{let e=f.readFileSync(t,"utf8"),o=P.load(e);return Qt(M,o)}catch{return {...M}}}function Qt(n,t){let e={...n};if(t.version&&(e.version=t.version),t.default_ring&&(e.default_ring=t.default_ring),t.observation&&(e.observation={allow:t.observation.allow||n.observation?.allow,deny:[...n.observation?.deny||[],...t.observation.deny||[]].filter((o,i,r)=>r.indexOf(o)===i)}),t.streams){e.streams={...n.streams};for(let o of ["work_log","learning_journal","team_decisions"])t.streams[o]&&(e.streams[o]={...n.streams?.[o],...t.streams[o],deny_content:[...n.streams?.[o]?.deny_content||[],...t.streams[o]?.deny_content||[]].filter((i,r,s)=>s.indexOf(i)===r)});}return t.upstream&&(e.upstream={...n.upstream,...t.upstream}),t.network&&(e.network={...n.network,...t.network}),t.agent_overrides&&(e.agent_overrides={...n.agent_overrides,...t.agent_overrides}),t.deployment&&(e.deployment={...n.deployment,...t.deployment}),e}function wt(n,t,e){return e&&n.agent_overrides?.[e]?.observation&&n.agent_overrides[e].observation.deny?.some(i=>q(i,t))||n.observation?.deny?.some(o=>q(o,t))?false:n.observation?.allow?.length?n.observation.allow.some(o=>q(o,t)):true}function q(n,t){if(n===t)return true;let e=n.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${e}$`).test(t)}catch{return false}}var R=".paradigm/events",ae="nominations.jsonl",ce="debates.jsonl",le=500,de=200,ue=7,me=14,pe=100;function fe(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${n}-${t}`}function ge(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${n}-${t}`}function ye(n,t){let e=
|
|
9
|
+
`).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null)}catch{return [...N]}}function ht(n,t,e){let o=0,i=0,r=0,s=0;if(e.symbols?.length&&n.symbols?.length)for(let u of e.symbols)for(let l of n.symbols)pt(u,l)&&(o=Math.max(o,1));if(e.paths?.length&&n.path){for(let u of e.paths)if(pt(u,n.path)){i=1;break}}if(e.concepts?.length){let u=[n.context||"",...n.keywords||[],n.type].join(" ").toLowerCase(),l=0;for(let m of e.concepts)u.includes(m.toLowerCase())&&l++;e.concepts.length>0&&(r=l/e.concepts.length);}if(e.signals?.length){for(let u of e.signals)if(u.type===n.type){s=1;break}}let a=[o,i,r,s].sort((u,l)=>l-u),c=a[0]*.5+a[1]*.2+a[2]*.15+a[3]*.15,d=e.threshold??.6;return {agentId:t,score:c,breakdown:{symbolMatch:o,pathMatch:i,conceptMatch:r,signalMatch:s},shouldNominate:c>=d,quietReason:c<d?"below-threshold":void 0}}function pt(n,t){if(n===t)return true;let e=n.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${e}$`).test(t)}catch{return false}}var M={version:"1.0",default_ring:"project-locked",observation:{allow:["src/**",".paradigm/**","portal.yaml"],deny:[".env*","**/*.key","**/*.pem","**/secrets/**"]},streams:{work_log:{ring:"project-locked",allow_content:["file_paths","symbol_names","outcome"],deny_content:["code_snippets","file_contents","diff_content"]},learning_journal:{ring:"user-scoped",allow_content:["pattern_descriptions","confidence_adjustments","approach_descriptions"],deny_content:["code_snippets","file_contents","symbol_names_with_context"],redaction:[{pattern:"\\b[A-Z_]{2,}_KEY\\b"},{pattern:"password|secret|token"}]},team_decisions:{ring:"project-locked",allow_content:["rationale","alternatives","symbol_references"],deny_content:["implementation_details"]}},upstream:{ring:"creator-upstream",allowed:["task_type","outcome","helpfulness","duration_bucket","error_category"],denied:["code_of_any_kind","file_paths","symbol_names","conversation_content","user_identity"]},network:{ring:"network-public",opt_in:false,if_opted_in:["aggregated_task_success_rates","anonymized_pattern_frequency"]}};var Xt=".paradigm/data-policy.yaml";function St(n){let t=b.join(n,Xt);if(!f.existsSync(t))return {...M};try{let e=f.readFileSync(t,"utf8"),o=P.load(e);return Qt(M,o)}catch{return {...M}}}function Qt(n,t){let e={...n};if(t.version&&(e.version=t.version),t.default_ring&&(e.default_ring=t.default_ring),t.observation&&(e.observation={allow:t.observation.allow||n.observation?.allow,deny:[...n.observation?.deny||[],...t.observation.deny||[]].filter((o,i,r)=>r.indexOf(o)===i)}),t.streams){e.streams={...n.streams};for(let o of ["work_log","learning_journal","team_decisions"])t.streams[o]&&(e.streams[o]={...n.streams?.[o],...t.streams[o],deny_content:[...n.streams?.[o]?.deny_content||[],...t.streams[o]?.deny_content||[]].filter((i,r,s)=>s.indexOf(i)===r)});}return t.upstream&&(e.upstream={...n.upstream,...t.upstream}),t.network&&(e.network={...n.network,...t.network}),t.agent_overrides&&(e.agent_overrides={...n.agent_overrides,...t.agent_overrides}),t.deployment&&(e.deployment={...n.deployment,...t.deployment}),e}function wt(n,t,e){return e&&n.agent_overrides?.[e]?.observation&&n.agent_overrides[e].observation.deny?.some(i=>q(i,t))||n.observation?.deny?.some(o=>q(o,t))?false:n.observation?.allow?.length?n.observation.allow.some(o=>q(o,t)):true}function q(n,t){if(n===t)return true;let e=n.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${e}$`).test(t)}catch{return false}}var R=".paradigm/events",ae="nominations.jsonl",ce="debates.jsonl",le=500,de=200,ue=7,me=14,pe=100;function fe(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${n}-${t}`}function ge(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${n}-${t}`}function ye(n,t){let e=i(n),o=St(n),i$1=[];for(let d of e){if(!d.attention||d.benched||t.path&&!wt(o,t.path,d.id))continue;let u=ht(t,d.id,d.attention);u.shouldNominate&&i$1.push({profile:d,score:u});}if(i$1.length===0)return {nominations:[],debates:[]};let r=k(n,{since:new Date(Date.now()-3e4).toISOString()}),s=i$1.filter(({profile:d})=>!r.find(l=>l.agent===d.id&&l.brief===Nt(d,t,{...i$1.find(m=>m.profile.id===d.id).score})));if(s.length===0)return {nominations:[],debates:[]};let a=s.map(({profile:d,score:u})=>{let l=he(t,u),m=be(d,t);return {id:fe(),agent:d.id,relevance:u.score,urgency:l,type:m,brief:Nt(d,t,u),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});Se(n,a);let c=_e(n,a);return c.length>0&&we(n,c),{nominations:a,debates:c}}function he(n,t){return n.severity==="critical"?"critical":n.severity==="error"||n.type==="compliance-violation"||n.type==="error-encountered"?"high":n.type==="gate-added"||n.type==="route-created"||t.score>=.9?"medium":"low"}function be(n,t){let e=n.collaboration?.stance;return t.type==="compliance-violation"||t.type==="error-encountered"?"warning":t.type==="gate-added"||t.type==="route-created"?"observation":e==="advisory"||e==="lead"?"suggestion":"observation"}function Nt(n,t,e){let o=n.role||n.id;switch(t.type){case "gate-checked":return `${o}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${o}: ${t.path||"File"} modified \u2014 review for ${n.id==="security"?"security implications":n.id==="tester"?"test coverage":n.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${o}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${o}: New route ${t.symbols?.join(", ")||""} \u2014 ${n.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${o}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${n.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${o}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${o}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${o}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let i=e.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:e.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${o}: ${i}`}}}function _e(n,t){if(t.length<2)return [];let e=[],o=new Map;for(let i of t)for(let r of i.triggered_by){let s=o.get(r)||[];s.push(i),o.set(r,s);}for(let[i,r]of o){if(r.length<2||new Set(r.map(d=>d.agent)).size<2)continue;let a=new Set(r.map(d=>d.type)),c=a.size>1&&a.has("warning")&&a.has("suggestion");e.push({id:ge(),topic:`Multiple agents responded to event ${i}`,nominations:r.map(d=>d.id),type:c?"conflicting":"complementary",overlap_events:[i]});}return e}function Z(n){return b.join(n,R,ae)}function tt(n){return b.join(n,R,ce)}function Se(n,t){try{let e=b.join(n,R);f.mkdirSync(e,{recursive:!0});let o=Z(n),i=t.map(s=>JSON.stringify(s)).join(`
|
|
10
10
|
`)+`
|
|
11
11
|
`;f.appendFileSync(o,i,"utf8"),Tt(o,le);let{nominationTtlDays:r}=U(n);Pt(o,r*24*60*60*1e3);}catch{}}function we(n,t){try{let e=b.join(n,R);f.mkdirSync(e,{recursive:!0});let o=tt(n),i=t.map(s=>JSON.stringify(s)).join(`
|
|
12
12
|
`)+`
|
|
@@ -18,18 +18,18 @@ import {f as f$1,n,g,h}from'./chunk-XGAOYG77.js';import {b as b$2}from'./chunk-P
|
|
|
18
18
|
`)+`
|
|
19
19
|
`,"utf8");}catch{}}function k(n,t){let e=Z(n);if(!f.existsSync(e))return [];try{let i=f.readFileSync(e,"utf8").trim().split(`
|
|
20
20
|
`).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null);return t?.agent&&(i=i.filter(r=>r.agent===t.agent)),t?.urgency&&(i=i.filter(r=>r.urgency===t.urgency)),t?.surfaced!==void 0&&(i=i.filter(r=>r.surfaced===t.surfaced)),t?.pending_only&&(i=i.filter(r=>!r.engaged)),t?.since&&(i=i.filter(r=>r.timestamp>=t.since)),i.sort((r,s)=>s.timestamp.localeCompare(r.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}catch{return []}}function $t(n){let t=tt(n);if(!f.existsSync(t))return [];try{return f.readFileSync(t,"utf8").trim().split(`
|
|
21
|
-
`).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return []}}function Ot(n,t,e,o){let i=Z(n);if(!f.existsSync(i))return false;try{let s=f.readFileSync(i,"utf8").trim().split(`
|
|
22
|
-
`),a=!1,c=s.map(d=>{try{let u=JSON.parse(d);return u.id===t?(u.engaged=!0,u.response=e,o&&(u.reason=o),a=!0,JSON.stringify(u)):d}catch{return d}});if(a&&(f.writeFileSync(i,c.join(`
|
|
21
|
+
`).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return []}}function Ot(n,t,e,o){let i$1=Z(n);if(!f.existsSync(i$1))return false;try{let s=f.readFileSync(i$1,"utf8").trim().split(`
|
|
22
|
+
`),a=!1,c=s.map(d=>{try{let u=JSON.parse(d);return u.id===t?(u.engaged=!0,u.response=e,o&&(u.reason=o),a=!0,JSON.stringify(u)):d}catch{return d}});if(a&&(f.writeFileSync(i$1,c.join(`
|
|
23
23
|
`)+`
|
|
24
|
-
`,"utf8"),e==="accepted"||e==="dismissed")){let d=JSON.parse(s.find(l=>{try{return JSON.parse(l).id===t}catch{return !1}}));
|
|
24
|
+
`,"utf8"),e==="accepted"||e==="dismissed")){let d=JSON.parse(s.find(l=>{try{return JSON.parse(l).id===t}catch{return !1}}));i(n).find(l=>l.id===d.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&J(n,{type:"work-completed",source:"agent-action",agent:d.agent,context:`Nomination ${t} ${e} \u2014 feedback for learning`,data:{nomination_id:t,response:e}});}return a}catch{return false}}function At(n,t,e,o){let i=tt(n);if(!f.existsSync(i))return false;try{let s=f.readFileSync(i,"utf8").trim().split(`
|
|
25
25
|
`),a=!1,c=s.map(d=>{try{let u=JSON.parse(d);if(u.id===t){u.resolution={chosen:e,reason:o,resolved_by:"human",resolved_at:new Date().toISOString()},a=!0;let l=u.nominations.filter(m=>m!==e);for(let m of l){let y=k(n).find(p=>p.id===m);y&&J(n,{type:"work-completed",source:"agent-action",agent:y.agent,context:`Debate ${t} resolved \u2014 nomination ${m} not chosen`,data:{debate_id:t,chosen:e,reason:o}});}return JSON.stringify(u)}return d}catch{return d}});return a&&f.writeFileSync(i,c.join(`
|
|
26
26
|
`)+`
|
|
27
27
|
`,"utf8"),a}catch{return false}}function Ft(n){let t=b.join(n,R,".last-processed"),e="";try{f.existsSync(t)&&(e=f.readFileSync(t,"utf8").trim());}catch{}let o=b.join(n,R,"stream.jsonl");if(!f.existsSync(o))return {processed:0,nominations:[]};let i=[];try{i=f.readFileSync(o,"utf8").trim().split(`
|
|
28
|
-
`).filter(l=>l.trim()).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(l=>l!==null);}catch{return {processed:0,nominations:[]}}let r=0;if(e){let u=i.findIndex(l=>l.id===e);u>=0&&(r=u+1);}let s=i.slice(r);if(s.length===0)return {processed:0,nominations:[]};let a=[],c=s.slice(0,50);for(let u of c){let{nominations:l}=ye(n,u);a.push(...l);}let d=c[c.length-1];try{f.mkdirSync(b.join(n,R),{recursive:!0}),f.writeFileSync(t,d.id,"utf8");}catch{}return {processed:c.length,nominations:a}}function Ct(n,t){let e=f$1(n,t);if(!e?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let o=e.attention.threshold??.6,{nominationTtlDays:i}=U(n),r=i*24*60*60*1e3,c=k(n,{agent:t}).filter(j=>j.engaged||Date.now()-new Date(j.timestamp).getTime()<r).filter(j=>j.engaged);if(c.length<5)return {adjusted:false,oldThreshold:o,newThreshold:o,reason:`Insufficient data (${c.length}/5 engaged nominations)`};let d=c.filter(j=>j.response==="accepted").length,u=c.filter(j=>j.response==="dismissed").length,l=d/c.length,m=u/c.length,y=o,p="No adjustment needed";if(m>.6?(y=Math.min(.95,o+.05),p=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):l>.8&&(y=Math.max(.2,o-.05),p=`High accept rate (${(l*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),y===o)return {adjusted:false,oldThreshold:o,newThreshold:y,reason:p};e.attention.threshold=y;let g=b.join(n,".paradigm/agents",`${t}.agent`),D=f.existsSync(g)?"project":"global";return
|
|
28
|
+
`).filter(l=>l.trim()).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(l=>l!==null);}catch{return {processed:0,nominations:[]}}let r=0;if(e){let u=i.findIndex(l=>l.id===e);u>=0&&(r=u+1);}let s=i.slice(r);if(s.length===0)return {processed:0,nominations:[]};let a=[],c=s.slice(0,50);for(let u of c){let{nominations:l}=ye(n,u);a.push(...l);}let d=c[c.length-1];try{f.mkdirSync(b.join(n,R),{recursive:!0}),f.writeFileSync(t,d.id,"utf8");}catch{}return {processed:c.length,nominations:a}}function Ct(n,t){let e=f$1(n,t);if(!e?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let o=e.attention.threshold??.6,{nominationTtlDays:i}=U(n),r=i*24*60*60*1e3,c=k(n,{agent:t}).filter(j=>j.engaged||Date.now()-new Date(j.timestamp).getTime()<r).filter(j=>j.engaged);if(c.length<5)return {adjusted:false,oldThreshold:o,newThreshold:o,reason:`Insufficient data (${c.length}/5 engaged nominations)`};let d=c.filter(j=>j.response==="accepted").length,u=c.filter(j=>j.response==="dismissed").length,l=d/c.length,m=u/c.length,y=o,p="No adjustment needed";if(m>.6?(y=Math.min(.95,o+.05),p=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):l>.8&&(y=Math.max(.2,o-.05),p=`High accept rate (${(l*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),y===o)return {adjusted:false,oldThreshold:o,newThreshold:y,reason:p};e.attention.threshold=y;let g=b.join(n,".paradigm/agents",`${t}.agent`),D=f.existsSync(g)?"project":"global";return j(t,e,D,n),J(n,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${o.toFixed(2)} \u2192 ${y.toFixed(2)} (${p})`,data:{old_threshold:o,new_threshold:y,accept_rate:l,dismiss_rate:m}}),{adjusted:true,oldThreshold:o,newThreshold:y,reason:p}}function et(n,t){let{nominationTtlDays:e}=U(n),o=e*24*60*60*1e3,r=k(n,{agent:t}).filter(l=>l.engaged||Date.now()-new Date(l.timestamp).getTime()<o),s=r.filter(l=>l.response==="accepted").length,a=r.filter(l=>l.response==="dismissed").length,c=r.filter(l=>l.response==="deferred").length,d=r.filter(l=>!l.engaged).length,u=s+a+c;return {total:r.length,accepted:s,dismissed:a,deferred:c,pending:d,acceptRate:u>0?s/u:0}}function It(n){let e=i(n).filter(l=>!l.benched).map(l=>{let m=et(n,l.id),y=0;try{let p=b.join(Q.homedir(),".paradigm","notebooks",l.id);f.existsSync(p)&&(y=f.readdirSync(p).filter(g=>g.endsWith(".yaml")).length);}catch{}return {id:l.id,acceptRate:m.acceptRate,threshold:l.attention?.threshold??.5,expertiseCount:(l.expertise||[]).length,notebookCount:y,transferableCount:(l.transferable||[]).length,totalNominations:m.total}}),o=e.length||1,i$1=e.reduce((l,m)=>l+m.acceptRate,0)/o,r=e.reduce((l,m)=>l+m.threshold,0)/o,s=e.reduce((l,m)=>l+m.expertiseCount,0),a=e.reduce((l,m)=>l+m.notebookCount,0),c=e.reduce((l,m)=>l+m.transferableCount,0),d=e.reduce((l,m)=>l+m.totalNominations,0),u;return d<10?u="cold-start":i$1<.5?u="accumulating":i$1<.7?u="calibrating":u="mature",{agents:e,aggregate:{avgAcceptRate:i$1,avgThreshold:r,totalExpertise:s,totalNotebooks:a,totalTransferable:c},healthStatus:u}}function nt(n,t){let e,o;try{let c=(K(),d(vt)),d$1=(Rt(),d(Dt));e=c.loadJournalEntries,o=d$1.addNotebookEntry;}catch{return {promoted:0,entries:[]}}let i=e(t,{trigger:"pattern_discovered",limit:100}),r=e(t,{trigger:"human_feedback",limit:100}),s=[...i,...r],a=[];for(let c of s)if(!c.promoted_to_notebook&&!((c.confidence_after??0)<.8))try{let{entry:d}=o(t,{context:c.pattern?.applies_when||c.insight.slice(0,80),snippet:c.pattern?.correct_approach||c.insight,concepts:c.tags||[c.pattern?.id||"learned-pattern"],provenance:{source:"journal-auto-promote",sourceId:c.id,createdBy:t}},"global",n);a.push({journalId:c.id,notebookId:d.id});try{let u=b.join(Q.homedir(),".paradigm","agents",t,"journal");if(f.existsSync(u)){let l=f.readdirSync(u).filter(m=>m.endsWith(".yaml"));for(let m of l){let y=b.join(u,m),p=f.readFileSync(y,"utf8");if(p.includes(c.id)){let g=p.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${d.id}"`);if(g===p){let D=p.trimEnd().split(`
|
|
29
29
|
`);D.push(`promoted_to_notebook: "${d.id}"`),f.writeFileSync(y,D.join(`
|
|
30
30
|
`)+`
|
|
31
|
-
`,"utf8");}else f.writeFileSync(y,g,"utf8");break}}}}catch{}}catch{}return {promoted:a.length,entries:a}}var ve=".paradigm/surfacing.yaml";function Jt(n){let t=b.join(n,ve),e={default_min_urgency:"low",enable_debates:true};if(!f.existsSync(t))return e;try{let o=a("js-yaml"),i=f.readFileSync(t,"utf8"),r=o.load(i);return {...e,...r}}catch{return e}}function Mt(n,t){let e={critical:0,high:1,medium:2,low:3},o=e[t.default_min_urgency||"low"]??3;return n.filter(i=>{let r=e[i.urgency]??3;if(t.preferences){let s=t.preferences.find(a=>a.agent===i.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(c=>i.urgency===c||i.type===c))return false;if(s.min_urgency){let a=e[s.min_urgency]??3;return r<=a}}}return r<=o})}var je=".paradigm/decisions";function Lt(n,t){let e=b.join(n,je);if(!f.existsSync(e))return [];let o=[],i=f.readdirSync(e).filter(s=>s.endsWith(".yaml"));for(let s of i)try{let a=f.readFileSync(b.join(e,s),"utf8"),c=P.load(a);c&&c.id&&o.push(c);}catch{}let r=o;return (r=r.filter(s=>s.status===t.status)),t?.participant&&(r=r.filter(s=>s.participants.some(a=>a.id===t.participant))),t?.symbol&&(r=r.filter(s=>s.symbols_affected?.includes(t.symbol))),t?.tag&&(r=r.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(r=r.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(r=r.filter(s=>s.timestamp<=t.dateTo)),r.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(r=r.slice(0,t.limit)),r}K();function Ge(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_neverland",description:"Neverland Validation \u2014 aggregate learning metrics across all agents. Shows acceptance rates, threshold drift, expertise growth, notebook counts, cross-project transfer, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature). ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function ke(n){let t=Date.now(),e=n.match(/^(\d+)(m|h|d)$/);if(e){let o=parseInt(e[1],10),i=e[2],r=i==="m"?o*6e4:i==="h"?o*36e5:o*864e5;return new Date(t-r).toISOString()}return n}async function ze(n
|
|
31
|
+
`,"utf8");}else f.writeFileSync(y,g,"utf8");break}}}}catch{}}catch{}return {promoted:a.length,entries:a}}var ve=".paradigm/surfacing.yaml";function Jt(n){let t=b.join(n,ve),e={default_min_urgency:"low",enable_debates:true};if(!f.existsSync(t))return e;try{let o=a("js-yaml"),i=f.readFileSync(t,"utf8"),r=o.load(i);return {...e,...r}}catch{return e}}function Mt(n,t){let e={critical:0,high:1,medium:2,low:3},o=e[t.default_min_urgency||"low"]??3;return n.filter(i=>{let r=e[i.urgency]??3;if(t.preferences){let s=t.preferences.find(a=>a.agent===i.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(c=>i.urgency===c||i.type===c))return false;if(s.min_urgency){let a=e[s.min_urgency]??3;return r<=a}}}return r<=o})}var je=".paradigm/decisions";function Lt(n,t){let e=b.join(n,je);if(!f.existsSync(e))return [];let o=[],i=f.readdirSync(e).filter(s=>s.endsWith(".yaml"));for(let s of i)try{let a=f.readFileSync(b.join(e,s),"utf8"),c=P.load(a);c&&c.id&&o.push(c);}catch{}let r=o;return (r=r.filter(s=>s.status===t.status)),t?.participant&&(r=r.filter(s=>s.participants.some(a=>a.id===t.participant))),t?.symbol&&(r=r.filter(s=>s.symbols_affected?.includes(t.symbol))),t?.tag&&(r=r.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(r=r.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(r=r.filter(s=>s.timestamp<=t.dateTo)),r.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(r=r.slice(0,t.limit)),r}K();function Ge(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_neverland",description:"Neverland Validation \u2014 aggregate learning metrics across all agents. Shows acceptance rates, threshold drift, expertise growth, notebook counts, cross-project transfer, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature). ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function ke(n){let t=Date.now(),e=n.match(/^(\d+)(m|h|d)$/);if(e){let o=parseInt(e[1],10),i=e[2],r=i==="m"?o*6e4:i==="h"?o*36e5:o*864e5;return new Date(t-r).toISOString()}return n}async function ze(n,t,e){let o=i=>JSON.stringify(i,null,2);switch(n){case "paradigm_ambient_nominations":{Ft(e.rootDir);let r=t.pending_only!==false,s=t.limit||20,a=k(e.rootDir,{agent:t.agent,urgency:t.urgency,pending_only:r,limit:s+20}),c=Jt(e.rootDir);a=Mt(a,c).slice(0,s);let d=b.join(e.rootDir,".paradigm/events/nominations.jsonl");if(f.existsSync(d))try{let l=f.readFileSync(d,"utf8"),m=new Set(a.map(p=>p.id)),y=l.trim().split(`
|
|
32
32
|
`).map(p=>{try{let g=JSON.parse(p);return m.has(g.id)?(g.surfaced=!0,JSON.stringify(g)):p}catch{return p}});f.writeFileSync(d,y.join(`
|
|
33
33
|
`)+`
|
|
34
|
-
`,"utf8");}catch{}let u={count:a.length,nominations:a.map(l=>({id:l.id,agent:l.agent,urgency:l.urgency,type:l.type,brief:l.brief,relevance:l.relevance,timestamp:l.timestamp,engaged:l.engaged,response:l.response}))};if(t.include_debates){let m=$t(e.rootDir).filter(y=>!y.resolution);u.debates=m.map(y=>({id:y.id,topic:y.topic,type:y.type,nominations:y.nominations})),u.debate_count=m.length;}return {text:o(u),handled:true}}case "paradigm_ambient_events":{let i=t.since?ke(t.since):void 0,r=t.limit||50,s=yt(e.rootDir,{type:t.type,source:t.source,symbol:t.symbol,agent:t.agent,since:i,limit:r});return {text:o({count:s.length,events:s.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i=t.nomination_id,r=t.response,s=t.reason,a=Ot(e.rootDir,i,r,s);if(a)try{let{appendSessionWorkEntry:d}=await import('./session-work-log-
|
|
35
|
-
`),sections_included:{profile:true,decisions:a,journal:c,nominations:s}}),handled:true}}case "paradigm_ambient_promote":{let i=t.agent,r=nt(e.rootDir,i);return {text:o({agent:i,promoted:r.promoted,entries:r.entries}),handled:true}}case "paradigm_ambient_learn":{let i=t.agent,r=t.dry_run===true,s=et(e.rootDir,i);if(r)return {text:o({agent:i,dry_run:true,stats:s,note:s.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(s.acceptRate*100).toFixed(0)}% \u2014 ${s.acceptRate>.8?"would lower threshold":s.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=Ct(e.rootDir,i);return {text:o({agent:i,...a,stats:s}),handled:true}}case "paradigm_ambient_neverland":{let i=It(e.rootDir);return {text:o(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:o(await De(e.rootDir,t)),handled:true};default:return {text:`Unknown ambient tool: ${n
|
|
34
|
+
`,"utf8");}catch{}let u={count:a.length,nominations:a.map(l=>({id:l.id,agent:l.agent,urgency:l.urgency,type:l.type,brief:l.brief,relevance:l.relevance,timestamp:l.timestamp,engaged:l.engaged,response:l.response}))};if(t.include_debates){let m=$t(e.rootDir).filter(y=>!y.resolution);u.debates=m.map(y=>({id:y.id,topic:y.topic,type:y.type,nominations:y.nominations})),u.debate_count=m.length;}return {text:o(u),handled:true}}case "paradigm_ambient_events":{let i=t.since?ke(t.since):void 0,r=t.limit||50,s=yt(e.rootDir,{type:t.type,source:t.source,symbol:t.symbol,agent:t.agent,since:i,limit:r});return {text:o({count:s.length,events:s.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i=t.nomination_id,r=t.response,s=t.reason,a=Ot(e.rootDir,i,r,s);if(a)try{let{appendSessionWorkEntry:d}=await import('./session-work-log-LWEGZ5CN.js'),l=k(e.rootDir,{limit:500}).find(m=>m.id===i);d(e.rootDir,{timestamp:new Date().toISOString(),type:"user-verdict",agent:l?.agent,nominationId:i,verdict:r,reason:s});}catch{}let c=false;return t.resolve_debate&&a&&(c=At(e.rootDir,t.resolve_debate,i,t.reason)),{text:o({engaged:a,nomination_id:i,response:r,debate_resolved:c||void 0}),handled:true}}case "paradigm_context_compose":{let i=t.agent,r=t.symbols||[],s=t.include_nominations!==false,a=t.include_decisions!==false,c=t.include_journal!==false,d=t.max_decisions||5,u=t.max_journal||5,l=f$1(e.rootDir,i);if(!l)return {text:o({error:`Agent profile not found: ${i}`}),handled:true};let m=[],y=p(l,r);if(y.trim()&&m.push(y),a){let p=Lt(e.rootDir,{status:"active",limit:d});if(p.length>0){m.push("## Recent Team Decisions");for(let g of p)m.push(`- **${g.title}**: ${g.decision.slice(0,150)}${g.decision.length>150?"...":""}`);m.push("");}}if(c){let p=O(i,{transferable:true,limit:u});if(p.length>0){m.push("## Transferable Insights");for(let g of p)m.push(`- [${g.trigger}] ${g.insight.slice(0,150)}${g.insight.length>150?"...":""}`);m.push("");}}if(s){let p=k(e.rootDir,{pending_only:true,limit:10});if(p.length>0){m.push("## Pending Nominations");for(let g of p)m.push(`- [${g.urgency}] ${g.brief}`);m.push("");}}return {text:o({agent:i,context:m.join(`
|
|
35
|
+
`),sections_included:{profile:true,decisions:a,journal:c,nominations:s}}),handled:true}}case "paradigm_ambient_promote":{let i=t.agent,r=nt(e.rootDir,i);return {text:o({agent:i,promoted:r.promoted,entries:r.entries}),handled:true}}case "paradigm_ambient_learn":{let i=t.agent,r=t.dry_run===true,s=et(e.rootDir,i);if(r)return {text:o({agent:i,dry_run:true,stats:s,note:s.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(s.acceptRate*100).toFixed(0)}% \u2014 ${s.acceptRate>.8?"would lower threshold":s.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=Ct(e.rootDir,i);return {text:o({agent:i,...a,stats:s}),handled:true}}case "paradigm_ambient_neverland":{let i=It(e.rootDir);return {text:o(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:o(await De(e.rootDir,t)),handled:true};default:return {text:`Unknown ambient tool: ${n}`,handled:false}}}var Ee={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function xe(n){try{let t=b.join(n,".paradigm","config.yaml");if(f.existsSync(t)){let o=f.readFileSync(t,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(o)return o[1].trim()}}catch{}return b.basename(n)}async function De(n,t={}){let e=t.dry_run===true,o=xe(n),i=b$2(n),r=i.filter(p=>p.type==="user-verdict"&&p.verdict&&p.agent);if(r.length===0)return {sessionEntries:i.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:e,details:[]};let s=new Map;for(let p of r){let g=p.agent;s.has(g)||s.set(g,[]),s.get(g).push(p);}let a=i.filter(p=>p.type==="agent-contribution"),c=new Map;for(let p of a)p.agent&&(c.has(p.agent)||c.set(p.agent,[]),c.get(p.agent).push(p));let d=[],u={},l=0;for(let[p,g]of s){u[p]=0;let D=g.filter(h=>h.verdict==="accepted").length;g.filter(h=>h.verdict==="dismissed").length;g.filter(h=>h.verdict==="revised").length;let B=g.length,Bt=B>0?D/B:0;for(let h of g){let H=Ee[h.verdict];if(!H)continue;let Ht=c.get(p)?.shift(),it=Re(h,Ht,{acceptRate:Bt,total:B,accepted:D}),Wt=h.verdict==="accepted"?.85:h.verdict==="revised"?.6:.4,qt={agent:p,verdict:h.verdict,trigger:H,insight:it,symbols:h.symbols};if(d.push(qt),e)u[p]++,l++;else try{z(p,{trigger:H,insight:it,confidence_before:h.verdict==="accepted"?.7:.8,confidence_after:Wt,project:o,transferable:h.verdict==="dismissed",tags:["postflight",`verdict:${h.verdict}`,...(h.symbols||[]).map(Gt=>`symbol:${Gt}`)]}),u[p]++,l++;}catch{}}}let m={},y=0;if(!e)for(let p of s.keys())try{let g=nt(n,p);g.promoted>0&&(m[p]=g.promoted,y+=g.promoted);}catch{}return {sessionEntries:i.length,agentsProcessed:Array.from(s.keys()),journalsWritten:l,journalsByAgent:u,promoted:y,promotedByAgent:m,dryRun:e,details:d}}function Re(n,t,e){let o=n.symbols?.length?` (symbols: ${n.symbols.join(", ")})`:"",i=n.reason?` Reason: ${n.reason}.`:"";switch(n.verdict){case "accepted":return `Contribution accepted by user${o}.${i}`+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;case "dismissed":return `Contribution dismissed by user${o}.${i}`+(t?.contribution?` Rejected contribution: "${t.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;case "revised":return `Contribution revised by user${o}.${i}`+(n.revisionDelta?` Delta: "${n.revisionDelta.slice(0,120)}".`:"")+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;default:return `Unknown verdict "${n.verdict}"${o}.${i}`}}export{Ge as getAmbientToolsList,ze as handleAmbientTool,De as runPostflightLearning};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import {v,i,f,j as j$1}from'./chunk-QWL3LERH.js';import {g as g$1,f as f$1}from'./chunk-QGZRM6ZB.js';import {g as g$2,f as f$2}from'./chunk-VG7FN2TU.js';import {b,a,d}from'./chunk-5TAVYPOV.js';import*as u from'fs';import*as g from'path';import*as W from'js-yaml';import*as R from'os';function G(e){return g.join(e,q,st)}function at(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${e}-${t}`}function k(e,t){let n={id:at(),timestamp:new Date().toISOString(),...t};w.push(n),w.length>N&&(w=w.slice(-N));try{let r=g.join(e,q);u.mkdirSync(r,{recursive:!0});let o=G(e);u.appendFileSync(o,JSON.stringify(n)+`
|
|
3
3
|
`,"utf8"),ct(o);}catch{}return n}function ct(e){try{if(u.statSync(e).size>512*1024){let r=u.readFileSync(e,"utf8").trim().split(`
|
|
4
4
|
`);if(r.length>N){let o=r.slice(-N);u.writeFileSync(e,o.join(`
|
|
5
5
|
`)+`
|
|
6
6
|
`,"utf8");}}}catch{}}function Dt(e,t){let n=lt(e);return t?.type&&(n=n.filter(r=>r.type===t.type)),t?.source&&(n=n.filter(r=>r.source===t.source)),t?.symbol&&(n=n.filter(r=>r.symbols?.includes(t.symbol))),t?.agent&&(n=n.filter(r=>r.agent===t.agent)),t?.since&&(n=n.filter(r=>r.timestamp>=t.since)),n.sort((r,o)=>o.timestamp.localeCompare(r.timestamp)),t?.limit&&(n=n.slice(0,t.limit)),n}function lt(e){let t=G(e);if(!u.existsSync(t))return [...w];try{return u.readFileSync(t,"utf8").trim().split(`
|
|
7
|
-
`).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return [...w]}}function Y(e,t,n){let r=0,o=0,i=0,a=0;if(n.symbols?.length&&e.symbols?.length)for(let l of n.symbols)for(let s of e.symbols)B(l,s)&&(r=Math.max(r,1));if(n.paths?.length&&e.path){for(let l of n.paths)if(B(l,e.path)){o=1;break}}if(n.concepts?.length){let l=[e.context||"",...e.keywords||[],e.type].join(" ").toLowerCase(),s=0;for(let m of n.concepts)l.includes(m.toLowerCase())&&s++;n.concepts.length>0&&(i=s/n.concepts.length);}if(n.signals?.length){for(let l of n.signals)if(l.type===e.type){a=1;break}}let f=[r,o,i,a].sort((l,s)=>s-l),c=f[0]*.5+f[1]*.2+f[2]*.15+f[3]*.15,d=n.threshold??.6;return {agentId:t,score:c,breakdown:{symbolMatch:r,pathMatch:o,conceptMatch:i,signalMatch:a},shouldNominate:c>=d,quietReason:c<d?"below-threshold":void 0}}function B(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var q,st,N,w,z=b(()=>{q=".paradigm/events",st="stream.jsonl",N=1e3,w=[];});var j,H=b(()=>{j={version:"1.0",default_ring:"project-locked",observation:{allow:["src/**",".paradigm/**","portal.yaml"],deny:[".env*","**/*.key","**/*.pem","**/secrets/**"]},streams:{work_log:{ring:"project-locked",allow_content:["file_paths","symbol_names","outcome"],deny_content:["code_snippets","file_contents","diff_content"]},learning_journal:{ring:"user-scoped",allow_content:["pattern_descriptions","confidence_adjustments","approach_descriptions"],deny_content:["code_snippets","file_contents","symbol_names_with_context"],redaction:[{pattern:"\\b[A-Z_]{2,}_KEY\\b"},{pattern:"password|secret|token"}]},team_decisions:{ring:"project-locked",allow_content:["rationale","alternatives","symbol_references"],deny_content:["implementation_details"]}},upstream:{ring:"creator-upstream",allowed:["task_type","outcome","helpfulness","duration_bucket","error_category"],denied:["code_of_any_kind","file_paths","symbol_names","conversation_content","user_identity"]},network:{ring:"network-public",opt_in:false,if_opted_in:["aggregated_task_success_rates","anonymized_pattern_frequency"]}};});function C(e){let t=g.join(e,dt);if(!u.existsSync(t))return {...j};try{let n=u.readFileSync(t,"utf8"),r=W.load(n);return ut(j,r)}catch{return {...j}}}function ut(e,t){let n={...e};if(t.version&&(n.version=t.version),t.default_ring&&(n.default_ring=t.default_ring),t.observation&&(n.observation={allow:t.observation.allow||e.observation?.allow,deny:[...e.observation?.deny||[],...t.observation.deny||[]].filter((r,o,i)=>i.indexOf(r)===o)}),t.streams){n.streams={...e.streams};for(let r of ["work_log","learning_journal","team_decisions"])t.streams[r]&&(n.streams[r]={...e.streams?.[r],...t.streams[r],deny_content:[...e.streams?.[r]?.deny_content||[],...t.streams[r]?.deny_content||[]].filter((o,i,a)=>a.indexOf(o)===i)});}return t.upstream&&(n.upstream={...e.upstream,...t.upstream}),t.network&&(n.network={...e.network,...t.network}),t.agent_overrides&&(n.agent_overrides={...e.agent_overrides,...t.agent_overrides}),t.deployment&&(n.deployment={...e.deployment,...t.deployment}),n}function $(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(o=>F(o,t))||e.observation?.deny?.some(r=>F(r,t))?false:e.observation?.allow?.length?e.observation.allow.some(r=>F(r,t)):true}function Ot(e,t,n){let r=t.streams?.[n];if(!r)return {filtered:e,redacted:[]};let o=[],i=e;if(r.redaction)for(let a of r.redaction)try{let f=new RegExp(a.pattern,"gi"),c=i.match(f);c&&(o.push(...c),i=i.replace(f,a.replacement||"[REDACTED]"));}catch{}return {filtered:i,redacted:o}}function F(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var dt,X=b(()=>{H();dt=".paradigm/data-policy.yaml";});function _t(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function St(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${e}-${t}`}function Z(e,t){let n=
|
|
7
|
+
`).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return [...w]}}function Y(e,t,n){let r=0,o=0,i=0,a=0;if(n.symbols?.length&&e.symbols?.length)for(let l of n.symbols)for(let s of e.symbols)B(l,s)&&(r=Math.max(r,1));if(n.paths?.length&&e.path){for(let l of n.paths)if(B(l,e.path)){o=1;break}}if(n.concepts?.length){let l=[e.context||"",...e.keywords||[],e.type].join(" ").toLowerCase(),s=0;for(let m of n.concepts)l.includes(m.toLowerCase())&&s++;n.concepts.length>0&&(i=s/n.concepts.length);}if(n.signals?.length){for(let l of n.signals)if(l.type===e.type){a=1;break}}let f=[r,o,i,a].sort((l,s)=>s-l),c=f[0]*.5+f[1]*.2+f[2]*.15+f[3]*.15,d=n.threshold??.6;return {agentId:t,score:c,breakdown:{symbolMatch:r,pathMatch:o,conceptMatch:i,signalMatch:a},shouldNominate:c>=d,quietReason:c<d?"below-threshold":void 0}}function B(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var q,st,N,w,z=b(()=>{q=".paradigm/events",st="stream.jsonl",N=1e3,w=[];});var j,H=b(()=>{j={version:"1.0",default_ring:"project-locked",observation:{allow:["src/**",".paradigm/**","portal.yaml"],deny:[".env*","**/*.key","**/*.pem","**/secrets/**"]},streams:{work_log:{ring:"project-locked",allow_content:["file_paths","symbol_names","outcome"],deny_content:["code_snippets","file_contents","diff_content"]},learning_journal:{ring:"user-scoped",allow_content:["pattern_descriptions","confidence_adjustments","approach_descriptions"],deny_content:["code_snippets","file_contents","symbol_names_with_context"],redaction:[{pattern:"\\b[A-Z_]{2,}_KEY\\b"},{pattern:"password|secret|token"}]},team_decisions:{ring:"project-locked",allow_content:["rationale","alternatives","symbol_references"],deny_content:["implementation_details"]}},upstream:{ring:"creator-upstream",allowed:["task_type","outcome","helpfulness","duration_bucket","error_category"],denied:["code_of_any_kind","file_paths","symbol_names","conversation_content","user_identity"]},network:{ring:"network-public",opt_in:false,if_opted_in:["aggregated_task_success_rates","anonymized_pattern_frequency"]}};});function C(e){let t=g.join(e,dt);if(!u.existsSync(t))return {...j};try{let n=u.readFileSync(t,"utf8"),r=W.load(n);return ut(j,r)}catch{return {...j}}}function ut(e,t){let n={...e};if(t.version&&(n.version=t.version),t.default_ring&&(n.default_ring=t.default_ring),t.observation&&(n.observation={allow:t.observation.allow||e.observation?.allow,deny:[...e.observation?.deny||[],...t.observation.deny||[]].filter((r,o,i)=>i.indexOf(r)===o)}),t.streams){n.streams={...e.streams};for(let r of ["work_log","learning_journal","team_decisions"])t.streams[r]&&(n.streams[r]={...e.streams?.[r],...t.streams[r],deny_content:[...e.streams?.[r]?.deny_content||[],...t.streams[r]?.deny_content||[]].filter((o,i,a)=>a.indexOf(o)===i)});}return t.upstream&&(n.upstream={...e.upstream,...t.upstream}),t.network&&(n.network={...e.network,...t.network}),t.agent_overrides&&(n.agent_overrides={...e.agent_overrides,...t.agent_overrides}),t.deployment&&(n.deployment={...e.deployment,...t.deployment}),n}function $(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(o=>F(o,t))||e.observation?.deny?.some(r=>F(r,t))?false:e.observation?.allow?.length?e.observation.allow.some(r=>F(r,t)):true}function Ot(e,t,n){let r=t.streams?.[n];if(!r)return {filtered:e,redacted:[]};let o=[],i=e;if(r.redaction)for(let a of r.redaction)try{let f=new RegExp(a.pattern,"gi"),c=i.match(f);c&&(o.push(...c),i=i.replace(f,a.replacement||"[REDACTED]"));}catch{}return {filtered:i,redacted:o}}function F(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var dt,X=b(()=>{H();dt=".paradigm/data-policy.yaml";});function _t(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function St(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${e}-${t}`}function Z(e,t){let n=i(e),r=C(e),o=[];for(let d of n){if(!d.attention||d.benched||t.path&&!$(r,t.path,d.id))continue;let l=Y(t,d.id,d.attention);l.shouldNominate&&o.push({profile:d,score:l});}if(o.length===0)return {nominations:[],debates:[]};let i$1=D(e,{since:new Date(Date.now()-3e4).toISOString()}),a=o.filter(({profile:d})=>!i$1.find(s=>s.agent===d.id&&s.brief===K(d,t,{...o.find(m=>m.profile.id===d.id).score})));if(a.length===0)return {nominations:[],debates:[]};let f=a.map(({profile:d,score:l})=>{let s=wt(t,l),m=kt(d,t);return {id:_t(),agent:d.id,relevance:l.score,urgency:s,type:m,brief:K(d,t,l),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});vt(e,f);let c=xt(e,f);return c.length>0&&Et(e,c),{nominations:f,debates:c}}function wt(e,t){return e.severity==="critical"?"critical":e.severity==="error"||e.type==="compliance-violation"||e.type==="error-encountered"?"high":e.type==="gate-added"||e.type==="route-created"||t.score>=.9?"medium":"low"}function kt(e,t){let n=e.collaboration?.stance;return t.type==="compliance-violation"||t.type==="error-encountered"?"warning":t.type==="gate-added"||t.type==="route-created"?"observation":n==="advisory"||n==="lead"?"suggestion":"observation"}function K(e,t,n){let r=e.role||e.id;switch(t.type){case "gate-checked":return `${r}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${r}: ${t.path||"File"} modified \u2014 review for ${e.id==="security"?"security implications":e.id==="tester"?"test coverage":e.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${r}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${r}: New route ${t.symbols?.join(", ")||""} \u2014 ${e.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${r}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${e.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${r}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${r}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${r}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let o=n.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:n.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${r}: ${o}`}}}function xt(e,t){if(t.length<2)return [];let n=[],r=new Map;for(let o of t)for(let i of o.triggered_by){let a=r.get(i)||[];a.push(o),r.set(i,a);}for(let[o,i]of r){if(i.length<2||new Set(i.map(d=>d.agent)).size<2)continue;let f=new Set(i.map(d=>d.type)),c=f.size>1&&f.has("warning")&&f.has("suggestion");n.push({id:St(),topic:`Multiple agents responded to event ${o}`,nominations:i.map(d=>d.id),type:c?"conflicting":"complementary",overlap_events:[o]});}return n}function O(e){return g.join(e,_,ft)}function M(e){return g.join(e,_,mt)}function vt(e,t){try{let n=g.join(e,_);u.mkdirSync(n,{recursive:!0});let r=O(e),o=t.map(a=>JSON.stringify(a)).join(`
|
|
8
8
|
`)+`
|
|
9
9
|
`;u.appendFileSync(r,o,"utf8"),Q(r,gt);let{nominationTtlDays:i}=A(e);tt(r,i*24*60*60*1e3);}catch{}}function Et(e,t){try{let n=g.join(e,_);u.mkdirSync(n,{recursive:!0});let r=M(e),o=t.map(a=>JSON.stringify(a)).join(`
|
|
10
10
|
`)+`
|
|
@@ -19,11 +19,11 @@ import {t,g as g$1,f,h}from'./chunk-ZMQXXFG2.js';import {g as g$2,f as f$1}from'
|
|
|
19
19
|
`).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function Bt(e,t,n,r){let o=O(e);if(!u.existsSync(o))return false;try{let a=u.readFileSync(o,"utf8").trim().split(`
|
|
20
20
|
`),f=!1,c=a.map(d=>{try{let l=JSON.parse(d);return l.id===t?(l.engaged=!0,l.response=n,r&&(l.reason=r),f=!0,JSON.stringify(l)):d}catch{return d}});if(f&&(u.writeFileSync(o,c.join(`
|
|
21
21
|
`)+`
|
|
22
|
-
`,"utf8"),n==="accepted"||n==="dismissed")){let d=JSON.parse(a.find(s=>{try{return JSON.parse(s).id===t}catch{return !1}}));
|
|
22
|
+
`,"utf8"),n==="accepted"||n==="dismissed")){let d=JSON.parse(a.find(s=>{try{return JSON.parse(s).id===t}catch{return !1}}));i(e).find(s=>s.id===d.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&k(e,{type:"work-completed",source:"agent-action",agent:d.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return f}catch{return false}}function qt(e,t,n,r){let o=M(e);if(!u.existsSync(o))return false;try{let a=u.readFileSync(o,"utf8").trim().split(`
|
|
23
23
|
`),f=!1,c=a.map(d=>{try{let l=JSON.parse(d);if(l.id===t){l.resolution={chosen:n,reason:r,resolved_by:"human",resolved_at:new Date().toISOString()},f=!0;let s=l.nominations.filter(m=>m!==n);for(let m of s){let p=D(e).find(y=>y.id===m);p&&k(e,{type:"work-completed",source:"agent-action",agent:p.agent,context:`Debate ${t} resolved \u2014 nomination ${m} not chosen`,data:{debate_id:t,chosen:n,reason:r}});}return JSON.stringify(l)}return d}catch{return d}});return f&&u.writeFileSync(o,c.join(`
|
|
24
24
|
`)+`
|
|
25
25
|
`,"utf8"),f}catch{return false}}function Gt(e){let t=g.join(e,_,".last-processed"),n="";try{u.existsSync(t)&&(n=u.readFileSync(t,"utf8").trim());}catch{}let r=g.join(e,_,"stream.jsonl");if(!u.existsSync(r))return {processed:0,nominations:[]};let o=[];try{o=u.readFileSync(r,"utf8").trim().split(`
|
|
26
|
-
`).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(n){let l=o.findIndex(s=>s.id===n);l>=0&&(i=l+1);}let a=o.slice(i);if(a.length===0)return {processed:0,nominations:[]};let f=[],c=a.slice(0,50);for(let l of c){let{nominations:s}=Z(e,l);f.push(...s);}let d=c[c.length-1];try{u.mkdirSync(g.join(e,_),{recursive:!0}),u.writeFileSync(t,d.id,"utf8");}catch{}return {processed:c.length,nominations:f}}function Yt(e,t,n){let r=C(e);if(t.path&&!$(r,t.path))return {event:k(e,t),nominations:[],debates:[]};let o=k(e,t);if(n?.skipNominations)return {event:o,nominations:[],debates:[]};let{nominations:i,debates:a}=Z(e,o);return i.length>0&&jt(e,i),{event:o,nominations:i,debates:a}}function zt(e,t){let n=f(e,t);if(!n?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let r=n.attention.threshold??.6,{nominationTtlDays:o}=A(e),i=o*24*60*60*1e3,c=D(e,{agent:t}).filter(b=>b.engaged||Date.now()-new Date(b.timestamp).getTime()<i).filter(b=>b.engaged);if(c.length<5)return {adjusted:false,oldThreshold:r,newThreshold:r,reason:`Insufficient data (${c.length}/5 engaged nominations)`};let d=c.filter(b=>b.response==="accepted").length,l=c.filter(b=>b.response==="dismissed").length,s=d/c.length,m=l/c.length,p=r,y="No adjustment needed";if(m>.6?(p=Math.min(.95,r+.05),y=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):s>.8&&(p=Math.max(.2,r-.05),y=`High accept rate (${(s*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),p===r)return {adjusted:false,oldThreshold:r,newThreshold:p,reason:y};n.attention.threshold=p;let S=g.join(e,".paradigm/agents",`${t}.agent`),x=u.existsSync(S)?"project":"global";return
|
|
26
|
+
`).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(n){let l=o.findIndex(s=>s.id===n);l>=0&&(i=l+1);}let a=o.slice(i);if(a.length===0)return {processed:0,nominations:[]};let f=[],c=a.slice(0,50);for(let l of c){let{nominations:s}=Z(e,l);f.push(...s);}let d=c[c.length-1];try{u.mkdirSync(g.join(e,_),{recursive:!0}),u.writeFileSync(t,d.id,"utf8");}catch{}return {processed:c.length,nominations:f}}function Yt(e,t,n){let r=C(e);if(t.path&&!$(r,t.path))return {event:k(e,t),nominations:[],debates:[]};let o=k(e,t);if(n?.skipNominations)return {event:o,nominations:[],debates:[]};let{nominations:i,debates:a}=Z(e,o);return i.length>0&&jt(e,i),{event:o,nominations:i,debates:a}}function zt(e,t){let n=f(e,t);if(!n?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let r=n.attention.threshold??.6,{nominationTtlDays:o}=A(e),i=o*24*60*60*1e3,c=D(e,{agent:t}).filter(b=>b.engaged||Date.now()-new Date(b.timestamp).getTime()<i).filter(b=>b.engaged);if(c.length<5)return {adjusted:false,oldThreshold:r,newThreshold:r,reason:`Insufficient data (${c.length}/5 engaged nominations)`};let d=c.filter(b=>b.response==="accepted").length,l=c.filter(b=>b.response==="dismissed").length,s=d/c.length,m=l/c.length,p=r,y="No adjustment needed";if(m>.6?(p=Math.min(.95,r+.05),y=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):s>.8&&(p=Math.max(.2,r-.05),y=`High accept rate (${(s*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),p===r)return {adjusted:false,oldThreshold:r,newThreshold:p,reason:y};n.attention.threshold=p;let S=g.join(e,".paradigm/agents",`${t}.agent`),x=u.existsSync(S)?"project":"global";return j$1(t,n,x,e),k(e,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${r.toFixed(2)} \u2192 ${p.toFixed(2)} (${y})`,data:{old_threshold:r,new_threshold:p,accept_rate:s,dismiss_rate:m}}),{adjusted:true,oldThreshold:r,newThreshold:p,reason:y}}function Nt(e,t){let{nominationTtlDays:n}=A(e),r=n*24*60*60*1e3,i=D(e,{agent:t}).filter(s=>s.engaged||Date.now()-new Date(s.timestamp).getTime()<r),a=i.filter(s=>s.response==="accepted").length,f=i.filter(s=>s.response==="dismissed").length,c=i.filter(s=>s.response==="deferred").length,d=i.filter(s=>!s.engaged).length,l=a+f+c;return {total:i.length,accepted:a,dismissed:f,deferred:c,pending:d,acceptRate:l>0?a/l:0}}function Ht(e){let n=i(e).filter(s=>!s.benched).map(s=>{let m=Nt(e,s.id),p=0;try{let y=g.join(R.homedir(),".paradigm","notebooks",s.id);u.existsSync(y)&&(p=u.readdirSync(y).filter(S=>S.endsWith(".yaml")).length);}catch{}return {id:s.id,acceptRate:m.acceptRate,threshold:s.attention?.threshold??.5,expertiseCount:(s.expertise||[]).length,notebookCount:p,transferableCount:(s.transferable||[]).length,totalNominations:m.total}}),r=n.length||1,o=n.reduce((s,m)=>s+m.acceptRate,0)/r,i$1=n.reduce((s,m)=>s+m.threshold,0)/r,a=n.reduce((s,m)=>s+m.expertiseCount,0),f=n.reduce((s,m)=>s+m.notebookCount,0),c=n.reduce((s,m)=>s+m.transferableCount,0),d=n.reduce((s,m)=>s+m.totalNominations,0),l;return d<10?l="cold-start":o<.5?l="accumulating":o<.7?l="calibrating":l="mature",{agents:n,aggregate:{avgAcceptRate:o,avgThreshold:i$1,totalExpertise:a,totalNotebooks:f,totalTransferable:c},healthStatus:l}}function jt(e,t){if(t.length===0)return;let n=g.join(R.homedir(),".paradigm","score","outbox");if(u.existsSync(n))try{let r=g.join(n,`nom-${Date.now()}.json`),o={type:"nomination_forward",nominations:t.map(i=>({...i})),origin:Tt(e),timestamp:new Date().toISOString()};u.writeFileSync(r,JSON.stringify(o),"utf8");}catch{}}function Tt(e){try{let t=g.join(e,".paradigm","config.yaml");if(u.existsSync(t)){let r=u.readFileSync(t,"utf8").match(/project:\s*(.+)/);if(r)return r[1].trim()}}catch{}return g.basename(e)}function Vt(e,t){let n,r;try{let c=(g$1(),d(f$1)),d$1=(g$2(),d(f$2));n=c.loadJournalEntries,r=d$1.addNotebookEntry;}catch{return {promoted:0,entries:[]}}let o=n(t,{trigger:"pattern_discovered",limit:100}),i=n(t,{trigger:"human_feedback",limit:100}),a=[...o,...i],f=[];for(let c of a)if(!c.promoted_to_notebook&&!((c.confidence_after??0)<.8))try{let{entry:d}=r(t,{context:c.pattern?.applies_when||c.insight.slice(0,80),snippet:c.pattern?.correct_approach||c.insight,concepts:c.tags||[c.pattern?.id||"learned-pattern"],provenance:{source:"journal-auto-promote",sourceId:c.id,createdBy:t}},"global",e);f.push({journalId:c.id,notebookId:d.id});try{let l=g.join(R.homedir(),".paradigm","agents",t,"journal");if(u.existsSync(l)){let s=u.readdirSync(l).filter(m=>m.endsWith(".yaml"));for(let m of s){let p=g.join(l,m),y=u.readFileSync(p,"utf8");if(y.includes(c.id)){let S=y.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${d.id}"`);if(S===y){let x=y.trimEnd().split(`
|
|
27
27
|
`);x.push(`promoted_to_notebook: "${d.id}"`),u.writeFileSync(p,x.join(`
|
|
28
28
|
`)+`
|
|
29
|
-
`,"utf8");}else u.writeFileSync(p,S,"utf8");break}}}}catch{}}catch{}return {promoted:f.length,entries:f}}function Wt(e){let t=g.join(e,Rt),n={default_min_urgency:"low",enable_debates:true};if(!u.existsSync(t))return n;try{let r=a("js-yaml"),o=u.readFileSync(t,"utf8"),i=r.load(o);return {...n,...i}}catch{return n}}function Xt(e,t){let n={critical:0,high:1,medium:2,low:3},r=n[t.default_min_urgency||"low"]??3;return e.filter(o=>{let i=n[o.urgency]??3;if(t.preferences){let a=t.preferences.find(f=>f.agent===o.agent);if(a){if(a.always_show)return true;if(a.mute_unless?.length&&!a.mute_unless.some(c=>o.urgency===c||o.type===c))return false;if(a.min_urgency){let f=n[a.min_urgency]??3;return i<=f}}}return i<=r})}var _,ft,mt,gt,pt,yt,ht,bt,Rt,At=b(()=>{z();X();
|
|
29
|
+
`,"utf8");}else u.writeFileSync(p,S,"utf8");break}}}}catch{}}catch{}return {promoted:f.length,entries:f}}function Wt(e){let t=g.join(e,Rt),n={default_min_urgency:"low",enable_debates:true};if(!u.existsSync(t))return n;try{let r=a("js-yaml"),o=u.readFileSync(t,"utf8"),i=r.load(o);return {...n,...i}}catch{return n}}function Xt(e,t){let n={critical:0,high:1,medium:2,low:3},r=n[t.default_min_urgency||"low"]??3;return e.filter(o=>{let i=n[o.urgency]??3;if(t.preferences){let a=t.preferences.find(f=>f.agent===o.agent);if(a){if(a.always_show)return true;if(a.mute_unless?.length&&!a.mute_unless.some(c=>o.urgency===c||o.type===c))return false;if(a.min_urgency){let f=n[a.min_urgency]??3;return i<=f}}}return i<=r})}var _,ft,mt,gt,pt,yt,ht,bt,Rt,At=b(()=>{z();X();v();_=".paradigm/events",ft="nominations.jsonl",mt="debates.jsonl",gt=500,pt=200,yt=7,ht=14,bt=100;Rt=".paradigm/surfacing.yaml";});export{Dt as a,z as b,C as c,Ot as d,X as e,Z as f,xt as g,vt as h,D as i,Jt as j,Bt as k,qt as l,Gt as m,Yt as n,zt as o,Nt as p,Ht as q,jt as r,Vt as s,Wt as t,Xt as u,At as v};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {h,g as g$1}from'./chunk-UELDOSWH.js';import {d}from'./chunk-5TAVYPOV.js';import*as i from'fs';import*as a from'path';import*as D from'os';import*as x from'crypto';import*as p from'js-yaml';function T(){let n=a.join(D.homedir(),".paradigm");return i.existsSync(n)||i.mkdirSync(n,{recursive:true}),n}function N(n){let s=a.resolve(n);return x.createHash("sha256").update(s).digest("hex").slice(0,12)}function f(n){let s=N(n),t=a.join(T(),"sessions",s);i.existsSync(t)||i.mkdirSync(t,{recursive:true});let e=a.join(t,"pending-handoffs");return i.existsSync(e)||i.mkdirSync(e,{recursive:true}),t}function b(n){let s=f(n),t=a.join(s,"_project-meta.json"),o={name:a.basename(a.resolve(n)),path:a.resolve(n),lastSeen:new Date().toISOString()};i.writeFileSync(t,JSON.stringify(o,null,2));}function M(n,s){let t=f(n),e=a.join(t,"pending-handoffs",`${s.id}.json`);i.writeFileSync(e,JSON.stringify(s,null,2));}function E(n){let s=f(n),t=a.join(s,"pending-handoffs");if(!i.existsSync(t))return [];let e=[];try{let o=i.readdirSync(t);for(let l of o)if(l.endsWith(".json"))try{let u=i.readFileSync(a.join(t,l),"utf8"),m=JSON.parse(u);m.status==="pending"&&e.push(m);}catch{}}catch{}return e.sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime()),e}function O(n,s){let t=f(n),e=a.join(t,"pending-handoffs",`${s}.json`);if(i.existsSync(e))try{let o=i.readFileSync(e,"utf8"),l=JSON.parse(o);l.status="delivered",i.writeFileSync(e,JSON.stringify(l,null,2));}catch{}}function g(){let n=a.join(T(),"wisdom");return i.existsSync(n)||i.mkdirSync(n,{recursive:true}),n}function A(){let n=a.join(g(),"antipatterns.yaml");if(!i.existsSync(n))return [];try{let s=i.readFileSync(n,"utf8");return p.load(s)?.antipatterns||[]}catch{return []}}function W(){let n=a.join(g(),"decisions");if(!i.existsSync(n))return [];let s=[];try{let t=i.readdirSync(n);for(let e of t)if(!(!e.endsWith(".yaml")&&!e.endsWith(".yml")))try{let o=i.readFileSync(a.join(n,e),"utf8"),l=p.load(o);s.push(l);}catch{}}catch{}return s.sort((t,e)=>t.id.localeCompare(e.id)),s}function H(){let n=a.join(g(),"preferences.yaml");if(!i.existsSync(n))return null;try{let s=i.readFileSync(n,"utf8");return p.load(s)}catch{return null}}function L(n){let s=a.join(g(),"antipatterns.yaml"),t={version:"1.0",antipatterns:[]};if(i.existsSync(s))try{let e=i.readFileSync(s,"utf8");t=p.load(e),t.antipatterns||(t.antipatterns=[]);}catch{}t.antipatterns.push({...n,added:new Date().toISOString()}),i.writeFileSync(s,p.dump(t,{lineWidth:-1}));}function _(n){let s=a.join(g(),"decisions");i.existsSync(s)||i.mkdirSync(s,{recursive:true});let t=n.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),e=`${n.id}-${t}.yaml`,o=a.join(s,e);i.writeFileSync(o,p.dump(n,{lineWidth:-1}));}var S={"claude-opus-4":{input:15,output:75,name:"Claude Opus 4"},"claude-sonnet-4":{input:3,output:15,name:"Claude Sonnet 4"},"claude-haiku-3.5":{input:.8,output:4,name:"Claude Haiku 3.5"}},w=50,j=".paradigm/session-breadcrumbs.json",P=".paradigm/session-checkpoint.json",F=10080*60*1e3,k=class{session;rootDir=null;_recovered=false;lastLoreEntryId=null;constructor(){this.session=this.createNewSession();}setRootDir(s){this.rootDir=s;try{let{clearSessionWorkLog:t}=(h(),d(g$1));t(s);}catch{}}createNewSession(){return {sessionId:`s${Date.now().toString(36)}`,startTime:Date.now(),lastActivity:Date.now(),model:"claude-sonnet-4",resourceReads:[],toolCalls:[],breadcrumbs:[],totals:{resourceReadCount:0,toolCallCount:0,totalBytes:0,totalTokens:0,estimatedCostUsd:0}}}addBreadcrumb(s,t,e={}){this.session.breadcrumbs.push({timestamp:Date.now(),action:s,tool:e.tool,symbol:e.symbol,summary:t}),this.session.breadcrumbs.length>w&&(this.session.breadcrumbs=this.session.breadcrumbs.slice(-w)),this.persistBreadcrumbs();}getBreadcrumbs(s=20){return this.session.breadcrumbs.slice(-s)}persistBreadcrumbs(){if(!this.rootDir)return;let s={sessionId:this.session.sessionId,startTime:this.session.startTime,lastActivity:this.session.lastActivity,breadcrumbs:this.session.breadcrumbs,symbolsModified:this.extractSymbolsFromBreadcrumbs(),filesExplored:this.extractFilesFromBreadcrumbs()},t;try{t=JSON.stringify(s,null,2);}catch(e){console.error("[paradigm-mcp] persistBreadcrumbs: JSON.stringify failed:",e.message);return}try{let e=a.join(this.rootDir,j),o=a.dirname(e);i.existsSync(o)||i.mkdirSync(o,{recursive:!0}),i.writeFileSync(e,t);}catch(e){console.error("[paradigm-mcp] persistBreadcrumbs: local write failed:",e.message);}try{let e=f(this.rootDir);i.writeFileSync(a.join(e,"breadcrumbs.json"),t),b(this.rootDir);}catch(e){console.error("[paradigm-mcp] persistBreadcrumbs: global write failed:",e.message);}}loadPreviousSession(){if(!this.rootDir)return null;try{let s=f(this.rootDir),t=a.join(s,"breadcrumbs.json");if(i.existsSync(t)){let e=i.readFileSync(t,"utf8");return JSON.parse(e)}}catch{}try{let s=a.join(this.rootDir,j);if(!i.existsSync(s))return null;let t=i.readFileSync(s,"utf8");return JSON.parse(t)}catch{return null}}saveCheckpoint(s){let t={phase:s.phase,context:s.context,timestamp:Date.now(),sessionId:this.session.sessionId,externalId:s.externalId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:this.session.breadcrumbs.slice(-10)},e=this.persistCheckpoint(t);return {checkpoint:t,persisted:e}}loadCheckpoint(){if(!this.rootDir)return null;let s=null;try{let t=f(this.rootDir),e=a.join(t,"checkpoint.json");if(i.existsSync(e)){let o=i.readFileSync(e,"utf8");s=JSON.parse(o);}}catch{}if(!s)try{let t=a.join(this.rootDir,P);if(i.existsSync(t)){let e=i.readFileSync(t,"utf8");s=JSON.parse(e);}}catch{}if(s&&Date.now()-s.timestamp>F)return null;if(s)for(let t of ["modifiedFiles","symbolsTouched","decisions"]){let e=s[t];if(typeof e=="string")try{s[t]=JSON.parse(e);}catch{s[t]=[];}}return s}persistCheckpoint(s){let t={local:false,global:false};if(!this.rootDir)return console.error("[paradigm-mcp] persistCheckpoint: rootDir not set, skipping write"),t;let e;try{e=JSON.stringify(s,null,2);}catch(o){return console.error("[paradigm-mcp] persistCheckpoint: JSON.stringify failed:",o.message),t}try{let o=a.join(this.rootDir,P),l=a.dirname(o);i.existsSync(l)||i.mkdirSync(l,{recursive:!0}),i.writeFileSync(o,e),t.local=!0;}catch(o){console.error("[paradigm-mcp] persistCheckpoint: local write failed:",o.message);}try{let o=f(this.rootDir);i.writeFileSync(a.join(o,"checkpoint.json"),e),b(this.rootDir),t.global=!0;}catch(o){console.error("[paradigm-mcp] persistCheckpoint: global write failed:",o.message);}return t}setLastLoreEntryId(s){this.lastLoreEntryId=s;}getLastLoreEntryId(){return this.lastLoreEntryId}hasRecoveredThisSession(){return this._recovered}markRecovered(){this._recovered=true;}extractSymbolsFromBreadcrumbs(){let s=new Set;for(let t of this.session.breadcrumbs)t.symbol&&s.add(t.symbol);return Array.from(s)}extractFilesFromBreadcrumbs(){let s=new Set;for(let t of this.session.breadcrumbs){let e=t.summary.match(/\b[\w./]+\.(ts|js|tsx|jsx|py|go|rs|yaml|json|md)\b/g);if(e)for(let o of e)s.add(o);}return Array.from(s)}estimateTokens(s){let t=typeof s=="number"?s:s.length;return Math.ceil(t/3.5)}calculateCost(s,t=true){let e=S[this.session.model],o=t?e.output:e.input;return s/1e6*o}setModel(s){this.session.model=s,this.recalculateTotals();}getModel(){return this.session.model}trackResourceRead(s,t){let e=this.extractResourceType(s),o=this.estimateTokens(t);this.session.resourceReads.push({timestamp:Date.now(),resourceType:e,uri:s,bytes:t,tokens:o}),this.session.lastActivity=Date.now(),this.updateTotals(t,o);}trackToolCall(s,t){let e=this.estimateTokens(t);this.session.toolCalls.push({timestamp:Date.now(),toolName:s,responseBytes:t,responseTokens:e}),this.session.lastActivity=Date.now(),this.updateTotals(t,e);}updateTotals(s,t){this.session.totals.resourceReadCount=this.session.resourceReads.length,this.session.totals.toolCallCount=this.session.toolCalls.length,this.session.totals.totalBytes+=s,this.session.totals.totalTokens+=t,this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}recalculateTotals(){this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}extractResourceType(s){return s.replace("paradigm://","").split("/")[0]||"unknown"}getStats(){return {...this.session}}getCostBreakdown(){let s={},t=0,e=0;for(let r of this.session.resourceReads)s[r.resourceType]||(s[r.resourceType]={count:0,bytes:0,tokens:0}),s[r.resourceType].count++,s[r.resourceType].bytes+=r.bytes,s[r.resourceType].tokens+=r.tokens,t+=r.bytes,e+=r.tokens;let o={},l=0,u=0;for(let r of this.session.toolCalls)o[r.toolName]||(o[r.toolName]={count:0,bytes:0,tokens:0}),o[r.toolName].count++,o[r.toolName].bytes+=r.responseBytes,o[r.toolName].tokens+=r.responseTokens,l+=r.responseBytes,u+=r.responseTokens;let m=e+u,h=this.calculateCost(m);return {model:S[this.session.model].name,modelId:this.session.model,pricing:S[this.session.model],resources:{count:this.session.resourceReads.length,bytes:t,tokens:e,costUsd:this.calculateCost(e),byType:s},tools:{count:this.session.toolCalls.length,bytes:l,tokens:u,costUsd:this.calculateCost(u),byName:o},total:{tokens:m,costUsd:h}}}getHandoffRecommendation(s=2e5,t){let e=this.session.totals.totalTokens,o=e*4,l=t||e+o,u=Math.round(l/s*100),m,h;u>=85?(m="handoff-urgent",h="Context is nearly full. Initiate handoff immediately to preserve session continuity."):u>=70?(m="handoff-recommended",h="Context usage is high. Consider initiating handoff soon to ensure smooth transition."):u>=50?(m="consider-handoff",h="Context usage is moderate. Plan a good stopping point for potential handoff."):(m="continue",h="Context usage is healthy. Continue working.");let r=[],C=Math.round((Date.now()-this.session.startTime)/6e4),v=this.session.toolCalls.length+this.session.resourceReads.length;return v>50&&r.push(`High number of MCP interactions (${v})`),C>30&&r.push(`Session duration >30 min (${C} min)`),this.session.totals.totalBytes>5e5&&r.push(`Large data volume (${Math.round(this.session.totals.totalBytes/1024)}KB)`),{recommendation:m,message:h,usagePercent:u,signals:r}}getDurationMinutes(){return Math.round((Date.now()-this.session.startTime)/6e4)}reset(){this.session=this.createNewSession(),this._recovered=false,this.lastLoreEntryId=null;}},y=null;function G(){return y||(y=new k),y}function $(){y&&y.reset();}
|
|
2
|
+
import {h,g as g$1}from'./chunk-SL3RZQPW.js';import {d}from'./chunk-5TAVYPOV.js';import*as i from'fs';import*as a from'path';import*as D from'os';import*as x from'crypto';import*as p from'js-yaml';function T(){let n=a.join(D.homedir(),".paradigm");return i.existsSync(n)||i.mkdirSync(n,{recursive:true}),n}function N(n){let s=a.resolve(n);return x.createHash("sha256").update(s).digest("hex").slice(0,12)}function f(n){let s=N(n),t=a.join(T(),"sessions",s);i.existsSync(t)||i.mkdirSync(t,{recursive:true});let e=a.join(t,"pending-handoffs");return i.existsSync(e)||i.mkdirSync(e,{recursive:true}),t}function b(n){let s=f(n),t=a.join(s,"_project-meta.json"),o={name:a.basename(a.resolve(n)),path:a.resolve(n),lastSeen:new Date().toISOString()};i.writeFileSync(t,JSON.stringify(o,null,2));}function M(n,s){let t=f(n),e=a.join(t,"pending-handoffs",`${s.id}.json`);i.writeFileSync(e,JSON.stringify(s,null,2));}function E(n){let s=f(n),t=a.join(s,"pending-handoffs");if(!i.existsSync(t))return [];let e=[];try{let o=i.readdirSync(t);for(let l of o)if(l.endsWith(".json"))try{let u=i.readFileSync(a.join(t,l),"utf8"),m=JSON.parse(u);m.status==="pending"&&e.push(m);}catch{}}catch{}return e.sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime()),e}function O(n,s){let t=f(n),e=a.join(t,"pending-handoffs",`${s}.json`);if(i.existsSync(e))try{let o=i.readFileSync(e,"utf8"),l=JSON.parse(o);l.status="delivered",i.writeFileSync(e,JSON.stringify(l,null,2));}catch{}}function g(){let n=a.join(T(),"wisdom");return i.existsSync(n)||i.mkdirSync(n,{recursive:true}),n}function A(){let n=a.join(g(),"antipatterns.yaml");if(!i.existsSync(n))return [];try{let s=i.readFileSync(n,"utf8");return p.load(s)?.antipatterns||[]}catch{return []}}function W(){let n=a.join(g(),"decisions");if(!i.existsSync(n))return [];let s=[];try{let t=i.readdirSync(n);for(let e of t)if(!(!e.endsWith(".yaml")&&!e.endsWith(".yml")))try{let o=i.readFileSync(a.join(n,e),"utf8"),l=p.load(o);s.push(l);}catch{}}catch{}return s.sort((t,e)=>t.id.localeCompare(e.id)),s}function H(){let n=a.join(g(),"preferences.yaml");if(!i.existsSync(n))return null;try{let s=i.readFileSync(n,"utf8");return p.load(s)}catch{return null}}function L(n){let s=a.join(g(),"antipatterns.yaml"),t={version:"1.0",antipatterns:[]};if(i.existsSync(s))try{let e=i.readFileSync(s,"utf8");t=p.load(e),t.antipatterns||(t.antipatterns=[]);}catch{}t.antipatterns.push({...n,added:new Date().toISOString()}),i.writeFileSync(s,p.dump(t,{lineWidth:-1}));}function _(n){let s=a.join(g(),"decisions");i.existsSync(s)||i.mkdirSync(s,{recursive:true});let t=n.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),e=`${n.id}-${t}.yaml`,o=a.join(s,e);i.writeFileSync(o,p.dump(n,{lineWidth:-1}));}var S={"claude-opus-4":{input:15,output:75,name:"Claude Opus 4"},"claude-sonnet-4":{input:3,output:15,name:"Claude Sonnet 4"},"claude-haiku-3.5":{input:.8,output:4,name:"Claude Haiku 3.5"}},w=50,j=".paradigm/session-breadcrumbs.json",P=".paradigm/session-checkpoint.json",F=10080*60*1e3,k=class{session;rootDir=null;_recovered=false;lastLoreEntryId=null;constructor(){this.session=this.createNewSession();}setRootDir(s){this.rootDir=s;try{let{clearSessionWorkLog:t}=(h(),d(g$1));t(s);}catch{}}createNewSession(){return {sessionId:`s${Date.now().toString(36)}`,startTime:Date.now(),lastActivity:Date.now(),model:"claude-sonnet-4",resourceReads:[],toolCalls:[],breadcrumbs:[],totals:{resourceReadCount:0,toolCallCount:0,totalBytes:0,totalTokens:0,estimatedCostUsd:0}}}addBreadcrumb(s,t,e={}){this.session.breadcrumbs.push({timestamp:Date.now(),action:s,tool:e.tool,symbol:e.symbol,summary:t}),this.session.breadcrumbs.length>w&&(this.session.breadcrumbs=this.session.breadcrumbs.slice(-w)),this.persistBreadcrumbs();}getBreadcrumbs(s=20){return this.session.breadcrumbs.slice(-s)}persistBreadcrumbs(){if(!this.rootDir)return;let s={sessionId:this.session.sessionId,startTime:this.session.startTime,lastActivity:this.session.lastActivity,breadcrumbs:this.session.breadcrumbs,symbolsModified:this.extractSymbolsFromBreadcrumbs(),filesExplored:this.extractFilesFromBreadcrumbs()},t;try{t=JSON.stringify(s,null,2);}catch(e){console.error("[paradigm-mcp] persistBreadcrumbs: JSON.stringify failed:",e.message);return}try{let e=a.join(this.rootDir,j),o=a.dirname(e);i.existsSync(o)||i.mkdirSync(o,{recursive:!0}),i.writeFileSync(e,t);}catch(e){console.error("[paradigm-mcp] persistBreadcrumbs: local write failed:",e.message);}try{let e=f(this.rootDir);i.writeFileSync(a.join(e,"breadcrumbs.json"),t),b(this.rootDir);}catch(e){console.error("[paradigm-mcp] persistBreadcrumbs: global write failed:",e.message);}}loadPreviousSession(){if(!this.rootDir)return null;try{let s=f(this.rootDir),t=a.join(s,"breadcrumbs.json");if(i.existsSync(t)){let e=i.readFileSync(t,"utf8");return JSON.parse(e)}}catch{}try{let s=a.join(this.rootDir,j);if(!i.existsSync(s))return null;let t=i.readFileSync(s,"utf8");return JSON.parse(t)}catch{return null}}saveCheckpoint(s){let t={phase:s.phase,context:s.context,timestamp:Date.now(),sessionId:this.session.sessionId,externalId:s.externalId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:this.session.breadcrumbs.slice(-10)},e=this.persistCheckpoint(t);return {checkpoint:t,persisted:e}}loadCheckpoint(){if(!this.rootDir)return null;let s=null;try{let t=f(this.rootDir),e=a.join(t,"checkpoint.json");if(i.existsSync(e)){let o=i.readFileSync(e,"utf8");s=JSON.parse(o);}}catch{}if(!s)try{let t=a.join(this.rootDir,P);if(i.existsSync(t)){let e=i.readFileSync(t,"utf8");s=JSON.parse(e);}}catch{}if(s&&Date.now()-s.timestamp>F)return null;if(s)for(let t of ["modifiedFiles","symbolsTouched","decisions"]){let e=s[t];if(typeof e=="string")try{s[t]=JSON.parse(e);}catch{s[t]=[];}}return s}persistCheckpoint(s){let t={local:false,global:false};if(!this.rootDir)return console.error("[paradigm-mcp] persistCheckpoint: rootDir not set, skipping write"),t;let e;try{e=JSON.stringify(s,null,2);}catch(o){return console.error("[paradigm-mcp] persistCheckpoint: JSON.stringify failed:",o.message),t}try{let o=a.join(this.rootDir,P),l=a.dirname(o);i.existsSync(l)||i.mkdirSync(l,{recursive:!0}),i.writeFileSync(o,e),t.local=!0;}catch(o){console.error("[paradigm-mcp] persistCheckpoint: local write failed:",o.message);}try{let o=f(this.rootDir);i.writeFileSync(a.join(o,"checkpoint.json"),e),b(this.rootDir),t.global=!0;}catch(o){console.error("[paradigm-mcp] persistCheckpoint: global write failed:",o.message);}return t}setLastLoreEntryId(s){this.lastLoreEntryId=s;}getLastLoreEntryId(){return this.lastLoreEntryId}hasRecoveredThisSession(){return this._recovered}markRecovered(){this._recovered=true;}extractSymbolsFromBreadcrumbs(){let s=new Set;for(let t of this.session.breadcrumbs)t.symbol&&s.add(t.symbol);return Array.from(s)}extractFilesFromBreadcrumbs(){let s=new Set;for(let t of this.session.breadcrumbs){let e=t.summary.match(/\b[\w./]+\.(ts|js|tsx|jsx|py|go|rs|yaml|json|md)\b/g);if(e)for(let o of e)s.add(o);}return Array.from(s)}estimateTokens(s){let t=typeof s=="number"?s:s.length;return Math.ceil(t/3.5)}calculateCost(s,t=true){let e=S[this.session.model],o=t?e.output:e.input;return s/1e6*o}setModel(s){this.session.model=s,this.recalculateTotals();}getModel(){return this.session.model}trackResourceRead(s,t){let e=this.extractResourceType(s),o=this.estimateTokens(t);this.session.resourceReads.push({timestamp:Date.now(),resourceType:e,uri:s,bytes:t,tokens:o}),this.session.lastActivity=Date.now(),this.updateTotals(t,o);}trackToolCall(s,t){let e=this.estimateTokens(t);this.session.toolCalls.push({timestamp:Date.now(),toolName:s,responseBytes:t,responseTokens:e}),this.session.lastActivity=Date.now(),this.updateTotals(t,e);}updateTotals(s,t){this.session.totals.resourceReadCount=this.session.resourceReads.length,this.session.totals.toolCallCount=this.session.toolCalls.length,this.session.totals.totalBytes+=s,this.session.totals.totalTokens+=t,this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}recalculateTotals(){this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}extractResourceType(s){return s.replace("paradigm://","").split("/")[0]||"unknown"}getStats(){return {...this.session}}getCostBreakdown(){let s={},t=0,e=0;for(let r of this.session.resourceReads)s[r.resourceType]||(s[r.resourceType]={count:0,bytes:0,tokens:0}),s[r.resourceType].count++,s[r.resourceType].bytes+=r.bytes,s[r.resourceType].tokens+=r.tokens,t+=r.bytes,e+=r.tokens;let o={},l=0,u=0;for(let r of this.session.toolCalls)o[r.toolName]||(o[r.toolName]={count:0,bytes:0,tokens:0}),o[r.toolName].count++,o[r.toolName].bytes+=r.responseBytes,o[r.toolName].tokens+=r.responseTokens,l+=r.responseBytes,u+=r.responseTokens;let m=e+u,h=this.calculateCost(m);return {model:S[this.session.model].name,modelId:this.session.model,pricing:S[this.session.model],resources:{count:this.session.resourceReads.length,bytes:t,tokens:e,costUsd:this.calculateCost(e),byType:s},tools:{count:this.session.toolCalls.length,bytes:l,tokens:u,costUsd:this.calculateCost(u),byName:o},total:{tokens:m,costUsd:h}}}getHandoffRecommendation(s=2e5,t){let e=this.session.totals.totalTokens,o=e*4,l=t||e+o,u=Math.round(l/s*100),m,h;u>=85?(m="handoff-urgent",h="Context is nearly full. Initiate handoff immediately to preserve session continuity."):u>=70?(m="handoff-recommended",h="Context usage is high. Consider initiating handoff soon to ensure smooth transition."):u>=50?(m="consider-handoff",h="Context usage is moderate. Plan a good stopping point for potential handoff."):(m="continue",h="Context usage is healthy. Continue working.");let r=[],C=Math.round((Date.now()-this.session.startTime)/6e4),v=this.session.toolCalls.length+this.session.resourceReads.length;return v>50&&r.push(`High number of MCP interactions (${v})`),C>30&&r.push(`Session duration >30 min (${C} min)`),this.session.totals.totalBytes>5e5&&r.push(`Large data volume (${Math.round(this.session.totals.totalBytes/1024)}KB)`),{recommendation:m,message:h,usagePercent:u,signals:r}}getDurationMinutes(){return Math.round((Date.now()-this.session.startTime)/6e4)}reset(){this.session=this.createNewSession(),this._recovered=false,this.lastLoreEntryId=null;}},y=null;function G(){return y||(y=new k),y}function $(){y&&y.reset();}
|
|
3
3
|
export{M as a,E as b,O as c,A as d,W as e,H as f,L as g,_ as h,S as i,G as j,$ as k};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {b as b$1}from'./chunk-5TAVYPOV.js';import*as l from'fs';import*as u from'path';import*as T from'os';import*as E from'crypto';import*as d from'js-yaml';var v,w,j,S=b$1(()=>{v={architect:{style:"deliberate",risk:"conservative",verbosity:"detailed"},builder:{style:"rapid",risk:"balanced",verbosity:"concise"},tester:{style:"methodical",risk:"conservative",verbosity:"concise"},reviewer:{style:"deliberate",risk:"conservative",verbosity:"detailed"},security:{style:"methodical",risk:"conservative",verbosity:"detailed"},documentor:{style:"methodical",risk:"conservative",verbosity:"concise"}},w={architect:{symbols:["$*","#*"],concepts:["architecture","design","pattern","refactor"],signals:[{type:"flow-modified"},{type:"compliance-violation"}],threshold:.5},builder:{paths:["src/**","lib/**","packages/**"],signals:[{type:"file-modified"},{type:"error-encountered"}],threshold:.7},reviewer:{concepts:["code quality","bug","smell","convention"],signals:[{type:"compliance-violation"}],threshold:.6},tester:{paths:["**/*.test.*","**/*.spec.*"],concepts:["test","coverage","assertion"],signals:[{type:"error-encountered"},{type:"test-result"}],threshold:.5},security:{symbols:["^*","#*-auth","#*-middleware"],paths:["auth/**","middleware/**","guards/**"],concepts:["permission","JWT","session","RBAC","XSS","injection"],signals:[{type:"gate-added"},{type:"route-created"},{type:"gate-checked"},{type:"compliance-violation"}],threshold:.4},documentor:{paths:["**/.purpose","**/portal.yaml",".paradigm/**"],concepts:["purpose","portal","symbol","documentation","component","gate","flow"],signals:[{type:"file-modified"},{type:"compliance-violation"},{type:"work-completed"}],threshold:.3}},j={architect:{stance:"lead",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},builder:{stance:"supportive",with:{architect:{stance:"supportive",can_contradict:false}}},reviewer:{stance:"advisory",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},tester:{stance:"supportive",debate:{will_challenge:false,evidence_required:true,escalate_to_human:false}},security:{stance:"advisory",with:{architect:{stance:"peer",can_contradict:true},builder:{stance:"advisory",review_output:true}},debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},documentor:{stance:"supportive",with:{architect:{stance:"supportive"},builder:{stance:"supportive"},reviewer:{stance:"supportive"},security:{stance:"supportive"}},debate:{will_challenge:false,evidence_required:false,escalate_to_human:false}}};});function m(e,t){let o=(Date.now()-new Date(t).getTime())/(1e3*60*60*24);if(o<=k)return e;let r=Math.pow(.5,(o-k)/I);return e*r}function D(e){let t=u.join(e,R);if(!l.existsSync(t))return null;try{return d.load(l.readFileSync(t,"utf8"))?.active??null}catch{return null}}function Y(e,t){let i=D(t);return i?i.includes(e):true}function B(e,t){let i=u.join(e,R),o=u.dirname(i);l.existsSync(o)||l.mkdirSync(o,{recursive:true});let r={version:"1.0",active:t.sort()};l.writeFileSync(i,d.dump(r,{lineWidth:-1,noRefs:true}),"utf8");}function J(){if(!l.existsSync(y))return [];try{return l.readdirSync(y).filter(e=>e.endsWith(h)).map(e=>e.replace(h,""))}catch{return []}}function _(e,t){let i=u.join(e,x,`${t}${h}`);if(l.existsSync(i))try{let r=l.readFileSync(i,"utf-8");return d.load(r)}catch{}let o=u.join(y,`${t}${h}`);if(l.existsSync(o))try{let r=l.readFileSync(o,"utf-8"),n=d.load(r);if(l.existsSync(i))try{let a=l.readFileSync(i,"utf-8"),f=d.load(a);return N(n,f)}catch{}return n}catch{}return null}function M(e,t){let i=C(e),o=t.toLowerCase();return i.filter(r=>r.nickname?.toLowerCase()===o)}function z(e,t){let i=_(e,t);return i||(M(e,t)[0]??null)}function C(e){let t=new Map;if(l.existsSync(y))try{let o=l.readdirSync(y).filter(r=>r.endsWith(h));for(let r of o)try{let n=l.readFileSync(u.join(y,r),"utf-8"),a=d.load(n);a?.id&&t.set(a.id,a);}catch{}}catch{}let i=u.join(e,x);if(l.existsSync(i))try{let o=l.readdirSync(i).filter(r=>r.endsWith(h));for(let r of o)try{let n=l.readFileSync(u.join(i,r),"utf-8"),a=d.load(n);if(!a?.id)continue;let f=t.get(a.id);f?t.set(a.id,N(f,a)):t.set(a.id,a);}catch{}}catch{}return Array.from(t.values())}function P(e,t,i,o){let r=i==="global"?y:u.join(o||process.cwd(),x);l.existsSync(r)||l.mkdirSync(r,{recursive:true});let n=u.join(r,`${e}${h}`);t.permissions&&(t.integrityHash=L(t)),t.updated=new Date().toISOString();let a=d.dump(t,{lineWidth:120,noRefs:true,sortKeys:false});return l.writeFileSync(n,a,"utf-8"),n}function q(e,t={}){let i=new Date().toISOString(),o={id:e,role:t.role||`${e.charAt(0).toUpperCase()+e.slice(1)} agent`,description:t.description||`Persistent identity for the ${e} agent role`,version:"1.0.0",personality:v[e]||{style:"balanced",risk:"balanced",verbosity:"concise"},expertise:[],transferable:[],contexts:{},created:i,updated:i};v[e]||(o.personality={style:"deliberate",risk:"balanced",verbosity:"concise"}),w[e]&&(o.attention={...w[e]}),j[e]&&(o.collaboration={...j[e]});let r=t.scope||"global",n=P(e,o,r,t.rootDir);return {profile:o,filePath:n}}function X(e,t){let i=C(e),o=[];for(let r of i){let n=(r.expertise||[]).find(a=>a.symbol===t);n&&o.push({agentId:r.id,entry:n});}return o.sort((r,n)=>m(n.entry.confidence,n.entry.lastTouch)-m(r.entry.confidence,r.entry.lastTouch))}function K(e,t,i){let o=_(e,t);if(!o)return false;let r=new Date().toISOString(),n=o.expertise||[];for(let c of i.symbols_touched){let p=n.find(g=>g.symbol===c);p?(p.sessions++,p.lastTouch=r,i.confidence!=null&&(p.confidence=(1-b)*p.confidence+b*i.confidence)):n.push({symbol:c,confidence:i.confidence??.5,sessions:1,lastTouch:r});}o.expertise=n;let a=W(e);if(a){let c=o.contexts[a]||{focus:[],sessionsInProject:0};c.lastActive=r,c.sessionsInProject=(c.sessionsInProject||0)+1,o.contexts[a]=c;}let f=u.join(e,x,`${t}${h}`),s=l.existsSync(f)?"project":"global";return P(t,o,s,e),true}function V(e,t,i){let o=_(e,t);if(!o)return false;let n={correct:1,partial:.5,incorrect:0}[i.verdict];for(let s of i.symbols_touched){let c=(o.expertise||[]).find(p=>p.symbol===s);c&&(c.confidence=(1-b)*c.confidence+b*n);}let a=u.join(e,x,`${t}${h}`),f=l.existsSync(a)?"project":"global";return P(t,o,f,e),true}function Q(e,t,i){return t?{personality:t.personality||null,topExpertise:(t.expertise||[]).sort((o,r)=>m(r.confidence,r.lastTouch)-m(o.confidence,o.lastTouch)).slice(0,10),projectContext:t.contexts?.[i]||null,transferablePatterns:(t.transferable||[]).filter(o=>o.successRate>=.7).map(o=>({id:o.id,description:o.description,successRate:o.successRate}))}:{personality:null,topExpertise:[],projectContext:null,transferablePatterns:[]}}function Z(e,t,i,o,r){let n=[];if(e.personality){let s=e.personality;n.push(`## Agent Identity: ${e.id}`),n.push(`**Style:** ${s.style} | **Risk:** ${s.risk} | **Verbosity:** ${s.verbosity}`),n.push("");}let a=(e.expertise||[]).filter(s=>t.length===0||t.includes(s.symbol)).sort((s,c)=>m(c.confidence,c.lastTouch)-m(s.confidence,s.lastTouch)).slice(0,8);if(a.length>0){n.push("## Your Expertise on Relevant Symbols");for(let s of a){let p=1-m(s.confidence,s.lastTouch)/s.confidence,g=s.confidence>0&&p>O?" (aging)":"";n.push(`- \`${s.symbol}\`: confidence ${s.confidence.toFixed(2)} (${s.sessions} sessions)${g}`);}n.push("");}let f=(e.transferable||[]).filter(s=>s.successRate>=.7);if(f.length>0){n.push("## Transferable Patterns");for(let s of f){let c=s.appliedIn?.length||0;n.push(`- ${s.id}: ${(s.successRate*100).toFixed(0)}% success (learned in ${s.learnedIn}${c>0?`, applied in ${c} projects`:""})`);}n.push("");}if(i&&i.length>0){n.push("## Relevant Notebook Entries");for(let s of i.slice(0,5)){n.push(`### ${s.context}`),n.push(`Concepts: ${s.concepts.join(", ")}`),n.push("```");let c=s.snippet.length>300?s.snippet.slice(0,300)+"...":s.snippet;n.push(c),n.push("```"),n.push("");}}if(r){if(n.push(""),n.push("## Your Recent Work on This Project"),r.lastSession){let s=Date.now()-new Date(r.lastSession.date).getTime(),c=Math.floor(s/(3600*1e3)),p=c<24?`${c}h ago`:`${Math.floor(c/24)}d ago`;n.push(`Last session (${p}): ${r.lastSession.summary}`);}if(r.sessionsOnProject&&n.push(`Sessions on this project: ${r.sessionsOnProject}`),r.pendingWork?.length){n.push("**Pending from last session:**");for(let s of r.pendingWork.slice(0,5))n.push(`- ${s}`);}if(r.recentPatterns?.length){n.push("**Project patterns you've learned:**");for(let s of r.recentPatterns.slice(0,5))n.push(`- ${s}`);}n.push("");}if(e.attention){let s=e.attention,c=[];s.symbols?.length&&c.push(`Symbols: ${s.symbols.join(", ")}`),s.paths?.length&&c.push(`Paths: ${s.paths.join(", ")}`),s.concepts?.length&&c.push(`Concepts: ${s.concepts.join(", ")}`),s.signals?.length&&c.push(`Signals: ${s.signals.map(p=>p.type).join(", ")}`),c.length>0&&(n.push(""),n.push("### Attention"),n.push(`Threshold: ${s.threshold??.6}`),n.push(c.join(" | ")));}if(e.collaboration){let s=e.collaboration;if(n.push(""),n.push("### Collaboration"),n.push(`Default stance: ${s.stance||"supportive"}`),s.with)for(let[c,p]of Object.entries(s.with)){let g=[`${c}: ${p.stance||"peer"}`];p.can_contradict&&g.push("can contradict"),p.review_output&&g.push("reviews output"),n.push(`- ${g.join(", ")}`);}if(s.debate){let c=s.debate,p=[];c.will_challenge&&p.push("challenges"),c.evidence_required&&p.push("evidence-based"),c.escalate_to_human&&p.push("escalates to human"),p.length&&n.push(`Debate: ${p.join(", ")}`);}}if(e.nomination){let s=e.nomination;if(n.push(""),n.push("### Nomination"),s.speak_when?.urgency?.length&&n.push(`Always speaks on: ${s.speak_when.urgency.join(", ")}`),s.contribution_style){let c=[];s.contribution_style.brief_first&&c.push("brief first"),s.contribution_style.cite_sources&&c.push("cites sources"),s.contribution_style.offer_action&&c.push("offers action"),c.length&&n.push(`Style: ${c.join(", ")}`);}}if(o){if(o.recentDecisions?.length){n.push(""),n.push("## Recent Team Decisions");for(let s of o.recentDecisions.slice(0,5))n.push(`- **${s.title}**: ${s.decision.slice(0,150)}${s.decision.length>150?"...":""}`);}if(o.journalInsights?.length){n.push(""),n.push("## Transferable Insights");for(let s of o.journalInsights.slice(0,5))n.push(`- [${s.trigger}] ${s.insight.slice(0,150)}${s.insight.length>150?"...":""}`);}if(o.pendingNominations?.length){n.push(""),n.push("## Pending Nominations");for(let s of o.pendingNominations.slice(0,10))n.push(`- [${s.urgency}] ${s.brief}`);}}return n.join(`
|
|
3
|
+
`)}async function ee(e,t,i=false){let{loadLoreEntries:o}=await import('./lore-loader-RVQI5GXL.js'),r=await o(e,{limit:500}),n=0,a=new Set,f=_(e,t)||q(t,{rootDir:e}).profile,s=f.expertise||[];for(let c of r)if(!(!c.symbols_touched||c.symbols_touched.length===0)){n++;for(let p of c.symbols_touched){a.add(p);let g=s.find(F=>F.symbol===p);g?(g.sessions++,g.lastTouch=c.timestamp,c.confidence!=null&&(g.confidence=(1-b)*g.confidence+b*c.confidence)):s.push({symbol:p,confidence:c.confidence??.5,sessions:1,lastTouch:c.timestamp});}}if(f.expertise=s,!i){let c=u.join(e,x,`${t}${h}`),p=l.existsSync(c)?"project":"global";P(t,f,p,e);}return {entriesProcessed:n,symbolsUpdated:a.size}}function te(e,t,i){if(!e.permissions?.paths)return {allowed:true};let{read:o,write:r,deny:n}=e.permissions.paths;if(n&&n.length>0){for(let f of n)if(A(f,t))return {allowed:false,reason:`Path denied by pattern: ${f}`}}let a=i==="read"?o:r;if(a&&a.length>0){for(let f of a)if(A(f,t))return {allowed:true};return {allowed:false,reason:`No ${i} pattern matches: ${t}`}}return {allowed:true}}function ne(e,t){if(!e.permissions?.tools)return {allowed:true};let{allow:i,deny:o}=e.permissions.tools;if(o&&o.length>0){for(let r of o)if(A(r,t))return {allowed:false,reason:`Tool denied by pattern: ${r}`}}if(i&&i.length>0){for(let r of i)if(A(r,t))return {allowed:true};return {allowed:false,reason:`Tool not in allow list: ${t}`}}return {allowed:true}}function L(e){let t=JSON.stringify({id:e.id,role:e.role,permissions:e.permissions||null});return E.createHash("sha256").update(t).digest("hex")}function se(e){return e.integrityHash?L(e)===e.integrityHash?{valid:true}:{valid:false,reason:"Integrity hash mismatch \u2014 profile may have been tampered with"}:{valid:true,reason:"No integrity hash stored (pre-4.0 profile)"}}function A(e,t){let i=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}function N(e,t){let i={...e};if(t.role&&(i.role=t.role),t.description&&(i.description=t.description),t.version&&(i.version=t.version),t.personality&&(i.personality={...e.personality,...t.personality}),t.expertise){let o=new Map(e.expertise.map(r=>[r.symbol,r]));for(let r of t.expertise)o.set(r.symbol,r);i.expertise=Array.from(o.values());}if(t.transferable){let o=new Map(e.transferable.map(r=>[r.id,r]));for(let r of t.transferable)o.set(r.id,r);i.transferable=Array.from(o.values());}if(t.contexts){i.contexts={...e.contexts};for(let[o,r]of Object.entries(t.contexts))i.contexts[o]={...i.contexts[o],...r};}return i}function W(e){try{let t=u.join(e,".paradigm","config.yaml");if(l.existsSync(t)){let i=l.readFileSync(t,"utf-8"),o=d.load(i);if(o?.project&&typeof o.project=="string")return o.project}}catch{}return u.basename(e)}var y,x,h,R,b,I,k,O,U=b$1(()=>{S();y=u.join(T.homedir(),".paradigm","agents"),x=".paradigm/agents",h=".agent",R=".paradigm/roster.yaml",b=.3,I=60,k=7,O=.2;});export{m as a,D as b,Y as c,B as d,J as e,_ as f,M as g,z as h,C as i,P as j,q as k,X as l,K as m,V as n,Q as o,Z as p,ee as q,te as r,ne as s,L as t,se as u,U as v};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {c,b as b$1}from'./chunk-5TAVYPOV.js';import*as i from'fs';import*as f from'path';var W={};c(W,{appendSessionWorkEntry:()=>b,clearSessionWorkLog:()=>E,getAgentEntries:()=>p,getAgentVerdicts:()=>k,getContributingAgents:()=>x,readSessionWorkLog:()=>l});function b(e,t){try{let n=f.join(e,u),o=f.dirname(n);if(i.existsSync(o)||i.mkdirSync(o,{recursive:!0}),i.existsSync(n)&&i.readFileSync(n,"utf8").trim().split(`
|
|
3
3
|
`).filter(r=>r.trim()).length>=v)return;let g=JSON.stringify(t)+`
|
|
4
|
-
`;i.appendFileSync(n,g,"utf8"),t.type==="user-verdict"&&t.agent&&t.symbols?.length&&import('./agent-loader-
|
|
4
|
+
`;i.appendFileSync(n,g,"utf8"),t.type==="user-verdict"&&t.agent&&t.symbols?.length&&import('./agent-loader-CZFB5BDP.js').then(({loadAgentProfile:c,saveAgentProfile:s})=>{try{let r=c(e,t.agent);if(r?.expertise){let d=t.verdict==="accepted"?.03:t.verdict==="dismissed"?-.02:t.verdict==="revised"?-.01:0;if(d!==0){for(let S of t.symbols){let a=r.expertise.find(y=>y.symbol===S);a&&(a.confidence=Math.max(0,Math.min(1,a.confidence+d)),a.sessions=(a.sessions||0)+1,a.lastTouch=new Date().toISOString());}s(t.agent,r,"global");}}}catch{}}).catch(()=>{});}catch{}}function l(e){try{let t=f.join(e,u);return i.existsSync(t)?i.readFileSync(t,"utf8").trim().split(`
|
|
5
5
|
`).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null):[]}catch{return []}}function E(e){try{let t=f.join(e,u);i.existsSync(t)&&i.writeFileSync(t,"","utf8");}catch{}}function x(e){let t=l(e),n=new Set;for(let o of t)o.agent&&n.add(o.agent);return Array.from(n)}function p(e,t){return l(e).filter(n=>n.agent===t)}function k(e,t){let n=p(e,t),o=n.filter(s=>s.type==="agent-contribution"),g=n.filter(s=>s.type==="user-verdict"),c=[];for(let s of o)c.push({contribution:s});for(let s of g){let r=c.find(d=>!d.verdict&&d.contribution);r?r.verdict=s:c.push({verdict:s});}return c}var u,v,A=b$1(()=>{u=".paradigm/events/session-log.jsonl",v=200;});export{b as a,l as b,E as c,x as d,p as e,k as f,W as g,A as h};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import*as l from'fs';import*as u from'path';import*as S from'os';import*as k from'crypto';import*as d from'js-yaml';var v={architect:{style:"deliberate",risk:"conservative",verbosity:"detailed"},builder:{style:"rapid",risk:"balanced",verbosity:"concise"},tester:{style:"methodical",risk:"conservative",verbosity:"concise"},reviewer:{style:"deliberate",risk:"conservative",verbosity:"detailed"},security:{style:"methodical",risk:"conservative",verbosity:"detailed"},documentor:{style:"methodical",risk:"conservative",verbosity:"concise"}},w={architect:{symbols:["$*","#*"],concepts:["architecture","design","pattern","refactor"],signals:[{type:"flow-modified"},{type:"compliance-violation"}],threshold:.5},builder:{paths:["src/**","lib/**","packages/**"],signals:[{type:"file-modified"},{type:"error-encountered"}],threshold:.7},reviewer:{concepts:["code quality","bug","smell","convention"],signals:[{type:"compliance-violation"}],threshold:.6},tester:{paths:["**/*.test.*","**/*.spec.*"],concepts:["test","coverage","assertion"],signals:[{type:"error-encountered"},{type:"test-result"}],threshold:.5},security:{symbols:["^*","#*-auth","#*-middleware"],paths:["auth/**","middleware/**","guards/**"],concepts:["permission","JWT","session","RBAC","XSS","injection"],signals:[{type:"gate-added"},{type:"route-created"},{type:"gate-checked"},{type:"compliance-violation"}],threshold:.4},documentor:{paths:["**/.purpose","**/portal.yaml",".paradigm/**"],concepts:["purpose","portal","symbol","documentation","component","gate","flow"],signals:[{type:"file-modified"},{type:"compliance-violation"},{type:"work-completed"}],threshold:.3}},j={architect:{stance:"lead",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},builder:{stance:"supportive",with:{architect:{stance:"supportive",can_contradict:false}}},reviewer:{stance:"advisory",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},tester:{stance:"supportive",debate:{will_challenge:false,evidence_required:true,escalate_to_human:false}},security:{stance:"advisory",with:{architect:{stance:"peer",can_contradict:true},builder:{stance:"advisory",review_output:true}},debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},documentor:{stance:"supportive",with:{architect:{stance:"supportive"},builder:{stance:"supportive"},reviewer:{stance:"supportive"},security:{stance:"supportive"}},debate:{will_challenge:false,evidence_required:false,escalate_to_human:false}}};var y=u.join(S.homedir(),".paradigm","agents"),x=".paradigm/agents",h=".agent",T=".paradigm/roster.yaml",b=.3,N=60,$=7,F=.2;function m(e,t){let o=(Date.now()-new Date(t).getTime())/(1e3*60*60*24);if(o<=$)return e;let r=Math.pow(.5,(o-$)/N);return e*r}function I(e){let t=u.join(e,T);if(!l.existsSync(t))return null;try{return d.load(l.readFileSync(t,"utf8"))?.active??null}catch{return null}}function U(e,t){let i=I(t);return i?i.includes(e):true}function H(e,t){let i=u.join(e,T),o=u.dirname(i);l.existsSync(o)||l.mkdirSync(o,{recursive:true});let r={version:"1.0",active:t.sort()};l.writeFileSync(i,d.dump(r,{lineWidth:-1,noRefs:true}),"utf8");}function G(){if(!l.existsSync(y))return [];try{return l.readdirSync(y).filter(e=>e.endsWith(h)).map(e=>e.replace(h,""))}catch{return []}}function _(e,t){let i=u.join(e,x,`${t}${h}`);if(l.existsSync(i))try{let r=l.readFileSync(i,"utf-8");return d.load(r)}catch{}let o=u.join(y,`${t}${h}`);if(l.existsSync(o))try{let r=l.readFileSync(o,"utf-8"),n=d.load(r);if(l.existsSync(i))try{let a=l.readFileSync(i,"utf-8"),f=d.load(a);return C(n,f)}catch{}return n}catch{}return null}function O(e,t){let i=E(e),o=t.toLowerCase();return i.filter(r=>r.nickname?.toLowerCase()===o)}function Y(e,t){let i=_(e,t);return i||(O(e,t)[0]??null)}function E(e){let t=new Map;if(l.existsSync(y))try{let o=l.readdirSync(y).filter(r=>r.endsWith(h));for(let r of o)try{let n=l.readFileSync(u.join(y,r),"utf-8"),a=d.load(n);a?.id&&t.set(a.id,a);}catch{}}catch{}let i=u.join(e,x);if(l.existsSync(i))try{let o=l.readdirSync(i).filter(r=>r.endsWith(h));for(let r of o)try{let n=l.readFileSync(u.join(i,r),"utf-8"),a=d.load(n);if(!a?.id)continue;let f=t.get(a.id);f?t.set(a.id,C(f,a)):t.set(a.id,a);}catch{}}catch{}return Array.from(t.values())}function P(e,t,i,o){let r=i==="global"?y:u.join(o||process.cwd(),x);l.existsSync(r)||l.mkdirSync(r,{recursive:true});let n=u.join(r,`${e}${h}`);t.permissions&&(t.integrityHash=R(t)),t.updated=new Date().toISOString();let a=d.dump(t,{lineWidth:120,noRefs:true,sortKeys:false});return l.writeFileSync(n,a,"utf-8"),n}function D(e,t={}){let i=new Date().toISOString(),o={id:e,role:t.role||`${e.charAt(0).toUpperCase()+e.slice(1)} agent`,description:t.description||`Persistent identity for the ${e} agent role`,version:"1.0.0",personality:v[e]||{style:"balanced",risk:"balanced",verbosity:"concise"},expertise:[],transferable:[],contexts:{},created:i,updated:i};v[e]||(o.personality={style:"deliberate",risk:"balanced",verbosity:"concise"}),w[e]&&(o.attention={...w[e]}),j[e]&&(o.collaboration={...j[e]});let r=t.scope||"global",n=P(e,o,r,t.rootDir);return {profile:o,filePath:n}}function B(e,t){let i=E(e),o=[];for(let r of i){let n=(r.expertise||[]).find(a=>a.symbol===t);n&&o.push({agentId:r.id,entry:n});}return o.sort((r,n)=>m(n.entry.confidence,n.entry.lastTouch)-m(r.entry.confidence,r.entry.lastTouch))}function J(e,t,i){let o=_(e,t);if(!o)return false;let r=new Date().toISOString(),n=o.expertise||[];for(let c of i.symbols_touched){let p=n.find(g=>g.symbol===c);p?(p.sessions++,p.lastTouch=r,i.confidence!=null&&(p.confidence=(1-b)*p.confidence+b*i.confidence)):n.push({symbol:c,confidence:i.confidence??.5,sessions:1,lastTouch:r});}o.expertise=n;let a=M(e);if(a){let c=o.contexts[a]||{focus:[],sessionsInProject:0};c.lastActive=r,c.sessionsInProject=(c.sessionsInProject||0)+1,o.contexts[a]=c;}let f=u.join(e,x,`${t}${h}`),s=l.existsSync(f)?"project":"global";return P(t,o,s,e),true}function z(e,t,i){let o=_(e,t);if(!o)return false;let n={correct:1,partial:.5,incorrect:0}[i.verdict];for(let s of i.symbols_touched){let c=(o.expertise||[]).find(p=>p.symbol===s);c&&(c.confidence=(1-b)*c.confidence+b*n);}let a=u.join(e,x,`${t}${h}`),f=l.existsSync(a)?"project":"global";return P(t,o,f,e),true}function X(e,t,i){return t?{personality:t.personality||null,topExpertise:(t.expertise||[]).sort((o,r)=>m(r.confidence,r.lastTouch)-m(o.confidence,o.lastTouch)).slice(0,10),projectContext:t.contexts?.[i]||null,transferablePatterns:(t.transferable||[]).filter(o=>o.successRate>=.7).map(o=>({id:o.id,description:o.description,successRate:o.successRate}))}:{personality:null,topExpertise:[],projectContext:null,transferablePatterns:[]}}function K(e,t,i,o,r){let n=[];if(e.personality){let s=e.personality;n.push(`## Agent Identity: ${e.id}`),n.push(`**Style:** ${s.style} | **Risk:** ${s.risk} | **Verbosity:** ${s.verbosity}`),n.push("");}let a=(e.expertise||[]).filter(s=>t.length===0||t.includes(s.symbol)).sort((s,c)=>m(c.confidence,c.lastTouch)-m(s.confidence,s.lastTouch)).slice(0,8);if(a.length>0){n.push("## Your Expertise on Relevant Symbols");for(let s of a){let p=1-m(s.confidence,s.lastTouch)/s.confidence,g=s.confidence>0&&p>F?" (aging)":"";n.push(`- \`${s.symbol}\`: confidence ${s.confidence.toFixed(2)} (${s.sessions} sessions)${g}`);}n.push("");}let f=(e.transferable||[]).filter(s=>s.successRate>=.7);if(f.length>0){n.push("## Transferable Patterns");for(let s of f){let c=s.appliedIn?.length||0;n.push(`- ${s.id}: ${(s.successRate*100).toFixed(0)}% success (learned in ${s.learnedIn}${c>0?`, applied in ${c} projects`:""})`);}n.push("");}if(i&&i.length>0){n.push("## Relevant Notebook Entries");for(let s of i.slice(0,5)){n.push(`### ${s.context}`),n.push(`Concepts: ${s.concepts.join(", ")}`),n.push("```");let c=s.snippet.length>300?s.snippet.slice(0,300)+"...":s.snippet;n.push(c),n.push("```"),n.push("");}}if(r){if(n.push(""),n.push("## Your Recent Work on This Project"),r.lastSession){let s=Date.now()-new Date(r.lastSession.date).getTime(),c=Math.floor(s/(3600*1e3)),p=c<24?`${c}h ago`:`${Math.floor(c/24)}d ago`;n.push(`Last session (${p}): ${r.lastSession.summary}`);}if(r.sessionsOnProject&&n.push(`Sessions on this project: ${r.sessionsOnProject}`),r.pendingWork?.length){n.push("**Pending from last session:**");for(let s of r.pendingWork.slice(0,5))n.push(`- ${s}`);}if(r.recentPatterns?.length){n.push("**Project patterns you've learned:**");for(let s of r.recentPatterns.slice(0,5))n.push(`- ${s}`);}n.push("");}if(e.attention){let s=e.attention,c=[];s.symbols?.length&&c.push(`Symbols: ${s.symbols.join(", ")}`),s.paths?.length&&c.push(`Paths: ${s.paths.join(", ")}`),s.concepts?.length&&c.push(`Concepts: ${s.concepts.join(", ")}`),s.signals?.length&&c.push(`Signals: ${s.signals.map(p=>p.type).join(", ")}`),c.length>0&&(n.push(""),n.push("### Attention"),n.push(`Threshold: ${s.threshold??.6}`),n.push(c.join(" | ")));}if(e.collaboration){let s=e.collaboration;if(n.push(""),n.push("### Collaboration"),n.push(`Default stance: ${s.stance||"supportive"}`),s.with)for(let[c,p]of Object.entries(s.with)){let g=[`${c}: ${p.stance||"peer"}`];p.can_contradict&&g.push("can contradict"),p.review_output&&g.push("reviews output"),n.push(`- ${g.join(", ")}`);}if(s.debate){let c=s.debate,p=[];c.will_challenge&&p.push("challenges"),c.evidence_required&&p.push("evidence-based"),c.escalate_to_human&&p.push("escalates to human"),p.length&&n.push(`Debate: ${p.join(", ")}`);}}if(e.nomination){let s=e.nomination;if(n.push(""),n.push("### Nomination"),s.speak_when?.urgency?.length&&n.push(`Always speaks on: ${s.speak_when.urgency.join(", ")}`),s.contribution_style){let c=[];s.contribution_style.brief_first&&c.push("brief first"),s.contribution_style.cite_sources&&c.push("cites sources"),s.contribution_style.offer_action&&c.push("offers action"),c.length&&n.push(`Style: ${c.join(", ")}`);}}if(o){if(o.recentDecisions?.length){n.push(""),n.push("## Recent Team Decisions");for(let s of o.recentDecisions.slice(0,5))n.push(`- **${s.title}**: ${s.decision.slice(0,150)}${s.decision.length>150?"...":""}`);}if(o.journalInsights?.length){n.push(""),n.push("## Transferable Insights");for(let s of o.journalInsights.slice(0,5))n.push(`- [${s.trigger}] ${s.insight.slice(0,150)}${s.insight.length>150?"...":""}`);}if(o.pendingNominations?.length){n.push(""),n.push("## Pending Nominations");for(let s of o.pendingNominations.slice(0,10))n.push(`- [${s.urgency}] ${s.brief}`);}}return n.join(`
|
|
3
|
+
`)}async function V(e,t,i=false){let{loadLoreEntries:o}=await import('./lore-loader-XY5MZRR2.js'),r=await o(e,{limit:500}),n=0,a=new Set,f=_(e,t)||D(t,{rootDir:e}).profile,s=f.expertise||[];for(let c of r)if(!(!c.symbols_touched||c.symbols_touched.length===0)){n++;for(let p of c.symbols_touched){a.add(p);let g=s.find(L=>L.symbol===p);g?(g.sessions++,g.lastTouch=c.timestamp,c.confidence!=null&&(g.confidence=(1-b)*g.confidence+b*c.confidence)):s.push({symbol:p,confidence:c.confidence??.5,sessions:1,lastTouch:c.timestamp});}}if(f.expertise=s,!i){let c=u.join(e,x,`${t}${h}`),p=l.existsSync(c)?"project":"global";P(t,f,p,e);}return {entriesProcessed:n,symbolsUpdated:a.size}}function Q(e,t,i){if(!e.permissions?.paths)return {allowed:true};let{read:o,write:r,deny:n}=e.permissions.paths;if(n&&n.length>0){for(let f of n)if(A(f,t))return {allowed:false,reason:`Path denied by pattern: ${f}`}}let a=i==="read"?o:r;if(a&&a.length>0){for(let f of a)if(A(f,t))return {allowed:true};return {allowed:false,reason:`No ${i} pattern matches: ${t}`}}return {allowed:true}}function Z(e,t){if(!e.permissions?.tools)return {allowed:true};let{allow:i,deny:o}=e.permissions.tools;if(o&&o.length>0){for(let r of o)if(A(r,t))return {allowed:false,reason:`Tool denied by pattern: ${r}`}}if(i&&i.length>0){for(let r of i)if(A(r,t))return {allowed:true};return {allowed:false,reason:`Tool not in allow list: ${t}`}}return {allowed:true}}function R(e){let t=JSON.stringify({id:e.id,role:e.role,permissions:e.permissions||null});return k.createHash("sha256").update(t).digest("hex")}function ee(e){return e.integrityHash?R(e)===e.integrityHash?{valid:true}:{valid:false,reason:"Integrity hash mismatch \u2014 profile may have been tampered with"}:{valid:true,reason:"No integrity hash stored (pre-4.0 profile)"}}function A(e,t){let i=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}function C(e,t){let i={...e};if(t.role&&(i.role=t.role),t.description&&(i.description=t.description),t.version&&(i.version=t.version),t.personality&&(i.personality={...e.personality,...t.personality}),t.expertise){let o=new Map(e.expertise.map(r=>[r.symbol,r]));for(let r of t.expertise)o.set(r.symbol,r);i.expertise=Array.from(o.values());}if(t.transferable){let o=new Map(e.transferable.map(r=>[r.id,r]));for(let r of t.transferable)o.set(r.id,r);i.transferable=Array.from(o.values());}if(t.contexts){i.contexts={...e.contexts};for(let[o,r]of Object.entries(t.contexts))i.contexts[o]={...i.contexts[o],...r};}return i}function M(e){try{let t=u.join(e,".paradigm","config.yaml");if(l.existsSync(t)){let i=l.readFileSync(t,"utf-8"),o=d.load(i);if(o?.project&&typeof o.project=="string")return o.project}}catch{}return u.basename(e)}export{m as a,I as b,U as c,H as d,G as e,_ as f,O as g,Y as h,E as i,P as j,D as k,B as l,J as m,z as n,X as o,K as p,V as q,Q as r,Z as s,R as t,ee as u};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import*as i from'fs';import*as f from'path';var u=".paradigm/events/session-log.jsonl",y=200;function h(e,t){try{let n=f.join(e,u),o=f.dirname(n);if(i.existsSync(o)||i.mkdirSync(o,{recursive:!0}),i.existsSync(n)&&i.readFileSync(n,"utf8").trim().split(`
|
|
3
3
|
`).filter(r=>r.trim()).length>=y)return;let g=JSON.stringify(t)+`
|
|
4
|
-
`;i.appendFileSync(n,g,"utf8"),t.type==="user-verdict"&&t.agent&&t.symbols?.length&&import('./agent-loader-
|
|
4
|
+
`;i.appendFileSync(n,g,"utf8"),t.type==="user-verdict"&&t.agent&&t.symbols?.length&&import('./agent-loader-EBERCNMO.js').then(({loadAgentProfile:c,saveAgentProfile:s})=>{try{let r=c(e,t.agent);if(r?.expertise){let d=t.verdict==="accepted"?.03:t.verdict==="dismissed"?-.02:t.verdict==="revised"?-.01:0;if(d!==0){for(let p of t.symbols){let a=r.expertise.find(S=>S.symbol===p);a&&(a.confidence=Math.max(0,Math.min(1,a.confidence+d)),a.sessions=(a.sessions||0)+1,a.lastTouch=new Date().toISOString());}s(t.agent,r,"global");}}}catch{}}).catch(()=>{});}catch{}}function l(e){try{let t=f.join(e,u);return i.existsSync(t)?i.readFileSync(t,"utf8").trim().split(`
|
|
5
5
|
`).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null):[]}catch{return []}}function v(e){try{let t=f.join(e,u);i.existsSync(t)&&i.writeFileSync(t,"","utf8");}catch{}}function b(e){let t=l(e),n=new Set;for(let o of t)o.agent&&n.add(o.agent);return Array.from(n)}function m(e,t){return l(e).filter(n=>n.agent===t)}function E(e,t){let n=m(e,t),o=n.filter(s=>s.type==="agent-contribution"),g=n.filter(s=>s.type==="user-verdict"),c=[];for(let s of o)c.push({contribution:s});for(let s of g){let r=c.find(d=>!d.verdict&&d.contribution);r?r.verdict=s:c.push({verdict:s});}return c}export{h as a,l as b,v as c,b as d,m as e,E as f};
|
|
@@ -1,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,b as b$1,c as c$1,k}from'./chunk-
|
|
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,b as b$1,c as c$1,k}from'./chunk-AYYS2AMB.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as v from'fs';import*as $ from'path';import*as K from'crypto';import {execSync}from'child_process';import*as O from'js-yaml';import {z as z$1}from'zod';import {glob}from'glob';import*as he from'os';import ms from'sql.js';var Ft={};c(Ft,{contentSearch:()=>gs,detectFileRename:()=>Ot,generateFingerprint:()=>Ct,levenshteinDistance:()=>jt,levenshteinSimilarity:()=>Fe,searchSiblingFiles:()=>Lt,slidingWindowSearch:()=>we});function Ct(t){let e=t.split(`
|
|
3
3
|
`).filter(n=>n.trim()!=="");return {firstLine:ye(e[0]||""),lastLine:ye(e[e.length-1]||""),lineCount:e.length,structuralHash:At(e)}}function At(t){let e=t.map(n=>n.trim()).filter(n=>kt.test(n)).map(n=>{let s=n.match(kt);return s?s[1].trim():""}).join("|");return K.createHash("sha256").update(e).digest("hex").slice(0,16)}function ye(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function jt(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 n=t.length,s=e.length;if(n>5e3||s>5e3)return Math.abs(n-s);let o=new Array(n+1),r=new Array(n+1);for(let i=0;i<=n;i++)o[i]=i;for(let i=1;i<=s;i++){r[0]=i;for(let a=1;a<=n;a++){let l=t[a-1]===e[i-1]?0:1;r[a]=Math.min(o[a]+1,r[a-1]+1,o[a-1]+l);}[o,r]=[r,o];}return o[n]}function Fe(t,e){if(t.length===0&&e.length===0)return 1;let n=Math.max(t.length,e.length);return 1-jt(t,e)/n}function we(t,e,n,s=3){let{lineCount:o}=e,r=Math.max(1,Math.floor(o*.8)),i=Math.ceil(o*1.2),a=[],l=Le(n);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),g=fs(p,e,l);if(g>=.5){let m=p.join(`
|
|
4
4
|
`);a.push({windowStart:u+1,windowEnd:u+d,similarity:Fe(Le(m),l),score:g});}}let c=new Map;for(let d of a){let u=c.get(d.windowStart);(!u||d.score>u.score)&&c.set(d.windowStart,d);}return Array.from(c.values()).sort((d,u)=>u.score-d.score).slice(0,s)}function fs(t,e,n){let s=t.filter(p=>p.trim()!=="");if(s.length===0)return 0;let o=0,r=ye(s[0]),i=ye(s[s.length-1]),a=0;r===e.firstLine&&(a+=.5),i===e.lastLine&&(a+=.5),o+=a*ls,At(s)===e.structuralHash&&(o+=ds);let c=s.join(`
|
|
5
5
|
`),d=Fe(Le(c),n);d>=.8&&(o+=(d-.8)/.2*us);let u=s.length/e.lineCount;if(u>=.8&&u<=1.2){let p=1-Math.abs(1-u)/.2;o+=p*ps;}return o}function Le(t){return t.split(`
|
|
@@ -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-
|
|
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-LMSZ2CAS.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-
|
|
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-S3CXHD7P.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};
|