@a-company/paradigm 6.6.6 → 7.0.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-YO2V2WYA.js} +1 -1
- package/dist/{agents-suggest-IKY6VD2R.js → agents-suggest-WZEGQT5E.js} +1 -1
- package/dist/ambient-7HBJHJL2.js +2 -0
- package/dist/{ambient-FNNFB4AP.js → ambient-OX7YJ4PJ.js} +1 -1
- package/dist/ambient-SST5CLEC.js +35 -0
- package/dist/captain-YUP3KVCA.js +2 -0
- package/dist/chunk-33ERV2MW.js +18 -0
- package/dist/chunk-3MZ4J2LF.js +2 -0
- package/dist/chunk-47YPID6H.js +142 -0
- package/dist/chunk-6AKNXD22.js +32 -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-DLMDHS2X.js +10 -0
- package/dist/chunk-FRQRREJ6.js +29 -0
- package/dist/{chunk-5RFISGUW.js → chunk-G6DK3ND3.js} +250 -25
- package/dist/{chunk-XKNJSPB5.js → chunk-JCGCPAHF.js} +1 -1
- package/dist/chunk-K54L6CFR.js +25 -0
- package/dist/chunk-QBIQ2FYB.js +20 -0
- package/dist/chunk-QEQCPVF5.js +4 -0
- package/dist/chunk-ROU3F2HZ.js +6 -0
- package/dist/chunk-S4J337EQ.js +504 -0
- package/dist/chunk-V6MIKLMY.js +18 -0
- package/dist/chunk-WROJSWAO.js +93 -0
- package/dist/{chunk-TQOT2LBO.js → chunk-YXLGVOZO.js} +1 -1
- package/dist/chunk-ZSWXLFN7.js +12 -0
- package/dist/{compliance-J3VOV445.js → compliance-MLG4W6S4.js} +1 -1
- package/dist/{diff-ANKTFDRA.js → diff-MC6AXLKX.js} +1 -1
- package/dist/{docs-TSAAS4W3.js → docs-3YFNNZRV.js} +1 -1
- package/dist/doctor-CBZYYQQH.js +2 -0
- package/dist/{hooks-45WDP6QS.js → hooks-AXBWYJ5V.js} +1 -1
- package/dist/index.js +4 -4
- package/dist/mcp.js +3 -3
- package/dist/{migrate-R64OQGSM.js → migrate-5M4KUQ2L.js} +1 -1
- package/dist/{nomination-engine-NCLTGMAK.js → nomination-engine-AQHU2KBU.js} +1 -1
- package/dist/notebook-loader-6DYFMNJ2.js +2 -0
- package/dist/orchestrate-GMYEBA5T.js +8 -0
- package/dist/orchestration-G5MAY6IA.js +2 -0
- package/dist/propose-block-ZEMEWJQF.js +2 -0
- package/dist/{providers-TBPOE4DI.js → providers-5EHD45C6.js} +1 -1
- package/dist/reindex-XTRF23F7.js +2 -0
- package/dist/{serve-3FMUWW5K.js → serve-SMGWGJLM.js} +1 -1
- package/dist/session-tracker-BZ7FU4AT.js +2 -0
- package/dist/session-work-log-QXPAXY5K.js +2 -0
- package/dist/session-work-log-T2IE4Y4T.js +2 -0
- package/dist/{shift-TNA2E5O7.js → shift-JBCEDCGA.js} +2 -2
- package/dist/solo-OWR3MX74.js +3 -0
- package/dist/{spawn-KKDDR6UR.js → spawn-PHA2SVQ3.js} +1 -1
- package/dist/task-loader-IGQQ6ZFL.js +2 -0
- package/dist/task-settlement-NW4XMJGJ.js +3 -0
- package/dist/{team-PEGP6F7S.js → team-J2YXPEGX.js} +1 -1
- package/dist/team-funnel-RAJ6EDG3.js +2 -0
- package/dist/tools-HNJ7D5IO.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-B8hm_MdR.js} +2 -2
- package/dist/university-ui/assets/{index-DrtbBC21.js.map → index-B8hm_MdR.js.map} +1 -1
- package/dist/university-ui/index.html +1 -1
- 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-XQLO5URP.js +0 -11
- package/dist/doctor-L5XZENCF.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/tools-PUSDXUYE.js +0 -2
- /package/dist/{chunk-HXGYVS2N.js → chunk-ECLUYHAR.js} +0 -0
- /package/dist/{platform-server-ANOALDPL.js → platform-server-WIBVYHIV.js} +0 -0
|
@@ -0,0 +1,32 @@
|
|
|
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};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import*as r from'fs';import*as l from'path';var f=".paradigm/events/team-funnel.jsonl",d=["trivial","hotfix","user-directed","exploratory"];function y(a,s){try{let n=l.join(a,f),o=l.dirname(n);r.existsSync(o)||r.mkdirSync(o,{recursive:!0});let e={timestamp:new Date().toISOString(),...s};r.appendFileSync(n,JSON.stringify(e)+`
|
|
3
|
+
`,"utf8");}catch{}}function p(a,s){try{let n=l.join(a,f);if(!r.existsSync(n))return [];let o=s!==void 0?Date.now()-s*24*60*60*1e3:void 0;return r.readFileSync(n,"utf8").trim().split(`
|
|
4
|
+
`).filter(e=>e.trim()).map(e=>{try{return JSON.parse(e)}catch{return null}}).filter(e=>{if(e===null||!e.type)return !1;if(o===void 0)return !0;let i=Date.parse(e.timestamp);return !Number.isNaN(i)&&i>=o})}catch{return []}}function g(a,s=30){let n=p(a,s),o=n.filter(t=>t.type==="eligible").length,e=n.filter(t=>t.type==="orchestrated").length,i=n.filter(t=>t.type==="solo-declared").length,c=n.filter(t=>t.type==="bypass").length,u=e+i+c,m={};for(let t of n)t.type==="solo-declared"&&t.reason&&(m[t.reason]=(m[t.reason]||0)+1);return {windowDays:s,eligible:o,orchestrated:e,soloDeclared:i,bypasses:c,invocationRate:u>0?e/u:null,legibleRate:u>0?(e+i)/u:null,soloByReason:m}}export{d as a,y as b,p as c,g as d};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {s,r as r$1}from'./chunk-33ERV2MW.js';import {b as b$1,a as a$1}from'./chunk-EK4ZRIFJ.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 E(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s.id}.json`);r.writeFileSync(t,JSON.stringify(s,null,2));}function O(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"),o=h.load(t);o&&typeof o=="object"&&(e={version:o.version||"1.0",antipatterns:Array.isArray(o.antipatterns)?o.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",A=10080*60*1e3,C=class{session;rootDir=null;_recovered=false;lastLoreEntryId=null;constructor(){this.session=this.createNewSession();}setRootDir(s$1){this.rootDir=s$1;try{let{clearSessionWorkLog:e}=(s(),d(r$1));e(s$1);}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>A)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{E as a,O 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};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import*as a from'fs/promises';import*as n from'path';import*as m from'js-yaml';var u=n.join(".paradigm","remediations");function b(){return "rmd-"+Date.now().toString(36)}function k(){return [{name:"paradigm_propose_block",description:"Author a soft-block (remediation) that the Stop hook will honor until resolved. Use when your archetype detects a condition the user should resolve before continuing (e.g., coverage drop, missing aspect, broken anchor). User can override via `paradigm override <id>` or PARADIGM_OVERRIDE env var. v6.1: only severity=guard hard-blocks; advise/auto-author are informational. ~150 tokens.",inputSchema:{type:"object",properties:{claimant:{type:"string",description:'Archetype id authoring this block (e.g., "compliance", "security"). REQUIRED \u2014 do not infer.'},severity:{type:"string",enum:["advise","auto-author","guard"],description:"Block intent for this event. v6.1: only `guard` hard-blocks; `advise`/`auto-author` are informational."},reason:{type:"string",description:"Free-text explanation surfaced to the user verbatim. Be specific (component name, file path)."},unblock_hint:{type:"string",description:"Plain-string remediation hint (v6.1; JSONLogic predicates ship v6.2). Tell the user how to resolve."},expires_at:{type:"string",description:"OPTIONAL ISO 8601 UTC timestamp. After this, Check 14 silently skips the remediation. Use for time-bounded conditions."},target:{type:"object",description:"OPTIONAL context: {file, symbol, line}.",properties:{file:{type:"string"},symbol:{type:"string"},line:{type:"number"}}}},required:["claimant","severity","reason","unblock_hint"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function x(g,e,h){if(g!=="paradigm_propose_block")return {handled:false,text:""};let s=e.claimant,r=e.severity,d=e.reason,c=e.unblock_hint,o=e.expires_at,t=e.target;if(!s||!r||!d||!c)return {handled:true,text:JSON.stringify({error:"Missing required field. Required: claimant, severity, reason, unblock_hint."},null,2)};let i=b(),f=new Date().toISOString(),l={id:i,claimant:s,severity:r,reason:d,unblock_hint:c,created:f};o&&(l.expires_at=o),t&&(t.file||t.symbol||t.line!=null)&&(l.target=t);let p=n.join(h.rootDir,u);await a.mkdir(p,{recursive:true});let y=n.join(p,`${i}.yaml`),v=m.dump(l,{lineWidth:100,sortKeys:false});return await a.writeFile(y,v,"utf8"),{handled:true,text:JSON.stringify({id:i,path:n.join(u,`${i}.yaml`),claimant:s,severity:r,...o?{expires_at:o}:{},note:`Stop hook will ${r==="guard"?"block":"note"} on next run. User can clear with: paradigm override ${i}`},null,2)}}export{k as a,x as b};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {a as a$1}from'./chunk-FYDRENK7.js';import {f,a}from'./chunk-ECLUYHAR.js';import {e}from'./chunk-YXLGVOZO.js';import {b,d,c}from'./chunk-EKZDFEJW.js';import*as h from'fs';import*as P from'path';import*as M from'js-yaml';import {glob}from'glob';import {EventEmitter}from'events';var W=/[#$^!~][a-zA-Z0-9_-]+/g;function G(a){let e=a.match(W)||[];return [...new Set(e)]}function K(a){let e=a.charAt(0);return {"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"}[e]||"unknown"}async function j(a,e,s,t){let o=P.join(s,".paradigm"),n=G(e),c=J(a,t),u=N(c.include||[],n),l=c.exclude||[],p=await X(s,u,l);return {systemPrompt:await Y(a,o,n),files:p,symbols:n}}function J(a,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/**"]}}[a.name]||{include:[".purpose","portal.yaml"],exclude:["node_modules/**","dist/**"]}}function N(a,e){let s=[];for(let t of a)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 X(a,e,s){let t=new Set;for(let o of e)try{let n=await glob(o,{cwd:a,ignore:s,nodir:!0,absolute:!1});for(let c of n)t.add(c);}catch{}return Array.from(t)}async function Y(a,e,s){let t=[],o=P.join(e,"config.yaml"),n=null;if(h.existsSync(o))try{n=M.load(h.readFileSync(o,"utf-8"));}catch{}if(t.push(`# ${a.name.charAt(0).toUpperCase()+a.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[u,l]of Object.entries(n["symbol-system"]))t.push(`| \`${u}\` | ${l.name} | ${l.description} |`);t.push("");}if(n?.conventions){let u=Z(n.conventions,a.name);if(u.length>0){t.push(`## Conventions
|
|
6
|
+
`);for(let l of u)t.push(`- ${l}`);t.push("");}}if(s.length>0){t.push(`## Symbols in Scope
|
|
7
|
+
`);for(let u of s){let l=K(u);t.push(`- \`${u}\` (${l})`);}t.push("");}let c=q(a.name);if(c.length>0){t.push(`## Tips for This Role
|
|
8
|
+
`);for(let u of c)t.push(`- ${u}`);t.push("");}return t.join(`
|
|
9
|
+
`)}function Z(a,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 a.filter(o=>t.some(n=>o.toLowerCase().includes(n)))}function q(a){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"]}[a]||[]}var x=class extends EventEmitter{config;usage;records=[];configPath;constructor(e){super(),this.configPath=P.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 c=this.usage.tokens.total+s;if(c>this.config.maxTokens)return {allowed:false,reason:`Global token limit exceeded: ${d(c)} > ${d(this.config.maxTokens)}`,usage:this.usage,warningLevel:"exceeded"}}if(this.config.maxCostUsd){let c$1=this.usage.cost+t;if(c$1>this.config.maxCostUsd)return {allowed:false,reason:`Cost ceiling exceeded: ${c(c$1)} > ${c(this.config.maxCostUsd)}`,usage:this.usage,warningLevel:"exceeded"}}let o=this.config.agentLimits?.[e];if(o){let c$1=this.usage.byAgent[e]||{tokens:{total:0},cost:0};if(o.maxTokens){let u=c$1.tokens.total+s;if(u>o.maxTokens)return {allowed:false,reason:`Agent '${e}' token limit exceeded: ${d(u)} > ${d(o.maxTokens)}`,usage:this.usage,warningLevel:"exceeded"}}if(o.maxCostUsd){let u=c$1.cost+t;if(u>o.maxCostUsd)return {allowed:false,reason:`Agent '${e}' cost limit exceeded: ${c(u)} > ${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 c={timestamp:new Date().toISOString(),agent:e,model:t,tokens:s,cost:n,orchestrationId:o};this.records.push(c),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=M.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 O=class{provider=null;budgetTracker=null;auditLogger=null;rootDir;constructor(e){this.rootDir=e;}async initialize(){await f(),this.provider=a(),this.budgetTracker=new x(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 c=t.provider||this.provider.name,u=a(c);if(!u)return {success:false,error:`Provider '${c}' not available`,sessionId:""};if(!await u.isAvailable())return {success:false,error:`Provider '${c}' not configured (missing API key?)`,sessionId:""};let p=this.generateSessionId(e$1),C=this.loadFacetConfig(e$1),S=await j(n,s,this.rootDir,C),y=t.model||C?.defaultModel||"sonnet",B={model:y,task:s,context:S,budget:t.budget,mcpServerPath:t.mcpServerPath,workingDirectory:t.workingDirectory||this.rootDir,checkpoints:t.checkpoints,timeout:t.timeout},T=Date.now(),z=new Date().toISOString(),i={agent:e$1,task:s,status:"success",completionVerified:false,outputs:{artifacts:[],symbols:S.symbols,decisions:[]},metrics:{tokens_used:{input:0,output:0,total:0},duration_ms:0,files_read:0,files_written:0}},E=32*1024,w="";try{for await(let r of u.spawn(n,B)){if(r.usage&&(i.metrics.tokens_used=r.usage),r.type==="text"&&r.content&&(w=(w+r.content).slice(-E)),r.type==="tool_use"){if(r.toolName==="read_file")i.metrics.files_read++;else if(r.toolName==="write_file"){i.metrics.files_written++;let f=r.toolInput?.path;f&&i.outputs.artifacts.push({path:f,action:"modified"});}}if(t.checkpoints&&r.type==="tool_use"&&this.shouldPauseForCheckpoint(r,t.checkpoints)&&t.onCheckpoint&&!await t.onCheckpoint(`Agent wants to ${r.toolName}: ${JSON.stringify(r.toolInput)}`)){i.status="blocked";break}if(t.onMessage&&t.onMessage(r),r.type==="error"&&(i.status="failed"),this.budgetTracker&&r.usage&&!this.budgetTracker.checkBudget(e$1,r.usage.total).allowed){i.status="failed";break}}if(i.metrics.duration_ms=Date.now()-T,i.rawResponse=w,this.budgetTracker&&this.budgetTracker.recordUsage(e$1,i.metrics.tokens_used,y),i.status==="success"){let r=i.outputs.artifacts.length>0,f=i.outputs.decisions.length>0,v=!!i.handoff,U=i.metrics.files_written>0,H=e$1==="architect";(e$1==="builder"&&!U&&!v||!r&&!f&&!v&&!U)&&(i.status="partial"),i.completionVerified=!0,i.status==="partial"&&!H&&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 r={name:e$1,model:y,started:z,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,r);}return {success:i.status==="success"||i.status==="partial",relay:i,sessionId:p}}catch(r){return {success:false,error:r instanceof Error?r.message:String(r),sessionId:p,relay:{...i,status:"failed",rawResponse:w,metrics:{...i.metrics,duration_ms:Date.now()-T}}}}}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=P.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 M.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{G as a,O as b};
|
|
@@ -0,0 +1,29 @@
|
|
|
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};
|