@a-company/paradigm 6.6.6 → 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-JHDCVHB2.js → accept-orchestration-WMGFGYDK.js} +1 -1
- package/dist/{agent-loader-VGBPL3TH.js → agent-loader-Z753DQWH.js} +1 -1
- package/dist/{agents-suggest-IKY6VD2R.js → agents-suggest-WZEGQT5E.js} +1 -1
- package/dist/{ambient-FNNFB4AP.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-3COP6YTD.js +2 -0
- package/dist/chunk-33ERV2MW.js +18 -0
- package/dist/chunk-4CGPLLWQ.js +30 -0
- package/dist/chunk-6HVOZANP.js +4 -0
- package/dist/chunk-ACJWUOMA.js +3 -0
- package/dist/chunk-B5KLSBOZ.js +2 -0
- package/dist/chunk-CHSU6LTR.js +2 -0
- package/dist/chunk-DLMDHS2X.js +10 -0
- package/dist/chunk-ECO3LHCE.js +2 -0
- package/dist/chunk-EG22HDXI.js +33 -0
- package/dist/{chunk-5RFISGUW.js → chunk-G6DK3ND3.js} +250 -25
- package/dist/{chunk-GD4F2HC6.js → chunk-H55W26AR.js} +1 -1
- package/dist/chunk-HSY75GRR.js +6 -0
- package/dist/chunk-KAUGQMXU.js +4 -0
- package/dist/chunk-KP5VOYAH.js +20 -0
- package/dist/chunk-OIYJUU6T.js +25 -0
- package/dist/chunk-RDWWSQGH.js +142 -0
- package/dist/chunk-RVXQNS6K.js +30 -0
- package/dist/chunk-VPNJL4LS.js +93 -0
- package/dist/{chunk-XKNJSPB5.js → chunk-W4BW7GXA.js} +1 -1
- package/dist/chunk-XPPFILCM.js +2 -0
- package/dist/chunk-YCDOA5IQ.js +18 -0
- package/dist/chunk-YQK3XU63.js +504 -0
- package/dist/{chunk-TQOT2LBO.js → chunk-YXLGVOZO.js} +1 -1
- package/dist/chunk-ZSWXLFN7.js +12 -0
- package/dist/{compliance-J3VOV445.js → compliance-4P3EE5OA.js} +1 -1
- package/dist/{diff-ANKTFDRA.js → diff-VBVIUNL5.js} +1 -1
- package/dist/{docs-TSAAS4W3.js → docs-NTP6UENF.js} +1 -1
- package/dist/doctor-CBZYYQQH.js +2 -0
- package/dist/{hooks-45WDP6QS.js → hooks-AXBWYJ5V.js} +1 -1
- package/dist/index.js +6 -6
- package/dist/journal-loader-CNNA4EAU.js +2 -0
- package/dist/lore-loader-HAZ5FRLP.js +2 -0
- package/dist/mcp.js +3 -3
- package/dist/{migrate-R64OQGSM.js → migrate-5M4KUQ2L.js} +1 -1
- package/dist/nomination-engine-ORHH4L2W.js +2 -0
- package/dist/{nomination-engine-NCLTGMAK.js → nomination-engine-YRHZZZUN.js} +1 -1
- package/dist/notebook-loader-TZVIMNDJ.js +2 -0
- package/dist/orchestrate-MLUGQOEJ.js +8 -0
- package/dist/orchestration-O2OVPTIZ.js +2 -0
- package/dist/{platform-server-ANOALDPL.js → platform-server-Y6TLEXR2.js} +1 -1
- package/dist/propose-block-ZEMEWJQF.js +2 -0
- package/dist/{providers-TBPOE4DI.js → providers-5EHD45C6.js} +1 -1
- package/dist/reindex-ZLDQBFUR.js +2 -0
- package/dist/{serve-3FMUWW5K.js → serve-XZ6GBUS3.js} +1 -1
- package/dist/session-tracker-BZ7FU4AT.js +2 -0
- package/dist/session-work-log-FF7CKMWP.js +2 -0
- package/dist/session-work-log-T2IE4Y4T.js +2 -0
- package/dist/{shift-TNA2E5O7.js → shift-PM4GI736.js} +2 -2
- package/dist/solo-OWR3MX74.js +3 -0
- package/dist/{spawn-KKDDR6UR.js → spawn-PHA2SVQ3.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-H7HQAYGL.js +2 -0
- package/dist/task-loader-YZME4RKE.js +2 -0
- package/dist/task-settlement-HINBVZBE.js +3 -0
- package/dist/task-settlement-XC6E6JNT.js +3 -0
- package/dist/team-25LK6CWM.js +2 -0
- package/dist/team-funnel-RAJ6EDG3.js +2 -0
- package/dist/tools-GAU5WOEI.js +2 -0
- package/dist/university-content/notes/N-para-801-cid-becomes-real.md +60 -0
- package/dist/university-content/notes/N-para-801-falsifiable-self-improvement.md +66 -0
- package/dist/university-content/notes/N-para-801-honest-routing-and-the-method.md +57 -0
- package/dist/university-content/notes/N-para-801-orchestration-emits-dag.md +60 -0
- package/dist/university-content/notes/N-para-801-settlement-closes-the-loop.md +64 -0
- package/dist/university-content/notes/N-para-801-the-task-dag.md +93 -0
- package/dist/university-content/paths/LP-para-801.yaml +43 -0
- package/dist/university-content/quizzes/Q-para-801-cid-becomes-real.yaml +54 -0
- package/dist/university-content/quizzes/Q-para-801-falsifiable-self-improvement.yaml +54 -0
- package/dist/university-content/quizzes/Q-para-801-honest-routing-and-the-method.yaml +54 -0
- package/dist/university-content/quizzes/Q-para-801-orchestration-emits-dag.yaml +54 -0
- package/dist/university-content/quizzes/Q-para-801-settlement-closes-the-loop.yaml +54 -0
- package/dist/university-content/quizzes/Q-para-801-the-task-dag.yaml +54 -0
- package/dist/university-ui/assets/{index-DrtbBC21.js → index-AbTjHBCf.js} +2 -2
- package/dist/university-ui/assets/{index-DrtbBC21.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-AI42BOM5.js +0 -35
- package/dist/chunk-3OXR6F65.js +0 -666
- package/dist/chunk-4N56FRNE.js +0 -29
- package/dist/chunk-6QXBXZF6.js +0 -3
- package/dist/chunk-AMLD7IYC.js +0 -10
- package/dist/chunk-DVZWCXB6.js +0 -2
- package/dist/chunk-F6E3HW45.js +0 -14
- package/dist/chunk-K7X3Z3GL.js +0 -4
- package/dist/chunk-LAYBUKMB.js +0 -14
- package/dist/chunk-MU5YWTNE.js +0 -24
- package/dist/chunk-PMKZMCTS.js +0 -111
- package/dist/chunk-QGZRM6ZB.js +0 -2
- package/dist/chunk-XQLO5URP.js +0 -11
- package/dist/doctor-L5XZENCF.js +0 -2
- package/dist/journal-loader-GLH7XFTK.js +0 -2
- package/dist/lore-loader-D2ISOASW.js +0 -2
- package/dist/notebook-loader-3J2OFMS3.js +0 -2
- package/dist/orchestrate-UG5QXNAU.js +0 -8
- package/dist/reindex-PTIQ2UGY.js +0 -2
- package/dist/session-tracker-HHNY6J4I.js +0 -2
- package/dist/session-work-log-MEJ33TYD.js +0 -2
- package/dist/session-work-log-ZVVJGO7X.js +0 -2
- package/dist/task-loader-NZFDTUQ5.js +0 -2
- package/dist/team-PEGP6F7S.js +0 -2
- package/dist/tools-PUSDXUYE.js +0 -2
- /package/dist/{chunk-HXGYVS2N.js → chunk-ECLUYHAR.js} +0 -0
- /package/dist/{chunk-CVPKQ3JH.js → chunk-HE2NA5QF.js} +0 -0
package/dist/chunk-4N56FRNE.js
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {c,b as b$1}from'./chunk-3KVVC4WV.js';import {z as z$1,i,c as c$1,f,j}from'./chunk-KAFQA7HV.js';import {g as g$1,f as f$1}from'./chunk-QGZRM6ZB.js';import {h,g as g$2}from'./chunk-K7X3Z3GL.js';import {b,a,d as d$1}from'./chunk-5TAVYPOV.js';import*as d from'fs';import*as g from'path';import*as W from'js-yaml';import*as T from'os';function Y(e){return g.join(e,G,at)}function ct(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${e}-${t}`}function 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);d.mkdirSync(r,{recursive:!0});let o=Y(e);d.appendFileSync(o,JSON.stringify(n)+`
|
|
3
|
-
`,"utf8"),lt(o);}catch{}return n}function lt(e){try{if(d.statSync(e).size>512*1024){let r=d.readFileSync(e,"utf8").trim().split(`
|
|
4
|
-
`);if(r.length>v){let o=r.slice(-v);d.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=Y(e);if(!d.existsSync(t))return [..._];try{return d.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 H(e,t,n){let r=0,o=0,i=0,a=0;if(n.symbols?.length&&e.symbols?.length)for(let l of n.symbols)for(let s of e.symbols)B(l,s)&&(r=Math.max(r,1));if(n.paths?.length&&e.path){for(let l of n.paths)if(B(l,e.path)){o=1;break}}if(n.concepts?.length){let l=[e.context||"",...e.keywords||[],e.type||""].join(" ").toLowerCase(),s=0;for(let m of n.concepts)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 u=[r,o,i,a].sort((l,s)=>s-l),c=u[0]*.5+u[1]*.2+u[2]*.15+u[3]*.15,f=n.threshold??.6;return {agentId:t,score:c,breakdown:{symbolMatch:r,pathMatch:o,conceptMatch:i,signalMatch:a},shouldNominate:c>=f,quietReason:c<f?"below-threshold":void 0}}function B(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var G,at,v,_,z=b(()=>{G=".paradigm/events",at="stream.jsonl",v=1e3,_=[];});function O(e){let t=g.join(e,dt);if(!d.existsSync(t))return {...b$1};try{let n=d.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 u=new RegExp(a.pattern,"gi"),c=i.match(u);c&&(o.push(...c),i=i.replace(u,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 f of n){if(!f.attention||!c$1(f.id,e)||t.path&&!C(r,t.path,f.id))continue;let l=H(t,f.id,f.attention);l.shouldNominate&&o.push({profile:f,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:f})=>!i$1.find(s=>s.agent===f.id&&s.brief===K(f,t,{...o.find(m=>m.profile.id===f.id).score})));if(a.length===0)return {nominations:[],debates:[]};let u=a.map(({profile:f,score:l})=>{let s=Et(t,l),m=Nt(f,t);return {id:wt(),agent:f.id,relevance:l.score,urgency:s,type:m,brief:K(f,t,l),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});xt(e,u);let c=kt(e,u);return c.length>0&&vt(e,c),{nominations:u,debates:c}}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(f=>f.agent)).size<2)continue;let u=new Set(i.map(f=>f.type)),c=u.size>1&&u.has("warning")&&u.has("suggestion");n.push({id:_t(),topic:`Multiple agents responded to event ${o}`,nominations:i.map(f=>f.id),type:c?"conflicting":"complementary",overlap_events:[o]});}return n}function M(e){return g.join(e,S,mt)}function I(e){return g.join(e,S,gt)}function xt(e,t){try{let n=g.join(e,S);d.mkdirSync(n,{recursive:!0});let r=M(e),o=t.map(a=>JSON.stringify(a)).join(`
|
|
8
|
-
`)+`
|
|
9
|
-
`;d.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,S);d.mkdirSync(n,{recursive:!0});let r=I(e),o=t.map(a=>JSON.stringify(a)).join(`
|
|
10
|
-
`)+`
|
|
11
|
-
`;d.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=d.readFileSync(e,"utf8").trim().split(`
|
|
12
|
-
`).filter(o=>o.trim());if(r.length>t){let o=r.slice(-t);d.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(!d.existsSync(n))return t;let r=a("js-yaml"),o=d.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(!d.existsSync(e))return;let r=d.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 u=JSON.parse(a);return (u.timestamp?new Date(u.timestamp).getTime():Date.now())>=o}catch{return !0}});i.length<r.length&&d.writeFileSync(e,i.join(`
|
|
16
|
-
`)+`
|
|
17
|
-
`,"utf8");}catch{}}function P(e,t){let n=M(e);if(!d.existsSync(n))return [];try{let o=d.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(!d.existsSync(t))return [];try{return d.readFileSync(t,"utf8").trim().split(`
|
|
19
|
-
`).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function qt(e,t,n,r){let o=M(e);if(!d.existsSync(o))return false;try{let a=d.readFileSync(o,"utf8").trim().split(`
|
|
20
|
-
`),u=!1,c=a.map(f=>{try{let l=JSON.parse(f);return l.id===t?(l.engaged=!0,l.response=n,r&&(l.reason=r),u=!0,JSON.stringify(l)):f}catch{return f}});if(u&&(d.writeFileSync(o,c.join(`
|
|
21
|
-
`)+`
|
|
22
|
-
`,"utf8"),n==="accepted"||n==="dismissed")){let f=JSON.parse(a.find(s=>{try{return JSON.parse(s).id===t}catch{return !1}}));i(e).find(s=>s.id===f.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&E(e,{type:"work-completed",source:"agent-action",agent:f.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return u}catch{return false}}function Bt(e,t,n,r){let o=I(e);if(!d.existsSync(o))return false;try{let a=d.readFileSync(o,"utf8").trim().split(`
|
|
23
|
-
`),u=!1,c=a.map(f=>{try{let l=JSON.parse(f);if(l.id===t){l.resolution={chosen:n,reason:r,resolved_by:"human",resolved_at:new Date().toISOString()},u=!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 f}catch{return f}});return u&&d.writeFileSync(o,c.join(`
|
|
24
|
-
`)+`
|
|
25
|
-
`,"utf8"),u}catch{return false}}function Gt(e){let t=g.join(e,S,".last-processed"),n="";try{d.existsSync(t)&&(n=d.readFileSync(t,"utf8").trim());}catch{}let r=g.join(e,S,"stream.jsonl");if(!d.existsSync(r))return {processed:0,nominations:[]};let o=[];try{o=d.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 u=[],c=a.slice(0,50);for(let l of c){let{nominations:s}=Q(e,l);u.push(...s);}let f=c[c.length-1];try{d.mkdirSync(g.join(e,S),{recursive:!0}),d.writeFileSync(t,f.id,"utf8");}catch{}return {processed:c.length,nominations:u}}function Yt(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 Ht(e,t){let n=f(e,t);if(!n?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let r=n.attention.threshold??.6,{nominationTtlDays:o}=A(e),i=o*24*60*60*1e3,c=P(e,{agent:t}).filter(b=>b.engaged||Date.now()-new Date(b.timestamp).getTime()<i).filter(b=>b.engaged);if(c.length<5)return {adjusted:false,oldThreshold:r,newThreshold:r,reason:`Insufficient data (${c.length}/5 engaged nominations)`};let f$1=c.filter(b=>b.response==="accepted").length,l=c.filter(b=>b.response==="dismissed").length,s=f$1/c.length,m=l/c.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 w=g.join(e,".paradigm/agents",`${t}.agent`),N=d.existsSync(w)?"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,u=i.filter(s=>s.response==="dismissed").length,c=i.filter(s=>s.response==="deferred").length,f=i.filter(s=>!s.engaged).length,l=a+u+c;return {total:i.length,accepted:a,dismissed:u,deferred:c,pending:f,acceptRate:l>0?a/l:0}}function zt(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);d.existsSync(h)&&(p=d.readdirSync(h).filter(w=>w.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),u=n.reduce((s,m)=>s+m.notebookCount,0),c=n.reduce((s,m)=>s+m.transferableCount,0),f=n.reduce((s,m)=>s+m.totalNominations,0),l;return f<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:u,totalTransferable:c},healthStatus:l}}function Tt(e,t){if(t.length===0)return;let n=g.join(T.homedir(),".paradigm","score","outbox");if(d.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()};d.writeFileSync(r,JSON.stringify(o),"utf8");}catch{}}function At(e){try{let t=g.join(e,".paradigm","config.yaml");if(d.existsSync(t)){let r=d.readFileSync(t,"utf8").match(/project:\s*(.+)/);if(r)return r[1].trim()}}catch{}return g.basename(e)}function Vt(e,t){let n,r;try{let c=(g$1(),d$1(f$1)),f=(h(),d$1(g$2));n=c.loadJournalEntries,r=f.addNotebookEntry;}catch{return {promoted:0,entries:[]}}let o=n(t,{trigger:"pattern_discovered",limit:100}),i=n(t,{trigger:"human_feedback",limit:100}),a=[...o,...i],u=[];for(let c of a)if(!c.promoted_to_notebook&&!((c.confidence_after??0)<.8))try{let{entry:f}=r(t,{context:c.pattern?.applies_when||c.insight.slice(0,80),snippet:c.pattern?.correct_approach||c.insight,concepts:c.tags||[c.pattern?.id||"learned-pattern"],provenance:{source:"lore",loreEntryId:c.id,createdBy:t}},"global",e);u.push({journalId:c.id,notebookId:f.id});try{let l=g.join(T.homedir(),".paradigm","agents",t,"journal");if(d.existsSync(l)){let s=d.readdirSync(l).filter(m=>m.endsWith(".yaml"));for(let m of s){let p=g.join(l,m),h=d.readFileSync(p,"utf8");if(h.includes(c.id)){let w=h.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${f.id}"`);if(w===h){let N=h.trimEnd().split(`
|
|
27
|
-
`);N.push(`promoted_to_notebook: "${f.id}"`),d.writeFileSync(p,N.join(`
|
|
28
|
-
`)+`
|
|
29
|
-
`,"utf8");}else d.writeFileSync(p,w,"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(!d.existsSync(t))return n;try{let r=a("js-yaml"),o=d.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(u=>u.agent===o.agent);if(a){if(a.always_show)return true;if(a.mute_unless?.length&&!a.mute_unless.some(c=>o.urgency===c||o.type===c))return false;if(a.min_urgency){let u=n[a.min_urgency]??3;return i<=u}}}return i<=r})}var S,mt,gt,pt,ht,yt,bt,St,Pt,Dt=b(()=>{z();X();z$1();S=".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,z 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,qt as k,Bt as l,Gt as m,Yt as n,Ht as o,jt as p,zt as q,Tt as r,Vt as s,Wt as t,Xt as u,Dt as v};
|
package/dist/chunk-6QXBXZF6.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {b as b$1,a as a$1}from'./chunk-EK4ZRIFJ.js';import {q as q$1,p}from'./chunk-LAYBUKMB.js';import {d}from'./chunk-5TAVYPOV.js';import*as r from'fs';import*as a from'path';import*as x from'os';import*as T from'crypto';import*as h from'js-yaml';function w(){let n=a.join(x.homedir(),".paradigm");return r.existsSync(n)||r.mkdirSync(n,{recursive:true}),n}function M(n){let s=a.resolve(n);return T.createHash("sha256").update(s).digest("hex").slice(0,12)}function f(n){let s=M(n),e=a.join(w(),"sessions",s);r.existsSync(e)||r.mkdirSync(e,{recursive:true});let t=a.join(e,"pending-handoffs");return r.existsSync(t)||r.mkdirSync(t,{recursive:true}),e}function S(n){let s=f(n),e=a.join(s,"_project-meta.json"),o={name:a.basename(a.resolve(n)),path:a.resolve(n),lastSeen:new Date().toISOString()};r.writeFileSync(e,JSON.stringify(o,null,2));}function O(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s.id}.json`);r.writeFileSync(t,JSON.stringify(s,null,2));}function A(n){let s=f(n),e=a.join(s,"pending-handoffs");if(!r.existsSync(e))return [];let t=[];try{let o=r.readdirSync(e);for(let l of o)if(l.endsWith(".json"))try{let u=r.readFileSync(a.join(e,l),"utf8"),m=JSON.parse(u);m.status==="pending"&&t.push(m);}catch{}}catch{}return t.sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime()),t}function W(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s}.json`);if(r.existsSync(t))try{let o=r.readFileSync(t,"utf8"),l=JSON.parse(o);l.status="delivered",r.writeFileSync(t,JSON.stringify(l,null,2));}catch{}}function y(){let n=a.join(w(),"wisdom");return r.existsSync(n)||r.mkdirSync(n,{recursive:true}),n}function H(){let n=a.join(y(),"antipatterns.yaml");if(!r.existsSync(n))return [];try{let s=r.readFileSync(n,"utf8");return h.load(s)?.antipatterns||[]}catch{return []}}function L(){let n=a.join(y(),"decisions");if(!r.existsSync(n))return [];let s=[];try{let e=r.readdirSync(n);for(let t of e)if(!(!t.endsWith(".yaml")&&!t.endsWith(".yml")))try{let o=r.readFileSync(a.join(n,t),"utf8"),l=h.load(o);s.push(l);}catch{}}catch{}return s.sort((e,t)=>e.id.localeCompare(t.id)),s}function _(){let n=a.join(y(),"preferences.yaml");if(!r.existsSync(n))return null;try{let s=r.readFileSync(n,"utf8");return h.load(s)}catch{return null}}function J(n){let s=a.join(y(),"antipatterns.yaml"),e={version:"1.0",antipatterns:[]};if(r.existsSync(s))try{let t=r.readFileSync(s,"utf8");e=h.load(t),e.antipatterns||(e.antipatterns=[]);}catch{}e.antipatterns.push({...n,added:new Date().toISOString()}),r.writeFileSync(s,h.dump(e,{lineWidth:-1}));}function U(n){let s=a.join(y(),"decisions");r.existsSync(s)||r.mkdirSync(s,{recursive:true});let e=n.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),t=`${n.id}-${e}.yaml`,o=a.join(s,t);r.writeFileSync(o,h.dump(n,{lineWidth:-1}));}b$1();var k={"claude-opus-4":{input:15,output:75,name:"Claude Opus 4"},"claude-sonnet-4":{input:3,output:15,name:"Claude Sonnet 4"},"claude-haiku-3.5":{input:.8,output:4,name:"Claude Haiku 3.5"}},j=50,P=".paradigm/session-breadcrumbs.json",I=".paradigm/session-checkpoint.json",E=10080*60*1e3,C=class{session;rootDir=null;_recovered=false;lastLoreEntryId=null;constructor(){this.session=this.createNewSession();}setRootDir(s){this.rootDir=s;try{let{clearSessionWorkLog:e}=(q$1(),d(p));e(s);}catch{}}createNewSession(){return {sessionId:`s${Date.now().toString(36)}`,startTime:Date.now(),lastActivity:Date.now(),model:"claude-sonnet-4",resourceReads:[],toolCalls:[],breadcrumbs:[],totals:{resourceReadCount:0,toolCallCount:0,totalBytes:0,totalTokens:0,estimatedCostUsd:0}}}addBreadcrumb(s,e,t={}){this.session.breadcrumbs.push({timestamp:Date.now(),action:s,tool:t.tool,symbol:t.symbol,summary:e}),this.session.breadcrumbs.length>j&&(this.session.breadcrumbs=this.session.breadcrumbs.slice(-j)),this.persistBreadcrumbs();}getBreadcrumbs(s=20){return this.session.breadcrumbs.slice(-s)}persistBreadcrumbs(){if(!this.rootDir)return;let s={sessionId:this.session.sessionId,startTime:this.session.startTime,lastActivity:this.session.lastActivity,breadcrumbs:this.session.breadcrumbs,symbolsModified:this.extractSymbolsFromBreadcrumbs(),filesExplored:this.extractFilesFromBreadcrumbs()},e;try{e=JSON.stringify(s,null,2);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: JSON.stringify failed",{error:t.message});return}try{let t=a.join(this.rootDir,P),o=a.dirname(t);r.existsSync(o)||r.mkdirSync(o,{recursive:!0}),r.writeFileSync(t,e);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: local write failed",{error:t.message});}try{let t=f(this.rootDir);r.writeFileSync(a.join(t,"breadcrumbs.json"),e),S(this.rootDir);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: global write failed",{error:t.message});}}loadPreviousSession(){if(!this.rootDir)return null;try{let s=f(this.rootDir),e=a.join(s,"breadcrumbs.json");if(r.existsSync(e)){let t=r.readFileSync(e,"utf8");return JSON.parse(t)}}catch{}try{let s=a.join(this.rootDir,P);if(!r.existsSync(s))return null;let e=r.readFileSync(s,"utf8");return JSON.parse(e)}catch{return null}}saveCheckpoint(s){let e={phase:s.phase,context:s.context,timestamp:Date.now(),sessionId:this.session.sessionId,externalId:s.externalId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:this.session.breadcrumbs.slice(-10)},t=this.persistCheckpoint(e);return {checkpoint:e,persisted:t}}loadCheckpoint(){if(!this.rootDir)return null;let s=null;try{let e=f(this.rootDir),t=a.join(e,"checkpoint.json");if(r.existsSync(t)){let o=r.readFileSync(t,"utf8");s=JSON.parse(o);}}catch{}if(!s)try{let e=a.join(this.rootDir,I);if(r.existsSync(e)){let t=r.readFileSync(e,"utf8");s=JSON.parse(t);}}catch{}if(s&&Date.now()-s.timestamp>E)return null;if(s)for(let e of ["modifiedFiles","symbolsTouched","decisions"]){let t=s[e];if(typeof t=="string")try{s[e]=JSON.parse(t);}catch{s[e]=[];}}return s}persistCheckpoint(s){let e={local:false,global:false};if(!this.rootDir)return a$1.component("#session-tracker").warn("persistCheckpoint: rootDir not set, skipping write"),e;let t;try{t=JSON.stringify(s,null,2);}catch(o){return a$1.component("#session-tracker").error("persistCheckpoint: JSON.stringify failed",{error:o.message}),e}try{let o=a.join(this.rootDir,I),l=a.dirname(o);r.existsSync(l)||r.mkdirSync(l,{recursive:!0}),r.writeFileSync(o,t),e.local=!0;}catch(o){a$1.component("#session-tracker").error("persistCheckpoint: local write failed",{error:o.message});}try{let o=f(this.rootDir);r.writeFileSync(a.join(o,"checkpoint.json"),t),S(this.rootDir),e.global=!0;}catch(o){a$1.component("#session-tracker").error("persistCheckpoint: global write failed",{error:o.message});}return e}setLastLoreEntryId(s){this.lastLoreEntryId=s;}getLastLoreEntryId(){return this.lastLoreEntryId}hasRecoveredThisSession(){return this._recovered}markRecovered(){this._recovered=true;}extractSymbolsFromBreadcrumbs(){let s=new Set;for(let e of this.session.breadcrumbs)e.symbol&&s.add(e.symbol);return Array.from(s)}extractFilesFromBreadcrumbs(){let s=new Set;for(let e of this.session.breadcrumbs){let t=e.summary.match(/\b[\w./]+\.(ts|js|tsx|jsx|py|go|rs|yaml|json|md)\b/g);if(t)for(let o of t)s.add(o);}return Array.from(s)}estimateTokens(s){let e=typeof s=="number"?s:s.length;return Math.ceil(e/3.5)}calculateCost(s,e=true){let t=k[this.session.model],o=e?t.output:t.input;return s/1e6*o}setModel(s){this.session.model=s,this.recalculateTotals();}getModel(){return this.session.model}trackResourceRead(s,e){let t=this.extractResourceType(s),o=this.estimateTokens(e);this.session.resourceReads.push({timestamp:Date.now(),resourceType:t,uri:s,bytes:e,tokens:o}),this.session.lastActivity=Date.now(),this.updateTotals(e,o);}trackToolCall(s,e){let t=this.estimateTokens(e);this.session.toolCalls.push({timestamp:Date.now(),toolName:s,responseBytes:e,responseTokens:t}),this.session.lastActivity=Date.now(),this.updateTotals(e,t);}updateTotals(s,e){this.session.totals.resourceReadCount=this.session.resourceReads.length,this.session.totals.toolCallCount=this.session.toolCalls.length,this.session.totals.totalBytes+=s,this.session.totals.totalTokens+=e,this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}recalculateTotals(){this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}extractResourceType(s){return s.replace("paradigm://","").split("/")[0]||"unknown"}getStats(){return {...this.session}}getCostBreakdown(){let s={},e=0,t=0;for(let i of this.session.resourceReads)s[i.resourceType]||(s[i.resourceType]={count:0,bytes:0,tokens:0}),s[i.resourceType].count++,s[i.resourceType].bytes+=i.bytes,s[i.resourceType].tokens+=i.tokens,e+=i.bytes,t+=i.tokens;let o={},l=0,u=0;for(let i of this.session.toolCalls)o[i.toolName]||(o[i.toolName]={count:0,bytes:0,tokens:0}),o[i.toolName].count++,o[i.toolName].bytes+=i.responseBytes,o[i.toolName].tokens+=i.responseTokens,l+=i.responseBytes,u+=i.responseTokens;let m=t+u,g=this.calculateCost(m);return {model:k[this.session.model].name,modelId:this.session.model,pricing:k[this.session.model],resources:{count:this.session.resourceReads.length,bytes:e,tokens:t,costUsd:this.calculateCost(t),byType:s},tools:{count:this.session.toolCalls.length,bytes:l,tokens:u,costUsd:this.calculateCost(u),byName:o},total:{tokens:m,costUsd:g}}}getHandoffRecommendation(s=2e5,e){let t=this.session.totals.totalTokens,o=t*4,l=e||t+o,u=Math.round(l/s*100),m,g;u>=85?(m="handoff-urgent",g="Context is nearly full. Initiate handoff immediately to preserve session continuity."):u>=70?(m="handoff-recommended",g="Context usage is high. Consider initiating handoff soon to ensure smooth transition."):u>=50?(m="consider-handoff",g="Context usage is moderate. Plan a good stopping point for potential handoff."):(m="continue",g="Context usage is healthy. Continue working.");let i=[],v=Math.round((Date.now()-this.session.startTime)/6e4),D=this.session.toolCalls.length+this.session.resourceReads.length;return D>50&&i.push(`High number of MCP interactions (${D})`),v>30&&i.push(`Session duration >30 min (${v} min)`),this.session.totals.totalBytes>5e5&&i.push(`Large data volume (${Math.round(this.session.totals.totalBytes/1024)}KB)`),{recommendation:m,message:g,usagePercent:u,signals:i}}getDurationMinutes(){return Math.round((Date.now()-this.session.startTime)/6e4)}reset(){this.session=this.createNewSession(),this._recovered=false,this.lastLoreEntryId=null;}},b=null;function X(){return b||(b=new C),b}function q(){b&&b.reset();}
|
|
3
|
-
export{O as a,A as b,W as c,H as d,L as e,_ as f,J as g,U as h,k as i,X as j,q as k};
|
package/dist/chunk-AMLD7IYC.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {a as a$1}from'./chunk-FYDRENK7.js';import {f,a}from'./chunk-HXGYVS2N.js';import {e}from'./chunk-TQOT2LBO.js';import {b,d,c}from'./chunk-EKZDFEJW.js';import*as h from'fs';import*as A from'path';import*as R from'js-yaml';import {glob}from'glob';import {EventEmitter}from'events';var H=/[#$^!~][a-zA-Z0-9_-]+/g;function V(r){let e=r.match(H)||[];return [...new Set(e)]}function G(r){let e=r.charAt(0);return {"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"}[e]||"unknown"}async function M(r,e,s,t){let o=A.join(s,".paradigm"),n=V(e),a=K(r,t),c=W(a.include||[],n),l=a.exclude||[],p=await J(s,c,l);return {systemPrompt:await Y(r,o,n),files:p,symbols:n}}function K(r,e){return e?.contextInclude||e?.contextExclude?{include:e.contextInclude,exclude:e.contextExclude}:{architect:{include:["specs/*.md",".purpose","**/.purpose","portal.yaml",".paradigm/config.yaml"],exclude:["src/**","tests/**","node_modules/**","dist/**"]},builder:{include:["src/**","tests/**","{feature}.purpose","specs/{feature}.md"],exclude:["specs/*.md","node_modules/**","dist/**"]},reviewer:{include:["src/**","specs/*.md","portal.yaml",".purpose"],exclude:["tests/**","node_modules/**","dist/**"]},tester:{include:["tests/**","health.yaml","{feature}.purpose"],exclude:["src/**","specs/**","node_modules/**","dist/**"]},security:{include:["portal.yaml","src/middleware/**","src/auth/**",".paradigm/wisdom/antipatterns.yaml"],exclude:["src/routes/**","tests/**","node_modules/**","dist/**"]}}[r.name]||{include:[".purpose","portal.yaml"],exclude:["node_modules/**","dist/**"]}}function W(r,e){let s=[];for(let t of r)if(t.includes("{feature}")||t.includes("{symbol}"))for(let o of e){let n=o.substring(1);s.push(t.replace(/\{feature\}/g,n).replace(/\{symbol\}/g,n));}else s.push(t);return s}async function J(r,e,s){let t=new Set;for(let o of e)try{let n=await glob(o,{cwd:r,ignore:s,nodir:!0,absolute:!1});for(let a of n)t.add(a);}catch{}return Array.from(t)}async function Y(r,e,s){let t=[],o=A.join(e,"config.yaml"),n=null;if(h.existsSync(o))try{n=R.load(h.readFileSync(o,"utf-8"));}catch{}if(t.push(`# ${r.name.charAt(0).toUpperCase()+r.name.slice(1)} Agent Context
|
|
3
|
-
`),n?.project&&(t.push(`> Project: ${n.project}`),n.discipline&&n.discipline!=="auto"&&t.push(`> Discipline: ${n.discipline}`),t.push("")),n?.["agent-guidelines"]?.overview&&(t.push(`## Project Overview
|
|
4
|
-
`),t.push(n["agent-guidelines"].overview),t.push("")),n?.["symbol-system"]){t.push(`## Symbol System
|
|
5
|
-
`),t.push("| Symbol | Meaning | Description |"),t.push("|--------|---------|-------------|");for(let[c,l]of Object.entries(n["symbol-system"]))t.push(`| \`${c}\` | ${l.name} | ${l.description} |`);t.push("");}if(n?.conventions){let c=Z(n.conventions,r.name);if(c.length>0){t.push(`## Conventions
|
|
6
|
-
`);for(let l of c)t.push(`- ${l}`);t.push("");}}if(s.length>0){t.push(`## Symbols in Scope
|
|
7
|
-
`);for(let c of s){let l=G(c);t.push(`- \`${c}\` (${l})`);}t.push("");}let a=q(r.name);if(a.length>0){t.push(`## Tips for This Role
|
|
8
|
-
`);for(let c of a)t.push(`- ${c}`);t.push("");}return t.join(`
|
|
9
|
-
`)}function Z(r,e){let t={architect:["design","spec","document","flow","symbol","reference"],builder:["code","implement","component","logger","test"],reviewer:["review","portal","gate","check","validate"],tester:["test","verify","health","validate"],security:["portal","gate","auth","security","vulnerability"]}[e]||[];return r.filter(o=>t.some(n=>o.toLowerCase().includes(n)))}function q(r){return {architect:["Focus on design decisions, not implementation details","Use paradigm symbols to reference features and components","Document flows that span 3+ components","Hand off to builder when spec is ready"],builder:["Follow the spec from architect exactly","If spec is unclear, ask for clarification or hand back","Use the Paradigm logger, not raw console.log","Hand off to reviewer when implementation is ready"],reviewer:["Check that all ^gate requirements are met","Verify adherence to specs","Do NOT implement fixes - hand back to builder","Approve or request changes with clear feedback"],tester:["Run tests and verify health status","Check portal validations","Update health.yaml when verified","Report issues with reproduction steps"],security:["Focus on ^gate implementations","Check for OWASP top 10 vulnerabilities","Flag issues but do NOT implement fixes","Review auth flows and session handling"]}[r]||[]}var w=class extends EventEmitter{config;usage;records=[];configPath;constructor(e){super(),this.configPath=A.join(e,".paradigm","config.yaml"),this.config=this.loadConfig(),this.usage=this.initializeUsage();}checkBudget(e,s){let t=this.estimateCost(s,"sonnet");if(this.config.maxTokens){let a=this.usage.tokens.total+s;if(a>this.config.maxTokens)return {allowed:false,reason:`Global token limit exceeded: ${d(a)} > ${d(this.config.maxTokens)}`,usage:this.usage,warningLevel:"exceeded"}}if(this.config.maxCostUsd){let a=this.usage.cost+t;if(a>this.config.maxCostUsd)return {allowed:false,reason:`Cost ceiling exceeded: ${c(a)} > ${c(this.config.maxCostUsd)}`,usage:this.usage,warningLevel:"exceeded"}}let o=this.config.agentLimits?.[e];if(o){let a=this.usage.byAgent[e]||{tokens:{total:0},cost:0};if(o.maxTokens){let c=a.tokens.total+s;if(c>o.maxTokens)return {allowed:false,reason:`Agent '${e}' token limit exceeded: ${d(c)} > ${d(o.maxTokens)}`,usage:this.usage,warningLevel:"exceeded"}}if(o.maxCostUsd){let c$1=a.cost+t;if(c$1>o.maxCostUsd)return {allowed:false,reason:`Agent '${e}' cost limit exceeded: ${c(c$1)} > ${c(o.maxCostUsd)}`,usage:this.usage,warningLevel:"exceeded"}}}let n="none";return this.config.warnAtPercent&&this.config.maxTokens&&(this.usage.tokens.total+s)/this.config.maxTokens*100>=this.config.warnAtPercent&&(n="approaching"),{allowed:true,usage:this.usage,warningLevel:n}}recordUsage(e,s,t,o){let n=b(s,t);this.usage.tokens.input+=s.input,this.usage.tokens.output+=s.output,this.usage.tokens.total+=s.total,this.usage.cost+=n,this.config.maxTokens&&(this.usage.percentage=this.usage.tokens.total/this.config.maxTokens*100),this.usage.byAgent[e]||(this.usage.byAgent[e]={tokens:{input:0,output:0,total:0},cost:0}),this.usage.byAgent[e].tokens.input+=s.input,this.usage.byAgent[e].tokens.output+=s.output,this.usage.byAgent[e].tokens.total+=s.total,this.usage.byAgent[e].cost+=n;let a={timestamp:new Date().toISOString(),agent:e,model:t,tokens:s,cost:n,orchestrationId:o};this.records.push(a),this.emit("usage",{agent:e,tokens:s,cost:n,total:this.usage}),this.config.warnAtPercent&&this.usage.percentage>=this.config.warnAtPercent&&this.emit("warning",{type:"budget_approaching",percentage:this.usage.percentage,usage:this.usage});}getUsage(){return {...this.usage}}getRecords(){return [...this.records]}getRemaining(){return {tokens:this.config.maxTokens?this.config.maxTokens-this.usage.tokens.total:null,cost:this.config.maxCostUsd?this.config.maxCostUsd-this.usage.cost:null}}reset(){this.usage=this.initializeUsage(),this.records=[];}estimateCost(e,s){let t={input:Math.floor(e/2),output:Math.ceil(e/2),total:e};return b(t,s)}estimateTime(e,s){return Math.ceil(e/{opus:50,sonnet:100,haiku:200}[s])*1e3}getSummary(){let e=[];if(e.push("Budget Summary:"),e.push(` Tokens: ${d(this.usage.tokens.total)}`),e.push(` Cost: ${c(this.usage.cost)}`),this.config.maxTokens&&e.push(` Token limit: ${d(this.config.maxTokens)} (${this.usage.percentage.toFixed(1)}% used)`),this.config.maxCostUsd){let s=this.usage.cost/this.config.maxCostUsd*100;e.push(` Cost limit: ${c(this.config.maxCostUsd)} (${s.toFixed(1)}% used)`);}if(Object.keys(this.usage.byAgent).length>0){e.push(" By agent:");for(let[s,t]of Object.entries(this.usage.byAgent))e.push(` ${s}: ${d(t.tokens.total)} (${c(t.cost)})`);}return e.join(`
|
|
10
|
-
`)}loadConfig(){let e={maxTokens:5e5,maxCostUsd:5,warnAtPercent:80};if(!h.existsSync(this.configPath))return e;try{let s=h.readFileSync(this.configPath,"utf-8"),o=R.load(s).orchestration;if(o?.budget){let n=o.budget;return {maxTokens:n.max_tokens,maxCostUsd:n.max_cost_usd,warnAtPercent:n.warn_at_percent,agentLimits:o.agent_limits}}return e}catch{return e}}initializeUsage(){return {tokens:{input:0,output:0,total:0},cost:0,percentage:0,byAgent:{}}}};var F=class{provider=null;budgetTracker=null;auditLogger=null;rootDir;constructor(e){this.rootDir=e;}async initialize(){await f(),this.provider=a(),this.budgetTracker=new w(this.rootDir),this.auditLogger=new a$1(this.rootDir);}isReady(){return this.provider!==null}getProvider(){return this.provider}async spawn(e$1,s,t={}){if(!this.provider)return {success:false,error:"Spawner not initialized",sessionId:""};let o=e(this.rootDir);if(!o)return {success:false,error:"Team not configured. Run `paradigm team init` first.",sessionId:""};let n=o.agents[e$1];if(!n)return {success:false,error:`Unknown agent: ${e$1}. Available: ${Object.keys(o.agents).join(", ")}`,sessionId:""};let a$1=t.provider||this.provider.name,c=a(a$1);if(!c)return {success:false,error:`Provider '${a$1}' not available`,sessionId:""};if(!await c.isAvailable())return {success:false,error:`Provider '${a$1}' not configured (missing API key?)`,sessionId:""};let p=this.generateSessionId(e$1),k=this.loadFacetConfig(e$1),P=await M(n,s,this.rootDir,k),y=t.model||k?.defaultModel||"sonnet",O={model:y,task:s,context:P,budget:t.budget,mcpServerPath:t.mcpServerPath,workingDirectory:t.workingDirectory||this.rootDir,checkpoints:t.checkpoints,timeout:t.timeout},S=Date.now(),B=new Date().toISOString(),i={agent:e$1,task:s,status:"success",completionVerified:false,outputs:{artifacts:[],symbols:P.symbols,decisions:[]},metrics:{tokens_used:{input:0,output:0,total:0},duration_ms:0,files_read:0,files_written:0}};try{for await(let u of c.spawn(n,O)){if(u.usage&&(i.metrics.tokens_used=u.usage),u.type==="tool_use"){if(u.toolName==="read_file")i.metrics.files_read++;else if(u.toolName==="write_file"){i.metrics.files_written++;let f=u.toolInput?.path;f&&i.outputs.artifacts.push({path:f,action:"modified"});}}if(t.checkpoints&&u.type==="tool_use"&&this.shouldPauseForCheckpoint(u,t.checkpoints)&&t.onCheckpoint&&!await t.onCheckpoint(`Agent wants to ${u.toolName}: ${JSON.stringify(u.toolInput)}`)){i.status="blocked";break}if(t.onMessage&&t.onMessage(u),u.type==="error"&&(i.status="failed"),this.budgetTracker&&u.usage&&!this.budgetTracker.checkBudget(e$1,u.usage.total).allowed){i.status="failed";break}}if(i.metrics.duration_ms=Date.now()-S,this.budgetTracker&&this.budgetTracker.recordUsage(e$1,i.metrics.tokens_used,y),i.status==="success"){let u=i.outputs.artifacts.length>0,f=i.outputs.decisions.length>0,C=!!i.handoff,T=i.metrics.files_written>0,z=e$1==="architect";(e$1==="builder"&&!T&&!C||!u&&!f&&!C&&!T)&&(i.status="partial"),i.completionVerified=!0,i.status==="partial"&&!z&&t.onMessage&&t.onMessage({type:"text",content:`[completion-check] Agent "${e$1}" downgraded from success \u2192 partial: no meaningful output detected.`,timestamp:new Date().toISOString()});}if(this.auditLogger){let u={name:e$1,model:y,started:B,completed:new Date().toISOString(),duration_ms:i.metrics.duration_ms,tokens:i.metrics.tokens_used,cost_usd:b(i.metrics.tokens_used,y),status:i.status,artifacts:i.outputs.artifacts,symbols:i.outputs.symbols};this.auditLogger.logAgentCompletion(p,u);}return {success:i.status==="success"||i.status==="partial",relay:i,sessionId:p}}catch(u){return {success:false,error:u instanceof Error?u.message:String(u),sessionId:p,relay:{...i,status:"failed",metrics:{...i.metrics,duration_ms:Date.now()-S}}}}}async spawnParallel(e){let s=e.map(({name:t,task:o,options:n})=>this.spawn(t,o,n));return Promise.all(s)}generateSessionId(e){let s=Date.now(),t=Math.random().toString(36).substring(2,8);return `${e}-${s}-${t}`}loadFacetConfig(e){let s=A.join(this.rootDir,".paradigm","facets.yaml");if(!h.existsSync(s))return {architect:{defaultModel:"opus"},security:{defaultModel:"opus"},reviewer:{defaultModel:"sonnet"},builder:{defaultModel:"haiku"},tester:{defaultModel:"haiku"}}[e];try{let t=h.readFileSync(s,"utf-8");return R.load(t)[e]}catch{return}}shouldPauseForCheckpoint(e,s){if(!s.beforeActions||e.type!=="tool_use")return false;let t={write:["write_file","edit_file"],delete:["delete_file","rm"],execute:["run_command","bash"],external_api:["mcp_call","http_request"]};for(let o of s.beforeActions){let n=t[o]||[];if(e.toolName&&n.includes(e.toolName))return true}return false}};export{V as a,F as b};
|
package/dist/chunk-DVZWCXB6.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import*as i from'fs';import*as o from'path';import*as d from'js-yaml';var u=".paradigm/tasks",m="entries",P="index.yaml";function b(n,t){let s=o.join(n,u,m,t);if(!i.existsSync(s))return `T-${t}-001`;let e=i.readdirSync(s).filter(a=>a.startsWith("T-")&&a.endsWith(".yaml")).map(a=>{let l=a.match(/T-\d{4}-\d{2}-\d{2}-(\d+)\.yaml/);return l?parseInt(l[1],10):0}),r=e.length>0?Math.max(...e)+1:1;return `T-${t}-${String(r).padStart(3,"0")}`}var k={high:0,medium:1,low:2};function w(n,t){let s=n;return t.status&&t.status!=="all"&&(s=s.filter(e=>e.status===t.status)),t.priority&&(s=s.filter(e=>e.priority===t.priority)),t.tag&&(s=s.filter(e=>e.tags.includes(t.tag))),s.sort((e,r)=>{let a=(k[e.priority]??1)-(k[r.priority]??1);return a!==0?a:new Date(r.created).getTime()-new Date(e.created).getTime()}),t.limit&&(s=s.slice(0,t.limit)),s}async function _(n,t){let s=o.join(n,u,m);if(!i.existsSync(s))return [];let e={status:"open",limit:20,...t},r=[],a=i.readdirSync(s).filter(l=>/^\d{4}-\d{2}-\d{2}$/.test(l)).sort().reverse();for(let l of a){let f=o.join(s,l),p=i.readdirSync(f).filter(c=>c.endsWith(".yaml")).sort();for(let c of p)try{let g=i.readFileSync(o.join(f,c),"utf8"),y=d.load(g);r.push(y);}catch{}}return w(r,e)}async function v(n,t){let s=t.match(/^T-(\d{4}-\d{2}-\d{2})-/);if(s){let r=o.join(n,u,m,s[1],`${t}.yaml`);if(i.existsSync(r))try{return d.load(i.readFileSync(r,"utf8"))}catch{return null}}return (await _(n,{status:"all",limit:9999})).find(r=>r.id===t)||null}async function I(n,t){let s=new Date,e=s.toISOString().slice(0,10),r=o.join(n,u,m,e);i.mkdirSync(r,{recursive:true});let a=b(n,e),l={id:a,blurb:t.blurb,priority:t.priority||"medium",status:"open",tags:t.tags||[],created:s.toISOString(),session_link:t.session_link,related_lore:t.related_lore};return i.writeFileSync(o.join(r,`${a}.yaml`),d.dump(l,{lineWidth:-1,noRefs:true})),await x(n),a}async function S(n,t,s){let e=await v(n,t);if(!e)return false;let r=e.created.slice(0,10),a=o.join(n,u,m,r,`${t}.yaml`);if(!i.existsSync(a))return false;let{id:l,created:f,...p}=s,c={...e,...p};return i.writeFileSync(a,d.dump(c,{lineWidth:-1,noRefs:true})),await x(n),true}async function j(n,t){return S(n,t,{status:"done",completed:new Date().toISOString()})}async function F(n,t){return S(n,t,{status:"shelved",shelved:new Date().toISOString()})}async function x(n){let t=o.join(n,u,m),s=o.join(n,u),e=0,r=0,a=0,l=0;if(i.existsSync(t)){let p=i.readdirSync(t).filter(c=>/^\d{4}-\d{2}-\d{2}$/.test(c));for(let c of p){let g=o.join(t,c),y=i.readdirSync(g).filter(h=>h.endsWith(".yaml"));for(let h of y)try{let T=d.load(i.readFileSync(o.join(g,h),"utf8"));e++,T.status==="open"?r++:T.status==="done"?a++:T.status==="shelved"&&l++;}catch{}}}let f={version:"1.0",total:e,open:r,done:a,shelved:l,last_updated:new Date().toISOString()};return i.mkdirSync(s,{recursive:true}),i.writeFileSync(o.join(s,P),d.dump(f,{lineWidth:-1,noRefs:true})),f}export{_ as a,v as b,I as c,S as d,j as e,F as f,x as g};
|
package/dist/chunk-F6E3HW45.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import*as e from'fs';import*as o from'path';var y=".paradigm/events/session-log.jsonl",d=".paradigm/events/session-metrics.jsonl",p=".paradigm/events/verdicts.jsonl",v=200,g=".paradigm/events/notebook-refs.jsonl";function x(i,n){try{let t=o.join(i,y),r=o.dirname(t);if(e.existsSync(r)||e.mkdirSync(r,{recursive:!0}),e.existsSync(t)&&e.readFileSync(t,"utf8").trim().split(`
|
|
3
|
-
`).filter(a=>a.trim()).length>=v)return;let f=JSON.stringify(n)+`
|
|
4
|
-
`;e.appendFileSync(t,f,"utf8"),n.type==="user-verdict"&&n.agent&&n.symbols?.length&&import('./agent-loader-VGBPL3TH.js').then(({loadAgentProfile:c,saveAgentProfile:s})=>{try{let a=c(i,n.agent);if(a?.expertise){let u=n.verdict==="accepted"?.03:n.verdict==="dismissed"?-.02:n.verdict==="revised"?-.01:0;if(u!==0){for(let S of n.symbols){let l=a.expertise.find(h=>h.symbol===S);l&&(l.confidence=Math.max(0,Math.min(1,l.confidence+u)),l.sessions=(l.sessions||0)+1,l.lastTouch=new Date().toISOString());}s(n.agent,a,"global");}}}catch{}}).catch(()=>{});}catch{}}function m(i){try{let n=o.join(i,y);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
|
|
5
|
-
`).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null):[]}catch{return []}}function C(i){try{let n=o.join(i,y);e.existsSync(n)&&e.writeFileSync(n,"","utf8");}catch{}}function I(i,n){try{let t=o.join(i,p),r=o.dirname(t);e.existsSync(r)||e.mkdirSync(r,{recursive:!0}),e.appendFileSync(t,JSON.stringify(n)+`
|
|
6
|
-
`,"utf8");}catch{}}function N(i){try{let n=o.join(i,p);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
|
|
7
|
-
`).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&!t.consumed):[]}catch{return []}}function M(i,n){try{let t=o.join(i,p);if(!e.existsSync(t))return;let r=new Set(n),c=e.readFileSync(t,"utf8").trim().split(`
|
|
8
|
-
`).filter(s=>s.trim()).map(s=>{try{let a=JSON.parse(s);return a.nominationId&&r.has(a.nominationId)?JSON.stringify({...a,consumed:!0}):s}catch{return s}});e.writeFileSync(t,c.join(`
|
|
9
|
-
`)+`
|
|
10
|
-
`,"utf8");}catch{}}function O(i){let n=m(i),t=new Set;for(let r of n)r.agent&&t.add(r.agent);return Array.from(t)}function k(i,n){return m(i).filter(t=>t.agent===n)}function A(i,n){let t=k(i,n),r=t.filter(s=>s.type==="agent-contribution"),f=t.filter(s=>s.type==="user-verdict"),c=[];for(let s of r)c.push({contribution:s});for(let s of f){let a=c.find(u=>!u.verdict&&u.contribution);a?a.verdict=s:c.push({verdict:s});}return c}function P(i,n){try{let t=o.join(i,d),r=o.dirname(t);e.existsSync(r)||e.mkdirSync(r,{recursive:!0});let f={timestamp:new Date().toISOString(),type:"activity",...n},c=JSON.stringify(f)+`
|
|
11
|
-
`;e.appendFileSync(t,c,"utf8");}catch{}}function b(i){try{let n=o.join(i,d);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
|
|
12
|
-
`).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="activity"):[]}catch{return []}}function F(i){let n=b(i),t={toolCallCount:0,responsePayloadBytes:0,sessionDurationMs:0,agentBreakdown:{}};for(let r of n)if(r.toolCallCount!=null&&(t.toolCallCount+=r.toolCallCount),r.responsePayloadBytes!=null&&(t.responsePayloadBytes+=r.responsePayloadBytes),r.sessionDurationMs!=null&&(t.sessionDurationMs=Math.max(t.sessionDurationMs,r.sessionDurationMs)),r.agentId){t.agentBreakdown[r.agentId]||(t.agentBreakdown[r.agentId]={toolCalls:0,payloadBytes:0});let f=t.agentBreakdown[r.agentId];r.toolCallCount!=null&&(f.toolCalls+=r.toolCallCount),r.responsePayloadBytes!=null&&(f.payloadBytes+=r.responsePayloadBytes);}return t}function B(i){try{let n=o.join(i,d);e.existsSync(n)&&e.writeFileSync(n,"","utf8");}catch{}}function W(i,n,t,r){try{if(t.length===0)return;let f=o.join(i,g),c=o.dirname(f);e.existsSync(c)||e.mkdirSync(c,{recursive:!0});let s={timestamp:new Date().toISOString(),type:"notebook-reference",agentId:n,notebookEntryIds:t,...r?{orchestrationId:r}:{}},a=JSON.stringify(s)+`
|
|
13
|
-
`;e.appendFileSync(f,a,"utf8");}catch{}}function E(i){try{let n=o.join(i,g);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
|
|
14
|
-
`).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="notebook-reference"):[]}catch{return []}}function j(i){return E(i).length}export{x as a,m as b,C as c,I as d,N as e,M as f,O as g,k as h,A as i,P as j,F as k,B as l,W as m,E as n,j as o};
|
package/dist/chunk-K7X3Z3GL.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {c,b}from'./chunk-5TAVYPOV.js';import*as i from'fs';import*as l from'path';import*as k from'os';import*as g from'js-yaml';var $={};c($,{addNotebookEntry:()=>N,classifyNotebookScope:()=>w,incrementApplied:()=>P,loadNotebookEntries:()=>S,promoteFromLore:()=>_,searchNotebooks:()=>O});function S(e,t,n){let r=new Map,a=l.join(u,e);h(a,r);let o=l.join(t,d,e);h(o,r);let c=Array.from(r.values());if(n?.concepts&&n.concepts.length>0){let p=new Set(n.concepts.map(s=>s.toLowerCase()));c=c.filter(s=>s.concepts.some(f=>p.has(f.toLowerCase())));}if(n?.tags&&n.tags.length>0){let p=new Set(n.tags.map(s=>s.toLowerCase()));c=c.filter(s=>s.tags.some(f=>p.has(f.toLowerCase())));}return c.sort((p,s)=>s.appliedCount-p.appliedCount)}function h(e,t){if(i.existsSync(e))try{let n=i.readdirSync(e).filter(r=>r.startsWith(L)&&r.endsWith(y));for(let r of n)try{let a=i.readFileSync(l.join(e,r),"utf-8"),o=g.load(a);o?.id&&t.set(o.id,o);}catch{}}catch{}}function O(e,t,n){let r=S(e,n),a=t.toLowerCase();return r.filter(o=>o.context.toLowerCase().includes(a)||o.snippet.toLowerCase().includes(a)||o.concepts.some(c=>c.toLowerCase().includes(a))||o.tags.some(c=>c.toLowerCase().includes(a)))}function w(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(r=>t.includes(r))?"platform-specific":/[#$^!~][a-z][a-z0-9-]{2,}/.test(t)||/\/[a-z0-9_-]{2,}\/[a-z0-9_-]/.test(t)?"project-specific":"generalizable"}function N(e,t,n,r){let a=new Date().toISOString(),o=(t.concepts[0]||t.context.split(" ").slice(0,4).join(" ")||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),p=`nb-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}-${o}`,s=t.scope??w({context:t.context,snippet:t.snippet,concepts:t.concepts,tags:t.tags}),f={...t,id:p,scope:s,publishable:t.publishable??true,appliedCount:0,created:a,updated:a},m=n==="global"?l.join(u,e):l.join(r||process.cwd(),d,e);i.existsSync(m)||i.mkdirSync(m,{recursive:true});let E=`${p}${y}`,b=l.join(m,E),C=g.dump(f,{lineWidth:120,noRefs:true,sortKeys:false});return i.writeFileSync(b,C,"utf-8"),{entry:f,filePath:b}}async function _(e,t,n,r="global"){let{loadLoreEntry:a}=await import('./lore-loader-PXFKMKAN.js'),o=await a(n,t);if(!o)return null;let c=[];if(o.symbols_touched)for(let f of o.symbols_touched){let m=f.replace(/^[#$^!~]/,"").toLowerCase();c.push(m);}let p=o.summary||"";o.body&&(p+=`
|
|
3
|
-
|
|
4
|
-
`+o.body);let s={source:"lore",loreEntryId:t,originProject:l.basename(n),createdBy:e};return N(e,{context:o.title||`Promoted from ${t}`,snippet:p,provenance:s,confidence:o.confidence??.7,concepts:c,tags:o.tags||[]},r,n)}function P(e,t,n){let r=l.join(n,d,e),a=l.join(u,e);for(let o of [r,a]){let c=l.join(o,`${t}${y}`);if(i.existsSync(c))try{let p=i.readFileSync(c,"utf-8"),s=g.load(p);if(s)return s.appliedCount=(s.appliedCount||0)+1,s.updated=new Date().toISOString(),i.writeFileSync(c,g.dump(s,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var u,d,L,y,v=b(()=>{u=l.join(k.homedir(),".paradigm","notebooks"),d=".paradigm/notebooks",L="nb-",y=".yaml";});export{S as a,O as b,w as c,N as d,_ as e,P as f,$ as g,v as h};
|
package/dist/chunk-LAYBUKMB.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {c,b}from'./chunk-5TAVYPOV.js';import*as e from'fs';import*as o from'path';var D={};c(D,{appendSessionWorkEntry:()=>C,appendVerdictEntry:()=>N,clearActivityMetrics:()=>j,clearSessionWorkLog:()=>I,countNotebookReferences:()=>w,getAgentEntries:()=>S,getAgentVerdicts:()=>P,getContributingAgents:()=>A,getNotebookReferences:()=>h,getSessionActivitySummary:()=>W,markVerdictsConsumed:()=>O,readPendingVerdicts:()=>M,readSessionWorkLog:()=>g,recordActivityMetric:()=>F,recordNotebookReference:()=>R});function C(i,n){try{let t=o.join(i,y),r=o.dirname(t);if(e.existsSync(r)||e.mkdirSync(r,{recursive:!0}),e.existsSync(t)&&e.readFileSync(t,"utf8").trim().split(`
|
|
3
|
-
`).filter(a=>a.trim()).length>=x)return;let f=JSON.stringify(n)+`
|
|
4
|
-
`;e.appendFileSync(t,f,"utf8"),n.type==="user-verdict"&&n.agent&&n.symbols?.length&&import('./agent-loader-W3RQJVW7.js').then(({loadAgentProfile:c,saveAgentProfile:s})=>{try{let a=c(i,n.agent);if(a?.expertise){let u=n.verdict==="accepted"?.03:n.verdict==="dismissed"?-.02:n.verdict==="revised"?-.01:0;if(u!==0){for(let v of n.symbols){let l=a.expertise.find(k=>k.symbol===v);l&&(l.confidence=Math.max(0,Math.min(1,l.confidence+u)),l.sessions=(l.sessions||0)+1,l.lastTouch=new Date().toISOString());}s(n.agent,a,"global");}}}catch{}}).catch(()=>{});}catch{}}function g(i){try{let n=o.join(i,y);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
|
|
5
|
-
`).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null):[]}catch{return []}}function I(i){try{let n=o.join(i,y);e.existsSync(n)&&e.writeFileSync(n,"","utf8");}catch{}}function N(i,n){try{let t=o.join(i,p),r=o.dirname(t);e.existsSync(r)||e.mkdirSync(r,{recursive:!0}),e.appendFileSync(t,JSON.stringify(n)+`
|
|
6
|
-
`,"utf8");}catch{}}function M(i){try{let n=o.join(i,p);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
|
|
7
|
-
`).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&!t.consumed):[]}catch{return []}}function O(i,n){try{let t=o.join(i,p);if(!e.existsSync(t))return;let r=new Set(n),c=e.readFileSync(t,"utf8").trim().split(`
|
|
8
|
-
`).filter(s=>s.trim()).map(s=>{try{let a=JSON.parse(s);return a.nominationId&&r.has(a.nominationId)?JSON.stringify({...a,consumed:!0}):s}catch{return s}});e.writeFileSync(t,c.join(`
|
|
9
|
-
`)+`
|
|
10
|
-
`,"utf8");}catch{}}function A(i){let n=g(i),t=new Set;for(let r of n)r.agent&&t.add(r.agent);return Array.from(t)}function S(i,n){return g(i).filter(t=>t.agent===n)}function P(i,n){let t=S(i,n),r=t.filter(s=>s.type==="agent-contribution"),f=t.filter(s=>s.type==="user-verdict"),c=[];for(let s of r)c.push({contribution:s});for(let s of f){let a=c.find(u=>!u.verdict&&u.contribution);a?a.verdict=s:c.push({verdict:s});}return c}function F(i,n){try{let t=o.join(i,d),r=o.dirname(t);e.existsSync(r)||e.mkdirSync(r,{recursive:!0});let f={timestamp:new Date().toISOString(),type:"activity",...n},c=JSON.stringify(f)+`
|
|
11
|
-
`;e.appendFileSync(t,c,"utf8");}catch{}}function B(i){try{let n=o.join(i,d);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
|
|
12
|
-
`).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="activity"):[]}catch{return []}}function W(i){let n=B(i),t={toolCallCount:0,responsePayloadBytes:0,sessionDurationMs:0,agentBreakdown:{}};for(let r of n)if(r.toolCallCount!=null&&(t.toolCallCount+=r.toolCallCount),r.responsePayloadBytes!=null&&(t.responsePayloadBytes+=r.responsePayloadBytes),r.sessionDurationMs!=null&&(t.sessionDurationMs=Math.max(t.sessionDurationMs,r.sessionDurationMs)),r.agentId){t.agentBreakdown[r.agentId]||(t.agentBreakdown[r.agentId]={toolCalls:0,payloadBytes:0});let f=t.agentBreakdown[r.agentId];r.toolCallCount!=null&&(f.toolCalls+=r.toolCallCount),r.responsePayloadBytes!=null&&(f.payloadBytes+=r.responsePayloadBytes);}return t}function j(i){try{let n=o.join(i,d);e.existsSync(n)&&e.writeFileSync(n,"","utf8");}catch{}}function R(i,n,t,r){try{if(t.length===0)return;let f=o.join(i,m),c=o.dirname(f);e.existsSync(c)||e.mkdirSync(c,{recursive:!0});let s={timestamp:new Date().toISOString(),type:"notebook-reference",agentId:n,notebookEntryIds:t,...r?{orchestrationId:r}:{}},a=JSON.stringify(s)+`
|
|
13
|
-
`;e.appendFileSync(f,a,"utf8");}catch{}}function h(i){try{let n=o.join(i,m);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
|
|
14
|
-
`).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="notebook-reference"):[]}catch{return []}}function w(i){return h(i).length}var y,d,p,x,m,J=b(()=>{y=".paradigm/events/session-log.jsonl",d=".paradigm/events/session-metrics.jsonl",p=".paradigm/events/verdicts.jsonl",x=200,m=".paradigm/events/notebook-refs.jsonl";});export{C as a,g as b,I as c,N as d,M as e,O as f,A as g,S as h,P as i,F as j,W as k,j as l,R as m,h as n,w as o,D as p,J as q};
|
package/dist/chunk-MU5YWTNE.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {a as a$3}from'./chunk-TYWB5IQJ.js';import {b,a as a$1}from'./chunk-AMLD7IYC.js';import {a}from'./chunk-FYDRENK7.js';import {e}from'./chunk-TQOT2LBO.js';import {b as b$1}from'./chunk-EKZDFEJW.js';import {a as a$2,b as b$2}from'./chunk-LPBCQM5Y.js';import {o,t,x}from'./chunk-4GC35IFF.js';import'minimatch';import*as w from'fs';import*as A from'path';import*as F from'js-yaml';import {spawn}from'child_process';var ee=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","tradeoff","pros and cons","decision"],te=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs","changelog","architecture doc"],se=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","doesn't work","doesn't","cant","can't","regression","patch"],re=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify","modularize","decouple","split","merge"],ne=["auth","authentication","authorization","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","api key","role","access","gate","portal","sensitive","private","security","vulnerability","xss","sql injection","csrf"],oe=/[@#$%^!?&~][a-zA-Z0-9_-]+/g,Y={analysis:{agents:["architect"],models:{architect:"opus"},costMultiplier:{min:.3,max:.5}},documentation:{agents:["architect"],models:{architect:"sonnet"},costMultiplier:{min:.25,max:.45}},bugfix:{agents:["security","builder"],models:{security:"opus",builder:"haiku"},costMultiplier:{min:.5,max:.8}},refactor:{agents:["architect","builder"],models:{architect:"opus",builder:"haiku"},costMultiplier:{min:.6,max:.85}},feature:{agents:["architect","security","builder","tester"],models:{architect:"opus",security:"opus",builder:"haiku",tester:"haiku"},costMultiplier:{min:.8,max:1.2}}};function ie(p){let s=p.match(oe)||[];return [...new Set(s)]}function $(p,s){let e=p.toLowerCase();return s.filter(t=>e.includes(t.toLowerCase()))}function ae(p,s,e,t){let n=0;e.length>=5?n+=2:e.length>=2&&(n+=1);let o=p.split(/\s+/).length;o>=100?n+=2:o>=50&&(n+=1);let r=new Set(e.map(a=>a[0]));return r.size>=4?n+=2:r.size>=2&&(n+=1),e.some(a=>a.startsWith("^"))&&(n+=1),e.some(a=>a.startsWith("$"))&&(n+=1),s==="feature"&&(n+=1),s==="refactor"&&(n+=1),n>=5?"high":n>=2?"medium":"low"}function le(p,s,e){if($(p,ne).length>0||s.some(n=>n.startsWith("^")))return true;return false}function K(p,s){let e=ie(p),t=$(p,ee),n=$(p,te),o=$(p,se),r=$(p,re),a,i;t.length>0&&o.length===0&&r.length===0?(a="analysis",i=t):n.length>0&&o.length===0?(a="documentation",i=n):o.length>0?(a="bugfix",i=o):r.length>0?(a="refactor",i=r):(a="feature",i=[]);let c=Y[a],d=le(p,e),u=[...c.agents];d&&!u.includes("security")&&(u=["security",...u]);let m=ae(p,a,e),g={...c.costMultiplier};return m==="high"?(g.min*=1.2,g.max*=1.3):m==="low"&&(g.min*=.8,g.max*=.9),d&&!c.agents.includes("security")&&(g.min+=.15,g.max+=.2),{type:a,complexity:m,recommendedAgents:u,securityRequired:d,costMultiplier:g,matchedKeywords:i,symbols:e}}function B(p,s){let e=Y[s.type];return p==="security"&&s.securityRequired?"opus":e.models[p]||"sonnet"}var ce=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,ue=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi],de=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"];function V(p,s,e$1){let t$1=p.toLowerCase(),n=p.match(ce)||[],o=[...new Set(n)],r=o.map(l=>{let y=t(e$1,l),k=y.length>0?y[0]:null;return {symbol:l,exists:!!k,type:k?.type,description:k?.description}}),a=r.filter(l=>l.exists).map(l=>{let y=x(e$1,l.symbol),k=new Set;for(let S of y){let x$1=x(e$1,S.symbol);for(let P of x$1)P.symbol!==l.symbol&&!y.find(O=>O.symbol===P.symbol)&&k.add(P.symbol);}let f=y.length+k.size,b="low";return f>10?b="high":f>3&&(b="medium"),{symbol:l.symbol,directDependents:y.length,indirectDependents:k.size,impact:b}}),i=a$2(s),c=i.status==="ok"?i.data:null,d={exists:i.status!=="missing",gateCount:c?b$2(c).length:0,gates:c?b$2(c).map(l=>`^${l}`):[],routeCount:c?.routes?Object.keys(c.routes).length:0},u=de.some(l=>t$1.includes(l)),m=e(s),g=m?a$3(p,m.agents).map(l=>({name:l.name,confidence:l.confidence,reason:l.reason})):[],h=[];return r.some(l=>l.exists)&&h.push("ripple-analysis"),u&&h.push("portal-compliance"),o.some(l=>l.startsWith("^"))&&h.push("gate-validation"),o.some(l=>l.startsWith("!"))&&h.push("signal-registration"),h.push("purpose-coverage"),{affectedSymbols:r,rippleAnalysis:a,portalStatus:d,taskAddsRoutes:u,suggestedAgents:g,requiredChecks:h}}function H(p,s,e,t$1){let n=[],o=a$2(e),r=o.status==="ok"?o.data:null,a=r?b$2(r):[],i=r?.routes?Object.keys(r.routes):[];for(let g of p){let h=A.isAbsolute(g)?g:A.join(e,g);if(!w.existsSync(h))continue;let l;try{l=w.readFileSync(h,"utf-8");}catch{continue}for(let y of ue){y.lastIndex=0;let k;for(;(k=y.exec(l))!==null;){let f=k[2]||k[0];f&&f.startsWith("/")&&(!i.some(S=>S.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===f)&&r?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${f}" found in ${A.relative(e,h)} but not declared in portal.yaml`,file:A.relative(e,h),suggestion:"Add this route to portal.yaml with appropriate ^gates. Run paradigm_gates_for_route to get suggestions."}):!r&&f.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${f}" found but no portal.yaml exists`,file:A.relative(e,h),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 h=g.slice(1);a.includes(h)||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.`});}p.length>=5&&s.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${p.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 c=n.filter(g=>g.severity==="error").length,d=n.filter(g=>g.severity==="warning").length,u=4,m="pass";return c>0?m="violations":d>0&&(m="warnings"),{status:m,violations:n,summary:{totalChecks:u,passed:u-(c>0?1:0)-(d>0?1:0),warnings:d,errors:c},blocksCompletion:c>0}}var pe={architect:"opus",security:"opus",reviewer:"sonnet",builder:"haiku",tester:"haiku"},he=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","role","access control","vulnerability","injection","xss","csrf"];function me(p,s){let e=p.toLowerCase(),t=he.some(r=>e.includes(r.toLowerCase())),n=p.includes("^"),o=false;return t||n||o}var ye=["rename","refactor","migrate","restructure","move","reorganize"];function be(p){let s=p.toLowerCase();return ye.some(e=>s.includes(e))}var E=class{spawner;auditLogger;rootDir;constructor(s){this.rootDir=s,this.spawner=new b(s),this.auditLogger=new a(s);}async initialize(){await this.spawner.initialize();}async orchestrate(s,e={}){let t=e.mode||"faceted",n=Date.now(),o$1=this.generateOrchestrationId(),r={success:false,mode:t,orchestrationId:o$1,task:s,agentsSpawned:0,totalTokens:{input:0,output:0,total:0},totalCost:0,duration_ms:0,agentResults:[]};try{let a;if(e.pmGovernance?.enabled)try{let{aggregateFromDirectory:c}=await import('./dist-TNE4GFT7.js'),d=await c(this.rootDir),u=o(d);a=V(s,this.rootDir,u);}catch{}if(t==="solo"){let c=await this.runSoloMode(s,e);r.agentsSpawned=1,r.agentResults=[c],r.success=c.success,c.relay&&(r.totalTokens=c.relay.metrics.tokens_used,r.totalCost=b$1(r.totalTokens,e.orchestratorModel||"opus"));}else {let c=await this.runFacetedMode(s,e);r.agentsSpawned=c.results.length,r.agentResults=c.results,r.totalTokens=c.totalTokens,r.totalCost=c.totalCost,r.success=c.success,r.parallelBuilderStats=c.parallelBuilderStats;}if(e.pmGovernance?.enabled&&a)try{let{aggregateFromDirectory:c}=await import('./dist-TNE4GFT7.js'),d=await c(this.rootDir),u=o(d),m=[],g=[];for(let l of r.agentResults)l.relay?.outputs?.artifacts&&m.push(...l.relay.outputs.artifacts.map(y=>y.path));for(let l of a.affectedSymbols)g.push(l.symbol);let h=H(m,g,this.rootDir,u);r.complianceReport={preflight:a,postflight:h},e.pmGovernance.blockOnViolations&&h.blocksCompletion&&(r.success=!1);}catch{r.complianceReport={preflight:a};}r.duration_ms=Date.now()-n;let i=this.auditLogger.startOrchestration(o$1,s,t);return i.completed=new Date().toISOString(),i.status=r.success?"success":"failed",i.totals={duration_ms:r.duration_ms,tokens:r.totalTokens.total,cost_usd:r.totalCost,agents_spawned:r.agentsSpawned,files_created:0,files_modified:0},this.auditLogger.saveOrchestration(i),r.log=i,r}catch(a){return r.error=a instanceof Error?a.message:String(a),r.duration_ms=Date.now()-n,r}}async compare(s,e={}){let t=await this.orchestrate(s,{...e,mode:"solo"}),n=await this.orchestrate(s,{...e,mode:"faceted"}),o=t.totalTokens.total-n.totalTokens.total,r=t.totalCost-n.totalCost,a=t.duration_ms-n.duration_ms,i="tie";return n.success&&!t.success?i="faceted":t.success&&!n.success?i="solo":n.totalCost<t.totalCost*.8?i="faceted":t.totalCost<n.totalCost*.8&&(i="solo"),{solo:t,faceted:n,comparison:{winner:i,tokensSaved:o,costDiff:r,timeDiff:a,soloSucceeded:t.success,facetedSucceeded:n.success}}}async runSoloMode(s,e$1){let n=e(this.rootDir)?.team.default_agent||"architect",o=e$1.orchestratorModel||"opus",r={model:o,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.budget,onMessage:e$1.onMessage?i=>e$1.onMessage("solo",i):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart("solo",s,o);let a=await this.spawner.spawn(n,s,r);return e$1.onAgentComplete&&e$1.onAgentComplete("solo",a,o),a}async runFacetedMode(s,e$1){let t=e(this.rootDir);if(!t)return {success:false,results:[],totalTokens:{input:0,output:0,total:0},totalCost:0};let n="";if(be(s)){let h=a$1(s);if(h.length>0){let l=[];l.push(`## Auto-Ripple Analysis
|
|
3
|
-
`),l.push("The following symbols are affected by this refactoring:"),l.push("");for(let y of h.slice(0,5))l.push(`- **${y}**: Check dependencies before renaming/moving`);l.push(""),l.push("**Recommendation:** Run `paradigm_ripple` for each symbol before making changes."),n=l.join(`
|
|
4
|
-
`);}}let o=this.planAgentSequence(s,t.agents),r=this.groupByStage(o),a=[],i={input:0,output:0,total:0},c=0,d=new Map,u=true,m,g=Array.from(r.keys()).sort((h,l)=>h-l);for(let h of g){let l=r.get(h)||[];if(l.length===0)continue;if(e$1.checkpoints?.beforeAgentSpawn&&e$1.onCheckpoint){let f=l.map(S=>S.agent).join(", ");if(!await e$1.onCheckpoint(`Stage ${h}: Spawn ${f}${l.length>1?" (parallel)":""}`)){u=false;break}}let y=l.map(async f=>{let b=e$1.agentBudgets?.[f.agent]?.maxTokens?"haiku":f.model||pe[f.agent]||"sonnet",S="";if(f.dependsOn.length>0){let R=f.dependsOn.map(I=>d.get(I)).filter(Boolean);R.length>0&&(S=R.join(`
|
|
5
|
-
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
`));}let x=S;f.agent==="architect"&&n&&(x=n+(S?`
|
|
9
|
-
|
|
10
|
-
---
|
|
11
|
-
|
|
12
|
-
`+S:""));let P=x?`${f.subtask}
|
|
13
|
-
|
|
14
|
-
## Context from previous agents:
|
|
15
|
-
${x}`:f.subtask,O={model:b,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.agentBudgets?.[f.agent]||e$1.budget,onMessage:e$1.onMessage?R=>e$1.onMessage(f.agent,R):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart(f.agent,f.subtask,b);let C=await this.spawner.spawn(f.agent,P,O);return e$1.onAgentComplete&&e$1.onAgentComplete(f.agent,C,b),{step:f,result:C,model:b}}),k=await Promise.all(y);for(let{step:f,result:b,model:S}of k){if(a.push(b),b.relay){i.input+=b.relay.metrics.tokens_used.input,i.output+=b.relay.metrics.tokens_used.output,i.total+=b.relay.metrics.tokens_used.total,c+=b$1(b.relay.metrics.tokens_used,S);let x=b.relay.handoff?.context||`${f.agent} completed: ${b.relay.outputs.decisions.join(", ")||"task done"}`;if(d.set(f.agent,x),f.agent==="architect"&&b.relay){let P=this.extractFilePlanFromRelay(b);if(P&&P.length>0){let O=this.planBuilderStages(P);if(O.hasFilePlan&&O.totalBuilders>1){let C=await this.runParallelBuilders(O,d.get("architect")||"",e$1);a.push(...C.results),i.input+=C.totalTokens.input,i.output+=C.totalTokens.output,i.total+=C.totalTokens.total,c+=C.totalCost,C.success||(u=false),m={usedFilePlan:true,totalSubPhases:O.stages.length,totalParallelBuilders:O.totalBuilders,filesCreated:O.totalFiles};for(let[R,I]of r){let X=I.filter(Q=>Q.agent!=="builder");r.set(R,X);}}}}}!b.success&&f.required&&(u=false);}if(!u||e$1.checkpoints?.afterAgentComplete&&e$1.onCheckpoint&&!await e$1.onCheckpoint(`Stage ${h} completed. Continue to next stage?`))break}return {success:u,results:a,totalTokens:i,totalCost:c,parallelBuilderStats:m}}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(`
|
|
16
|
-
`),r=null,a=false,i={};for(let c of o){let d=c.trim();if(!(!d||d.startsWith("#"))){if(d.startsWith("- group:")){r&&(i.path&&(r.files.push({path:i.path,description:i.description||""}),i={}),e.push(r)),r={group:d.split(":")[1].trim(),subPhase:0,files:[]},a=false;continue}if(r){if(d.startsWith("subPhase:")){r.subPhase=parseInt(d.split(":")[1].trim(),10)||0;continue}if(d==="files:"){a=true;continue}if(a){if(d.startsWith("- path:")){i.path&&r.files.push({path:i.path,description:i.description||""}),i={path:d.split(":").slice(1).join(":").trim().replace(/^["']|["']$/g,"")};continue}if(d.startsWith("description:")){i.description=d.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=K(s),r=[],a=me(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"),c=a||n.includes("auth")||n.includes("security")||n.includes("gate")||t.some(l=>l.startsWith("^"));if(i&&e.architect&&r.push({agent:"architect",subtask:`Design and specify: ${s}`,required:true,stage:0,dependsOn:[],model:"opus"}),c&&e.security&&r.push({agent:"security",subtask:`Review security aspects of: ${s}`,required:a,stage:0,dependsOn:[],model:"opus"}),(n.includes("build")||n.includes("implement")||n.includes("create")||n.includes("add")||n.includes("fix"))&&e.builder){let l=i&&e.architect?["architect"]:[];r.push({agent:"builder",subtask:`Implement: ${s}`,required:true,stage:l.length>0?1:0,dependsOn:l,model:"haiku"});}let u=n.includes("review")||n.includes("check"),m=n.includes("test")||n.includes("verify")||n.includes("validate"),g=r.some(l=>l.agent==="builder"),h=g?2:i?1:0;if(u&&e.reviewer&&r.push({agent:"reviewer",subtask:`Review: ${s}`,required:false,stage:h,dependsOn:g?["builder"]:[],model:"sonnet"}),m&&e.tester&&r.push({agent:"tester",subtask:`Test and validate: ${s}`,required:false,stage:h,dependsOn:g?["builder"]:[],model:"haiku"}),r.length===0){let l=o.recommendedAgents;if(l.includes("architect")&&e.architect&&r.push({agent:"architect",subtask:`Design: ${s}`,required:true,stage:0,dependsOn:[],model:B("architect",o)}),(l.includes("security")||a)&&e.security&&r.push({agent:"security",subtask:`Security review: ${s}`,required:a,stage:0,dependsOn:[],model:"opus"}),l.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(k=>k.stage===0).map(k=>k.agent),model:B("builder",o)});}if(l.includes("tester")&&e.tester){let y=r.find(k=>k.agent==="builder")?.stage??0;r.push({agent:"tester",subtask:`Test: ${s}`,required:false,stage:y+1,dependsOn:e.builder?["builder"]:[],model:B("tester",o)});}}return r.sort((l,y)=>l.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 c=e.get(i.subPhase)||[];c.push(i),e.set(i.subPhase,c);}let t=[],n=[...e.keys()].sort((i,c)=>i-c),o=[],r=0,a=0;for(let i of n){let c=e.get(i),d=[];for(let u=0;u<c.length;u++){let m=c[u];a+=m.files.length,r++,d.push({agent:`builder-${i}-${u}`,group:m.group,files:m.files,availableFiles:[...o]});}t.push({subPhase:i,builders:d});for(let u of c)for(let m of u.files)o.push(m.path);}return {hasFilePlan:true,stages:t,totalFiles:a,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(`
|
|
17
|
-
`)}async runParallelBuilders(s,e,t){let n=[],o={input:0,output:0,total:0},r=0,a=true;for(let i of s.stages){if(t.checkpoints?.beforeAgentSpawn&&t.onCheckpoint){let u=i.builders.map(g=>g.group).join(", ");if(!await t.onCheckpoint(`Builder Sub-phase ${i.subPhase}: ${u}${i.builders.length>1?" (parallel)":""}`)){a=false;break}}let c=i.builders.map(async u=>{let m=this.buildParallelBuilderPrompt(u.files,u.availableFiles,e,u.group),g={model:"haiku",workingDirectory:t.workingDirectory||this.rootDir,mcpServerPath:t.mcpServerPath,budget:t.budget,onMessage:t.onMessage?l=>t.onMessage(u.agent,l):void 0,onCheckpoint:t.onCheckpoint};t.onAgentStart&&t.onAgentStart(u.agent,`Implement ${u.group}`,"haiku");let h=await this.spawner.spawn("builder",m,g);return t.onAgentComplete&&t.onAgentComplete(u.agent,h,"haiku"),{builder:u,result:h}}),d=await Promise.all(c);for(let{result:u}of d)n.push(u),u.relay&&(o.input+=u.relay.metrics.tokens_used.input,o.output+=u.relay.metrics.tokens_used.output,o.total+=u.relay.metrics.tokens_used.total,r+=b$1(u.relay.metrics.tokens_used,"haiku")),u.success||(a=false);if(!a||t.checkpoints?.afterAgentComplete&&t.onCheckpoint&&!await t.onCheckpoint(`Sub-phase ${i.subPhase} complete. Continue to next sub-phase?`))break}return {success:a,results:n,totalTokens:o,totalCost:r}}};var J=class{rootDir;orchestrationsDir;constructor(s){this.rootDir=s,this.orchestrationsDir=A.join(s,".paradigm","orchestrations"),this.ensureOrchestrationDir();}async startBackground(s,e={}){let t=this.generateId(),n=A.join(this.orchestrationsDir,`${t}.output`),o=A.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=A.join(this.orchestrationsDir,`${s}.yaml`);if(!w.existsSync(e))return null;try{let t=w.readFileSync(e,"utf-8");return F.load(t)}catch{return null}}listOrchestrations(s={}){let e=w.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=A.join(this.orchestrationsDir,n);try{let r=w.readFileSync(o,"utf-8"),a=F.load(r);if(s.status&&!(Array.isArray(s.status)?s.status:[s.status]).includes(a.status))continue;t.push(a);}catch{}}return t}getRunning(){return this.listOrchestrations({status:"running"})}getOutput(s,e={}){let t=this.getOrchestration(s);if(!t||!w.existsSync(t.outputFile))return "";let n=w.readFileSync(t.outputFile,"utf-8");return e.lines?n.split(`
|
|
18
|
-
`).slice(-e.lines).join(`
|
|
19
|
-
`):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=A.join(this.rootDir,n.path);w.existsSync(o)&&w.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(`
|
|
20
|
-
`)}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=A.join(this.orchestrationsDir,`${s}.status`);w.writeFileSync(o,JSON.stringify({id:s,status:t.status,completed:t.completed,task:t.task}));break;}}ensureOrchestrationDir(){w.existsSync(this.orchestrationsDir)||w.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=A.join(this.orchestrationsDir,`${s.id}.yaml`);w.writeFileSync(e,F.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 E(this.rootDir);await o.initialize();let r=w.createWriteStream(n.outputFile,{flags:"a"}),a=await o.orchestrate(e,{...t,onMessage:(i,c)=>{c.type==="text"&&r.write(`[${i}] ${c.content}
|
|
21
|
-
`),t.onMessage?.(i,c);},onAgentStart:(i,c,d)=>{r.write(`
|
|
22
|
-
\u25B6 ${i}: ${c}
|
|
23
|
-
`),t.onAgentStart?.(i,c,d);},onAgentComplete:(i,c,d)=>{let u=c.success?"\u2713":"\u2717";r.write(`${u} ${i} completed
|
|
24
|
-
`),t.onAgentComplete?.(i,c,d);}});r.end(),this.markComplete(s,a),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{E as a,J as b};
|