@a-company/paradigm 7.0.0 → 7.1.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/{accept-orchestration-YO2V2WYA.js → accept-orchestration-WMGFGYDK.js} +1 -1
- package/dist/{agent-loader-VGBPL3TH.js → agent-loader-Z753DQWH.js} +1 -1
- package/dist/{ambient-OX7YJ4PJ.js → ambient-HAXPDIWK.js} +1 -1
- package/dist/ambient-OW5M5LVN.js +2 -0
- package/dist/ambient-QB7V4TBR.js +6 -0
- package/dist/calibrate-PHVP7RPH.js +4 -0
- package/dist/{captain-YUP3KVCA.js → captain-3COP6YTD.js} +1 -1
- package/dist/chunk-4CGPLLWQ.js +30 -0
- package/dist/{chunk-3MZ4J2LF.js → chunk-CHSU6LTR.js} +1 -1
- package/dist/chunk-ECO3LHCE.js +2 -0
- package/dist/chunk-EG22HDXI.js +33 -0
- package/dist/{chunk-GD4F2HC6.js → chunk-H55W26AR.js} +1 -1
- package/dist/{chunk-ROU3F2HZ.js → chunk-HSY75GRR.js} +3 -3
- package/dist/chunk-KAUGQMXU.js +4 -0
- package/dist/{chunk-QBIQ2FYB.js → chunk-KP5VOYAH.js} +1 -1
- package/dist/{chunk-K54L6CFR.js → chunk-OIYJUU6T.js} +4 -4
- package/dist/{chunk-47YPID6H.js → chunk-RDWWSQGH.js} +21 -21
- package/dist/chunk-RVXQNS6K.js +30 -0
- package/dist/{chunk-WROJSWAO.js → chunk-VPNJL4LS.js} +1 -1
- package/dist/{chunk-JCGCPAHF.js → chunk-W4BW7GXA.js} +1 -1
- package/dist/chunk-XPPFILCM.js +2 -0
- package/dist/{chunk-V6MIKLMY.js → chunk-YCDOA5IQ.js} +1 -1
- package/dist/chunk-YQK3XU63.js +504 -0
- package/dist/{compliance-MLG4W6S4.js → compliance-4P3EE5OA.js} +1 -1
- package/dist/{diff-MC6AXLKX.js → diff-VBVIUNL5.js} +1 -1
- package/dist/{docs-3YFNNZRV.js → docs-NTP6UENF.js} +1 -1
- package/dist/index.js +5 -5
- package/dist/journal-loader-CNNA4EAU.js +2 -0
- package/dist/lore-loader-HAZ5FRLP.js +2 -0
- package/dist/mcp.js +1 -1
- package/dist/nomination-engine-ORHH4L2W.js +2 -0
- package/dist/{nomination-engine-AQHU2KBU.js → nomination-engine-YRHZZZUN.js} +1 -1
- package/dist/notebook-loader-TZVIMNDJ.js +2 -0
- package/dist/{orchestrate-GMYEBA5T.js → orchestrate-MLUGQOEJ.js} +1 -1
- package/dist/orchestration-O2OVPTIZ.js +2 -0
- package/dist/{platform-server-WIBVYHIV.js → platform-server-Y6TLEXR2.js} +1 -1
- package/dist/{reindex-XTRF23F7.js → reindex-ZLDQBFUR.js} +1 -1
- package/dist/{serve-SMGWGJLM.js → serve-XZ6GBUS3.js} +1 -1
- package/dist/{session-work-log-QXPAXY5K.js → session-work-log-FF7CKMWP.js} +1 -1
- package/dist/{shift-JBCEDCGA.js → shift-PM4GI736.js} +1 -1
- package/dist/{symphony-G6IENE4K.js → symphony-CFAYJGLF.js} +1 -1
- package/dist/{symphony-7INZR43F.js → symphony-L56O5ZG3.js} +3 -3
- package/dist/{symphony-relay-2RHG25Z4.js → symphony-relay-Y2UR3YNR.js} +1 -1
- package/dist/{task-loader-IGQQ6ZFL.js → task-loader-H7HQAYGL.js} +1 -1
- package/dist/task-loader-YZME4RKE.js +2 -0
- package/dist/{task-settlement-NW4XMJGJ.js → task-settlement-HINBVZBE.js} +2 -2
- package/dist/task-settlement-XC6E6JNT.js +3 -0
- package/dist/{team-J2YXPEGX.js → team-25LK6CWM.js} +1 -1
- package/dist/tools-GAU5WOEI.js +2 -0
- package/dist/university-ui/assets/{index-B8hm_MdR.js → index-AbTjHBCf.js} +2 -2
- package/dist/university-ui/assets/{index-B8hm_MdR.js.map → index-AbTjHBCf.js.map} +1 -1
- package/dist/university-ui/index.html +1 -1
- package/dist/work-log-loader-CRVTOMVB.js +2 -0
- package/package.json +1 -1
- package/dist/ambient-7HBJHJL2.js +0 -2
- package/dist/ambient-SST5CLEC.js +0 -35
- package/dist/chunk-6AKNXD22.js +0 -32
- package/dist/chunk-FRQRREJ6.js +0 -29
- package/dist/chunk-QEQCPVF5.js +0 -4
- package/dist/chunk-QGZRM6ZB.js +0 -2
- package/dist/chunk-S4J337EQ.js +0 -504
- package/dist/journal-loader-GLH7XFTK.js +0 -2
- package/dist/lore-loader-D2ISOASW.js +0 -2
- package/dist/notebook-loader-6DYFMNJ2.js +0 -2
- package/dist/orchestration-G5MAY6IA.js +0 -2
- package/dist/tools-HNJ7D5IO.js +0 -2
- /package/dist/{chunk-CVPKQ3JH.js → chunk-HE2NA5QF.js} +0 -0
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
9
9
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
10
10
|
<link href="https://fonts.googleapis.com/css2?family=Crimson+Pro:ital,wght@0,400;0,500;0,600;0,700;1,400&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
|
|
11
|
-
<script type="module" crossorigin src="/assets/index-
|
|
11
|
+
<script type="module" crossorigin src="/assets/index-AbTjHBCf.js"></script>
|
|
12
12
|
<link rel="stylesheet" crossorigin href="/assets/index-C9zUgT5x.css">
|
|
13
13
|
</head>
|
|
14
14
|
<body>
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import'./chunk-5TAVYPOV.js';import*as s from'fs';import*as m from'path';import*as u from'js-yaml';var d=".paradigm/work-log";function p(a){let n=new Date().toISOString().slice(0,10),c=a.toLowerCase().replace(/[^a-z0-9-]/g,"-").slice(0,20),i=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `WL-${c}-${n}-${i}`}function k(a,o){return m.join(a,d,o)}function h(a,o){let n=new Date,c=n.toISOString().slice(0,10),i=p(o.agent),e={id:i,timestamp:n.toISOString(),...o},t=k(a,c);s.mkdirSync(t,{recursive:true});let r=m.join(t,`${i}.yaml`);return s.writeFileSync(r,u.dump(e,{lineWidth:120,noRefs:true}),"utf8"),e}function W(a,o){let n=m.join(a,d);if(!s.existsSync(n))return [];let c=[],i=s.readdirSync(n,{withFileTypes:true}).filter(t=>t.isDirectory()&&/^\d{4}-\d{2}-\d{2}$/.test(t.name)).map(t=>t.name).sort().reverse();for(let t of i){if(o?.dateFrom&&t<o.dateFrom||o?.dateTo&&t>o.dateTo)continue;let r=m.join(n,t),l=s.readdirSync(r).filter(g=>g.endsWith(".yaml"));for(let g of l)try{let y=s.readFileSync(m.join(r,g),"utf8"),f=u.load(y);f&&f.id&&c.push(f);}catch{}}let e=c;return o?.agent&&(e=e.filter(t=>t.agent===o.agent)),o?.outcome&&(e=e.filter(t=>t.outcome===o.outcome)),o?.task_ref&&(e=e.filter(t=>t.task_ref===o.task_ref)),o?.symbol&&(e=e.filter(t=>t.symbols_touched?.includes(o.symbol))),e.sort((t,r)=>r.timestamp.localeCompare(t.timestamp)),o?.limit&&(e=e.slice(0,o.limit)),e}function S(a,o){let n=m.join(a,d);if(!s.existsSync(n))return null;let c=o.match(/WL-[^-]+-(\d{4}-\d{2}-\d{2})-/);if(c){let e=m.join(n,c[1],`${o}.yaml`);if(s.existsSync(e)){let t=s.readFileSync(e,"utf8");return u.load(t)}}let i=s.readdirSync(n,{withFileTypes:true}).filter(e=>e.isDirectory());for(let e of i){let t=m.join(n,e.name,`${o}.yaml`);if(s.existsSync(t)){let r=s.readFileSync(t,"utf8");return u.load(r)}}return null}function L(a,o=7){let n=new Date;n.setDate(n.getDate()-o);let c=n.toISOString().slice(0,10),i=W(a,{dateFrom:c}),e={pass:0,fail:0,partial:0,blocked:0},t={};for(let r of i)e[r.outcome]=(e[r.outcome]||0)+1,t[r.agent]=(t[r.agent]||0)+1;return {total:i.length,byOutcome:e,byAgent:t,recentEntries:i.slice(0,10).map(r=>({id:r.id,agent:r.agent,summary:r.summary,outcome:r.outcome,timestamp:r.timestamp}))}}export{L as getWorkLogSummary,W as loadWorkLogEntries,S as loadWorkLogEntry,h as recordWorkLog};
|
package/package.json
CHANGED
package/dist/ambient-7HBJHJL2.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
export{a as getAmbientToolsList,b as handleAmbientTool,c as runPostflightLearning}from'./chunk-ROU3F2HZ.js';import'./chunk-FRQRREJ6.js';import'./chunk-3KVVC4WV.js';import'./chunk-QEQCPVF5.js';import'./chunk-Q527BPUF.js';import'./chunk-KAFQA7HV.js';import'./chunk-33ERV2MW.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-QGZRM6ZB.js';import'./chunk-5TAVYPOV.js';
|
package/dist/ambient-SST5CLEC.js
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {f,p as p$1,i,c as c$1,j}from'./chunk-GD4F2HC6.js';import {e,g,b as b$1,f as f$1,h}from'./chunk-V6MIKLMY.js';import {b as b$2}from'./chunk-7SWEOPWF.js';import'./chunk-MBPLJKE5.js';import {c,b,d,a}from'./chunk-5TAVYPOV.js';import*as p from'fs';import*as w from'path';import*as P from'js-yaml';import*as ot from'os';var Tt={};c(Tt,{getJournalStats:()=>ue,loadAllJournalEntries:()=>me,loadJournalEntries:()=>F,loadJournalEntry:()=>de,recordJournalEntry:()=>H});function Q(e){let t=process.env.HOME||process.env.USERPROFILE||"";return w.join(t,".paradigm","agents",e,"journal")}function le(){let e=new Date,t=e.toISOString().slice(0,10),n=e.toISOString().slice(11,19).replace(/:/g,""),o=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `LJ-${t}-${n}-${o}`}function H(e,t){let n=new Date,o=le(),r={id:o,agent:e,timestamp:n.toISOString(),...t},i=Q(e);p.mkdirSync(i,{recursive:true});let s=w.join(i,`${o}.yaml`);return p.writeFileSync(s,P.dump(r,{lineWidth:120,noRefs:true}),"utf8"),r}function F(e,t){let n=Q(e);if(!p.existsSync(n))return [];let o=[],r=p.readdirSync(n).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=p.readFileSync(w.join(n,s),"utf8"),d=P.load(a);d&&d.id&&o.push(d);}catch{}let i=o;return t?.trigger&&(i=i.filter(s=>s.trigger===t.trigger)),t?.project&&(i=i.filter(s=>s.project===t.project)),t?.transferable!==void 0&&(i=i.filter(s=>s.transferable===t.transferable)),t?.tag&&(i=i.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(i=i.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(i=i.filter(s=>s.timestamp<=t.dateTo)),i.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}function de(e,t){let n=Q(e),o=w.join(n,`${t}.yaml`);if(!p.existsSync(o))return null;let r=p.readFileSync(o,"utf8");return P.load(r)}function me(e){let t=process.env.HOME||process.env.USERPROFILE||"",n=w.join(t,".paradigm","agents");if(!p.existsSync(n))return [];let o=[],r=p.readdirSync(n,{withFileTypes:true}).filter(i=>i.isDirectory());for(let i of r){if(e?.agent&&i.name!==e.agent)continue;let s=F(i.name,e);o.push(...s);}return o.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),e?.limit?o.slice(0,e.limit):o}function ue(e){let t=F(e),n={},o={},r=0;for(let i of t)n[i.trigger]=(n[i.trigger]||0)+1,o[i.project]=(o[i.project]||0)+1,i.transferable&&r++;return {total:t.length,byTrigger:n,byProject:o,transferableCount:r,recentInsights:t.slice(0,5).map(i=>({id:i.id,trigger:i.trigger,insight:i.insight.slice(0,200),timestamp:i.timestamp}))}}var Z=b(()=>{});var It={};c(It,{addNotebookEntry:()=>Ct,classifyNotebookScope:()=>Ft,incrementApplied:()=>ye,loadNotebookEntries:()=>Ot,normalizeConcept:()=>W,promoteFromLore:()=>ge,searchNotebooks:()=>pe});function W(e){if(!e)return "";let t=e.trim();return t=t.replace(/^symbol:/i,""),t=t.replace(/^[#$^!~@&%?]/,""),t.trim().toLowerCase()}function Ot(e,t,n){let o=new Map,r=w.join(tt,e);Pt(r,o);let i=w.join(t,et,e);Pt(i,o);let s=Array.from(o.values());if(n?.concepts&&n.concepts.length>0){let a=new Set(n.concepts.map(W));s=s.filter(d=>d.concepts.some(l=>a.has(W(l))));}if(n?.tags&&n.tags.length>0){let a=new Set(n.tags.map(d=>d.toLowerCase()));s=s.filter(d=>d.tags.some(l=>a.has(l.toLowerCase())));}return s.sort((a,d)=>d.appliedCount-a.appliedCount)}function Pt(e,t){if(p.existsSync(e))try{let n=p.readdirSync(e).filter(o=>o.startsWith(fe)&&o.endsWith(nt));for(let o of n)try{let r=p.readFileSync(w.join(e,o),"utf-8"),i=P.load(r);i?.id&&t.set(i.id,i);}catch{}}catch{}}function pe(e,t,n){let o=Ot(e,n),r=t.toLowerCase();return o.filter(i=>i.context.toLowerCase().includes(r)||i.snippet.toLowerCase().includes(r)||i.concepts.some(s=>s.toLowerCase().includes(r))||i.tags.some(s=>s.toLowerCase().includes(r)))}function Ft(e){let t=[e.context,e.snippet,...e.concepts,...e.tags].join(" ").toLowerCase();return ["paradigm","mcp_","mcp tool",".paradigm/","lore entry","lore record","aspect","^gate","portal.yaml",".purpose","sentinel","symphony","ambient nomination","paradigm_"," pan ","agent notebook","concept anchor","symbol system","work log","knowledge stream","nevr.land","neverland"].some(o=>t.includes(o))?"platform-specific":/[#$^!~][a-z][a-z0-9-]{2,}/.test(t)||/\/[a-z0-9_-]{2,}\/[a-z0-9_-]/.test(t)?"project-specific":"generalizable"}function Ct(e,t,n,o){let r=new Date().toISOString(),i=(t.concepts[0]||t.context.split(" ").slice(0,4).join(" ")||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),a=`nb-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}-${i}`,d=t.scope??Ft({context:t.context,snippet:t.snippet,concepts:t.concepts,tags:t.tags}),l=Array.from(new Set((t.concepts||[]).map(W).filter(Boolean))),m={...t,concepts:l,id:a,scope:d,publishable:t.publishable??true,appliedCount:0,created:r,updated:r},c=n==="global"?w.join(tt,e):w.join(o||process.cwd(),et,e);p.existsSync(c)||p.mkdirSync(c,{recursive:true});let u=`${a}${nt}`,g=w.join(c,u),y=P.dump(m,{lineWidth:120,noRefs:true,sortKeys:false});return p.writeFileSync(g,y,"utf-8"),{entry:m,filePath:g}}async function ge(e,t,n,o="global"){let{loadLoreEntry:r}=await import('./lore-loader-D2ISOASW.js'),i=await r(n,t);if(!i)return null;let s=[];if(i.symbols_touched)for(let l of i.symbols_touched){let m=l.replace(/^[#$^!~]/,"").toLowerCase();s.push(m);}let a=i.summary||"";i.body&&(a+=`
|
|
3
|
-
|
|
4
|
-
`+i.body);let d={source:"lore",loreEntryId:t,originProject:w.basename(n),createdBy:e};return Ct(e,{context:i.title||`Promoted from ${t}`,snippet:a,provenance:d,confidence:i.confidence??.7,concepts:s,tags:i.tags||[]},o,n)}function ye(e,t,n){let o=w.join(n,et,e),r=w.join(tt,e);for(let i of [o,r]){let s=w.join(i,`${t}${nt}`);if(p.existsSync(s))try{let a=p.readFileSync(s,"utf-8"),d=P.load(a);if(d)return d.appliedCount=(d.appliedCount||0)+1,d.updated=new Date().toISOString(),p.writeFileSync(s,P.dump(d,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var tt,et,fe,nt,Jt=b(()=>{tt=w.join(ot.homedir(),".paradigm","notebooks"),et=".paradigm/notebooks",fe="nb-",nt=".yaml";});var jt=".paradigm/events",oe="stream.jsonl",L=1e3,R=[];function Et(e){return w.join(e,jt,oe)}function ie(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${e}-${t}`}function U(e,t){let n={id:ie(),timestamp:new Date().toISOString(),...t};R.push(n),R.length>L&&(R=R.slice(-L));try{let o=w.join(e,jt);p.mkdirSync(o,{recursive:!0});let r=Et(e);p.appendFileSync(r,JSON.stringify(n)+`
|
|
5
|
-
`,"utf8"),re(r);}catch{}return n}function re(e){try{if(p.statSync(e).size>512*1024){let o=p.readFileSync(e,"utf8").trim().split(`
|
|
6
|
-
`);if(o.length>L){let r=o.slice(-L);p.writeFileSync(e,r.join(`
|
|
7
|
-
`)+`
|
|
8
|
-
`,"utf8");}}}catch{}}function kt(e,t){let n=se(e);return t?.type&&(n=n.filter(o=>o.type===t.type)),t?.source&&(n=n.filter(o=>o.source===t.source)),t?.symbol&&(n=n.filter(o=>o.symbols?.includes(t.symbol))),t?.agent&&(n=n.filter(o=>o.agent===t.agent)),t?.since&&(n=n.filter(o=>o.timestamp>=t.since)),n.sort((o,r)=>r.timestamp.localeCompare(o.timestamp)),t?.limit&&(n=n.slice(0,t.limit)),n}function se(e){let t=Et(e);if(!p.existsSync(t))return [...R];try{return p.readFileSync(t,"utf8").trim().split(`
|
|
9
|
-
`).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return [...R]}}function xt(e,t,n){let o=0,r=0,i=0,s=0;if(n.symbols?.length&&e.symbols?.length)for(let m of n.symbols)for(let c of e.symbols)vt(m,c)&&(o=Math.max(o,1));if(n.paths?.length&&e.path){for(let m of n.paths)if(vt(m,e.path)){r=1;break}}if(n.concepts?.length){let m=[e.context||"",...e.keywords||[],e.type||""].join(" ").toLowerCase(),c=0;for(let u of n.concepts)u&&m.includes(u.toLowerCase())&&c++;n.concepts.length>0&&(i=c/n.concepts.length);}if(n.signals?.length){for(let m of n.signals)if(m.type===e.type){s=1;break}}let a=[o,r,i,s].sort((m,c)=>c-m),d=a[0]*.5+a[1]*.2+a[2]*.15+a[3]*.15,l=n.threshold??.6;return {agentId:t,score:d,breakdown:{symbolMatch:o,pathMatch:r,conceptMatch:i,signalMatch:s},shouldNominate:d>=l,quietReason:d<l?"below-threshold":void 0}}function vt(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 ae=".paradigm/data-policy.yaml";function $t(e){let t=w.join(e,ae);if(!p.existsSync(t))return {...b$2};try{let n=p.readFileSync(t,"utf8"),o=P.load(n);return ce(b$2,o)}catch{return {...b$2}}}function ce(e,t){let n={...e};if(t.version&&(n.version=t.version),t.default_ring&&(n.default_ring=t.default_ring),t.observation&&(n.observation={allow:t.observation.allow||e.observation?.allow,deny:[...e.observation?.deny||[],...t.observation.deny||[]].filter((o,r,i)=>i.indexOf(o)===r)}),t.streams){n.streams={...e.streams};for(let o of ["work_log","learning_journal","team_decisions"])t.streams[o]&&(n.streams[o]={...e.streams?.[o],...t.streams[o],deny_content:[...e.streams?.[o]?.deny_content||[],...t.streams[o]?.deny_content||[]].filter((r,i,s)=>s.indexOf(r)===i)});}return t.upstream&&(n.upstream={...e.upstream,...t.upstream}),t.network&&(n.network={...e.network,...t.network}),t.agent_overrides&&(n.agent_overrides={...e.agent_overrides,...t.agent_overrides}),t.deployment&&(n.deployment={...e.deployment,...t.deployment}),n}function Rt(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(r=>Y(r,t))||e.observation?.deny?.some(o=>Y(o,t))?false:e.observation?.allow?.length?e.observation.allow.some(o=>Y(o,t)):true}function Y(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 $=".paradigm/events",he="nominations.jsonl",be="debates.jsonl",Se=500,we=200,_e=7,ve=14,je=100;function Ee(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function ke(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${e}-${t}`}function xe(e,t){let n=i(e),o=$t(e),r=[];for(let l of n){if(!l.attention||!c$1(l.id,e)||t.path&&!Rt(o,t.path,l.id))continue;let m=xt(t,l.id,l.attention);m.shouldNominate&&r.push({profile:l,score:m});}if(r.length===0)return {nominations:[],debates:[]};let i$1=k(e,{since:new Date(Date.now()-3e4).toISOString()}),s=r.filter(({profile:l})=>!i$1.find(c=>c.agent===l.id&&c.brief===Mt(l,t,{...r.find(u=>u.profile.id===l.id).score})));if(s.length===0)return {nominations:[],debates:[]};let a=s.map(({profile:l,score:m})=>{let c=De(t,m),u=Ne(l,t);return {id:Ee(),agent:l.id,relevance:m.score,urgency:c,type:u,brief:Mt(l,t,m),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});Re(e,a);let d=$e(e,a);return d.length>0&&Te(e,d),{nominations:a,debates:d}}function De(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 Ne(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 Mt(e,t,n){let o=e.role||e.id;switch(t.type){case "gate-checked":return `${o}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${o}: ${t.path||"File"} modified \u2014 review for ${e.id==="security"?"security implications":e.id==="tester"?"test coverage":e.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${o}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${o}: New route ${t.symbols?.join(", ")||""} \u2014 ${e.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${o}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${e.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${o}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${o}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${o}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let r=n.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:n.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${o}: ${r}`}}}function $e(e,t){if(t.length<2)return [];let n=[],o=new Map;for(let r of t)for(let i of r.triggered_by){let s=o.get(i)||[];s.push(r),o.set(i,s);}for(let[r,i]of o){if(i.length<2||new Set(i.map(l=>l.agent)).size<2)continue;let a=new Set(i.map(l=>l.type)),d=a.size>1&&a.has("warning")&&a.has("suggestion");n.push({id:ke(),topic:`Multiple agents responded to event ${r}`,nominations:i.map(l=>l.id),type:d?"conflicting":"complementary",overlap_events:[r]});}return n}function it(e){return w.join(e,$,he)}function rt(e){return w.join(e,$,be)}function Re(e,t){try{let n=w.join(e,$);p.mkdirSync(n,{recursive:!0});let o=it(e),r=t.map(s=>JSON.stringify(s)).join(`
|
|
10
|
-
`)+`
|
|
11
|
-
`;p.appendFileSync(o,r,"utf8"),Lt(o,Se);let{nominationTtlDays:i}=z(e);Ut(o,i*24*60*60*1e3);}catch{}}function Te(e,t){try{let n=w.join(e,$);p.mkdirSync(n,{recursive:!0});let o=rt(e),r=t.map(s=>JSON.stringify(s)).join(`
|
|
12
|
-
`)+`
|
|
13
|
-
`;p.appendFileSync(o,r,"utf8"),Lt(o,we);let{debateTtlDays:i}=z(e);Ut(o,i*24*60*60*1e3);}catch{}}function Lt(e,t){try{let o=p.readFileSync(e,"utf8").trim().split(`
|
|
14
|
-
`).filter(r=>r.trim());if(o.length>t){let r=o.slice(-t);p.writeFileSync(e,r.join(`
|
|
15
|
-
`)+`
|
|
16
|
-
`,"utf8");}}catch{}}function z(e){let t={nominationTtlDays:_e,debateTtlDays:ve};try{let n=w.join(e,".paradigm","config.yaml");if(!p.existsSync(n))return t;let o=a("js-yaml"),r=p.readFileSync(n,"utf8"),s=o.load(r)?.ambient;return s?{nominationTtlDays:typeof s["nomination-ttl-days"]=="number"?s["nomination-ttl-days"]:t.nominationTtlDays,debateTtlDays:typeof s["debate-ttl-days"]=="number"?s["debate-ttl-days"]:t.debateTtlDays}:t}catch{return t}}function Ut(e,t){try{if(!p.existsSync(e))return;let o=p.readFileSync(e,"utf8").trim().split(`
|
|
17
|
-
`).filter(s=>s.trim());if(o.length<=je)return;let r=Date.now()-t,i=o.filter(s=>{try{let a=JSON.parse(s);return (a.timestamp?new Date(a.timestamp).getTime():Date.now())>=r}catch{return !0}});i.length<o.length&&p.writeFileSync(e,i.join(`
|
|
18
|
-
`)+`
|
|
19
|
-
`,"utf8");}catch{}}function k(e,t){let n=it(e);if(!p.existsSync(n))return [];try{let r=p.readFileSync(n,"utf8").trim().split(`
|
|
20
|
-
`).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null);return t?.agent&&(r=r.filter(i=>i.agent===t.agent)),t?.urgency&&(r=r.filter(i=>i.urgency===t.urgency)),t?.surfaced!==void 0&&(r=r.filter(i=>i.surfaced===t.surfaced)),t?.pending_only&&(r=r.filter(i=>!i.engaged)),t?.since&&(r=r.filter(i=>i.timestamp>=t.since)),r.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),t?.limit&&(r=r.slice(0,t.limit)),r}catch{return []}}function Bt(e){let t=rt(e);if(!p.existsSync(t))return [];try{return p.readFileSync(t,"utf8").trim().split(`
|
|
21
|
-
`).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return []}}function Ht(e,t,n,o){let r=it(e);if(!p.existsSync(r))return false;try{let s=p.readFileSync(r,"utf8").trim().split(`
|
|
22
|
-
`),a=!1,d=s.map(l=>{try{let m=JSON.parse(l);return m.id===t?(m.engaged=!0,m.response=n,o&&(m.reason=o),a=!0,JSON.stringify(m)):l}catch{return l}});if(a&&(p.writeFileSync(r,d.join(`
|
|
23
|
-
`)+`
|
|
24
|
-
`,"utf8"),n==="accepted"||n==="dismissed")){let l=JSON.parse(s.find(c=>{try{return JSON.parse(c).id===t}catch{return !1}}));i(e).find(c=>c.id===l.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&U(e,{type:"work-completed",source:"agent-action",agent:l.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return a}catch{return false}}function Wt(e,t,n,o){let r=rt(e);if(!p.existsSync(r))return false;try{let s=p.readFileSync(r,"utf8").trim().split(`
|
|
25
|
-
`),a=!1,d=s.map(l=>{try{let m=JSON.parse(l);if(m.id===t){m.resolution={chosen:n,reason:o,resolved_by:"human",resolved_at:new Date().toISOString()},a=!0;let c=m.nominations.filter(u=>u!==n);for(let u of c){let g=k(e).find(y=>y.id===u);g&&U(e,{type:"work-completed",source:"agent-action",agent:g.agent,context:`Debate ${t} resolved \u2014 nomination ${u} not chosen`,data:{debate_id:t,chosen:n,reason:o}});}return JSON.stringify(m)}return l}catch{return l}});return a&&p.writeFileSync(r,d.join(`
|
|
26
|
-
`)+`
|
|
27
|
-
`,"utf8"),a}catch{return false}}function zt(e){let t=w.join(e,$,".last-processed"),n="";try{p.existsSync(t)&&(n=p.readFileSync(t,"utf8").trim());}catch{}let o=w.join(e,$,"stream.jsonl");if(!p.existsSync(o))return {processed:0,nominations:[]};let r=[];try{r=p.readFileSync(o,"utf8").trim().split(`
|
|
28
|
-
`).filter(c=>c.trim()).map(c=>{try{return JSON.parse(c)}catch{return null}}).filter(c=>c!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(n){let m=r.findIndex(c=>c.id===n);m>=0&&(i=m+1);}let s=r.slice(i);if(s.length===0)return {processed:0,nominations:[]};let a=[],d=s.slice(0,50);for(let m of d){let{nominations:c}=xe(e,m);a.push(...c);}let l=d[d.length-1];try{p.mkdirSync(w.join(e,$),{recursive:!0}),p.writeFileSync(t,l.id,"utf8");}catch{}return {processed:d.length,nominations:a}}function qt(e,t){let n=f(e,t);if(!n?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let o=n.attention.threshold??.6,{nominationTtlDays:r}=z(e),i=r*24*60*60*1e3,d=k(e,{agent:t}).filter(f=>f.engaged||Date.now()-new Date(f.timestamp).getTime()<i).filter(f=>f.engaged);if(d.length<5)return {adjusted:false,oldThreshold:o,newThreshold:o,reason:`Insufficient data (${d.length}/5 engaged nominations)`};let l=d.filter(f=>f.response==="accepted").length,m=d.filter(f=>f.response==="dismissed").length,c=l/d.length,u=m/d.length,g=o,y="No adjustment needed";if(u>.6?(g=Math.min(.95,o+.05),y=`High dismiss rate (${(u*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):c>.8&&(g=Math.max(.2,o-.05),y=`High accept rate (${(c*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),g===o)return {adjusted:false,oldThreshold:o,newThreshold:g,reason:y};n.attention.threshold=g;let h=w.join(e,".paradigm/agents",`${t}.agent`),N=p.existsSync(h)?"project":"global";return j(t,n,N,e),U(e,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${o.toFixed(2)} \u2192 ${g.toFixed(2)} (${y})`,data:{old_threshold:o,new_threshold:g,accept_rate:c,dismiss_rate:u}}),{adjusted:true,oldThreshold:o,newThreshold:g,reason:y}}function st(e,t){let{nominationTtlDays:n}=z(e),o=n*24*60*60*1e3,i=k(e,{agent:t}).filter(c=>c.engaged||Date.now()-new Date(c.timestamp).getTime()<o),s=i.filter(c=>c.response==="accepted").length,a=i.filter(c=>c.response==="dismissed").length,d=i.filter(c=>c.response==="deferred").length,l=i.filter(c=>!c.engaged).length,m=s+a+d;return {total:i.length,accepted:s,dismissed:a,deferred:d,pending:l,acceptRate:m>0?s/m:0}}function Gt(e){let n=i(e).filter(c=>c$1(c.id,e)).map(c=>{let u=st(e,c.id),g=0;try{let y=w.join(ot.homedir(),".paradigm","notebooks",c.id);p.existsSync(y)&&(g=p.readdirSync(y).filter(h=>h.endsWith(".yaml")).length);}catch{}return {id:c.id,acceptRate:u.acceptRate,threshold:c.attention?.threshold??.5,expertiseCount:(c.expertise||[]).length,notebookCount:g,transferableCount:(c.transferable||[]).length,totalNominations:u.total}}),o=n.length||1,r=n.reduce((c,u)=>c+u.acceptRate,0)/o,i$1=n.reduce((c,u)=>c+u.threshold,0)/o,s=n.reduce((c,u)=>c+u.expertiseCount,0),a=n.reduce((c,u)=>c+u.notebookCount,0),d=n.reduce((c,u)=>c+u.transferableCount,0),l=n.reduce((c,u)=>c+u.totalNominations,0),m;return l<10?m="cold-start":r<.5?m="accumulating":r<.7?m="calibrating":m="mature",{agents:n,aggregate:{avgAcceptRate:r,avgThreshold:i$1,totalExpertise:s,totalNotebooks:a,totalTransferable:d},healthStatus:m}}function at(e,t){let n,o,r;try{let l=(Z(),d(Tt)),m=(Jt(),d(It));n=l.loadJournalEntries,o=m.addNotebookEntry,r=m.normalizeConcept;}catch{return {promoted:0,entries:[]}}let i=n(t,{trigger:"pattern_discovered",limit:100}),s=n(t,{trigger:"human_feedback",limit:100}),a=[...i,...s],d$1=[];for(let l of a)if(!l.promoted_to_notebook&&!((l.confidence_after??0)<.8))try{let{entry:m}=o(t,{context:l.pattern?.applies_when||l.insight.slice(0,80),snippet:l.pattern?.correct_approach||l.insight,concepts:(l.tags||[l.pattern?.id||"learned-pattern"]).map(r).filter(Boolean),provenance:{source:"lore",loreEntryId:l.id,createdBy:t}},"global",e);d$1.push({journalId:l.id,notebookId:m.id});try{let c=w.join(ot.homedir(),".paradigm","agents",t,"journal");if(p.existsSync(c)){let u=p.readdirSync(c).filter(g=>g.endsWith(".yaml"));for(let g of u){let y=w.join(c,g),h=p.readFileSync(y,"utf8");if(h.includes(l.id)){let N=h.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${m.id}"`);if(N===h){let f=h.trimEnd().split(`
|
|
29
|
-
`);f.push(`promoted_to_notebook: "${m.id}"`),p.writeFileSync(y,f.join(`
|
|
30
|
-
`)+`
|
|
31
|
-
`,"utf8");}else p.writeFileSync(y,N,"utf8");break}}}}catch{}}catch{}return {promoted:d$1.length,entries:d$1}}var Pe=".paradigm/surfacing.yaml";function Vt(e){let t=w.join(e,Pe),n={default_min_urgency:"low",enable_debates:true};if(!p.existsSync(t))return n;try{let o=a("js-yaml"),r=p.readFileSync(t,"utf8"),i=o.load(r);return {...n,...i}}catch{return n}}function Kt(e,t){let n={critical:0,high:1,medium:2,low:3},o=n[t.default_min_urgency||"low"]??3;return e.filter(r=>{let i=n[r.urgency]??3;if(t.preferences){let s=t.preferences.find(a=>a.agent===r.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(d=>r.urgency===d||r.type===d))return false;if(s.min_urgency){let a=n[s.min_urgency]??3;return i<=a}}}return i<=o})}var Ae=".paradigm/decisions";function Xt(e,t){let n=w.join(e,Ae);if(!p.existsSync(n))return [];let o=[],r=p.readdirSync(n).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=p.readFileSync(w.join(n,s),"utf8"),d=P.load(a);d&&d.id&&o.push(d);}catch{}let i=o;return (i=i.filter(s=>s.status===t.status)),t?.participant&&(i=i.filter(s=>s.participants.some(a=>a.id===t.participant))),t?.symbol&&(i=i.filter(s=>s.symbols_affected?.includes(t.symbol))),t?.tag&&(i=i.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(i=i.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(i=i.filter(s=>s.timestamp<=t.dateTo)),i.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}Z();function on(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function Oe(e){let t=Date.now(),n=e.match(/^(\d+)(m|h|d)$/);if(n){let o=parseInt(n[1],10),r=n[2],i=r==="m"?o*6e4:r==="h"?o*36e5:o*864e5;return new Date(t-i).toISOString()}return e}async function rn(e,t,n){let o=r=>JSON.stringify(r,null,2);switch(e){case "paradigm_ambient_nominations":{zt(n.rootDir);let i=t.pending_only!==false,s=t.limit||20,a=k(n.rootDir,{agent:t.agent,urgency:t.urgency,pending_only:i,limit:s+20}),d=Vt(n.rootDir);a=Kt(a,d).slice(0,s);let l=w.join(n.rootDir,".paradigm/events/nominations.jsonl");if(p.existsSync(l))try{let c=p.readFileSync(l,"utf8"),u=new Set(a.map(y=>y.id)),g=c.trim().split(`
|
|
32
|
-
`).map(y=>{try{let h=JSON.parse(y);return u.has(h.id)?(h.surfaced=!0,JSON.stringify(h)):y}catch{return y}});p.writeFileSync(l,g.join(`
|
|
33
|
-
`)+`
|
|
34
|
-
`,"utf8");}catch{}let m={count:a.length,nominations:a.map(c=>({id:c.id,agent:c.agent,urgency:c.urgency,type:c.type,brief:c.brief,relevance:c.relevance,timestamp:c.timestamp,engaged:c.engaged,response:c.response}))};if(t.include_debates){let u=Bt(n.rootDir).filter(g=>!g.resolution);m.debates=u.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),m.debate_count=u.length;}return {text:o(m),handled:true}}case "paradigm_ambient_events":{let r=t.since?Oe(t.since):void 0,i=t.limit||50,s=kt(n.rootDir,{type:t.type,source:t.source,symbol:t.symbol,agent:t.agent,since:r,limit:i});return {text:o({count:s.length,events:s.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let r=t.nomination_id,i=t.response,s=t.reason,a=Ht(n.rootDir,r,i,s);if(a)try{let{appendSessionWorkEntry:l,appendVerdictEntry:m}=await import('./session-work-log-QXPAXY5K.js'),u=k(n.rootDir,{limit:500}).find(y=>y.id===r),g={timestamp:new Date().toISOString(),type:"user-verdict",agent:u?.agent,nominationId:r,verdict:i,reason:s};l(n.rootDir,g),m(n.rootDir,g);}catch{}let d=false;return t.resolve_debate&&a&&(d=Wt(n.rootDir,t.resolve_debate,r,t.reason)),{text:o({engaged:a,nomination_id:r,response:i,debate_resolved:d||void 0}),handled:true}}case "paradigm_context_compose":{let r=t.agent,i=t.symbols||[],s=t.include_nominations!==false,a=t.include_decisions!==false,d=t.include_journal!==false,l=t.max_decisions||5,m=t.max_journal||5,c=f(n.rootDir,r);if(!c)return {text:o({error:`Agent profile not found: ${r}`}),handled:true};let u=[],g=p$1(c,i);if(g.trim()&&u.push(g),a){let y=Xt(n.rootDir,{status:"active",limit:l});if(y.length>0){u.push("## Recent Team Decisions");for(let h of y)u.push(`- **${h.title}**: ${h.decision.slice(0,150)}${h.decision.length>150?"...":""}`);u.push("");}}if(d){let y=F(r,{transferable:true,limit:m});if(y.length>0){u.push("## Transferable Insights");for(let h of y)u.push(`- [${h.trigger}] ${h.insight.slice(0,150)}${h.insight.length>150?"...":""}`);u.push("");}}if(s){let y=k(n.rootDir,{pending_only:true,limit:10});if(y.length>0){u.push("## Pending Nominations");for(let h of y)u.push(`- [${h.urgency}] ${h.brief}`);u.push("");}}return {text:o({agent:r,context:u.join(`
|
|
35
|
-
`),sections_included:{profile:true,decisions:a,journal:d,nominations:s}}),handled:true}}case "paradigm_ambient_promote":{let r=t.agent,i=at(n.rootDir,r);return {text:o({agent:r,promoted:i.promoted,entries:i.entries}),handled:true}}case "paradigm_ambient_learn":{let r=t.agent,i=t.dry_run===true,s=st(n.rootDir,r);if(i)return {text:o({agent:r,dry_run:true,stats:s,note:s.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(s.acceptRate*100).toFixed(0)}% \u2014 ${s.acceptRate>.8?"would lower threshold":s.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=qt(n.rootDir,r);return {text:o({agent:r,...a,stats:s}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let r=Gt(n.rootDir);return {text:o(r),handled:true}}case "paradigm_ambient_learn_postflight":return {text:o(await Ie(n.rootDir,t)),handled:true};default:return {text:`Unknown ambient tool: ${e}`,handled:false}}}var Fe={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function Ce(e){try{let t=w.join(e,".paradigm","config.yaml");if(p.existsSync(t)){let o=p.readFileSync(t,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(o)return o[1].trim()}}catch{}return w.basename(e)}async function Ie(e$1,t={}){let n=t.dry_run===true,o=Ce(e$1),r=e(e$1).filter(f=>f.verdict&&f.agent),i=g(e$1).filter(f=>f.agent&&f.corrections.length>0),s=b$1(e$1);if(r.length===0&&i.length===0)return {sessionEntries:s.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:n,details:[]};let a=new Map;for(let f of r){let b=f.agent;a.has(b)||a.set(b,[]),a.get(b).push(f);}let d=s.filter(f=>f.type==="agent-contribution"),l=new Map;for(let f of d)f.agent&&(l.has(f.agent)||l.set(f.agent,[]),l.get(f.agent).push(f));let m=[],c={},u=0;for(let[f,b]of a){c[f]=0;let A=b.filter(S=>S.verdict==="accepted").length;b.filter(S=>S.verdict==="dismissed").length;b.filter(S=>S.verdict==="revised").length;let G=b.length,Qt=G>0?A/G:0;for(let S of b){let V=Fe[S.verdict];if(!V)continue;let Zt=l.get(f)?.shift(),dt=Je(S,Zt,{acceptRate:Qt,total:G,accepted:A}),te=typeof S.confidence=="number"?S.confidence:S.verdict==="accepted"?.85:S.verdict==="revised"?.6:.4,ee={agent:f,verdict:S.verdict,trigger:V,insight:dt,symbols:S.symbols};if(m.push(ee),n)c[f]++,u++;else try{H(f,{trigger:V,insight:dt,confidence_before:S.verdict==="accepted"?.7:.8,confidence_after:te,project:o,transferable:S.verdict==="dismissed",tags:["postflight",`verdict:${S.verdict}`,...(S.symbols||[]).map(ne=>`symbol:${ne}`)]}),c[f]++,u++;}catch{}}}let g$1=new Set;for(let f of i){let b=f.agent;g$1.add(b),c[b]===void 0&&(c[b]=0);let A=`Self-revision during iteration round ${f.round}: ${f.corrections.join("; ")}`;if(m.push({agent:b,verdict:"iteration-revision",trigger:"self_reflection",insight:A,symbols:f.symbols}),n)c[b]++,u++;else try{H(b,{trigger:"self_reflection",insight:A,confidence_before:.6,confidence_after:typeof f.confidence=="number"?f.confidence:.75,project:o,transferable:!1,tags:["postflight","iteration-revision",`round:${f.round}`,...(f.symbols||[]).map(q=>`symbol:${q}`)]}),c[b]++,u++;}catch{}}let y={},h$1=0,N=new Set([...a.keys(),...g$1]);if(!n)for(let f of N)try{let b=at(e$1,f);b.promoted>0&&(y[f]=b.promoted,h$1+=b.promoted);}catch{}return !n&&r.length>0&&f$1(e$1,r.map(f=>f.nominationId).filter(Boolean)),!n&&i.length>0&&h(e$1,i.map(f=>f.id)),{sessionEntries:s.length,agentsProcessed:Array.from(N),journalsWritten:u,journalsByAgent:c,promoted:h$1,promotedByAgent:y,dryRun:n,details:m}}function Je(e,t,n){let o=e.symbols?.length?` (symbols: ${e.symbols.join(", ")})`:"",r=e.reason?` Reason: ${e.reason}.`:"";switch(e.verdict){case "accepted":return `Contribution accepted by user${o}.${r}`+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(n.acceptRate*100).toFixed(0)}% (${n.accepted}/${n.total}).`;case "dismissed":return `Contribution dismissed by user${o}.${r}`+(t?.contribution?` Rejected contribution: "${t.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(n.acceptRate*100).toFixed(0)}% (${n.accepted}/${n.total}).`;case "revised":return `Contribution revised by user${o}.${r}`+(e.revisionDelta?` Delta: "${e.revisionDelta.slice(0,120)}".`:"")+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(n.acceptRate*100).toFixed(0)}% (${n.accepted}/${n.total}).`;default:return `Unknown verdict "${e.verdict}"${o}.${r}`}}export{on as getAmbientToolsList,rn as handleAmbientTool,Ie as runPostflightLearning};
|
package/dist/chunk-6AKNXD22.js
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {b,a as a$1}from'./chunk-DLMDHS2X.js';import {a}from'./chunk-FYDRENK7.js';import {a as a$2}from'./chunk-TYWB5IQJ.js';import {e}from'./chunk-YXLGVOZO.js';import {b as b$1}from'./chunk-EKZDFEJW.js';import {a as a$3,b as b$2}from'./chunk-LPBCQM5Y.js';import {o,t,x as x$1}from'./chunk-4GC35IFF.js';import'minimatch';import*as v from'fs';import*as x from'path';import*as L from'js-yaml';import {spawn}from'child_process';var pe=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","tradeoff","pros and cons","decision"],he=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs","changelog","architecture doc"],fe=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","doesn't work","doesn't","cant","can't","regression","patch"],me=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify","modularize","decouple","split","merge"],ye=["auth","authentication","authorization","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","api key","role","access","gate","portal","sensitive","private","security","vulnerability","xss","sql injection","csrf"],be=/[@#$%^!?&~][a-zA-Z0-9_-]+/g,ee={analysis:{agents:["architect"],models:{architect:"opus"},costMultiplier:{min:.3,max:.5}},documentation:{agents:["architect"],models:{architect:"sonnet"},costMultiplier:{min:.25,max:.45}},bugfix:{agents:["security","builder"],models:{security:"opus",builder:"haiku"},costMultiplier:{min:.5,max:.8}},refactor:{agents:["architect","builder"],models:{architect:"opus",builder:"haiku"},costMultiplier:{min:.6,max:.85}},feature:{agents:["architect","security","builder","tester"],models:{architect:"opus",security:"opus",builder:"haiku",tester:"haiku"},costMultiplier:{min:.8,max:1.2}}};function we(h){let s=h.match(be)||[];return [...new Set(s)]}function j(h,s){let e=h.toLowerCase();return s.filter(t=>e.includes(t.toLowerCase()))}function ke(h,s,e,t){let n=0;e.length>=5?n+=2:e.length>=2&&(n+=1);let o=h.split(/\s+/).length;o>=100?n+=2:o>=50&&(n+=1);let r=new Set(e.map(l=>l[0]));return r.size>=4?n+=2:r.size>=2&&(n+=1),e.some(l=>l.startsWith("^"))&&(n+=1),e.some(l=>l.startsWith("$"))&&(n+=1),s==="feature"&&(n+=1),s==="refactor"&&(n+=1),n>=5?"high":n>=2?"medium":"low"}function ve(h,s,e){if(j(h,ye).length>0||s.some(n=>n.startsWith("^")))return true;return false}function te(h,s){let e=we(h),t=j(h,pe),n=j(h,he),o=j(h,fe),r=j(h,me),l,i;t.length>0&&o.length===0&&r.length===0?(l="analysis",i=t):n.length>0&&o.length===0?(l="documentation",i=n):o.length>0?(l="bugfix",i=o):r.length>0?(l="refactor",i=r):(l="feature",i=[]);let a=ee[l],p=ve(h,e),c=[...a.agents];p&&!c.includes("security")&&(c=["security",...c]);let m=ke(h,l,e),g={...a.costMultiplier};return m==="high"?(g.min*=1.2,g.max*=1.3):m==="low"&&(g.min*=.8,g.max*=.9),p&&!a.agents.includes("security")&&(g.min+=.15,g.max+=.2),{type:l,complexity:m,recommendedAgents:c,securityRequired:p,costMultiplier:g,matchedKeywords:i,symbols:e}}function U(h,s){let e=ee[s.type];return h==="security"&&s.securityRequired?"opus":e.models[h]||"sonnet"}var Se=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,Oe=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi],Re=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"];function se(h,s,e$1){let t$1=h.toLowerCase(),n=h.match(Se)||[],o=[...new Set(n)],r=o.map(d=>{let y=t(e$1,d),w=y.length>0?y[0]:null;return {symbol:d,exists:!!w,type:w?.type,description:w?.description}}),l=r.filter(d=>d.exists).map(d=>{let y=x$1(e$1,d.symbol),w=new Set;for(let C of y){let f=x$1(e$1,C.symbol);for(let b of f)b.symbol!==d.symbol&&!y.find(O=>O.symbol===b.symbol)&&w.add(b.symbol);}let R=y.length+w.size,A="low";return R>10?A="high":R>3&&(A="medium"),{symbol:d.symbol,directDependents:y.length,indirectDependents:w.size,impact:A}}),i=a$3(s),a=i.status==="ok"?i.data:null,p={exists:i.status!=="missing",gateCount:a?b$2(a).length:0,gates:a?b$2(a).map(d=>`^${d}`):[],routeCount:a?.routes?Object.keys(a.routes).length:0},c=Re.some(d=>t$1.includes(d)),m=e(s),g=m?a$2(h,m.agents).map(d=>({name:d.name,confidence:d.confidence,reason:d.reason})):[],u=[];return r.some(d=>d.exists)&&u.push("ripple-analysis"),c&&u.push("portal-compliance"),o.some(d=>d.startsWith("^"))&&u.push("gate-validation"),o.some(d=>d.startsWith("!"))&&u.push("signal-registration"),u.push("purpose-coverage"),{affectedSymbols:r,rippleAnalysis:l,portalStatus:p,taskAddsRoutes:c,suggestedAgents:g,requiredChecks:u}}function re(h,s,e,t$1){let n=[],o=a$3(e),r=o.status==="ok"?o.data:null,l=r?b$2(r):[],i=r?.routes?Object.keys(r.routes):[];for(let g of h){let u=x.isAbsolute(g)?g:x.join(e,g);if(!v.existsSync(u))continue;let d;try{d=v.readFileSync(u,"utf-8");}catch{continue}for(let y of Oe){y.lastIndex=0;let w;for(;(w=y.exec(d))!==null;){let R=w[2]||w[0];R&&R.startsWith("/")&&(!i.some(C=>C.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===R)&&r?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${R}" found in ${x.relative(e,u)} but not declared in portal.yaml`,file:x.relative(e,u),suggestion:"Add this route to portal.yaml with appropriate ^gates. Run paradigm_gates_for_route to get suggestions."}):!r&&R.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${R}" found but no portal.yaml exists`,file:x.relative(e,u),suggestion:"Create portal.yaml to declare gates for API routes. Run: paradigm portal init"}));}}}for(let g of s)t(t$1,g).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${g}" was touched but is not registered in any .purpose file`,suggestion:`Add "${g}" to the nearest .purpose file. Use paradigm_purpose_add_component or paradigm_purpose_add_signal.`});for(let g of s)if(g.startsWith("^")){let u=g.slice(1);l.includes(u)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${g}" is referenced but not declared in portal.yaml`,suggestion:`Add ${g} to portal.yaml with description and check expression.`});}h.length>=5&&s.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${h.length} files, ${s.length} symbols) \u2014 consider recording architectural decisions`,suggestion:"Use paradigm_wisdom_record to capture any decisions or antipatterns discovered during this task."});let a=n.filter(g=>g.severity==="error").length,p=n.filter(g=>g.severity==="warning").length,c=4,m="pass";return a>0?m="violations":p>0&&(m="warnings"),{status:m,violations:n,summary:{totalChecks:c,passed:c-(a>0?1:0)-(p>0?1:0),warnings:p,errors:a},blocksCompletion:a>0}}var Pe=".paradigm/events/iteration-revisions.jsonl";function ne(h,s){try{let e=x.join(h,Pe),t=x.dirname(e);v.existsSync(t)||v.mkdirSync(t,{recursive:!0});let n={timestamp:new Date().toISOString(),type:"iteration-revision",...s};v.appendFileSync(e,JSON.stringify(n)+`
|
|
3
|
-
`,"utf8");}catch{}}function oe(h,s){let e=Math.random().toString(36).substring(2,8);return `itrev-${h}-r${s}-${Date.now()}-${e}`}var ie={architect:"opus",security:"opus",reviewer:"sonnet",builder:"haiku",tester:"haiku"},Ae=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","role","access control","vulnerability","injection","xss","csrf"];function Te(h,s){let e=h.toLowerCase(),t=Ae.some(r=>e.includes(r.toLowerCase())),n=h.includes("^"),o=false;return t||n||o}var $e=["rename","refactor","migrate","restructure","move","reorganize"];function De(h){let s=h.toLowerCase();return $e.some(e=>s.includes(e))}var V=class{spawner;auditLogger;rootDir;constructor(s){this.rootDir=s,this.spawner=new b(s),this.auditLogger=new a(s);}async initialize(){await this.spawner.initialize();}async orchestrate(s,e={}){let t=e.mode||"faceted",n=Date.now(),o$1=this.generateOrchestrationId(),r={success:false,mode:t,orchestrationId:o$1,task:s,agentsSpawned:0,totalTokens:{input:0,output:0,total:0},totalCost:0,duration_ms:0,agentResults:[]};try{let l;if(e.pmGovernance?.enabled)try{let{aggregateFromDirectory:a}=await import('./dist-TNE4GFT7.js'),p=await a(this.rootDir),c=o(p);l=se(s,this.rootDir,c);}catch{}if(t==="solo"){let a=await this.runSoloMode(s,e);r.agentsSpawned=1,r.agentResults=[a],r.success=a.success,a.relay&&(r.totalTokens=a.relay.metrics.tokens_used,r.totalCost=b$1(r.totalTokens,e.orchestratorModel||"opus"));}else {let a=await this.runFacetedMode(s,e);r.agentsSpawned=a.results.length,r.agentResults=a.results,r.totalTokens=a.totalTokens,r.totalCost=a.totalCost,r.success=a.success,r.parallelBuilderStats=a.parallelBuilderStats,r.iterationOutcome=a.iterationOutcome;}if(e.pmGovernance?.enabled&&l)try{let{aggregateFromDirectory:a}=await import('./dist-TNE4GFT7.js'),p=await a(this.rootDir),c=o(p),m=[],g=[];for(let d of r.agentResults)d.relay?.outputs?.artifacts&&m.push(...d.relay.outputs.artifacts.map(y=>y.path));for(let d of l.affectedSymbols)g.push(d.symbol);let u=re(m,g,this.rootDir,c);r.complianceReport={preflight:l,postflight:u},e.pmGovernance.blockOnViolations&&u.blocksCompletion&&(r.success=!1);}catch{r.complianceReport={preflight:l};}r.duration_ms=Date.now()-n;let i=this.auditLogger.startOrchestration(o$1,s,t);return i.completed=new Date().toISOString(),i.status=r.success?"success":"failed",i.totals={duration_ms:r.duration_ms,tokens:r.totalTokens.total,cost_usd:r.totalCost,agents_spawned:r.agentsSpawned,files_created:0,files_modified:0},this.auditLogger.saveOrchestration(i),r.log=i,r}catch(l){return r.error=l instanceof Error?l.message:String(l),r.duration_ms=Date.now()-n,r}}async compare(s,e={}){let t=await this.orchestrate(s,{...e,mode:"solo"}),n=await this.orchestrate(s,{...e,mode:"faceted"}),o=t.totalTokens.total-n.totalTokens.total,r=t.totalCost-n.totalCost,l=t.duration_ms-n.duration_ms,i="tie";return n.success&&!t.success?i="faceted":t.success&&!n.success?i="solo":n.totalCost<t.totalCost*.8?i="faceted":t.totalCost<n.totalCost*.8&&(i="solo"),{solo:t,faceted:n,comparison:{winner:i,tokensSaved:o,costDiff:r,timeDiff:l,soloSucceeded:t.success,facetedSucceeded:n.success}}}async runSoloMode(s,e$1){let n=e(this.rootDir)?.team.default_agent||"architect",o=e$1.orchestratorModel||"opus",r={model:o,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.budget,onMessage:e$1.onMessage?i=>e$1.onMessage("solo",i):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart("solo",s,o);let l=await this.spawner.spawn(n,s,r);return e$1.onAgentComplete&&e$1.onAgentComplete("solo",l,o),l}async runFacetedMode(s,e$1){let t=e(this.rootDir);if(!t)return {success:false,results:[],totalTokens:{input:0,output:0,total:0},totalCost:0};let n="";if(De(s)){let f=a$1(s);if(f.length>0){let b=[];b.push(`## Auto-Ripple Analysis
|
|
4
|
-
`),b.push("The following symbols are affected by this refactoring:"),b.push("");for(let O of f.slice(0,5))b.push(`- **${O}**: Check dependencies before renaming/moving`);b.push(""),b.push("**Recommendation:** Run `paradigm_ripple` for each symbol before making changes."),n=b.join(`
|
|
5
|
-
`);}}let o=this.planAgentSequence(s,t.agents),r=this.groupByStage(o),l=[],i={input:0,output:0,total:0},a=0,p=new Map,c=true,m=t.orchestration?.iteration,g=m?.enabled===true,u=o.find(f=>f.agent==="builder")?.subtask,d=o.some(f=>f.agent==="reviewer"),y=o.some(f=>f.agent==="tester"),w=g&&!!u&&d,R,A=Array.from(r.keys()).sort((f,b)=>f-b);for(let f of A){let b=r.get(f)||[];if(b.length===0)continue;if(e$1.checkpoints?.beforeAgentSpawn&&e$1.onCheckpoint){let k=b.map(T=>T.agent).join(", ");if(!await e$1.onCheckpoint(`Stage ${f}: Spawn ${k}${b.length>1?" (parallel)":""}`)){c=false;break}}let O=b.map(async k=>{let S=e$1.agentBudgets?.[k.agent]?.maxTokens?"haiku":k.model||ie[k.agent]||"sonnet",T="";if(k.dependsOn.length>0){let M=k.dependsOn.map(Y=>p.get(Y)).filter(Boolean);M.length>0&&(T=M.join(`
|
|
6
|
-
|
|
7
|
-
---
|
|
8
|
-
|
|
9
|
-
`));}let _=T;k.agent==="architect"&&n&&(_=n+(T?`
|
|
10
|
-
|
|
11
|
-
---
|
|
12
|
-
|
|
13
|
-
`+T:""));let I=_?`${k.subtask}
|
|
14
|
-
|
|
15
|
-
## Context from previous agents:
|
|
16
|
-
${_}`:k.subtask;w&&k.agent==="reviewer"&&(I=`${I}
|
|
17
|
-
|
|
18
|
-
${ae}`);let $={model:S,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.agentBudgets?.[k.agent]||e$1.budget,onMessage:e$1.onMessage?M=>e$1.onMessage(k.agent,M):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart(k.agent,k.subtask,S);let P=await this.spawner.spawn(k.agent,I,$);return e$1.onAgentComplete&&e$1.onAgentComplete(k.agent,P,S),{step:k,result:P,model:S}}),ue=await Promise.all(O);for(let{step:k,result:S,model:T}of ue){if(l.push(S),S.relay){i.input+=S.relay.metrics.tokens_used.input,i.output+=S.relay.metrics.tokens_used.output,i.total+=S.relay.metrics.tokens_used.total,a+=b$1(S.relay.metrics.tokens_used,T);let _=S.relay.handoff?.context||`${k.agent} completed: ${S.relay.outputs.decisions.join(", ")||"task done"}`;if(p.set(k.agent,_),k.agent==="architect"&&S.relay){let I=this.extractFilePlanFromRelay(S);if(I&&I.length>0){let $=this.planBuilderStages(I);if($.hasFilePlan&&$.totalBuilders>1){let P=await this.runParallelBuilders($,p.get("architect")||"",e$1);l.push(...P.results),i.input+=P.totalTokens.input,i.output+=P.totalTokens.output,i.total+=P.totalTokens.total,a+=P.totalCost,P.success||(c=false),R={usedFilePlan:true,totalSubPhases:$.stages.length,totalParallelBuilders:$.totalBuilders,filesCreated:$.totalFiles};for(let[M,Y]of r){let de=Y.filter(ge=>ge.agent!=="builder");r.set(M,de);}}}}}!S.success&&k.required&&(c=false);}if(!c||e$1.checkpoints?.afterAgentComplete&&e$1.onCheckpoint&&!await e$1.onCheckpoint(`Stage ${f} completed. Continue to next stage?`))break}let C;if(w&&c){let f=[...l].reverse().find(O=>O.relay?.agent==="reviewer"),b=f?this.parseIterationVerdict(f):null;if(b?.verdict==="changes-requested"){let O=await this.runReviewIteration({builderSubtask:u,firstReview:b,hasTester:y,maxRoundsConfig:m?.defaultMaxRounds??3,options:e$1});l.push(...O.extraResults),i.input+=O.extraTokens.input,i.output+=O.extraTokens.output,i.total+=O.extraTokens.total,a+=O.extraCost,C=O.iterationOutcome;}else f&&!b&&e$1.onMessage&&e$1.onMessage("orchestrator",{type:"text",content:"[iteration] reviewer produced no parseable iteration-verdict \u2014 re-review loop not triggered.",timestamp:new Date().toISOString()});}return {success:c,results:l,totalTokens:i,totalCost:a,parallelBuilderStats:R,iterationOutcome:C}}async runReviewIteration(s){let{builderSubtask:e,firstReview:t,hasTester:n,maxRoundsConfig:o,options:r}=s,l=o%2===0?o:o+1,i=[e];t.openThreads.length&&i.push("","## Reviewer asked you to resolve:",...t.openThreads.map(u=>`- ${u}`)),t.whatChanged.length&&i.push("","## Reviewer notes:",...t.whatChanged.map(u=>`- ${u}`));let a=u=>r.agentBudgets?.[u]?.maxTokens?"haiku":ie[u]||"sonnet",p=u=>r.agentBudgets?.[u]||r.budget,c=await this.runIterationLoop(i.join(`
|
|
19
|
-
`),{maxRounds:l,mode:"ping-pong",iterateAgent:"builder",reviewAgent:"reviewer",workingDirectory:r.workingDirectory||this.rootDir,mcpServerPath:r.mcpServerPath,resolveModel:a,resolveBudget:p,onRound:r.onAgentComplete?u=>r.onAgentComplete(u.agent,u.spawnResult,a(u.agent)):void 0}),m=c.rounds.map(u=>u.spawnResult),g=0;for(let u of c.rounds)u.spawnResult.relay&&(g+=b$1(u.spawnResult.relay.metrics.tokens_used,a(u.agent)));if(n&&c.converged){let u=await this.spawner.spawn("tester",`Re-test after re-review convergence:
|
|
20
|
-
${e}`,{model:"haiku",workingDirectory:r.workingDirectory||this.rootDir,mcpServerPath:r.mcpServerPath});m.push(u),u.relay&&(g+=b$1(u.relay.metrics.tokens_used,"haiku"),c.totalTokens.input+=u.relay.metrics.tokens_used.input,c.totalTokens.output+=u.relay.metrics.tokens_used.output,c.totalTokens.total+=u.relay.metrics.tokens_used.total);}return {extraResults:m,extraTokens:c.totalTokens,extraCost:g,iterationOutcome:{converged:c.converged,roundsRun:c.rounds.length,openThreads:c.unresolved?.openThreads??[]}}}extractFilePlanFromRelay(s){if(!s.relay)return;let e=s.relay.handoff?.context||"";if(e.includes("filePlan:"))return this.parseFilePlanFromText(e)}parseFilePlanFromText(s){let e=[],t=s.match(/filePlan:\s*\n([\s\S]*?)(?=\n[a-z_]+:|$)/);if(!t)return;let o=t[1].split(`
|
|
21
|
-
`),r=null,l=false,i={};for(let a of o){let p=a.trim();if(!(!p||p.startsWith("#"))){if(p.startsWith("- group:")){r&&(i.path&&(r.files.push({path:i.path,description:i.description||""}),i={}),e.push(r)),r={group:p.split(":")[1].trim(),subPhase:0,files:[]},l=false;continue}if(r){if(p.startsWith("subPhase:")){r.subPhase=parseInt(p.split(":")[1].trim(),10)||0;continue}if(p==="files:"){l=true;continue}if(l){if(p.startsWith("- path:")){i.path&&r.files.push({path:i.path,description:i.description||""}),i={path:p.split(":").slice(1).join(":").trim().replace(/^["']|["']$/g,"")};continue}if(p.startsWith("description:")){i.description=p.split(":").slice(1).join(":").trim().replace(/^["']|["']$/g,"");continue}}}}}return i.path&&r&&r.files.push({path:i.path,description:i.description||""}),r&&e.push(r),e.length>0?e:void 0}planAgentSequence(s,e){let t=a$1(s),n=s.toLowerCase(),o=te(s),r=[],l=Te(s);if(o.type==="analysis")return e.architect&&r.push({agent:"architect",subtask:`Analyze and recommend: ${s}`,required:true,stage:0,dependsOn:[],model:"opus"}),r;if(o.type==="documentation")return e.architect&&r.push({agent:"architect",subtask:`Document: ${s}`,required:true,stage:0,dependsOn:[],model:"sonnet"}),r;let i=n.includes("design")||n.includes("architect")||n.includes("plan")||n.includes("spec"),a=l||n.includes("auth")||n.includes("security")||n.includes("gate")||t.some(d=>d.startsWith("^"));if(i&&e.architect&&r.push({agent:"architect",subtask:`Design and specify: ${s}`,required:true,stage:0,dependsOn:[],model:"opus"}),a&&e.security&&r.push({agent:"security",subtask:`Review security aspects of: ${s}`,required:l,stage:0,dependsOn:[],model:"opus"}),(n.includes("build")||n.includes("implement")||n.includes("create")||n.includes("add")||n.includes("fix"))&&e.builder){let d=i&&e.architect?["architect"]:[];r.push({agent:"builder",subtask:`Implement: ${s}`,required:true,stage:d.length>0?1:0,dependsOn:d,model:"haiku"});}let c=n.includes("review")||n.includes("check"),m=n.includes("test")||n.includes("verify")||n.includes("validate"),g=r.some(d=>d.agent==="builder"),u=g?2:i?1:0;if(c&&e.reviewer&&r.push({agent:"reviewer",subtask:`Review: ${s}`,required:false,stage:u,dependsOn:g?["builder"]:[],model:"sonnet"}),m&&e.tester&&r.push({agent:"tester",subtask:`Test and validate: ${s}`,required:false,stage:u,dependsOn:g?["builder"]:[],model:"haiku"}),r.length===0){let d=o.recommendedAgents;if(d.includes("architect")&&e.architect&&r.push({agent:"architect",subtask:`Design: ${s}`,required:true,stage:0,dependsOn:[],model:U("architect",o)}),(d.includes("security")||l)&&e.security&&r.push({agent:"security",subtask:`Security review: ${s}`,required:l,stage:0,dependsOn:[],model:"opus"}),d.includes("builder")&&e.builder){let y=r.length>0;r.push({agent:"builder",subtask:`Implement: ${s}`,required:true,stage:y?1:0,dependsOn:r.filter(w=>w.stage===0).map(w=>w.agent),model:U("builder",o)});}if(d.includes("tester")&&e.tester){let y=r.find(w=>w.agent==="builder")?.stage??0;r.push({agent:"tester",subtask:`Test: ${s}`,required:false,stage:y+1,dependsOn:e.builder?["builder"]:[],model:U("tester",o)});}}try{let d=a$2(s,e),y=new Set(r.map(f=>f.agent)),w=new Set(["documentor"]),A=(r.length>0?Math.max(...r.map(f=>f.stage)):-1)+1,C=r.map(f=>f.agent);for(let f of d){if(y.has(f.name)||w.has(f.name)||!e[f.name]||f.confidence==="low")continue;let b=e[f.name];r.push({agent:f.name,subtask:`Contribute (${b?.focus??"specialist"}): ${s}`,required:!1,stage:A,dependsOn:C,model:b?.defaultModel??"sonnet"}),y.add(f.name);}}catch{}return r.sort((d,y)=>d.stage-y.stage)}groupByStage(s){let e=new Map;for(let t of s){let n=e.get(t.stage)||[];n.push({agent:t.agent,subtask:t.subtask,required:t.required,dependsOn:t.dependsOn}),e.set(t.stage,n);}return e}generateOrchestrationId(){let s=new Date().toISOString().slice(0,10),e=Math.random().toString(36).substring(2,8);return `orch-${s}-${e}`}planBuilderStages(s){if(!s||s.length===0)return {hasFilePlan:false,stages:[{subPhase:0,builders:[{agent:"builder",group:"all",files:[],availableFiles:[]}]}],totalFiles:0,totalBuilders:1};let e=new Map;for(let i of s){let a=e.get(i.subPhase)||[];a.push(i),e.set(i.subPhase,a);}let t=[],n=[...e.keys()].sort((i,a)=>i-a),o=[],r=0,l=0;for(let i of n){let a=e.get(i),p=[];for(let c=0;c<a.length;c++){let m=a[c];l+=m.files.length,r++,p.push({agent:`builder-${i}-${c}`,group:m.group,files:m.files,availableFiles:[...o]});}t.push({subPhase:i,builders:p});for(let c of a)for(let m of c.files)o.push(m.path);}return {hasFilePlan:true,stages:t,totalFiles:l,totalBuilders:r}}buildParallelBuilderPrompt(s,e,t,n){let o=[];o.push(`You are a BUILDER agent responsible for implementing the **${n}** group.`),o.push(""),o.push("## Your Assignment"),o.push(""),o.push("### Files to Create:");for(let r of s)o.push(`- \`${r.path}\`: ${r.description}`);if(o.push(""),e.length>0){o.push("### Available Files (already created):"),o.push("These files exist and you can import from them:");for(let r of e)o.push(`- \`${r}\``);o.push("");}return t&&(o.push("### Context from Architect:"),o.push(t),o.push("")),o.push("### Instructions:"),o.push("1. Create ONLY the files assigned to you"),o.push("2. You can import from available files (already created)"),o.push("3. Follow existing patterns in the codebase"),o.push("4. Use the Paradigm logger (not console.log)"),o.push("5. End with the standard Agent Relay block"),o.join(`
|
|
22
|
-
`)}async runParallelBuilders(s,e,t){let n=[],o={input:0,output:0,total:0},r=0,l=true;for(let i of s.stages){if(t.checkpoints?.beforeAgentSpawn&&t.onCheckpoint){let c=i.builders.map(g=>g.group).join(", ");if(!await t.onCheckpoint(`Builder Sub-phase ${i.subPhase}: ${c}${i.builders.length>1?" (parallel)":""}`)){l=false;break}}let a=i.builders.map(async c=>{let m=this.buildParallelBuilderPrompt(c.files,c.availableFiles,e,c.group),g={model:"haiku",workingDirectory:t.workingDirectory||this.rootDir,mcpServerPath:t.mcpServerPath,budget:t.budget,onMessage:t.onMessage?d=>t.onMessage(c.agent,d):void 0,onCheckpoint:t.onCheckpoint};t.onAgentStart&&t.onAgentStart(c.agent,`Implement ${c.group}`,"haiku");let u=await this.spawner.spawn("builder",m,g);return t.onAgentComplete&&t.onAgentComplete(c.agent,u,"haiku"),{builder:c,result:u}}),p=await Promise.all(a);for(let{result:c}of p)n.push(c),c.relay&&(o.input+=c.relay.metrics.tokens_used.input,o.output+=c.relay.metrics.tokens_used.output,o.total+=c.relay.metrics.tokens_used.total,r+=b$1(c.relay.metrics.tokens_used,"haiku")),c.success||(l=false);if(!l||t.checkpoints?.afterAgentComplete&&t.onCheckpoint&&!await t.onCheckpoint(`Sub-phase ${i.subPhase} complete. Continue to next sub-phase?`))break}return {success:l,results:n,totalTokens:o,totalCost:r}}async runIterationLoop(s,e,t){if(!Number.isInteger(e.maxRounds)||e.maxRounds<1)throw new Error(`runIterationLoop: maxRounds must be an integer >= 1 (got ${e.maxRounds})`);if(e.mode==="ping-pong"&&!e.reviewAgent)throw new Error("runIterationLoop: ping-pong mode requires reviewAgent");let n=t??(a=>ne(this.rootDir,{id:oe(a.agent,a.round),agent:a.agent,corrections:a.corrections,symbols:a.symbols,round:a.round})),o=[],r={input:0,output:0,total:0},l=null,i=null;for(let a=1;a<=e.maxRounds;a++){let p=this.iterationAgentForRound(e,a),c=this.buildIterationTask(s,l,a),m={workingDirectory:e.workingDirectory||this.rootDir,mcpServerPath:e.mcpServerPath,model:e.resolveModel?.(p),budget:e.resolveBudget?.(p)},g=await this.spawner.spawn(p,c,m);g.relay&&(r.input+=g.relay.metrics.tokens_used.input,r.output+=g.relay.metrics.tokens_used.output,r.total+=g.relay.metrics.tokens_used.total);let u=this.parseIterationVerdict(g);u&&(i=u);let d=false;if(this.beliefRevised(u,l)){let w=u.corrections.length>0?u.corrections:this.reopenedClaims(u,l);n({agent:p,corrections:w,symbols:g.relay?.outputs.symbols??[],round:a}),d=true;}let y={round:a,agent:p,spawnResult:g,delta:u,promoted:d};if(o.push(y),e.onRound?.(y),!g.success)return this.unresolvedResult(o,i,r,"spawn-failed",a);if(u===null)return this.unresolvedResult(o,i,r,"unparseable-verdict",a);if(this.isConverged(u,e,p))return {converged:true,rounds:o,finalDelta:u,totalTokens:r};l=u;}return this.unresolvedResult(o,i,r,"max-rounds",e.maxRounds)}unresolvedResult(s,e,t,n,o){return {converged:false,rounds:s,finalDelta:e,totalTokens:t,unresolved:{reason:n,roundsRun:o,openThreads:e?.openThreads??[]}}}iterationAgentForRound(s,e){return s.mode==="single-role"||e%2===1?s.iterateAgent:s.reviewAgent}isConverged(s,e,t){return s.verdict!=="approved"?false:e.mode==="single-role"?s.openThreads.length===0:t===e.reviewAgent}reopenedClaims(s,e){return e?s.whatChanged.filter(t=>e.alreadyVerified.includes(t)):[]}beliefRevised(s,e){return s?s.corrections.length>0?true:this.reopenedClaims(s,e).length>0:false}buildIterationTask(s,e,t){let n=[s];return e&&(n.push("",`## Iteration delta (entering round ${t})`),n.push(`- Verdict so far: ${e.verdict}`),e.whatChanged.length&&n.push("- Changed last round:",...e.whatChanged.map(o=>` - ${o}`)),e.alreadyVerified.length&&n.push("- Already verified (do NOT re-litigate):",...e.alreadyVerified.map(o=>` - ${o}`)),e.openThreads.length&&n.push("- Open threads to resolve:",...e.openThreads.map(o=>` - ${o}`))),n.push("",ae),n.join(`
|
|
23
|
-
`)}parseIterationVerdict(s){if(!s.relay)return null;let e=[];s.relay.handoff?.context&&e.push(s.relay.handoff.context),s.relay.outputs?.decisions?.length&&e.push(s.relay.outputs.decisions.join(`
|
|
24
|
-
`)),s.relay.rawResponse&&e.push(s.relay.rawResponse);for(let t of e){let n=Ie(t);if(n)return n}return null}},ae=["## Required: end with an iteration-verdict block","After your work, append a fenced block tagged `iteration-verdict` with JSON:","```iteration-verdict","{",' "verdict": "approved" | "changes-requested",',' "whatChanged": ["progress made this round"],',' "alreadyVerified": ["settled claims; do not revisit"],',' "openThreads": ["unresolved items for the next round"],',' "corrections": ["only genuine belief revisions: was X, now Y"]',"}","```",'Use "approved" only when no open threads remain. Leave "corrections" empty if nothing you previously believed changed.'].join(`
|
|
25
|
-
`);function Ie(h){let s=[...h.matchAll(/```iteration-verdict\s*\n([\s\S]*?)```/g)];if(s.length===0)return null;for(let e=s.length-1;e>=0;e--)try{let t=JSON.parse(s[e][1].trim());if(t.verdict!=="approved"&&t.verdict!=="changes-requested")continue;return {verdict:t.verdict,whatChanged:Array.isArray(t.whatChanged)?t.whatChanged:[],alreadyVerified:Array.isArray(t.alreadyVerified)?t.alreadyVerified:[],openThreads:Array.isArray(t.openThreads)?t.openThreads:[],corrections:Array.isArray(t.corrections)?t.corrections:[]}}catch{continue}return null}var ce=class{rootDir;orchestrationsDir;constructor(s){this.rootDir=s,this.orchestrationsDir=x.join(s,".paradigm","orchestrations"),this.ensureOrchestrationDir();}async startBackground(s,e={}){let t=this.generateId(),n=x.join(this.orchestrationsDir,`${t}.output`),o=x.join(this.orchestrationsDir,`${t}.log`),r={id:t,task:s,status:"pending",mode:e.mode||"faceted",created:new Date().toISOString(),outputFile:n,logFile:o,artifacts:[]};return this.saveOrchestration(r),this.spawnOrchestration(t,s,e),r}getOrchestration(s){let e=x.join(this.orchestrationsDir,`${s}.yaml`);if(!v.existsSync(e))return null;try{let t=v.readFileSync(e,"utf-8");return L.load(t)}catch{return null}}listOrchestrations(s={}){let e=v.readdirSync(this.orchestrationsDir).filter(n=>n.endsWith(".yaml")&&!n.includes("output")&&!n.includes("log")).sort().reverse(),t=[];for(let n of e){if(s.limit&&t.length>=s.limit)break;let o=x.join(this.orchestrationsDir,n);try{let r=v.readFileSync(o,"utf-8"),l=L.load(r);if(s.status&&!(Array.isArray(s.status)?s.status:[s.status]).includes(l.status))continue;t.push(l);}catch{}}return t}getRunning(){return this.listOrchestrations({status:"running"})}getOutput(s,e={}){let t=this.getOrchestration(s);if(!t||!v.existsSync(t.outputFile))return "";let n=v.readFileSync(t.outputFile,"utf-8");return e.lines?n.split(`
|
|
26
|
-
`).slice(-e.lines).join(`
|
|
27
|
-
`):n}async accept(s,e={}){let t=this.getOrchestration(s);if(!t)return false;if(t.status!=="completed")throw new Error(`Cannot accept orchestration in '${t.status}' status`);return t.status="accepted",this.saveOrchestration(t),true}async reject(s,e={}){let t=this.getOrchestration(s);if(!t)return false;if(t.status!=="completed")throw new Error(`Cannot reject orchestration in '${t.status}' status`);if(t.status="rejected",t.error=e.reason,this.saveOrchestration(t),e.cleanup&&t.artifacts.length>0){for(let n of t.artifacts)if(n.action==="created"){let o=x.join(this.rootDir,n.path);v.existsSync(o)&&v.unlinkSync(o);}}return true}async getDiff(s){let e=this.getOrchestration(s);if(!e)return "";if(e.artifacts.length===0)return "No file changes in this orchestration.";let t=[];t.push(`Orchestration: ${s}`),t.push(`Task: ${e.task}`),t.push(`Status: ${e.status}`),t.push(""),t.push("Files:");for(let n of e.artifacts){let o=n.action==="created"?"+":n.action==="modified"?"~":"-";t.push(` ${o} ${n.path}`);}return t.join(`
|
|
28
|
-
`)}markComplete(s,e){let t=this.getOrchestration(s);if(t){t.status=e.success?"completed":"failed",t.completed=new Date().toISOString(),t.result=e,t.parallelBuilderStats=e.parallelBuilderStats;for(let n of e.agentResults)if(n.relay?.outputs.artifacts)for(let o of n.relay.outputs.artifacts)t.artifacts.push(o);this.saveOrchestration(t);}}async notify(s,e=["bell"]){let t=this.getOrchestration(s);if(t)for(let n of e)switch(n){case "bell":process.stdout.write("\x07");break;case "desktop":try{process.platform==="darwin"?spawn("osascript",["-e",`display notification "Orchestration ${t.status}: ${t.task.slice(0,50)}" with title "Paradigm"`]):spawn("notify-send",["Paradigm",`Orchestration ${t.status}: ${t.task.slice(0,50)}`]);}catch{}break;case "file":let o=x.join(this.orchestrationsDir,`${s}.status`);v.writeFileSync(o,JSON.stringify({id:s,status:t.status,completed:t.completed,task:t.task}));break;}}ensureOrchestrationDir(){v.existsSync(this.orchestrationsDir)||v.mkdirSync(this.orchestrationsDir,{recursive:true});}generateId(){let s=new Date().toISOString().slice(0,10),e=Date.now().toString(36),t=Math.random().toString(36).substring(2,6);return `orch-${s}-${e}-${t}`}saveOrchestration(s){let e=x.join(this.orchestrationsDir,`${s.id}.yaml`);v.writeFileSync(e,L.dump(s));}spawnOrchestration(s,e,t){let n=this.getOrchestration(s);n&&(n.status="running",n.started=new Date().toISOString(),this.saveOrchestration(n)),(async()=>{try{let o=new V(this.rootDir);await o.initialize();let r=v.createWriteStream(n.outputFile,{flags:"a"}),l=await o.orchestrate(e,{...t,onMessage:(i,a)=>{a.type==="text"&&r.write(`[${i}] ${a.content}
|
|
29
|
-
`),t.onMessage?.(i,a);},onAgentStart:(i,a,p)=>{r.write(`
|
|
30
|
-
\u25B6 ${i}: ${a}
|
|
31
|
-
`),t.onAgentStart?.(i,a,p);},onAgentComplete:(i,a,p)=>{let c=a.success?"\u2713":"\u2717";r.write(`${c} ${i} completed
|
|
32
|
-
`),t.onAgentComplete?.(i,a,p);}});r.end(),this.markComplete(s,l),t.notify&&await this.notify(s,t.notifyMethods||["bell"]);}catch(o){let r=this.getOrchestration(s);r&&(r.status="failed",r.error=o instanceof Error?o.message:String(o),r.completed=new Date().toISOString(),this.saveOrchestration(r));}})();}};export{V as a,ce as b};
|
package/dist/chunk-FRQRREJ6.js
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {c,b as b$1}from'./chunk-3KVVC4WV.js';import {i as i$1,h}from'./chunk-QEQCPVF5.js';import {z as z$1,i,c as c$1,f as f$1,j}from'./chunk-KAFQA7HV.js';import {g as g$1,f as f$2}from'./chunk-QGZRM6ZB.js';import {b,a,d}from'./chunk-5TAVYPOV.js';import*as f from'fs';import*as g from'path';import*as W from'js-yaml';import*as T from'os';function z(e){return g.join(e,G,at)}function ct(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${e}-${t}`}function E(e,t){let n={id:ct(),timestamp:new Date().toISOString(),...t};_.push(n),_.length>v&&(_=_.slice(-v));try{let r=g.join(e,G);f.mkdirSync(r,{recursive:!0});let o=z(e);f.appendFileSync(o,JSON.stringify(n)+`
|
|
3
|
-
`,"utf8"),lt(o);}catch{}return n}function lt(e){try{if(f.statSync(e).size>512*1024){let r=f.readFileSync(e,"utf8").trim().split(`
|
|
4
|
-
`);if(r.length>v){let o=r.slice(-v);f.writeFileSync(e,o.join(`
|
|
5
|
-
`)+`
|
|
6
|
-
`,"utf8");}}}catch{}}function $t(e,t){let n=ft(e);return t?.type&&(n=n.filter(r=>r.type===t.type)),t?.source&&(n=n.filter(r=>r.source===t.source)),t?.symbol&&(n=n.filter(r=>r.symbols?.includes(t.symbol))),t?.agent&&(n=n.filter(r=>r.agent===t.agent)),t?.since&&(n=n.filter(r=>r.timestamp>=t.since)),n.sort((r,o)=>o.timestamp.localeCompare(r.timestamp)),t?.limit&&(n=n.slice(0,t.limit)),n}function ft(e){let t=z(e);if(!f.existsSync(t))return [..._];try{return f.readFileSync(t,"utf8").trim().split(`
|
|
7
|
-
`).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return [..._]}}function 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)q(l,s)&&(r=Math.max(r,1));if(n.paths?.length&&e.path){for(let l of n.paths)if(q(l,e.path)){o=1;break}}if(n.concepts?.length){let l=[e.context||"",...e.keywords||[],e.type||""].join(" ").toLowerCase(),s=0;for(let m of n.concepts)m&&l.includes(m.toLowerCase())&&s++;n.concepts.length>0&&(i=s/n.concepts.length);}if(n.signals?.length){for(let l of n.signals)if(l.type===e.type){a=1;break}}let d=[r,o,i,a].sort((l,s)=>s-l),u=d[0]*.5+d[1]*.2+d[2]*.15+d[3]*.15,c=n.threshold??.6;return {agentId:t,score:u,breakdown:{symbolMatch:r,pathMatch:o,conceptMatch:i,signalMatch:a},shouldNominate:u>=c,quietReason:u<c?"below-threshold":void 0}}function q(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var G,at,v,_,H=b(()=>{G=".paradigm/events",at="stream.jsonl",v=1e3,_=[];});function O(e){let t=g.join(e,dt);if(!f.existsSync(t))return {...b$1};try{let n=f.readFileSync(t,"utf8"),r=W.load(n);return ut(b$1,r)}catch{return {...b$1}}}function ut(e,t){let n={...e};if(t.version&&(n.version=t.version),t.default_ring&&(n.default_ring=t.default_ring),t.observation&&(n.observation={allow:t.observation.allow||e.observation?.allow,deny:[...e.observation?.deny||[],...t.observation.deny||[]].filter((r,o,i)=>i.indexOf(r)===o)}),t.streams){n.streams={...e.streams};for(let r of ["work_log","learning_journal","team_decisions"])t.streams[r]&&(n.streams[r]={...e.streams?.[r],...t.streams[r],deny_content:[...e.streams?.[r]?.deny_content||[],...t.streams[r]?.deny_content||[]].filter((o,i,a)=>a.indexOf(o)===i)});}return t.upstream&&(n.upstream={...e.upstream,...t.upstream}),t.network&&(n.network={...e.network,...t.network}),t.agent_overrides&&(n.agent_overrides={...e.agent_overrides,...t.agent_overrides}),t.deployment&&(n.deployment={...e.deployment,...t.deployment}),n}function C(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(o=>R(o,t))||e.observation?.deny?.some(r=>R(r,t))?false:e.observation?.allow?.length?e.observation.allow.some(r=>R(r,t)):true}function Ct(e,t,n){let r=t.streams?.[n];if(!r)return {filtered:e,redacted:[]};let o=[],i=e;if(r.redaction)for(let a of r.redaction)try{let d=new RegExp(a.pattern,"gi"),u=i.match(d);u&&(o.push(...u),i=i.replace(d,a.replacement||"[REDACTED]"));}catch{}return {filtered:i,redacted:o}}function R(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var dt,X=b(()=>{c();dt=".paradigm/data-policy.yaml";});function wt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function _t(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${e}-${t}`}function Q(e,t){let n=i(e),r=O(e),o=[];for(let c of n){if(!c.attention||!c$1(c.id,e)||t.path&&!C(r,t.path,c.id))continue;let l=Y(t,c.id,c.attention);l.shouldNominate&&o.push({profile:c,score:l});}if(o.length===0)return {nominations:[],debates:[]};let i$1=P(e,{since:new Date(Date.now()-3e4).toISOString()}),a=o.filter(({profile:c})=>!i$1.find(s=>s.agent===c.id&&s.brief===K(c,t,{...o.find(m=>m.profile.id===c.id).score})));if(a.length===0)return {nominations:[],debates:[]};let d=a.map(({profile:c,score:l})=>{let s=Et(t,l),m=Nt(c,t);return {id:wt(),agent:c.id,relevance:l.score,urgency:s,type:m,brief:K(c,t,l),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});xt(e,d);let u=kt(e,d);return u.length>0&&vt(e,u),{nominations:d,debates:u}}function Et(e,t){return e.severity==="critical"?"critical":e.severity==="error"||e.type==="compliance-violation"||e.type==="error-encountered"?"high":e.type==="gate-added"||e.type==="route-created"||t.score>=.9?"medium":"low"}function Nt(e,t){let n=e.collaboration?.stance;return t.type==="compliance-violation"||t.type==="error-encountered"?"warning":t.type==="gate-added"||t.type==="route-created"?"observation":n==="advisory"||n==="lead"?"suggestion":"observation"}function K(e,t,n){let r=e.role||e.id;switch(t.type){case "gate-checked":return `${r}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${r}: ${t.path||"File"} modified \u2014 review for ${e.id==="security"?"security implications":e.id==="tester"?"test coverage":e.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${r}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${r}: New route ${t.symbols?.join(", ")||""} \u2014 ${e.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${r}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${e.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${r}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${r}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${r}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let o=n.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:n.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${r}: ${o}`}}}function kt(e,t){if(t.length<2)return [];let n=[],r=new Map;for(let o of t)for(let i of o.triggered_by){let a=r.get(i)||[];a.push(o),r.set(i,a);}for(let[o,i]of r){if(i.length<2||new Set(i.map(c=>c.agent)).size<2)continue;let d=new Set(i.map(c=>c.type)),u=d.size>1&&d.has("warning")&&d.has("suggestion");n.push({id:_t(),topic:`Multiple agents responded to event ${o}`,nominations:i.map(c=>c.id),type:u?"conflicting":"complementary",overlap_events:[o]});}return n}function M(e){return g.join(e,w,mt)}function I(e){return g.join(e,w,gt)}function xt(e,t){try{let n=g.join(e,w);f.mkdirSync(n,{recursive:!0});let r=M(e),o=t.map(a=>JSON.stringify(a)).join(`
|
|
8
|
-
`)+`
|
|
9
|
-
`;f.appendFileSync(r,o,"utf8"),Z(r,pt);let{nominationTtlDays:i}=A(e);tt(r,i*24*60*60*1e3);}catch{}}function vt(e,t){try{let n=g.join(e,w);f.mkdirSync(n,{recursive:!0});let r=I(e),o=t.map(a=>JSON.stringify(a)).join(`
|
|
10
|
-
`)+`
|
|
11
|
-
`;f.appendFileSync(r,o,"utf8"),Z(r,ht);let{debateTtlDays:i}=A(e);tt(r,i*24*60*60*1e3);}catch{}}function Z(e,t){try{let r=f.readFileSync(e,"utf8").trim().split(`
|
|
12
|
-
`).filter(o=>o.trim());if(r.length>t){let o=r.slice(-t);f.writeFileSync(e,o.join(`
|
|
13
|
-
`)+`
|
|
14
|
-
`,"utf8");}}catch{}}function A(e){let t={nominationTtlDays:yt,debateTtlDays:bt};try{let n=g.join(e,".paradigm","config.yaml");if(!f.existsSync(n))return t;let r=a("js-yaml"),o=f.readFileSync(n,"utf8"),a$1=r.load(o)?.ambient;return a$1?{nominationTtlDays:typeof a$1["nomination-ttl-days"]=="number"?a$1["nomination-ttl-days"]:t.nominationTtlDays,debateTtlDays:typeof a$1["debate-ttl-days"]=="number"?a$1["debate-ttl-days"]:t.debateTtlDays}:t}catch{return t}}function tt(e,t){try{if(!f.existsSync(e))return;let r=f.readFileSync(e,"utf8").trim().split(`
|
|
15
|
-
`).filter(a=>a.trim());if(r.length<=St)return;let o=Date.now()-t,i=r.filter(a=>{try{let d=JSON.parse(a);return (d.timestamp?new Date(d.timestamp).getTime():Date.now())>=o}catch{return !0}});i.length<r.length&&f.writeFileSync(e,i.join(`
|
|
16
|
-
`)+`
|
|
17
|
-
`,"utf8");}catch{}}function P(e,t){let n=M(e);if(!f.existsSync(n))return [];try{let o=f.readFileSync(n,"utf8").trim().split(`
|
|
18
|
-
`).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null);return t?.agent&&(o=o.filter(i=>i.agent===t.agent)),t?.urgency&&(o=o.filter(i=>i.urgency===t.urgency)),t?.surfaced!==void 0&&(o=o.filter(i=>i.surfaced===t.surfaced)),t?.pending_only&&(o=o.filter(i=>!i.engaged)),t?.since&&(o=o.filter(i=>i.timestamp>=t.since)),o.sort((i,a)=>a.timestamp.localeCompare(i.timestamp)),t?.limit&&(o=o.slice(0,t.limit)),o}catch{return []}}function Ut(e){let t=I(e);if(!f.existsSync(t))return [];try{return f.readFileSync(t,"utf8").trim().split(`
|
|
19
|
-
`).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function Bt(e,t,n,r){let o=M(e);if(!f.existsSync(o))return false;try{let a=f.readFileSync(o,"utf8").trim().split(`
|
|
20
|
-
`),d=!1,u=a.map(c=>{try{let l=JSON.parse(c);return l.id===t?(l.engaged=!0,l.response=n,r&&(l.reason=r),d=!0,JSON.stringify(l)):c}catch{return c}});if(d&&(f.writeFileSync(o,u.join(`
|
|
21
|
-
`)+`
|
|
22
|
-
`,"utf8"),n==="accepted"||n==="dismissed")){let c=JSON.parse(a.find(s=>{try{return JSON.parse(s).id===t}catch{return !1}}));i(e).find(s=>s.id===c.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&E(e,{type:"work-completed",source:"agent-action",agent:c.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return d}catch{return false}}function qt(e,t,n,r){let o=I(e);if(!f.existsSync(o))return false;try{let a=f.readFileSync(o,"utf8").trim().split(`
|
|
23
|
-
`),d=!1,u=a.map(c=>{try{let l=JSON.parse(c);if(l.id===t){l.resolution={chosen:n,reason:r,resolved_by:"human",resolved_at:new Date().toISOString()},d=!0;let s=l.nominations.filter(m=>m!==n);for(let m of s){let p=P(e).find(h=>h.id===m);p&&E(e,{type:"work-completed",source:"agent-action",agent:p.agent,context:`Debate ${t} resolved \u2014 nomination ${m} not chosen`,data:{debate_id:t,chosen:n,reason:r}});}return JSON.stringify(l)}return c}catch{return c}});return d&&f.writeFileSync(o,u.join(`
|
|
24
|
-
`)+`
|
|
25
|
-
`,"utf8"),d}catch{return false}}function Gt(e){let t=g.join(e,w,".last-processed"),n="";try{f.existsSync(t)&&(n=f.readFileSync(t,"utf8").trim());}catch{}let r=g.join(e,w,"stream.jsonl");if(!f.existsSync(r))return {processed:0,nominations:[]};let o=[];try{o=f.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 d=[],u=a.slice(0,50);for(let l of u){let{nominations:s}=Q(e,l);d.push(...s);}let c=u[u.length-1];try{f.mkdirSync(g.join(e,w),{recursive:!0}),f.writeFileSync(t,c.id,"utf8");}catch{}return {processed:u.length,nominations:d}}function zt(e,t,n){let r=O(e);if(t.path&&!C(r,t.path))return {event:E(e,t),nominations:[],debates:[]};let o=E(e,t);if(n?.skipNominations)return {event:o,nominations:[],debates:[]};let{nominations:i,debates:a}=Q(e,o);return i.length>0&&Tt(e,i),{event:o,nominations:i,debates:a}}function Yt(e,t){let n=f$1(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,u=P(e,{agent:t}).filter(b=>b.engaged||Date.now()-new Date(b.timestamp).getTime()<i).filter(b=>b.engaged);if(u.length<5)return {adjusted:false,oldThreshold:r,newThreshold:r,reason:`Insufficient data (${u.length}/5 engaged nominations)`};let c=u.filter(b=>b.response==="accepted").length,l=u.filter(b=>b.response==="dismissed").length,s=c/u.length,m=l/u.length,p=r,h="No adjustment needed";if(m>.6?(p=Math.min(.95,r+.05),h=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):s>.8&&(p=Math.max(.2,r-.05),h=`High accept rate (${(s*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),p===r)return {adjusted:false,oldThreshold:r,newThreshold:p,reason:h};n.attention.threshold=p;let S=g.join(e,".paradigm/agents",`${t}.agent`),N=f.existsSync(S)?"project":"global";return j(t,n,N,e),E(e,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${r.toFixed(2)} \u2192 ${p.toFixed(2)} (${h})`,data:{old_threshold:r,new_threshold:p,accept_rate:s,dismiss_rate:m}}),{adjusted:true,oldThreshold:r,newThreshold:p,reason:h}}function jt(e,t){let{nominationTtlDays:n}=A(e),r=n*24*60*60*1e3,i=P(e,{agent:t}).filter(s=>s.engaged||Date.now()-new Date(s.timestamp).getTime()<r),a=i.filter(s=>s.response==="accepted").length,d=i.filter(s=>s.response==="dismissed").length,u=i.filter(s=>s.response==="deferred").length,c=i.filter(s=>!s.engaged).length,l=a+d+u;return {total:i.length,accepted:a,dismissed:d,deferred:u,pending:c,acceptRate:l>0?a/l:0}}function Ht(e){let n=i(e).filter(s=>c$1(s.id,e)).map(s=>{let m=jt(e,s.id),p=0;try{let h=g.join(T.homedir(),".paradigm","notebooks",s.id);f.existsSync(h)&&(p=f.readdirSync(h).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),d=n.reduce((s,m)=>s+m.notebookCount,0),u=n.reduce((s,m)=>s+m.transferableCount,0),c=n.reduce((s,m)=>s+m.totalNominations,0),l;return c<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:d,totalTransferable:u},healthStatus:l}}function Tt(e,t){if(t.length===0)return;let n=g.join(T.homedir(),".paradigm","score","outbox");if(f.existsSync(n))try{let r=g.join(n,`nom-${Date.now()}.json`),o={type:"nomination_forward",nominations:t.map(i=>({...i})),origin:At(e),timestamp:new Date().toISOString()};f.writeFileSync(r,JSON.stringify(o),"utf8");}catch{}}function At(e){try{let t=g.join(e,".paradigm","config.yaml");if(f.existsSync(t)){let r=f.readFileSync(t,"utf8").match(/project:\s*(.+)/);if(r)return r[1].trim()}}catch{}return g.basename(e)}function Vt(e,t){let n,r,o;try{let c=(g$1(),d(f$2)),l=(i$1(),d(h));n=c.loadJournalEntries,r=l.addNotebookEntry,o=l.normalizeConcept;}catch{return {promoted:0,entries:[]}}let i=n(t,{trigger:"pattern_discovered",limit:100}),a=n(t,{trigger:"human_feedback",limit:100}),d$1=[...i,...a],u=[];for(let c of d$1)if(!c.promoted_to_notebook&&!((c.confidence_after??0)<.8))try{let{entry:l}=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"]).map(o).filter(Boolean),provenance:{source:"lore",loreEntryId:c.id,createdBy:t}},"global",e);u.push({journalId:c.id,notebookId:l.id});try{let s=g.join(T.homedir(),".paradigm","agents",t,"journal");if(f.existsSync(s)){let m=f.readdirSync(s).filter(p=>p.endsWith(".yaml"));for(let p of m){let h=g.join(s,p),S=f.readFileSync(h,"utf8");if(S.includes(c.id)){let N=S.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${l.id}"`);if(N===S){let b=S.trimEnd().split(`
|
|
27
|
-
`);b.push(`promoted_to_notebook: "${l.id}"`),f.writeFileSync(h,b.join(`
|
|
28
|
-
`)+`
|
|
29
|
-
`,"utf8");}else f.writeFileSync(h,N,"utf8");break}}}}catch{}}catch{}return {promoted:u.length,entries:u}}function Wt(e){let t=g.join(e,Pt),n={default_min_urgency:"low",enable_debates:true};if(!f.existsSync(t))return n;try{let r=a("js-yaml"),o=f.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(d=>d.agent===o.agent);if(a){if(a.always_show)return true;if(a.mute_unless?.length&&!a.mute_unless.some(u=>o.urgency===u||o.type===u))return false;if(a.min_urgency){let d=n[a.min_urgency]??3;return i<=d}}}return i<=r})}var w,mt,gt,pt,ht,yt,bt,St,Pt,Dt=b(()=>{H();X();z$1();w=".paradigm/events",mt="nominations.jsonl",gt="debates.jsonl",pt=500,ht=200,yt=7,bt=14,St=100;Pt=".paradigm/surfacing.yaml";});export{$t as a,H as b,O as c,Ct as d,X as e,Q as f,kt as g,xt as h,P as i,Ut as j,Bt as k,qt as l,Gt as m,zt as n,Yt as o,jt as p,Ht as q,Tt as r,Vt as s,Wt as t,Xt as u,Dt as v};
|
package/dist/chunk-QEQCPVF5.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {c,b as b$1}from'./chunk-5TAVYPOV.js';import*as i from'fs';import*as l from'path';import*as w from'os';import*as f from'js-yaml';var z={};c(z,{addNotebookEntry:()=>C,classifyNotebookScope:()=>E,incrementApplied:()=>v,loadNotebookEntries:()=>N,normalizeConcept:()=>u,promoteFromLore:()=>P,searchNotebooks:()=>$});function u(o){if(!o)return "";let t=o.trim();return t=t.replace(/^symbol:/i,""),t=t.replace(/^[#$^!~@&%?]/,""),t.trim().toLowerCase()}function N(o,t,n){let s=new Map,a=l.join(y,o);k(a,s);let e=l.join(t,b,o);k(e,s);let r=Array.from(s.values());if(n?.concepts&&n.concepts.length>0){let p=new Set(n.concepts.map(u));r=r.filter(c=>c.concepts.some(m=>p.has(u(m))));}if(n?.tags&&n.tags.length>0){let p=new Set(n.tags.map(c=>c.toLowerCase()));r=r.filter(c=>c.tags.some(m=>p.has(m.toLowerCase())));}return r.sort((p,c)=>c.appliedCount-p.appliedCount)}function k(o,t){if(i.existsSync(o))try{let n=i.readdirSync(o).filter(s=>s.startsWith(_)&&s.endsWith(h));for(let s of n)try{let a=i.readFileSync(l.join(o,s),"utf-8"),e=f.load(a);e?.id&&t.set(e.id,e);}catch{}}catch{}}function $(o,t,n){let s=N(o,n),a=t.toLowerCase();return s.filter(e=>e.context.toLowerCase().includes(a)||e.snippet.toLowerCase().includes(a)||e.concepts.some(r=>r.toLowerCase().includes(a))||e.tags.some(r=>r.toLowerCase().includes(a)))}function E(o){let t=[o.context,o.snippet,...o.concepts,...o.tags].join(" ").toLowerCase();return ["paradigm","mcp_","mcp tool",".paradigm/","lore entry","lore record","aspect","^gate","portal.yaml",".purpose","sentinel","symphony","ambient nomination","paradigm_"," pan ","agent notebook","concept anchor","symbol system","work log","knowledge stream","nevr.land","neverland"].some(s=>t.includes(s))?"platform-specific":/[#$^!~][a-z][a-z0-9-]{2,}/.test(t)||/\/[a-z0-9_-]{2,}\/[a-z0-9_-]/.test(t)?"project-specific":"generalizable"}function C(o,t,n,s){let a=new Date().toISOString(),e=(t.concepts[0]||t.context.split(" ").slice(0,4).join(" ")||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),p=`nb-${o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}-${e}`,c=t.scope??E({context:t.context,snippet:t.snippet,concepts:t.concepts,tags:t.tags}),m=Array.from(new Set((t.concepts||[]).map(u).filter(Boolean))),g={...t,concepts:m,id:p,scope:c,publishable:t.publishable??true,appliedCount:0,created:a,updated:a},d=n==="global"?l.join(y,o):l.join(s||process.cwd(),b,o);i.existsSync(d)||i.mkdirSync(d,{recursive:true});let j=`${p}${h}`,S=l.join(d,j),x=f.dump(g,{lineWidth:120,noRefs:true,sortKeys:false});return i.writeFileSync(S,x,"utf-8"),{entry:g,filePath:S}}async function P(o,t,n,s="global"){let{loadLoreEntry:a}=await import('./lore-loader-PXFKMKAN.js'),e=await a(n,t);if(!e)return null;let r=[];if(e.symbols_touched)for(let m of e.symbols_touched){let g=m.replace(/^[#$^!~]/,"").toLowerCase();r.push(g);}let p=e.summary||"";e.body&&(p+=`
|
|
3
|
-
|
|
4
|
-
`+e.body);let c={source:"lore",loreEntryId:t,originProject:l.basename(n),createdBy:o};return C(o,{context:e.title||`Promoted from ${t}`,snippet:p,provenance:c,confidence:e.confidence??.7,concepts:r,tags:e.tags||[]},s,n)}function v(o,t,n){let s=l.join(n,b,o),a=l.join(y,o);for(let e of [s,a]){let r=l.join(e,`${t}${h}`);if(i.existsSync(r))try{let p=i.readFileSync(r,"utf-8"),c=f.load(p);if(c)return c.appliedCount=(c.appliedCount||0)+1,c.updated=new Date().toISOString(),i.writeFileSync(r,f.dump(c,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var y,b,_,h,T=b$1(()=>{y=l.join(w.homedir(),".paradigm","notebooks"),b=".paradigm/notebooks",_="nb-",h=".yaml";});export{u as a,N as b,$ as c,E as d,C as e,P as f,v as g,z as h,T as i};
|
package/dist/chunk-QGZRM6ZB.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {c as c$1,b as b$1}from'./chunk-5TAVYPOV.js';import*as s from'fs';import*as c from'path';import*as g from'js-yaml';var b={};c$1(b,{getJournalStats:()=>S,loadAllJournalEntries:()=>E,loadJournalEntries:()=>f,loadJournalEntry:()=>J,recordJournalEntry:()=>h});function m(e){let r=process.env.HOME||process.env.USERPROFILE||"";return c.join(r,".paradigm","agents",e,"journal")}function y(){let e=new Date,r=e.toISOString().slice(0,10),i=e.toISOString().slice(11,19).replace(/:/g,""),o=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `LJ-${r}-${i}-${o}`}function h(e,r){let i=new Date,o=y(),a={id:o,agent:e,timestamp:i.toISOString(),...r},t=m(e);s.mkdirSync(t,{recursive:true});let n=c.join(t,`${o}.yaml`);return s.writeFileSync(n,g.dump(a,{lineWidth:120,noRefs:true}),"utf8"),a}function f(e,r){let i=m(e);if(!s.existsSync(i))return [];let o=[],a=s.readdirSync(i).filter(n=>n.endsWith(".yaml"));for(let n of a)try{let l=s.readFileSync(c.join(i,n),"utf8"),u=g.load(l);u&&u.id&&o.push(u);}catch{}let t=o;return r?.trigger&&(t=t.filter(n=>n.trigger===r.trigger)),r?.project&&(t=t.filter(n=>n.project===r.project)),r?.transferable!==void 0&&(t=t.filter(n=>n.transferable===r.transferable)),r?.tag&&(t=t.filter(n=>n.tags?.some(l=>l.startsWith(r.tag)))),r?.dateFrom&&(t=t.filter(n=>n.timestamp>=r.dateFrom)),r?.dateTo&&(t=t.filter(n=>n.timestamp<=r.dateTo)),t.sort((n,l)=>l.timestamp.localeCompare(n.timestamp)),r?.limit&&(t=t.slice(0,r.limit)),t}function J(e,r){let i=m(e),o=c.join(i,`${r}.yaml`);if(!s.existsSync(o))return null;let a=s.readFileSync(o,"utf8");return g.load(a)}function E(e){let r=process.env.HOME||process.env.USERPROFILE||"",i=c.join(r,".paradigm","agents");if(!s.existsSync(i))return [];let o=[],a=s.readdirSync(i,{withFileTypes:true}).filter(t=>t.isDirectory());for(let t of a){if(e?.agent&&t.name!==e.agent)continue;let n=f(t.name,e);o.push(...n);}return o.sort((t,n)=>n.timestamp.localeCompare(t.timestamp)),e?.limit?o.slice(0,e.limit):o}function S(e){let r=f(e),i={},o={},a=0;for(let t of r)i[t.trigger]=(i[t.trigger]||0)+1,o[t.project]=(o[t.project]||0)+1,t.transferable&&a++;return {total:r.length,byTrigger:i,byProject:o,transferableCount:a,recentInsights:r.slice(0,5).map(t=>({id:t.id,trigger:t.trigger,insight:t.insight.slice(0,200),timestamp:t.timestamp}))}}var j=b$1(()=>{});export{h as a,f as b,J as c,E as d,S as e,b as f,j as g};
|