@a-company/paradigm 6.6.6 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/dist/{accept-orchestration-JHDCVHB2.js → accept-orchestration-WMGFGYDK.js} +1 -1
  2. package/dist/{agent-loader-VGBPL3TH.js → agent-loader-Z753DQWH.js} +1 -1
  3. package/dist/{agents-suggest-IKY6VD2R.js → agents-suggest-WZEGQT5E.js} +1 -1
  4. package/dist/{ambient-FNNFB4AP.js → ambient-HAXPDIWK.js} +1 -1
  5. package/dist/ambient-OW5M5LVN.js +2 -0
  6. package/dist/ambient-QB7V4TBR.js +6 -0
  7. package/dist/calibrate-PHVP7RPH.js +4 -0
  8. package/dist/captain-3COP6YTD.js +2 -0
  9. package/dist/chunk-33ERV2MW.js +18 -0
  10. package/dist/chunk-4CGPLLWQ.js +30 -0
  11. package/dist/chunk-6HVOZANP.js +4 -0
  12. package/dist/chunk-ACJWUOMA.js +3 -0
  13. package/dist/chunk-B5KLSBOZ.js +2 -0
  14. package/dist/chunk-CHSU6LTR.js +2 -0
  15. package/dist/chunk-DLMDHS2X.js +10 -0
  16. package/dist/chunk-ECO3LHCE.js +2 -0
  17. package/dist/chunk-EG22HDXI.js +33 -0
  18. package/dist/{chunk-5RFISGUW.js → chunk-G6DK3ND3.js} +250 -25
  19. package/dist/{chunk-GD4F2HC6.js → chunk-H55W26AR.js} +1 -1
  20. package/dist/chunk-HSY75GRR.js +6 -0
  21. package/dist/chunk-KAUGQMXU.js +4 -0
  22. package/dist/chunk-KP5VOYAH.js +20 -0
  23. package/dist/chunk-OIYJUU6T.js +25 -0
  24. package/dist/chunk-RDWWSQGH.js +142 -0
  25. package/dist/chunk-RVXQNS6K.js +30 -0
  26. package/dist/chunk-VPNJL4LS.js +93 -0
  27. package/dist/{chunk-XKNJSPB5.js → chunk-W4BW7GXA.js} +1 -1
  28. package/dist/chunk-XPPFILCM.js +2 -0
  29. package/dist/chunk-YCDOA5IQ.js +18 -0
  30. package/dist/chunk-YQK3XU63.js +504 -0
  31. package/dist/{chunk-TQOT2LBO.js → chunk-YXLGVOZO.js} +1 -1
  32. package/dist/chunk-ZSWXLFN7.js +12 -0
  33. package/dist/{compliance-J3VOV445.js → compliance-4P3EE5OA.js} +1 -1
  34. package/dist/{diff-ANKTFDRA.js → diff-VBVIUNL5.js} +1 -1
  35. package/dist/{docs-TSAAS4W3.js → docs-NTP6UENF.js} +1 -1
  36. package/dist/doctor-CBZYYQQH.js +2 -0
  37. package/dist/{hooks-45WDP6QS.js → hooks-AXBWYJ5V.js} +1 -1
  38. package/dist/index.js +6 -6
  39. package/dist/journal-loader-CNNA4EAU.js +2 -0
  40. package/dist/lore-loader-HAZ5FRLP.js +2 -0
  41. package/dist/mcp.js +3 -3
  42. package/dist/{migrate-R64OQGSM.js → migrate-5M4KUQ2L.js} +1 -1
  43. package/dist/nomination-engine-ORHH4L2W.js +2 -0
  44. package/dist/{nomination-engine-NCLTGMAK.js → nomination-engine-YRHZZZUN.js} +1 -1
  45. package/dist/notebook-loader-TZVIMNDJ.js +2 -0
  46. package/dist/orchestrate-MLUGQOEJ.js +8 -0
  47. package/dist/orchestration-O2OVPTIZ.js +2 -0
  48. package/dist/{platform-server-ANOALDPL.js → platform-server-Y6TLEXR2.js} +1 -1
  49. package/dist/propose-block-ZEMEWJQF.js +2 -0
  50. package/dist/{providers-TBPOE4DI.js → providers-5EHD45C6.js} +1 -1
  51. package/dist/reindex-ZLDQBFUR.js +2 -0
  52. package/dist/{serve-3FMUWW5K.js → serve-XZ6GBUS3.js} +1 -1
  53. package/dist/session-tracker-BZ7FU4AT.js +2 -0
  54. package/dist/session-work-log-FF7CKMWP.js +2 -0
  55. package/dist/session-work-log-T2IE4Y4T.js +2 -0
  56. package/dist/{shift-TNA2E5O7.js → shift-PM4GI736.js} +2 -2
  57. package/dist/solo-OWR3MX74.js +3 -0
  58. package/dist/{spawn-KKDDR6UR.js → spawn-PHA2SVQ3.js} +1 -1
  59. package/dist/{symphony-G6IENE4K.js → symphony-CFAYJGLF.js} +1 -1
  60. package/dist/{symphony-7INZR43F.js → symphony-L56O5ZG3.js} +3 -3
  61. package/dist/{symphony-relay-2RHG25Z4.js → symphony-relay-Y2UR3YNR.js} +1 -1
  62. package/dist/task-loader-H7HQAYGL.js +2 -0
  63. package/dist/task-loader-YZME4RKE.js +2 -0
  64. package/dist/task-settlement-HINBVZBE.js +3 -0
  65. package/dist/task-settlement-XC6E6JNT.js +3 -0
  66. package/dist/team-25LK6CWM.js +2 -0
  67. package/dist/team-funnel-RAJ6EDG3.js +2 -0
  68. package/dist/tools-GAU5WOEI.js +2 -0
  69. package/dist/university-content/notes/N-para-801-cid-becomes-real.md +60 -0
  70. package/dist/university-content/notes/N-para-801-falsifiable-self-improvement.md +66 -0
  71. package/dist/university-content/notes/N-para-801-honest-routing-and-the-method.md +57 -0
  72. package/dist/university-content/notes/N-para-801-orchestration-emits-dag.md +60 -0
  73. package/dist/university-content/notes/N-para-801-settlement-closes-the-loop.md +64 -0
  74. package/dist/university-content/notes/N-para-801-the-task-dag.md +93 -0
  75. package/dist/university-content/paths/LP-para-801.yaml +43 -0
  76. package/dist/university-content/quizzes/Q-para-801-cid-becomes-real.yaml +54 -0
  77. package/dist/university-content/quizzes/Q-para-801-falsifiable-self-improvement.yaml +54 -0
  78. package/dist/university-content/quizzes/Q-para-801-honest-routing-and-the-method.yaml +54 -0
  79. package/dist/university-content/quizzes/Q-para-801-orchestration-emits-dag.yaml +54 -0
  80. package/dist/university-content/quizzes/Q-para-801-settlement-closes-the-loop.yaml +54 -0
  81. package/dist/university-content/quizzes/Q-para-801-the-task-dag.yaml +54 -0
  82. package/dist/university-ui/assets/{index-DrtbBC21.js → index-AbTjHBCf.js} +2 -2
  83. package/dist/university-ui/assets/{index-DrtbBC21.js.map → index-AbTjHBCf.js.map} +1 -1
  84. package/dist/university-ui/index.html +1 -1
  85. package/dist/work-log-loader-CRVTOMVB.js +2 -0
  86. package/package.json +1 -1
  87. package/dist/ambient-AI42BOM5.js +0 -35
  88. package/dist/chunk-3OXR6F65.js +0 -666
  89. package/dist/chunk-4N56FRNE.js +0 -29
  90. package/dist/chunk-6QXBXZF6.js +0 -3
  91. package/dist/chunk-AMLD7IYC.js +0 -10
  92. package/dist/chunk-DVZWCXB6.js +0 -2
  93. package/dist/chunk-F6E3HW45.js +0 -14
  94. package/dist/chunk-K7X3Z3GL.js +0 -4
  95. package/dist/chunk-LAYBUKMB.js +0 -14
  96. package/dist/chunk-MU5YWTNE.js +0 -24
  97. package/dist/chunk-PMKZMCTS.js +0 -111
  98. package/dist/chunk-QGZRM6ZB.js +0 -2
  99. package/dist/chunk-XQLO5URP.js +0 -11
  100. package/dist/doctor-L5XZENCF.js +0 -2
  101. package/dist/journal-loader-GLH7XFTK.js +0 -2
  102. package/dist/lore-loader-D2ISOASW.js +0 -2
  103. package/dist/notebook-loader-3J2OFMS3.js +0 -2
  104. package/dist/orchestrate-UG5QXNAU.js +0 -8
  105. package/dist/reindex-PTIQ2UGY.js +0 -2
  106. package/dist/session-tracker-HHNY6J4I.js +0 -2
  107. package/dist/session-work-log-MEJ33TYD.js +0 -2
  108. package/dist/session-work-log-ZVVJGO7X.js +0 -2
  109. package/dist/task-loader-NZFDTUQ5.js +0 -2
  110. package/dist/team-PEGP6F7S.js +0 -2
  111. package/dist/tools-PUSDXUYE.js +0 -2
  112. /package/dist/{chunk-HXGYVS2N.js → chunk-ECLUYHAR.js} +0 -0
  113. /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-MU5YWTNE.js';import'./chunk-TYWB5IQJ.js';import'./chunk-AMLD7IYC.js';import'./chunk-FYDRENK7.js';import'./chunk-HXGYVS2N.js';import'./chunk-TQOT2LBO.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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a}from'./chunk-TYWB5IQJ.js';import {e}from'./chunk-TQOT2LBO.js';import'./chunk-5TAVYPOV.js';import o from'chalk';async function y(s,g){let r=process.cwd(),t=e(r);t||(g.json?console.log(JSON.stringify({error:"No agents.yaml found"})):console.log(o.red("\nNo agents.yaml found. Run `paradigm team init` first.\n")),process.exit(1));let e$1=a(s,t.agents);if(g.json){console.log(JSON.stringify({task:s,suggestions:e$1},null,2));return}if(console.log(o.cyan(`
2
+ import {a}from'./chunk-TYWB5IQJ.js';import {e}from'./chunk-YXLGVOZO.js';import'./chunk-5TAVYPOV.js';import o from'chalk';async function y(s,g){let r=process.cwd(),t=e(r);t||(g.json?console.log(JSON.stringify({error:"No agents.yaml found"})):console.log(o.red("\nNo agents.yaml found. Run `paradigm team init` first.\n")),process.exit(1));let e$1=a(s,t.agents);if(g.json){console.log(JSON.stringify({task:s,suggestions:e$1},null,2));return}if(console.log(o.cyan(`
3
3
  Suggested agents for this task:
4
4
  `)),console.log(o.gray(` Task: "${s}"
5
5
  `)),e$1.length===0){console.log(o.yellow(` No agents matched. Consider using architect \u2192 builder flow.
@@ -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-ZVVJGO7X.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-AI42BOM5.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};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
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,18 @@
1
+ #!/usr/bin/env node
2
+ import {c,b}from'./chunk-5TAVYPOV.js';import*as e from'fs';import*as o from'path';var L={};c(L,{appendSessionWorkEntry:()=>N,appendVerdictEntry:()=>O,clearActivityMetrics:()=>J,clearSessionWorkLog:()=>C,countNotebookReferences:()=>_,getAgentEntries:()=>h,getAgentVerdicts:()=>j,getContributingAgents:()=>M,getNotebookReferences:()=>v,getSessionActivitySummary:()=>W,markIterationRevisionsConsumed:()=>A,markVerdictsConsumed:()=>P,readPendingIterationRevisions:()=>F,readPendingVerdicts:()=>R,readSessionWorkLog:()=>g,recordActivityMetric:()=>w,recordNotebookReference:()=>D});function N(i,n){try{let t=o.join(i,y),r=o.dirname(t);if(e.existsSync(r)||e.mkdirSync(r,{recursive:!0}),e.existsSync(t)&&e.readFileSync(t,"utf8").trim().split(`
3
+ `).filter(c=>c.trim()).length>=I)return;let f=JSON.stringify(n)+`
4
+ `;e.appendFileSync(t,f,"utf8"),n.type==="user-verdict"&&n.agent&&n.symbols?.length&&import('./agent-loader-W3RQJVW7.js').then(({loadAgentProfile:a,saveAgentProfile:s})=>{try{let c=a(i,n.agent);if(c?.expertise){let l=n.verdict==="accepted"?.03:n.verdict==="dismissed"?-.02:n.verdict==="revised"?-.01:0;if(l!==0){for(let b of n.symbols){let u=c.expertise.find(k=>k.symbol===b);u&&(u.confidence=Math.max(0,Math.min(1,u.confidence+l)),u.sessions=(u.sessions||0)+1,u.lastTouch=new Date().toISOString());}s(n.agent,c,"global");}}}catch{}}).catch(()=>{});}catch{}}function g(i){try{let n=o.join(i,y);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
5
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null):[]}catch{return []}}function C(i){try{let n=o.join(i,y);e.existsSync(n)&&e.writeFileSync(n,"","utf8");}catch{}}function O(i,n){try{let t=o.join(i,p),r=o.dirname(t);e.existsSync(r)||e.mkdirSync(r,{recursive:!0}),e.appendFileSync(t,JSON.stringify(n)+`
6
+ `,"utf8");}catch{}}function R(i){try{let n=o.join(i,p);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
7
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&!t.consumed):[]}catch{return []}}function P(i,n){try{let t=o.join(i,p);if(!e.existsSync(t))return;let r=new Set(n),a=e.readFileSync(t,"utf8").trim().split(`
8
+ `).filter(s=>s.trim()).map(s=>{try{let c=JSON.parse(s);return c.nominationId&&r.has(c.nominationId)?JSON.stringify({...c,consumed:!0}):s}catch{return s}});e.writeFileSync(t,a.join(`
9
+ `)+`
10
+ `,"utf8");}catch{}}function F(i){try{let n=o.join(i,m);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
11
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="iteration-revision"&&!t.consumed):[]}catch{return []}}function A(i,n){try{let t=o.join(i,m);if(!e.existsSync(t))return;let r=new Set(n),a=e.readFileSync(t,"utf8").trim().split(`
12
+ `).filter(s=>s.trim()).map(s=>{try{let c=JSON.parse(s);return c.id&&r.has(c.id)?JSON.stringify({...c,consumed:!0}):s}catch{return s}});e.writeFileSync(t,a.join(`
13
+ `)+`
14
+ `,"utf8");}catch{}}function M(i){let n=g(i),t=new Set;for(let r of n)r.agent&&t.add(r.agent);return Array.from(t)}function h(i,n){return g(i).filter(t=>t.agent===n)}function j(i,n){let t=h(i,n),r=t.filter(s=>s.type==="agent-contribution"),f=t.filter(s=>s.type==="user-verdict"),a=[];for(let s of r)a.push({contribution:s});for(let s of f){let c=a.find(l=>!l.verdict&&l.contribution);c?c.verdict=s:a.push({verdict:s});}return a}function w(i,n){try{let t=o.join(i,d),r=o.dirname(t);e.existsSync(r)||e.mkdirSync(r,{recursive:!0});let f={timestamp:new Date().toISOString(),type:"activity",...n},a=JSON.stringify(f)+`
15
+ `;e.appendFileSync(t,a,"utf8");}catch{}}function B(i){try{let n=o.join(i,d);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
16
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="activity"):[]}catch{return []}}function W(i){let n=B(i),t={toolCallCount:0,responsePayloadBytes:0,sessionDurationMs:0,agentBreakdown:{}};for(let r of n)if(r.toolCallCount!=null&&(t.toolCallCount+=r.toolCallCount),r.responsePayloadBytes!=null&&(t.responsePayloadBytes+=r.responsePayloadBytes),r.sessionDurationMs!=null&&(t.sessionDurationMs=Math.max(t.sessionDurationMs,r.sessionDurationMs)),r.agentId){t.agentBreakdown[r.agentId]||(t.agentBreakdown[r.agentId]={toolCalls:0,payloadBytes:0});let f=t.agentBreakdown[r.agentId];r.toolCallCount!=null&&(f.toolCalls+=r.toolCallCount),r.responsePayloadBytes!=null&&(f.payloadBytes+=r.responsePayloadBytes);}return t}function J(i){try{let n=o.join(i,d);e.existsSync(n)&&e.writeFileSync(n,"","utf8");}catch{}}function D(i,n,t,r){try{if(t.length===0)return;let f=o.join(i,S),a=o.dirname(f);e.existsSync(a)||e.mkdirSync(a,{recursive:!0});let s={timestamp:new Date().toISOString(),type:"notebook-reference",agentId:n,notebookEntryIds:t,...r?{orchestrationId:r}:{}},c=JSON.stringify(s)+`
17
+ `;e.appendFileSync(f,c,"utf8");}catch{}}function v(i){try{let n=o.join(i,S);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
18
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="notebook-reference"):[]}catch{return []}}function _(i){return v(i).length}var y,d,p,m,I,S,T=b(()=>{y=".paradigm/events/session-log.jsonl",d=".paradigm/events/session-metrics.jsonl",p=".paradigm/events/verdicts.jsonl",m=".paradigm/events/iteration-revisions.jsonl",I=200,S=".paradigm/events/notebook-refs.jsonl";});export{N as a,g as b,C as c,O as d,R as e,P as f,F as g,A as h,M as i,h as j,j as k,w as l,W as m,J as n,D as o,v as p,_ as q,L as r,T as s};
@@ -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};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import*as r from'fs';import*as l from'path';var f=".paradigm/events/team-funnel.jsonl",d=["trivial","hotfix","user-directed","exploratory"];function y(a,s){try{let n=l.join(a,f),o=l.dirname(n);r.existsSync(o)||r.mkdirSync(o,{recursive:!0});let e={timestamp:new Date().toISOString(),...s};r.appendFileSync(n,JSON.stringify(e)+`
3
+ `,"utf8");}catch{}}function p(a,s){try{let n=l.join(a,f);if(!r.existsSync(n))return [];let o=s!==void 0?Date.now()-s*24*60*60*1e3:void 0;return r.readFileSync(n,"utf8").trim().split(`
4
+ `).filter(e=>e.trim()).map(e=>{try{return JSON.parse(e)}catch{return null}}).filter(e=>{if(e===null||!e.type)return !1;if(o===void 0)return !0;let i=Date.parse(e.timestamp);return !Number.isNaN(i)&&i>=o})}catch{return []}}function g(a,s=30){let n=p(a,s),o=n.filter(t=>t.type==="eligible").length,e=n.filter(t=>t.type==="orchestrated").length,i=n.filter(t=>t.type==="solo-declared").length,c=n.filter(t=>t.type==="bypass").length,u=e+i+c,m={};for(let t of n)t.type==="solo-declared"&&t.reason&&(m[t.reason]=(m[t.reason]||0)+1);return {windowDays:s,eligible:o,orchestrated:e,soloDeclared:i,bypasses:c,invocationRate:u>0?e/u:null,legibleRate:u>0?(e+i)/u:null,soloByReason:m}}export{d as a,y as b,p as c,g as d};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import {s,r as r$1}from'./chunk-33ERV2MW.js';import {b as b$1,a as a$1}from'./chunk-EK4ZRIFJ.js';import {d}from'./chunk-5TAVYPOV.js';import*as r from'fs';import*as a from'path';import*as x from'os';import*as T from'crypto';import*as h from'js-yaml';function w(){let n=a.join(x.homedir(),".paradigm");return r.existsSync(n)||r.mkdirSync(n,{recursive:true}),n}function M(n){let s=a.resolve(n);return T.createHash("sha256").update(s).digest("hex").slice(0,12)}function f(n){let s=M(n),e=a.join(w(),"sessions",s);r.existsSync(e)||r.mkdirSync(e,{recursive:true});let t=a.join(e,"pending-handoffs");return r.existsSync(t)||r.mkdirSync(t,{recursive:true}),e}function S(n){let s=f(n),e=a.join(s,"_project-meta.json"),o={name:a.basename(a.resolve(n)),path:a.resolve(n),lastSeen:new Date().toISOString()};r.writeFileSync(e,JSON.stringify(o,null,2));}function E(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s.id}.json`);r.writeFileSync(t,JSON.stringify(s,null,2));}function O(n){let s=f(n),e=a.join(s,"pending-handoffs");if(!r.existsSync(e))return [];let t=[];try{let o=r.readdirSync(e);for(let l of o)if(l.endsWith(".json"))try{let u=r.readFileSync(a.join(e,l),"utf8"),m=JSON.parse(u);m.status==="pending"&&t.push(m);}catch{}}catch{}return t.sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime()),t}function W(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s}.json`);if(r.existsSync(t))try{let o=r.readFileSync(t,"utf8"),l=JSON.parse(o);l.status="delivered",r.writeFileSync(t,JSON.stringify(l,null,2));}catch{}}function y(){let n=a.join(w(),"wisdom");return r.existsSync(n)||r.mkdirSync(n,{recursive:true}),n}function H(){let n=a.join(y(),"antipatterns.yaml");if(!r.existsSync(n))return [];try{let s=r.readFileSync(n,"utf8");return h.load(s)?.antipatterns||[]}catch{return []}}function L(){let n=a.join(y(),"decisions");if(!r.existsSync(n))return [];let s=[];try{let e=r.readdirSync(n);for(let t of e)if(!(!t.endsWith(".yaml")&&!t.endsWith(".yml")))try{let o=r.readFileSync(a.join(n,t),"utf8"),l=h.load(o);s.push(l);}catch{}}catch{}return s.sort((e,t)=>e.id.localeCompare(t.id)),s}function _(){let n=a.join(y(),"preferences.yaml");if(!r.existsSync(n))return null;try{let s=r.readFileSync(n,"utf8");return h.load(s)}catch{return null}}function J(n){let s=a.join(y(),"antipatterns.yaml"),e={version:"1.0",antipatterns:[]};if(r.existsSync(s))try{let t=r.readFileSync(s,"utf8"),o=h.load(t);o&&typeof o=="object"&&(e={version:o.version||"1.0",antipatterns:Array.isArray(o.antipatterns)?o.antipatterns:[]});}catch{}e.antipatterns.push({...n,added:new Date().toISOString()}),r.writeFileSync(s,h.dump(e,{lineWidth:-1}));}function U(n){let s=a.join(y(),"decisions");r.existsSync(s)||r.mkdirSync(s,{recursive:true});let e=n.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),t=`${n.id}-${e}.yaml`,o=a.join(s,t);r.writeFileSync(o,h.dump(n,{lineWidth:-1}));}b$1();var k={"claude-opus-4":{input:15,output:75,name:"Claude Opus 4"},"claude-sonnet-4":{input:3,output:15,name:"Claude Sonnet 4"},"claude-haiku-3.5":{input:.8,output:4,name:"Claude Haiku 3.5"}},j=50,P=".paradigm/session-breadcrumbs.json",I=".paradigm/session-checkpoint.json",A=10080*60*1e3,C=class{session;rootDir=null;_recovered=false;lastLoreEntryId=null;constructor(){this.session=this.createNewSession();}setRootDir(s$1){this.rootDir=s$1;try{let{clearSessionWorkLog:e}=(s(),d(r$1));e(s$1);}catch{}}createNewSession(){return {sessionId:`s${Date.now().toString(36)}`,startTime:Date.now(),lastActivity:Date.now(),model:"claude-sonnet-4",resourceReads:[],toolCalls:[],breadcrumbs:[],totals:{resourceReadCount:0,toolCallCount:0,totalBytes:0,totalTokens:0,estimatedCostUsd:0}}}addBreadcrumb(s,e,t={}){this.session.breadcrumbs.push({timestamp:Date.now(),action:s,tool:t.tool,symbol:t.symbol,summary:e}),this.session.breadcrumbs.length>j&&(this.session.breadcrumbs=this.session.breadcrumbs.slice(-j)),this.persistBreadcrumbs();}getBreadcrumbs(s=20){return this.session.breadcrumbs.slice(-s)}persistBreadcrumbs(){if(!this.rootDir)return;let s={sessionId:this.session.sessionId,startTime:this.session.startTime,lastActivity:this.session.lastActivity,breadcrumbs:this.session.breadcrumbs,symbolsModified:this.extractSymbolsFromBreadcrumbs(),filesExplored:this.extractFilesFromBreadcrumbs()},e;try{e=JSON.stringify(s,null,2);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: JSON.stringify failed",{error:t.message});return}try{let t=a.join(this.rootDir,P),o=a.dirname(t);r.existsSync(o)||r.mkdirSync(o,{recursive:!0}),r.writeFileSync(t,e);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: local write failed",{error:t.message});}try{let t=f(this.rootDir);r.writeFileSync(a.join(t,"breadcrumbs.json"),e),S(this.rootDir);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: global write failed",{error:t.message});}}loadPreviousSession(){if(!this.rootDir)return null;try{let s=f(this.rootDir),e=a.join(s,"breadcrumbs.json");if(r.existsSync(e)){let t=r.readFileSync(e,"utf8");return JSON.parse(t)}}catch{}try{let s=a.join(this.rootDir,P);if(!r.existsSync(s))return null;let e=r.readFileSync(s,"utf8");return JSON.parse(e)}catch{return null}}saveCheckpoint(s){let e={phase:s.phase,context:s.context,timestamp:Date.now(),sessionId:this.session.sessionId,externalId:s.externalId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:this.session.breadcrumbs.slice(-10)},t=this.persistCheckpoint(e);return {checkpoint:e,persisted:t}}loadCheckpoint(){if(!this.rootDir)return null;let s=null;try{let e=f(this.rootDir),t=a.join(e,"checkpoint.json");if(r.existsSync(t)){let o=r.readFileSync(t,"utf8");s=JSON.parse(o);}}catch{}if(!s)try{let e=a.join(this.rootDir,I);if(r.existsSync(e)){let t=r.readFileSync(e,"utf8");s=JSON.parse(t);}}catch{}if(s&&Date.now()-s.timestamp>A)return null;if(s)for(let e of ["modifiedFiles","symbolsTouched","decisions"]){let t=s[e];if(typeof t=="string")try{s[e]=JSON.parse(t);}catch{s[e]=[];}}return s}persistCheckpoint(s){let e={local:false,global:false};if(!this.rootDir)return a$1.component("#session-tracker").warn("persistCheckpoint: rootDir not set, skipping write"),e;let t;try{t=JSON.stringify(s,null,2);}catch(o){return a$1.component("#session-tracker").error("persistCheckpoint: JSON.stringify failed",{error:o.message}),e}try{let o=a.join(this.rootDir,I),l=a.dirname(o);r.existsSync(l)||r.mkdirSync(l,{recursive:!0}),r.writeFileSync(o,t),e.local=!0;}catch(o){a$1.component("#session-tracker").error("persistCheckpoint: local write failed",{error:o.message});}try{let o=f(this.rootDir);r.writeFileSync(a.join(o,"checkpoint.json"),t),S(this.rootDir),e.global=!0;}catch(o){a$1.component("#session-tracker").error("persistCheckpoint: global write failed",{error:o.message});}return e}setLastLoreEntryId(s){this.lastLoreEntryId=s;}getLastLoreEntryId(){return this.lastLoreEntryId}hasRecoveredThisSession(){return this._recovered}markRecovered(){this._recovered=true;}extractSymbolsFromBreadcrumbs(){let s=new Set;for(let e of this.session.breadcrumbs)e.symbol&&s.add(e.symbol);return Array.from(s)}extractFilesFromBreadcrumbs(){let s=new Set;for(let e of this.session.breadcrumbs){let t=e.summary.match(/\b[\w./]+\.(ts|js|tsx|jsx|py|go|rs|yaml|json|md)\b/g);if(t)for(let o of t)s.add(o);}return Array.from(s)}estimateTokens(s){let e=typeof s=="number"?s:s.length;return Math.ceil(e/3.5)}calculateCost(s,e=true){let t=k[this.session.model],o=e?t.output:t.input;return s/1e6*o}setModel(s){this.session.model=s,this.recalculateTotals();}getModel(){return this.session.model}trackResourceRead(s,e){let t=this.extractResourceType(s),o=this.estimateTokens(e);this.session.resourceReads.push({timestamp:Date.now(),resourceType:t,uri:s,bytes:e,tokens:o}),this.session.lastActivity=Date.now(),this.updateTotals(e,o);}trackToolCall(s,e){let t=this.estimateTokens(e);this.session.toolCalls.push({timestamp:Date.now(),toolName:s,responseBytes:e,responseTokens:t}),this.session.lastActivity=Date.now(),this.updateTotals(e,t);}updateTotals(s,e){this.session.totals.resourceReadCount=this.session.resourceReads.length,this.session.totals.toolCallCount=this.session.toolCalls.length,this.session.totals.totalBytes+=s,this.session.totals.totalTokens+=e,this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}recalculateTotals(){this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}extractResourceType(s){return s.replace("paradigm://","").split("/")[0]||"unknown"}getStats(){return {...this.session}}getCostBreakdown(){let s={},e=0,t=0;for(let i of this.session.resourceReads)s[i.resourceType]||(s[i.resourceType]={count:0,bytes:0,tokens:0}),s[i.resourceType].count++,s[i.resourceType].bytes+=i.bytes,s[i.resourceType].tokens+=i.tokens,e+=i.bytes,t+=i.tokens;let o={},l=0,u=0;for(let i of this.session.toolCalls)o[i.toolName]||(o[i.toolName]={count:0,bytes:0,tokens:0}),o[i.toolName].count++,o[i.toolName].bytes+=i.responseBytes,o[i.toolName].tokens+=i.responseTokens,l+=i.responseBytes,u+=i.responseTokens;let m=t+u,g=this.calculateCost(m);return {model:k[this.session.model].name,modelId:this.session.model,pricing:k[this.session.model],resources:{count:this.session.resourceReads.length,bytes:e,tokens:t,costUsd:this.calculateCost(t),byType:s},tools:{count:this.session.toolCalls.length,bytes:l,tokens:u,costUsd:this.calculateCost(u),byName:o},total:{tokens:m,costUsd:g}}}getHandoffRecommendation(s=2e5,e){let t=this.session.totals.totalTokens,o=t*4,l=e||t+o,u=Math.round(l/s*100),m,g;u>=85?(m="handoff-urgent",g="Context is nearly full. Initiate handoff immediately to preserve session continuity."):u>=70?(m="handoff-recommended",g="Context usage is high. Consider initiating handoff soon to ensure smooth transition."):u>=50?(m="consider-handoff",g="Context usage is moderate. Plan a good stopping point for potential handoff."):(m="continue",g="Context usage is healthy. Continue working.");let i=[],v=Math.round((Date.now()-this.session.startTime)/6e4),D=this.session.toolCalls.length+this.session.resourceReads.length;return D>50&&i.push(`High number of MCP interactions (${D})`),v>30&&i.push(`Session duration >30 min (${v} min)`),this.session.totals.totalBytes>5e5&&i.push(`Large data volume (${Math.round(this.session.totals.totalBytes/1024)}KB)`),{recommendation:m,message:g,usagePercent:u,signals:i}}getDurationMinutes(){return Math.round((Date.now()-this.session.startTime)/6e4)}reset(){this.session=this.createNewSession(),this._recovered=false,this.lastLoreEntryId=null;}},b=null;function X(){return b||(b=new C),b}function q(){b&&b.reset();}
3
+ export{E as a,O as b,W as c,H as d,L as e,_ as f,J as g,U as h,k as i,X as j,q as k};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import*as a from'fs/promises';import*as n from'path';import*as m from'js-yaml';var u=n.join(".paradigm","remediations");function b(){return "rmd-"+Date.now().toString(36)}function k(){return [{name:"paradigm_propose_block",description:"Author a soft-block (remediation) that the Stop hook will honor until resolved. Use when your archetype detects a condition the user should resolve before continuing (e.g., coverage drop, missing aspect, broken anchor). User can override via `paradigm override <id>` or PARADIGM_OVERRIDE env var. v6.1: only severity=guard hard-blocks; advise/auto-author are informational. ~150 tokens.",inputSchema:{type:"object",properties:{claimant:{type:"string",description:'Archetype id authoring this block (e.g., "compliance", "security"). REQUIRED \u2014 do not infer.'},severity:{type:"string",enum:["advise","auto-author","guard"],description:"Block intent for this event. v6.1: only `guard` hard-blocks; `advise`/`auto-author` are informational."},reason:{type:"string",description:"Free-text explanation surfaced to the user verbatim. Be specific (component name, file path)."},unblock_hint:{type:"string",description:"Plain-string remediation hint (v6.1; JSONLogic predicates ship v6.2). Tell the user how to resolve."},expires_at:{type:"string",description:"OPTIONAL ISO 8601 UTC timestamp. After this, Check 14 silently skips the remediation. Use for time-bounded conditions."},target:{type:"object",description:"OPTIONAL context: {file, symbol, line}.",properties:{file:{type:"string"},symbol:{type:"string"},line:{type:"number"}}}},required:["claimant","severity","reason","unblock_hint"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function x(g,e,h){if(g!=="paradigm_propose_block")return {handled:false,text:""};let s=e.claimant,r=e.severity,d=e.reason,c=e.unblock_hint,o=e.expires_at,t=e.target;if(!s||!r||!d||!c)return {handled:true,text:JSON.stringify({error:"Missing required field. Required: claimant, severity, reason, unblock_hint."},null,2)};let i=b(),f=new Date().toISOString(),l={id:i,claimant:s,severity:r,reason:d,unblock_hint:c,created:f};o&&(l.expires_at=o),t&&(t.file||t.symbol||t.line!=null)&&(l.target=t);let p=n.join(h.rootDir,u);await a.mkdir(p,{recursive:true});let y=n.join(p,`${i}.yaml`),v=m.dump(l,{lineWidth:100,sortKeys:false});return await a.writeFile(y,v,"utf8"),{handled:true,text:JSON.stringify({id:i,path:n.join(u,`${i}.yaml`),claimant:s,severity:r,...o?{expires_at:o}:{},note:`Stop hook will ${r==="guard"?"block":"note"} on next run. User can clear with: paradigm override ${i}`},null,2)}}export{k as a,x as b};
@@ -0,0 +1,2 @@
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-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,10 @@
1
+ #!/usr/bin/env node
2
+ import {a as a$1}from'./chunk-FYDRENK7.js';import {f,a}from'./chunk-ECLUYHAR.js';import {e}from'./chunk-YXLGVOZO.js';import {b,d,c}from'./chunk-EKZDFEJW.js';import*as h from'fs';import*as P from'path';import*as M from'js-yaml';import {glob}from'glob';import {EventEmitter}from'events';var W=/[#$^!~][a-zA-Z0-9_-]+/g;function G(a){let e=a.match(W)||[];return [...new Set(e)]}function K(a){let e=a.charAt(0);return {"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"}[e]||"unknown"}async function j(a,e,s,t){let o=P.join(s,".paradigm"),n=G(e),c=J(a,t),u=N(c.include||[],n),l=c.exclude||[],p=await X(s,u,l);return {systemPrompt:await Y(a,o,n),files:p,symbols:n}}function J(a,e){return e?.contextInclude||e?.contextExclude?{include:e.contextInclude,exclude:e.contextExclude}:{architect:{include:["specs/*.md",".purpose","**/.purpose","portal.yaml",".paradigm/config.yaml"],exclude:["src/**","tests/**","node_modules/**","dist/**"]},builder:{include:["src/**","tests/**","{feature}.purpose","specs/{feature}.md"],exclude:["specs/*.md","node_modules/**","dist/**"]},reviewer:{include:["src/**","specs/*.md","portal.yaml",".purpose"],exclude:["tests/**","node_modules/**","dist/**"]},tester:{include:["tests/**","health.yaml","{feature}.purpose"],exclude:["src/**","specs/**","node_modules/**","dist/**"]},security:{include:["portal.yaml","src/middleware/**","src/auth/**",".paradigm/wisdom/antipatterns.yaml"],exclude:["src/routes/**","tests/**","node_modules/**","dist/**"]}}[a.name]||{include:[".purpose","portal.yaml"],exclude:["node_modules/**","dist/**"]}}function N(a,e){let s=[];for(let t of a)if(t.includes("{feature}")||t.includes("{symbol}"))for(let o of e){let n=o.substring(1);s.push(t.replace(/\{feature\}/g,n).replace(/\{symbol\}/g,n));}else s.push(t);return s}async function X(a,e,s){let t=new Set;for(let o of e)try{let n=await glob(o,{cwd:a,ignore:s,nodir:!0,absolute:!1});for(let c of n)t.add(c);}catch{}return Array.from(t)}async function Y(a,e,s){let t=[],o=P.join(e,"config.yaml"),n=null;if(h.existsSync(o))try{n=M.load(h.readFileSync(o,"utf-8"));}catch{}if(t.push(`# ${a.name.charAt(0).toUpperCase()+a.name.slice(1)} Agent Context
3
+ `),n?.project&&(t.push(`> Project: ${n.project}`),n.discipline&&n.discipline!=="auto"&&t.push(`> Discipline: ${n.discipline}`),t.push("")),n?.["agent-guidelines"]?.overview&&(t.push(`## Project Overview
4
+ `),t.push(n["agent-guidelines"].overview),t.push("")),n?.["symbol-system"]){t.push(`## Symbol System
5
+ `),t.push("| Symbol | Meaning | Description |"),t.push("|--------|---------|-------------|");for(let[u,l]of Object.entries(n["symbol-system"]))t.push(`| \`${u}\` | ${l.name} | ${l.description} |`);t.push("");}if(n?.conventions){let u=Z(n.conventions,a.name);if(u.length>0){t.push(`## Conventions
6
+ `);for(let l of u)t.push(`- ${l}`);t.push("");}}if(s.length>0){t.push(`## Symbols in Scope
7
+ `);for(let u of s){let l=K(u);t.push(`- \`${u}\` (${l})`);}t.push("");}let c=q(a.name);if(c.length>0){t.push(`## Tips for This Role
8
+ `);for(let u of c)t.push(`- ${u}`);t.push("");}return t.join(`
9
+ `)}function Z(a,e){let t={architect:["design","spec","document","flow","symbol","reference"],builder:["code","implement","component","logger","test"],reviewer:["review","portal","gate","check","validate"],tester:["test","verify","health","validate"],security:["portal","gate","auth","security","vulnerability"]}[e]||[];return a.filter(o=>t.some(n=>o.toLowerCase().includes(n)))}function q(a){return {architect:["Focus on design decisions, not implementation details","Use paradigm symbols to reference features and components","Document flows that span 3+ components","Hand off to builder when spec is ready"],builder:["Follow the spec from architect exactly","If spec is unclear, ask for clarification or hand back","Use the Paradigm logger, not raw console.log","Hand off to reviewer when implementation is ready"],reviewer:["Check that all ^gate requirements are met","Verify adherence to specs","Do NOT implement fixes - hand back to builder","Approve or request changes with clear feedback"],tester:["Run tests and verify health status","Check portal validations","Update health.yaml when verified","Report issues with reproduction steps"],security:["Focus on ^gate implementations","Check for OWASP top 10 vulnerabilities","Flag issues but do NOT implement fixes","Review auth flows and session handling"]}[a]||[]}var x=class extends EventEmitter{config;usage;records=[];configPath;constructor(e){super(),this.configPath=P.join(e,".paradigm","config.yaml"),this.config=this.loadConfig(),this.usage=this.initializeUsage();}checkBudget(e,s){let t=this.estimateCost(s,"sonnet");if(this.config.maxTokens){let c=this.usage.tokens.total+s;if(c>this.config.maxTokens)return {allowed:false,reason:`Global token limit exceeded: ${d(c)} > ${d(this.config.maxTokens)}`,usage:this.usage,warningLevel:"exceeded"}}if(this.config.maxCostUsd){let c$1=this.usage.cost+t;if(c$1>this.config.maxCostUsd)return {allowed:false,reason:`Cost ceiling exceeded: ${c(c$1)} > ${c(this.config.maxCostUsd)}`,usage:this.usage,warningLevel:"exceeded"}}let o=this.config.agentLimits?.[e];if(o){let c$1=this.usage.byAgent[e]||{tokens:{total:0},cost:0};if(o.maxTokens){let u=c$1.tokens.total+s;if(u>o.maxTokens)return {allowed:false,reason:`Agent '${e}' token limit exceeded: ${d(u)} > ${d(o.maxTokens)}`,usage:this.usage,warningLevel:"exceeded"}}if(o.maxCostUsd){let u=c$1.cost+t;if(u>o.maxCostUsd)return {allowed:false,reason:`Agent '${e}' cost limit exceeded: ${c(u)} > ${c(o.maxCostUsd)}`,usage:this.usage,warningLevel:"exceeded"}}}let n="none";return this.config.warnAtPercent&&this.config.maxTokens&&(this.usage.tokens.total+s)/this.config.maxTokens*100>=this.config.warnAtPercent&&(n="approaching"),{allowed:true,usage:this.usage,warningLevel:n}}recordUsage(e,s,t,o){let n=b(s,t);this.usage.tokens.input+=s.input,this.usage.tokens.output+=s.output,this.usage.tokens.total+=s.total,this.usage.cost+=n,this.config.maxTokens&&(this.usage.percentage=this.usage.tokens.total/this.config.maxTokens*100),this.usage.byAgent[e]||(this.usage.byAgent[e]={tokens:{input:0,output:0,total:0},cost:0}),this.usage.byAgent[e].tokens.input+=s.input,this.usage.byAgent[e].tokens.output+=s.output,this.usage.byAgent[e].tokens.total+=s.total,this.usage.byAgent[e].cost+=n;let c={timestamp:new Date().toISOString(),agent:e,model:t,tokens:s,cost:n,orchestrationId:o};this.records.push(c),this.emit("usage",{agent:e,tokens:s,cost:n,total:this.usage}),this.config.warnAtPercent&&this.usage.percentage>=this.config.warnAtPercent&&this.emit("warning",{type:"budget_approaching",percentage:this.usage.percentage,usage:this.usage});}getUsage(){return {...this.usage}}getRecords(){return [...this.records]}getRemaining(){return {tokens:this.config.maxTokens?this.config.maxTokens-this.usage.tokens.total:null,cost:this.config.maxCostUsd?this.config.maxCostUsd-this.usage.cost:null}}reset(){this.usage=this.initializeUsage(),this.records=[];}estimateCost(e,s){let t={input:Math.floor(e/2),output:Math.ceil(e/2),total:e};return b(t,s)}estimateTime(e,s){return Math.ceil(e/{opus:50,sonnet:100,haiku:200}[s])*1e3}getSummary(){let e=[];if(e.push("Budget Summary:"),e.push(` Tokens: ${d(this.usage.tokens.total)}`),e.push(` Cost: ${c(this.usage.cost)}`),this.config.maxTokens&&e.push(` Token limit: ${d(this.config.maxTokens)} (${this.usage.percentage.toFixed(1)}% used)`),this.config.maxCostUsd){let s=this.usage.cost/this.config.maxCostUsd*100;e.push(` Cost limit: ${c(this.config.maxCostUsd)} (${s.toFixed(1)}% used)`);}if(Object.keys(this.usage.byAgent).length>0){e.push(" By agent:");for(let[s,t]of Object.entries(this.usage.byAgent))e.push(` ${s}: ${d(t.tokens.total)} (${c(t.cost)})`);}return e.join(`
10
+ `)}loadConfig(){let e={maxTokens:5e5,maxCostUsd:5,warnAtPercent:80};if(!h.existsSync(this.configPath))return e;try{let s=h.readFileSync(this.configPath,"utf-8"),o=M.load(s).orchestration;if(o?.budget){let n=o.budget;return {maxTokens:n.max_tokens,maxCostUsd:n.max_cost_usd,warnAtPercent:n.warn_at_percent,agentLimits:o.agent_limits}}return e}catch{return e}}initializeUsage(){return {tokens:{input:0,output:0,total:0},cost:0,percentage:0,byAgent:{}}}};var O=class{provider=null;budgetTracker=null;auditLogger=null;rootDir;constructor(e){this.rootDir=e;}async initialize(){await f(),this.provider=a(),this.budgetTracker=new x(this.rootDir),this.auditLogger=new a$1(this.rootDir);}isReady(){return this.provider!==null}getProvider(){return this.provider}async spawn(e$1,s,t={}){if(!this.provider)return {success:false,error:"Spawner not initialized",sessionId:""};let o=e(this.rootDir);if(!o)return {success:false,error:"Team not configured. Run `paradigm team init` first.",sessionId:""};let n=o.agents[e$1];if(!n)return {success:false,error:`Unknown agent: ${e$1}. Available: ${Object.keys(o.agents).join(", ")}`,sessionId:""};let c=t.provider||this.provider.name,u=a(c);if(!u)return {success:false,error:`Provider '${c}' not available`,sessionId:""};if(!await u.isAvailable())return {success:false,error:`Provider '${c}' not configured (missing API key?)`,sessionId:""};let p=this.generateSessionId(e$1),C=this.loadFacetConfig(e$1),S=await j(n,s,this.rootDir,C),y=t.model||C?.defaultModel||"sonnet",B={model:y,task:s,context:S,budget:t.budget,mcpServerPath:t.mcpServerPath,workingDirectory:t.workingDirectory||this.rootDir,checkpoints:t.checkpoints,timeout:t.timeout},T=Date.now(),z=new Date().toISOString(),i={agent:e$1,task:s,status:"success",completionVerified:false,outputs:{artifacts:[],symbols:S.symbols,decisions:[]},metrics:{tokens_used:{input:0,output:0,total:0},duration_ms:0,files_read:0,files_written:0}},E=32*1024,w="";try{for await(let r of u.spawn(n,B)){if(r.usage&&(i.metrics.tokens_used=r.usage),r.type==="text"&&r.content&&(w=(w+r.content).slice(-E)),r.type==="tool_use"){if(r.toolName==="read_file")i.metrics.files_read++;else if(r.toolName==="write_file"){i.metrics.files_written++;let f=r.toolInput?.path;f&&i.outputs.artifacts.push({path:f,action:"modified"});}}if(t.checkpoints&&r.type==="tool_use"&&this.shouldPauseForCheckpoint(r,t.checkpoints)&&t.onCheckpoint&&!await t.onCheckpoint(`Agent wants to ${r.toolName}: ${JSON.stringify(r.toolInput)}`)){i.status="blocked";break}if(t.onMessage&&t.onMessage(r),r.type==="error"&&(i.status="failed"),this.budgetTracker&&r.usage&&!this.budgetTracker.checkBudget(e$1,r.usage.total).allowed){i.status="failed";break}}if(i.metrics.duration_ms=Date.now()-T,i.rawResponse=w,this.budgetTracker&&this.budgetTracker.recordUsage(e$1,i.metrics.tokens_used,y),i.status==="success"){let r=i.outputs.artifacts.length>0,f=i.outputs.decisions.length>0,v=!!i.handoff,U=i.metrics.files_written>0,H=e$1==="architect";(e$1==="builder"&&!U&&!v||!r&&!f&&!v&&!U)&&(i.status="partial"),i.completionVerified=!0,i.status==="partial"&&!H&&t.onMessage&&t.onMessage({type:"text",content:`[completion-check] Agent "${e$1}" downgraded from success \u2192 partial: no meaningful output detected.`,timestamp:new Date().toISOString()});}if(this.auditLogger){let r={name:e$1,model:y,started:z,completed:new Date().toISOString(),duration_ms:i.metrics.duration_ms,tokens:i.metrics.tokens_used,cost_usd:b(i.metrics.tokens_used,y),status:i.status,artifacts:i.outputs.artifacts,symbols:i.outputs.symbols};this.auditLogger.logAgentCompletion(p,r);}return {success:i.status==="success"||i.status==="partial",relay:i,sessionId:p}}catch(r){return {success:false,error:r instanceof Error?r.message:String(r),sessionId:p,relay:{...i,status:"failed",rawResponse:w,metrics:{...i.metrics,duration_ms:Date.now()-T}}}}}async spawnParallel(e){let s=e.map(({name:t,task:o,options:n})=>this.spawn(t,o,n));return Promise.all(s)}generateSessionId(e){let s=Date.now(),t=Math.random().toString(36).substring(2,8);return `${e}-${s}-${t}`}loadFacetConfig(e){let s=P.join(this.rootDir,".paradigm","facets.yaml");if(!h.existsSync(s))return {architect:{defaultModel:"opus"},security:{defaultModel:"opus"},reviewer:{defaultModel:"sonnet"},builder:{defaultModel:"haiku"},tester:{defaultModel:"haiku"}}[e];try{let t=h.readFileSync(s,"utf-8");return M.load(t)[e]}catch{return}}shouldPauseForCheckpoint(e,s){if(!s.beforeActions||e.type!=="tool_use")return false;let t={write:["write_file","edit_file"],delete:["delete_file","rm"],execute:["run_command","bash"],external_api:["mcp_call","http_request"]};for(let o of s.beforeActions){let n=t[o]||[];if(e.toolName&&n.includes(e.toolName))return true}return false}};export{G as a,O as b};
@@ -0,0 +1,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};