@a-company/paradigm 7.0.0 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/{accept-orchestration-YO2V2WYA.js → accept-orchestration-WMGFGYDK.js} +1 -1
  2. package/dist/{agent-loader-VGBPL3TH.js → agent-loader-Z753DQWH.js} +1 -1
  3. package/dist/{ambient-OX7YJ4PJ.js → ambient-HAXPDIWK.js} +1 -1
  4. package/dist/ambient-OW5M5LVN.js +2 -0
  5. package/dist/ambient-QB7V4TBR.js +6 -0
  6. package/dist/calibrate-PHVP7RPH.js +4 -0
  7. package/dist/{captain-YUP3KVCA.js → captain-3COP6YTD.js} +1 -1
  8. package/dist/chunk-4CGPLLWQ.js +30 -0
  9. package/dist/{chunk-3MZ4J2LF.js → chunk-CHSU6LTR.js} +1 -1
  10. package/dist/chunk-ECO3LHCE.js +2 -0
  11. package/dist/chunk-EG22HDXI.js +33 -0
  12. package/dist/{chunk-GD4F2HC6.js → chunk-H55W26AR.js} +1 -1
  13. package/dist/{chunk-ROU3F2HZ.js → chunk-HSY75GRR.js} +3 -3
  14. package/dist/chunk-KAUGQMXU.js +4 -0
  15. package/dist/{chunk-QBIQ2FYB.js → chunk-KP5VOYAH.js} +1 -1
  16. package/dist/{chunk-K54L6CFR.js → chunk-OIYJUU6T.js} +4 -4
  17. package/dist/{chunk-47YPID6H.js → chunk-RDWWSQGH.js} +21 -21
  18. package/dist/chunk-RVXQNS6K.js +30 -0
  19. package/dist/{chunk-WROJSWAO.js → chunk-VPNJL4LS.js} +1 -1
  20. package/dist/{chunk-JCGCPAHF.js → chunk-W4BW7GXA.js} +1 -1
  21. package/dist/chunk-XPPFILCM.js +2 -0
  22. package/dist/{chunk-V6MIKLMY.js → chunk-YCDOA5IQ.js} +1 -1
  23. package/dist/chunk-YQK3XU63.js +504 -0
  24. package/dist/{compliance-MLG4W6S4.js → compliance-4P3EE5OA.js} +1 -1
  25. package/dist/{diff-MC6AXLKX.js → diff-VBVIUNL5.js} +1 -1
  26. package/dist/{docs-3YFNNZRV.js → docs-NTP6UENF.js} +1 -1
  27. package/dist/index.js +5 -5
  28. package/dist/journal-loader-CNNA4EAU.js +2 -0
  29. package/dist/lore-loader-HAZ5FRLP.js +2 -0
  30. package/dist/mcp.js +1 -1
  31. package/dist/nomination-engine-ORHH4L2W.js +2 -0
  32. package/dist/{nomination-engine-AQHU2KBU.js → nomination-engine-YRHZZZUN.js} +1 -1
  33. package/dist/notebook-loader-TZVIMNDJ.js +2 -0
  34. package/dist/{orchestrate-GMYEBA5T.js → orchestrate-MLUGQOEJ.js} +1 -1
  35. package/dist/orchestration-O2OVPTIZ.js +2 -0
  36. package/dist/{platform-server-WIBVYHIV.js → platform-server-Y6TLEXR2.js} +1 -1
  37. package/dist/{reindex-XTRF23F7.js → reindex-ZLDQBFUR.js} +1 -1
  38. package/dist/{serve-SMGWGJLM.js → serve-XZ6GBUS3.js} +1 -1
  39. package/dist/{session-work-log-QXPAXY5K.js → session-work-log-FF7CKMWP.js} +1 -1
  40. package/dist/{shift-JBCEDCGA.js → shift-PM4GI736.js} +1 -1
  41. package/dist/{symphony-G6IENE4K.js → symphony-CFAYJGLF.js} +1 -1
  42. package/dist/{symphony-7INZR43F.js → symphony-L56O5ZG3.js} +3 -3
  43. package/dist/{symphony-relay-2RHG25Z4.js → symphony-relay-Y2UR3YNR.js} +1 -1
  44. package/dist/{task-loader-IGQQ6ZFL.js → task-loader-H7HQAYGL.js} +1 -1
  45. package/dist/task-loader-YZME4RKE.js +2 -0
  46. package/dist/{task-settlement-NW4XMJGJ.js → task-settlement-HINBVZBE.js} +2 -2
  47. package/dist/task-settlement-XC6E6JNT.js +3 -0
  48. package/dist/{team-J2YXPEGX.js → team-25LK6CWM.js} +1 -1
  49. package/dist/tools-GAU5WOEI.js +2 -0
  50. package/dist/university-ui/assets/{index-B8hm_MdR.js → index-AbTjHBCf.js} +2 -2
  51. package/dist/university-ui/assets/{index-B8hm_MdR.js.map → index-AbTjHBCf.js.map} +1 -1
  52. package/dist/university-ui/index.html +1 -1
  53. package/dist/work-log-loader-CRVTOMVB.js +2 -0
  54. package/package.json +1 -1
  55. package/dist/ambient-7HBJHJL2.js +0 -2
  56. package/dist/ambient-SST5CLEC.js +0 -35
  57. package/dist/chunk-6AKNXD22.js +0 -32
  58. package/dist/chunk-FRQRREJ6.js +0 -29
  59. package/dist/chunk-QEQCPVF5.js +0 -4
  60. package/dist/chunk-QGZRM6ZB.js +0 -2
  61. package/dist/chunk-S4J337EQ.js +0 -504
  62. package/dist/journal-loader-GLH7XFTK.js +0 -2
  63. package/dist/lore-loader-D2ISOASW.js +0 -2
  64. package/dist/notebook-loader-6DYFMNJ2.js +0 -2
  65. package/dist/orchestration-G5MAY6IA.js +0 -2
  66. package/dist/tools-HNJ7D5IO.js +0 -2
  67. /package/dist/{chunk-CVPKQ3JH.js → chunk-HE2NA5QF.js} +0 -0
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-6AKNXD22.js';import'./chunk-DLMDHS2X.js';import'./chunk-FYDRENK7.js';import'./chunk-ECLUYHAR.js';import'./chunk-TYWB5IQJ.js';import'./chunk-YXLGVOZO.js';import'./chunk-EKZDFEJW.js';import'./chunk-LPBCQM5Y.js';import'./chunk-4GC35IFF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as g from'path';import e from'chalk';async function u(n,s,r){let a=s?g.resolve(s):process.cwd();if(!n){r.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(e.red(`
2
+ import {b}from'./chunk-EG22HDXI.js';import'./chunk-DLMDHS2X.js';import'./chunk-FYDRENK7.js';import'./chunk-ECLUYHAR.js';import'./chunk-TYWB5IQJ.js';import'./chunk-YXLGVOZO.js';import'./chunk-XPPFILCM.js';import'./chunk-MBPLJKE5.js';import'./chunk-EKZDFEJW.js';import'./chunk-LPBCQM5Y.js';import'./chunk-4GC35IFF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as g from'path';import e from'chalk';async function u(n,s,r){let a=s?g.resolve(s):process.cwd();if(!n){r.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(e.red(`
3
3
  Orchestration ID required.`)),console.log(e.gray(`Usage: paradigm team accept <orchestration-id>
4
4
  `)));return}let l=new b(a),o=l.getOrchestration(n);if(!o){r.json?console.log(JSON.stringify({error:"Orchestration not found",id:n})):console.log(e.red(`
5
5
  Orchestration not found: ${n}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- export{p as buildProfileEnrichment,t as checkPathPermission,u as checkToolPermission,x as computeIntegrityHash,k as createAgentProfile,a as decayedConfidence,s as determineIntegrityStatus,w as enforcePermissions,g as findAgentsByNickname,v as getPermissionConstraints,c as isAgentActive,e as listAllGlobalAgentIds,f as loadAgentProfile,i as loadAllAgentProfiles,b as loadProjectRoster,o as mergeAgentProfileWithManifest,l as queryExpertise,h as resolveAgent,r as sanitizeForPrompt,j as saveAgentProfile,d as saveProjectRoster,q as syncExpertiseFromLore,n as updateExpertiseFromAssessment,m as updateExpertiseFromLore,y as verifyIntegrity}from'./chunk-GD4F2HC6.js';import'./chunk-MBPLJKE5.js';import'./chunk-5TAVYPOV.js';
2
+ export{p as buildProfileEnrichment,t as checkPathPermission,u as checkToolPermission,x as computeIntegrityHash,k as createAgentProfile,a as decayedConfidence,s as determineIntegrityStatus,w as enforcePermissions,g as findAgentsByNickname,v as getPermissionConstraints,c as isAgentActive,e as listAllGlobalAgentIds,f as loadAgentProfile,i as loadAllAgentProfiles,b as loadProjectRoster,o as mergeAgentProfileWithManifest,l as queryExpertise,h as resolveAgent,r as sanitizeForPrompt,j as saveAgentProfile,d as saveProjectRoster,q as syncExpertiseFromLore,n as updateExpertiseFromAssessment,m as updateExpertiseFromLore,y as verifyIntegrity}from'./chunk-H55W26AR.js';import'./chunk-MBPLJKE5.js';import'./chunk-5TAVYPOV.js';
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import'./chunk-5TAVYPOV.js';import*as s from'path';import t from'chalk';async function g(n){let e=n.project?s.resolve(n.project):process.cwd(),r=n.dryRun===true,{readPendingVerdicts:a}=await import('./session-work-log-QXPAXY5K.js'),i=a(e);if(i.length===0){console.log(t.dim("[paradigm] No pending verdicts \u2014 postflight skipped."));return}console.log(t.cyan(`[paradigm] Running postflight \u2014 ${i.length} pending verdict(s)${r?" (dry run)":""}...`));let{runPostflightLearning:l}=await import('./ambient-SST5CLEC.js'),o=await l(e,{dry_run:r});if(o.journalsWritten===0&&o.promoted===0){console.log(t.dim("[paradigm] Postflight complete \u2014 no new journals written."));return}console.log(t.green("[paradigm] Postflight complete:")),o.journalsWritten>0&&console.log(` ${t.bold(o.journalsWritten)} journal entries written across ${o.agentsProcessed.length} agent(s)`),o.promoted>0&&console.log(` ${t.bold(o.promoted)} entries auto-promoted to notebooks`);}export{g as ambientPostflightCommand};
2
+ import'./chunk-5TAVYPOV.js';import*as s from'path';import t from'chalk';async function g(n){let e=n.project?s.resolve(n.project):process.cwd(),r=n.dryRun===true,{readPendingVerdicts:a}=await import('./session-work-log-FF7CKMWP.js'),i=a(e);if(i.length===0){console.log(t.dim("[paradigm] No pending verdicts \u2014 postflight skipped."));return}console.log(t.cyan(`[paradigm] Running postflight \u2014 ${i.length} pending verdict(s)${r?" (dry run)":""}...`));let{runPostflightLearning:l}=await import('./ambient-QB7V4TBR.js'),o=await l(e,{dry_run:r});if(o.journalsWritten===0&&o.promoted===0){console.log(t.dim("[paradigm] Postflight complete \u2014 no new journals written."));return}console.log(t.green("[paradigm] Postflight complete:")),o.journalsWritten>0&&console.log(` ${t.bold(o.journalsWritten)} journal entries written across ${o.agentsProcessed.length} agent(s)`),o.promoted>0&&console.log(` ${t.bold(o.promoted)} entries auto-promoted to notebooks`);}export{g as ambientPostflightCommand};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export{a as getAmbientToolsList,b as handleAmbientTool,c as runPostflightLearning}from'./chunk-HSY75GRR.js';import'./chunk-RVXQNS6K.js';import'./chunk-3KVVC4WV.js';import'./chunk-KAUGQMXU.js';import'./chunk-Q527BPUF.js';import'./chunk-KAFQA7HV.js';import'./chunk-33ERV2MW.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-ECO3LHCE.js';import'./chunk-5TAVYPOV.js';
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import {e,g as g$1,b,f as f$1,h as h$1}from'./chunk-YCDOA5IQ.js';import {o,n,m,q,c,g,i,j,a,k,r,s,h,b as b$1}from'./chunk-4CGPLLWQ.js';import'./chunk-7SWEOPWF.js';import {f,p}from'./chunk-H55W26AR.js';import'./chunk-MBPLJKE5.js';import'./chunk-5TAVYPOV.js';import*as _ from'fs';import*as S from'path';import*as E from'js-yaml';var se=".paradigm/decisions";function X(c,e){let t=S.join(c,se);if(!_.existsSync(t))return [];let a=[],n=_.readdirSync(t).filter(i=>i.endsWith(".yaml"));for(let i of n)try{let s=_.readFileSync(S.join(t,i),"utf8"),y=E.load(s);y&&y.id&&a.push(y);}catch{}let r=a;return (r=r.filter(i=>i.status===e.status)),e?.participant&&(r=r.filter(i=>i.participants.some(s=>s.id===e.participant))),e?.symbol&&(r=r.filter(i=>i.symbols_affected?.includes(e.symbol))),e?.tag&&(r=r.filter(i=>i.tags?.some(s=>s.startsWith(e.tag)))),e?.dateFrom&&(r=r.filter(i=>i.timestamp>=e.dateFrom)),e?.dateTo&&(r=r.filter(i=>i.timestamp<=e.dateTo)),r.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),e?.limit&&(r=r.slice(0,e.limit)),r}function _e(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function oe(c){let e=Date.now(),t=c.match(/^(\d+)(m|h|d)$/);if(t){let a=parseInt(t[1],10),n=t[2],r=n==="m"?a*6e4:n==="h"?a*36e5:a*864e5;return new Date(e-r).toISOString()}return c}async function De(c$1,e,t){let a$1=n=>JSON.stringify(n,null,2);switch(c$1){case "paradigm_ambient_nominations":{k(t.rootDir);let r$1=e.pending_only!==false,i=e.limit||20,s$1=g(t.rootDir,{agent:e.agent,urgency:e.urgency,pending_only:r$1,limit:i+20}),y=r(t.rootDir);s$1=s(s$1,y).slice(0,i);let h$1=S.join(t.rootDir,".paradigm/events/nominations.jsonl");if(_.existsSync(h$1))try{let d=_.readFileSync(h$1,"utf8"),l=new Set(s$1.map(u=>u.id)),g=d.trim().split(`
3
+ `).map(u=>{try{let f=JSON.parse(u);return l.has(f.id)?(f.surfaced=!0,JSON.stringify(f)):u}catch{return u}});_.writeFileSync(h$1,g.join(`
4
+ `)+`
5
+ `,"utf8");}catch{}let b={count:s$1.length,nominations:s$1.map(d=>({id:d.id,agent:d.agent,urgency:d.urgency,type:d.type,brief:d.brief,relevance:d.relevance,timestamp:d.timestamp,engaged:d.engaged,response:d.response}))};if(e.include_debates){let l=h(t.rootDir).filter(g=>!g.resolution);b.debates=l.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),b.debate_count=l.length;}return {text:a$1(b),handled:true}}case "paradigm_ambient_events":{let n=e.since?oe(e.since):void 0,r=e.limit||50,i=a(t.rootDir,{type:e.type,source:e.source,symbol:e.symbol,agent:e.agent,since:n,limit:r});return {text:a$1({count:i.length,events:i.map(s=>({id:s.id,type:s.type,source:s.source,timestamp:s.timestamp,path:s.path,symbols:s.symbols,context:s.context,agent:s.agent,tool:s.tool,severity:s.severity}))}),handled:true}}case "paradigm_ambient_engage":{let n=e.nomination_id,r=e.response,i$1=e.reason,s=i(t.rootDir,n,r,i$1);if(s)try{let{appendSessionWorkEntry:h,appendVerdictEntry:b}=await import('./session-work-log-FF7CKMWP.js'),l=g(t.rootDir,{limit:500}).find(u=>u.id===n),g$1={timestamp:new Date().toISOString(),type:"user-verdict",agent:l?.agent,nominationId:n,verdict:r,reason:i$1};h(t.rootDir,g$1),b(t.rootDir,g$1);}catch{}let y=false;return e.resolve_debate&&s&&(y=j(t.rootDir,e.resolve_debate,n,e.reason)),{text:a$1({engaged:s,nomination_id:n,response:r,debate_resolved:y||void 0}),handled:true}}case "paradigm_context_compose":{let n=e.agent,r=e.symbols||[],i=e.include_nominations!==false,s=e.include_decisions!==false,y=e.include_journal!==false,h=e.max_decisions||5,b=e.max_journal||5,d=f(t.rootDir,n);if(!d)return {text:a$1({error:`Agent profile not found: ${n}`}),handled:true};let l=[],g$1=p(d,r);if(g$1.trim()&&l.push(g$1),s){let u=X(t.rootDir,{status:"active",limit:h});if(u.length>0){l.push("## Recent Team Decisions");for(let f of u)l.push(`- **${f.title}**: ${f.decision.slice(0,150)}${f.decision.length>150?"...":""}`);l.push("");}}if(y){let u=c(n,{transferable:true,limit:b});if(u.length>0){l.push("## Transferable Insights");for(let f of u)l.push(`- [${f.trigger}] ${f.insight.slice(0,150)}${f.insight.length>150?"...":""}`);l.push("");}}if(i){let u=g(t.rootDir,{pending_only:true,limit:10});if(u.length>0){l.push("## Pending Nominations");for(let f of u)l.push(`- [${f.urgency}] ${f.brief}`);l.push("");}}return {text:a$1({agent:n,context:l.join(`
6
+ `),sections_included:{profile:true,decisions:s,journal:y,nominations:i}}),handled:true}}case "paradigm_ambient_promote":{let n=e.agent,r=q(t.rootDir,n);return {text:a$1({agent:n,promoted:r.promoted,entries:r.entries}),handled:true}}case "paradigm_ambient_learn":{let n$1=e.agent,r=e.dry_run===true,i=n(t.rootDir,n$1);if(r)return {text:a$1({agent:n$1,dry_run:true,stats:i,note:i.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(i.acceptRate*100).toFixed(0)}% \u2014 ${i.acceptRate>.8?"would lower threshold":i.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let s=m(t.rootDir,n$1);return {text:a$1({agent:n$1,...s,stats:i}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let n=o(t.rootDir);return {text:a$1(n),handled:true}}case "paradigm_ambient_learn_postflight":return {text:a$1(await ce(t.rootDir,e)),handled:true};default:return {text:`Unknown ambient tool: ${c$1}`,handled:false}}}var re={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function ae(c){try{let e=S.join(c,".paradigm","config.yaml");if(_.existsSync(e)){let a=_.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(a)return a[1].trim()}}catch{}return S.basename(c)}async function ce(c,e$1={}){let t=e$1.dry_run===true,a=ae(c),n=e(c).filter(o=>o.verdict&&o.agent),r=g$1(c).filter(o=>o.agent&&o.corrections.length>0),i=b(c);if(n.length===0&&r.length===0)return {sessionEntries:i.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:t,details:[]};let s=new Map;for(let o of n){let m=o.agent;s.has(m)||s.set(m,[]),s.get(m).push(o);}let y=i.filter(o=>o.type==="agent-contribution"),h=new Map;for(let o of y)o.agent&&(h.has(o.agent)||h.set(o.agent,[]),h.get(o.agent).push(o));let b$2=[],d={},l=0;for(let[o,m]of s){d[o]=0;let D=m.filter(p=>p.verdict==="accepted").length;m.filter(p=>p.verdict==="dismissed").length;m.filter(p=>p.verdict==="revised").length;let $=m.length,Z=$>0?D/$:0;for(let p of m){let R=re[p.verdict];if(!R)continue;let ee=h.get(o)?.shift(),A=de(p,ee,{acceptRate:Z,total:$,accepted:D}),te=typeof p.confidence=="number"?p.confidence:p.verdict==="accepted"?.85:p.verdict==="revised"?.6:.4,ne={agent:o,verdict:p.verdict,trigger:R,insight:A,symbols:p.symbols};if(b$2.push(ne),t)d[o]++,l++;else try{b$1(o,{trigger:R,insight:A,confidence_before:p.verdict==="accepted"?.7:.8,confidence_after:te,project:a,transferable:p.verdict==="dismissed",tags:["postflight",`verdict:${p.verdict}`,...(p.symbols||[]).map(ie=>`symbol:${ie}`)]}),d[o]++,l++;}catch{}}}let g=new Set;for(let o of r){let m=o.agent;g.add(m),d[m]===void 0&&(d[m]=0);let D=`Self-revision during iteration round ${o.round}: ${o.corrections.join("; ")}`;if(b$2.push({agent:m,verdict:"iteration-revision",trigger:"self_reflection",insight:D,symbols:o.symbols}),t)d[m]++,l++;else try{b$1(m,{trigger:"self_reflection",insight:D,confidence_before:.6,confidence_after:typeof o.confidence=="number"?o.confidence:.75,project:a,transferable:!1,tags:["postflight","iteration-revision",`round:${o.round}`,...(o.symbols||[]).map(w=>`symbol:${w}`)]}),d[m]++,l++;}catch{}}let u={},f=0,P=new Set([...s.keys(),...g]);if(!t)for(let o of P)try{let m=q(c,o);m.promoted>0&&(u[o]=m.promoted,f+=m.promoted);}catch{}return !t&&n.length>0&&f$1(c,n.map(o=>o.nominationId).filter(Boolean)),!t&&r.length>0&&h$1(c,r.map(o=>o.id)),{sessionEntries:i.length,agentsProcessed:Array.from(P),journalsWritten:l,journalsByAgent:d,promoted:f,promotedByAgent:u,dryRun:t,details:b$2}}function de(c,e,t){let a=c.symbols?.length?` (symbols: ${c.symbols.join(", ")})`:"",n=c.reason?` Reason: ${c.reason}.`:"";switch(c.verdict){case "accepted":return `Contribution accepted by user${a}.${n}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "dismissed":return `Contribution dismissed by user${a}.${n}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "revised":return `Contribution revised by user${a}.${n}`+(c.revisionDelta?` Delta: "${c.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;default:return `Unknown verdict "${c.verdict}"${a}.${n}`}}export{_e as getAmbientToolsList,De as handleAmbientTool,ce as runPostflightLearning};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import {c,e,f,g,a,b}from'./chunk-WR6D3SC6.js';import'./chunk-5TAVYPOV.js';import*as p from'fs';import*as u from'path';var y=8,L=".paradigm/events/estimate-actuals.jsonl",k=".paradigm/learned/token-estimates.json";function S(d,i){if(d.length===0)return 0;let n=[...d].sort((s,o)=>s-o);if(n.length===1)return n[0];let l=i*(n.length-1),r=Math.floor(l),a=Math.ceil(l);if(r===a)return n[r];let t=l-r;return n[r]+(n[a]-n[r])*t}function x(d){let i=new Map;for(let r of d){let a=r.trim();if(!a)continue;let t;try{t=JSON.parse(a);}catch{continue}let s=t.archetype,o=t.taskType,c=t.actualTokens?.total;if(typeof s!="string"||typeof o!="string"||typeof c!="number"||!Number.isFinite(c))continue;let e=`${s}\0${o}`,m=i.get(e);m?m.push(c):i.set(e,[c]);}let n={},l=[];for(let[r,a]of i){let[t,s]=r.split("\0"),o=a.length;if(o>=y){let c={min:Math.round(S(a,.1)),max:Math.round(S(a,.9)),n:o};n[t]||(n[t]={}),n[t][s]=c,l.push({archetype:t,taskType:s,n:o,learned:true,band:c});}else l.push({archetype:t,taskType:s,n:o,learned:false});}return l.sort((r,a)=>r.archetype===a.archetype?r.taskType.localeCompare(a.taskType):r.archetype.localeCompare(a.archetype)),{table:n,groups:l}}async function j(d={}){let i=d.project?u.resolve(d.project):process.cwd(),n=u.join(i,L);if(!p.existsSync(n)){c(`No captured actuals yet (${L} not found).`),e("Run some orchestrations first \u2014 actuals are captured per agent-step.");return}let r=p.readFileSync(n,"utf8").split(`
3
+ `),{table:a$1,groups:t}=x(r),s=t.filter(e=>e.learned),o=t.filter(e=>!e.learned),c$1=u.join(i,u.dirname(k));if(p.existsSync(c$1)||p.mkdirSync(c$1,{recursive:true}),p.writeFileSync(u.join(i,k),JSON.stringify(a$1,null,2)+`
4
+ `,"utf8"),f("Calibration \u2014 learned token-estimate table"),g("Samples read",String(t.reduce((e,m)=>e+m.n,0))),g("Groups",String(t.length)),g("Written to",k),s.length>0){a(""),b(`${s.length} group(s) learned (n >= ${y}):`);for(let e of s)g(`${e.archetype} \xB7 ${e.taskType}`,`${e.band.min}\u2013${e.band.max} tokens (n=${e.band.n})`);}else a(""),c(`No group reached the ${y}-sample floor \u2014 table written empty; planner uses the constant.`);if(o.length>0){a(""),e(`${o.length} group(s) below floor (n < ${y}) \u2014 still using the constant prior:`);for(let e$1 of o)e(` ${e$1.archetype} \xB7 ${e$1.taskType} (n=${e$1.n})`);}}export{x as aggregateActuals,j as calibrateCommand,S as percentile};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- export{E as assembleCaptainBoard,C as getCaptainToolsList,D as handleCaptainTool,F as proposeClaimantFor}from'./chunk-K54L6CFR.js';import'./chunk-QBIQ2FYB.js';import'./chunk-Q527BPUF.js';import'./chunk-RGSFU2YW.js';import'./chunk-TMDPDIWA.js';import'./chunk-KLBH26PA.js';import'./chunk-GRZQIKST.js';import'./chunk-ACJWUOMA.js';import'./chunk-33ERV2MW.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-5TAVYPOV.js';
2
+ export{E as assembleCaptainBoard,C as getCaptainToolsList,D as handleCaptainTool,F as proposeClaimantFor}from'./chunk-OIYJUU6T.js';import'./chunk-KP5VOYAH.js';import'./chunk-Q527BPUF.js';import'./chunk-RGSFU2YW.js';import'./chunk-TMDPDIWA.js';import'./chunk-KLBH26PA.js';import'./chunk-GRZQIKST.js';import'./chunk-ACJWUOMA.js';import'./chunk-33ERV2MW.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-5TAVYPOV.js';
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ import {b}from'./chunk-7SWEOPWF.js';import {i,c,f,j as j$1}from'./chunk-H55W26AR.js';import {a as a$1}from'./chunk-MBPLJKE5.js';import {a}from'./chunk-5TAVYPOV.js';import*as u from'fs';import*as R from'os';import*as p from'path';import*as A from'js-yaml';var et=".paradigm/events",bt="stream.jsonl",O=1e3,x=[];function nt(e){return p.join(e,et,bt)}function St(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${e}-${t}`}function k(e,t){let n={id:St(),timestamp:new Date().toISOString(),...t};x.push(n),x.length>O&&(x=x.slice(-O));try{let o=p.join(e,et);u.mkdirSync(o,{recursive:!0});let r=nt(e);u.appendFileSync(r,JSON.stringify(n)+`
3
+ `,"utf8"),wt(r);}catch{}return n}function wt(e){try{if(u.statSync(e).size>512*1024){let o=u.readFileSync(e,"utf8").trim().split(`
4
+ `);if(o.length>O){let r=o.slice(-O);u.writeFileSync(e,r.join(`
5
+ `)+`
6
+ `,"utf8");}}}catch{}}function qt(e,t){let n=Et(e);return t?.type&&(n=n.filter(o=>o.type===t.type)),t?.source&&(n=n.filter(o=>o.source===t.source)),t?.symbol&&(n=n.filter(o=>o.symbols?.includes(t.symbol))),t?.agent&&(n=n.filter(o=>o.agent===t.agent)),t?.since&&(n=n.filter(o=>o.timestamp>=t.since)),n.sort((o,r)=>r.timestamp.localeCompare(o.timestamp)),t?.limit&&(n=n.slice(0,t.limit)),n}function Et(e){let t=nt(e);if(!u.existsSync(t))return [...x];try{return u.readFileSync(t,"utf8").trim().split(`
7
+ `).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return [...x]}}function ot(e,t,n){let o=0,r=0,i=0,s=0;if(n.symbols?.length&&e.symbols?.length)for(let l of n.symbols)for(let a of e.symbols)tt(l,a)&&(o=Math.max(o,1));if(n.paths?.length&&e.path){for(let l of n.paths)if(tt(l,e.path)){r=1;break}}if(n.concepts?.length){let l=[e.context||"",...e.keywords||[],e.type||""].join(" ").toLowerCase(),a=0;for(let d of n.concepts)d&&l.includes(d.toLowerCase())&&a++;n.concepts.length>0&&(i=a/n.concepts.length);}if(n.signals?.length){for(let l of n.signals)if(l.type===e.type){s=1;break}}let c=[o,r,i,s].sort((l,a)=>a-l),f=c[0]*.5+c[1]*.2+c[2]*.15+c[3]*.15,m=n.threshold??.6;return {agentId:t,score:f,breakdown:{symbolMatch:o,pathMatch:r,conceptMatch:i,signalMatch:s},shouldNominate:f>=m,quietReason:f<m?"below-threshold":void 0}}function tt(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 _t=".paradigm/data-policy.yaml";function U(e){let t=p.join(e,_t);if(!u.existsSync(t))return {...b};try{let n=u.readFileSync(t,"utf8"),o=A.load(n);return Nt(b,o)}catch{return {...b}}}function Nt(e,t){let n={...e};if(t.version&&(n.version=t.version),t.default_ring&&(n.default_ring=t.default_ring),t.observation&&(n.observation={allow:t.observation.allow||e.observation?.allow,deny:[...e.observation?.deny||[],...t.observation.deny||[]].filter((o,r,i)=>i.indexOf(o)===r)}),t.streams){n.streams={...e.streams};for(let o of ["work_log","learning_journal","team_decisions"])t.streams[o]&&(n.streams[o]={...e.streams?.[o],...t.streams[o],deny_content:[...e.streams?.[o]?.deny_content||[],...t.streams[o]?.deny_content||[]].filter((r,i,s)=>s.indexOf(r)===i)});}return t.upstream&&(n.upstream={...e.upstream,...t.upstream}),t.network&&(n.network={...e.network,...t.network}),t.agent_overrides&&(n.agent_overrides={...e.agent_overrides,...t.agent_overrides}),t.deployment&&(n.deployment={...e.deployment,...t.deployment}),n}function B(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(r=>I(r,t))||e.observation?.deny?.some(o=>I(o,t))?false:e.observation?.allow?.length?e.observation.allow.some(o=>I(o,t)):true}function I(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}}function st(e){let t=process.env.HOME||process.env.USERPROFILE||"";return p.join(t,".paradigm","agents",e,"journal")}function xt(){let e=new Date,t=e.toISOString().slice(0,10),n=e.toISOString().slice(11,19).replace(/:/g,""),o=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `LJ-${t}-${n}-${o}`}function Qt(e,t){let n=new Date,o=xt(),r={id:o,agent:e,timestamp:n.toISOString(),...t},i=st(e);u.mkdirSync(i,{recursive:true});let s=p.join(i,`${o}.yaml`);return u.writeFileSync(s,A.dump(r,{lineWidth:120,noRefs:true}),"utf8"),r}function z(e,t){let n=st(e);if(!u.existsSync(n))return [];let o=[],r=u.readdirSync(n).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let c=u.readFileSync(p.join(n,s),"utf8"),f=A.load(c);f&&f.id&&o.push(f);}catch{}let i=o;return t?.trigger&&(i=i.filter(s=>s.trigger===t.trigger)),t?.project&&(i=i.filter(s=>s.project===t.project)),t?.transferable!==void 0&&(i=i.filter(s=>s.transferable===t.transferable)),t?.tag&&(i=i.filter(s=>s.tags?.some(c=>c.startsWith(t.tag)))),t?.dateFrom&&(i=i.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(i=i.filter(s=>s.timestamp<=t.dateTo)),i.sort((s,c)=>c.timestamp.localeCompare(s.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}var lt=p.join(R.homedir(),".paradigm","notebooks"),ft=".paradigm/notebooks",kt="nb-",mt=".yaml";function j(e){if(!e)return "";let t=e.trim();return t=t.replace(/^symbol:/i,""),t=t.replace(/^[#$^!~@&%?]/,""),t.trim().toLowerCase()}function jt(e,t,n){let o=new Map,r=p.join(lt,e);at(r,o);let i=p.join(t,ft,e);at(i,o);let s=Array.from(o.values());if(n?.concepts&&n.concepts.length>0){let c=new Set(n.concepts.map(j));s=s.filter(f=>f.concepts.some(m=>c.has(j(m))));}if(n?.tags&&n.tags.length>0){let c=new Set(n.tags.map(f=>f.toLowerCase()));s=s.filter(f=>f.tags.some(m=>c.has(m.toLowerCase())));}return s.sort((c,f)=>f.appliedCount-c.appliedCount)}function at(e,t){if(u.existsSync(e))try{let n=u.readdirSync(e).filter(o=>o.startsWith(kt)&&o.endsWith(mt));for(let o of n)try{let r=u.readFileSync(p.join(e,o),"utf-8"),i=A.load(r);i?.id&&t.set(i.id,i);}catch{}}catch{}}var W=.5;function ut(e,t,n){let o=Array.from(new Set((t||[]).map(j).filter(Boolean)));if(o.length===0)return {value:W,found:false};let r=jt(e,n,{concepts:o});return r.length===0?{value:W,found:false}:{value:Math.max(...r.map(s=>typeof s.confidence=="number"?s.confidence:W)),found:true}}function vt(e){let t=[e.context,e.snippet,...e.concepts,...e.tags].join(" ").toLowerCase();return ["paradigm","mcp_","mcp tool",".paradigm/","lore entry","lore record","aspect","^gate","portal.yaml",".purpose","sentinel","symphony","ambient nomination","paradigm_"," pan ","agent notebook","concept anchor","symbol system","work log","knowledge stream","nevr.land","neverland"].some(o=>t.includes(o))?"platform-specific":/[#$^!~][a-z][a-z0-9-]{2,}/.test(t)||/\/[a-z0-9_-]{2,}\/[a-z0-9_-]/.test(t)?"project-specific":"generalizable"}function dt(e,t,n,o){let r=new Date().toISOString(),i=(t.concepts[0]||t.context.split(" ").slice(0,4).join(" ")||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),c=`nb-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}-${i}`,f=t.scope??vt({context:t.context,snippet:t.snippet,concepts:t.concepts,tags:t.tags}),m=Array.from(new Set((t.concepts||[]).map(j).filter(Boolean))),l={...t,concepts:m,id:c,scope:f,publishable:t.publishable??true,confidence:t.confidence??.5,appliedCount:0,created:r,updated:r},a=p.join(lt,e);u.existsSync(a)||u.mkdirSync(a,{recursive:true});let d=`${c}${mt}`,g=p.join(a,d),y=A.dump(l,{lineWidth:120,noRefs:true,sortKeys:false});return u.writeFileSync(g,y,"utf-8"),{entry:l,filePath:g}}var _=".paradigm/events",Tt="nominations.jsonl",Pt="promotion-decisions.jsonl",Ot="debates.jsonl",pt=500,Ft=200,Dt=7,At=14,$t=100;function Rt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function Ct(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${e}-${t}`}function yt(e,t){let n=i(e),o=U(e),r=[];for(let m of n){if(!m.attention||!c(m.id,e)||t.path&&!B(o,t.path,m.id))continue;let l=ot(t,m.id,m.attention);l.shouldNominate&&r.push({profile:m,score:l});}if(r.length===0)return {nominations:[],debates:[]};let i$1=J(e,{since:new Date(Date.now()-3e4).toISOString()}),s=r.filter(({profile:m})=>!i$1.find(a=>a.agent===m.id&&a.brief===gt(m,t,{...r.find(d=>d.profile.id===m.id).score})));if(s.length===0)return {nominations:[],debates:[]};let c$1=s.map(({profile:m,score:l})=>{let a=Jt(t,l),d=Lt(m,t);return {id:Rt(),agent:m.id,relevance:l.score,urgency:a,type:d,brief:gt(m,t,l),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});It(e,c$1);let f=Mt(e,c$1);return f.length>0&&Ut(e,f),{nominations:c$1,debates:f}}function Jt(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 Lt(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 gt(e,t,n){let o=e.role||e.id;switch(t.type){case "gate-checked":return `${o}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${o}: ${t.path||"File"} modified \u2014 review for ${e.id==="security"?"security implications":e.id==="tester"?"test coverage":e.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${o}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${o}: New route ${t.symbols?.join(", ")||""} \u2014 ${e.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${o}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${e.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${o}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${o}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${o}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let r=n.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:n.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${o}: ${r}`}}}function Mt(e,t){if(t.length<2)return [];let n=[],o=new Map;for(let r of t)for(let i of r.triggered_by){let s=o.get(i)||[];s.push(r),o.set(i,s);}for(let[r,i]of o){if(i.length<2||new Set(i.map(m=>m.agent)).size<2)continue;let c=new Set(i.map(m=>m.type)),f=c.size>1&&c.has("warning")&&c.has("suggestion");n.push({id:Ct(),topic:`Multiple agents responded to event ${r}`,nominations:i.map(m=>m.id),type:f?"conflicting":"complementary",overlap_events:[r]});}return n}function G(e){return p.join(e,_,Tt)}function H(e){return p.join(e,_,Ot)}function It(e,t){try{let n=p.join(e,_);u.mkdirSync(n,{recursive:!0});let o=G(e),r=t.map(s=>JSON.stringify(s)).join(`
8
+ `)+`
9
+ `;u.appendFileSync(o,r,"utf8"),q(o,pt);let{nominationTtlDays:i}=C(e);ht(o,i*24*60*60*1e3);}catch{}}function Ut(e,t){try{let n=p.join(e,_);u.mkdirSync(n,{recursive:!0});let o=H(e),r=t.map(s=>JSON.stringify(s)).join(`
10
+ `)+`
11
+ `;u.appendFileSync(o,r,"utf8"),q(o,Ft);let{debateTtlDays:i}=C(e);ht(o,i*24*60*60*1e3);}catch{}}function Bt(e,t){try{let n=p.join(e,_);u.mkdirSync(n,{recursive:!0});let o=p.join(n,Pt);u.appendFileSync(o,JSON.stringify(t)+`
12
+ `,"utf8"),q(o,pt);}catch(n){a$1.component("#promotion-decisions").warn("failed to record promotion decision",{agent:t.agent,error:n instanceof Error?n.message:String(n)});}}function q(e,t){try{let o=u.readFileSync(e,"utf8").trim().split(`
13
+ `).filter(r=>r.trim());if(o.length>t){let r=o.slice(-t);u.writeFileSync(e,r.join(`
14
+ `)+`
15
+ `,"utf8");}}catch{}}function C(e){let t={nominationTtlDays:Dt,debateTtlDays:At};try{let n=p.join(e,".paradigm","config.yaml");if(!u.existsSync(n))return t;let o=a("js-yaml"),r=u.readFileSync(n,"utf8"),s=o.load(r)?.ambient;return s?{nominationTtlDays:typeof s["nomination-ttl-days"]=="number"?s["nomination-ttl-days"]:t.nominationTtlDays,debateTtlDays:typeof s["debate-ttl-days"]=="number"?s["debate-ttl-days"]:t.debateTtlDays}:t}catch{return t}}function ht(e,t){try{if(!u.existsSync(e))return;let o=u.readFileSync(e,"utf8").trim().split(`
16
+ `).filter(s=>s.trim());if(o.length<=$t)return;let r=Date.now()-t,i=o.filter(s=>{try{let c=JSON.parse(s);return (c.timestamp?new Date(c.timestamp).getTime():Date.now())>=r}catch{return !0}});i.length<o.length&&u.writeFileSync(e,i.join(`
17
+ `)+`
18
+ `,"utf8");}catch{}}function J(e,t){let n=G(e);if(!u.existsSync(n))return [];try{let r=u.readFileSync(n,"utf8").trim().split(`
19
+ `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null);return t?.agent&&(r=r.filter(i=>i.agent===t.agent)),t?.urgency&&(r=r.filter(i=>i.urgency===t.urgency)),t?.surfaced!==void 0&&(r=r.filter(i=>i.surfaced===t.surfaced)),t?.pending_only&&(r=r.filter(i=>!i.engaged)),t?.since&&(r=r.filter(i=>i.timestamp>=t.since)),r.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),t?.limit&&(r=r.slice(0,t.limit)),r}catch{return []}}function ae(e){let t=H(e);if(!u.existsSync(t))return [];try{return u.readFileSync(t,"utf8").trim().split(`
20
+ `).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return []}}function ce(e,t,n,o){let r=G(e);if(!u.existsSync(r))return false;try{let s=u.readFileSync(r,"utf8").trim().split(`
21
+ `),c=!1,f=s.map(m=>{try{let l=JSON.parse(m);return l.id===t?(l.engaged=!0,l.response=n,o&&(l.reason=o),c=!0,JSON.stringify(l)):m}catch{return m}});if(c&&(u.writeFileSync(r,f.join(`
22
+ `)+`
23
+ `,"utf8"),n==="accepted"||n==="dismissed")){let m=JSON.parse(s.find(a=>{try{return JSON.parse(a).id===t}catch{return !1}}));i(e).find(a=>a.id===m.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&k(e,{type:"work-completed",source:"agent-action",agent:m.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return c}catch{return false}}function le(e,t,n,o){let r=H(e);if(!u.existsSync(r))return false;try{let s=u.readFileSync(r,"utf8").trim().split(`
24
+ `),c=!1,f=s.map(m=>{try{let l=JSON.parse(m);if(l.id===t){l.resolution={chosen:n,reason:o,resolved_by:"human",resolved_at:new Date().toISOString()},c=!0;let a=l.nominations.filter(d=>d!==n);for(let d of a){let g=J(e).find(y=>y.id===d);g&&k(e,{type:"work-completed",source:"agent-action",agent:g.agent,context:`Debate ${t} resolved \u2014 nomination ${d} not chosen`,data:{debate_id:t,chosen:n,reason:o}});}return JSON.stringify(l)}return m}catch{return m}});return c&&u.writeFileSync(r,f.join(`
25
+ `)+`
26
+ `,"utf8"),c}catch{return false}}function fe(e){let t=p.join(e,_,".last-processed"),n="";try{u.existsSync(t)&&(n=u.readFileSync(t,"utf8").trim());}catch{}let o=p.join(e,_,"stream.jsonl");if(!u.existsSync(o))return {processed:0,nominations:[]};let r=[];try{r=u.readFileSync(o,"utf8").trim().split(`
27
+ `).filter(a=>a.trim()).map(a=>{try{return JSON.parse(a)}catch{return null}}).filter(a=>a!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(n){let l=r.findIndex(a=>a.id===n);l>=0&&(i=l+1);}let s=r.slice(i);if(s.length===0)return {processed:0,nominations:[]};let c=[],f=s.slice(0,50);for(let l of f){let{nominations:a}=yt(e,l);c.push(...a);}let m=f[f.length-1];try{u.mkdirSync(p.join(e,_),{recursive:!0}),u.writeFileSync(t,m.id,"utf8");}catch{}return {processed:f.length,nominations:c}}function me(e,t,n){let o=U(e);if(t.path&&!B(o,t.path))return {event:k(e,t),nominations:[],debates:[]};let r=k(e,t);if(n?.skipNominations)return {event:r,nominations:[],debates:[]};let{nominations:i,debates:s}=yt(e,r);return i.length>0&&Wt(e,i),{event:r,nominations:i,debates:s}}function ue(e,t){let n=f(e,t);if(!n?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let o=n.attention.threshold??.6,{nominationTtlDays:r}=C(e),i=r*24*60*60*1e3,f$1=J(e,{agent:t}).filter(h=>h.engaged||Date.now()-new Date(h.timestamp).getTime()<i).filter(h=>h.engaged);if(f$1.length<5)return {adjusted:false,oldThreshold:o,newThreshold:o,reason:`Insufficient data (${f$1.length}/5 engaged nominations)`};let m=f$1.filter(h=>h.response==="accepted").length,l=f$1.filter(h=>h.response==="dismissed").length,a=m/f$1.length,d=l/f$1.length,g=o,y="No adjustment needed";if(d>.6?(g=Math.min(.95,o+.05),y=`High dismiss rate (${(d*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):a>.8&&(g=Math.max(.2,o-.05),y=`High accept rate (${(a*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),g===o)return {adjusted:false,oldThreshold:o,newThreshold:g,reason:y};n.attention.threshold=g;let N=p.join(e,".paradigm/agents",`${t}.agent`),v=u.existsSync(N)?"project":"global";return j$1(t,n,v,e),k(e,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${o.toFixed(2)} \u2192 ${g.toFixed(2)} (${y})`,data:{old_threshold:o,new_threshold:g,accept_rate:a,dismiss_rate:d}}),{adjusted:true,oldThreshold:o,newThreshold:g,reason:y}}function zt(e,t){let{nominationTtlDays:n}=C(e),o=n*24*60*60*1e3,i=J(e,{agent:t}).filter(a=>a.engaged||Date.now()-new Date(a.timestamp).getTime()<o),s=i.filter(a=>a.response==="accepted").length,c=i.filter(a=>a.response==="dismissed").length,f=i.filter(a=>a.response==="deferred").length,m=i.filter(a=>!a.engaged).length,l=s+c+f;return {total:i.length,accepted:s,dismissed:c,deferred:f,pending:m,acceptRate:l>0?s/l:0}}function de(e){let n=i(e).filter(a=>c(a.id,e)).map(a=>{let d=zt(e,a.id),g=0;try{let y=p.join(R.homedir(),".paradigm","notebooks",a.id);u.existsSync(y)&&(g=u.readdirSync(y).filter(N=>N.endsWith(".yaml")).length);}catch{}return {id:a.id,acceptRate:d.acceptRate,threshold:a.attention?.threshold??.5,expertiseCount:(a.expertise||[]).length,notebookCount:g,transferableCount:(a.transferable||[]).length,totalNominations:d.total}}),o=n.length||1,r=n.reduce((a,d)=>a+d.acceptRate,0)/o,i$1=n.reduce((a,d)=>a+d.threshold,0)/o,s=n.reduce((a,d)=>a+d.expertiseCount,0),c$1=n.reduce((a,d)=>a+d.notebookCount,0),f=n.reduce((a,d)=>a+d.transferableCount,0),m=n.reduce((a,d)=>a+d.totalNominations,0),l;return m<10?l="cold-start":r<.5?l="accumulating":r<.7?l="calibrating":l="mature",{agents:n,aggregate:{avgAcceptRate:r,avgThreshold:i$1,totalExpertise:s,totalNotebooks:c$1,totalTransferable:f},healthStatus:l}}function Wt(e,t){if(t.length===0)return;let n=p.join(R.homedir(),".paradigm","score","outbox");if(u.existsSync(n))try{let o=p.join(n,`nom-${Date.now()}.json`),r={type:"nomination_forward",nominations:t.map(i=>({...i})),origin:Gt(e),timestamp:new Date().toISOString()};u.writeFileSync(o,JSON.stringify(r),"utf8");}catch{}}function Gt(e){try{let t=p.join(e,".paradigm","config.yaml");if(u.existsSync(t)){let o=u.readFileSync(t,"utf8").match(/project:\s*(.+)/);if(o)return o[1].trim()}}catch{}return p.basename(e)}function ge(e,t){let n=z(t,{trigger:"pattern_discovered",limit:100}),o=z(t,{trigger:"human_feedback",limit:100}),r=[...n,...o],i=[];for(let s of r){if(s.promoted_to_notebook)continue;let c=(s.tags||[s.pattern?.id||"learned-pattern"]).map(j).filter(Boolean),f=s.confidence_after??0,m=f>=.8,l=.5,a=false;try{let d=ut(t,c,e);l=d.value,a=d.found;}catch{}if(Bt(e,{ts:new Date().toISOString(),agent:t,concepts:c,before:l,after:f,delta:f-l,promoted:m,priorFound:a,gate:"absolute-0.8"}),!((s.confidence_after??0)<.8))try{let{entry:d}=dt(t,{context:s.pattern?.applies_when||s.insight.slice(0,80),snippet:s.pattern?.correct_approach||s.insight,confidence:s.confidence_after??.5,concepts:c,tags:s.tags??[],provenance:{source:"lore",loreEntryId:s.id,createdBy:t}},"global",e);i.push({journalId:s.id,notebookId:d.id});try{let g=p.join(R.homedir(),".paradigm","agents",t,"journal");if(u.existsSync(g)){let y=u.readdirSync(g).filter(N=>N.endsWith(".yaml"));for(let N of y){let v=p.join(g,N),h=u.readFileSync(v,"utf8");if(h.includes(s.id)){let K=h.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${d.id}"`);if(K===h){let X=h.trimEnd().split(`
28
+ `);X.push(`promoted_to_notebook: "${d.id}"`),u.writeFileSync(v,X.join(`
29
+ `)+`
30
+ `,"utf8");}else u.writeFileSync(v,K,"utf8");break}}}}catch{}}catch(d){console.error("PROMOTE_THREW",d.message);}}return {promoted:i.length,entries:i}}var Ht=".paradigm/surfacing.yaml";function pe(e){let t=p.join(e,Ht),n={default_min_urgency:"low",enable_debates:true};if(!u.existsSync(t))return n;try{let o=a("js-yaml"),r=u.readFileSync(t,"utf8"),i=o.load(r);return {...n,...i}}catch{return n}}function ye(e,t){let n={critical:0,high:1,medium:2,low:3},o=n[t.default_min_urgency||"low"]??3;return e.filter(r=>{let i=n[r.urgency]??3;if(t.preferences){let s=t.preferences.find(c=>c.agent===r.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(f=>r.urgency===f||r.type===f))return false;if(s.min_urgency){let c=n[s.min_urgency]??3;return i<=c}}}return i<=o})}export{qt as a,Qt as b,z as c,yt as d,Mt as e,It as f,J as g,ae as h,ce as i,le as j,fe as k,me as l,ue as m,zt as n,de as o,Wt as p,ge as q,pe as r,ye as s};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import*as r from'fs';import*as o from'path';import*as f from'js-yaml';b$1();var m=".paradigm/tasks",T="entries",F="index.yaml";function k(e){if(e&&e.session_link&&!e.external_ref){let t=e.session_link,n=t.toLowerCase(),s;n.includes("github")?s="github":n.includes("session")?s="session":s="url",e.external_ref={kind:s,ref:t},delete e.session_link;}return e}function j(e,t){let n=o.join(e,m,T,t);if(!r.existsSync(n))return `T-${t}-001`;let s=r.readdirSync(n).filter(i=>i.startsWith("T-")&&i.endsWith(".yaml")).map(i=>{let l=i.match(/T-\d{4}-\d{2}-\d{2}-(\d+)\.yaml/);return l?parseInt(l[1],10):0}),a=s.length>0?Math.max(...s)+1:1;return `T-${t}-${String(a).padStart(3,"0")}`}function O(e,t){return e===t?true:({open:["in-progress","done","shelved"],"in-progress":["done","open","shelved"],shelved:["open"],done:[]}[e]??[]).includes(t)}var _={high:0,medium:1,low:2},E=["open","in-progress"];function N(e,t){return t==="all"?true:t==="active"?E.includes(e.status):e.status===t}function b(e){let t=e.created?new Date(e.created).getTime():NaN;if(!Number.isNaN(t))return t;let n=e.id?.match(/^T-(\d{4}-\d{2}-\d{2})-/);if(n){let s=new Date(n[1]).getTime();if(!Number.isNaN(s))return s}return 0}function C(e,t){let n=e;return t.status&&t.status!=="all"&&(n=n.filter(s=>N(s,t.status))),t.priority&&(n=n.filter(s=>s.priority===t.priority)),t.tag&&(n=n.filter(s=>s.tags.includes(t.tag))),n.sort((s,a)=>{let i=(_[s.priority]??1)-(_[a.priority]??1);return i!==0?i:b(a)-b(s)}),t.limit&&(n=n.slice(0,t.limit)),n}async function D(e,t){let n=o.join(e,m,T);if(!r.existsSync(n))return [];let s={status:"open",limit:20,...t},a=[],i=r.readdirSync(n).filter(l=>/^\d{4}-\d{2}-\d{2}$/.test(l)).sort().reverse();for(let l of i){let g=o.join(n,l),d=r.readdirSync(g).filter(c=>c.endsWith(".yaml")).sort();for(let c of d)try{let u=r.readFileSync(o.join(g,c),"utf8"),h=k(f.load(u));a.push(h);}catch{}}return C(a,s)}async function $(e,t){let n=t.match(/^T-(\d{4}-\d{2}-\d{2})-/);if(n){let a=o.join(e,m,T,n[1],`${t}.yaml`);if(r.existsSync(a))try{return k(f.load(r.readFileSync(a,"utf8")))}catch{return null}}return (await D(e,{status:"all",limit:9999})).find(a=>a.id===t)||null}async function A(e,t){let n=new Date,s=n.toISOString().slice(0,10),a=o.join(e,m,T,s);r.mkdirSync(a,{recursive:true});let i=j(e,s),l={id:i,blurb:t.blurb,priority:t.priority||"medium",status:"open",tags:t.tags||[],created:n.toISOString(),related_lore:t.related_lore,claimant:t.claimant,parentTaskId:t.parentTaskId,dependsOn:t.dependsOn,stage:t.stage,external_ref:t.external_ref,session_link:t.session_link};return k(l),r.writeFileSync(o.join(a,`${i}.yaml`),f.dump(w(l),{lineWidth:-1,noRefs:true})),await v(e),i}async function I(e,t,n){let s=await $(e,t);if(!s)return false;let a$1=s.created.slice(0,10),i=o.join(e,m,T,a$1,`${t}.yaml`);if(!r.existsSync(i))return false;let{id:l,created:g,...d}=n;if(d.status!==void 0&&d.status!==s.status){if(!O(s.status,d.status))return a.component("#task-loader").warn("Illegal task status transition rejected",{taskId:t,from:s.status,to:d.status}),false;d.status==="in-progress"&&!s.started_at&&d.started_at===void 0&&(d.started_at=new Date().toISOString());}let c={...s,...d};if(r.writeFileSync(i,f.dump(w(c),{lineWidth:-1,noRefs:true})),await v(e),W(c.status)&&c.parentTaskId)try{let{settleParentIfComplete:u}=await import('./task-settlement-NW4XMJGJ.js');await u(e,c.parentTaskId,c.id);}catch(u){a.component("#task-loader").warn("Settlement after updateTask failed (non-fatal)",{taskId:t,parentTaskId:c.parentTaskId,error:u instanceof Error?u.message:String(u)});}return true}function W(e){return e==="done"||e==="shelved"}async function L(e,t){return I(e,t,{status:"done",completed:new Date().toISOString()})}async function M(e,t){return I(e,t,{status:"shelved",shelved:new Date().toISOString()})}async function v(e){let t=o.join(e,m,T),n=o.join(e,m),s=0,a=0,i=0,l=0,g=0,d=[];if(r.existsSync(t)){let u=r.readdirSync(t).filter(h=>/^\d{4}-\d{2}-\d{2}$/.test(h));for(let h of u){let x=o.join(t,h),P=r.readdirSync(x).filter(y=>y.endsWith(".yaml"));for(let y of P)try{let p=k(f.load(r.readFileSync(o.join(x,y),"utf8")));s++,p.status==="open"?a++:p.status==="in-progress"?i++:p.status==="done"?l++:p.status==="shelved"&&g++,!p.parentTaskId&&p.id&&d.push(p.id);}catch{}}}let c={version:"1.1",total:s,open:a,in_progress:i,done:l,shelved:g,roots:d,last_updated:new Date().toISOString()};return r.mkdirSync(n,{recursive:true}),r.writeFileSync(o.join(n,F),f.dump(c,{lineWidth:-1,noRefs:true})),c}function w(e){let t={};for(let[n,s]of Object.entries(e))s!==void 0&&(t[n]=s);return t}export{k as a,O as b,D as c,$ as d,A as e,I as f,L as g,M as h,v as i};
2
+ import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import*as r from'fs';import*as o from'path';import*as f from'js-yaml';b$1();var m=".paradigm/tasks",T="entries",F="index.yaml";function k(e){if(e&&e.session_link&&!e.external_ref){let t=e.session_link,n=t.toLowerCase(),s;n.includes("github")?s="github":n.includes("session")?s="session":s="url",e.external_ref={kind:s,ref:t},delete e.session_link;}return e}function j(e,t){let n=o.join(e,m,T,t);if(!r.existsSync(n))return `T-${t}-001`;let s=r.readdirSync(n).filter(i=>i.startsWith("T-")&&i.endsWith(".yaml")).map(i=>{let l=i.match(/T-\d{4}-\d{2}-\d{2}-(\d+)\.yaml/);return l?parseInt(l[1],10):0}),a=s.length>0?Math.max(...s)+1:1;return `T-${t}-${String(a).padStart(3,"0")}`}function O(e,t){return e===t?true:({open:["in-progress","done","shelved"],"in-progress":["done","open","shelved"],shelved:["open"],done:[]}[e]??[]).includes(t)}var _={high:0,medium:1,low:2},E=["open","in-progress"];function N(e,t){return t==="all"?true:t==="active"?E.includes(e.status):e.status===t}function b(e){let t=e.created?new Date(e.created).getTime():NaN;if(!Number.isNaN(t))return t;let n=e.id?.match(/^T-(\d{4}-\d{2}-\d{2})-/);if(n){let s=new Date(n[1]).getTime();if(!Number.isNaN(s))return s}return 0}function C(e,t){let n=e;return t.status&&t.status!=="all"&&(n=n.filter(s=>N(s,t.status))),t.priority&&(n=n.filter(s=>s.priority===t.priority)),t.tag&&(n=n.filter(s=>s.tags.includes(t.tag))),n.sort((s,a)=>{let i=(_[s.priority]??1)-(_[a.priority]??1);return i!==0?i:b(a)-b(s)}),t.limit&&(n=n.slice(0,t.limit)),n}async function D(e,t){let n=o.join(e,m,T);if(!r.existsSync(n))return [];let s={status:"open",limit:20,...t},a=[],i=r.readdirSync(n).filter(l=>/^\d{4}-\d{2}-\d{2}$/.test(l)).sort().reverse();for(let l of i){let g=o.join(n,l),d=r.readdirSync(g).filter(c=>c.endsWith(".yaml")).sort();for(let c of d)try{let u=r.readFileSync(o.join(g,c),"utf8"),h=k(f.load(u));a.push(h);}catch{}}return C(a,s)}async function $(e,t){let n=t.match(/^T-(\d{4}-\d{2}-\d{2})-/);if(n){let a=o.join(e,m,T,n[1],`${t}.yaml`);if(r.existsSync(a))try{return k(f.load(r.readFileSync(a,"utf8")))}catch{return null}}return (await D(e,{status:"all",limit:9999})).find(a=>a.id===t)||null}async function A(e,t){let n=new Date,s=n.toISOString().slice(0,10),a=o.join(e,m,T,s);r.mkdirSync(a,{recursive:true});let i=j(e,s),l={id:i,blurb:t.blurb,priority:t.priority||"medium",status:"open",tags:t.tags||[],created:n.toISOString(),related_lore:t.related_lore,claimant:t.claimant,parentTaskId:t.parentTaskId,dependsOn:t.dependsOn,stage:t.stage,external_ref:t.external_ref,session_link:t.session_link};return k(l),r.writeFileSync(o.join(a,`${i}.yaml`),f.dump(w(l),{lineWidth:-1,noRefs:true})),await v(e),i}async function I(e,t,n){let s=await $(e,t);if(!s)return false;let a$1=s.created.slice(0,10),i=o.join(e,m,T,a$1,`${t}.yaml`);if(!r.existsSync(i))return false;let{id:l,created:g,...d}=n;if(d.status!==void 0&&d.status!==s.status){if(!O(s.status,d.status))return a.component("#task-loader").warn("Illegal task status transition rejected",{taskId:t,from:s.status,to:d.status}),false;d.status==="in-progress"&&!s.started_at&&d.started_at===void 0&&(d.started_at=new Date().toISOString());}let c={...s,...d};if(r.writeFileSync(i,f.dump(w(c),{lineWidth:-1,noRefs:true})),await v(e),W(c.status)&&c.parentTaskId)try{let{settleParentIfComplete:u}=await import('./task-settlement-HINBVZBE.js');await u(e,c.parentTaskId,c.id);}catch(u){a.component("#task-loader").warn("Settlement after updateTask failed (non-fatal)",{taskId:t,parentTaskId:c.parentTaskId,error:u instanceof Error?u.message:String(u)});}return true}function W(e){return e==="done"||e==="shelved"}async function L(e,t){return I(e,t,{status:"done",completed:new Date().toISOString()})}async function M(e,t){return I(e,t,{status:"shelved",shelved:new Date().toISOString()})}async function v(e){let t=o.join(e,m,T),n=o.join(e,m),s=0,a=0,i=0,l=0,g=0,d=[];if(r.existsSync(t)){let u=r.readdirSync(t).filter(h=>/^\d{4}-\d{2}-\d{2}$/.test(h));for(let h of u){let x=o.join(t,h),P=r.readdirSync(x).filter(y=>y.endsWith(".yaml"));for(let y of P)try{let p=k(f.load(r.readFileSync(o.join(x,y),"utf8")));s++,p.status==="open"?a++:p.status==="in-progress"?i++:p.status==="done"?l++:p.status==="shelved"&&g++,!p.parentTaskId&&p.id&&d.push(p.id);}catch{}}}let c={version:"1.1",total:s,open:a,in_progress:i,done:l,shelved:g,roots:d,last_updated:new Date().toISOString()};return r.mkdirSync(n,{recursive:true}),r.writeFileSync(o.join(n,F),f.dump(c,{lineWidth:-1,noRefs:true})),c}function w(e){let t={};for(let[n,s]of Object.entries(e))s!==void 0&&(t[n]=s);return t}export{k as a,O as b,D as c,$ as d,A as e,I as f,L as g,M as h,v as i};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {b}from'./chunk-5TAVYPOV.js';import*as s from'fs';import*as c from'path';import*as g from'js-yaml';function m(e){let r=process.env.HOME||process.env.USERPROFILE||"";return c.join(r,".paradigm","agents",e,"journal")}function d(){let e=new Date,r=e.toISOString().slice(0,10),i=e.toISOString().slice(11,19).replace(/:/g,""),o=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `LJ-${r}-${i}-${o}`}function h(e,r){let i=new Date,o=d(),a={id:o,agent:e,timestamp:i.toISOString(),...r},t=m(e);s.mkdirSync(t,{recursive:true});let n=c.join(t,`${o}.yaml`);return s.writeFileSync(n,g.dump(a,{lineWidth:120,noRefs:true}),"utf8"),a}function f(e,r){let i=m(e);if(!s.existsSync(i))return [];let o=[],a=s.readdirSync(i).filter(n=>n.endsWith(".yaml"));for(let n of a)try{let l=s.readFileSync(c.join(i,n),"utf8"),u=g.load(l);u&&u.id&&o.push(u);}catch{}let t=o;return r?.trigger&&(t=t.filter(n=>n.trigger===r.trigger)),r?.project&&(t=t.filter(n=>n.project===r.project)),r?.transferable!==void 0&&(t=t.filter(n=>n.transferable===r.transferable)),r?.tag&&(t=t.filter(n=>n.tags?.some(l=>l.startsWith(r.tag)))),r?.dateFrom&&(t=t.filter(n=>n.timestamp>=r.dateFrom)),r?.dateTo&&(t=t.filter(n=>n.timestamp<=r.dateTo)),t.sort((n,l)=>l.timestamp.localeCompare(n.timestamp)),r?.limit&&(t=t.slice(0,r.limit)),t}function J(e,r){let i=m(e),o=c.join(i,`${r}.yaml`);if(!s.existsSync(o))return null;let a=s.readFileSync(o,"utf8");return g.load(a)}function E(e){let r=process.env.HOME||process.env.USERPROFILE||"",i=c.join(r,".paradigm","agents");if(!s.existsSync(i))return [];let o=[],a=s.readdirSync(i,{withFileTypes:true}).filter(t=>t.isDirectory());for(let t of a){if(e?.agent&&t.name!==e.agent)continue;let n=f(t.name,e);o.push(...n);}return o.sort((t,n)=>n.timestamp.localeCompare(t.timestamp)),e?.limit?o.slice(0,e.limit):o}function S(e){let r=f(e),i={},o={},a=0;for(let t of r)i[t.trigger]=(i[t.trigger]||0)+1,o[t.project]=(o[t.project]||0)+1,t.transferable&&a++;return {total:r.length,byTrigger:i,byProject:o,transferableCount:a,recentInsights:r.slice(0,5).map(t=>({id:t.id,trigger:t.trigger,insight:t.insight.slice(0,200),timestamp:t.timestamp}))}}var y=b(()=>{});export{h as a,f as b,J as c,E as d,S as e,y as f};
@@ -0,0 +1,33 @@
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 {e as e$1,f,g}from'./chunk-XPPFILCM.js';import {a as a$4}from'./chunk-MBPLJKE5.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}from'./chunk-4GC35IFF.js';import'minimatch';import*as S from'fs';import*as C from'path';import*as W 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"],Ae=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs","changelog","architecture doc"],Ce=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","doesn't work","doesn't","cant","can't","regression","patch"],Ie=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify","modularize","decouple","split","merge"],De=["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"],$e=/[@#$%^!?&~][a-zA-Z0-9_-]+/g,fe={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 Me(h){let t=h.match($e)||[];return [...new Set(t)]}function U(h,t){let e=h.toLowerCase();return t.filter(s=>e.includes(s.toLowerCase()))}function Fe(h,t,e,s){let n=0;e.length>=5?n+=2:e.length>=2&&(n+=1);let i=h.split(/\s+/).length;i>=100?n+=2:i>=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),t==="feature"&&(n+=1),t==="refactor"&&(n+=1),n>=5?"high":n>=2?"medium":"low"}function Be(h,t,e){if(U(h,De).length>0||t.some(n=>n.startsWith("^")))return true;return false}function K(h,t){let e=Me(h),s=U(h,Pe),n=U(h,Ae),i=U(h,Ce),r=U(h,Ie),l,o;s.length>0&&i.length===0&&r.length===0?(l="analysis",o=s):n.length>0&&i.length===0?(l="documentation",o=n):i.length>0?(l="bugfix",o=i):r.length>0?(l="refactor",o=r):(l="feature",o=[]);let a=fe[l],d=Be(h,e),c=[...a.agents];d&&!c.includes("security")&&(c=["security",...c]);let f=Fe(h,l,e),p={...a.costMultiplier};return f==="high"?(p.min*=1.2,p.max*=1.3):f==="low"&&(p.min*=.8,p.max*=.9),d&&!a.agents.includes("security")&&(p.min+=.15,p.max+=.2),{type:l,complexity:f,recommendedAgents:c,securityRequired:d,costMultiplier:p,matchedKeywords:o,symbols:e}}function H(h,t){let e=fe[t.type];return h==="security"&&t.securityRequired?"opus":e.models[h]||"sonnet"}var _e=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,Ee=[/\.(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],Le=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"];function me(h,t$1,e$1){let s=h.toLowerCase(),n=h.match(_e)||[],i=[...new Set(n)],r=i.map(g=>{let y=t(e$1,g),w=y.length>0?y[0]:null;return {symbol:g,exists:!!w,type:w?.type,description:w?.description}}),l=r.filter(g=>g.exists).map(g=>{let y=x(e$1,g.symbol),w=new Set;for(let F of y){let v=x(e$1,F.symbol);for(let P of v)P.symbol!==g.symbol&&!y.find(ee=>ee.symbol===P.symbol)&&w.add(P.symbol);}let R=y.length+w.size,I="low";return R>10?I="high":R>3&&(I="medium"),{symbol:g.symbol,directDependents:y.length,indirectDependents:w.size,impact:I}}),o=a$3(t$1),a=o.status==="ok"?o.data:null,d={exists:o.status!=="missing",gateCount:a?b$2(a).length:0,gates:a?b$2(a).map(g=>`^${g}`):[],routeCount:a?.routes?Object.keys(a.routes).length:0},c=Le.some(g=>s.includes(g)),f=e(t$1),p=f?a$2(h,f.agents).map(g=>({name:g.name,confidence:g.confidence,reason:g.reason})):[],u=[];return r.some(g=>g.exists)&&u.push("ripple-analysis"),c&&u.push("portal-compliance"),i.some(g=>g.startsWith("^"))&&u.push("gate-validation"),i.some(g=>g.startsWith("!"))&&u.push("signal-registration"),u.push("purpose-coverage"),{affectedSymbols:r,rippleAnalysis:l,portalStatus:d,taskAddsRoutes:c,suggestedAgents:p,requiredChecks:u}}function ye(h,t$1,e,s){let n=[],i=a$3(e),r=i.status==="ok"?i.data:null,l=r?b$2(r):[],o=r?.routes?Object.keys(r.routes):[];for(let p of h){let u=C.isAbsolute(p)?p:C.join(e,p);if(!S.existsSync(u))continue;let g;try{g=S.readFileSync(u,"utf-8");}catch{continue}for(let y of Ee){y.lastIndex=0;let w;for(;(w=y.exec(g))!==null;){let R=w[2]||w[0];R&&R.startsWith("/")&&(!o.some(F=>F.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===R)&&r?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${R}" found in ${C.relative(e,u)} but not declared in portal.yaml`,file:C.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:C.relative(e,u),suggestion:"Create portal.yaml to declare gates for API routes. Run: paradigm portal init"}));}}}for(let p of t$1)t(s,p).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${p}" was touched but is not registered in any .purpose file`,suggestion:`Add "${p}" to the nearest .purpose file. Use paradigm_purpose_add_component or paradigm_purpose_add_signal.`});for(let p of t$1)if(p.startsWith("^")){let u=p.slice(1);l.includes(u)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${p}" is referenced but not declared in portal.yaml`,suggestion:`Add ${p} to portal.yaml with description and check expression.`});}h.length>=5&&t$1.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${h.length} files, ${t$1.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(p=>p.severity==="error").length,d=n.filter(p=>p.severity==="warning").length,c=4,f="pass";return a>0?f="violations":d>0&&(f="warnings"),{status:f,violations:n,summary:{totalChecks:c,passed:c-(a>0?1:0)-(d>0?1:0),warnings:d,errors:a},blocksCompletion:a>0}}var je=".paradigm/events/iteration-revisions.jsonl";function be(h,t){try{let e=C.join(h,je),s=C.dirname(e);S.existsSync(s)||S.mkdirSync(s,{recursive:!0});let n={timestamp:new Date().toISOString(),type:"iteration-revision",...t};S.appendFileSync(e,JSON.stringify(n)+`
3
+ `,"utf8");}catch{}}function we(h,t){let e=Math.random().toString(36).substring(2,8);return `itrev-${h}-r${t}-${Date.now()}-${e}`}async function le(h,t,e,s){let n=new Map,i;try{i=await e$1(h,{blurb:e,priority:"medium",tags:["orchestration","epic"],claimant:{kind:"archetype",ref:"orchestrator"},external_ref:{kind:"orchestration",ref:t}});try{await f(h,i,{status:"in-progress"});}catch(l){a$4.flow("$cli-task-bridge").warn("Epic promote to in-progress failed",{orchestrationId:t,epicTaskId:i,error:l instanceof Error?l.message:String(l)});}let r=[...s].sort((l,o)=>l.stage-o.stage);for(let l of r)try{let o=(l.dependsOn||[]).map(d=>n.get(d)).filter(d=>typeof d=="string"),a=await e$1(h,{blurb:l.subtask,priority:"medium",tags:["orchestration"],claimant:{kind:"archetype",ref:l.agent},parentTaskId:i,stage:l.stage,...o.length>0?{dependsOn:o}:{},external_ref:{kind:"orchestration",ref:t}});n.set(l.agent,a);}catch(o){a$4.flow("$cli-task-bridge").warn("Stage task emission failed",{orchestrationId:t,agent:l.agent,stage:l.stage,error:o instanceof Error?o.message:String(o)});}a$4.flow("$cli-task-bridge").info("Emitted CLI orchestration task DAG",{orchestrationId:t,epicTaskId:i,stageTasks:n.size});}catch(r){a$4.flow("$cli-task-bridge").warn("CLI task DAG emission failed; orchestration continues",{orchestrationId:t,error:r instanceof Error?r.message:String(r)});}return {epicTaskId:i,stageTaskIds:n}}async function ce(h,t){if(!t)return false;try{return await f(h,t,{status:"in-progress"})}catch(e){return a$4.flow("$cli-task-bridge").warn("Stage progress update failed (non-fatal)",{taskId:t,error:e instanceof Error?e.message:String(e)}),false}}async function G(h,t,e){if(!t)return false;try{return e==="success"?await g(h,t):await f(h,t,{status:"shelved",shelved:new Date().toISOString()})}catch(s){return a$4.flow("$cli-task-bridge").warn("Stage complete update failed (non-fatal)",{taskId:t,outcome:e,error:s instanceof Error?s.message:String(s)}),false}}var qe=".paradigm/events/estimate-actuals.jsonl";function ue(h,t){try{let e=C.join(h,qe),s=C.dirname(e);S.existsSync(s)||S.mkdirSync(s,{recursive:!0});let n={archetype:t.archetype,taskType:t.taskType,actualTokens:t.actualTokens,...t.parentTaskId?{parentTaskId:t.parentTaskId}:{},ts:t.ts||new Date().toISOString()};return S.appendFileSync(e,JSON.stringify(n)+`
4
+ `,"utf8"),!0}catch(e){return a$4.component("#calibration").warn("estimate-actual capture failed (non-fatal)",{archetype:t.archetype,taskType:t.taskType,error:e instanceof Error?e.message:String(e)}),false}}var ke={architect:"opus",security:"opus",reviewer:"sonnet",builder:"haiku",tester:"haiku"},Ue=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","role","access control","vulnerability","injection","xss","csrf"];function We(h,t){let e=h.toLowerCase(),s=Ue.some(r=>e.includes(r.toLowerCase())),n=h.includes("^"),i=false;return s||n||i}var ze=["rename","refactor","migrate","restructure","move","reorganize"];function Ve(h){let t=h.toLowerCase();return ze.some(e=>t.includes(e))}var Q=class{spawner;auditLogger;rootDir;constructor(t){this.rootDir=t,this.spawner=new b(t),this.auditLogger=new a(t);}async initialize(){await this.spawner.initialize();}async orchestrate(t,e={}){let s=e.mode||"faceted",n=Date.now(),i=this.generateOrchestrationId(),r={success:false,mode:s,orchestrationId:i,task:t,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'),d=await a(this.rootDir),c=o(d);l=me(t,this.rootDir,c);}catch{}if(s==="solo"){let a=await this.runSoloMode(t,e,i);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(t,e,i);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'),d=await a(this.rootDir),c=o(d),f=[],p=[];for(let g of r.agentResults)g.relay?.outputs?.artifacts&&f.push(...g.relay.outputs.artifacts.map(y=>y.path));for(let g of l.affectedSymbols)p.push(g.symbol);let u=ye(f,p,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 o$1=this.auditLogger.startOrchestration(i,t,s);return o$1.completed=new Date().toISOString(),o$1.status=r.success?"success":"failed",o$1.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(o$1),r.log=o$1,r}catch(l){return r.error=l instanceof Error?l.message:String(l),r.duration_ms=Date.now()-n,r}}async compare(t,e={}){let s=await this.orchestrate(t,{...e,mode:"solo"}),n=await this.orchestrate(t,{...e,mode:"faceted"}),i=s.totalTokens.total-n.totalTokens.total,r=s.totalCost-n.totalCost,l=s.duration_ms-n.duration_ms,o="tie";return n.success&&!s.success?o="faceted":s.success&&!n.success?o="solo":n.totalCost<s.totalCost*.8?o="faceted":s.totalCost<n.totalCost*.8&&(o="solo"),{solo:s,faceted:n,comparison:{winner:o,tokensSaved:i,costDiff:r,timeDiff:l,soloSucceeded:s.success,facetedSucceeded:n.success}}}async runSoloMode(t,e$1,s){let i=e(this.rootDir)?.team.default_agent||"architect",r=e$1.orchestratorModel||"opus",l;s&&(l=await le(this.rootDir,s,t,[{agent:i,stage:0,subtask:t,dependsOn:[]}]));let o=l?.stageTaskIds.get(i),a={model:r,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.budget,onMessage:e$1.onMessage?c=>e$1.onMessage("solo",c):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart("solo",t,r),await ce(this.rootDir,o);let d=await this.spawner.spawn(i,t,a);return e$1.onAgentComplete&&e$1.onAgentComplete("solo",d,r),d.relay&&ue(this.rootDir,{archetype:i,taskType:K(t).type,actualTokens:d.relay.metrics.tokens_used,parentTaskId:l?.epicTaskId}),await G(this.rootDir,o,d.success?"success":"failure"),d}async runFacetedMode(t,e$1,s){let n=e(this.rootDir);if(!n)return {success:false,results:[],totalTokens:{input:0,output:0,total:0},totalCost:0};let i=K(t).type,r="";if(Ve(t)){let k=a$1(t);if(k.length>0){let b=[];b.push(`## Auto-Ripple Analysis
5
+ `),b.push("The following symbols are affected by this refactoring:"),b.push("");for(let T of k.slice(0,5))b.push(`- **${T}**: Check dependencies before renaming/moving`);b.push(""),b.push("**Recommendation:** Run `paradigm_ripple` for each symbol before making changes."),r=b.join(`
6
+ `);}}let l=this.planAgentSequence(t,n.agents),o=this.groupByStage(l),a;if(s){let k=l.map(b=>({agent:b.agent,stage:b.stage,subtask:b.subtask,dependsOn:b.dependsOn}));a=await le(this.rootDir,s,t,k);}let d=new Set,c=[],f={input:0,output:0,total:0},p=0,u=new Map,g=true,y=n.orchestration?.iteration,w=y?.enabled===true,R=l.find(k=>k.agent==="builder")?.subtask,I=l.some(k=>k.agent==="reviewer"),F=l.some(k=>k.agent==="tester"),v=w&&!!R&&I,P,ee=Array.from(o.keys()).sort((k,b)=>k-b);for(let k of ee){let b=o.get(k)||[];if(b.length===0)continue;if(e$1.checkpoints?.beforeAgentSpawn&&e$1.onCheckpoint){let m=b.map(D=>D.agent).join(", ");if(!await e$1.onCheckpoint(`Stage ${k}: Spawn ${m}${b.length>1?" (parallel)":""}`)){g=false;break}}let T=b.map(async m=>{let O=e$1.agentBudgets?.[m.agent]?.maxTokens?"haiku":m.model||ke[m.agent]||"sonnet",D="";if(m.dependsOn.length>0){let _=m.dependsOn.map(te=>u.get(te)).filter(Boolean);_.length>0&&(D=_.join(`
7
+
8
+ ---
9
+
10
+ `));}let q=D;m.agent==="architect"&&r&&(q=r+(D?`
11
+
12
+ ---
13
+
14
+ `+D:""));let B=q?`${m.subtask}
15
+
16
+ ## Context from previous agents:
17
+ ${q}`:m.subtask;v&&m.agent==="reviewer"&&(B=`${B}
18
+
19
+ ${Se}`);let $={model:O,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.agentBudgets?.[m.agent]||e$1.budget,onMessage:e$1.onMessage?_=>e$1.onMessage(m.agent,_):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart(m.agent,m.subtask,O),await ce(this.rootDir,a?.stageTaskIds.get(m.agent));let x=await this.spawner.spawn(m.agent,B,$);return e$1.onAgentComplete&&e$1.onAgentComplete(m.agent,x,O),await G(this.rootDir,a?.stageTaskIds.get(m.agent),x.success?"success":"failure"),d.add(m.agent),{step:m,result:x,model:O}}),Re=await Promise.all(T);for(let{step:m,result:O,model:D}of Re){if(c.push(O),O.relay){f.input+=O.relay.metrics.tokens_used.input,f.output+=O.relay.metrics.tokens_used.output,f.total+=O.relay.metrics.tokens_used.total,p+=b$1(O.relay.metrics.tokens_used,D),ue(this.rootDir,{archetype:m.agent,taskType:i,actualTokens:O.relay.metrics.tokens_used,parentTaskId:a?.epicTaskId});let q=O.relay.handoff?.context||`${m.agent} completed: ${O.relay.outputs.decisions.join(", ")||"task done"}`;if(u.set(m.agent,q),m.agent==="architect"&&O.relay){let B=this.extractFilePlanFromRelay(O);if(B&&B.length>0){let $=this.planBuilderStages(B);if($.hasFilePlan&&$.totalBuilders>1){let x=await this.runParallelBuilders($,u.get("architect")||"",e$1);c.push(...x.results),f.input+=x.totalTokens.input,f.output+=x.totalTokens.output,f.total+=x.totalTokens.total,p+=x.totalCost,x.success||(g=false),P={usedFilePlan:true,totalSubPhases:$.stages.length,totalParallelBuilders:$.totalBuilders,filesCreated:$.totalFiles};for(let[_,te]of o){let Te=te.filter(xe=>xe.agent!=="builder");o.set(_,Te);}await G(this.rootDir,a?.stageTaskIds.get("builder"),x.success?"success":"failure"),d.add("builder");}}}}!O.success&&m.required&&(g=false);}if(!g||e$1.checkpoints?.afterAgentComplete&&e$1.onCheckpoint&&!await e$1.onCheckpoint(`Stage ${k} completed. Continue to next stage?`))break}let de;if(v&&g){let k=[...c].reverse().find(T=>T.relay?.agent==="reviewer"),b=k?this.parseIterationVerdict(k):null;if(b?.verdict==="changes-requested"){let T=await this.runReviewIteration({builderSubtask:R,firstReview:b,hasTester:F,maxRoundsConfig:y?.defaultMaxRounds??3,options:e$1});c.push(...T.extraResults),f.input+=T.extraTokens.input,f.output+=T.extraTokens.output,f.total+=T.extraTokens.total,p+=T.extraCost,de=T.iterationOutcome;}else k&&!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()});}if(a)for(let[k,b]of a.stageTaskIds)d.has(k)||await G(this.rootDir,b,"failure");return {success:g,results:c,totalTokens:f,totalCost:p,parallelBuilderStats:P,iterationOutcome:de}}async runReviewIteration(t){let{builderSubtask:e,firstReview:s,hasTester:n,maxRoundsConfig:i,options:r}=t,l=i%2===0?i:i+1,o=[e];s.openThreads.length&&o.push("","## Reviewer asked you to resolve:",...s.openThreads.map(u=>`- ${u}`)),s.whatChanged.length&&o.push("","## Reviewer notes:",...s.whatChanged.map(u=>`- ${u}`));let a=u=>r.agentBudgets?.[u]?.maxTokens?"haiku":ke[u]||"sonnet",d=u=>r.agentBudgets?.[u]||r.budget,c=await this.runIterationLoop(o.join(`
20
+ `),{maxRounds:l,mode:"ping-pong",iterateAgent:"builder",reviewAgent:"reviewer",workingDirectory:r.workingDirectory||this.rootDir,mcpServerPath:r.mcpServerPath,resolveModel:a,resolveBudget:d,onRound:r.onAgentComplete?u=>r.onAgentComplete(u.agent,u.spawnResult,a(u.agent)):void 0}),f=c.rounds.map(u=>u.spawnResult),p=0;for(let u of c.rounds)u.spawnResult.relay&&(p+=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:
21
+ ${e}`,{model:"haiku",workingDirectory:r.workingDirectory||this.rootDir,mcpServerPath:r.mcpServerPath});f.push(u),u.relay&&(p+=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:f,extraTokens:c.totalTokens,extraCost:p,iterationOutcome:{converged:c.converged,roundsRun:c.rounds.length,openThreads:c.unresolved?.openThreads??[]}}}extractFilePlanFromRelay(t){if(!t.relay)return;let e=t.relay.handoff?.context||"";if(e.includes("filePlan:"))return this.parseFilePlanFromText(e)}parseFilePlanFromText(t){let e=[],s=t.match(/filePlan:\s*\n([\s\S]*?)(?=\n[a-z_]+:|$)/);if(!s)return;let i=s[1].split(`
22
+ `),r=null,l=false,o={};for(let a of i){let d=a.trim();if(!(!d||d.startsWith("#"))){if(d.startsWith("- group:")){r&&(o.path&&(r.files.push({path:o.path,description:o.description||""}),o={}),e.push(r)),r={group:d.split(":")[1].trim(),subPhase:0,files:[]},l=false;continue}if(r){if(d.startsWith("subPhase:")){r.subPhase=parseInt(d.split(":")[1].trim(),10)||0;continue}if(d==="files:"){l=true;continue}if(l){if(d.startsWith("- path:")){o.path&&r.files.push({path:o.path,description:o.description||""}),o={path:d.split(":").slice(1).join(":").trim().replace(/^["']|["']$/g,"")};continue}if(d.startsWith("description:")){o.description=d.split(":").slice(1).join(":").trim().replace(/^["']|["']$/g,"");continue}}}}}return o.path&&r&&r.files.push({path:o.path,description:o.description||""}),r&&e.push(r),e.length>0?e:void 0}planAgentSequence(t,e){let s=a$1(t),n=t.toLowerCase(),i=K(t),r=[],l=We(t);if(i.type==="analysis")return e.architect&&r.push({agent:"architect",subtask:`Analyze and recommend: ${t}`,required:true,stage:0,dependsOn:[],model:"opus"}),r;if(i.type==="documentation")return e.architect&&r.push({agent:"architect",subtask:`Document: ${t}`,required:true,stage:0,dependsOn:[],model:"sonnet"}),r;let o=n.includes("design")||n.includes("architect")||n.includes("plan")||n.includes("spec"),a=l||n.includes("auth")||n.includes("security")||n.includes("gate")||s.some(g=>g.startsWith("^"));if(o&&e.architect&&r.push({agent:"architect",subtask:`Design and specify: ${t}`,required:true,stage:0,dependsOn:[],model:"opus"}),a&&e.security&&r.push({agent:"security",subtask:`Review security aspects of: ${t}`,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 g=o&&e.architect?["architect"]:[];r.push({agent:"builder",subtask:`Implement: ${t}`,required:true,stage:g.length>0?1:0,dependsOn:g,model:"haiku"});}let c=n.includes("review")||n.includes("check"),f=n.includes("test")||n.includes("verify")||n.includes("validate"),p=r.some(g=>g.agent==="builder"),u=p?2:o?1:0;if(c&&e.reviewer&&r.push({agent:"reviewer",subtask:`Review: ${t}`,required:false,stage:u,dependsOn:p?["builder"]:[],model:"sonnet"}),f&&e.tester&&r.push({agent:"tester",subtask:`Test and validate: ${t}`,required:false,stage:u,dependsOn:p?["builder"]:[],model:"haiku"}),r.length===0){let g=i.recommendedAgents;if(g.includes("architect")&&e.architect&&r.push({agent:"architect",subtask:`Design: ${t}`,required:true,stage:0,dependsOn:[],model:H("architect",i)}),(g.includes("security")||l)&&e.security&&r.push({agent:"security",subtask:`Security review: ${t}`,required:l,stage:0,dependsOn:[],model:"opus"}),g.includes("builder")&&e.builder){let y=r.length>0;r.push({agent:"builder",subtask:`Implement: ${t}`,required:true,stage:y?1:0,dependsOn:r.filter(w=>w.stage===0).map(w=>w.agent),model:H("builder",i)});}if(g.includes("tester")&&e.tester){let y=r.find(w=>w.agent==="builder")?.stage??0;r.push({agent:"tester",subtask:`Test: ${t}`,required:false,stage:y+1,dependsOn:e.builder?["builder"]:[],model:H("tester",i)});}}try{let g=a$2(t,e),y=new Set(r.map(v=>v.agent)),w=new Set(["documentor"]),I=(r.length>0?Math.max(...r.map(v=>v.stage)):-1)+1,F=r.map(v=>v.agent);for(let v of g){if(y.has(v.name)||w.has(v.name)||!e[v.name]||v.confidence==="low")continue;let P=e[v.name];r.push({agent:v.name,subtask:`Contribute (${P?.focus??"specialist"}): ${t}`,required:!1,stage:I,dependsOn:F,model:P?.defaultModel??"sonnet"}),y.add(v.name);}}catch{}return r.sort((g,y)=>g.stage-y.stage)}groupByStage(t){let e=new Map;for(let s of t){let n=e.get(s.stage)||[];n.push({agent:s.agent,subtask:s.subtask,required:s.required,dependsOn:s.dependsOn}),e.set(s.stage,n);}return e}generateOrchestrationId(){let t=new Date().toISOString().slice(0,10),e=Math.random().toString(36).substring(2,8);return `orch-${t}-${e}`}planBuilderStages(t){if(!t||t.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 o of t){let a=e.get(o.subPhase)||[];a.push(o),e.set(o.subPhase,a);}let s=[],n=[...e.keys()].sort((o,a)=>o-a),i=[],r=0,l=0;for(let o of n){let a=e.get(o),d=[];for(let c=0;c<a.length;c++){let f=a[c];l+=f.files.length,r++,d.push({agent:`builder-${o}-${c}`,group:f.group,files:f.files,availableFiles:[...i]});}s.push({subPhase:o,builders:d});for(let c of a)for(let f of c.files)i.push(f.path);}return {hasFilePlan:true,stages:s,totalFiles:l,totalBuilders:r}}buildParallelBuilderPrompt(t,e,s,n){let i=[];i.push(`You are a BUILDER agent responsible for implementing the **${n}** group.`),i.push(""),i.push("## Your Assignment"),i.push(""),i.push("### Files to Create:");for(let r of t)i.push(`- \`${r.path}\`: ${r.description}`);if(i.push(""),e.length>0){i.push("### Available Files (already created):"),i.push("These files exist and you can import from them:");for(let r of e)i.push(`- \`${r}\``);i.push("");}return s&&(i.push("### Context from Architect:"),i.push(s),i.push("")),i.push("### Instructions:"),i.push("1. Create ONLY the files assigned to you"),i.push("2. You can import from available files (already created)"),i.push("3. Follow existing patterns in the codebase"),i.push("4. Use the Paradigm logger (not console.log)"),i.push("5. End with the standard Agent Relay block"),i.join(`
23
+ `)}async runParallelBuilders(t,e,s){let n=[],i={input:0,output:0,total:0},r=0,l=true;for(let o of t.stages){if(s.checkpoints?.beforeAgentSpawn&&s.onCheckpoint){let c=o.builders.map(p=>p.group).join(", ");if(!await s.onCheckpoint(`Builder Sub-phase ${o.subPhase}: ${c}${o.builders.length>1?" (parallel)":""}`)){l=false;break}}let a=o.builders.map(async c=>{let f=this.buildParallelBuilderPrompt(c.files,c.availableFiles,e,c.group),p={model:"haiku",workingDirectory:s.workingDirectory||this.rootDir,mcpServerPath:s.mcpServerPath,budget:s.budget,onMessage:s.onMessage?g=>s.onMessage(c.agent,g):void 0,onCheckpoint:s.onCheckpoint};s.onAgentStart&&s.onAgentStart(c.agent,`Implement ${c.group}`,"haiku");let u=await this.spawner.spawn("builder",f,p);return s.onAgentComplete&&s.onAgentComplete(c.agent,u,"haiku"),{builder:c,result:u}}),d=await Promise.all(a);for(let{result:c}of d)n.push(c),c.relay&&(i.input+=c.relay.metrics.tokens_used.input,i.output+=c.relay.metrics.tokens_used.output,i.total+=c.relay.metrics.tokens_used.total,r+=b$1(c.relay.metrics.tokens_used,"haiku")),c.success||(l=false);if(!l||s.checkpoints?.afterAgentComplete&&s.onCheckpoint&&!await s.onCheckpoint(`Sub-phase ${o.subPhase} complete. Continue to next sub-phase?`))break}return {success:l,results:n,totalTokens:i,totalCost:r}}async runIterationLoop(t,e,s){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=s??(a=>be(this.rootDir,{id:we(a.agent,a.round),agent:a.agent,corrections:a.corrections,symbols:a.symbols,round:a.round})),i=[],r={input:0,output:0,total:0},l=null,o=null;for(let a=1;a<=e.maxRounds;a++){let d=this.iterationAgentForRound(e,a),c=this.buildIterationTask(t,l,a),f={workingDirectory:e.workingDirectory||this.rootDir,mcpServerPath:e.mcpServerPath,model:e.resolveModel?.(d),budget:e.resolveBudget?.(d)},p=await this.spawner.spawn(d,c,f);p.relay&&(r.input+=p.relay.metrics.tokens_used.input,r.output+=p.relay.metrics.tokens_used.output,r.total+=p.relay.metrics.tokens_used.total);let u=this.parseIterationVerdict(p);u&&(o=u);let g=false;if(this.beliefRevised(u,l)){let w=u.corrections.length>0?u.corrections:this.reopenedClaims(u,l);n({agent:d,corrections:w,symbols:p.relay?.outputs.symbols??[],round:a}),g=true;}let y={round:a,agent:d,spawnResult:p,delta:u,promoted:g};if(i.push(y),e.onRound?.(y),!p.success)return this.unresolvedResult(i,o,r,"spawn-failed",a);if(u===null)return this.unresolvedResult(i,o,r,"unparseable-verdict",a);if(this.isConverged(u,e,d))return {converged:true,rounds:i,finalDelta:u,totalTokens:r};l=u;}return this.unresolvedResult(i,o,r,"max-rounds",e.maxRounds)}unresolvedResult(t,e,s,n,i){return {converged:false,rounds:t,finalDelta:e,totalTokens:s,unresolved:{reason:n,roundsRun:i,openThreads:e?.openThreads??[]}}}iterationAgentForRound(t,e){return t.mode==="single-role"||e%2===1?t.iterateAgent:t.reviewAgent}isConverged(t,e,s){return t.verdict!=="approved"?false:e.mode==="single-role"?t.openThreads.length===0:s===e.reviewAgent}reopenedClaims(t,e){return e?t.whatChanged.filter(s=>e.alreadyVerified.includes(s)):[]}beliefRevised(t,e){return t?t.corrections.length>0?true:this.reopenedClaims(t,e).length>0:false}buildIterationTask(t,e,s){let n=[t];return e&&(n.push("",`## Iteration delta (entering round ${s})`),n.push(`- Verdict so far: ${e.verdict}`),e.whatChanged.length&&n.push("- Changed last round:",...e.whatChanged.map(i=>` - ${i}`)),e.alreadyVerified.length&&n.push("- Already verified (do NOT re-litigate):",...e.alreadyVerified.map(i=>` - ${i}`)),e.openThreads.length&&n.push("- Open threads to resolve:",...e.openThreads.map(i=>` - ${i}`))),n.push("",Se),n.join(`
24
+ `)}parseIterationVerdict(t){if(!t.relay)return null;let e=[];t.relay.handoff?.context&&e.push(t.relay.handoff.context),t.relay.outputs?.decisions?.length&&e.push(t.relay.outputs.decisions.join(`
25
+ `)),t.relay.rawResponse&&e.push(t.relay.rawResponse);for(let s of e){let n=Ye(s);if(n)return n}return null}},Se=["## 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(`
26
+ `);function Ye(h){let t=[...h.matchAll(/```iteration-verdict\s*\n([\s\S]*?)```/g)];if(t.length===0)return null;for(let e=t.length-1;e>=0;e--)try{let s=JSON.parse(t[e][1].trim());if(s.verdict!=="approved"&&s.verdict!=="changes-requested")continue;return {verdict:s.verdict,whatChanged:Array.isArray(s.whatChanged)?s.whatChanged:[],alreadyVerified:Array.isArray(s.alreadyVerified)?s.alreadyVerified:[],openThreads:Array.isArray(s.openThreads)?s.openThreads:[],corrections:Array.isArray(s.corrections)?s.corrections:[]}}catch{continue}return null}var Oe=class{rootDir;orchestrationsDir;constructor(t){this.rootDir=t,this.orchestrationsDir=C.join(t,".paradigm","orchestrations"),this.ensureOrchestrationDir();}async startBackground(t,e={}){let s=this.generateId(),n=C.join(this.orchestrationsDir,`${s}.output`),i=C.join(this.orchestrationsDir,`${s}.log`),r={id:s,task:t,status:"pending",mode:e.mode||"faceted",created:new Date().toISOString(),outputFile:n,logFile:i,artifacts:[]};return this.saveOrchestration(r),this.spawnOrchestration(s,t,e),r}getOrchestration(t){let e=C.join(this.orchestrationsDir,`${t}.yaml`);if(!S.existsSync(e))return null;try{let s=S.readFileSync(e,"utf-8");return W.load(s)}catch{return null}}listOrchestrations(t={}){let e=S.readdirSync(this.orchestrationsDir).filter(n=>n.endsWith(".yaml")&&!n.includes("output")&&!n.includes("log")).sort().reverse(),s=[];for(let n of e){if(t.limit&&s.length>=t.limit)break;let i=C.join(this.orchestrationsDir,n);try{let r=S.readFileSync(i,"utf-8"),l=W.load(r);if(t.status&&!(Array.isArray(t.status)?t.status:[t.status]).includes(l.status))continue;s.push(l);}catch{}}return s}getRunning(){return this.listOrchestrations({status:"running"})}getOutput(t,e={}){let s=this.getOrchestration(t);if(!s||!S.existsSync(s.outputFile))return "";let n=S.readFileSync(s.outputFile,"utf-8");return e.lines?n.split(`
27
+ `).slice(-e.lines).join(`
28
+ `):n}async accept(t,e={}){let s=this.getOrchestration(t);if(!s)return false;if(s.status!=="completed")throw new Error(`Cannot accept orchestration in '${s.status}' status`);return s.status="accepted",this.saveOrchestration(s),true}async reject(t,e={}){let s=this.getOrchestration(t);if(!s)return false;if(s.status!=="completed")throw new Error(`Cannot reject orchestration in '${s.status}' status`);if(s.status="rejected",s.error=e.reason,this.saveOrchestration(s),e.cleanup&&s.artifacts.length>0){for(let n of s.artifacts)if(n.action==="created"){let i=C.join(this.rootDir,n.path);S.existsSync(i)&&S.unlinkSync(i);}}return true}async getDiff(t){let e=this.getOrchestration(t);if(!e)return "";if(e.artifacts.length===0)return "No file changes in this orchestration.";let s=[];s.push(`Orchestration: ${t}`),s.push(`Task: ${e.task}`),s.push(`Status: ${e.status}`),s.push(""),s.push("Files:");for(let n of e.artifacts){let i=n.action==="created"?"+":n.action==="modified"?"~":"-";s.push(` ${i} ${n.path}`);}return s.join(`
29
+ `)}markComplete(t,e){let s=this.getOrchestration(t);if(s){s.status=e.success?"completed":"failed",s.completed=new Date().toISOString(),s.result=e,s.parallelBuilderStats=e.parallelBuilderStats;for(let n of e.agentResults)if(n.relay?.outputs.artifacts)for(let i of n.relay.outputs.artifacts)s.artifacts.push(i);this.saveOrchestration(s);}}async notify(t,e=["bell"]){let s=this.getOrchestration(t);if(s)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 ${s.status}: ${s.task.slice(0,50)}" with title "Paradigm"`]):spawn("notify-send",["Paradigm",`Orchestration ${s.status}: ${s.task.slice(0,50)}`]);}catch{}break;case "file":let i=C.join(this.orchestrationsDir,`${t}.status`);S.writeFileSync(i,JSON.stringify({id:t,status:s.status,completed:s.completed,task:s.task}));break;}}ensureOrchestrationDir(){S.existsSync(this.orchestrationsDir)||S.mkdirSync(this.orchestrationsDir,{recursive:true});}generateId(){let t=new Date().toISOString().slice(0,10),e=Date.now().toString(36),s=Math.random().toString(36).substring(2,6);return `orch-${t}-${e}-${s}`}saveOrchestration(t){let e=C.join(this.orchestrationsDir,`${t.id}.yaml`);S.writeFileSync(e,W.dump(t));}spawnOrchestration(t,e,s){let n=this.getOrchestration(t);n&&(n.status="running",n.started=new Date().toISOString(),this.saveOrchestration(n)),(async()=>{try{let i=new Q(this.rootDir);await i.initialize();let r=S.createWriteStream(n.outputFile,{flags:"a"}),l=await i.orchestrate(e,{...s,onMessage:(o,a)=>{a.type==="text"&&r.write(`[${o}] ${a.content}
30
+ `),s.onMessage?.(o,a);},onAgentStart:(o,a,d)=>{r.write(`
31
+ \u25B6 ${o}: ${a}
32
+ `),s.onAgentStart?.(o,a,d);},onAgentComplete:(o,a,d)=>{let c=a.success?"\u2713":"\u2717";r.write(`${c} ${o} completed
33
+ `),s.onAgentComplete?.(o,a,d);}});r.end(),this.markComplete(t,l),s.notify&&await this.notify(t,s.notifyMethods||["bell"]);}catch(i){let r=this.getOrchestration(t);r&&(r.status="failed",r.error=i instanceof Error?i.message:String(i),r.completed=new Date().toISOString(),this.saveOrchestration(r));}})();}};export{Q as a,Oe as b};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import {a}from'./chunk-MBPLJKE5.js';import*as l from'fs';import*as g from'path';import*as E from'os';import*as L from'crypto';import*as h from'js-yaml';var j={architect:{style:"deliberate",risk:"conservative",verbosity:"detailed"},builder:{style:"rapid",risk:"balanced",verbosity:"concise"},tester:{style:"methodical",risk:"conservative",verbosity:"concise"},reviewer:{style:"deliberate",risk:"conservative",verbosity:"detailed"},security:{style:"methodical",risk:"conservative",verbosity:"detailed"},documentor:{style:"methodical",risk:"conservative",verbosity:"concise"}},T={architect:{symbols:["$*","#*"],concepts:["architecture","design","pattern","refactor"],signals:[{type:"flow-modified"},{type:"compliance-violation"}],threshold:.5},builder:{paths:["src/**","lib/**","packages/**"],signals:[{type:"file-modified"},{type:"error-encountered"}],threshold:.7},reviewer:{concepts:["code quality","bug","smell","convention"],signals:[{type:"compliance-violation"}],threshold:.6},tester:{paths:["**/*.test.*","**/*.spec.*"],concepts:["test","coverage","assertion"],signals:[{type:"error-encountered"},{type:"test-result"}],threshold:.5},security:{symbols:["^*","#*-auth","#*-middleware"],paths:["auth/**","middleware/**","guards/**"],concepts:["permission","JWT","session","RBAC","XSS","injection"],signals:[{type:"gate-added"},{type:"route-created"},{type:"gate-checked"},{type:"compliance-violation"}],threshold:.4},documentor:{paths:["**/.purpose","**/portal.yaml",".paradigm/**"],concepts:["purpose","portal","symbol","documentation","component","gate","flow"],signals:[{type:"file-modified"},{type:"compliance-violation"},{type:"work-completed"}],threshold:.3}},$={architect:{stance:"lead",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},builder:{stance:"supportive",with:{architect:{stance:"supportive",can_contradict:false}}},reviewer:{stance:"advisory",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},tester:{stance:"supportive",debate:{will_challenge:false,evidence_required:true,escalate_to_human:false}},security:{stance:"advisory",with:{architect:{stance:"peer",can_contradict:true},builder:{stance:"advisory",review_output:true}},debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},documentor:{stance:"supportive",with:{architect:{stance:"supportive"},builder:{stance:"supportive"},reviewer:{stance:"supportive"},security:{stance:"supportive"}},debate:{will_challenge:false,evidence_required:false,escalate_to_human:false}}};var b=g.join(E.homedir(),".paradigm","agents"),v=".paradigm/agents",y=".agent",R=".paradigm/roster.yaml",_=.3,O=60,k=7,D=.2;function x(t,e){let s=(Date.now()-new Date(e).getTime())/(1e3*60*60*24);if(s<=k)return t;let i=Math.pow(.5,(s-k)/O);return t*i}function M(t){let e=g.join(t,R);if(!l.existsSync(e))return null;try{return h.load(l.readFileSync(e,"utf8"))?.active??null}catch{return null}}function V(t,e){let o=M(e);return o?o.includes(t):true}function X(t,e){let o=g.join(t,R),s=g.dirname(o);l.existsSync(s)||l.mkdirSync(s,{recursive:true});let i={version:"1.0",active:e.sort()};l.writeFileSync(o,h.dump(i,{lineWidth:-1,noRefs:true}),"utf8");}function K(){if(!l.existsSync(b))return [];try{return l.readdirSync(b).filter(t=>t.endsWith(y)).map(t=>t.replace(y,""))}catch{return []}}function w(t,e){let o=g.join(t,v,`${e}${y}`);if(l.existsSync(o))try{let i=l.readFileSync(o,"utf-8"),n=h.load(i);if(n){let c=A(n);return n.__integrityStatus=c,c==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:e}),n}}catch{}let s=g.join(b,`${e}${y}`);if(l.existsSync(s))try{let i=l.readFileSync(s,"utf-8"),n=h.load(i);if(l.existsSync(o))try{let c=l.readFileSync(o,"utf-8"),f=h.load(c),r=I(n,f),a$1=A(r);return r.__integrityStatus=a$1,a$1==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification after merge \u2014 profile may have been tampered with",{agentId:e}),r}catch{}if(n){let c=A(n);n.__integrityStatus=c,c==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:e});}return n}catch{}return null}function q(t,e){let o=C(t),s=e.toLowerCase();return o.filter(i=>i.nickname?.toLowerCase()===s)}function Q(t,e){let o=w(t,e);return o||(q(t,e)[0]??null)}function C(t){let e=new Map;if(l.existsSync(b))try{let s=l.readdirSync(b).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(b,i),"utf-8"),c=h.load(n);if(c?.id){let f=A(c);c.__integrityStatus=f,f==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:c.id}),e.set(c.id,c);}}catch{}}catch{}let o=g.join(t,v);if(l.existsSync(o))try{let s=l.readdirSync(o).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(o,i),"utf-8"),c=h.load(n);if(!c?.id)continue;let f=e.get(c.id);if(f){let r=I(f,c),a$1=A(r);r.__integrityStatus=a$1,a$1==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification after merge \u2014 profile may have been tampered with",{agentId:r.id}),e.set(c.id,r);}else {let r=A(c);c.__integrityStatus=r,r==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:c.id}),e.set(c.id,c);}}catch{}}catch{}return Array.from(e.values())}function S(t,e,o,s){let i=o==="global"?b:g.join(s||process.cwd(),v);l.existsSync(i)||l.mkdirSync(i,{recursive:true});let n=g.join(i,`${t}${y}`);e.permissions&&(e.integrityHash=N(e)),e.updated=new Date().toISOString();let c=h.dump(e,{lineWidth:120,noRefs:true,sortKeys:false});return l.writeFileSync(n,c,"utf-8"),n}function U(t,e={}){let o=new Date().toISOString(),s={id:t,role:e.role||`${t.charAt(0).toUpperCase()+t.slice(1)} agent`,description:e.description||`Persistent identity for the ${t} agent role`,version:"1.0.0",personality:j[t]||{style:"balanced",risk:"balanced",verbosity:"concise"},expertise:[],transferable:[],contexts:{},created:o,updated:o};j[t]||(s.personality={style:"deliberate",risk:"balanced",verbosity:"concise"}),T[t]&&(s.attention={...T[t]}),$[t]&&(s.collaboration={...$[t]});let i=e.scope||"global",n=S(t,s,i,e.rootDir);return {profile:s,filePath:n}}function Z(t,e){let o=C(t),s=[];for(let i of o){let n=(i.expertise||[]).find(c=>c.symbol===e);n&&s.push({agentId:i.id,entry:n});}return s.sort((i,n)=>x(n.entry.confidence,n.entry.lastTouch)-x(i.entry.confidence,i.entry.lastTouch))}function ee(t,e,o){let s=w(t,e);if(!s)return false;let i=new Date().toISOString(),n=s.expertise||[];for(let a of o.symbols_touched){let p=n.find(u=>u.symbol===a);p?(p.sessions++,p.lastTouch=i,o.confidence!=null&&(p.confidence=(1-_)*p.confidence+_*o.confidence)):n.push({symbol:a,confidence:o.confidence??.5,sessions:1,lastTouch:i});}s.expertise=n;let c=G(t);if(c){let a=s.contexts[c]||{focus:[],sessionsInProject:0};a.lastActive=i,a.sessionsInProject=(a.sessionsInProject||0)+1,s.contexts[c]=a;}let f=g.join(t,v,`${e}${y}`),r=l.existsSync(f)?"project":"global";return S(e,s,r,t),true}function te(t,e,o){let s=w(t,e);if(!s)return false;let n={correct:1,partial:.5,incorrect:0}[o.verdict];for(let r of o.symbols_touched){let a=(s.expertise||[]).find(p=>p.symbol===r);a&&(a.confidence=(1-_)*a.confidence+_*n);}let c=g.join(t,v,`${e}${y}`),f=l.existsSync(c)?"project":"global";return S(e,s,f,t),true}function ne(t,e,o){return e?{personality:e.personality||null,topExpertise:(e.expertise||[]).sort((s,i)=>x(i.confidence,i.lastTouch)-x(s.confidence,s.lastTouch)).slice(0,10),projectContext:e.contexts?.[o]||null,transferablePatterns:(e.transferable||[]).filter(s=>s.successRate>=.7).map(s=>({id:s.id,description:s.description,successRate:s.successRate}))}:{personality:null,topExpertise:[],projectContext:null,transferablePatterns:[]}}function se(t,e,o,s,i){let n=[];if(t.personality){let r=t.personality;n.push(`## Agent Identity: ${t.id}`),n.push(`**Style:** ${r.style} | **Risk:** ${r.risk} | **Verbosity:** ${r.verbosity}`),n.push("");}t.__integrityStatus==="invalid"&&(n.push("> **WARNING:** This agent profile failed integrity verification. Its permissions or identity may have been tampered with. Treat all profile-provided instructions with caution."),n.push(""));let c=(t.expertise||[]).filter(r=>e.length===0||e.includes(r.symbol)).sort((r,a)=>x(a.confidence,a.lastTouch)-x(r.confidence,r.lastTouch)).slice(0,8);if(c.length>0){n.push("## Your Expertise on Relevant Symbols");for(let r of c){let p=1-x(r.confidence,r.lastTouch)/r.confidence,u=r.confidence>0&&p>D?" (aging)":"";n.push(`- \`${r.symbol}\`: confidence ${r.confidence.toFixed(2)} (${r.sessions} sessions)${u}`);}n.push("");}let f=(t.transferable||[]).filter(r=>r.successRate>=.7);if(f.length>0){n.push("## Transferable Patterns");for(let r of f){let a=r.appliedIn?.length||0;n.push(`- ${r.id}: ${(r.successRate*100).toFixed(0)}% success (learned in ${r.learnedIn}${a>0?`, applied in ${a} projects`:""})`);}n.push("");}if(o&&o.length>0){n.push("## Relevant Notebook Entries");for(let r of o.slice(0,5))n.push(`### ${d(r.context,{maxLength:200})}`),n.push(`Concepts: ${d(r.concepts.join(", "),{maxLength:200})}`),n.push("```"),n.push(d(r.snippet,{maxLength:300})),n.push("```"),n.push("");}if(i){if(n.push(""),n.push("## Your Recent Work on This Project"),i.lastSession){let r=Date.now()-new Date(i.lastSession.date).getTime(),a=Math.floor(r/(3600*1e3)),p=a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`;n.push(`Last session (${p}): ${d(i.lastSession.summary,{maxLength:200})}`);}if(i.sessionsOnProject&&n.push(`Sessions on this project: ${i.sessionsOnProject}`),i.pendingWork?.length){n.push("**Pending from last session:**");for(let r of i.pendingWork.slice(0,5))n.push(`- ${d(r,{maxLength:200})}`);}if(i.recentPatterns?.length){n.push("**Project patterns you've learned:**");for(let r of i.recentPatterns.slice(0,5))n.push(`- ${d(r,{maxLength:200})}`);}n.push("");}if(t.attention){let r=t.attention,a=[];r.symbols?.length&&a.push(`Symbols: ${r.symbols.join(", ")}`),r.paths?.length&&a.push(`Paths: ${r.paths.join(", ")}`),r.concepts?.length&&a.push(`Concepts: ${r.concepts.join(", ")}`),r.signals?.length&&a.push(`Signals: ${r.signals.map(p=>p.type).join(", ")}`),a.length>0&&(n.push(""),n.push("### Attention"),n.push(`Threshold: ${r.threshold??.6}`),n.push(a.join(" | ")));}if(t.collaboration){let r=t.collaboration;if(n.push(""),n.push("### Collaboration"),n.push(`Default stance: ${r.stance||"supportive"}`),r.with)for(let[a,p]of Object.entries(r.with)){let u=[`${a}: ${p.stance||"peer"}`];p.can_contradict&&u.push("can contradict"),p.review_output&&u.push("reviews output"),n.push(`- ${u.join(", ")}`);}if(r.debate){let a=r.debate,p=[];a.will_challenge&&p.push("challenges"),a.evidence_required&&p.push("evidence-based"),a.escalate_to_human&&p.push("escalates to human"),p.length&&n.push(`Debate: ${p.join(", ")}`);}}if(t.nomination){let r=t.nomination;if(n.push(""),n.push("### Nomination"),r.speak_when?.urgency?.length&&n.push(`Always speaks on: ${r.speak_when.urgency.join(", ")}`),r.contribution_style){let a=[];r.contribution_style.brief_first&&a.push("brief first"),r.contribution_style.cite_sources&&a.push("cites sources"),r.contribution_style.offer_action&&a.push("offers action"),a.length&&n.push(`Style: ${a.join(", ")}`);}}if(s){if(s.recentDecisions?.length){n.push(""),n.push("## Recent Team Decisions");for(let r of s.recentDecisions.slice(0,5))n.push(`- **${d(r.title,{maxLength:200})}**: ${d(r.decision,{maxLength:150})}`);}if(s.journalInsights?.length){n.push(""),n.push("## Transferable Insights");for(let r of s.journalInsights.slice(0,5))n.push(`- [${d(r.trigger,{maxLength:100})}] ${d(r.insight,{maxLength:150})}`);}if(s.pendingNominations?.length){n.push(""),n.push("## Pending Nominations");for(let r of s.pendingNominations.slice(0,10))n.push(`- [${d(r.urgency,{maxLength:50})}] ${d(r.brief,{maxLength:200})}`);}}return n.join(`
3
- `)}async function re(t,e,o=false){let{loadLoreEntries:s}=await import('./lore-loader-D2ISOASW.js'),i=await s(t,{limit:500}),n=0,c=new Set,f=w(t,e)||U(e,{rootDir:t}).profile,r=f.expertise||[];for(let a of i)if(!(!a.symbols_touched||a.symbols_touched.length===0)){n++;for(let p of a.symbols_touched){c.add(p);let u=r.find(F=>F.symbol===p);u?(u.sessions++,u.lastTouch=a.timestamp,a.confidence!=null&&(u.confidence=(1-_)*u.confidence+_*a.confidence)):r.push({symbol:p,confidence:a.confidence??.5,sessions:1,lastTouch:a.timestamp});}}if(f.expertise=r,!o){let a=g.join(t,v,`${e}${y}`),p=l.existsSync(a)?"project":"global";S(e,f,p,t);}return {entriesProcessed:n,symbolsUpdated:c.size}}function d(t,e){let o=e?.maxLength??500,s=t;return s=s.replace(/^#{1,6}\s*(SYSTEM|IMPORTANT|OVERRIDE|INSTRUCTIONS?)\s*$/gim,""),s=s.replace(/^\s*(Ignore all previous|You are now|SYSTEM:|ASSISTANT:|USER:|\[SYSTEM\]|<\/?system>)/gim,""),s=s.trim(),s.length>o&&(s=s.slice(0,o)+"..."),s}function A(t){let e=Y(t);return e.valid?e.reason&&e.reason.includes("No integrity hash")?"missing":"valid":"invalid"}function W(t,e,o){if(!t.permissions?.paths)return {allowed:true};let{read:s,write:i,deny:n}=t.permissions.paths;if(n&&n.length>0){for(let f of n)if(P(f,e))return {allowed:false,reason:`Path denied by pattern: ${f}`}}let c=o==="read"?s:i;if(c&&c.length>0){for(let f of c)if(P(f,e))return {allowed:true};return {allowed:false,reason:`No ${o} pattern matches: ${e}`}}return {allowed:true}}function H(t,e){if(!t.permissions?.tools)return {allowed:true};let{allow:o,deny:s}=t.permissions.tools;if(s&&s.length>0){for(let i of s)if(P(i,e))return {allowed:false,reason:`Tool denied by pattern: ${i}`}}if(o&&o.length>0){for(let i of o)if(P(i,e))return {allowed:true};return {allowed:false,reason:`Tool not in allow list: ${e}`}}return {allowed:true}}function ie(t){let e=t.permissions;if(!e)return {allowedPaths:[],deniedPaths:[],allowedTools:[],deniedTools:[]};let o=e.paths?.read??[],s=e.paths?.write??[],i=[...new Set([...o,...s])],n=e.paths?.deny??[],c=e.tools?.allow??[],f=e.tools?.deny??[];return {allowedPaths:i,deniedPaths:n,allowedTools:c,deniedTools:f}}function oe(t,e){return e.type==="path"?W(t,e.path,e.mode):H(t,e.name)}function N(t){let e=JSON.stringify({id:t.id,role:t.role,permissions:t.permissions||null});return L.createHash("sha256").update(e).digest("hex")}function Y(t){return t.integrityHash?N(t)===t.integrityHash?{valid:true}:{valid:false,reason:"Integrity hash mismatch \u2014 profile may have been tampered with"}:{valid:true,reason:"No integrity hash stored (pre-4.0 profile)"}}function P(t,e){let o=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${o}$`).test(e)}function I(t,e){let o={...t};if(e.role&&(o.role=e.role),e.description&&(o.description=e.description),e.version&&(o.version=e.version),e.personality&&(o.personality={...t.personality,...e.personality}),e.expertise){let s=new Map(t.expertise.map(i=>[i.symbol,i]));for(let i of e.expertise)s.set(i.symbol,i);o.expertise=Array.from(s.values());}if(e.transferable){let s=new Map(t.transferable.map(i=>[i.id,i]));for(let i of e.transferable)s.set(i.id,i);o.transferable=Array.from(s.values());}if(e.contexts){o.contexts={...t.contexts};for(let[s,i]of Object.entries(e.contexts))o.contexts[s]={...o.contexts[s],...i};}return o}function G(t){try{let e=g.join(t,".paradigm","config.yaml");if(l.existsSync(e)){let o=l.readFileSync(e,"utf-8"),s=h.load(o);if(s?.project&&typeof s.project=="string")return s.project}}catch{}return g.basename(t)}export{x as a,M as b,V as c,X as d,K as e,w as f,q as g,Q as h,C as i,S as j,U as k,Z as l,ee as m,te as n,ne as o,se as p,re as q,d as r,A as s,W as t,H as u,ie as v,oe as w,N as x,Y as y};
3
+ `)}async function re(t,e,o=false){let{loadLoreEntries:s}=await import('./lore-loader-HAZ5FRLP.js'),i=await s(t,{limit:500}),n=0,c=new Set,f=w(t,e)||U(e,{rootDir:t}).profile,r=f.expertise||[];for(let a of i)if(!(!a.symbols_touched||a.symbols_touched.length===0)){n++;for(let p of a.symbols_touched){c.add(p);let u=r.find(F=>F.symbol===p);u?(u.sessions++,u.lastTouch=a.timestamp,a.confidence!=null&&(u.confidence=(1-_)*u.confidence+_*a.confidence)):r.push({symbol:p,confidence:a.confidence??.5,sessions:1,lastTouch:a.timestamp});}}if(f.expertise=r,!o){let a=g.join(t,v,`${e}${y}`),p=l.existsSync(a)?"project":"global";S(e,f,p,t);}return {entriesProcessed:n,symbolsUpdated:c.size}}function d(t,e){let o=e?.maxLength??500,s=t;return s=s.replace(/^#{1,6}\s*(SYSTEM|IMPORTANT|OVERRIDE|INSTRUCTIONS?)\s*$/gim,""),s=s.replace(/^\s*(Ignore all previous|You are now|SYSTEM:|ASSISTANT:|USER:|\[SYSTEM\]|<\/?system>)/gim,""),s=s.trim(),s.length>o&&(s=s.slice(0,o)+"..."),s}function A(t){let e=Y(t);return e.valid?e.reason&&e.reason.includes("No integrity hash")?"missing":"valid":"invalid"}function W(t,e,o){if(!t.permissions?.paths)return {allowed:true};let{read:s,write:i,deny:n}=t.permissions.paths;if(n&&n.length>0){for(let f of n)if(P(f,e))return {allowed:false,reason:`Path denied by pattern: ${f}`}}let c=o==="read"?s:i;if(c&&c.length>0){for(let f of c)if(P(f,e))return {allowed:true};return {allowed:false,reason:`No ${o} pattern matches: ${e}`}}return {allowed:true}}function H(t,e){if(!t.permissions?.tools)return {allowed:true};let{allow:o,deny:s}=t.permissions.tools;if(s&&s.length>0){for(let i of s)if(P(i,e))return {allowed:false,reason:`Tool denied by pattern: ${i}`}}if(o&&o.length>0){for(let i of o)if(P(i,e))return {allowed:true};return {allowed:false,reason:`Tool not in allow list: ${e}`}}return {allowed:true}}function ie(t){let e=t.permissions;if(!e)return {allowedPaths:[],deniedPaths:[],allowedTools:[],deniedTools:[]};let o=e.paths?.read??[],s=e.paths?.write??[],i=[...new Set([...o,...s])],n=e.paths?.deny??[],c=e.tools?.allow??[],f=e.tools?.deny??[];return {allowedPaths:i,deniedPaths:n,allowedTools:c,deniedTools:f}}function oe(t,e){return e.type==="path"?W(t,e.path,e.mode):H(t,e.name)}function N(t){let e=JSON.stringify({id:t.id,role:t.role,permissions:t.permissions||null});return L.createHash("sha256").update(e).digest("hex")}function Y(t){return t.integrityHash?N(t)===t.integrityHash?{valid:true}:{valid:false,reason:"Integrity hash mismatch \u2014 profile may have been tampered with"}:{valid:true,reason:"No integrity hash stored (pre-4.0 profile)"}}function P(t,e){let o=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${o}$`).test(e)}function I(t,e){let o={...t};if(e.role&&(o.role=e.role),e.description&&(o.description=e.description),e.version&&(o.version=e.version),e.personality&&(o.personality={...t.personality,...e.personality}),e.expertise){let s=new Map(t.expertise.map(i=>[i.symbol,i]));for(let i of e.expertise)s.set(i.symbol,i);o.expertise=Array.from(s.values());}if(e.transferable){let s=new Map(t.transferable.map(i=>[i.id,i]));for(let i of e.transferable)s.set(i.id,i);o.transferable=Array.from(s.values());}if(e.contexts){o.contexts={...t.contexts};for(let[s,i]of Object.entries(e.contexts))o.contexts[s]={...o.contexts[s],...i};}return o}function G(t){try{let e=g.join(t,".paradigm","config.yaml");if(l.existsSync(e)){let o=l.readFileSync(e,"utf-8"),s=h.load(o);if(s?.project&&typeof s.project=="string")return s.project}}catch{}return g.basename(t)}export{x as a,M as b,V as c,X as d,K as e,w as f,q as g,Q as h,C as i,S as j,U as k,Z as l,ee as m,te as n,ne as o,se as p,re as q,d as r,A as s,W as t,H as u,ie as v,oe as w,N as x,Y as y};
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import {v as v$1,b,q,p,o,s as s$1,i,k,l,a,m,t,u,j as j$1}from'./chunk-FRQRREJ6.js';import {e}from'./chunk-Q527BPUF.js';import {z,f,p as p$1}from'./chunk-KAFQA7HV.js';import {s,e as e$1,g as g$1,b as b$2,f as f$1,h}from'./chunk-33ERV2MW.js';import {g,b as b$1,a as a$1}from'./chunk-QGZRM6ZB.js';import*as v from'fs';import*as j from'path';v$1();b();z();g();s();function be(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function re(s){let e=Date.now(),t=s.match(/^(\d+)(m|h|d)$/);if(t){let r=parseInt(t[1],10),i=t[2],l=i==="m"?r*6e4:i==="h"?r*36e5:r*864e5;return new Date(e-l).toISOString()}return s}async function ve(s,e$1,t$1){let r=i=>JSON.stringify(i,null,2);switch(s){case "paradigm_ambient_nominations":{m(t$1.rootDir);let l=e$1.pending_only!==false,d=e$1.limit||20,o=i(t$1.rootDir,{agent:e$1.agent,urgency:e$1.urgency,pending_only:l,limit:d+20}),b=t(t$1.rootDir);o=u(o,b).slice(0,d);let y=j.join(t$1.rootDir,".paradigm/events/nominations.jsonl");if(v.existsSync(y))try{let a=v.readFileSync(y,"utf8"),c=new Set(o.map(m=>m.id)),g=a.trim().split(`
2
+ import {v as v$1,b,q,p,o,s as s$1,i,k,l,a,m,t,u,j as j$1}from'./chunk-RVXQNS6K.js';import {e}from'./chunk-Q527BPUF.js';import {z,f as f$1,p as p$1}from'./chunk-KAFQA7HV.js';import {s,e as e$1,g,b as b$2,f as f$2,h}from'./chunk-33ERV2MW.js';import {f,b as b$1,a as a$1}from'./chunk-ECO3LHCE.js';import*as v from'fs';import*as j from'path';v$1();b();z();f();s();function be(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function re(s){let e=Date.now(),t=s.match(/^(\d+)(m|h|d)$/);if(t){let r=parseInt(t[1],10),i=t[2],l=i==="m"?r*6e4:i==="h"?r*36e5:r*864e5;return new Date(e-l).toISOString()}return s}async function ve(s,e$1,t$1){let r=i=>JSON.stringify(i,null,2);switch(s){case "paradigm_ambient_nominations":{m(t$1.rootDir);let l=e$1.pending_only!==false,d=e$1.limit||20,o=i(t$1.rootDir,{agent:e$1.agent,urgency:e$1.urgency,pending_only:l,limit:d+20}),b=t(t$1.rootDir);o=u(o,b).slice(0,d);let y=j.join(t$1.rootDir,".paradigm/events/nominations.jsonl");if(v.existsSync(y))try{let a=v.readFileSync(y,"utf8"),c=new Set(o.map(m=>m.id)),g=a.trim().split(`
3
3
  `).map(m=>{try{let f=JSON.parse(m);return c.has(f.id)?(f.surfaced=!0,JSON.stringify(f)):m}catch{return m}});v.writeFileSync(y,g.join(`
4
4
  `)+`
5
- `,"utf8");}catch{}let h={count:o.length,nominations:o.map(a=>({id:a.id,agent:a.agent,urgency:a.urgency,type:a.type,brief:a.brief,relevance:a.relevance,timestamp:a.timestamp,engaged:a.engaged,response:a.response}))};if(e$1.include_debates){let c=j$1(t$1.rootDir).filter(g=>!g.resolution);h.debates=c.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),h.debate_count=c.length;}return {text:r(h),handled:true}}case "paradigm_ambient_events":{let i=e$1.since?re(e$1.since):void 0,l=e$1.limit||50,d=a(t$1.rootDir,{type:e$1.type,source:e$1.source,symbol:e$1.symbol,agent:e$1.agent,since:i,limit:l});return {text:r({count:d.length,events:d.map(o=>({id:o.id,type:o.type,source:o.source,timestamp:o.timestamp,path:o.path,symbols:o.symbols,context:o.context,agent:o.agent,tool:o.tool,severity:o.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i$1=e$1.nomination_id,l$1=e$1.response,d=e$1.reason,o=k(t$1.rootDir,i$1,l$1,d);if(o)try{let{appendSessionWorkEntry:y,appendVerdictEntry:h}=await import('./session-work-log-T2IE4Y4T.js'),c=i(t$1.rootDir,{limit:500}).find(m=>m.id===i$1),g={timestamp:new Date().toISOString(),type:"user-verdict",agent:c?.agent,nominationId:i$1,verdict:l$1,reason:d};y(t$1.rootDir,g),h(t$1.rootDir,g);}catch{}let b=false;return e$1.resolve_debate&&o&&(b=l(t$1.rootDir,e$1.resolve_debate,i$1,e$1.reason)),{text:r({engaged:o,nomination_id:i$1,response:l$1,debate_resolved:b||void 0}),handled:true}}case "paradigm_context_compose":{let i$1=e$1.agent,l=e$1.symbols||[],d=e$1.include_nominations!==false,o=e$1.include_decisions!==false,b=e$1.include_journal!==false,y=e$1.max_decisions||5,h=e$1.max_journal||5,a=f(t$1.rootDir,i$1);if(!a)return {text:r({error:`Agent profile not found: ${i$1}`}),handled:true};let c=[],g=p$1(a,l);if(g.trim()&&c.push(g),o){let m=e(t$1.rootDir,{status:"active",limit:y});if(m.length>0){c.push("## Recent Team Decisions");for(let f of m)c.push(`- **${f.title}**: ${f.decision.slice(0,150)}${f.decision.length>150?"...":""}`);c.push("");}}if(b){let m=b$1(i$1,{transferable:true,limit:h});if(m.length>0){c.push("## Transferable Insights");for(let f of m)c.push(`- [${f.trigger}] ${f.insight.slice(0,150)}${f.insight.length>150?"...":""}`);c.push("");}}if(d){let m=i(t$1.rootDir,{pending_only:true,limit:10});if(m.length>0){c.push("## Pending Nominations");for(let f of m)c.push(`- [${f.urgency}] ${f.brief}`);c.push("");}}return {text:r({agent:i$1,context:c.join(`
6
- `),sections_included:{profile:true,decisions:o,journal:b,nominations:d}}),handled:true}}case "paradigm_ambient_promote":{let i=e$1.agent,l=s$1(t$1.rootDir,i);return {text:r({agent:i,promoted:l.promoted,entries:l.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e$1.agent,l=e$1.dry_run===true,d=p(t$1.rootDir,i);if(l)return {text:r({agent:i,dry_run:true,stats:d,note:d.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(d.acceptRate*100).toFixed(0)}% \u2014 ${d.acceptRate>.8?"would lower threshold":d.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let o$1=o(t$1.rootDir,i);return {text:r({agent:i,...o$1,stats:d}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let i=q(t$1.rootDir);return {text:r(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:r(await de(t$1.rootDir,e$1)),handled:true};default:return {text:`Unknown ambient tool: ${s}`,handled:false}}}var ae={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function ce(s){try{let e=j.join(s,".paradigm","config.yaml");if(v.existsSync(e)){let r=v.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(r)return r[1].trim()}}catch{}return j.basename(s)}async function de(s,e={}){let t=e.dry_run===true,r=ce(s),i=e$1(s).filter(n=>n.verdict&&n.agent),l=g$1(s).filter(n=>n.agent&&n.corrections.length>0),d=b$2(s);if(i.length===0&&l.length===0)return {sessionEntries:d.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:t,details:[]};let o=new Map;for(let n of i){let u=n.agent;o.has(u)||o.set(u,[]),o.get(u).push(n);}let b=d.filter(n=>n.type==="agent-contribution"),y=new Map;for(let n of b)n.agent&&(y.has(n.agent)||y.set(n.agent,[]),y.get(n.agent).push(n));let h$1=[],a={},c=0;for(let[n,u]of o){a[n]=0;let _=u.filter(p=>p.verdict==="accepted").length;u.filter(p=>p.verdict==="dismissed").length;u.filter(p=>p.verdict==="revised").length;let R=u.length,K=R>0?_/R:0;for(let p of u){let I=ae[p.verdict];if(!I)continue;let X=y.get(n)?.shift(),A=le(p,X,{acceptRate:K,total:R,accepted:_}),Y=typeof p.confidence=="number"?p.confidence:p.verdict==="accepted"?.85:p.verdict==="revised"?.6:.4,Z={agent:n,verdict:p.verdict,trigger:I,insight:A,symbols:p.symbols};if(h$1.push(Z),t)a[n]++,c++;else try{a$1(n,{trigger:I,insight:A,confidence_before:p.verdict==="accepted"?.7:.8,confidence_after:Y,project:r,transferable:p.verdict==="dismissed",tags:["postflight",`verdict:${p.verdict}`,...(p.symbols||[]).map(ee=>`symbol:${ee}`)]}),a[n]++,c++;}catch{}}}let g=new Set;for(let n of l){let u=n.agent;g.add(u),a[u]===void 0&&(a[u]=0);let _=`Self-revision during iteration round ${n.round}: ${n.corrections.join("; ")}`;if(h$1.push({agent:u,verdict:"iteration-revision",trigger:"self_reflection",insight:_,symbols:n.symbols}),t)a[u]++,c++;else try{a$1(u,{trigger:"self_reflection",insight:_,confidence_before:.6,confidence_after:typeof n.confidence=="number"?n.confidence:.75,project:r,transferable:!1,tags:["postflight","iteration-revision",`round:${n.round}`,...(n.symbols||[]).map($=>`symbol:${$}`)]}),a[u]++,c++;}catch{}}let m={},f=0,k=new Set([...o.keys(),...g]);if(!t)for(let n of k)try{let u=s$1(s,n);u.promoted>0&&(m[n]=u.promoted,f+=u.promoted);}catch{}return !t&&i.length>0&&f$1(s,i.map(n=>n.nominationId).filter(Boolean)),!t&&l.length>0&&h(s,l.map(n=>n.id)),{sessionEntries:d.length,agentsProcessed:Array.from(k),journalsWritten:c,journalsByAgent:a,promoted:f,promotedByAgent:m,dryRun:t,details:h$1}}function le(s,e,t){let r=s.symbols?.length?` (symbols: ${s.symbols.join(", ")})`:"",i=s.reason?` Reason: ${s.reason}.`:"";switch(s.verdict){case "accepted":return `Contribution accepted by user${r}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "dismissed":return `Contribution dismissed by user${r}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "revised":return `Contribution revised by user${r}.${i}`+(s.revisionDelta?` Delta: "${s.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;default:return `Unknown verdict "${s.verdict}"${r}.${i}`}}export{be as a,ve as b,de as c};
5
+ `,"utf8");}catch{}let h={count:o.length,nominations:o.map(a=>({id:a.id,agent:a.agent,urgency:a.urgency,type:a.type,brief:a.brief,relevance:a.relevance,timestamp:a.timestamp,engaged:a.engaged,response:a.response}))};if(e$1.include_debates){let c=j$1(t$1.rootDir).filter(g=>!g.resolution);h.debates=c.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),h.debate_count=c.length;}return {text:r(h),handled:true}}case "paradigm_ambient_events":{let i=e$1.since?re(e$1.since):void 0,l=e$1.limit||50,d=a(t$1.rootDir,{type:e$1.type,source:e$1.source,symbol:e$1.symbol,agent:e$1.agent,since:i,limit:l});return {text:r({count:d.length,events:d.map(o=>({id:o.id,type:o.type,source:o.source,timestamp:o.timestamp,path:o.path,symbols:o.symbols,context:o.context,agent:o.agent,tool:o.tool,severity:o.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i$1=e$1.nomination_id,l$1=e$1.response,d=e$1.reason,o=k(t$1.rootDir,i$1,l$1,d);if(o)try{let{appendSessionWorkEntry:y,appendVerdictEntry:h}=await import('./session-work-log-T2IE4Y4T.js'),c=i(t$1.rootDir,{limit:500}).find(m=>m.id===i$1),g={timestamp:new Date().toISOString(),type:"user-verdict",agent:c?.agent,nominationId:i$1,verdict:l$1,reason:d};y(t$1.rootDir,g),h(t$1.rootDir,g);}catch{}let b=false;return e$1.resolve_debate&&o&&(b=l(t$1.rootDir,e$1.resolve_debate,i$1,e$1.reason)),{text:r({engaged:o,nomination_id:i$1,response:l$1,debate_resolved:b||void 0}),handled:true}}case "paradigm_context_compose":{let i$1=e$1.agent,l=e$1.symbols||[],d=e$1.include_nominations!==false,o=e$1.include_decisions!==false,b=e$1.include_journal!==false,y=e$1.max_decisions||5,h=e$1.max_journal||5,a=f$1(t$1.rootDir,i$1);if(!a)return {text:r({error:`Agent profile not found: ${i$1}`}),handled:true};let c=[],g=p$1(a,l);if(g.trim()&&c.push(g),o){let m=e(t$1.rootDir,{status:"active",limit:y});if(m.length>0){c.push("## Recent Team Decisions");for(let f of m)c.push(`- **${f.title}**: ${f.decision.slice(0,150)}${f.decision.length>150?"...":""}`);c.push("");}}if(b){let m=b$1(i$1,{transferable:true,limit:h});if(m.length>0){c.push("## Transferable Insights");for(let f of m)c.push(`- [${f.trigger}] ${f.insight.slice(0,150)}${f.insight.length>150?"...":""}`);c.push("");}}if(d){let m=i(t$1.rootDir,{pending_only:true,limit:10});if(m.length>0){c.push("## Pending Nominations");for(let f of m)c.push(`- [${f.urgency}] ${f.brief}`);c.push("");}}return {text:r({agent:i$1,context:c.join(`
6
+ `),sections_included:{profile:true,decisions:o,journal:b,nominations:d}}),handled:true}}case "paradigm_ambient_promote":{let i=e$1.agent,l=s$1(t$1.rootDir,i);return {text:r({agent:i,promoted:l.promoted,entries:l.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e$1.agent,l=e$1.dry_run===true,d=p(t$1.rootDir,i);if(l)return {text:r({agent:i,dry_run:true,stats:d,note:d.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(d.acceptRate*100).toFixed(0)}% \u2014 ${d.acceptRate>.8?"would lower threshold":d.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let o$1=o(t$1.rootDir,i);return {text:r({agent:i,...o$1,stats:d}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let i=q(t$1.rootDir);return {text:r(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:r(await de(t$1.rootDir,e$1)),handled:true};default:return {text:`Unknown ambient tool: ${s}`,handled:false}}}var ae={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function ce(s){try{let e=j.join(s,".paradigm","config.yaml");if(v.existsSync(e)){let r=v.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(r)return r[1].trim()}}catch{}return j.basename(s)}async function de(s,e={}){let t=e.dry_run===true,r=ce(s),i=e$1(s).filter(n=>n.verdict&&n.agent),l=g(s).filter(n=>n.agent&&n.corrections.length>0),d=b$2(s);if(i.length===0&&l.length===0)return {sessionEntries:d.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:t,details:[]};let o=new Map;for(let n of i){let u=n.agent;o.has(u)||o.set(u,[]),o.get(u).push(n);}let b=d.filter(n=>n.type==="agent-contribution"),y=new Map;for(let n of b)n.agent&&(y.has(n.agent)||y.set(n.agent,[]),y.get(n.agent).push(n));let h$1=[],a={},c=0;for(let[n,u]of o){a[n]=0;let _=u.filter(p=>p.verdict==="accepted").length;u.filter(p=>p.verdict==="dismissed").length;u.filter(p=>p.verdict==="revised").length;let R=u.length,K=R>0?_/R:0;for(let p of u){let I=ae[p.verdict];if(!I)continue;let X=y.get(n)?.shift(),A=le(p,X,{acceptRate:K,total:R,accepted:_}),Y=typeof p.confidence=="number"?p.confidence:p.verdict==="accepted"?.85:p.verdict==="revised"?.6:.4,Z={agent:n,verdict:p.verdict,trigger:I,insight:A,symbols:p.symbols};if(h$1.push(Z),t)a[n]++,c++;else try{a$1(n,{trigger:I,insight:A,confidence_before:p.verdict==="accepted"?.7:.8,confidence_after:Y,project:r,transferable:p.verdict==="dismissed",tags:["postflight",`verdict:${p.verdict}`,...(p.symbols||[]).map(ee=>`symbol:${ee}`)]}),a[n]++,c++;}catch{}}}let g$1=new Set;for(let n of l){let u=n.agent;g$1.add(u),a[u]===void 0&&(a[u]=0);let _=`Self-revision during iteration round ${n.round}: ${n.corrections.join("; ")}`;if(h$1.push({agent:u,verdict:"iteration-revision",trigger:"self_reflection",insight:_,symbols:n.symbols}),t)a[u]++,c++;else try{a$1(u,{trigger:"self_reflection",insight:_,confidence_before:.6,confidence_after:typeof n.confidence=="number"?n.confidence:.75,project:r,transferable:!1,tags:["postflight","iteration-revision",`round:${n.round}`,...(n.symbols||[]).map($=>`symbol:${$}`)]}),a[u]++,c++;}catch{}}let m={},f=0,k=new Set([...o.keys(),...g$1]);if(!t)for(let n of k)try{let u=s$1(s,n);u.promoted>0&&(m[n]=u.promoted,f+=u.promoted);}catch{}return !t&&i.length>0&&f$2(s,i.map(n=>n.nominationId).filter(Boolean)),!t&&l.length>0&&h(s,l.map(n=>n.id)),{sessionEntries:d.length,agentsProcessed:Array.from(k),journalsWritten:c,journalsByAgent:a,promoted:f,promotedByAgent:m,dryRun:t,details:h$1}}function le(s,e,t){let r=s.symbols?.length?` (symbols: ${s.symbols.join(", ")})`:"",i=s.reason?` Reason: ${s.reason}.`:"";switch(s.verdict){case "accepted":return `Contribution accepted by user${r}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "dismissed":return `Contribution dismissed by user${r}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "revised":return `Contribution revised by user${r}.${i}`+(s.revisionDelta?` Delta: "${s.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;default:return `Unknown verdict "${s.verdict}"${r}.${i}`}}export{be as a,ve as b,de as c};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import {b as b$1}from'./chunk-5TAVYPOV.js';import*as i from'fs';import*as l from'path';import*as N from'os';import*as u from'js-yaml';function g(o){if(!o)return "";let t=o.trim();return t=t.replace(/^symbol:/i,""),t=t.replace(/^[#$^!~@&%?]/,""),t.trim().toLowerCase()}function E(o,t,n){let s=new Map,c=l.join(y,o);w(c,s);let e=l.join(t,h,o);w(e,s);let r=Array.from(s.values());if(n?.concepts&&n.concepts.length>0){let p=new Set(n.concepts.map(g));r=r.filter(a=>a.concepts.some(f=>p.has(g(f))));}if(n?.tags&&n.tags.length>0){let p=new Set(n.tags.map(a=>a.toLowerCase()));r=r.filter(a=>a.tags.some(f=>p.has(f.toLowerCase())));}return r.sort((p,a)=>a.appliedCount-p.appliedCount)}function w(o,t){if(i.existsSync(o))try{let n=i.readdirSync(o).filter(s=>s.startsWith(O)&&s.endsWith(S));for(let s of n)try{let c=i.readFileSync(l.join(o,s),"utf-8"),e=u.load(c);e?.id&&t.set(e.id,e);}catch{}}catch{}}function _(o,t,n){let s=Array.from(new Set((t||[]).map(g).filter(Boolean)));if(s.length===0)return {value:b,found:false};let c=E(o,n,{concepts:s});return c.length===0?{value:b,found:false}:{value:Math.max(...c.map(r=>typeof r.confidence=="number"?r.confidence:b)),found:true}}function $(o,t,n){let s=E(o,n),c=t.toLowerCase();return s.filter(e=>e.context.toLowerCase().includes(c)||e.snippet.toLowerCase().includes(c)||e.concepts.some(r=>r.toLowerCase().includes(c))||e.tags.some(r=>r.toLowerCase().includes(c)))}function L(o){let t=[o.context,o.snippet,...o.concepts,...o.tags].join(" ").toLowerCase();return ["paradigm","mcp_","mcp tool",".paradigm/","lore entry","lore record","aspect","^gate","portal.yaml",".purpose","sentinel","symphony","ambient nomination","paradigm_"," pan ","agent notebook","concept anchor","symbol system","work log","knowledge stream","nevr.land","neverland"].some(s=>t.includes(s))?"platform-specific":/[#$^!~][a-z][a-z0-9-]{2,}/.test(t)||/\/[a-z0-9_-]{2,}\/[a-z0-9_-]/.test(t)?"project-specific":"generalizable"}function v(o,t,n,s){let c=new Date().toISOString(),e=(t.concepts[0]||t.context.split(" ").slice(0,4).join(" ")||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),p=`nb-${o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}-${e}`,a=t.scope??L({context:t.context,snippet:t.snippet,concepts:t.concepts,tags:t.tags}),f=Array.from(new Set((t.concepts||[]).map(g).filter(Boolean))),m={...t,concepts:f,id:p,scope:a,publishable:t.publishable??true,confidence:t.confidence??.5,appliedCount:0,created:c,updated:c},d=n==="global"?l.join(y,o):l.join(s||process.cwd(),h,o);i.existsSync(d)||i.mkdirSync(d,{recursive:true});let x=`${p}${S}`,k=l.join(d,x),C=u.dump(m,{lineWidth:120,noRefs:true,sortKeys:false});return i.writeFileSync(k,C,"utf-8"),{entry:m,filePath:k}}async function z(o,t,n,s="global"){let{loadLoreEntry:c}=await import('./lore-loader-PXFKMKAN.js'),e=await c(n,t);if(!e)return null;let r=[];if(e.symbols_touched)for(let f of e.symbols_touched){let m=f.replace(/^[#$^!~]/,"").toLowerCase();r.push(m);}let p=e.summary||"";e.body&&(p+=`
3
+
4
+ `+e.body);let a={source:"lore",loreEntryId:t,originProject:l.basename(n),createdBy:o};return v(o,{context:e.title||`Promoted from ${t}`,snippet:p,provenance:a,confidence:e.confidence??.7,concepts:r,tags:e.tags||[]},s,n)}function T(o,t,n){let s=l.join(n,h,o),c=l.join(y,o);for(let e of [s,c]){let r=l.join(e,`${t}${S}`);if(i.existsSync(r))try{let p=i.readFileSync(r,"utf-8"),a=u.load(p);if(a)return a.appliedCount=(a.appliedCount||0)+1,a.updated=new Date().toISOString(),i.writeFileSync(r,u.dump(a,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var y,h,O,S,b,P=b$1(()=>{y=l.join(N.homedir(),".paradigm","notebooks"),h=".paradigm/notebooks",O="nb-",S=".yaml";b=.5;});export{g as a,E as b,b as c,_ as d,$ as e,L as f,v as g,z as h,T as i,P as j};
@@ -16,5 +16,5 @@ ${i.map((w,I)=>`${I+1}. ${w}`).join(`
16
16
  - Modified files: ${r.length>0?r.join(", "):"(not specified)"}
17
17
  - Symbols touched: ${l.length>0?l.join(", "):"(not specified)"}
18
18
  - Open questions: ${d.length>0?d.join(", "):"(none)"}
19
- `;return Mt(),{handled:true,text:JSON.stringify({handoff:f,markdownSummary:b,persisted:g,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let s=n.getStats(),i=n.getCostBreakdown(),a=n.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(s.startTime).toISOString(),durationMinutes:a,lastActivity:new Date(s.lastActivity).toISOString()},model:{name:i.model,id:i.modelId,pricing:{inputPerMillion:`$${i.pricing.input.toFixed(2)}`,outputPerMillion:`$${i.pricing.output.toFixed(2)}`}},interactions:{toolCalls:s.totals.toolCallCount,resourceReads:s.totals.resourceReadCount,totalInteractions:s.totals.toolCallCount+s.totals.resourceReadCount},tokens:{total:s.totals.totalTokens,byCategory:{resources:i.resources.tokens,tools:i.tools.tokens}},cost:{totalUsd:`$${i.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${i.resources.costUsd.toFixed(4)}`,tools:`$${i.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:i.resources.byType,toolsByName:i.tools.byName}},null,2)}}if(t==="paradigm_session_recover"){let{checkpoint:s,pendingHandoffs:i,previousSession:a}=Je(o.rootDir);if(!a&&i.length===0&&!s)return {handled:true,text:JSON.stringify({found:false,message:"No previous session breadcrumbs, checkpoints, or pending handoffs found.",tip:"Breadcrumbs persist to ~/.paradigm/sessions/ and handoffs persist via paradigm_handoff_prepare. Checkpoints persist via paradigm_session_checkpoint."},null,2)};let r={found:true};if(s){let d=Date.now()-s.timestamp,c=Math.round(d/6e4),u=Math.round(d/36e5);r.checkpoint={phase:s.phase,context:s.context,age:u>1?`${u} hours ago`:`${c} minutes ago`,timestamp:new Date(s.timestamp).toISOString(),sessionId:s.sessionId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:s.recentBreadcrumbs?.map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}))};}if(a){let d=Date.now()-a.lastActivity,c=Math.round(d/6e4),u=Math.round(d/36e5),h=a.breadcrumbs.slice(-10).map(f=>({time:new Date(f.timestamp).toISOString(),action:f.action,tool:f.tool,symbol:f.symbol,summary:f.summary}));r.previousSession={sessionId:a.sessionId,startTime:new Date(a.startTime).toISOString(),lastActivity:new Date(a.lastActivity).toISOString(),age:u>1?`${u} hours ago`:`${c} minutes ago`},r.context={symbolsModified:a.symbolsModified,filesExplored:a.filesExplored},r.recentActions=h;}if(i.length>0){r.pendingHandoffs=i.map(d=>({id:d.id,timestamp:d.timestamp,from:d.from,to:d.to,summary:d.summary,nextSteps:d.nextSteps,modifiedFiles:d.modifiedFiles,symbolsTouched:d.symbolsTouched,openQuestions:d.openQuestions}));for(let d of i)try{c(o.rootDir,d.id);}catch{}}let l="Continue where the previous session left off.";if(s)l=`Previous session was in "${s.phase}" phase: ${s.context}`,s.decisions?.length&&(l+=` Key decisions: ${s.decisions.slice(0,2).join("; ")}`);else if(i.length>0){let d=i[i.length-1];l=`Handoff received: "${d.summary}". `,d.nextSteps.length>0&&(l+=`Start with: ${d.nextSteps[0]}`);}else if(a){let d=a.breadcrumbs.slice(-10);if(d.length>0){let c=d[d.length-1];c.symbol&&(l=`Last work involved ${c.symbol}. Consider checking its current state with paradigm_ripple.`);}}return r.suggestion=l,r.agentInstruction="Present a brief summary of the previous session, then ask the user what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking.",n.markRecovered(),{handled:true,text:JSON.stringify(r,null,2)}}if(t==="paradigm_session_checkpoint"){n.setRootDir(o.rootDir);let s=e.phase,i=e.context,a=e.externalId,r=e.plan,l=e.modifiedFiles,d=e.symbolsTouched,c=e.decisions,{checkpoint:u,persisted:p}=n.saveCheckpoint({phase:s,context:i,externalId:a,plan:r,modifiedFiles:l,symbolsTouched:d,decisions:c}),h=p.local||p.global;return {handled:true,text:JSON.stringify({saved:h,persisted:p,checkpoint:{phase:u.phase,context:u.context,sessionId:u.sessionId,...u.externalId?{externalId:u.externalId}:{},timestamp:new Date(u.timestamp).toISOString(),modifiedFiles:u.modifiedFiles?.length||0,symbolsTouched:u.symbolsTouched?.length||0,decisions:u.decisions?.length||0,recentBreadcrumbs:u.recentBreadcrumbs?.length||0},...h?{note:"Checkpoint saved. Recovery data will be auto-surfaced on the first tool call of the next session."}:{warning:"Checkpoint was NOT persisted to disk. Both local and global writes failed. Check MCP server stderr for details."}},null,2)}}return {handled:false,text:""}}function Je(t){let e=j$1();e.setRootDir(t);let o=e.loadCheckpoint(),n=e.loadPreviousSession(),s=[];try{s=b(t);}catch{}return {checkpoint:o,pendingHandoffs:s,previousSession:n}}async function kn(t){let{checkpoint:e,pendingHandoffs:o}=Je(t);if(!e&&o.length===0)return null;let n=[];if(n.push("--- SESSION RECOVERY ---"),e){let s=Date.now()-e.timestamp,i=Math.round(s/6e4),a=Math.round(s/36e5),r=a>1?`${a}h ago`:`${i}m ago`;n.push(`Previous session was in "${e.phase}" phase (${r}): ${e.context}`),e.modifiedFiles?.length&&n.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&n.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&n.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&n.push(`Plan: ${e.plan.slice(0,200)}`);}if(o.length>0){let s=o[o.length-1];n.push(`Pending handoff: "${s.summary}"`),s.nextSteps.length>0&&n.push(`Next steps: ${s.nextSteps.slice(0,3).join(", ")}`);}try{try{let{reapStaleInProgress:l}=await import('./task-settlement-NW4XMJGJ.js');await l(t);}catch{}let{assembleCaptainBoard:s,proposeClaimantFor:i}=await import('./captain-YUP3KVCA.js'),a=await s(t,{proposeClaimants:!0}),r=a.unclaimed.slice(0,5);if(a.summary.open>0||a.summary.inFlight>0||a.summary.runs>0){n.push(""),n.push(`Cid (captain): ${a.summary.open} open, ${a.summary.inFlight} in-flight`+(a.summary.runs>0?`, ${a.summary.runs} active run(s)`:"")+`, ${a.summary.unclaimed} unclaimed`);let{updateTask:l,loadTask:d}=await import('./task-loader-IGQQ6ZFL.js');for(let c of r){let u=c.tags.length>0?` [${c.tags.join(", ")}]`:"",p=c.proposedClaimant;if(!p){let h=await d(t,c.taskId);h&&(p=await i(h,t));}if(p){try{let h=await d(t,c.taskId);h&&!h.claimant&&h.status==="open"&&await l(t,c.taskId,{claimant:p});}catch{}n.push(` [${c.priority}] ${c.taskId}: ${c.blurb}${u} \u2192 proposed ${p.ref}`);}else n.push(` [${c.priority}] ${c.taskId}: ${c.blurb}${u}`);}}}catch{try{let{loadTasks:s}=await import('./task-loader-IGQQ6ZFL.js'),i=await s(t,{status:"open",limit:5});if(i.length>0){n.push(""),n.push("Open tasks:");for(let a of i){let r=a.tags.length>0?` [${a.tags.join(", ")}]`:"";n.push(` [${a.priority}] ${a.id}: ${a.blurb}${r}`);}}}catch{}}try{let{loadLoreEntries:s}=await import('./lore-loader-PXFKMKAN.js'),a=(await s(t,{limit:10})).filter(r=>r.tags?.some(l=>l.startsWith("arc:")));if(a.length>0){let r=new Map;for(let c of a){let u=c.tags?.find(p=>p.startsWith("arc:"))||"";r.set(u,(r.get(u)||0)+1);}let l=e?.symbolsTouched||[];if((l.length>0?a.filter(c=>c.symbols_touched?.some(u=>l.includes(u))):a.slice(0,3)).length>0||r.size>0){n.push(""),n.push("Active lore arcs:");for(let[c,u]of r)n.push(` ${c} (${u} entries)`);}}}catch{}try{let{loadNominations:s}=await import('./nomination-engine-AQHU2KBU.js'),i=s(t,{pending_only:!0}).filter(a=>a.urgency==="critical"||a.urgency==="high");if(i.length>0){n.push(""),n.push("Ambient nominations (urgent):");for(let a of i.slice(0,5))n.push(` [${a.urgency}] ${a.brief}`);i.length>5&&n.push(` ... and ${i.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return n.push(""),n.push("IMPORTANT: Present a brief summary of this recovery data to the user, then ask what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking."),n.push("---"),n.join(`
19
+ `;return Mt(),{handled:true,text:JSON.stringify({handoff:f,markdownSummary:b,persisted:g,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let s=n.getStats(),i=n.getCostBreakdown(),a=n.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(s.startTime).toISOString(),durationMinutes:a,lastActivity:new Date(s.lastActivity).toISOString()},model:{name:i.model,id:i.modelId,pricing:{inputPerMillion:`$${i.pricing.input.toFixed(2)}`,outputPerMillion:`$${i.pricing.output.toFixed(2)}`}},interactions:{toolCalls:s.totals.toolCallCount,resourceReads:s.totals.resourceReadCount,totalInteractions:s.totals.toolCallCount+s.totals.resourceReadCount},tokens:{total:s.totals.totalTokens,byCategory:{resources:i.resources.tokens,tools:i.tools.tokens}},cost:{totalUsd:`$${i.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${i.resources.costUsd.toFixed(4)}`,tools:`$${i.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:i.resources.byType,toolsByName:i.tools.byName}},null,2)}}if(t==="paradigm_session_recover"){let{checkpoint:s,pendingHandoffs:i,previousSession:a}=Je(o.rootDir);if(!a&&i.length===0&&!s)return {handled:true,text:JSON.stringify({found:false,message:"No previous session breadcrumbs, checkpoints, or pending handoffs found.",tip:"Breadcrumbs persist to ~/.paradigm/sessions/ and handoffs persist via paradigm_handoff_prepare. Checkpoints persist via paradigm_session_checkpoint."},null,2)};let r={found:true};if(s){let d=Date.now()-s.timestamp,c=Math.round(d/6e4),u=Math.round(d/36e5);r.checkpoint={phase:s.phase,context:s.context,age:u>1?`${u} hours ago`:`${c} minutes ago`,timestamp:new Date(s.timestamp).toISOString(),sessionId:s.sessionId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:s.recentBreadcrumbs?.map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}))};}if(a){let d=Date.now()-a.lastActivity,c=Math.round(d/6e4),u=Math.round(d/36e5),h=a.breadcrumbs.slice(-10).map(f=>({time:new Date(f.timestamp).toISOString(),action:f.action,tool:f.tool,symbol:f.symbol,summary:f.summary}));r.previousSession={sessionId:a.sessionId,startTime:new Date(a.startTime).toISOString(),lastActivity:new Date(a.lastActivity).toISOString(),age:u>1?`${u} hours ago`:`${c} minutes ago`},r.context={symbolsModified:a.symbolsModified,filesExplored:a.filesExplored},r.recentActions=h;}if(i.length>0){r.pendingHandoffs=i.map(d=>({id:d.id,timestamp:d.timestamp,from:d.from,to:d.to,summary:d.summary,nextSteps:d.nextSteps,modifiedFiles:d.modifiedFiles,symbolsTouched:d.symbolsTouched,openQuestions:d.openQuestions}));for(let d of i)try{c(o.rootDir,d.id);}catch{}}let l="Continue where the previous session left off.";if(s)l=`Previous session was in "${s.phase}" phase: ${s.context}`,s.decisions?.length&&(l+=` Key decisions: ${s.decisions.slice(0,2).join("; ")}`);else if(i.length>0){let d=i[i.length-1];l=`Handoff received: "${d.summary}". `,d.nextSteps.length>0&&(l+=`Start with: ${d.nextSteps[0]}`);}else if(a){let d=a.breadcrumbs.slice(-10);if(d.length>0){let c=d[d.length-1];c.symbol&&(l=`Last work involved ${c.symbol}. Consider checking its current state with paradigm_ripple.`);}}return r.suggestion=l,r.agentInstruction="Present a brief summary of the previous session, then ask the user what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking.",n.markRecovered(),{handled:true,text:JSON.stringify(r,null,2)}}if(t==="paradigm_session_checkpoint"){n.setRootDir(o.rootDir);let s=e.phase,i=e.context,a=e.externalId,r=e.plan,l=e.modifiedFiles,d=e.symbolsTouched,c=e.decisions,{checkpoint:u,persisted:p}=n.saveCheckpoint({phase:s,context:i,externalId:a,plan:r,modifiedFiles:l,symbolsTouched:d,decisions:c}),h=p.local||p.global;return {handled:true,text:JSON.stringify({saved:h,persisted:p,checkpoint:{phase:u.phase,context:u.context,sessionId:u.sessionId,...u.externalId?{externalId:u.externalId}:{},timestamp:new Date(u.timestamp).toISOString(),modifiedFiles:u.modifiedFiles?.length||0,symbolsTouched:u.symbolsTouched?.length||0,decisions:u.decisions?.length||0,recentBreadcrumbs:u.recentBreadcrumbs?.length||0},...h?{note:"Checkpoint saved. Recovery data will be auto-surfaced on the first tool call of the next session."}:{warning:"Checkpoint was NOT persisted to disk. Both local and global writes failed. Check MCP server stderr for details."}},null,2)}}return {handled:false,text:""}}function Je(t){let e=j$1();e.setRootDir(t);let o=e.loadCheckpoint(),n=e.loadPreviousSession(),s=[];try{s=b(t);}catch{}return {checkpoint:o,pendingHandoffs:s,previousSession:n}}async function kn(t){let{checkpoint:e,pendingHandoffs:o}=Je(t);if(!e&&o.length===0)return null;let n=[];if(n.push("--- SESSION RECOVERY ---"),e){let s=Date.now()-e.timestamp,i=Math.round(s/6e4),a=Math.round(s/36e5),r=a>1?`${a}h ago`:`${i}m ago`;n.push(`Previous session was in "${e.phase}" phase (${r}): ${e.context}`),e.modifiedFiles?.length&&n.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&n.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&n.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&n.push(`Plan: ${e.plan.slice(0,200)}`);}if(o.length>0){let s=o[o.length-1];n.push(`Pending handoff: "${s.summary}"`),s.nextSteps.length>0&&n.push(`Next steps: ${s.nextSteps.slice(0,3).join(", ")}`);}try{try{let{reapStaleInProgress:l}=await import('./task-settlement-HINBVZBE.js');await l(t);}catch{}let{assembleCaptainBoard:s,proposeClaimantFor:i}=await import('./captain-3COP6YTD.js'),a=await s(t,{proposeClaimants:!0}),r=a.unclaimed.slice(0,5);if(a.summary.open>0||a.summary.inFlight>0||a.summary.runs>0){n.push(""),n.push(`Cid (captain): ${a.summary.open} open, ${a.summary.inFlight} in-flight`+(a.summary.runs>0?`, ${a.summary.runs} active run(s)`:"")+`, ${a.summary.unclaimed} unclaimed`);let{updateTask:l,loadTask:d}=await import('./task-loader-YZME4RKE.js');for(let c of r){let u=c.tags.length>0?` [${c.tags.join(", ")}]`:"",p=c.proposedClaimant;if(!p){let h=await d(t,c.taskId);h&&(p=await i(h,t));}if(p){try{let h=await d(t,c.taskId);h&&!h.claimant&&h.status==="open"&&await l(t,c.taskId,{claimant:p});}catch{}n.push(` [${c.priority}] ${c.taskId}: ${c.blurb}${u} \u2192 proposed ${p.ref}`);}else n.push(` [${c.priority}] ${c.taskId}: ${c.blurb}${u}`);}}}catch{try{let{loadTasks:s}=await import('./task-loader-YZME4RKE.js'),i=await s(t,{status:"open",limit:5});if(i.length>0){n.push(""),n.push("Open tasks:");for(let a of i){let r=a.tags.length>0?` [${a.tags.join(", ")}]`:"";n.push(` [${a.priority}] ${a.id}: ${a.blurb}${r}`);}}}catch{}}try{let{loadLoreEntries:s}=await import('./lore-loader-PXFKMKAN.js'),a=(await s(t,{limit:10})).filter(r=>r.tags?.some(l=>l.startsWith("arc:")));if(a.length>0){let r=new Map;for(let c of a){let u=c.tags?.find(p=>p.startsWith("arc:"))||"";r.set(u,(r.get(u)||0)+1);}let l=e?.symbolsTouched||[];if((l.length>0?a.filter(c=>c.symbols_touched?.some(u=>l.includes(u))):a.slice(0,3)).length>0||r.size>0){n.push(""),n.push("Active lore arcs:");for(let[c,u]of r)n.push(` ${c} (${u} entries)`);}}}catch{}try{let{loadNominations:s}=await import('./nomination-engine-YRHZZZUN.js'),i=s(t,{pending_only:!0}).filter(a=>a.urgency==="critical"||a.urgency==="high");if(i.length>0){n.push(""),n.push("Ambient nominations (urgent):");for(let a of i.slice(0,5))n.push(` [${a.urgency}] ${a.brief}`);i.length>5&&n.push(` ... and ${i.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return n.push(""),n.push("IMPORTANT: Present a brief summary of this recovery data to the user, then ask what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking."),n.push("---"),n.join(`
20
20
  `)}export{vt as A,Ue as B,kt as C,$t as D,jt as E,le as F,Et as G,cn as H,dn as I,ln as J,un as K,Ot as L,fn as M,pn as N,gn as O,Sn as P,bn as Q,wn as R,vn as S,kn as T,Lt as a,z as b,W as c,Wt as d,ye as e,Ut as f,Ht as g,qt as h,Gt as i,te as j,Jt as k,Bt as l,Kt as m,Vt as n,O as o,st as p,oe as q,B as r,Y as s,yt as t,ht as u,Ne as v,gt as w,ae as x,St as y,bt as z};