@a-company/paradigm 7.2.0 → 7.3.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 (92) hide show
  1. package/dist/{accept-orchestration-XW44LF5Y.js → accept-orchestration-JA3A3TSU.js} +1 -1
  2. package/dist/calibrate-SH6PRZFD.js +2 -0
  3. package/dist/calibration-aggregate-5IVXSBDP.js +2 -0
  4. package/dist/calibration-aggregate-DUEE3LL2.js +4 -0
  5. package/dist/{captain-CAXGHC2V.js → captain-ILBN2IKJ.js} +1 -1
  6. package/dist/{captain-CWCLFOXV.js → captain-J4FZ5PRU.js} +1 -1
  7. package/dist/{chunk-W3VWORQZ.js → chunk-3F4QP2Z5.js} +1 -1
  8. package/dist/{chunk-QPQBXRXX.js → chunk-5VR7FKS5.js} +1 -1
  9. package/dist/chunk-7BZPDOOQ.js +25 -0
  10. package/dist/{chunk-XSKIXXFW.js → chunk-7HUPVOAY.js} +12 -12
  11. package/dist/{chunk-ASBK55FU.js → chunk-DLMDHS2X.js} +1 -1
  12. package/dist/{chunk-6HYRS3PH.js → chunk-IBKCMLOW.js} +8 -8
  13. package/dist/{chunk-USYV5QYU.js → chunk-KA6QEI3C.js} +1 -1
  14. package/dist/{chunk-UNSI6DVD.js → chunk-L3AOKDMU.js} +1 -1
  15. package/dist/chunk-MBKTVQS2.js +2 -0
  16. package/dist/{chunk-RZRFYGND.js → chunk-O4ADSTSY.js} +12 -12
  17. package/dist/chunk-RPGSQQTS.js +2 -0
  18. package/dist/chunk-RQHZUPLO.js +4 -0
  19. package/dist/chunk-SD3KVW5Q.js +2 -0
  20. package/dist/chunk-VKVVIN6J.js +25 -0
  21. package/dist/{chunk-2KK4JQ55.js → chunk-VR2LLUYE.js} +1 -1
  22. package/dist/{chunk-NRP2KJ6I.js → chunk-YNFF7XHV.js} +2 -2
  23. package/dist/{diff-Z2YSIRC4.js → diff-NZSJW3V3.js} +1 -1
  24. package/dist/dist-6TDAY6TQ-HMSTBL57.js +39 -0
  25. package/dist/{docs-OWJ7EPD7.js → docs-DWU3T2BV.js} +1 -1
  26. package/dist/github-GI3HX3N5.js +4 -0
  27. package/dist/index.js +6 -6
  28. package/dist/mcp.js +1 -1
  29. package/dist/{orchestrate-C5NM5MFN.js → orchestrate-C7SI4J7C.js} +1 -1
  30. package/dist/orchestration-4MJKBSGM.js +2 -0
  31. package/dist/orchestration-S2ESNKSA.js +2 -0
  32. package/dist/platform-server-IOWHNS7Q.js +25 -0
  33. package/dist/{reindex-W67B2LQP.js → reindex-G2JLIGOQ.js} +1 -1
  34. package/dist/reindex-JR3PXYQE.js +2 -0
  35. package/dist/{sentinel-EFPEX246.js → sentinel-RIEQWALQ.js} +1 -1
  36. package/dist/{sentinel-bridge-UR2MKARY.js → sentinel-bridge-D4LFDFCH.js} +1 -1
  37. package/dist/serve-PWAFVYYC.js +9 -0
  38. package/dist/{server-4D77LCST.js → server-K7G3IHR3.js} +1 -1
  39. package/dist/{shift-UDKXCIW7.js → shift-HGXZ5THV.js} +1 -1
  40. package/dist/{spawn-I6XG57S2.js → spawn-PHA2SVQ3.js} +1 -1
  41. package/dist/sync-layer-C2PF273N.js +2 -0
  42. package/dist/task-PRLQ4VPK.js +3 -0
  43. package/dist/task-loader-EIXPKHA3.js +2 -0
  44. package/dist/task-loader-LFEE6OU7.js +2 -0
  45. package/dist/task-settlement-A2T6EACG.js +3 -0
  46. package/dist/task-settlement-ZXOY4YGX.js +3 -0
  47. package/dist/{team-6WNNLBAO.js → team-KP4HMUB5.js} +1 -1
  48. package/dist/tools-NOMEIBS7.js +2 -0
  49. package/dist/{tools-SDWAFQMQ.js → tools-YW3Q27UI.js} +11 -11
  50. package/package.json +2 -6
  51. package/platform-ui/dist/assets/{AmbientSection-CwatqcBD.js → AmbientSection-xoxr3DQg.js} +1 -1
  52. package/platform-ui/dist/assets/{DocsSection-BZ2SFJBZ.js → DocsSection-Us2qksna.js} +1 -1
  53. package/platform-ui/dist/assets/{GitSection-MNNYU1tO.js → GitSection-DIHZyadf.js} +1 -1
  54. package/platform-ui/dist/assets/{GraphSection-COYjb4Pt.js → GraphSection-9TO0L1IO.js} +1 -1
  55. package/platform-ui/dist/assets/{LoreSection-B0hUbfsJ.js → LoreSection-DVDit8Aw.js} +1 -1
  56. package/platform-ui/dist/assets/{SentinelSection-BCxW1DCp.js → SentinelSection-a5_VNYcx.js} +1 -1
  57. package/platform-ui/dist/assets/{SymphonySection-BsucZRqy.js → SymphonySection-cRHEoJ9t.js} +1 -1
  58. package/platform-ui/dist/assets/TasksSection-44_gDO3L.css +1 -0
  59. package/platform-ui/dist/assets/TasksSection-h8x3qRIj.js +1 -0
  60. package/platform-ui/dist/assets/{TeamSection-C0QNTudW.js → TeamSection-mFoDyNic.js} +1 -1
  61. package/platform-ui/dist/assets/{UniversitySection-DN1-g9pw.js → UniversitySection-D99YRjmC.js} +1 -1
  62. package/platform-ui/dist/assets/{index-DwUT8pju.js → index-D_wB2S_2.js} +11 -11
  63. package/platform-ui/dist/index.html +1 -1
  64. package/dist/calibrate-PHVP7RPH.js +0 -4
  65. package/dist/chunk-3I3TITBA.js +0 -25
  66. package/dist/chunk-3YM5ABNX.js +0 -2
  67. package/dist/chunk-727PXENG.js +0 -2
  68. package/dist/chunk-K7KT6FL3.js +0 -25
  69. package/dist/chunk-XMAV5AG6.js +0 -2
  70. package/dist/dist-GQ42YS5N-4HIJZVBB.js +0 -39
  71. package/dist/github-4X4MYINS.js +0 -4
  72. package/dist/lore-server-FC2GMDLT.js +0 -14
  73. package/dist/orchestration-EVWQWTOV.js +0 -2
  74. package/dist/orchestration-UP3KFUJT.js +0 -2
  75. package/dist/platform-server-FXF3XFHM.js +0 -25
  76. package/dist/reindex-QZYOD5K4.js +0 -2
  77. package/dist/serve-L52ZUTU6.js +0 -10
  78. package/dist/serve-ZT2Z54NK.js +0 -8
  79. package/dist/task-KFND4HLF.js +0 -3
  80. package/dist/task-loader-HBZ3KRH2.js +0 -2
  81. package/dist/task-loader-IO4UVFUD.js +0 -2
  82. package/dist/task-settlement-NF7PFSNE.js +0 -3
  83. package/dist/task-settlement-TATNPY6L.js +0 -3
  84. package/dist/tools-GDWT74O6.js +0 -2
  85. package/graph-ui/dist/assets/index-BlgXTl53.css +0 -1
  86. package/graph-ui/dist/assets/index-Bq5nXK8p.js +0 -63
  87. package/graph-ui/dist/index.html +0 -13
  88. package/lore-ui/dist/assets/index-C3EixkjW.css +0 -1
  89. package/lore-ui/dist/assets/index-DKhNxgtW.js +0 -56
  90. package/lore-ui/dist/index.html +0 -13
  91. package/platform-ui/dist/assets/CanvasSection-dFAthehN.js +0 -9
  92. package/platform-ui/dist/assets/CanvasSection-flMXU19z.css +0 -1
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {D as D$1}from'./chunk-K7KT6FL3.js';import {O}from'./chunk-W3VWORQZ.js';import {z as z$1,b as b$1,c}from'./chunk-KAFQA7HV.js';import {b,a}from'./chunk-EK4ZRIFJ.js';import*as D from'fs';import*as ne from'os';import*as Y from'path';import*as G from'js-yaml';z$1();b();var le=/[@#$%^!?&~][a-zA-Z0-9_-]+/g;var B={architect:"tier-1",ftux:"tier-1",scholar:"tier-1",security:"tier-1",advocate:"tier-1",product:"tier-1",operations:"tier-1",sales:"tier-1",legal:"tier-1",ethicist:"tier-1",futurist:"tier-1",cartographer:"tier-1",cid:"tier-1","agent-evaluator":"tier-1","data-model":"tier-1",domain:"tier-1",regulatory:"tier-1",compliance:"tier-2",reviewer:"tier-2",designer:"tier-2",copywriter:"tier-2",researcher:"tier-2",analyst:"tier-2",dx:"tier-2",qa:"tier-2",debugger:"tier-2",performance:"tier-2",creative:"tier-2",pm:"tier-2",narrator:"tier-2",e2e:"tier-2",educator:"tier-2",community:"tier-2","content-intel":"tier-2",ai:"tier-2",mediator:"tier-2",presenter:"tier-2",mentor:"tier-2",trainer:"tier-2",a11y:"tier-2",seo:"tier-2",swift:"tier-2",forms:"tier-2",geo:"tier-2",builder:"tier-3",tester:"tier-3",documentor:"tier-3",sysadmin:"tier-3",archivist:"tier-3",release:"tier-3",devops:"tier-3",dba:"tier-3",dataeng:"tier-3",integrator:"tier-3",network:"tier-3",streaming:"tier-3",mobile:"tier-3",gamedev:"tier-3","3d":"tier-3",i18n:"tier-3",translator:"tier-3",forge:"tier-3",secretary:"tier-3",reverser:"tier-3",audio:"tier-3",finance:"tier-3",offline:"tier-3","report-gen":"tier-3"},z={"tier-1":"opus","tier-2":"sonnet","tier-3":"haiku"};function se(a,e,t){try{let k=Y.join(e,".paradigm","config.yaml");if(D.existsSync(k)){let n=G.load(D.readFileSync(k,"utf8"))?.["model-resolution"];if(n){let d=t?.modelTier||B[a]||"tier-2";if(n[d])return n[d]}}}catch{}if(t?.defaultModel)return t.defaultModel;let c=B[a]||"tier-2";return z[c]||"sonnet"}var de={architect:{min:5e3,max:2e4},ftux:{min:4e3,max:18e3},security:{min:3e3,max:15e3},reviewer:{min:2e3,max:1e4},builder:{min:1e4,max:5e4},tester:{min:5e3,max:2e4},cartographer:{min:1e3,max:5e3}};function ue(a$1){try{let e=Y.join(a$1,".paradigm","learned","token-estimates.json");if(!D.existsSync(e))return {};let t=JSON.parse(D.readFileSync(e,"utf8"));return !t||typeof t!="object"||Array.isArray(t)?{}:t}catch(e){return a.component("#calibration").warn("learned token table load failed; using constant prior",{error:e instanceof Error?e.message:String(e)}),{}}}function pe(a,e,t){if(t){let c=a[e]?.[t];if(c&&typeof c.min=="number"&&typeof c.max=="number")return {min:c.min,max:c.max}}return de[e]||{min:5e3,max:2e4}}var U={architect:`You are the ARCHITECT agent.
2
+ import {D as D$1}from'./chunk-VKVVIN6J.js';import {O}from'./chunk-3F4QP2Z5.js';import {z,b as b$1,c}from'./chunk-KAFQA7HV.js';import {b,a}from'./chunk-EK4ZRIFJ.js';import*as D from'fs';import*as ie from'os';import*as Y from'path';import*as H from'js-yaml';z();b();var me=/[@#$%^!?&~][a-zA-Z0-9_-]+/g;var G={architect:"tier-1",ftux:"tier-1",scholar:"tier-1",security:"tier-1",advocate:"tier-1",product:"tier-1",operations:"tier-1",sales:"tier-1",legal:"tier-1",ethicist:"tier-1",futurist:"tier-1",cartographer:"tier-1",cid:"tier-1","agent-evaluator":"tier-1","data-model":"tier-1",domain:"tier-1",regulatory:"tier-1",compliance:"tier-2",reviewer:"tier-2",designer:"tier-2",copywriter:"tier-2",researcher:"tier-2",analyst:"tier-2",dx:"tier-2",qa:"tier-2",debugger:"tier-2",performance:"tier-2",creative:"tier-2",pm:"tier-2",narrator:"tier-2",e2e:"tier-2",educator:"tier-2",community:"tier-2","content-intel":"tier-2",ai:"tier-2",mediator:"tier-2",presenter:"tier-2",mentor:"tier-2",trainer:"tier-2",a11y:"tier-2",seo:"tier-2",swift:"tier-2",forms:"tier-2",geo:"tier-2",builder:"tier-3",tester:"tier-3",documentor:"tier-3",sysadmin:"tier-3",archivist:"tier-3",release:"tier-3",devops:"tier-3",dba:"tier-3",dataeng:"tier-3",integrator:"tier-3",network:"tier-3",streaming:"tier-3",mobile:"tier-3",gamedev:"tier-3","3d":"tier-3",i18n:"tier-3",translator:"tier-3",forge:"tier-3",secretary:"tier-3",reverser:"tier-3",audio:"tier-3",finance:"tier-3",offline:"tier-3","report-gen":"tier-3"},J={"tier-1":"opus","tier-2":"sonnet","tier-3":"haiku"};function oe(r,e,t){try{let f=Y.join(e,".paradigm","config.yaml");if(D.existsSync(f)){let n=H.load(D.readFileSync(f,"utf8"))?.["model-resolution"];if(n){let l=t?.modelTier||G[r]||"tier-2";if(n[l])return n[l]}}}catch{}if(t?.defaultModel)return t.defaultModel;let c=G[r]||"tier-2";return J[c]||"sonnet"}var re={architect:{min:5e3,max:2e4},ftux:{min:4e3,max:18e3},security:{min:3e3,max:15e3},reviewer:{min:2e3,max:1e4},builder:{min:1e4,max:5e4},tester:{min:5e3,max:2e4},cartographer:{min:1e3,max:5e3}},B=null;function ae(r){try{let e=Y.join(r,".paradigm","learned","token-estimates.json"),t;try{t=D.statSync(e);}catch{return {}}if(B&&B.path===e&&B.mtimeMs===t.mtimeMs)return B.table;let c=JSON.parse(D.readFileSync(e,"utf8"));return !c||typeof c!="object"||Array.isArray(c)?{}:(B={path:e,mtimeMs:t.mtimeMs,table:c},c)}catch(e){return a.component("#calibration").warn("learned token table load failed; using constant prior",{error:e instanceof Error?e.message:String(e)}),{}}}function ee(r,e,t){if(t){let f=r[e]?.[t];if(f&&typeof f.min=="number"&&typeof f.max=="number")return {min:f.min,max:f.max,n:typeof f.n=="number"?f.n:0,source:"learned"}}let c=re[e]||{min:5e3,max:2e4};return {min:c.min,max:c.max,n:0,source:"prior"}}function Le(r,e,t){let c=e.claimant?.kind==="archetype"?e.claimant.ref:t||"builder",f=de(e.blurb).type;return ee(r,c,f)}var he=["feature","bugfix","refactor","design","analysis","research","documentation","audit"];function Be(r){let e=ae(r),t=Array.from(new Set([...Object.keys(re),...Object.keys(e)])).sort(),c=Array.from(new Set([...he,...Object.values(e).flatMap(l=>Object.keys(l))])).sort(),f={},p=0,n=0;for(let l of t){f[l]={};for(let o of c){let s=ee(e,l,o);f[l][o]=s,n++,s.source==="learned"&&p++;}}return {archetypes:t,taskTypes:c,cells:f,coverage:{graduated:p,total:n,pct:n?Math.round(p/n*100):0}}}var U={architect:`You are the ARCHITECT agent.
3
3
 
4
4
  ## Your Role
5
5
  You design system architecture, write specifications, and plan features.
@@ -447,7 +447,7 @@ code, and never modify .purpose files or portal.yaml.
447
447
  - Block a build or deployment because of architectural drift
448
448
  - Write source code
449
449
  - Modify .purpose files, portal.yaml, or arch.yaml directly
450
- - Produce lengthy analysis \u2014 be sharp, summarize, and hand off`};function We(){return [{name:"paradigm_orchestrate_inline",description:`REQUIRED before implementing features. Start with mode="quick" for fast pre-check, or mode="plan" for full orchestration planning.
450
+ - Produce lengthy analysis \u2014 be sharp, summarize, and hand off`};function Ge(){return [{name:"paradigm_orchestrate_inline",description:`REQUIRED before implementing features. Start with mode="quick" for fast pre-check, or mode="plan" for full orchestration planning.
451
451
 
452
452
  Plans and coordinates multi-agent task execution within the same session.
453
453
  - mode: "quick" - Lightweight pre-implementation check (~3-4k tokens). Jinx (advocate) stress-tests assumptions, reviewer checks feasibility. Returns greenlight or escalates to full orchestration. NOTE: quick is a pre-check only \u2014 it does NOT satisfy orchestration-required enforcement. Enforcement is satisfied by a COMPLETED run (verdicts > 0 \u2014 a settled task DAG or a debrief with real agent verdicts) or by declaring \`paradigm solo\`.
@@ -470,17 +470,17 @@ Examples:
470
470
  - "Fix the login bug" \u2192 quick (greenlight or escalate)
471
471
  - "Add user authentication with JWT" \u2192 plan \u2192 architect + security + builder + tester
472
472
  - "Should I use soft delete or hard delete?" \u2192 plan \u2192 architect only (analysis)
473
- - "Refactor the payment module" \u2192 plan \u2192 architect + builder`,inputSchema:{type:"object",properties:{task:{type:"string",description:'The task to orchestrate (e.g., "Build @payment-system with Stripe integration")'},mode:{type:"string",enum:["quick","plan","execute"],description:'Mode: "quick" for lightweight pre-check (advocate + reviewer), "plan" returns suggested agents and plan, "execute" returns prompts ready for Task tool'},agents:{type:"array",items:{type:"string"},description:'Optional: Override which agents to use (e.g., ["architect", "builder"])'}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["plan","coordinate","team","multi-agent","orchestrate","agents","spawn agents"]},{name:"paradigm_agent_prompt",description:"Get the complete prompt for a specific agent to execute a task. Use this when you need to spawn an agent via the Task tool with full context.",inputSchema:{type:"object",properties:{agent:{type:"string",enum:["advocate","architect","builder","cartographer","compliance","ftux","scholar","swift","tester","reviewer","security","documentor"],description:"The agent role to get prompt for"},task:{type:"string",description:"The specific task for this agent"},handoffContext:{type:"string",description:"Optional: Context passed from a previous agent"},previousAgent:{type:"string",description:"Optional: Name of the agent that handed off"}},required:["agent","task"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Fe(a,e,t){return a==="paradigm_orchestrate_inline"?ge(e,t):a==="paradigm_agent_prompt"?he(e,t):{handled:false,text:""}}async function ge(a,e){let t=a.task,c$1=a.mode||"execute",k=a.agents;try{let h=Y.join(e.rootDir,".paradigm","events");D.existsSync(h)||D.mkdirSync(h,{recursive:!0}),D.appendFileSync(Y.join(h,"team-funnel.jsonl"),JSON.stringify({timestamp:new Date().toISOString(),type:"orchestrated",source:"orchestrate_inline",mode:c$1})+`
474
- `,"utf8");}catch{}let g=re(e.rootDir);if(!g){let h=JSON.stringify({error:"No agents.yaml found",suggestion:"Run `paradigm team init` to set up multi-agent orchestration"},null,2);return O(h.length,"paradigm_orchestrate_inline"),{handled:true,text:h}}let n=b$1(e.rootDir);if(n&&g.agents){let h={};for(let[m,u]of Object.entries(g.agents))n.includes(m)&&(h[m]=u);g.agents=h;}let d=H(t),o=[];try{let{processPendingEvents:h,loadNominations:m}=await import('./nomination-engine-YRHZZZUN.js');h(e.rootDir),o=m(e.rootDir,{pending_only:!0,limit:10}).filter(l=>l.urgency==="high"||l.urgency==="critical").map(l=>({agent:l.agent,urgency:l.urgency,brief:l.brief}));}catch{}let s=De(t);if(c$1==="quick")return me(t,d,s,o,g,e);let i=ye(t,g.agents,k,s,g.orchestration,e.rootDir);if(c$1==="plan"){let h=Ce(t,g.agents),m=Oe(i,s),u;try{let{loadNotebookEntries:S}=await import('./notebook-loader-TZVIMNDJ.js'),v=d.map(E=>E.replace(/^[#$^!~@&%?]/,"").toLowerCase()),N={},x=new Set;for(let E of i.stages)for(let P of E.agents){if(x.has(P.name))continue;x.add(P.name);let j=S(P.name,e.rootDir),I=v.length>0?S(P.name,e.rootDir,{concepts:v}):j;j.length>0&&(N[P.name]={totalEntries:j.length,relevantEntries:I.length});}Object.keys(N).length>0&&(u=N);}catch{}let l=i.stages.flatMap(S=>S.agents.map(v=>v.name)),w=ie(l,g.agents),T=w.length>0?{edges:w,note:"Shows which agents hand off to which based on agents.yaml handoff_to. Stage ordering was derived from this graph."}:void 0,_=JSON.stringify({task:t,mode:"plan",classification:{type:s.type,confidence:s.confidence,...s.alternativeType?{alternativeType:s.alternativeType}:{},overrideHint:s.overrideHint,complexity:s.complexity,securityRequired:s.securityRequired,costMultiplier:s.costMultiplier},plan:i,suggestedAgents:h,costPreview:m,...T?{collaborationGraph:T}:{},...u?{notebookKnowledge:u,notebookNote:"Agents with relevant notebook entries will have curated knowledge injected into their prompts during execute mode."}:{},...o.length>0?{activeNominations:o,nominationNote:`${o.length} high-urgency agent nomination(s) pending. These agents have been flagged by the system for attention on this project.`}:{},instructions:["Review task classification and cost preview above","Review suggested agents based on task triggers",...T?["Review collaboration graph \u2014 stage ordering was derived from agent handoff_to edges"]:[],...u?["Review notebook knowledge \u2014 agents with relevant entries will receive curated snippets in execute mode"]:[],...o.length>0?["Review active nominations \u2014 agents flagged by the system may need to be included"]:[],'Call again with mode="execute" to get full prompts and execution strategy',"Stages marked canRunParallel: true can be launched simultaneously","After each agent completes, pass handoff context to the next stage"]},null,2);return O(_.length,"paradigm_orchestrate_inline"),{handled:true,text:_}}let y=new Map;try{let{loadAgentProfile:h,buildProfileEnrichment:m}=await import('./agent-loader-W3RQJVW7.js'),{loadDecisions:u}=await import('./decision-loader-HELL2AMX.js'),{loadJournalEntries:l}=await import('./journal-loader-CNNA4EAU.js'),{loadNominations:w}=await import('./nomination-engine-YRHZZZUN.js'),{loadAgentState:T}=await import('./agent-state-KSQ3S7OB.js'),{loadNotebookEntries:_}=await import('./notebook-loader-TZVIMNDJ.js'),S=u(e.rootDir,{status:"active",limit:5}).map(x=>({title:x.title,decision:x.decision.slice(0,150)})),v=w(e.rootDir,{pending_only:!0,limit:10}).map(x=>({urgency:x.urgency,brief:x.brief})),N=d.map(x=>x.replace(/^[#$^!~@&%?]/,"").toLowerCase());for(let x of i.stages)for(let E of x.agents)if(!y.has(E.name)){let P=h(e.rootDir,E.name);if(P){if(!c(E.name,e.rootDir))continue;let j=l(E.name,{transferable:!0,limit:5}).map(M=>({trigger:M.trigger,insight:M.insight.slice(0,150)})),I=T(E.name,e.rootDir),K;try{let M=_(E.name,e.rootDir,N.length>0?{concepts:N}:void 0);if(M.length>0){let J=M.sort(($,W)=>W.confidence-$.confidence||new Date(W.updated).getTime()-new Date($.updated).getTime()).slice(0,5);K=J.map($=>({context:$.context,snippet:$.snippet,concepts:$.concepts}));try{let{recordNotebookReference:$}=await import('./session-work-log-T2IE4Y4T.js');$(e.rootDir,E.name,J.map(W=>W.id));}catch{}try{let{incrementApplied:$}=await import('./notebook-loader-TZVIMNDJ.js');for(let W of J)$(E.name,W.id,e.rootDir);}catch{}}}catch{}let L=m(P,d,K,{recentDecisions:S,journalInsights:j,pendingNominations:v},I?{lastSession:I.lastSession,pendingWork:I.pendingWork,recentPatterns:I.recentPatterns,sessionsOnProject:I.sessionsOnProject}:void 0);if(P.permissions){let M=[`
475
- ## Permission Constraints`];P.permissions.paths?.deny?.length&&M.push(`**Denied paths:** ${P.permissions.paths.deny.join(", ")}`),P.permissions.paths?.write?.length&&M.push(`**Writable paths:** ${P.permissions.paths.write.join(", ")}`),P.permissions.tools?.deny?.length&&M.push(`**Denied tools:** ${P.permissions.tools.deny.join(", ")}`),P.permissions.dangerous_actions?.length&&M.push(`**Requires approval for:** ${P.permissions.dangerous_actions.join(", ")}`),L+=`
476
- `+M.join(`
477
- `);}y.set(E.name,{enrichment:L.trim()?L:"",nickname:P.nickname,description:P.description});}}}catch{}let r;try{let h=await D$1("paradigm_captain_brief",{taskDescription:t,symbols:d,depth:"standard"},e);h.handled&&(r=JSON.parse(h.text).renderedBrief);}catch{}let p=[];for(let h of i.stages){let m=[];for(let u of h.agents){let l=g.agents[u.name],w=y.get(u.name),T={name:l?.name||u.name,role:l?.role||U[u.name]||`${u.name} agent`,description:w?.description,focus:l?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:se(u.name,e.rootDir,l),triggers:l?.triggers,handoff_to:l?.handoff_to,context:l?.context,protocol:l?.protocol},_=oe({agent:T,task:u.task,symbols:d,dependsOn:u.dependsOn,profileEnrichment:w?.enrichment,nickname:w?.nickname,captainBrief:r});m.push(_);}p.push({stage:h.stage,canRunParallel:h.canRunParallel,agents:m});}let f=`orch-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`;Ie(e.rootDir,f,t,i);let{epicTaskId:A,agentTaskIds:R}=await Ne(e.rootDir,f,t,i);for(let h of p)for(let m of h.agents){let u=R.get(m.agent);u&&(m.taskId=u,m.prompt+=`
473
+ - "Refactor the payment module" \u2192 plan \u2192 architect + builder`,inputSchema:{type:"object",properties:{task:{type:"string",description:'The task to orchestrate (e.g., "Build @payment-system with Stripe integration")'},mode:{type:"string",enum:["quick","plan","execute"],description:'Mode: "quick" for lightweight pre-check (advocate + reviewer), "plan" returns suggested agents and plan, "execute" returns prompts ready for Task tool'},agents:{type:"array",items:{type:"string"},description:'Optional: Override which agents to use (e.g., ["architect", "builder"])'}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["plan","coordinate","team","multi-agent","orchestrate","agents","spawn agents"]},{name:"paradigm_agent_prompt",description:"Get the complete prompt for a specific agent to execute a task. Use this when you need to spawn an agent via the Task tool with full context.",inputSchema:{type:"object",properties:{agent:{type:"string",enum:["advocate","architect","builder","cartographer","compliance","ftux","scholar","swift","tester","reviewer","security","documentor"],description:"The agent role to get prompt for"},task:{type:"string",description:"The specific task for this agent"},handoffContext:{type:"string",description:"Optional: Context passed from a previous agent"},previousAgent:{type:"string",description:"Optional: Name of the agent that handed off"}},required:["agent","task"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Ue(r,e,t){return r==="paradigm_orchestrate_inline"?fe(e,t):r==="paradigm_agent_prompt"?be(e,t):{handled:false,text:""}}async function fe(r,e){let t=r.task,c$1=r.mode||"execute",f=r.agents;try{let h=Y.join(e.rootDir,".paradigm","events");D.existsSync(h)||D.mkdirSync(h,{recursive:!0}),D.appendFileSync(Y.join(h,"team-funnel.jsonl"),JSON.stringify({timestamp:new Date().toISOString(),type:"orchestrated",source:"orchestrate_inline",mode:c$1})+`
474
+ `,"utf8");}catch{}let p=ue(e.rootDir);if(!p){let h=JSON.stringify({error:"No agents.yaml found",suggestion:"Run `paradigm team init` to set up multi-agent orchestration"},null,2);return O(h.length,"paradigm_orchestrate_inline"),{handled:true,text:h}}let n=b$1(e.rootDir);if(n&&p.agents){let h={};for(let[m,u]of Object.entries(p.agents))n.includes(m)&&(h[m]=u);p.agents=h;}let l=K(t),o=[];try{let{processPendingEvents:h,loadNominations:m}=await import('./nomination-engine-YRHZZZUN.js');h(e.rootDir),o=m(e.rootDir,{pending_only:!0,limit:10}).filter(d=>d.urgency==="high"||d.urgency==="critical").map(d=>({agent:d.agent,urgency:d.urgency,brief:d.brief}));}catch{}let s=de(t);if(c$1==="quick")return ye(t,l,s,o,p,e);let i=ke(t,p.agents,f,s,p.orchestration,e.rootDir);if(c$1==="plan"){let h=Ie(t,p.agents),m=Me(i,s),u;try{let{loadNotebookEntries:S}=await import('./notebook-loader-TZVIMNDJ.js'),v=l.map(E=>E.replace(/^[#$^!~@&%?]/,"").toLowerCase()),M={},_=new Set;for(let E of i.stages)for(let P of E.agents){if(_.has(P.name))continue;_.add(P.name);let j=S(P.name,e.rootDir),I=v.length>0?S(P.name,e.rootDir,{concepts:v}):j;j.length>0&&(M[P.name]={totalEntries:j.length,relevantEntries:I.length});}Object.keys(M).length>0&&(u=M);}catch{}let d=i.stages.flatMap(S=>S.agents.map(v=>v.name)),k=ce(d,p.agents),R=k.length>0?{edges:k,note:"Shows which agents hand off to which based on agents.yaml handoff_to. Stage ordering was derived from this graph."}:void 0,x=JSON.stringify({task:t,mode:"plan",classification:{type:s.type,confidence:s.confidence,...s.alternativeType?{alternativeType:s.alternativeType}:{},overrideHint:s.overrideHint,complexity:s.complexity,securityRequired:s.securityRequired,costMultiplier:s.costMultiplier},plan:i,suggestedAgents:h,costPreview:m,...R?{collaborationGraph:R}:{},...u?{notebookKnowledge:u,notebookNote:"Agents with relevant notebook entries will have curated knowledge injected into their prompts during execute mode."}:{},...o.length>0?{activeNominations:o,nominationNote:`${o.length} high-urgency agent nomination(s) pending. These agents have been flagged by the system for attention on this project.`}:{},instructions:["Review task classification and cost preview above","Review suggested agents based on task triggers",...R?["Review collaboration graph \u2014 stage ordering was derived from agent handoff_to edges"]:[],...u?["Review notebook knowledge \u2014 agents with relevant entries will receive curated snippets in execute mode"]:[],...o.length>0?["Review active nominations \u2014 agents flagged by the system may need to be included"]:[],'Call again with mode="execute" to get full prompts and execution strategy',"Stages marked canRunParallel: true can be launched simultaneously","After each agent completes, pass handoff context to the next stage"]},null,2);return O(x.length,"paradigm_orchestrate_inline"),{handled:true,text:x}}let b=new Map;try{let{loadAgentProfile:h,buildProfileEnrichment:m}=await import('./agent-loader-W3RQJVW7.js'),{loadDecisions:u}=await import('./decision-loader-HELL2AMX.js'),{loadJournalEntries:d}=await import('./journal-loader-CNNA4EAU.js'),{loadNominations:k}=await import('./nomination-engine-YRHZZZUN.js'),{loadAgentState:R}=await import('./agent-state-KSQ3S7OB.js'),{loadNotebookEntries:x}=await import('./notebook-loader-TZVIMNDJ.js'),S=u(e.rootDir,{status:"active",limit:5}).map(_=>({title:_.title,decision:_.decision.slice(0,150)})),v=k(e.rootDir,{pending_only:!0,limit:10}).map(_=>({urgency:_.urgency,brief:_.brief})),M=l.map(_=>_.replace(/^[#$^!~@&%?]/,"").toLowerCase());for(let _ of i.stages)for(let E of _.agents)if(!b.has(E.name)){let P=h(e.rootDir,E.name);if(P){if(!c(E.name,e.rootDir))continue;let j=d(E.name,{transferable:!0,limit:5}).map(N=>({trigger:N.trigger,insight:N.insight.slice(0,150)})),I=R(E.name,e.rootDir),z;try{let N=x(E.name,e.rootDir,M.length>0?{concepts:M}:void 0);if(N.length>0){let V=N.sort(($,W)=>W.confidence-$.confidence||new Date(W.updated).getTime()-new Date($.updated).getTime()).slice(0,5);z=V.map($=>({context:$.context,snippet:$.snippet,concepts:$.concepts}));try{let{recordNotebookReference:$}=await import('./session-work-log-T2IE4Y4T.js');$(e.rootDir,E.name,V.map(W=>W.id));}catch{}try{let{incrementApplied:$}=await import('./notebook-loader-TZVIMNDJ.js');for(let W of V)$(E.name,W.id,e.rootDir);}catch{}}}catch{}let L=m(P,l,z,{recentDecisions:S,journalInsights:j,pendingNominations:v},I?{lastSession:I.lastSession,pendingWork:I.pendingWork,recentPatterns:I.recentPatterns,sessionsOnProject:I.sessionsOnProject}:void 0);if(P.permissions){let N=[`
475
+ ## Permission Constraints`];P.permissions.paths?.deny?.length&&N.push(`**Denied paths:** ${P.permissions.paths.deny.join(", ")}`),P.permissions.paths?.write?.length&&N.push(`**Writable paths:** ${P.permissions.paths.write.join(", ")}`),P.permissions.tools?.deny?.length&&N.push(`**Denied tools:** ${P.permissions.tools.deny.join(", ")}`),P.permissions.dangerous_actions?.length&&N.push(`**Requires approval for:** ${P.permissions.dangerous_actions.join(", ")}`),L+=`
476
+ `+N.join(`
477
+ `);}b.set(E.name,{enrichment:L.trim()?L:"",nickname:P.nickname,description:P.description});}}}catch{}let a;try{let h=await D$1("paradigm_captain_brief",{taskDescription:t,symbols:l,depth:"standard"},e);h.handled&&(a=JSON.parse(h.text).renderedBrief);}catch{}let g=[];for(let h of i.stages){let m=[];for(let u of h.agents){let d=p.agents[u.name],k=b.get(u.name),R={name:d?.name||u.name,role:d?.role||U[u.name]||`${u.name} agent`,description:k?.description,focus:d?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:oe(u.name,e.rootDir,d),triggers:d?.triggers,handoff_to:d?.handoff_to,context:d?.context,protocol:d?.protocol},x=le({agent:R,task:u.task,symbols:l,dependsOn:u.dependsOn,profileEnrichment:k?.enrichment,nickname:k?.nickname,captainBrief:a});m.push(x);}g.push({stage:h.stage,canRunParallel:h.canRunParallel,agents:m});}let y=`orch-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`;Ye(e.rootDir,y,t,i);let{epicTaskId:A,agentTaskIds:T}=await Ne(e.rootDir,y,t,i);for(let h of g)for(let m of h.agents){let u=T.get(m.agent);u&&(m.taskId=u,m.prompt+=`
478
478
 
479
479
  ## Task tracking (v7 DAG)
480
- Your DAG task-id is \`${u}\`. On start, call \`paradigm_task_update({ id: "${u}", status: "in-progress" })\`; when finished, call \`paradigm_task_done({ id: "${u}" })\` (or \`paradigm_task_update\` \u2192 done) so the orchestration loop can settle.`);}try{let{appendSessionWorkEntry:h}=await import('./session-work-log-T2IE4Y4T.js');for(let m of p)for(let u of m.agents)h(e.rootDir,{timestamp:new Date().toISOString(),type:"agent-contribution",agent:u.agent,contribution:u.taskDescription?.slice(0,200)||t.slice(0,200),attribution:u.attribution,symbols:d});}catch{}try{let{recordAgentSession:h}=await import('./agent-state-KSQ3S7OB.js'),u=(await import('./session-tracker-BZ7FU4AT.js')).default?.session?.sessionId||f;for(let l of p)for(let w of l.agents)h(w.agent,e.rootDir,{sessionId:u,summary:`${w.attribution||w.agent}: ${(w.taskDescription||t).slice(0,200)}`,symbolsTouched:d});}catch{}let b=`thr-orch-${f}`;try{let h=await import('./symphony-loader-VA4UREOM.js'),m=Y.basename(e.rootDir),u=`${m}/maestro`;try{h.getMyIdentity(e.rootDir)||h.registerAgent(e.rootDir,"maestro","Maestro (orchestrator)");}catch{}h.createThread(`Orchestration: ${t.slice(0,80)}`,{id:u,name:"Maestro",type:"agent",project:m,role:"orchestrator"});let l=Y.join(ne.homedir(),".paradigm","score","threads"),w=D.readdirSync(l).filter(_=>_.endsWith(".json")).sort(),T=w[w.length-1];if(T){let _=Y.join(l,T),S=Y.join(l,`${b}.json`),v=JSON.parse(D.readFileSync(_,"utf8"));v.id=b,D.writeFileSync(S,JSON.stringify(v,null,2),"utf8"),_!==S&&D.unlinkSync(_);}for(let _ of p)for(let S of _.agents){let v=h.buildMessage({threadRoot:b,sender:{id:u,name:"Maestro",type:"agent",project:m,role:"orchestrator"},intent:"task",text:`[Maestro] Stage ${_.stage}: Assigned to ${S.attribution||S.agent} \u2014 ${S.taskDescription||t}`,symbols:d,metadata:{task:{stage:_.stage,canRunParallel:_.canRunParallel,...S.taskId?{taskId:S.taskId}:{}}}});h.routeMessage(v);}}catch{}let O$1={orchestrationId:f,task:t,mode:"execute",classification:{type:s.type,confidence:s.confidence,...s.alternativeType?{alternativeType:s.alternativeType}:{},overrideHint:s.overrideHint},symbols:d,totalAgents:i.estimatedAgents,...o.length>0?{activeNominations:o}:{},...A?{emittedTasks:{epicTaskId:A,stageTasks:p.flatMap(h=>h.agents.filter(m=>m.taskId).map(m=>({stage:h.stage,agent:m.agent,taskId:m.taskId})))}}:{},stages:p,executionInstructions:["Execute stages in order (stage 0, then stage 1, etc.)","Agents within a stage can be run in parallel if your environment supports it","Pass handoff context between stages",'Present each agent response as an attributed message using the attribution prefix (e.g., "[architect] Rate limiter should go before ^authenticated")',"Do NOT synthesize agent responses \u2014 show them as distinct contributions from each agent","After all agents in a stage complete, reconcile their outputs before proceeding to the next stage"],finalStep:{mandatory:true,description:"FINAL STEPS (mandatory, in order):",steps:[{order:1,action:"Call paradigm_captain_debrief",args:{orchestrationId:`${f} (use the orchestrationId from this response)`,sessionSummary:"(summarize what was accomplished)",touchedFiles:"(list all files modified during this session)",newSymbols:"(optional: list any new symbols registered)"}},{order:2,action:"Take the sessionInsights from the debrief result and call paradigm_ambient_learn_postflight",args:{sessionId:`${f} (use the orchestrationId from this response)`,context:"(pass the sessionInsights object from the debrief result here)"},note:"This is Loid's learning pass \u2014 she processes what the crew learned and ensures it compounds."},{order:3,action:"Session is complete."}],note:"Step 1 closes the session, updates .purpose coverage, records lore, and clears the stop hook. Step 2 runs Loid's learning pass on the session insights. Both steps are required \u2014 the session is NOT complete until both run."},claudeCode:{method:"Task tool",example:{description:p[0]?.agents[0]?.taskDescription||"Agent task",prompt:"(see agent prompts above)",subagent_type:"general-purpose"},parallel:"Launch multiple Task calls in one message for parallel stages"},sequential:{method:"Execute each role in sequence within this session",steps:i.stages.map((h,m)=>({stage:m,rolePrompt:`Adopt the ${h.agents[0]?.name} role. Focus ONLY on: ${h.agents.map(u=>u.task).join(", ")}`,constraint:m===0?"Design/plan only \u2014 do NOT write implementation code":m===i.stages.length-1?"Verify and test \u2014 do NOT change implementation":"Implement following the design from the previous stage"}))},cli:{method:"paradigm team orchestrate",command:`paradigm team orchestrate "${t}"`,note:"Spawns independent agent processes \u2014 works from any terminal"},symphony:{enabled:true,orchestrationThread:b,instructions:["After each agent completes, call paradigm_symphony_send to report progress. This makes the work visible in Conductor.",'Use intent "context" for analysis, "proposal" for recommendations, "decision" for decisions made',`Set threadRoot to "${b}" so all contributions are in one thread`,"Include the symbols array from the agent relay output"],perAgentInstruction:`When each agent finishes, run: paradigm_symphony_send threadId="${b}" intent="task-complete" text="[agentName] Summary of completed work" symbols=[touched symbols]`,exampleCall:{intent:"context",text:"[architect] Rate limiter should be placed before ^authenticated gate to prevent unauthenticated flood",threadRoot:b,symbols:["#rate-limiter","^authenticated"]}}},C=JSON.stringify(O$1,null,2);return O(C.length,"paradigm_orchestrate_inline"),{handled:true,text:C}}async function me(a,e,t,c,k,g){let n=a.toLowerCase(),d;try{let b=await D$1("paradigm_captain_brief",{taskDescription:a,symbols:e,depth:"quick"},g);if(b.handled){let O=JSON.parse(b.text);d={coverage:`${O.coverage?.label||"unknown"} (${Math.round((O.coverage?.score||0)*100)}%)`,warnings:O.warnings||[]};}}catch{}let o=[];t.securityRequired&&o.push("security-adjacent task (auth, gates, permissions detected)"),t.complexity==="high"&&o.push(`high complexity task (type: ${t.type})`),e.length>=4&&o.push(`${e.length} symbols in scope \u2014 cross-cutting change`);let s=c.filter(b=>b.urgency==="critical");s.length>0&&o.push(`${s.length} critical agent nomination(s) pending`);let i={assumptions:[],risks:[],edgeCases:[],questions:[]};(n.includes("simple")||n.includes("just")||n.includes("only"))&&i.assumptions.push("Task framed as simple \u2014 verify no hidden complexity"),(n.includes("always")||n.includes("never"))&&i.assumptions.push("Absolute language detected \u2014 edge cases likely exist"),!n.includes("error")&&!n.includes("fail")&&!n.includes("invalid")&&i.assumptions.push("No error/failure handling mentioned \u2014 what happens when it fails?"),e.some(b=>b.startsWith("$"))&&i.risks.push("Flow symbols detected \u2014 multi-step changes have ordering/rollback risk"),e.some(b=>b.startsWith("^"))&&(i.risks.push("Gate symbols detected \u2014 authorization changes require security review"),o.some(b=>b.includes("security"))||o.push("gate symbols in scope \u2014 security review recommended")),t.matchedKeywords.some(b=>["migration","database","schema"].includes(b))&&i.risks.push("Data migration risk \u2014 irreversible changes need rollback plan"),t.matchedKeywords.some(b=>["delete","remove","drop"].includes(b))&&i.risks.push("Destructive operation \u2014 verify nothing depends on removed items"),(n.includes("add")||n.includes("new"))&&i.edgeCases.push("New feature \u2014 how does it interact with existing features?"),(n.includes("refactor")||n.includes("rename"))&&i.edgeCases.push("Refactor \u2014 all callers updated? Integration tests cover the change?"),(n.includes("fix")||n.includes("bug"))&&i.edgeCases.push("Bug fix \u2014 does the fix address the root cause or just the symptom?"),n.includes("test")||i.questions.push("How will this be tested?"),e.length===0&&i.questions.push("No symbols referenced \u2014 which components are actually affected?");let y={concerns:[],suggestions:[]};for(let b of e){let O=b.replace(/^[#$^!~@&%?]/,"");!k.agents[O]&&b.startsWith("#");}t.costMultiplier.max>1&&y.concerns.push(`Higher-than-average complexity (${t.costMultiplier.min}x-${t.costMultiplier.max}x baseline) \u2014 consider breaking into smaller tasks`);let r=[];try{let{loadNotebookEntries:b}=await import('./notebook-loader-TZVIMNDJ.js'),O=e.map(h=>h.replace(/^[#$^!~@&%?]/,"").toLowerCase()),C=b("advocate",g.rootDir,O.length>0?{concepts:O}:void 0);C.length>0&&(r=C.sort((h,m)=>m.confidence-h.confidence).slice(0,3).map(h=>h.snippet));}catch{}let f=o.length>=2||o.some(b=>b.includes("security")||b.includes("critical"))?"escalate":"greenlight",A={mode:"quick",task:a,verdict:f,classification:{type:t.type,confidence:t.confidence,...t.alternativeType?{alternativeType:t.alternativeType}:{},overrideHint:t.overrideHint,complexity:t.complexity,securityRequired:t.securityRequired},advocate:{agent:"Jinx (advocate)",...i.assumptions.length>0?{assumptions:i.assumptions}:{},...i.risks.length>0?{risks:i.risks}:{},...i.edgeCases.length>0?{edgeCases:i.edgeCases}:{},...i.questions.length>0?{questions:i.questions}:{},...r.length>0?{notebookInsights:r}:{}},reviewer:{agent:"reviewer",...y.concerns.length>0?{concerns:y.concerns}:{},...y.suggestions.length>0?{suggestions:y.suggestions}:{}},...o.length>0?{escalationSignals:o}:{},...c.length>0?{activeNominations:c}:{},...d?{captainBrief:d}:{},symbols:e,instructions:f==="greenlight"?["Quick check passed \u2014 proceed with implementation.","Orchestration enforcement is satisfied.",i.questions.length>0?`Address Jinx's questions during implementation: ${i.questions.join("; ")}`:"No open questions from advocate."]:["Quick check recommends full orchestration.",`Escalation reasons: ${o.join("; ")}`,'Call paradigm_orchestrate_inline mode="plan" for full agent planning.',"Orchestration enforcement is satisfied regardless of verdict."]},R=JSON.stringify(A,null,2);return O(R.length,"paradigm_orchestrate_inline"),{handled:true,text:R}}async function he(a,e){let t=a.agent,c=a.task,k=a.handoffContext,g=a.previousAgent,n=re(e.rootDir),d=b$1(e.rootDir);if(d&&!d.includes(t)){let R=JSON.stringify({warning:`Agent "${t}" is not on this project's roster`,suggestion:`Run paradigm_agent_activate id="${t}" to add it, or check .paradigm/roster.yaml`,activeRoster:d},null,2);return O(R.length,"paradigm_agent_prompt"),{handled:true,text:R}}let o=n?.agents[t],s={name:o?.name||t,role:o?.role||U[t]||U.builder,focus:o?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:se(t,e.rootDir,o),triggers:o?.triggers,handoff_to:o?.handoff_to,context:o?.context,protocol:o?.protocol},i=H(c),y,r;try{let{loadAgentProfile:R,buildProfileEnrichment:b}=await import('./agent-loader-W3RQJVW7.js'),{loadDecisions:O}=await import('./decision-loader-HELL2AMX.js'),{loadJournalEntries:C}=await import('./journal-loader-CNNA4EAU.js'),{loadNominations:h}=await import('./nomination-engine-YRHZZZUN.js'),{loadNotebookEntries:m}=await import('./notebook-loader-TZVIMNDJ.js'),u=R(e.rootDir,t);if(u){r=u.nickname,s.description=u.description;let l=O(e.rootDir,{status:"active",limit:5}).map(v=>({title:v.title,decision:v.decision.slice(0,150)})),w=C(t,{transferable:!0,limit:5}).map(v=>({trigger:v.trigger,insight:v.insight.slice(0,150)})),T=h(e.rootDir,{pending_only:!0,limit:10}).map(v=>({urgency:v.urgency,brief:v.brief})),_;try{let v=i.map(x=>x.replace(/^[#$^!~@&%?]/,"").toLowerCase()),N=m(t,e.rootDir,v.length>0?{concepts:v}:void 0);if(N.length>0){let x=N.sort((E,P)=>P.confidence-E.confidence||new Date(P.updated).getTime()-new Date(E.updated).getTime()).slice(0,5);_=x.map(E=>({context:E.context,snippet:E.snippet,concepts:E.concepts}));try{let{recordNotebookReference:E}=await import('./session-work-log-T2IE4Y4T.js');E(e.rootDir,t,x.map(P=>P.id));}catch{}}}catch{}let S=b(u,i,_,{recentDecisions:l,journalInsights:w,pendingNominations:T});if(u.permissions){let v=[`
480
+ Your DAG task-id is \`${u}\`. On start, call \`paradigm_task_update({ id: "${u}", status: "in-progress" })\`; when finished, call \`paradigm_task_done({ id: "${u}" })\` (or \`paradigm_task_update\` \u2192 done) so the orchestration loop can settle.`);}try{let{appendSessionWorkEntry:h}=await import('./session-work-log-T2IE4Y4T.js');for(let m of g)for(let u of m.agents)h(e.rootDir,{timestamp:new Date().toISOString(),type:"agent-contribution",agent:u.agent,contribution:u.taskDescription?.slice(0,200)||t.slice(0,200),attribution:u.attribution,symbols:l});}catch{}try{let{recordAgentSession:h}=await import('./agent-state-KSQ3S7OB.js'),u=(await import('./session-tracker-BZ7FU4AT.js')).default?.session?.sessionId||y;for(let d of g)for(let k of d.agents)h(k.agent,e.rootDir,{sessionId:u,summary:`${k.attribution||k.agent}: ${(k.taskDescription||t).slice(0,200)}`,symbolsTouched:l});}catch{}let w=`thr-orch-${y}`;try{let h=await import('./symphony-loader-VA4UREOM.js'),m=Y.basename(e.rootDir),u=`${m}/maestro`;try{h.getMyIdentity(e.rootDir)||h.registerAgent(e.rootDir,"maestro","Maestro (orchestrator)");}catch{}h.createThread(`Orchestration: ${t.slice(0,80)}`,{id:u,name:"Maestro",type:"agent",project:m,role:"orchestrator"});let d=Y.join(ie.homedir(),".paradigm","score","threads"),k=D.readdirSync(d).filter(x=>x.endsWith(".json")).sort(),R=k[k.length-1];if(R){let x=Y.join(d,R),S=Y.join(d,`${w}.json`),v=JSON.parse(D.readFileSync(x,"utf8"));v.id=w,D.writeFileSync(S,JSON.stringify(v,null,2),"utf8"),x!==S&&D.unlinkSync(x);}for(let x of g)for(let S of x.agents){let v=h.buildMessage({threadRoot:w,sender:{id:u,name:"Maestro",type:"agent",project:m,role:"orchestrator"},intent:"task",text:`[Maestro] Stage ${x.stage}: Assigned to ${S.attribution||S.agent} \u2014 ${S.taskDescription||t}`,symbols:l,metadata:{task:{stage:x.stage,canRunParallel:x.canRunParallel,...S.taskId?{taskId:S.taskId}:{}}}});h.routeMessage(v);}}catch{}let O$1={orchestrationId:y,task:t,mode:"execute",classification:{type:s.type,confidence:s.confidence,...s.alternativeType?{alternativeType:s.alternativeType}:{},overrideHint:s.overrideHint},symbols:l,totalAgents:i.estimatedAgents,...o.length>0?{activeNominations:o}:{},...A?{emittedTasks:{epicTaskId:A,stageTasks:g.flatMap(h=>h.agents.filter(m=>m.taskId).map(m=>({stage:h.stage,agent:m.agent,taskId:m.taskId})))}}:{},stages:g,executionInstructions:["Execute stages in order (stage 0, then stage 1, etc.)","Agents within a stage can be run in parallel if your environment supports it","Pass handoff context between stages",'Present each agent response as an attributed message using the attribution prefix (e.g., "[architect] Rate limiter should go before ^authenticated")',"Do NOT synthesize agent responses \u2014 show them as distinct contributions from each agent","After all agents in a stage complete, reconcile their outputs before proceeding to the next stage"],finalStep:{mandatory:true,description:"FINAL STEPS (mandatory, in order):",steps:[{order:1,action:"Call paradigm_captain_debrief",args:{orchestrationId:`${y} (use the orchestrationId from this response)`,sessionSummary:"(summarize what was accomplished)",touchedFiles:"(list all files modified during this session)",newSymbols:"(optional: list any new symbols registered)"}},{order:2,action:"Take the sessionInsights from the debrief result and call paradigm_ambient_learn_postflight",args:{sessionId:`${y} (use the orchestrationId from this response)`,context:"(pass the sessionInsights object from the debrief result here)"},note:"This is Loid's learning pass \u2014 she processes what the crew learned and ensures it compounds."},{order:3,action:"Session is complete."}],note:"Step 1 closes the session, updates .purpose coverage, records lore, and clears the stop hook. Step 2 runs Loid's learning pass on the session insights. Both steps are required \u2014 the session is NOT complete until both run."},claudeCode:{method:"Task tool",example:{description:g[0]?.agents[0]?.taskDescription||"Agent task",prompt:"(see agent prompts above)",subagent_type:"general-purpose"},parallel:"Launch multiple Task calls in one message for parallel stages"},sequential:{method:"Execute each role in sequence within this session",steps:i.stages.map((h,m)=>({stage:m,rolePrompt:`Adopt the ${h.agents[0]?.name} role. Focus ONLY on: ${h.agents.map(u=>u.task).join(", ")}`,constraint:m===0?"Design/plan only \u2014 do NOT write implementation code":m===i.stages.length-1?"Verify and test \u2014 do NOT change implementation":"Implement following the design from the previous stage"}))},cli:{method:"paradigm team orchestrate",command:`paradigm team orchestrate "${t}"`,note:"Spawns independent agent processes \u2014 works from any terminal"},symphony:{enabled:true,orchestrationThread:w,instructions:["After each agent completes, call paradigm_symphony_send to report progress. This makes the work visible in Conductor.",'Use intent "context" for analysis, "proposal" for recommendations, "decision" for decisions made',`Set threadRoot to "${w}" so all contributions are in one thread`,"Include the symbols array from the agent relay output"],perAgentInstruction:`When each agent finishes, run: paradigm_symphony_send threadId="${w}" intent="task-complete" text="[agentName] Summary of completed work" symbols=[touched symbols]`,exampleCall:{intent:"context",text:"[architect] Rate limiter should be placed before ^authenticated gate to prevent unauthenticated flood",threadRoot:w,symbols:["#rate-limiter","^authenticated"]}}},C=JSON.stringify(O$1,null,2);return O(C.length,"paradigm_orchestrate_inline"),{handled:true,text:C}}async function ye(r,e,t,c,f,p){let n=r.toLowerCase(),l;try{let w=await D$1("paradigm_captain_brief",{taskDescription:r,symbols:e,depth:"quick"},p);if(w.handled){let O=JSON.parse(w.text);l={coverage:`${O.coverage?.label||"unknown"} (${Math.round((O.coverage?.score||0)*100)}%)`,warnings:O.warnings||[]};}}catch{}let o=[];t.securityRequired&&o.push("security-adjacent task (auth, gates, permissions detected)"),t.complexity==="high"&&o.push(`high complexity task (type: ${t.type})`),e.length>=4&&o.push(`${e.length} symbols in scope \u2014 cross-cutting change`);let s=c.filter(w=>w.urgency==="critical");s.length>0&&o.push(`${s.length} critical agent nomination(s) pending`);let i={assumptions:[],risks:[],edgeCases:[],questions:[]};(n.includes("simple")||n.includes("just")||n.includes("only"))&&i.assumptions.push("Task framed as simple \u2014 verify no hidden complexity"),(n.includes("always")||n.includes("never"))&&i.assumptions.push("Absolute language detected \u2014 edge cases likely exist"),!n.includes("error")&&!n.includes("fail")&&!n.includes("invalid")&&i.assumptions.push("No error/failure handling mentioned \u2014 what happens when it fails?"),e.some(w=>w.startsWith("$"))&&i.risks.push("Flow symbols detected \u2014 multi-step changes have ordering/rollback risk"),e.some(w=>w.startsWith("^"))&&(i.risks.push("Gate symbols detected \u2014 authorization changes require security review"),o.some(w=>w.includes("security"))||o.push("gate symbols in scope \u2014 security review recommended")),t.matchedKeywords.some(w=>["migration","database","schema"].includes(w))&&i.risks.push("Data migration risk \u2014 irreversible changes need rollback plan"),t.matchedKeywords.some(w=>["delete","remove","drop"].includes(w))&&i.risks.push("Destructive operation \u2014 verify nothing depends on removed items"),(n.includes("add")||n.includes("new"))&&i.edgeCases.push("New feature \u2014 how does it interact with existing features?"),(n.includes("refactor")||n.includes("rename"))&&i.edgeCases.push("Refactor \u2014 all callers updated? Integration tests cover the change?"),(n.includes("fix")||n.includes("bug"))&&i.edgeCases.push("Bug fix \u2014 does the fix address the root cause or just the symptom?"),n.includes("test")||i.questions.push("How will this be tested?"),e.length===0&&i.questions.push("No symbols referenced \u2014 which components are actually affected?");let b={concerns:[],suggestions:[]};for(let w of e){let O=w.replace(/^[#$^!~@&%?]/,"");!f.agents[O]&&w.startsWith("#");}t.costMultiplier.max>1&&b.concerns.push(`Higher-than-average complexity (${t.costMultiplier.min}x-${t.costMultiplier.max}x baseline) \u2014 consider breaking into smaller tasks`);let a=[];try{let{loadNotebookEntries:w}=await import('./notebook-loader-TZVIMNDJ.js'),O=e.map(h=>h.replace(/^[#$^!~@&%?]/,"").toLowerCase()),C=w("advocate",p.rootDir,O.length>0?{concepts:O}:void 0);C.length>0&&(a=C.sort((h,m)=>m.confidence-h.confidence).slice(0,3).map(h=>h.snippet));}catch{}let y=o.length>=2||o.some(w=>w.includes("security")||w.includes("critical"))?"escalate":"greenlight",A={mode:"quick",task:r,verdict:y,classification:{type:t.type,confidence:t.confidence,...t.alternativeType?{alternativeType:t.alternativeType}:{},overrideHint:t.overrideHint,complexity:t.complexity,securityRequired:t.securityRequired},advocate:{agent:"Jinx (advocate)",...i.assumptions.length>0?{assumptions:i.assumptions}:{},...i.risks.length>0?{risks:i.risks}:{},...i.edgeCases.length>0?{edgeCases:i.edgeCases}:{},...i.questions.length>0?{questions:i.questions}:{},...a.length>0?{notebookInsights:a}:{}},reviewer:{agent:"reviewer",...b.concerns.length>0?{concerns:b.concerns}:{},...b.suggestions.length>0?{suggestions:b.suggestions}:{}},...o.length>0?{escalationSignals:o}:{},...c.length>0?{activeNominations:c}:{},...l?{captainBrief:l}:{},symbols:e,instructions:y==="greenlight"?["Quick check passed \u2014 proceed with implementation.","Orchestration enforcement is satisfied.",i.questions.length>0?`Address Jinx's questions during implementation: ${i.questions.join("; ")}`:"No open questions from advocate."]:["Quick check recommends full orchestration.",`Escalation reasons: ${o.join("; ")}`,'Call paradigm_orchestrate_inline mode="plan" for full agent planning.',"Orchestration enforcement is satisfied regardless of verdict."]},T=JSON.stringify(A,null,2);return O(T.length,"paradigm_orchestrate_inline"),{handled:true,text:T}}async function be(r,e){let t=r.agent,c=r.task,f=r.handoffContext,p=r.previousAgent,n=ue(e.rootDir),l=b$1(e.rootDir);if(l&&!l.includes(t)){let T=JSON.stringify({warning:`Agent "${t}" is not on this project's roster`,suggestion:`Run paradigm_agent_activate id="${t}" to add it, or check .paradigm/roster.yaml`,activeRoster:l},null,2);return O(T.length,"paradigm_agent_prompt"),{handled:true,text:T}}let o=n?.agents[t],s={name:o?.name||t,role:o?.role||U[t]||U.builder,focus:o?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:oe(t,e.rootDir,o),triggers:o?.triggers,handoff_to:o?.handoff_to,context:o?.context,protocol:o?.protocol},i=K(c),b,a;try{let{loadAgentProfile:T,buildProfileEnrichment:w}=await import('./agent-loader-W3RQJVW7.js'),{loadDecisions:O}=await import('./decision-loader-HELL2AMX.js'),{loadJournalEntries:C}=await import('./journal-loader-CNNA4EAU.js'),{loadNominations:h}=await import('./nomination-engine-YRHZZZUN.js'),{loadNotebookEntries:m}=await import('./notebook-loader-TZVIMNDJ.js'),u=T(e.rootDir,t);if(u){a=u.nickname,s.description=u.description;let d=O(e.rootDir,{status:"active",limit:5}).map(v=>({title:v.title,decision:v.decision.slice(0,150)})),k=C(t,{transferable:!0,limit:5}).map(v=>({trigger:v.trigger,insight:v.insight.slice(0,150)})),R=h(e.rootDir,{pending_only:!0,limit:10}).map(v=>({urgency:v.urgency,brief:v.brief})),x;try{let v=i.map(_=>_.replace(/^[#$^!~@&%?]/,"").toLowerCase()),M=m(t,e.rootDir,v.length>0?{concepts:v}:void 0);if(M.length>0){let _=M.sort((E,P)=>P.confidence-E.confidence||new Date(P.updated).getTime()-new Date(E.updated).getTime()).slice(0,5);x=_.map(E=>({context:E.context,snippet:E.snippet,concepts:E.concepts}));try{let{recordNotebookReference:E}=await import('./session-work-log-T2IE4Y4T.js');E(e.rootDir,t,_.map(P=>P.id));}catch{}}}catch{}let S=w(u,i,x,{recentDecisions:d,journalInsights:k,pendingNominations:R});if(u.permissions){let v=[`
481
481
  ## Permission Constraints`];u.permissions.paths?.deny?.length&&v.push(`**Denied paths:** ${u.permissions.paths.deny.join(", ")}`),u.permissions.paths?.write?.length&&v.push(`**Writable paths:** ${u.permissions.paths.write.join(", ")}`),u.permissions.tools?.deny?.length&&v.push(`**Denied tools:** ${u.permissions.tools.deny.join(", ")}`),u.permissions.dangerous_actions?.length&&v.push(`**Requires approval for:** ${u.permissions.dangerous_actions.join(", ")}`),S+=`
482
482
  `+v.join(`
483
- `);}S.trim()&&(y=S);}}catch{}let p=oe({agent:s,task:c,symbols:i,handoffContext:k,previousAgent:g,profileEnrichment:y,nickname:r}),f={agent:t,model:p.model,prompt:p.prompt,attribution:p.attribution,taskToolParams:{description:p.taskDescription,prompt:p.prompt,subagent_type:p.subagentType,model:p.model},focusAreas:p.focusAreas,usage:"Use the Task tool with the taskToolParams to spawn this agent. Present the response with the attribution prefix."},A=JSON.stringify(f,null,2);return O(A.length,"paradigm_agent_prompt"),{handled:true,text:A}}function ie(a,e){let t=new Set(a),c=[];for(let k of a){let g=e[k];if(g?.handoff_to)for(let n of g.handoff_to)t.has(n)&&c.push({from:k,to:n});}return c}function fe(a,e){let t=ie(a,e);if(t.length===0)return null;let c=new Set,k=new Set(t.map(r=>`${r.from}->${r.to}`));for(let r of t)if(k.has(`${r.to}->${r.from}`)){let p=[r.from,r.to].sort().join(",");c.add(p);}let g=new Map;for(let r of c){let[p,f]=r.split(","),A=g.get(p)||p,R=g.get(f)||f,b=A<R?A:R;for(let[O,C]of g)(C===A||C===R)&&g.set(O,b);g.set(p,b),g.set(f,b);}for(let r of a)g.has(r)||g.set(r,r);let n=[...new Set(g.values())],d=new Map,o=new Map;for(let r of n)d.set(r,0),o.set(r,new Set);for(let r of t){let p=g.get(r.from),f=g.get(r.to);p!==f&&(o.get(p).has(f)||(o.get(p).add(f),d.set(f,(d.get(f)||0)+1)));}let s=new Map,i=[];for(let r of n)(d.get(r)||0)===0&&(i.push(r),s.set(r,0));for(;i.length>0;){let r=i.shift(),p=s.get(r)||0;for(let f of o.get(r)||[]){let A=(d.get(f)||1)-1;d.set(f,A);let R=p+1;s.set(f,Math.max(s.get(f)||0,R)),A===0&&i.push(f);}}if(s.size<n.length)return null;let y=new Map;for(let r of a){let p=g.get(r);y.set(r,s.get(p)||0);}return y}function ye(a,e,t,c,k,g){let n=H(a),d=a.toLowerCase(),o=[],s=[];if(t&&t.length>0)for(let l=0;l<t.length;l++){let w=t[l];e[w]&&s.push({name:w,task:`${w==="architect"?"Design":w==="builder"?"Implement":w==="tester"?"Test":"Process"}: ${a}`,dependsOn:l>0?[t[l-1]]:[],required:true,stage:l});}else if(c&&c.type!=="feature"&&c.type!=="unknown"){let l=c.recommendedAgents.length>0?c.recommendedAgents:["architect"],w={architect:Q(c.type)?"Analyze":"Design",security:Q(c.type)?"Assess security of":"Review security of",builder:"Implement",tester:"Test",reviewer:"Review"},T=0,_=null;for(let S of l){if(!e[S])continue;let v=_?[_]:[],N=w[S]||"Process",x=S==="architect"||S==="builder";s.push({name:S,task:`${N}: ${a}`,required:x,stage:T,dependsOn:v}),_=S,T++;}}else {let l=d.includes("design")||d.includes("architect")||d.includes("plan")||d.includes("spec"),w=d.includes("auth")||d.includes("security")||d.includes("gate")||n.some(x=>x.startsWith("^")),T=d.includes("build")||d.includes("implement")||d.includes("create")||d.includes("add")||d.includes("fix"),_=d.includes("review")||d.includes("check"),S=d.includes("test")||d.includes("verify")||d.includes("validate");if(l&&e.architect&&s.push({name:"architect",task:`Design and specify: ${a}`,dependsOn:[],required:true,stage:0}),w&&e.security&&s.push({name:"security",task:`Review security aspects of: ${a}`,dependsOn:[],required:false,stage:0}),T&&e.builder){let x=l&&e.architect?["architect"]:[];s.push({name:"builder",task:`Implement: ${a}`,dependsOn:x,required:true,stage:x.length>0?1:0});}let v=s.some(x=>x.name==="builder"),N=v?2:l?1:0;if(_&&e.reviewer&&s.push({name:"reviewer",task:`Review: ${a}`,dependsOn:v?["builder"]:[],required:false,stage:N}),S&&e.tester&&s.push({name:"tester",task:`Test and validate: ${a}`,dependsOn:v?["builder"]:[],required:false,stage:N}),s.length===0){let x=c?.recommendedAgents||["architect","builder","tester"],E={architect:"Design",security:"Review security of",builder:"Implement",tester:"Test",reviewer:"Review"},P=0,j=null;for(let I of x){if(!e[I])continue;let K=j?[j]:[],L=E[I]||"Process",M=I==="architect"||I==="builder";s.push({name:I,task:`${L}: ${a}`,required:M,stage:P,dependsOn:K}),j=I,P++;}}}let i=s.map(l=>l.name),y=fe(i,e);if(y)for(let l of s){l.stage=y.get(l.name)||0;let w=[];for(let T of i){if(T===l.name)continue;e[T]?.handoff_to?.includes(l.name)&&(y.get(T)||0)<l.stage&&w.push(T);}w.length>0&&(l.dependsOn=w);}let r=new Map;for(let l of s){let w=r.get(l.stage)||[];w.push(l),r.set(l.stage,w);}let p=Array.from(r.keys()).sort((l,w)=>l-w);for(let l of p){let w=r.get(l)||[];o.push({stage:l,agents:w.map(T=>({name:T.name,task:T.task,dependsOn:T.dependsOn,required:T.required})),canRunParallel:w.length>1});}let f=s.some(l=>l.name==="builder"||l.name==="tester"),R=(c?Q(c.type):false)||!f,b=false;if(!R){let l=p.length>0?p[p.length-1]+1:0;o.push({stage:l,agents:[{name:"documentor",task:"Review all changes made by previous agents. Update .purpose files, portal.yaml, and symbol registrations using only paradigm_purpose_* and paradigm_portal_* MCP tools. Run paradigm_reindex when done. Do NOT modify source code.",dependsOn:s.map(w=>w.name),required:true}],canRunParallel:false}),b=true;}let O=ue(g||"."),C=c?.type,h=0,m=0;for(let l of s){let w=pe(O,l.name,C);h+=w.min,m+=w.max;}b&&(h+=2e3,m+=8e3);let u=k?.default_mode||"faceted";return {task:a,mode:u,stages:o,symbols:n,estimatedAgents:s.length+(b?1:0),estimatedTokens:{min:h,max:m}}}function oe(a){let{agent:e,task:t,symbols:c,handoffContext:k,previousAgent:g}=a,n=[];a.profileEnrichment&&(n.push(a.profileEnrichment),n.push("---"),n.push("")),a.captainBrief&&(n.push(a.captainBrief),n.push(""));let d=U[e.name]||e.description||e.role||U.builder;if(n.push(d),n.push(""),n.push("---"),n.push(""),n.push("## Your Task"),n.push(""),n.push(t),n.push(""),c.length>0){n.push("## Symbols in Scope"),n.push("");for(let y of c){let r=be(y);n.push(`- \`${y}\` (${r})`);}n.push("");}k&&(n.push("## Context from Previous Agent"),g&&n.push(`*Handed off from ${g}:*`),n.push(""),n.push(k),n.push("")),(e.focus?.reads||e.focus?.writes)&&(n.push("## Focus Areas"),n.push(""),n.push(`**Read from:** ${e.focus?.reads?.join(", ")||"**/*"}`),n.push(`**Write to:** ${e.focus?.writes?.join(", ")||"**/*"}`),n.push("")),n.push(`## Output Format
483
+ `);}S.trim()&&(b=S);}}catch{}let g=le({agent:s,task:c,symbols:i,handoffContext:f,previousAgent:p,profileEnrichment:b,nickname:a}),y={agent:t,model:g.model,prompt:g.prompt,attribution:g.attribution,taskToolParams:{description:g.taskDescription,prompt:g.prompt,subagent_type:g.subagentType,model:g.model},focusAreas:g.focusAreas,usage:"Use the Task tool with the taskToolParams to spawn this agent. Present the response with the attribution prefix."},A=JSON.stringify(y,null,2);return O(A.length,"paradigm_agent_prompt"),{handled:true,text:A}}function ce(r,e){let t=new Set(r),c=[];for(let f of r){let p=e[f];if(p?.handoff_to)for(let n of p.handoff_to)t.has(n)&&c.push({from:f,to:n});}return c}function we(r,e){let t=ce(r,e);if(t.length===0)return null;let c=new Set,f=new Set(t.map(a=>`${a.from}->${a.to}`));for(let a of t)if(f.has(`${a.to}->${a.from}`)){let g=[a.from,a.to].sort().join(",");c.add(g);}let p=new Map;for(let a of c){let[g,y]=a.split(","),A=p.get(g)||g,T=p.get(y)||y,w=A<T?A:T;for(let[O,C]of p)(C===A||C===T)&&p.set(O,w);p.set(g,w),p.set(y,w);}for(let a of r)p.has(a)||p.set(a,a);let n=[...new Set(p.values())],l=new Map,o=new Map;for(let a of n)l.set(a,0),o.set(a,new Set);for(let a of t){let g=p.get(a.from),y=p.get(a.to);g!==y&&(o.get(g).has(y)||(o.get(g).add(y),l.set(y,(l.get(y)||0)+1)));}let s=new Map,i=[];for(let a of n)(l.get(a)||0)===0&&(i.push(a),s.set(a,0));for(;i.length>0;){let a=i.shift(),g=s.get(a)||0;for(let y of o.get(a)||[]){let A=(l.get(y)||1)-1;l.set(y,A);let T=g+1;s.set(y,Math.max(s.get(y)||0,T)),A===0&&i.push(y);}}if(s.size<n.length)return null;let b=new Map;for(let a of r){let g=p.get(a);b.set(a,s.get(g)||0);}return b}function ke(r,e,t,c,f,p){let n=K(r),l=r.toLowerCase(),o=[],s=[];if(t&&t.length>0)for(let d=0;d<t.length;d++){let k=t[d];e[k]&&s.push({name:k,task:`${k==="architect"?"Design":k==="builder"?"Implement":k==="tester"?"Test":"Process"}: ${r}`,dependsOn:d>0?[t[d-1]]:[],required:true,stage:d});}else if(c&&c.type!=="feature"&&c.type!=="unknown"){let d=c.recommendedAgents.length>0?c.recommendedAgents:["architect"],k={architect:Z(c.type)?"Analyze":"Design",security:Z(c.type)?"Assess security of":"Review security of",builder:"Implement",tester:"Test",reviewer:"Review"},R=0,x=null;for(let S of d){if(!e[S])continue;let v=x?[x]:[],M=k[S]||"Process",_=S==="architect"||S==="builder";s.push({name:S,task:`${M}: ${r}`,required:_,stage:R,dependsOn:v}),x=S,R++;}}else {let d=l.includes("design")||l.includes("architect")||l.includes("plan")||l.includes("spec"),k=l.includes("auth")||l.includes("security")||l.includes("gate")||n.some(_=>_.startsWith("^")),R=l.includes("build")||l.includes("implement")||l.includes("create")||l.includes("add")||l.includes("fix"),x=l.includes("review")||l.includes("check"),S=l.includes("test")||l.includes("verify")||l.includes("validate");if(d&&e.architect&&s.push({name:"architect",task:`Design and specify: ${r}`,dependsOn:[],required:true,stage:0}),k&&e.security&&s.push({name:"security",task:`Review security aspects of: ${r}`,dependsOn:[],required:false,stage:0}),R&&e.builder){let _=d&&e.architect?["architect"]:[];s.push({name:"builder",task:`Implement: ${r}`,dependsOn:_,required:true,stage:_.length>0?1:0});}let v=s.some(_=>_.name==="builder"),M=v?2:d?1:0;if(x&&e.reviewer&&s.push({name:"reviewer",task:`Review: ${r}`,dependsOn:v?["builder"]:[],required:false,stage:M}),S&&e.tester&&s.push({name:"tester",task:`Test and validate: ${r}`,dependsOn:v?["builder"]:[],required:false,stage:M}),s.length===0){let _=c?.recommendedAgents||["architect","builder","tester"],E={architect:"Design",security:"Review security of",builder:"Implement",tester:"Test",reviewer:"Review"},P=0,j=null;for(let I of _){if(!e[I])continue;let z=j?[j]:[],L=E[I]||"Process",N=I==="architect"||I==="builder";s.push({name:I,task:`${L}: ${r}`,required:N,stage:P,dependsOn:z}),j=I,P++;}}}let i=s.map(d=>d.name),b=we(i,e);if(b)for(let d of s){d.stage=b.get(d.name)||0;let k=[];for(let R of i){if(R===d.name)continue;e[R]?.handoff_to?.includes(d.name)&&(b.get(R)||0)<d.stage&&k.push(R);}k.length>0&&(d.dependsOn=k);}let a=new Map;for(let d of s){let k=a.get(d.stage)||[];k.push(d),a.set(d.stage,k);}let g=Array.from(a.keys()).sort((d,k)=>d-k);for(let d of g){let k=a.get(d)||[];o.push({stage:d,agents:k.map(R=>({name:R.name,task:R.task,dependsOn:R.dependsOn,required:R.required})),canRunParallel:k.length>1});}let y=s.some(d=>d.name==="builder"||d.name==="tester"),T=(c?Z(c.type):false)||!y,w=false;if(!T){let d=g.length>0?g[g.length-1]+1:0;o.push({stage:d,agents:[{name:"documentor",task:"Review all changes made by previous agents. Update .purpose files, portal.yaml, and symbol registrations using only paradigm_purpose_* and paradigm_portal_* MCP tools. Run paradigm_reindex when done. Do NOT modify source code.",dependsOn:s.map(k=>k.name),required:true}],canRunParallel:false}),w=true;}let O=ae(p||"."),C=c?.type,h=0,m=0;for(let d of s){let k=ee(O,d.name,C);h+=k.min,m+=k.max;}w&&(h+=2e3,m+=8e3);let u=f?.default_mode||"faceted";return {task:r,mode:u,stages:o,symbols:n,estimatedAgents:s.length+(w?1:0),estimatedTokens:{min:h,max:m}}}function le(r){let{agent:e,task:t,symbols:c,handoffContext:f,previousAgent:p}=r,n=[];r.profileEnrichment&&(n.push(r.profileEnrichment),n.push("---"),n.push("")),r.captainBrief&&(n.push(r.captainBrief),n.push(""));let l=U[e.name]||e.description||e.role||U.builder;if(n.push(l),n.push(""),n.push("---"),n.push(""),n.push("## Your Task"),n.push(""),n.push(t),n.push(""),c.length>0){n.push("## Symbols in Scope"),n.push("");for(let b of c){let a=ve(b);n.push(`- \`${b}\` (${a})`);}n.push("");}f&&(n.push("## Context from Previous Agent"),p&&n.push(`*Handed off from ${p}:*`),n.push(""),n.push(f),n.push("")),(e.focus?.reads||e.focus?.writes)&&(n.push("## Focus Areas"),n.push(""),n.push(`**Read from:** ${e.focus?.reads?.join(", ")||"**/*"}`),n.push(`**Write to:** ${e.focus?.writes?.join(", ")||"**/*"}`),n.push("")),n.push(`## Output Format
484
484
 
485
485
  When you complete your task, end with a structured summary block:
486
486
 
@@ -499,6 +499,6 @@ handoff_context: |
499
499
  \`\`\`
500
500
 
501
501
  This structured output helps track progress and pass context between agents.`);let o=n.join(`
502
- `),s=e.defaultModel||z[B[e.name]||"tier-2"]||"sonnet",i=a.nickname?`[${a.nickname} (${e.name})]`:`[${e.name}]`;return {agent:e.name,model:s,prompt:o,taskDescription:`${e.name}: ${t.slice(0,50)}${t.length>50?"...":""}`,subagentType:"general-purpose",attribution:i,focusAreas:e.focus||{reads:["**/*"],writes:["**/*"]}}}function H(a){let e=a.match(le)||[];return [...new Set(e)]}function be(a){let e=a.charAt(0);return {"@":"feature","#":"component",$:"flow","%":"state","^":"gate","!":"signal","?":"idea","&":"integration","~":"deprecated"}[e]||"unknown"}var we=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","pros and cons"],ke=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs"],ve=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","regression","patch"],Se=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify"],Ae=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","ownership","transfer","privilege","escalation","impersonation","takeover","rbac","acl","role","guard","middleware","session","cookie","csrf","xss","injection","sanitize"],_e=["audit","self-audit","inspect","examine","survey","inventory","find issues","identify problems","identify gaps","gap analysis","health check","sanity check","post-mortem","postmortem"],xe=["design","architect","architecture","spec","specify","specification","blueprint","plan","propose","proposal","rfc","schema design","api design","data model"],Re=["research","investigate","explore","study","discover","spike","prototype","feasibility","survey the","literature","prior art","options for","approaches to"],Te=new Set(["analysis","audit","design","research","documentation"]),Pe=[{pattern:/^(please\s+)?(audit|self-audit)\b/,family:"audit"},{pattern:/^(please\s+)?(analy[sz]e|assess|evaluate|examine|inspect|review)\b/,family:"analysis"},{pattern:/^(please\s+)?(design|architect|spec|specify|plan|propose)\b/,family:"design"},{pattern:/^(please\s+)?(research|investigate|explore|study)\b/,family:"research"},{pattern:/^(please\s+)?(document|write\s+docs)\b/,family:"documentation"}],Ee={audit:1.3,analysis:1.1,design:1.2,research:1.2,documentation:1.1,bugfix:1,refactor:1};function De(a){let e=a.toLowerCase(),t=H(a),c=m=>m.filter(u=>e.includes(u.toLowerCase())),k={audit:c(_e),analysis:c(we),design:c(xe),research:c(Re),documentation:c(ke),bugfix:c(ve),refactor:c(Se)},g=c(Ae),n={};for(let[m,u]of Object.entries(k))n[m]=u.length*(Ee[m]??1);let d;for(let{pattern:m,family:u}of Pe)if(m.test(e)){d=u,n[u]=(n[u]??0)+5;break}let o=Object.entries(n).filter(([,m])=>m>0).sort((m,u)=>u[1]-m[1]),s,i,y=0,r=0;o.length===0?s="feature":(s=o[0][0],y=o[0][1],i=o[1]?.[0],r=o.reduce((m,[,u])=>m+u,0));let p=r>0?y/r:.4;d&&(p=Math.max(p,.7)),p=Math.round(p*100)/100;let f=k[s]||[],A="medium",R=a.split(/\s+/).length;t.length>=5||R>=100?A="high":t.length<=1&&R<30&&(A="low");let b=g.length>0||t.some(m=>m.startsWith("^")),O={audit:["architect"],analysis:["architect"],design:["architect"],research:["architect"],documentation:["architect"],bugfix:["security","builder"],refactor:["architect","builder"],feature:["architect","security","builder","tester"]},C={audit:{min:.3,max:.5},analysis:{min:.3,max:.5},design:{min:.4,max:.7},research:{min:.3,max:.6},documentation:{min:.25,max:.45},bugfix:{min:.5,max:.8},refactor:{min:.6,max:.85},feature:{min:.8,max:1.2}},h=`classified ${s} (${p.toFixed(2)})`+(i?`; alt ${i}`:"")+"; override with agents:[...] if misrouted";return {type:s,confidence:p,...i?{alternativeType:i}:{},overrideHint:h,complexity:A,recommendedAgents:O[s]||["architect","builder"],securityRequired:b,costMultiplier:C[s]||{min:.8,max:1},matchedKeywords:f,symbols:t}}function Q(a){return Te.has(a)}var ee={opus:{input:15,output:75},sonnet:{input:3,output:15},haiku:{input:.25,output:1.25}},te={architect:{input:8e3,output:4e3},security:{input:6e3,output:3e3},reviewer:{input:5e3,output:2e3},builder:{input:15e3,output:1e4},tester:{input:8e3,output:5e3}};function Oe(a,e){let t=[],c=0,k=e.complexity==="high"?1.5:e.complexity==="low"?.6:1;for(let d of a.stages)for(let o of d.agents){let s=te[o.name]||{input:5e3,output:3e3},i=z[B[o.name]||"tier-2"]||"sonnet",y=ee[i],r=Math.round(s.input*k),p=Math.round(s.output*k),f=r+p,A=r/1e6*y.input+p/1e6*y.output;t.push({name:o.name,model:i,estimatedTokens:f,estimatedCost:Math.round(A*1e4)/1e4}),c+=A;}let g=0;for(let[d,o]of Object.entries(te)){let s=z[B[d]||"tier-2"]||"sonnet",i=ee[s];g+=o.input/1e6*i.input+o.output/1e6*i.output;}let n=g>0?c/g:1;return {agents:t,totalEstimatedCost:Math.round(c*1e4)/1e4,comparisonToBaseline:`${n.toFixed(2)}x`}}function Ce(a,e){let t=[],c=a.toLowerCase(),k=H(a);for(let[o,s]of Object.entries(e)){let i=[];for(let y of s.triggers||[]){if(y.type==="keyword"&&y.match)for(let r of y.match)c.includes(r.toLowerCase())&&i.push(`keyword:${r}`);if(y.type==="symbol"&&y.match)for(let r of y.match){let p=k.filter(f=>r.endsWith("*")?f.startsWith(r.slice(0,-1)):f===r);for(let f of p)i.push(`symbol:${f}`);}}if(i.length>0){let y=i.filter(b=>b.startsWith("keyword:")).length,r=i.filter(b=>b.startsWith("symbol:")).length,p=y>0&&r>0,f=i.length>=3||p?"high":i.length>=2?"medium":"low",A=s.role.split(`
503
- `)[0].trim(),R=A.length>50?A.slice(0,47)+"...":A;t.push({name:o,reason:R,confidence:f,triggers_matched:i});}}let g=new Set(t.map(o=>o.name)),n=[];for(let o of t){let s=e[o.name];if(s?.handoff_to)for(let i of s.handoff_to){if(g.has(i)||!e[i])continue;let y=e[i],r=[];for(let p of y.triggers||[]){if(p.type==="keyword"&&p.match)for(let f of p.match)c.includes(f.toLowerCase())&&r.push(`keyword:${f}`);if(p.type==="symbol"&&p.match)for(let f of p.match){let A=k.filter(R=>f.endsWith("*")?R.startsWith(f.slice(0,-1)):R===f);for(let R of A)r.push(`symbol:${R}`);}}if(r.length>0){g.add(i);let p=y.role.split(`
504
- `)[0].trim(),f=p.length>50?p.slice(0,47)+"...":p;n.push({name:i,reason:f,confidence:r.length>=2?"high":"medium",triggers_matched:[...r,`collaboration:handoff_from:${o.name}`]});}}}t.push(...n);let d={high:3,medium:2,low:1};return t.sort((o,s)=>d[s.confidence]-d[o.confidence])}function re(a){let e=Y.join(a,".paradigm","agents.yaml");if(!D.existsSync(e))return null;try{let t=D.readFileSync(e,"utf-8");return G.load(t)}catch{return null}}async function Ne(a$1,e,t,c){let k=new Map,g;try{let{createTask:n,updateTask:d}=await import('./task-loader-IO4UVFUD.js');g=await n(a$1,{blurb:t,priority:"medium",tags:["orchestration","epic"],claimant:{kind:"archetype",ref:"orchestrator"},external_ref:{provider:"orchestration",ref:e}});try{await d(a$1,g,{status:"in-progress"});}catch(o){a.flow("$dag-emission").warn("Epic promote to in-progress failed",{orchestrationId:e,epicTaskId:g,error:o instanceof Error?o.message:String(o)});}for(let o of c.stages)for(let s of o.agents)try{let i=(s.dependsOn||[]).map(r=>k.get(r)).filter(r=>typeof r=="string"),y=await n(a$1,{blurb:s.task,priority:"medium",tags:["orchestration"],claimant:{kind:"archetype",ref:s.name},parentTaskId:g,stage:o.stage,...i.length>0?{dependsOn:i}:{},external_ref:{provider:"orchestration",ref:e}});k.set(s.name,y);}catch(i){a.flow("$dag-emission").warn("Stage-agent task emission failed",{orchestrationId:e,agent:s.name,stage:o.stage,error:i instanceof Error?i.message:String(i)});}a.flow("$dag-emission").info("Emitted orchestration task DAG",{orchestrationId:e,epicTaskId:g,stageAgents:k.size});}catch(n){a.flow("$dag-emission").warn("Task DAG emission failed; orchestration continues",{orchestrationId:e,error:n instanceof Error?n.message:String(n)});}return {epicTaskId:g,agentTaskIds:k}}function Ie(a,e,t,c){let k=Y.join(a,".paradigm","orchestrations");D.existsSync(k)||D.mkdirSync(k,{recursive:true});let g=Y.join(k,`${e}.yaml`),n={id:e,task:t,created:new Date().toISOString(),status:"pending",mode:c.mode,symbols:c.symbols,estimatedAgents:c.estimatedAgents,estimatedTokens:c.estimatedTokens,stages:c.stages};try{D.writeFileSync(g,G.dump(n));}catch{}}function Me(a){let e=a?.filePlan;if(!(!e||e.length===0))return [{group:"all",subPhase:0,files:e.map(t=>({path:t,description:""}))}]}function Le(a){let e=Me(a);if(!e||e.length===0)return {hasFilePlan:false,stages:[{subPhase:0,builders:[{agent:"builder",group:"all",files:[],availableFiles:[]}]}],totalFiles:0,totalBuilders:1};let t=new Map;for(let o of e){let s=t.get(o.subPhase)||[];s.push(o),t.set(o.subPhase,s);}let c=[],k=[...t.keys()].sort((o,s)=>o-s),g=[],n=0,d=0;for(let o of k){let s=t.get(o),i=[];for(let y=0;y<s.length;y++){let r=s[y];d+=r.files.length,n++,i.push({agent:`builder-${o}-${y}`,group:r.group,files:r.files,availableFiles:[...g]});}c.push({subPhase:o,builders:i});for(let y of s)for(let r of y.files)g.push(r.path);}return {hasFilePlan:true,stages:c,totalFiles:d,totalBuilders:n}}export{ue as a,We as b,Fe as c,De as d,Ce as e,re as f,Ne as g,Le as h};
502
+ `),s=e.defaultModel||J[G[e.name]||"tier-2"]||"sonnet",i=r.nickname?`[${r.nickname} (${e.name})]`:`[${e.name}]`;return {agent:e.name,model:s,prompt:o,taskDescription:`${e.name}: ${t.slice(0,50)}${t.length>50?"...":""}`,subagentType:"general-purpose",attribution:i,focusAreas:e.focus||{reads:["**/*"],writes:["**/*"]}}}function K(r){let e=r.match(me)||[];return [...new Set(e)]}function ve(r){let e=r.charAt(0);return {"@":"feature","#":"component",$:"flow","%":"state","^":"gate","!":"signal","?":"idea","&":"integration","~":"deprecated"}[e]||"unknown"}var Se=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","pros and cons"],Ae=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs"],xe=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","regression","patch"],_e=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify"],Te=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","ownership","transfer","privilege","escalation","impersonation","takeover","rbac","acl","role","guard","middleware","session","cookie","csrf","xss","injection","sanitize"],Re=["audit","self-audit","inspect","examine","survey","inventory","find issues","identify problems","identify gaps","gap analysis","health check","sanity check","post-mortem","postmortem"],Pe=["design","architect","architecture","spec","specify","specification","blueprint","plan","propose","proposal","rfc","schema design","api design","data model"],Ee=["research","investigate","explore","study","discover","spike","prototype","feasibility","survey the","literature","prior art","options for","approaches to"],De=new Set(["analysis","audit","design","research","documentation"]),Oe=[{pattern:/^(please\s+)?(audit|self-audit)\b/,family:"audit"},{pattern:/^(please\s+)?(analy[sz]e|assess|evaluate|examine|inspect|review)\b/,family:"analysis"},{pattern:/^(please\s+)?(design|architect|spec|specify|plan|propose)\b/,family:"design"},{pattern:/^(please\s+)?(research|investigate|explore|study)\b/,family:"research"},{pattern:/^(please\s+)?(document|write\s+docs)\b/,family:"documentation"}],Ce={audit:1.3,analysis:1.1,design:1.2,research:1.2,documentation:1.1,bugfix:1,refactor:1};function de(r){let e=r.toLowerCase(),t=K(r),c=m=>m.filter(u=>e.includes(u.toLowerCase())),f={audit:c(Re),analysis:c(Se),design:c(Pe),research:c(Ee),documentation:c(Ae),bugfix:c(xe),refactor:c(_e)},p=c(Te),n={};for(let[m,u]of Object.entries(f))n[m]=u.length*(Ce[m]??1);let l;for(let{pattern:m,family:u}of Oe)if(m.test(e)){l=u,n[u]=(n[u]??0)+5;break}let o=Object.entries(n).filter(([,m])=>m>0).sort((m,u)=>u[1]-m[1]),s,i,b=0,a=0;o.length===0?s="feature":(s=o[0][0],b=o[0][1],i=o[1]?.[0],a=o.reduce((m,[,u])=>m+u,0));let g=a>0?b/a:.4;l&&(g=Math.max(g,.7)),g=Math.round(g*100)/100;let y=f[s]||[],A="medium",T=r.split(/\s+/).length;t.length>=5||T>=100?A="high":t.length<=1&&T<30&&(A="low");let w=p.length>0||t.some(m=>m.startsWith("^")),O={audit:["architect"],analysis:["architect"],design:["architect"],research:["architect"],documentation:["architect"],bugfix:["security","builder"],refactor:["architect","builder"],feature:["architect","security","builder","tester"]},C={audit:{min:.3,max:.5},analysis:{min:.3,max:.5},design:{min:.4,max:.7},research:{min:.3,max:.6},documentation:{min:.25,max:.45},bugfix:{min:.5,max:.8},refactor:{min:.6,max:.85},feature:{min:.8,max:1.2}},h=`classified ${s} (${g.toFixed(2)})`+(i?`; alt ${i}`:"")+"; override with agents:[...] if misrouted";return {type:s,confidence:g,...i?{alternativeType:i}:{},overrideHint:h,complexity:A,recommendedAgents:O[s]||["architect","builder"],securityRequired:w,costMultiplier:C[s]||{min:.8,max:1},matchedKeywords:y,symbols:t}}function Z(r){return De.has(r)}var ne={opus:{input:15,output:75},sonnet:{input:3,output:15},haiku:{input:.25,output:1.25}},se={architect:{input:8e3,output:4e3},security:{input:6e3,output:3e3},reviewer:{input:5e3,output:2e3},builder:{input:15e3,output:1e4},tester:{input:8e3,output:5e3}};function Me(r,e){let t=[],c=0,f=e.complexity==="high"?1.5:e.complexity==="low"?.6:1;for(let l of r.stages)for(let o of l.agents){let s=se[o.name]||{input:5e3,output:3e3},i=J[G[o.name]||"tier-2"]||"sonnet",b=ne[i],a=Math.round(s.input*f),g=Math.round(s.output*f),y=a+g,A=a/1e6*b.input+g/1e6*b.output;t.push({name:o.name,model:i,estimatedTokens:y,estimatedCost:Math.round(A*1e4)/1e4}),c+=A;}let p=0;for(let[l,o]of Object.entries(se)){let s=J[G[l]||"tier-2"]||"sonnet",i=ne[s];p+=o.input/1e6*i.input+o.output/1e6*i.output;}let n=p>0?c/p:1;return {agents:t,totalEstimatedCost:Math.round(c*1e4)/1e4,comparisonToBaseline:`${n.toFixed(2)}x`}}function Ie(r,e){let t=[],c=r.toLowerCase(),f=K(r);for(let[o,s]of Object.entries(e)){let i=[];for(let b of s.triggers||[]){if(b.type==="keyword"&&b.match)for(let a of b.match)c.includes(a.toLowerCase())&&i.push(`keyword:${a}`);if(b.type==="symbol"&&b.match)for(let a of b.match){let g=f.filter(y=>a.endsWith("*")?y.startsWith(a.slice(0,-1)):y===a);for(let y of g)i.push(`symbol:${y}`);}}if(i.length>0){let b=i.filter(w=>w.startsWith("keyword:")).length,a=i.filter(w=>w.startsWith("symbol:")).length,g=b>0&&a>0,y=i.length>=3||g?"high":i.length>=2?"medium":"low",A=s.role.split(`
503
+ `)[0].trim(),T=A.length>50?A.slice(0,47)+"...":A;t.push({name:o,reason:T,confidence:y,triggers_matched:i});}}let p=new Set(t.map(o=>o.name)),n=[];for(let o of t){let s=e[o.name];if(s?.handoff_to)for(let i of s.handoff_to){if(p.has(i)||!e[i])continue;let b=e[i],a=[];for(let g of b.triggers||[]){if(g.type==="keyword"&&g.match)for(let y of g.match)c.includes(y.toLowerCase())&&a.push(`keyword:${y}`);if(g.type==="symbol"&&g.match)for(let y of g.match){let A=f.filter(T=>y.endsWith("*")?T.startsWith(y.slice(0,-1)):T===y);for(let T of A)a.push(`symbol:${T}`);}}if(a.length>0){p.add(i);let g=b.role.split(`
504
+ `)[0].trim(),y=g.length>50?g.slice(0,47)+"...":g;n.push({name:i,reason:y,confidence:a.length>=2?"high":"medium",triggers_matched:[...a,`collaboration:handoff_from:${o.name}`]});}}}t.push(...n);let l={high:3,medium:2,low:1};return t.sort((o,s)=>l[s.confidence]-l[o.confidence])}function ue(r){let e=Y.join(r,".paradigm","agents.yaml");if(!D.existsSync(e))return null;try{let t=D.readFileSync(e,"utf-8");return H.load(t)}catch{return null}}async function Ne(r,e,t,c){let f=new Map,p;try{let{createTask:n,updateTask:l}=await import('./task-loader-LFEE6OU7.js');p=await n(r,{blurb:t,priority:"medium",tags:["orchestration","epic"],claimant:{kind:"archetype",ref:"orchestrator"},external_ref:{provider:"orchestration",ref:e}});try{await l(r,p,{status:"in-progress"});}catch(o){a.flow("$dag-emission").warn("Epic promote to in-progress failed",{orchestrationId:e,epicTaskId:p,error:o instanceof Error?o.message:String(o)});}for(let o of c.stages)for(let s of o.agents)try{let i=(s.dependsOn||[]).map(a=>f.get(a)).filter(a=>typeof a=="string"),b=await n(r,{blurb:s.task,priority:"medium",tags:["orchestration"],claimant:{kind:"archetype",ref:s.name},parentTaskId:p,stage:o.stage,...i.length>0?{dependsOn:i}:{},external_ref:{provider:"orchestration",ref:e}});f.set(s.name,b);}catch(i){a.flow("$dag-emission").warn("Stage-agent task emission failed",{orchestrationId:e,agent:s.name,stage:o.stage,error:i instanceof Error?i.message:String(i)});}a.flow("$dag-emission").info("Emitted orchestration task DAG",{orchestrationId:e,epicTaskId:p,stageAgents:f.size});}catch(n){a.flow("$dag-emission").warn("Task DAG emission failed; orchestration continues",{orchestrationId:e,error:n instanceof Error?n.message:String(n)});}return {epicTaskId:p,agentTaskIds:f}}function Ye(r,e,t,c){let f=Y.join(r,".paradigm","orchestrations");D.existsSync(f)||D.mkdirSync(f,{recursive:true});let p=Y.join(f,`${e}.yaml`),n={id:e,task:t,created:new Date().toISOString(),status:"pending",mode:c.mode,symbols:c.symbols,estimatedAgents:c.estimatedAgents,estimatedTokens:c.estimatedTokens,stages:c.stages};try{D.writeFileSync(p,H.dump(n));}catch{}}function $e(r){let e=r?.filePlan;if(!(!e||e.length===0))return [{group:"all",subPhase:0,files:e.map(t=>({path:t,description:""}))}]}function He(r){let e=$e(r);if(!e||e.length===0)return {hasFilePlan:false,stages:[{subPhase:0,builders:[{agent:"builder",group:"all",files:[],availableFiles:[]}]}],totalFiles:0,totalBuilders:1};let t=new Map;for(let o of e){let s=t.get(o.subPhase)||[];s.push(o),t.set(o.subPhase,s);}let c=[],f=[...t.keys()].sort((o,s)=>o-s),p=[],n=0,l=0;for(let o of f){let s=t.get(o),i=[];for(let b=0;b<s.length;b++){let a=s[b];l+=a.files.length,n++,i.push({agent:`builder-${o}-${b}`,group:a.group,files:a.files,availableFiles:[...p]});}c.push({subPhase:o,builders:i});for(let b of s)for(let a of b.files)p.push(a.path);}return {hasFilePlan:true,stages:c,totalFiles:l,totalBuilders:n}}export{ae as a,ee as b,Le as c,he as d,Be as e,Ge as f,Ue as g,de as h,Ie as i,ue as j,Ne as k,He as l};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {f,a}from'./chunk-ECLUYHAR.js';import {e}from'./chunk-YXLGVOZO.js';import {a as a$1}from'./chunk-FYDRENK7.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
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
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
4
  `),t.push(n["agent-guidelines"].overview),t.push("")),n?.["symbol-system"]){t.push(`## Symbol System
5
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