@oxgeneral/orch 1.0.7 → 1.0.8

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 (70) hide show
  1. package/dist/{App-LEVUTWQN.js → App-5OVBVRCD.js} +1 -1
  2. package/dist/{agent-Q34L27AY.js → agent-SI4JF5MV.js} +1 -1
  3. package/dist/{agent-shop-D2RS4BZK.js → agent-shop-JHDTCWCD.js} +1 -1
  4. package/dist/chunk-3AXNSYCM.js +2 -0
  5. package/dist/{chunk-BCPUTULS.js → chunk-HWEMBO36.js} +83 -54
  6. package/dist/chunk-J7ITYXE6.js +116 -0
  7. package/dist/chunk-J7ITYXE6.js.map +1 -0
  8. package/dist/{chunk-4TDXD3LA.js → chunk-SWNSNPBO.js} +12 -2
  9. package/dist/chunk-SWNSNPBO.js.map +1 -0
  10. package/dist/chunk-U2JVMD2G.js +66 -0
  11. package/dist/chunk-U2JVMD2G.js.map +1 -0
  12. package/dist/{chunk-EH3HRQP4.js → chunk-W3J7CURM.js} +8 -116
  13. package/dist/chunk-W3J7CURM.js.map +1 -0
  14. package/dist/chunk-ZMLF5HI5.js +11 -0
  15. package/dist/cli.js +1 -1
  16. package/dist/container-SEIWOLHY.js +4 -0
  17. package/dist/doctor-Q3GHJNZL.js +2 -0
  18. package/dist/index.d.ts +32 -1
  19. package/dist/index.js +12 -5
  20. package/dist/index.js.map +1 -1
  21. package/dist/init-D4356W7G.js +73 -0
  22. package/dist/orchestrator-G3Y7THMG.js +6 -0
  23. package/dist/{orchestrator-XPEMMBOO.js.map → orchestrator-G3Y7THMG.js.map} +1 -1
  24. package/dist/{orchestrator-JOTMB5XT.js → orchestrator-GQLNLOXB.js} +8 -4
  25. package/dist/{org-WAK3CDPG.js → org-KLYK6MMJ.js} +1 -1
  26. package/dist/skill-loader-IGRIELEM.js +9 -0
  27. package/dist/skill-loader-RHCFIK74.js +4 -0
  28. package/dist/skill-loader-RHCFIK74.js.map +1 -0
  29. package/dist/{task-QFLIIRKZ.js → task-3R2IX4HM.js} +1 -1
  30. package/dist/{tui-BJHZBCIR.js → tui-47O2OCKC.js} +1 -1
  31. package/dist/{workspace-manager-5EYCMAEO.js → workspace-manager-RH24FSNT.js} +4 -3
  32. package/dist/workspace-manager-RH24FSNT.js.map +1 -0
  33. package/dist/workspace-manager-VJ4FN5PJ.js +3 -0
  34. package/package.json +1 -1
  35. package/skills/library/autoplan.md +315 -0
  36. package/skills/library/benchmark.md +242 -0
  37. package/skills/library/browse.md +266 -0
  38. package/skills/library/canary.md +248 -0
  39. package/skills/library/careful.md +42 -0
  40. package/skills/library/codex.md +431 -0
  41. package/skills/library/design-consultation.md +367 -0
  42. package/skills/library/design-review.md +744 -0
  43. package/skills/library/document-release.md +365 -0
  44. package/skills/library/freeze.md +60 -0
  45. package/skills/library/guard.md +55 -0
  46. package/skills/library/investigate.md +171 -0
  47. package/skills/library/land-and-deploy.md +636 -0
  48. package/skills/library/office-hours.md +746 -0
  49. package/skills/library/plan-ceo-review.md +1029 -0
  50. package/skills/library/plan-design-review.md +428 -0
  51. package/skills/library/plan-eng-review.md +420 -0
  52. package/skills/library/qa-only.md +388 -0
  53. package/skills/library/qa.md +766 -0
  54. package/skills/library/retro.md +532 -0
  55. package/skills/library/review.md +421 -0
  56. package/skills/library/setup-browser-cookies.md +86 -0
  57. package/skills/library/setup-deploy.md +211 -0
  58. package/skills/library/ship.md +1018 -0
  59. package/skills/library/unfreeze.md +31 -0
  60. package/skills/library/upgrade.md +220 -0
  61. package/skills/orch/SKILL.md +138 -0
  62. package/dist/chunk-4TDXD3LA.js.map +0 -1
  63. package/dist/chunk-EH3HRQP4.js.map +0 -1
  64. package/dist/chunk-WVJTXBPL.js +0 -11
  65. package/dist/container-FXUUV6PP.js +0 -4
  66. package/dist/doctor-P2J6VAUX.js +0 -2
  67. package/dist/init-PTAYCSMO.js +0 -53
  68. package/dist/orchestrator-XPEMMBOO.js +0 -6
  69. package/dist/workspace-manager-5EYCMAEO.js.map +0 -1
  70. package/dist/workspace-manager-XKOZ5WM6.js +0 -3
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ import {f}from'./chunk-4MMHVHA6.js';import {a}from'./chunk-N4OXN2HW.js';import'./chunk-CHRW4CLD.js';import {b as b$1}from'./chunk-3AXNSYCM.js';import {k,j,c,a as a$1}from'./chunk-ZMLF5HI5.js';import {k as k$1,j as j$1,q}from'./chunk-64WUDYEM.js';import'./chunk-IKNBPOQL.js';import v from'path';import k$2 from'fs/promises';import {execFile}from'child_process';import {promisify}from'util';var x=`Agent architect \u2014 designs and creates AI agents for the orchestrator via \`orch agent add\`.
3
+
4
+ ## CREATION PROCESS
5
+
6
+ 1) ANALYZE \u2014 determine: agent function, required skills, adapter, team interactions.
7
+
8
+ 2) WRITE THE ROLE \u2014 this is the most important part. A good role includes:
9
+ - Identity and specialization (who you are)
10
+ - Concrete workflow (numbered steps)
11
+ - Which skills to invoke (\`/skill-name\`)
12
+ - Rules and constraints
13
+ Do NOT include CLI documentation or goal-mode instructions \u2014 these are already injected by the system prompt template.
14
+
15
+ 3) CHOOSE CONFIGURATION:
16
+ - adapter: \`claude\` (AI tasks), \`shell\` (bash scripts), \`codex\` (OpenAI Codex), \`cursor\` (Cursor IDE), \`opencode\` (OpenCode \u2014 multi-provider)
17
+ - model: \`claude-opus-4-6\` (complex/architectural), \`claude-sonnet-4-6\` (fast/routine), \`claude-haiku-4-5-20251001\` (simple/templated)
18
+ - approval_policy: \`auto\` (no confirmation) / \`suggest\` (proposes actions) / \`manual\` (human approval)
19
+ - max_turns: 50 (default), up to 100 for complex tasks
20
+
21
+ 4) CREATE:
22
+ \`orch agent add "<name>" --adapter claude --model <model> --skills "<skills>" --role "<role>" --approval-policy auto\`
23
+
24
+ ## SKILL TYPES
25
+
26
+ There are two types of skills:
27
+
28
+ **Library skills** \u2014 ORCH loads Markdown content and injects it into the agent's system prompt. Works with ALL adapters (claude, opencode, codex, cursor, shell). Use plain names without colons:
29
+
30
+ | Category | Skills |
31
+ |----------|--------|
32
+ | Code Review & QA | review, qa, qa-only, investigate |
33
+ | Planning | plan-ceo-review, plan-eng-review, plan-design-review, autoplan, office-hours |
34
+ | Design | design-consultation, design-review |
35
+ | Shipping | ship, land-and-deploy, canary, document-release |
36
+ | Infrastructure | browse, benchmark, setup-deploy, setup-browser-cookies |
37
+ | Safety | careful, freeze, unfreeze, guard |
38
+ | Cross-AI | codex |
39
+ | Meta | upgrade, retro |
40
+
41
+ **Claude Code MCP skills** \u2014 handled natively by Claude CLI. Use \`package:skill-name\` format (with colon):
42
+
43
+ Development: feature-dev:feature-dev, feature-dev:code-explorer, feature-dev:code-architect, feature-dev:code-reviewer
44
+ Testing: testing-suite:generate-tests, testing-suite:test-coverage, testing-suite:e2e-setup, testing-suite:test-quality-analyzer
45
+ Frontend: frontend-design:frontend-design, document-skills:frontend-design
46
+ Documents: document-skills:pdf, document-skills:xlsx, document-skills:docx, document-skills:pptx
47
+ Marketing: marketing-psychology, product-manager-toolkit
48
+ DevOps: devops-automation:cloud-architect
49
+
50
+ You can mix both types: \`--skills "review,feature-dev:code-explorer,investigate"\`
51
+
52
+ ## ANTI-PATTERNS
53
+
54
+ - Never create agents without skills \u2014 they cannot be auto-matched to tasks.
55
+ - Never write generic roles like "helper" \u2014 be specific about actions and tools.
56
+ - Never use opus for simple tasks \u2014 it is expensive; use sonnet or haiku.
57
+ - Never assign more than 3-4 skills per agent \u2014 create specialized agents instead.
58
+ - Never use the -e/--edit flag in automated mode \u2014 it opens an interactive editor.
59
+ - Always specify --role when calling \`orch agent add\`.
60
+
61
+ After creation \u2014 \`orch context set agent-<name> "<capabilities>"\`.`;function w(){return [{id:"agt_creator",name:"Agent Creator",adapter:"claude",role:x,config:{model:"claude-sonnet-4-6",approval_policy:"suggest",max_turns:50,timeout_ms:36e5,stall_timeout_ms:3e5,skills:["document-skills:skill-creator"]},status:"idle",stats:{tasks_completed:0,tasks_failed:0,total_runs:0,total_runtime_ms:0}}]}var l=promisify(execFile);async function P(t={}){let o=process.cwd(),e=new b$1(o);if(await k(e.root)){k$1("Already initialized");return}await Promise.all([j(e.tasksDir),j(e.agentsDir),j(e.goalsDir),j(e.runsDir),j(e.templatesDir),j(e.logsDir)]);let c$1=await I(o),s=structuredClone(a);s.project.name=t.name??v.basename(o),c$1||(s.defaults.agent.workspace_mode="shared");let A=["# Runtime state","state.json","*.lock","","# Logs and runs","runs/","logs/","","# Agent workspaces","workspaces/"].join(`
62
+ `)+`
63
+ `,C=[".orchestry","node_modules",".env",".env.*","dist","build",".next","__pycache__","*.pyc",".venv"].join(`
64
+ `)+`
65
+ `,m=w();await Promise.all([c(e.configPath,s),a$1(e.gitignorePath,A),a$1(e.workspaceExcludePath,C),a$1(e.defaultTemplatePath(),f),...m.map(i=>c(e.agentPath(i.id),i))]),await b(o),c$1&&await T(o),console.log(),j$1("initialized"),console.log(),console.log(` Created ${q(".orchestry/")}`),console.log(` ${q("\u251C\u2500\u2500")} config.yml`),console.log(` ${q("\u251C\u2500\u2500")} tasks/`),console.log(` ${q("\u251C\u2500\u2500")} agents/`);for(let i of m)console.log(` ${q("\u2502 \u2514\u2500\u2500")} ${i.id}.yml ${q(`(${i.name})`)}`);console.log(` ${q("\u251C\u2500\u2500")} templates/default.md`),console.log(` ${q("\u2514\u2500\u2500")} .gitignore`),console.log();}async function I(t){try{return await l("git",["rev-parse","--is-inside-work-tree"],{cwd:t}),!0}catch{try{return await l("git",["init"],{cwd:t}),!0}catch{return false}}}async function T(t){try{await l("git",["rev-parse","HEAD"],{cwd:t});}catch{try{await l("git",["add","-A"],{cwd:t}),await l("git",["commit","-m","Initial commit","--allow-empty"],{cwd:t});}catch{}}}async function b(t){let o=v.join(t,".gitignore");try{let e=await k$2.readFile(o,"utf-8");if(e.split(`
66
+ `).some(s=>s.trim()===".orchestry"))return;let c=e.endsWith(`
67
+ `)?"":`
68
+ `;await k$2.appendFile(o,`${c}
69
+ # Orchestry state
70
+ .orchestry
71
+ `);}catch{await a$1(o,`# Orchestry state
72
+ .orchestry
73
+ `);}}function W(t){t.command("init").description("Initialize .orchestry/ in the current directory").option("--name <name>","Project name").action(async o=>{await P(o),console.log(` Next: ${q('orch task add "Create backend agent" --assignee agt_creator')}`),console.log();});}export{W as registerInitCommand,P as runInit};
@@ -0,0 +1,6 @@
1
+ export { Orchestrator } from './chunk-SWNSNPBO.js';
2
+ import './chunk-VG4465AG.js';
3
+ import './chunk-RHFRHCN5.js';
4
+ import './chunk-NLQAJ7TW.js';
5
+ //# sourceMappingURL=orchestrator-G3Y7THMG.js.map
6
+ //# sourceMappingURL=orchestrator-G3Y7THMG.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"orchestrator-XPEMMBOO.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"orchestrator-G3Y7THMG.js"}
@@ -1,13 +1,17 @@
1
1
  #!/usr/bin/env node
2
- import {d as d$2,e as e$2,c as c$1}from'./chunk-4MMHVHA6.js';import {e,c,b as b$1,d as d$1,f,g}from'./chunk-KR7VDF23.js';import {a}from'./chunk-CHRW4CLD.js';import {a as a$1}from'./chunk-P4JTJBWO.js';import {d,l,h,e as e$1,n}from'./chunk-IKNBPOQL.js';import {dirname}from'path';import _ from'fs/promises';import {execFile}from'child_process';function et(d,t){if(!d?.length||!t?.length)return false;for(let e of d)for(let s of t)if(ht(e,s))return true;return false}function O(d){let t=d.split("*")[0],e=!t.endsWith("/"),s=e?dirname(t):"";return {raw:d,base:t,isFile:e,dir:s}}var b=class{entries;constructor(t){this.entries=[];for(let e of t)if(e?.length)for(let s of e)this.entries.push(O(s));}overlapsAny(t){if(!t?.length||this.entries.length===0)return false;for(let e of t){let s=O(e);for(let a of this.entries)if(ut(s,a))return true}return false}add(t){if(t?.length)for(let e of t)this.entries.push(O(e));}get size(){return this.entries.length}};function ut(d,t){return d.raw===t.raw||d.base.startsWith(t.base)||t.base.startsWith(d.base)?true:d.isFile&&t.isFile?d.dir===t.dir&&d.dir!==".":false}function ht(d,t){if(d===t)return true;let e=d.split("*")[0],s=t.split("*")[0];if(e.startsWith(s)||s.startsWith(e))return true;if(!e.endsWith("/")&&!s.endsWith("/")){let a=dirname(e),r=dirname(s);return a===r&&a!=="."}return false}var st=Promise.resolve();async function q(d){let t,e=new Promise(a=>{t=a;}),s=st;st=e,await s;try{return await ft(d)}finally{t();}}var pt=6e4;async function ft(d){let t=await it(d);if(t!==null){if(mt(t)&&!await gt(d))return {acquired:false,pid:t};await _.unlink(d).catch(()=>{});}try{let e=await _.open(d,"wx");return await e.writeFile(String(process.pid),"utf-8"),await e.close(),{acquired:!0,pid:process.pid}}catch(e){if(e.code==="EEXIST")return {acquired:false,pid:await it(d)??void 0};throw e}}async function G(d){await _.unlink(d).catch(()=>{});}async function at(d){let t=Date.now()/1e3;await _.utimes(d,t,t).catch(()=>{});}async function it(d){try{let t=await _.readFile(d,"utf-8"),e=parseInt(t.trim(),10);return isNaN(e)?null:e}catch{return null}}async function gt(d){try{let t=await _.stat(d);return Date.now()-t.mtimeMs>pt}catch{return true}}function mt(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}var D=class{constructor(t){this.inner=t;}cache=new Map;async list(t){let e=t?`${t.status??""}:${t.goalId??""}`:"__all__";if(this.cache.has(e))return this.cache.get(e);let s=await this.inner.list(t);return this.cache.set(e,s),s}async get(t){return this.inner.get(t)}async save(t){await this.inner.save(t),this.cache.clear();}async delete(t){await this.inner.delete(t),this.cache.clear();}invalidate(){this.cache.clear();}},C=class{constructor(t){this.inner=t;}listCache=null;nameCache=new Map;async list(){if(this.listCache)return this.listCache;let t=await this.inner.list();return this.listCache=t,t}async get(t){return this.inner.get(t)}async getByName(t){if(this.nameCache.has(t))return this.nameCache.get(t)??null;let e=await this.inner.getByName(t);return this.nameCache.set(t,e),e}async save(t){await this.inner.save(t),this.listCache=null,this.nameCache.clear();}async delete(t){await this.inner.delete(t),this.listCache=null,this.nameCache.clear();}invalidate(){this.listCache=null,this.nameCache.clear();}},B=class{constructor(t){this.inner=t;}cache=new Map;async list(t){let e=t?.status??"__all__";if(this.cache.has(e))return this.cache.get(e);let s=await this.inner.list(t);return this.cache.set(e,s),s}async get(t){return this.inner.get(t)}async save(t){await this.inner.save(t),this.cache.clear();}async delete(t){await this.inner.delete(t),this.cache.clear();}invalidate(){this.cache.clear();}};var wt={test_pass:{cmd:"npm",args:["test"]},typecheck:{cmd:"npx",args:["tsc","--noEmit"]},lint:{cmd:"npm",args:["run","lint"]}},T=class{cwd;timeoutMs;constructor(t){this.cwd=t.cwd,this.timeoutMs=t.timeout_ms??12e4;}async runAll(t){let e=[];for(let s of t){let a=await this.runCriterion(s);e.push(a);}return e}static allPassed(t){return t.length>0&&t.every(e=>e.passed)}static formatReport(t){return t.map(s=>{let a=s.passed?"\u2713":"\u2717",r=s.output.slice(0,500);return `${a} ${s.criterion}: ${s.passed?"PASSED":"FAILED"}
2
+ import {d as d$2,e as e$2,c as c$1}from'./chunk-4MMHVHA6.js';import {e,c,b as b$1,d as d$1,f,g}from'./chunk-KR7VDF23.js';import {a}from'./chunk-CHRW4CLD.js';import {a as a$1}from'./chunk-P4JTJBWO.js';import {d,l,h,e as e$1,n}from'./chunk-IKNBPOQL.js';import {dirname}from'path';import T from'fs/promises';import {execFile}from'child_process';function et(d,t){if(!d?.length||!t?.length)return false;for(let e of d)for(let s of t)if(ht(e,s))return true;return false}function O(d){let t=d.split("*")[0],e=!t.endsWith("/"),s=e?dirname(t):"";return {raw:d,base:t,isFile:e,dir:s}}var b=class{entries;constructor(t){this.entries=[];for(let e of t)if(e?.length)for(let s of e)this.entries.push(O(s));}overlapsAny(t){if(!t?.length||this.entries.length===0)return false;for(let e of t){let s=O(e);for(let a of this.entries)if(ut(s,a))return true}return false}add(t){if(t?.length)for(let e of t)this.entries.push(O(e));}get size(){return this.entries.length}};function ut(d,t){return d.raw===t.raw||d.base.startsWith(t.base)||t.base.startsWith(d.base)?true:d.isFile&&t.isFile?d.dir===t.dir&&d.dir!==".":false}function ht(d,t){if(d===t)return true;let e=d.split("*")[0],s=t.split("*")[0];if(e.startsWith(s)||s.startsWith(e))return true;if(!e.endsWith("/")&&!s.endsWith("/")){let a=dirname(e),r=dirname(s);return a===r&&a!=="."}return false}var st=Promise.resolve();async function q(d){let t,e=new Promise(a=>{t=a;}),s=st;st=e,await s;try{return await ft(d)}finally{t();}}var pt=6e4;async function ft(d){let t=await it(d);if(t!==null){if(mt(t)&&!await gt(d))return {acquired:false,pid:t};await T.unlink(d).catch(()=>{});}try{let e=await T.open(d,"wx");return await e.writeFile(String(process.pid),"utf-8"),await e.close(),{acquired:!0,pid:process.pid}}catch(e){if(e.code==="EEXIST")return {acquired:false,pid:await it(d)??void 0};throw e}}async function G(d){await T.unlink(d).catch(()=>{});}async function at(d){let t=Date.now()/1e3;await T.utimes(d,t,t).catch(()=>{});}async function it(d){try{let t=await T.readFile(d,"utf-8"),e=parseInt(t.trim(),10);return isNaN(e)?null:e}catch{return null}}async function gt(d){try{let t=await T.stat(d);return Date.now()-t.mtimeMs>pt}catch{return true}}function mt(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}var D=class{constructor(t){this.inner=t;}cache=new Map;async list(t){let e=t?`${t.status??""}:${t.goalId??""}`:"__all__";if(this.cache.has(e))return this.cache.get(e);let s=await this.inner.list(t);return this.cache.set(e,s),s}async get(t){return this.inner.get(t)}async save(t){await this.inner.save(t),this.cache.clear();}async delete(t){await this.inner.delete(t),this.cache.clear();}invalidate(){this.cache.clear();}},C=class{constructor(t){this.inner=t;}listCache=null;nameCache=new Map;async list(){if(this.listCache)return this.listCache;let t=await this.inner.list();return this.listCache=t,t}async get(t){return this.inner.get(t)}async getByName(t){if(this.nameCache.has(t))return this.nameCache.get(t)??null;let e=await this.inner.getByName(t);return this.nameCache.set(t,e),e}async save(t){await this.inner.save(t),this.listCache=null,this.nameCache.clear();}async delete(t){await this.inner.delete(t),this.listCache=null,this.nameCache.clear();}invalidate(){this.listCache=null,this.nameCache.clear();}},B=class{constructor(t){this.inner=t;}cache=new Map;async list(t){let e=t?.status??"__all__";if(this.cache.has(e))return this.cache.get(e);let s=await this.inner.list(t);return this.cache.set(e,s),s}async get(t){return this.inner.get(t)}async save(t){await this.inner.save(t),this.cache.clear();}async delete(t){await this.inner.delete(t),this.cache.clear();}invalidate(){this.cache.clear();}};var St={test_pass:{cmd:"npm",args:["test"]},typecheck:{cmd:"npx",args:["tsc","--noEmit"]},lint:{cmd:"npm",args:["run","lint"]}},A=class{cwd;timeoutMs;constructor(t){this.cwd=t.cwd,this.timeoutMs=t.timeout_ms??12e4;}async runAll(t){let e=[];for(let s of t){let a=await this.runCriterion(s);e.push(a);}return e}static allPassed(t){return t.length>0&&t.every(e=>e.passed)}static formatReport(t){return t.map(s=>{let a=s.passed?"\u2713":"\u2717",r=s.output.slice(0,500);return `${a} ${s.criterion}: ${s.passed?"PASSED":"FAILED"}
3
3
  ${r}`}).join(`
4
4
 
5
- `)}runCriterion(t){let{cmd:e,args:s}=wt[t];return new Promise(a=>{execFile(e,s,{cwd:this.cwd,timeout:this.timeoutMs,maxBuffer:1024*1024},(r,u,n)=>{let l=(u+`
6
- `+n).trim();a({criterion:t,passed:!r,output:l.slice(0,2e3)});});})}};var St=8192,yt=4096,rt=class{constructor(t){this.deps=t;this.cachedTaskStore=new D(t.taskStore),this.cachedAgentStore=new C(t.agentStore),this.cachedGoalStore=t.goalStore?new B(t.goalStore):null;}intervalId=null;shuttingDown=false;state=null;abortControllers=new Map;cachedTaskStore;cachedAgentStore;cachedGoalStore;saveStateTimer=null;saveStateDirty=false;lockAcquired=false;consecutiveTickFailures=0;maxConsecutiveTickFailures=5;maxRetryQueueSize=100;signalHandlers=[];immediateDispatchTimer=null;taskCreatedUnsub=null;tickInProgress=false;stoppedResolvers=[];skipAutonomousSeeding=false;stateMutex=Promise.resolve();get isOwner(){return this.lockAcquired}withStateLock(t){let e,s=new Promise(r=>{e=r;}),a=this.stateMutex;return this.stateMutex=s,a.then(async()=>{try{return await t()}finally{e();}})}async runTask(t){if(this.lockAcquired){await this.freshDispatch(()=>this.dispatchTask(t));return}await this.withTemporaryLock(()=>this.freshDispatch(()=>this.dispatchTask(t)));}async runAll(){if(this.lockAcquired){await this.freshDispatch(()=>this.dispatchAll());return}await this.withTemporaryLock(()=>this.freshDispatch(()=>this.dispatchAll()));}async freshDispatch(t){await this.withStateLock(async()=>{this.cachedTaskStore.invalidate(),this.cachedAgentStore.invalidate(),await this.loadState(),await t(),await this.saveState();});}async withTemporaryLock(t){let e=await q(this.deps.lockPath);if(!e.acquired)throw new d(e.pid);this.lockAcquired=true;try{await t();}finally{this.lockAcquired=false,await G(this.deps.lockPath);}}async startWatch(t){this.skipAutonomousSeeding=t?.skipAutonomousSeeding??false;let e=await q(this.deps.lockPath);if(!e.acquired)throw new d(e.pid);this.lockAcquired=true,await this.loadState(),await this.cleanupStaleRunningEntries(),this.state.pid=process.pid,this.state.started_at=new Date().toISOString(),await this.saveState(),this.registerSignalHandlers(),this.taskCreatedUnsub=this.deps.eventBus.on("task:created",()=>{this.scheduleImmediateDispatch();}),await this.tick(),this.intervalId=setInterval(()=>this.tick().then(()=>{this.consecutiveTickFailures=0;},s=>{this.consecutiveTickFailures++;let a=s instanceof Error?s.message:String(s);this.deps.eventBus.emit({type:"orchestrator:error",error:a,context:"tick",fatal:this.consecutiveTickFailures>=this.maxConsecutiveTickFailures}),this.consecutiveTickFailures>=this.maxConsecutiveTickFailures&&(this.deps.eventBus.emit({type:"orchestrator:shutdown",reason:`${this.consecutiveTickFailures} consecutive tick failures`}),this.stop().catch(r=>{this.deps.eventBus.emit({type:"orchestrator:error",error:r instanceof Error?r.message:String(r),context:"stop after consecutive tick failures",fatal:false});}));}),this.deps.config.scheduling.poll_interval_ms);}waitForStop(){return this.shuttingDown?Promise.resolve():new Promise(t=>{this.stoppedResolvers.push(t);})}registerSignalHandlers(){let t=e=>{this.deps.eventBus.emit({type:"orchestrator:shutdown",reason:`Received ${e}`}),this.stop().catch(s=>{this.deps.eventBus.emit({type:"orchestrator:error",error:s instanceof Error?s.message:String(s),context:`stop after ${e} signal`,fatal:false});});};for(let e of ["SIGINT","SIGTERM"]){let s=()=>t(e);this.signalHandlers.push([e,s]),process.on(e,s);}}removeSignalHandlers(){for(let[t,e]of this.signalHandlers)process.removeListener(t,e);this.signalHandlers=[];}async stop(){if(!this.shuttingDown){this.shuttingDown=true,this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.taskCreatedUnsub&&(this.taskCreatedUnsub(),this.taskCreatedUnsub=null),this.immediateDispatchTimer&&(clearTimeout(this.immediateDispatchTimer),this.immediateDispatchTimer=null),await this.flushStateLazy(),await this.withStateLock(async()=>{if(this.state){for(let[t,e$1]of Object.entries(this.state.running)){this.abortControllers.get(t)?.abort(),this.abortControllers.delete(t),await this.deps.processManager.killWithGrace(e$1.pid),await this.deps.runService.finish(e$1.run_id,"cancelled");let s=await this.deps.taskStore.get(t);s&&await this.deps.taskService.updateStatus(t,e(s)),await this.deps.agentService.setStatus(e$1.agent_id,"idle");}this.state.running={},this.state.claimed=new Set,this.state.pid=void 0,this.state.started_at=void 0,await this.saveState();}}),this.lockAcquired&&(await G(this.deps.lockPath),this.lockAcquired=false),this.removeSignalHandlers();for(let t of this.stoppedResolvers)t();this.stoppedResolvers=[];}}async cancelTask(t){if(!this.lockAcquired)return this.withTemporaryLock(()=>this.cancelTask(t));await this.withStateLock(async()=>{await this.loadState();let e=this.state,s=e.running[t];s&&(this.abortControllers.get(t)?.abort(),this.abortControllers.delete(t),await this.deps.processManager.killWithGrace(s.pid,3e3).catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`cancelTask kill process ${s.pid} for task ${t}`,fatal:false});}),await this.deps.runService.finish(s.run_id,"cancelled").catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`cancelTask finish run ${s.run_id}`,fatal:false});}),await this.deps.agentService.setStatus(s.agent_id,"idle").catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`cancelTask setStatus idle for agent ${s.agent_id}`,fatal:false});}),delete e.running[t],await this.saveState()),e.retry_queue=e.retry_queue.filter(a=>a.task_id!==t);try{await this.deps.taskService.cancel(t);}catch{try{await this.deps.taskService.updateStatus(t,"cancelled");}catch{}}await this.saveState();});}async forceStopAgent(t){if(!this.lockAcquired)return this.withTemporaryLock(()=>this.forceStopAgent(t));await this.withStateLock(async()=>{await this.loadState();let e=this.state;for(let[s,a]of Object.entries(e.running))if(a.agent_id===t){this.abortControllers.get(s)?.abort(),this.abortControllers.delete(s),await this.deps.processManager.killWithGrace(a.pid,3e3),await this.deps.runService.finish(a.run_id,"cancelled");try{await this.deps.taskService.updateStatus(s,"failed");}catch{}delete e.running[s];}await this.deps.agentService.setStatus(t,"idle"),await this.saveState();});}async tick(){if(!this.shuttingDown){this.tickInProgress=true;try{await this.withStateLock(async()=>{if(this.shuttingDown)return;this.cachedTaskStore.invalidate(),this.cachedAgentStore.invalidate(),this.cachedGoalStore?.invalidate(),await this.loadState(),await this.reconcile(),this.skipAutonomousSeeding||await this.seedAutonomousTasks(),await this.dispatchAll();let t=await this.cachedTaskStore.list(),e=Object.keys(this.state.running).length,s=t.filter(a=>c(a.status)).length;this.deps.eventBus.emit({type:"orchestrator:tick",running:e,queued:s});}),await at(this.deps.lockPath);}finally{this.tickInProgress=false;}}}scheduleImmediateDispatch(t=0){this.shuttingDown||this.immediateDispatchTimer||(this.immediateDispatchTimer=setTimeout(()=>{if(this.immediateDispatchTimer=null,!this.shuttingDown){if(this.tickInProgress){t<10&&this.scheduleImmediateDispatch(t+1);return}this.immediateDispatch().catch(e=>{this.deps.eventBus.emit({type:"orchestrator:error",error:e instanceof Error?e.message:String(e),context:"immediate dispatch on task:created",fatal:false});});}},500));}async immediateDispatch(){this.shuttingDown||await this.freshDispatch(()=>this.shuttingDown?Promise.resolve():this.dispatchAll());}async reconcile(){let t=this.state,e=Date.now(),s=Object.entries(t.running),a=await Promise.all(s.map(([i])=>this.deps.taskStore.get(i)));for(let i=0;i<s.length;i++){let[h,c]=s[i],w=a[i];if(!w||b$1(w.status)){this.abortControllers.delete(h),delete t.running[h],await this.deps.agentService.setStatus(c.agent_id,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`reconcile setStatus idle for stale agent ${c.agent_id} (task ${h})`,fatal:false});});continue}if(!this.deps.processManager.isAlive(c.pid)){try{await this._handleRunFailure(h,c,"Process crashed unexpectedly");}catch{delete t.running[h],await this.deps.agentService.setStatus(c.agent_id,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`reconcile crash fallback setStatus idle for agent ${c.agent_id} (task ${h})`,fatal:false});});}continue}let S=new Date(c.last_event_at).getTime(),m=this.deps.config.defaults.agent.stall_timeout_ms;if(e-S>m){this.deps.eventBus.emit({type:"orchestrator:stall_detected",runId:c.run_id}),this.abortControllers.get(h)?.abort(),await this.deps.processManager.killWithGrace(c.pid,5e3);try{await this._handleRunFailure(h,c,"Agent stalled (no events)");}catch{delete t.running[h],await this.deps.agentService.setStatus(c.agent_id,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`reconcile stall fallback setStatus idle for agent ${c.agent_id} (task ${h})`,fatal:false});});}}}let r=new Set(Object.values(t.running).map(i=>i.agent_id)),[u,n]=await Promise.all([this.cachedAgentStore.list(),this.cachedTaskStore.list()]),l=u.filter(i=>i.status==="running"&&!r.has(i.id));l.length>0&&await Promise.all(l.map(i=>this.deps.agentService.setStatus(i.id,"idle")));let p=n.filter(i=>i.status==="in_progress"&&!t.running[i.id]);p.length>0&&await Promise.all(p.map(async i=>{try{await this.deps.taskService.updateStatus(i.id,"failed");}catch{i.status="failed",i.updated_at=new Date().toISOString(),await this.deps.taskStore.save(i).catch(h=>{this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),context:`force-write orphaned task ${i.id}`,fatal:false});});}this.deps.eventBus.emit({type:"task:orphaned",taskId:i.id});}));let f=[];t.retry_queue=t.retry_queue.filter(i=>e>=new Date(i.due_at).getTime()?(f.push(i.task_id),false):true);for(let i of f)await this.dispatchTask(i);await this.saveState();}async seedAutonomousTasks(){let e=(await this.cachedAgentStore.list()).filter(n=>n.autonomous&&n.status==="idle");if(e.length===0)return;let s=await this.cachedTaskStore.list(),a$1=this.cachedGoalStore?await this.cachedGoalStore.list({status:"active"}):[],r=false,u=new Set;for(let n of e){if(s.some(c=>c.assignee===n.id&&!b$1(c.status)))continue;let p=a$1.find(c=>c.assignee===n.id&&!u.has(c.id))??a$1.find(c=>!c.assignee&&!u.has(c.id));p&&u.add(p.id);let f=n.role??"general assistant",i=p?`[auto] ${n.name}: ${p.title.slice(0,60)}`:`[auto] ${n.name}: ${f.slice(0,60)}`,h=p?`## GOAL (highest priority)
5
+ `)}runCriterion(t){let{cmd:e,args:s}=St[t];return new Promise(a=>{execFile(e,s,{cwd:this.cwd,timeout:this.timeoutMs,maxBuffer:1024*1024},(r,u,n)=>{let l=(u+`
6
+ `+n).trim();a({criterion:t,passed:!r,output:l.slice(0,2e3)});});})}};var wt=8192,yt=4096,rt=class{constructor(t){this.deps=t;this.cachedTaskStore=new D(t.taskStore),this.cachedAgentStore=new C(t.agentStore),this.cachedGoalStore=t.goalStore?new B(t.goalStore):null;}intervalId=null;shuttingDown=false;state=null;abortControllers=new Map;cachedTaskStore;cachedAgentStore;cachedGoalStore;saveStateTimer=null;saveStateDirty=false;lockAcquired=false;consecutiveTickFailures=0;maxConsecutiveTickFailures=5;maxRetryQueueSize=100;signalHandlers=[];immediateDispatchTimer=null;taskCreatedUnsub=null;tickInProgress=false;stoppedResolvers=[];skipAutonomousSeeding=false;stateMutex=Promise.resolve();get isOwner(){return this.lockAcquired}withStateLock(t){let e,s=new Promise(r=>{e=r;}),a=this.stateMutex;return this.stateMutex=s,a.then(async()=>{try{return await t()}finally{e();}})}async runTask(t){if(this.lockAcquired){await this.freshDispatch(()=>this.dispatchTask(t));return}await this.withTemporaryLock(()=>this.freshDispatch(()=>this.dispatchTask(t)));}async runAll(){if(this.lockAcquired){await this.freshDispatch(()=>this.dispatchAll());return}await this.withTemporaryLock(()=>this.freshDispatch(()=>this.dispatchAll()));}async freshDispatch(t){await this.withStateLock(async()=>{this.cachedTaskStore.invalidate(),this.cachedAgentStore.invalidate(),await this.loadState(),await t(),await this.saveState();});}async withTemporaryLock(t){let e=await q(this.deps.lockPath);if(!e.acquired)throw new d(e.pid);this.lockAcquired=true;try{await t();}finally{this.lockAcquired=false,await G(this.deps.lockPath);}}async startWatch(t){this.skipAutonomousSeeding=t?.skipAutonomousSeeding??false;let e=await q(this.deps.lockPath);if(!e.acquired)throw new d(e.pid);this.lockAcquired=true,await this.loadState(),await this.cleanupStaleRunningEntries(),this.state.pid=process.pid,this.state.started_at=new Date().toISOString(),await this.saveState(),this.registerSignalHandlers(),this.taskCreatedUnsub=this.deps.eventBus.on("task:created",()=>{this.scheduleImmediateDispatch();}),await this.tick(),this.intervalId=setInterval(()=>this.tick().then(()=>{this.consecutiveTickFailures=0;},s=>{this.consecutiveTickFailures++;let a=s instanceof Error?s.message:String(s);this.deps.eventBus.emit({type:"orchestrator:error",error:a,context:"tick",fatal:this.consecutiveTickFailures>=this.maxConsecutiveTickFailures}),this.consecutiveTickFailures>=this.maxConsecutiveTickFailures&&(this.deps.eventBus.emit({type:"orchestrator:shutdown",reason:`${this.consecutiveTickFailures} consecutive tick failures`}),this.stop().catch(r=>{this.deps.eventBus.emit({type:"orchestrator:error",error:r instanceof Error?r.message:String(r),context:"stop after consecutive tick failures",fatal:false});}));}),this.deps.config.scheduling.poll_interval_ms);}waitForStop(){return this.shuttingDown?Promise.resolve():new Promise(t=>{this.stoppedResolvers.push(t);})}registerSignalHandlers(){let t=e=>{this.deps.eventBus.emit({type:"orchestrator:shutdown",reason:`Received ${e}`}),this.stop().catch(s=>{this.deps.eventBus.emit({type:"orchestrator:error",error:s instanceof Error?s.message:String(s),context:`stop after ${e} signal`,fatal:false});});};for(let e of ["SIGINT","SIGTERM"]){let s=()=>t(e);this.signalHandlers.push([e,s]),process.on(e,s);}}removeSignalHandlers(){for(let[t,e]of this.signalHandlers)process.removeListener(t,e);this.signalHandlers=[];}async stop(){if(!this.shuttingDown){this.shuttingDown=true,this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.taskCreatedUnsub&&(this.taskCreatedUnsub(),this.taskCreatedUnsub=null),this.immediateDispatchTimer&&(clearTimeout(this.immediateDispatchTimer),this.immediateDispatchTimer=null),await this.flushStateLazy(),await this.withStateLock(async()=>{if(this.state){for(let[t,e$1]of Object.entries(this.state.running)){this.abortControllers.get(t)?.abort(),this.abortControllers.delete(t),await this.deps.processManager.killWithGrace(e$1.pid),await this.deps.runService.finish(e$1.run_id,"cancelled");let s=await this.deps.taskStore.get(t);s&&await this.deps.taskService.updateStatus(t,e(s)),await this.deps.agentService.setStatus(e$1.agent_id,"idle");}this.state.running={},this.state.claimed=new Set,this.state.pid=void 0,this.state.started_at=void 0,await this.saveState();}}),this.lockAcquired&&(await G(this.deps.lockPath),this.lockAcquired=false),this.removeSignalHandlers();for(let t of this.stoppedResolvers)t();this.stoppedResolvers=[];}}async cancelTask(t){if(!this.lockAcquired)return this.withTemporaryLock(()=>this.cancelTask(t));await this.withStateLock(async()=>{await this.loadState();let e=this.state,s=e.running[t];s&&(this.abortControllers.get(t)?.abort(),this.abortControllers.delete(t),await this.deps.processManager.killWithGrace(s.pid,3e3).catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`cancelTask kill process ${s.pid} for task ${t}`,fatal:false});}),await this.deps.runService.finish(s.run_id,"cancelled").catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`cancelTask finish run ${s.run_id}`,fatal:false});}),await this.deps.agentService.setStatus(s.agent_id,"idle").catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`cancelTask setStatus idle for agent ${s.agent_id}`,fatal:false});}),delete e.running[t],await this.saveState()),e.retry_queue=e.retry_queue.filter(a=>a.task_id!==t);try{await this.deps.taskService.cancel(t);}catch{try{await this.deps.taskService.updateStatus(t,"cancelled");}catch{}}await this.saveState();});}async forceStopAgent(t){if(!this.lockAcquired)return this.withTemporaryLock(()=>this.forceStopAgent(t));await this.withStateLock(async()=>{await this.loadState();let e=this.state;for(let[s,a]of Object.entries(e.running))if(a.agent_id===t){this.abortControllers.get(s)?.abort(),this.abortControllers.delete(s),await this.deps.processManager.killWithGrace(a.pid,3e3),await this.deps.runService.finish(a.run_id,"cancelled");try{await this.deps.taskService.updateStatus(s,"failed");}catch{}delete e.running[s];}await this.deps.agentService.setStatus(t,"idle"),await this.saveState();});}async tick(){if(!this.shuttingDown){this.tickInProgress=true;try{await this.withStateLock(async()=>{if(this.shuttingDown)return;this.cachedTaskStore.invalidate(),this.cachedAgentStore.invalidate(),this.cachedGoalStore?.invalidate(),await this.loadState(),await this.reconcile(),this.skipAutonomousSeeding||await this.seedAutonomousTasks(),await this.dispatchAll();let t=await this.cachedTaskStore.list(),e=Object.keys(this.state.running).length,s=t.filter(a=>c(a.status)).length;this.deps.eventBus.emit({type:"orchestrator:tick",running:e,queued:s});}),await at(this.deps.lockPath);}finally{this.tickInProgress=false;}}}scheduleImmediateDispatch(t=0){this.shuttingDown||this.immediateDispatchTimer||(this.immediateDispatchTimer=setTimeout(()=>{if(this.immediateDispatchTimer=null,!this.shuttingDown){if(this.tickInProgress){t<10&&this.scheduleImmediateDispatch(t+1);return}this.immediateDispatch().catch(e=>{this.deps.eventBus.emit({type:"orchestrator:error",error:e instanceof Error?e.message:String(e),context:"immediate dispatch on task:created",fatal:false});});}},500));}async immediateDispatch(){this.shuttingDown||await this.freshDispatch(()=>this.shuttingDown?Promise.resolve():this.dispatchAll());}async reconcile(){let t=this.state,e=Date.now(),s=Object.entries(t.running),a=await Promise.all(s.map(([i])=>this.deps.taskStore.get(i)));for(let i=0;i<s.length;i++){let[h,c]=s[i],S=a[i];if(!S||b$1(S.status)){this.abortControllers.delete(h),delete t.running[h],await this.deps.agentService.setStatus(c.agent_id,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`reconcile setStatus idle for stale agent ${c.agent_id} (task ${h})`,fatal:false});});continue}if(!this.deps.processManager.isAlive(c.pid)){try{await this._handleRunFailure(h,c,"Process crashed unexpectedly");}catch{delete t.running[h],await this.deps.agentService.setStatus(c.agent_id,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`reconcile crash fallback setStatus idle for agent ${c.agent_id} (task ${h})`,fatal:false});});}continue}let w=new Date(c.last_event_at).getTime(),v=this.deps.config.defaults.agent.stall_timeout_ms;if(e-w>v){this.deps.eventBus.emit({type:"orchestrator:stall_detected",runId:c.run_id}),this.abortControllers.get(h)?.abort(),await this.deps.processManager.killWithGrace(c.pid,5e3);try{await this._handleRunFailure(h,c,"Agent stalled (no events)");}catch{delete t.running[h],await this.deps.agentService.setStatus(c.agent_id,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`reconcile stall fallback setStatus idle for agent ${c.agent_id} (task ${h})`,fatal:false});});}}}let r=new Set(Object.values(t.running).map(i=>i.agent_id)),[u,n]=await Promise.all([this.cachedAgentStore.list(),this.cachedTaskStore.list()]),l=u.filter(i=>i.status==="running"&&!r.has(i.id));l.length>0&&await Promise.all(l.map(i=>this.deps.agentService.setStatus(i.id,"idle")));let p=n.filter(i=>i.status==="in_progress"&&!t.running[i.id]);p.length>0&&await Promise.all(p.map(async i=>{try{await this.deps.taskService.updateStatus(i.id,"failed");}catch{i.status="failed",i.updated_at=new Date().toISOString(),await this.deps.taskStore.save(i).catch(h=>{this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),context:`force-write orphaned task ${i.id}`,fatal:false});});}this.deps.eventBus.emit({type:"task:orphaned",taskId:i.id});}));let f=[];t.retry_queue=t.retry_queue.filter(i=>e>=new Date(i.due_at).getTime()?(f.push(i.task_id),false):true);for(let i of f)await this.dispatchTask(i);await this.saveState();}async seedAutonomousTasks(){let e=(await this.cachedAgentStore.list()).filter(n=>n.autonomous&&n.status==="idle");if(e.length===0)return;let s=await this.cachedTaskStore.list(),a$1=this.cachedGoalStore?await this.cachedGoalStore.list({status:"active"}):[],r=false,u=new Set;for(let n of e){if(s.some(c=>c.assignee===n.id&&!b$1(c.status)))continue;let p=a$1.find(c=>c.assignee===n.id&&!u.has(c.id))??a$1.find(c=>!c.assignee&&!u.has(c.id));p&&u.add(p.id);let f=n.role??"general assistant",i=p?`[auto] ${n.name}: ${p.title.slice(0,60)}`:`[auto] ${n.name}: ${f.slice(0,60)}`,h=p?`## GOAL (highest priority)
7
7
 
8
8
  ${p.description||p.title}
9
9
 
10
10
  ---
11
- Agent role: ${f}`:`Autonomous work cycle. Agent role: ${f}`;try{await this.deps.taskService.create({title:i,description:h,assignee:n.id,labels:[a],priority:3,goalId:p?.id}),r=!0;}catch(c){this.deps.eventBus.emit({type:"orchestrator:error",error:c instanceof Error?c.message:String(c),context:`autonomous task for agent ${n.id}`,fatal:false});}}r&&this.cachedTaskStore.invalidate();}async dispatchAll(){let t=this.state,e=this.deps.config.scheduling.max_concurrent_agents,s=Object.keys(t.running).length,a=e-s;if(a<=0)return;let r=await this.cachedTaskStore.list(),u=new Map(r.map(i=>[i.id,i])),n=r.filter(i=>c(i.status)&&!d$1(i,u)&&!t.running[i.id]&&!t.claimed.has(i.id)).sort((i,h)=>{let c=(i.priority??3)-(h.priority??3);if(c!==0)return c;let w=(i.goalId?0:1)-(h.goalId?0:1);if(w!==0)return w;let S=h.updated_at??"",m=i.updated_at??"";return S<m?-1:S>m?1:0}).slice(0,a),l$1=new Set,p=r.filter(i=>i.status==="in_progress"&&i.scope?.length),f=new b(p.map(i=>i.scope));for(let i of n)if(i.scope?.length)if(f.overlapsAny(i.scope)){let h=p.find(c=>et(i.scope,c.scope));this.deps.eventBus.emit({type:"task:scope_overlap",taskId:i.id,overlappingTaskId:h?.id??i.id,patterns:i.scope}),l$1.add(i.id);}else f.add(i.scope);for(let i of n)if(!l$1.has(i.id))try{await this.dispatchTask(i.id);}catch(h){if(h instanceof l)try{let c=await this.deps.taskStore.get(i.id);c&&!b$1(c.status)&&(c.status="failed",c.updated_at=new Date().toISOString(),await this.deps.taskStore.save(c));}catch{}this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),context:`dispatch task ${i.id}`,fatal:false});}}async dispatchTask(t){let e=this.state;if(e.running[t]){let a=e.running[t];throw new h(t,a.run_id,a.agent_id)}let s=await this.deps.taskService.get(t);e.claimed.add(t),await this.saveState();try{let a=await this.cachedAgentStore.list(),r=await this.deps.agentService.findBestAgent(s);if(!r){if(a.length===0)throw new e$1;this.unclaim(t),await this.saveState();return}let{path:u,branch:n}=await this.deps.workspaceManager.prepare(s,r,this.deps.config),l=this.deps.config.prompt?.system_template??d$2,p=this.deps.config.prompt?.user_template??e$2,f=this.deps.config.prompt?.template,i=s.attempts+1,h;if(i>1){let v=await this.deps.runService.getLastFailedRunContext(s.id);v&&(h={previous_error:v.error,previous_output:v.output});}let c=s.goalId,[w,S,m]=await Promise.all([this.deps.contextStore?.getAll(),this.deps.messageService?this.deps.messageService.drainMailbox(r.id,s.id):[],c&&this.cachedGoalStore?this.cachedGoalStore.get(c).catch(()=>null):null]),o;if(m){let ct=(await this.cachedTaskStore.list()).filter(x=>x.goalId===c),lt=await this.deps.contextStore?.get(`${c}-progress`),dt=ct.map(x=>`[${x.status}] ${x.title}`);o={id:m.id,title:m.title,description:m.description,status:m.status,task_names:dt,progress:lt?.value};}let g=c$1(s,r,i,u,this.deps.config,{allAgents:a,retryContext:h,sharedContext:w,feedback:s.feedback,messages:S.length?S:void 0,goal:o}),y,P;f?y=await this.deps.templateEngine.render(f,g):(P=await this.deps.templateEngine.render(l,g),y=await this.deps.templateEngine.render(p,g));let A=await this.deps.runService.create({taskId:s.id,agentId:r.id,attempt:i,prompt:y,workspacePath:u});if((s.status==="failed"||s.status==="cancelled")&&(await this.deps.taskService.retry(t),s.status="todo",s.attempts=0),await this.deps.taskService.updateStatus(t,"in_progress"),await this.deps.taskService.assign(t,r.id),await this.deps.taskService.incrementAttempts(t),n){let v=await this.deps.taskStore.get(t);v&&(v.proof={...v.proof??{files_changed:[]},branch:n},v.workspace=u,await this.deps.taskStore.save(v));}await this.deps.agentService.setStatus(r.id,"running");let k=await this.deps.agentService.get(r.id);k.current_task=t,k.last_error=void 0,await this.deps.agentStore.save(k);let ot=this.deps.adapterRegistry.require(r.adapter),F=new AbortController;this.abortControllers.set(t,F);let I=ot.execute({prompt:y,systemPrompt:P,workspace:u,env:{...r.config.env,ORCH_AGENT_ID:r.id,ORCH_AGENT_NAME:r.name,ORCH_TASK_ID:s.id},config:k.config,signal:F.signal}),N=I.pid,U=new Date().toISOString();await this.deps.runService.start(A.id,N),this.unclaim(t),e.running[t]={run_id:A.id,agent_id:r.id,task_id:t,pid:N,started_at:U,last_event_at:U},await this.saveState(),this.collectEvents(I.events,A.id,t,r.id).catch(v=>{this.deps.eventBus.emit({type:"orchestrator:error",error:v instanceof Error?v.message:String(v),context:`adapter execution for ${t}`,fatal:!1});});}catch(a){throw this.abortControllers.delete(t),this.unclaim(t),await this.saveState(),a}}async collectEvents(t,e,s,a){let r,u,n,l,p=new Set;try{for await(let i of t){if(this.shuttingDown)break;if(i.type==="done"){if(i.tokens){let{input:g,output:y,reasoning:P,cache_read:A,cache_write:k}=i.tokens;r=a$1(g,y,{reasoning:P,cache_read:A,cache_write:k});}let o=i.data;o&&typeof o.result=="string"&&(u=o.result);}if(i.type==="output"){let o=i.data;if(o){let g=typeof o.text=="string"?o.text:typeof o.message=="string"?o.message:void 0;g?.trim()&&(n=g);}}if(i.type==="file_change"){let o=i.data;if(o&&Array.isArray(o.paths))for(let g of o.paths)typeof g=="string"&&p.add(g);else {let g=o&&typeof o.path=="string"?o.path:typeof i.data=="string"?i.data:String(i.data);p.add(g);}}let h=kt(i.timestamp)?i.timestamp:new Date().toISOString(),c=i.type==="file_change"?(()=>{let o=i.data;return o&&typeof o.path=="string"?o.path:typeof i.data=="string"?i.data:String(i.data)})():null,w=nt(i.data,St);i.data=void 0;let S={timestamp:h,type:i.type==="output"?"agent_output":i.type==="file_change"?"file_changed":i.type==="command"?"command_run":i.type==="tool_call"?"tool_call":i.type==="error"?"error":"done",data:w};await this.deps.runService.appendEvent(e,S),this.state?.running[s]&&(this.state.running[s].last_event_at=h,this.saveStateLazy());let m=nt(w,yt);i.type==="output"||i.type==="tool_call"?this.deps.eventBus.emit({type:"agent:output",runId:e,agentId:a,data:m}):i.type==="file_change"?this.deps.eventBus.emit({type:"agent:file_changed",runId:e,agentId:a,path:c}):i.type==="error"&&(i.errorKind&&(l=i.errorKind),this.deps.eventBus.emit({type:"agent:error",runId:e,agentId:a,error:m,...i.errorKind?{errorKind:i.errorKind}:{}}));}let f=u??n;await this.handleRunSuccess(s,e,a,r,f,[...p]);}catch(f){let i=f instanceof Error?f.message:String(f),h=l??(f instanceof Error?f.errorKind:void 0),c=this.state?.running[s];c&&await this.handleRunFailure(s,c,i,h);}finally{this.deps.runStore.closeRunEvents(e);}}async handleRunSuccess(t,e,s,a,r,u){return this.withStateLock(()=>this._handleRunSuccess(t,e,s,a,r,u))}async _handleRunSuccess(t,e,s,a$1,r,u){await this.flushStateLazy(),this.abortControllers.delete(t);let n=this.state;if(!n.running[t])return;let l=await this.deps.taskStore.get(t);if(!l)return;l.proof={...l.proof,agent_summary:r?.slice(0,2e3)??l.proof?.agent_summary,files_changed:u?.length?u:l.proof?.files_changed??[]},delete l.feedback,await this.deps.taskStore.save(l);let p=await this.deps.agentStore.get(s),i=l.labels?.includes(a)||p?.config.approval_policy==="auto",h=f(l,true,i);await this.deps.runService.finish(e,"succeeded",a$1);let c=n.running[t],w=c?Date.now()-new Date(c.started_at).getTime():0;c&&(n.stats.total_runtime_ms+=w),delete n.running[t];let S={tasks_completed:(p?.stats.tasks_completed??0)+1,total_runs:(p?.stats.total_runs??0)+1,total_runtime_ms:(p?.stats.total_runtime_ms??0)+w};if(a$1&&(S.tokens_used=(p?.stats.tokens_used??0)+a$1.total),await this.deps.agentService.updateStats(s,S).catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`agent stats update for ${s}`,fatal:false});}),n.stats.total_tasks_completed++,n.stats.total_runs++,a$1&&(n.stats.total_tokens.input+=a$1.input,n.stats.total_tokens.output+=a$1.output,n.stats.total_tokens.reasoning+=a$1.reasoning,n.stats.total_tokens.cache_read+=a$1.cache_read,n.stats.total_tokens.cache_write+=a$1.cache_write,n.stats.total_tokens.total=n.stats.total_tokens.input+n.stats.total_tokens.output+n.stats.total_tokens.reasoning),l.proof?.branch)try{let o=await this.deps.workspaceManager.mergeBack(l.proof.branch);if(o.success)this.deps.eventBus.emit({type:"workspace:merge_succeeded",taskId:t,branch:l.proof.branch}),await this.deps.workspaceManager.cleanup(t,l.proof.branch).catch(g=>{this.deps.eventBus.emit({type:"orchestrator:error",error:g instanceof Error?g.message:String(g),context:`workspace cleanup for ${t}`,fatal:!1});});else {this.deps.eventBus.emit({type:"workspace:merge_conflict",taskId:t,branch:l.proof.branch,conflictInfo:o.conflictInfo}),await this.forceTaskToReview(l,s,`MERGE CONFLICT: ${o.conflictInfo}`);return}}catch(o){let g=o instanceof Error?o.message:String(o);await this.forceTaskToReview(l,s,`MERGE ERROR: ${g}`);return}try{await this.deps.taskService.updateStatus(t,h);}catch(o){let g=o instanceof Error?o.message:String(o);this.deps.eventBus.emit({type:"orchestrator:error",error:g,context:`state machine validation failed for task ${t} -> ${h}, force-writing`,fatal:false}),l.status=h,l.updated_at=new Date().toISOString(),await this.deps.taskStore.save(l).catch(y=>{this.deps.eventBus.emit({type:"orchestrator:error",error:y instanceof Error?y.message:String(y),context:`force-write task ${t} to store failed`,fatal:false});});}await this.deps.agentService.setStatus(s,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`_handleRunSuccess setStatus idle for agent ${s}`,fatal:false});});let m=await this.deps.agentStore.get(s);m&&(m.current_task=void 0,await this.deps.agentStore.save(m)),h==="review"&&l.review_criteria?.length?await this.runAutoReview(t,l.review_criteria,l.workspace??this.deps.projectRoot,i):h==="review"&&i&&await this.deps.taskService.updateStatus(t,"done"),await this.saveState(),this.scheduleImmediateDispatch();}async handleRunFailure(t,e,s,a){return this.withStateLock(()=>this._handleRunFailure(t,e,s,a))}async _handleRunFailure(t,e$1,s,a){await this.flushStateLazy(),this.abortControllers.delete(t);let r=this.state,u=await this.deps.taskStore.get(t);if(!u)return;await this.deps.runService.finish(e$1.run_id,"failed",void 0,s),await this.deps.agentService.setStatus(e$1.agent_id,"idle");let n$1=await this.deps.agentStore.get(e$1.agent_id);n$1&&(n$1.current_task=void 0,n$1.last_error={message:s.slice(0,500),kind:a??n(s),timestamp:new Date().toISOString()},await this.deps.agentStore.save(n$1));let l=await this.deps.agentStore.get(e$1.agent_id),p=Date.now()-new Date(e$1.started_at).getTime();await this.deps.agentService.updateStats(e$1.agent_id,{tasks_failed:(l?.stats.tasks_failed??0)+1,total_runs:(l?.stats.total_runs??0)+1,total_runtime_ms:(l?.stats.total_runtime_ms??0)+p});let f=e(u);if(await this.deps.taskService.updateStatus(t,f),f==="retrying"){let i=g(u.attempts-1,this.deps.config.scheduling.retry_base_delay_ms,this.deps.config.scheduling.retry_max_delay_ms);r.retry_queue.some(c=>c.task_id===t)||(r.retry_queue.length>=this.maxRetryQueueSize&&r.retry_queue.shift(),r.retry_queue.push({task_id:t,attempt:u.attempts+1,due_at:new Date(Date.now()+i).toISOString(),error:s})),this.deps.eventBus.emit({type:"run:retry",runId:e$1.run_id,attempt:u.attempts+1,delay_ms:i});}else r.stats.total_tasks_failed++;r.stats.total_runtime_ms+=p,u.proof?.branch&&await this.deps.workspaceManager.cleanup(t,u.proof.branch).catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:`workspace cleanup for ${t}`,fatal:false});}),delete r.running[t],r.stats.total_runs++,await this.saveState(),this.scheduleImmediateDispatch();}async runAutoReview(t,e,s,a=false){let u=await new T({cwd:s}).runAll(e),n=T.allPassed(u),l=await this.deps.taskStore.get(t);if(l&&(l.review_results=u,l.proof={...l.proof,test_results:T.formatReport(u),files_changed:l.proof?.files_changed??[]},await this.deps.taskStore.save(l),this.deps.eventBus.emit({type:"task:auto_reviewed",taskId:t,passed:n,results:u}),n||a)){n||this.deps.eventBus.emit({type:"orchestrator:error",error:`Review criteria failed for task ${t} but autoApprove is set \u2014 force-approving`,context:"auto-review-with-auto-approve",fatal:false});try{await this.deps.taskService.updateStatus(t,"done");}catch(p){let f=p instanceof Error?p.message:String(p);this.deps.eventBus.emit({type:"orchestrator:error",error:f,context:`auto-review transition failed for task ${t} -> done, force-writing`,fatal:false}),l.status="done",l.updated_at=new Date().toISOString(),await this.deps.taskStore.save(l).catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:`force-write task ${t} to store failed (auto-review)`,fatal:false});});}}}async forceTaskToReview(t,e,s){t.proof={...t.proof,agent_summary:`${s}
11
+ Agent role: ${f}`:`Autonomous work cycle. Agent role: ${f}`;try{await this.deps.taskService.create({title:i,description:h,assignee:n.id,labels:[a],priority:3,goalId:p?.id}),r=!0;}catch(c){this.deps.eventBus.emit({type:"orchestrator:error",error:c instanceof Error?c.message:String(c),context:`autonomous task for agent ${n.id}`,fatal:false});}}r&&this.cachedTaskStore.invalidate();}async dispatchAll(){let t=this.state,e=this.deps.config.scheduling.max_concurrent_agents,s=Object.keys(t.running).length,a=e-s;if(a<=0)return;let r=await this.cachedTaskStore.list(),u=new Map(r.map(i=>[i.id,i])),n=r.filter(i=>c(i.status)&&!d$1(i,u)&&!t.running[i.id]&&!t.claimed.has(i.id)).sort((i,h)=>{let c=(i.priority??3)-(h.priority??3);if(c!==0)return c;let S=(i.goalId?0:1)-(h.goalId?0:1);if(S!==0)return S;let w=h.updated_at??"",v=i.updated_at??"";return w<v?-1:w>v?1:0}).slice(0,a),l$1=new Set,p=r.filter(i=>i.status==="in_progress"&&i.scope?.length),f=new b(p.map(i=>i.scope));for(let i of n)if(i.scope?.length)if(f.overlapsAny(i.scope)){let h=p.find(c=>et(i.scope,c.scope));this.deps.eventBus.emit({type:"task:scope_overlap",taskId:i.id,overlappingTaskId:h?.id??i.id,patterns:i.scope}),l$1.add(i.id);}else f.add(i.scope);for(let i of n)if(!l$1.has(i.id))try{await this.dispatchTask(i.id);}catch(h){if(h instanceof l)try{let c=await this.deps.taskStore.get(i.id);c&&!b$1(c.status)&&(c.status="failed",c.updated_at=new Date().toISOString(),await this.deps.taskStore.save(c));}catch{}this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),context:`dispatch task ${i.id}`,fatal:false});}}async dispatchTask(t){let e=this.state;if(e.running[t]){let a=e.running[t];throw new h(t,a.run_id,a.agent_id)}let s=await this.deps.taskService.get(t);e.claimed.add(t),await this.saveState();try{let a=await this.cachedAgentStore.list(),r=await this.deps.agentService.findBestAgent(s);if(!r){if(a.length===0)throw new e$1;this.unclaim(t),await this.saveState();return}let{path:u,branch:n}=await this.deps.workspaceManager.prepare(s,r,this.deps.config),l=this.deps.config.prompt?.system_template??d$2,p=this.deps.config.prompt?.user_template??e$2,f=this.deps.config.prompt?.template,i=s.attempts+1,h;if(i>1){let m=await this.deps.runService.getLastFailedRunContext(s.id);m&&(h={previous_error:m.error,previous_output:m.output});}let c=s.goalId,[S,w,v]=await Promise.all([this.deps.contextStore?.getAll(),this.deps.messageService?this.deps.messageService.drainMailbox(r.id,s.id):[],c&&this.cachedGoalStore?this.cachedGoalStore.get(c).catch(()=>null):null]),o;if(v){let ct=(await this.cachedTaskStore.list()).filter(x=>x.goalId===c),lt=await this.deps.contextStore?.get(`${c}-progress`),dt=ct.map(x=>`[${x.status}] ${x.title}`);o={id:v.id,title:v.title,description:v.description,status:v.status,task_names:dt,progress:lt?.value};}let g=c$1(s,r,i,u,this.deps.config,{allAgents:a,retryContext:h,sharedContext:S,feedback:s.feedback,messages:w.length?w:void 0,goal:o}),y,k;if(f?y=await this.deps.templateEngine.render(f,g):(k=await this.deps.templateEngine.render(l,g),y=await this.deps.templateEngine.render(p,g)),this.deps.skillLoader&&r.config.skills?.length){let m=await this.deps.skillLoader.loadSkills(r.config.skills);m&&(k!==void 0?k=k+`
12
+
13
+ `+m:y=y+`
14
+
15
+ `+m);}let R=await this.deps.runService.create({taskId:s.id,agentId:r.id,attempt:i,prompt:y,workspacePath:u});if((s.status==="failed"||s.status==="cancelled")&&(await this.deps.taskService.retry(t),s.status="todo",s.attempts=0),await this.deps.taskService.updateStatus(t,"in_progress"),await this.deps.taskService.assign(t,r.id),await this.deps.taskService.incrementAttempts(t),n){let m=await this.deps.taskStore.get(t);m&&(m.proof={...m.proof??{files_changed:[]},branch:n},m.workspace=u,await this.deps.taskStore.save(m));}await this.deps.agentService.setStatus(r.id,"running");let _=await this.deps.agentService.get(r.id);_.current_task=t,_.last_error=void 0,await this.deps.agentStore.save(_);let ot=this.deps.adapterRegistry.require(r.adapter),F=new AbortController;this.abortControllers.set(t,F);let I=ot.execute({prompt:y,systemPrompt:k,workspace:u,env:{...r.config.env,ORCH_AGENT_ID:r.id,ORCH_AGENT_NAME:r.name,ORCH_TASK_ID:s.id},config:_.config,signal:F.signal}),N=I.pid,U=new Date().toISOString();await this.deps.runService.start(R.id,N),this.unclaim(t),e.running[t]={run_id:R.id,agent_id:r.id,task_id:t,pid:N,started_at:U,last_event_at:U},await this.saveState(),this.collectEvents(I.events,R.id,t,r.id).catch(m=>{this.deps.eventBus.emit({type:"orchestrator:error",error:m instanceof Error?m.message:String(m),context:`adapter execution for ${t}`,fatal:!1});});}catch(a){throw this.abortControllers.delete(t),this.unclaim(t),await this.saveState(),a}}async collectEvents(t,e,s,a){let r,u,n,l,p=new Set;try{for await(let i of t){if(this.shuttingDown)break;if(i.type==="done"){if(i.tokens){let{input:g,output:y,reasoning:k,cache_read:R,cache_write:_}=i.tokens;r=a$1(g,y,{reasoning:k,cache_read:R,cache_write:_});}let o=i.data;o&&typeof o.result=="string"&&(u=o.result);}if(i.type==="output"){let o=i.data;if(o){let g=typeof o.text=="string"?o.text:typeof o.message=="string"?o.message:void 0;g?.trim()&&(n=g);}}if(i.type==="file_change"){let o=i.data;if(o&&Array.isArray(o.paths))for(let g of o.paths)typeof g=="string"&&p.add(g);else {let g=o&&typeof o.path=="string"?o.path:typeof i.data=="string"?i.data:String(i.data);p.add(g);}}let h=kt(i.timestamp)?i.timestamp:new Date().toISOString(),c=i.type==="file_change"?(()=>{let o=i.data;return o&&typeof o.path=="string"?o.path:typeof i.data=="string"?i.data:String(i.data)})():null,S=nt(i.data,wt);i.data=void 0;let w={timestamp:h,type:i.type==="output"?"agent_output":i.type==="file_change"?"file_changed":i.type==="command"?"command_run":i.type==="tool_call"?"tool_call":i.type==="error"?"error":"done",data:S};await this.deps.runService.appendEvent(e,w),this.state?.running[s]&&(this.state.running[s].last_event_at=h,this.saveStateLazy());let v=nt(S,yt);i.type==="output"||i.type==="tool_call"?this.deps.eventBus.emit({type:"agent:output",runId:e,agentId:a,data:v}):i.type==="file_change"?this.deps.eventBus.emit({type:"agent:file_changed",runId:e,agentId:a,path:c}):i.type==="error"&&(i.errorKind&&(l=i.errorKind),this.deps.eventBus.emit({type:"agent:error",runId:e,agentId:a,error:v,...i.errorKind?{errorKind:i.errorKind}:{}}));}let f=u??n;await this.handleRunSuccess(s,e,a,r,f,[...p]);}catch(f){let i=f instanceof Error?f.message:String(f),h=l??(f instanceof Error?f.errorKind:void 0),c=this.state?.running[s];c&&await this.handleRunFailure(s,c,i,h);}finally{this.deps.runStore.closeRunEvents(e);}}async handleRunSuccess(t,e,s,a,r,u){return this.withStateLock(()=>this._handleRunSuccess(t,e,s,a,r,u))}async _handleRunSuccess(t,e,s,a$1,r,u){await this.flushStateLazy(),this.abortControllers.delete(t);let n=this.state;if(!n.running[t])return;let l=await this.deps.taskStore.get(t);if(!l)return;l.proof={...l.proof,agent_summary:r?.slice(0,2e3)??l.proof?.agent_summary,files_changed:u?.length?u:l.proof?.files_changed??[]},delete l.feedback,await this.deps.taskStore.save(l);let p=await this.deps.agentStore.get(s),i=l.labels?.includes(a)||p?.config.approval_policy==="auto",h=f(l,true,i);await this.deps.runService.finish(e,"succeeded",a$1);let c=n.running[t],S=c?Date.now()-new Date(c.started_at).getTime():0;c&&(n.stats.total_runtime_ms+=S),delete n.running[t];let w={tasks_completed:(p?.stats.tasks_completed??0)+1,total_runs:(p?.stats.total_runs??0)+1,total_runtime_ms:(p?.stats.total_runtime_ms??0)+S};if(a$1&&(w.tokens_used=(p?.stats.tokens_used??0)+a$1.total),await this.deps.agentService.updateStats(s,w).catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`agent stats update for ${s}`,fatal:false});}),n.stats.total_tasks_completed++,n.stats.total_runs++,a$1&&(n.stats.total_tokens.input+=a$1.input,n.stats.total_tokens.output+=a$1.output,n.stats.total_tokens.reasoning+=a$1.reasoning,n.stats.total_tokens.cache_read+=a$1.cache_read,n.stats.total_tokens.cache_write+=a$1.cache_write,n.stats.total_tokens.total=n.stats.total_tokens.input+n.stats.total_tokens.output+n.stats.total_tokens.reasoning),l.proof?.branch)try{let o=await this.deps.workspaceManager.mergeBack(l.proof.branch);if(o.success)this.deps.eventBus.emit({type:"workspace:merge_succeeded",taskId:t,branch:l.proof.branch}),await this.deps.workspaceManager.cleanup(t,l.proof.branch).catch(g=>{this.deps.eventBus.emit({type:"orchestrator:error",error:g instanceof Error?g.message:String(g),context:`workspace cleanup for ${t}`,fatal:!1});});else {this.deps.eventBus.emit({type:"workspace:merge_conflict",taskId:t,branch:l.proof.branch,conflictInfo:o.conflictInfo}),await this.forceTaskToReview(l,s,`MERGE CONFLICT: ${o.conflictInfo}`);return}}catch(o){let g=o instanceof Error?o.message:String(o);await this.forceTaskToReview(l,s,`MERGE ERROR: ${g}`);return}try{await this.deps.taskService.updateStatus(t,h);}catch(o){let g=o instanceof Error?o.message:String(o);this.deps.eventBus.emit({type:"orchestrator:error",error:g,context:`state machine validation failed for task ${t} -> ${h}, force-writing`,fatal:false}),l.status=h,l.updated_at=new Date().toISOString(),await this.deps.taskStore.save(l).catch(y=>{this.deps.eventBus.emit({type:"orchestrator:error",error:y instanceof Error?y.message:String(y),context:`force-write task ${t} to store failed`,fatal:false});});}await this.deps.agentService.setStatus(s,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`_handleRunSuccess setStatus idle for agent ${s}`,fatal:false});});let v=await this.deps.agentStore.get(s);v&&(v.current_task=void 0,await this.deps.agentStore.save(v)),h==="review"&&l.review_criteria?.length?await this.runAutoReview(t,l.review_criteria,l.workspace??this.deps.projectRoot,i):h==="review"&&i&&await this.deps.taskService.updateStatus(t,"done"),await this.saveState(),this.scheduleImmediateDispatch();}async handleRunFailure(t,e,s,a){return this.withStateLock(()=>this._handleRunFailure(t,e,s,a))}async _handleRunFailure(t,e$1,s,a){await this.flushStateLazy(),this.abortControllers.delete(t);let r=this.state,u=await this.deps.taskStore.get(t);if(!u)return;await this.deps.runService.finish(e$1.run_id,"failed",void 0,s),await this.deps.agentService.setStatus(e$1.agent_id,"idle");let n$1=await this.deps.agentStore.get(e$1.agent_id);n$1&&(n$1.current_task=void 0,n$1.last_error={message:s.slice(0,500),kind:a??n(s),timestamp:new Date().toISOString()},await this.deps.agentStore.save(n$1));let l=await this.deps.agentStore.get(e$1.agent_id),p=Date.now()-new Date(e$1.started_at).getTime();await this.deps.agentService.updateStats(e$1.agent_id,{tasks_failed:(l?.stats.tasks_failed??0)+1,total_runs:(l?.stats.total_runs??0)+1,total_runtime_ms:(l?.stats.total_runtime_ms??0)+p});let f=e(u);if(await this.deps.taskService.updateStatus(t,f),f==="retrying"){let i=g(u.attempts-1,this.deps.config.scheduling.retry_base_delay_ms,this.deps.config.scheduling.retry_max_delay_ms);r.retry_queue.some(c=>c.task_id===t)||(r.retry_queue.length>=this.maxRetryQueueSize&&r.retry_queue.shift(),r.retry_queue.push({task_id:t,attempt:u.attempts+1,due_at:new Date(Date.now()+i).toISOString(),error:s})),this.deps.eventBus.emit({type:"run:retry",runId:e$1.run_id,attempt:u.attempts+1,delay_ms:i});}else r.stats.total_tasks_failed++;r.stats.total_runtime_ms+=p,u.proof?.branch&&await this.deps.workspaceManager.cleanup(t,u.proof.branch).catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:`workspace cleanup for ${t}`,fatal:false});}),delete r.running[t],r.stats.total_runs++,await this.saveState(),this.scheduleImmediateDispatch();}async runAutoReview(t,e,s,a=false){let u=await new A({cwd:s}).runAll(e),n=A.allPassed(u),l=await this.deps.taskStore.get(t);if(l&&(l.review_results=u,l.proof={...l.proof,test_results:A.formatReport(u),files_changed:l.proof?.files_changed??[]},await this.deps.taskStore.save(l),this.deps.eventBus.emit({type:"task:auto_reviewed",taskId:t,passed:n,results:u}),n||a)){n||this.deps.eventBus.emit({type:"orchestrator:error",error:`Review criteria failed for task ${t} but autoApprove is set \u2014 force-approving`,context:"auto-review-with-auto-approve",fatal:false});try{await this.deps.taskService.updateStatus(t,"done");}catch(p){let f=p instanceof Error?p.message:String(p);this.deps.eventBus.emit({type:"orchestrator:error",error:f,context:`auto-review transition failed for task ${t} -> done, force-writing`,fatal:false}),l.status="done",l.updated_at=new Date().toISOString(),await this.deps.taskStore.save(l).catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:`force-write task ${t} to store failed (auto-review)`,fatal:false});});}}}async forceTaskToReview(t,e,s){t.proof={...t.proof,agent_summary:`${s}
12
16
 
13
17
  ${t.proof?.agent_summary??""}`.slice(0,2e3),files_changed:t.proof?.files_changed??[]},t.status="review",t.updated_at=new Date().toISOString(),await this.deps.taskStore.save(t),await this.deps.agentService.setStatus(e,"idle").catch(r=>{this.deps.eventBus.emit({type:"orchestrator:error",error:r instanceof Error?r.message:String(r),context:`forceTaskToReview setStatus idle for agent ${e}`,fatal:false});});let a=await this.deps.agentStore.get(e);a&&(a.current_task=void 0,await this.deps.agentStore.save(a)),await this.saveState();}unclaim(t){this.state.claimed.delete(t);}requireOwnership(){if(!this.lockAcquired)throw new d(0)}async loadState(){this.state=await this.deps.stateStore.read();}async cleanupStaleRunningEntries(){let t=this.state,e=Object.entries(t.running).filter(([,a])=>!this.deps.processManager.isAlive(a.pid)),s=new Set;if(e.length>0){for(let[a]of e)delete t.running[a],s.add(a);await Promise.all(e.map(async([a,r])=>{await this.deps.agentService.setStatus(r.agent_id,"idle").catch(u=>{this.deps.eventBus.emit({type:"orchestrator:error",error:u instanceof Error?u.message:String(u),context:`startup cleanup: setStatus idle for agent ${r.agent_id}`,fatal:false});}),await this.forceTaskCancelled(a),await this.deps.runService.finish(r.run_id,"cancelled",void 0,"Orchestrator restarted").catch(u=>{this.deps.eventBus.emit({type:"orchestrator:error",error:u instanceof Error?u.message:String(u),context:`startup cleanup: finish run ${r.run_id}`,fatal:false});});}));}if(t.claimed=new Set,s.size>0){let r=(await this.cachedTaskStore.list()).filter(n=>n.status==="in_progress"&&!t.running[n.id]);r.length>0&&await Promise.all(r.map(n=>this.forceTaskCancelled(n.id)));let u=new Set([...s,...r.map(n=>n.id)]);t.retry_queue=t.retry_queue.filter(n=>!u.has(n.task_id)),await this.saveState();}}async forceTaskCancelled(t){try{await this.deps.taskService.updateStatus(t,"cancelled");}catch{let e=await this.deps.taskStore.get(t);e&&!b$1(e.status)&&(e.status="cancelled",e.updated_at=new Date().toISOString(),await this.deps.taskStore.save(e).catch(s=>{this.deps.eventBus.emit({type:"orchestrator:error",error:s instanceof Error?s.message:String(s),context:`startup cleanup: force-cancel task ${t}`,fatal:false});}));}}async saveState(){this.state&&await this.deps.stateStore.write(this.state);}saveStateLazy(){this.saveStateDirty=true,!this.saveStateTimer&&(this.saveStateTimer=setTimeout(()=>{this.saveStateTimer=null,this.saveStateDirty&&(this.saveStateDirty=false,this.saveState().catch(t=>{this.deps.eventBus.emit({type:"orchestrator:error",error:t instanceof Error?t.message:String(t),context:"debounced state save",fatal:false});}));},500));}async flushStateLazy(){this.saveStateTimer&&(clearTimeout(this.saveStateTimer),this.saveStateTimer=null),this.saveStateDirty&&(this.saveStateDirty=false,await this.saveState());}};function kt(d){if(typeof d!="string")return false;let t=new Date(d);return !isNaN(t.getTime())&&t.toISOString()===d}function nt(d,t){let e=typeof d=="string"?d:JSON.stringify(d);return e.length>t?e.slice(0,t)+"\u2026":e}export{rt as Orchestrator};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-BCPUTULS.js';import {l,q,i,j}from'./chunk-64WUDYEM.js';var d=[{key:"startup-mvp",name:"Startup MVP",description:"Ship an MVP in 48 hours",lead_index:0,agents:[{shop_key:"architect",name:"CTO"},{shop_key:"backend-dev",name:"Backend"},{shop_key:"backend-dev",name:"Backend 2"},{shop_key:"frontend-dev",name:"Frontend"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"pr-review-corp",name:"PR Review Corp",description:"Automated review for every PR",lead_index:0,agents:[{shop_key:"architect",name:"CTO"},{shop_key:"security-auditor",name:"Security"},{shop_key:"performance-engineer",name:"Performance"},{shop_key:"code-reviewer",name:"Style"},{shop_key:"qa-engineer",name:"QA"}]},{key:"migration-squad",name:"Migration Squad",description:"JS-to-TS migration over a weekend",lead_index:0,agents:[{shop_key:"architect",name:"CTO"},{shop_key:"fullstack-dev",name:"Migrator"},{shop_key:"fullstack-dev",name:"Migrator 2"},{shop_key:"fullstack-dev",name:"Migrator 3"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"security-dept",name:"Security Department",description:"Multi-layer security audit",lead_index:0,agents:[{shop_key:"security-auditor",name:"Lead Auditor"},{shop_key:"security-auditor",name:"Scanner"},{shop_key:"security-auditor",name:"Secrets Auditor"},{shop_key:"bug-hunter",name:"Hunter"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"test-factory",name:"Test Factory",description:"Coverage from 40% to 80% overnight",lead_index:0,agents:[{shop_key:"qa-engineer",name:"Coverage Lead"},{shop_key:"backend-dev",name:"Backend"},{shop_key:"backend-dev",name:"Backend 2"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"qa-engineer",name:"QA 2"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"content-agency",name:"Content Agency",description:"Content factory: plan, write, edit, optimize",lead_index:0,agents:[{shop_key:"marketer",name:"Strategist"},{shop_key:"content-creator",name:"Writer"},{shop_key:"content-creator",name:"Writer 2"},{shop_key:"tech-writer",name:"Editor"},{shop_key:"growth-hacker",name:"SEO"}]},{key:"data-lab",name:"Data Lab",description:"3 CSVs to executive report by morning",lead_index:0,agents:[{shop_key:"data-engineer",name:"Lead Analyst"},{shop_key:"data-engineer",name:"Data Engineer"}]},{key:"sales-machine",name:"Sales Machine",description:"Outbound pipeline: research, outreach, follow-up, close",lead_index:0,agents:[{shop_key:"marketer",name:"Sales Director"},{shop_key:"content-creator",name:"SDR"},{shop_key:"content-creator",name:"SDR 2"},{shop_key:"content-creator",name:"Copywriter"},{shop_key:"growth-hacker",name:"Growth Analyst"}]},{key:"bugfix-dept",name:"Bugfix Department",description:"100 issues to 0 in a week",lead_index:0,agents:[{shop_key:"architect",name:"Triager"},{shop_key:"bug-hunter",name:"Fixer"},{shop_key:"bug-hunter",name:"Fixer 2"},{shop_key:"bug-hunter",name:"Fixer 3"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"docs-team",name:"Docs Team",description:"Technical docs from codebase analysis",lead_index:0,agents:[{shop_key:"architect",name:"Docs Lead"},{shop_key:"tech-writer",name:"Writer"},{shop_key:"tech-writer",name:"Writer 2"},{shop_key:"tech-writer",name:"Editor"},{shop_key:"code-reviewer",name:"Reviewer"}]}];function v(l){return d.find(t=>t.key===l)}function C(l$1,t){let h=l$1.command("org").description("Pre-built AI companies \u2014 deploy a full department with one command");h.command("list").alias("ls").description("List available company templates").action(async()=>{if(t.context.json){console.log(JSON.stringify(d,null,2));return}console.log();let c=["KEY","NAME","AGENTS","DESCRIPTION"],s=d.map(e=>[e.key,e.name,String(e.agents.length),e.description]);l(c,s),console.log(),console.log(` ${q("Deploy:")} orch org deploy <key> --goal "Your objective"`),console.log();}),h.command("deploy <template>").description("Deploy a pre-built AI company").option("--goal <goal>","Set a goal for the team").action(async(c,s)=>{let e=v(c);if(!e){i(`Unknown template "${c}"`,"Run: orch org list \u2014 to see available templates"),process.exitCode=1;return}let a=[];for(let n of e.agents){let o=b(n.shop_key);if(!o){i(`Agent shop template not found: ${n.shop_key}`),process.exitCode=1;return}try{let r=await t.agentService.create({name:n.name,adapter:o.adapter,role:o.role,model:o.model,approval_policy:o.approval_policy,skills:o.skills});a.push(r.id);}catch(r){i(`Failed to create agent "${n.name}": ${r instanceof Error?r.message:String(r)}`,a.length>0?`${a.length} agent(s) were already created. Clean up with: orch agent list`:void 0),process.exitCode=1;return}}let g=a[e.lead_index],w=a.filter(n=>n!==g),y=await t.teamService.create({name:e.name,description:e.description,lead_agent_id:g,member_agent_ids:w}),m;if(s.goal&&(m=(await t.goalService.create({title:s.goal,assignee:g})).id),t.context.json){console.log(JSON.stringify({team:y,agentIds:a,goalId:m},null,2));return}if(t.context.quiet){console.log(y.id);return}console.log(),j(`Deployed team "${e.name}" \u2014 ${e.agents.length} agents`),console.log();for(let n=0;n<e.agents.length;n++){let o=e.agents[n],r=a[n],k=n===e.lead_index,S=k?"lead":"member";console.log(` ${k?"\u2605":"\u2022"} ${o.name} ${q(`(${r}, ${S})`)}`);}console.log(`
2
+ import {b}from'./chunk-HWEMBO36.js';import {l,q,i,j}from'./chunk-64WUDYEM.js';var d=[{key:"startup-mvp",name:"Startup MVP",description:"Ship an MVP in 48 hours",lead_index:0,agents:[{shop_key:"architect",name:"CTO"},{shop_key:"backend-dev",name:"Backend"},{shop_key:"backend-dev",name:"Backend 2"},{shop_key:"frontend-dev",name:"Frontend"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"pr-review-corp",name:"PR Review Corp",description:"Automated review for every PR",lead_index:0,agents:[{shop_key:"architect",name:"CTO"},{shop_key:"security-auditor",name:"Security"},{shop_key:"performance-engineer",name:"Performance"},{shop_key:"code-reviewer",name:"Style"},{shop_key:"qa-engineer",name:"QA"}]},{key:"migration-squad",name:"Migration Squad",description:"JS-to-TS migration over a weekend",lead_index:0,agents:[{shop_key:"architect",name:"CTO"},{shop_key:"fullstack-dev",name:"Migrator"},{shop_key:"fullstack-dev",name:"Migrator 2"},{shop_key:"fullstack-dev",name:"Migrator 3"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"security-dept",name:"Security Department",description:"Multi-layer security audit",lead_index:0,agents:[{shop_key:"security-auditor",name:"Lead Auditor"},{shop_key:"security-auditor",name:"Scanner"},{shop_key:"security-auditor",name:"Secrets Auditor"},{shop_key:"bug-hunter",name:"Hunter"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"test-factory",name:"Test Factory",description:"Coverage from 40% to 80% overnight",lead_index:0,agents:[{shop_key:"qa-engineer",name:"Coverage Lead"},{shop_key:"backend-dev",name:"Backend"},{shop_key:"backend-dev",name:"Backend 2"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"qa-engineer",name:"QA 2"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"content-agency",name:"Content Agency",description:"Content factory: plan, write, edit, optimize",lead_index:0,agents:[{shop_key:"marketer",name:"Strategist"},{shop_key:"content-creator",name:"Writer"},{shop_key:"content-creator",name:"Writer 2"},{shop_key:"tech-writer",name:"Editor"},{shop_key:"growth-hacker",name:"SEO"}]},{key:"data-lab",name:"Data Lab",description:"3 CSVs to executive report by morning",lead_index:0,agents:[{shop_key:"data-engineer",name:"Lead Analyst"},{shop_key:"data-engineer",name:"Data Engineer"}]},{key:"sales-machine",name:"Sales Machine",description:"Outbound pipeline: research, outreach, follow-up, close",lead_index:0,agents:[{shop_key:"marketer",name:"Sales Director"},{shop_key:"content-creator",name:"SDR"},{shop_key:"content-creator",name:"SDR 2"},{shop_key:"content-creator",name:"Copywriter"},{shop_key:"growth-hacker",name:"Growth Analyst"}]},{key:"bugfix-dept",name:"Bugfix Department",description:"100 issues to 0 in a week",lead_index:0,agents:[{shop_key:"architect",name:"Triager"},{shop_key:"bug-hunter",name:"Fixer"},{shop_key:"bug-hunter",name:"Fixer 2"},{shop_key:"bug-hunter",name:"Fixer 3"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"docs-team",name:"Docs Team",description:"Technical docs from codebase analysis",lead_index:0,agents:[{shop_key:"architect",name:"Docs Lead"},{shop_key:"tech-writer",name:"Writer"},{shop_key:"tech-writer",name:"Writer 2"},{shop_key:"tech-writer",name:"Editor"},{shop_key:"code-reviewer",name:"Reviewer"}]}];function v(l){return d.find(t=>t.key===l)}function C(l$1,t){let h=l$1.command("org").description("Pre-built AI companies \u2014 deploy a full department with one command");h.command("list").alias("ls").description("List available company templates").action(async()=>{if(t.context.json){console.log(JSON.stringify(d,null,2));return}console.log();let c=["KEY","NAME","AGENTS","DESCRIPTION"],s=d.map(e=>[e.key,e.name,String(e.agents.length),e.description]);l(c,s),console.log(),console.log(` ${q("Deploy:")} orch org deploy <key> --goal "Your objective"`),console.log();}),h.command("deploy <template>").description("Deploy a pre-built AI company").option("--goal <goal>","Set a goal for the team").action(async(c,s)=>{let e=v(c);if(!e){i(`Unknown template "${c}"`,"Run: orch org list \u2014 to see available templates"),process.exitCode=1;return}let a=[];for(let n of e.agents){let o=b(n.shop_key);if(!o){i(`Agent shop template not found: ${n.shop_key}`),process.exitCode=1;return}try{let r=await t.agentService.create({name:n.name,adapter:o.adapter,role:o.role,model:o.model,approval_policy:o.approval_policy,skills:o.skills});a.push(r.id);}catch(r){i(`Failed to create agent "${n.name}": ${r instanceof Error?r.message:String(r)}`,a.length>0?`${a.length} agent(s) were already created. Clean up with: orch agent list`:void 0),process.exitCode=1;return}}let g=a[e.lead_index],w=a.filter(n=>n!==g),y=await t.teamService.create({name:e.name,description:e.description,lead_agent_id:g,member_agent_ids:w}),m;if(s.goal&&(m=(await t.goalService.create({title:s.goal,assignee:g})).id),t.context.json){console.log(JSON.stringify({team:y,agentIds:a,goalId:m},null,2));return}if(t.context.quiet){console.log(y.id);return}console.log(),j(`Deployed team "${e.name}" \u2014 ${e.agents.length} agents`),console.log();for(let n=0;n<e.agents.length;n++){let o=e.agents[n],r=a[n],k=n===e.lead_index,S=k?"lead":"member";console.log(` ${k?"\u2605":"\u2022"} ${o.name} ${q(`(${r}, ${S})`)}`);}console.log(`
3
3
  Team: ${q(y.id)}`),m&&console.log(` Goal: ${q(m)} \u2014 "${s.goal}"`),console.log(),console.log(` ${q("Next:")} orch run --all --watch`),console.log();});}export{C as registerOrgCommand};
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import {l,k}from'./chunk-ZMLF5HI5.js';import {readFile}from'fs/promises';import {fileURLToPath}from'url';import {join,dirname}from'path';var f=/^[a-z0-9-]+$/;async function p(){let l=dirname(fileURLToPath(import.meta.url)),i=l;for(let r=0;r<5;r++){let t=join(i,"skills","library");if(await k(t))return t;i=dirname(i);}return join(l,"..","..","..","skills","library")}var m=class{cache=new Map;libraryDirPromise;availableCache=null;constructor(i){this.libraryDirPromise=i?Promise.resolve(i):p();}async loadSkills(i){let r=i.filter(s=>!s.includes(":"));if(r.length===0)return "";let t=await Promise.all(r.map(s=>this.loadOne(s))),e=r.map((s,n)=>t[n]?`### ${s}
3
+
4
+ ${t[n]}`:null).filter(s=>s!==null);return e.length===0?"":`## Skills
5
+
6
+ ${e.join(`
7
+
8
+ `)}`}async listAvailable(){if(this.availableCache)return this.availableCache;let i=await this.libraryDirPromise,r=await l(i,".md");return this.availableCache=r.map(t=>t.replace(/\.md$/,"")).sort(),this.availableCache}async loadOne(i){let r=this.cache.get(i);if(r!==void 0)return r||null;if(!f.test(i))return null;let t=await this.libraryDirPromise,e=join(t,`${i}.md`);try{let s=await readFile(e,"utf8");return this.cache.set(i,s),s}catch{return process.stderr.write(`[orch] skill library: "${i}" not found in ${t}
9
+ `),this.cache.set(i,""),null}}};export{m as SkillLoader};
@@ -0,0 +1,4 @@
1
+ export { SkillLoader } from './chunk-U2JVMD2G.js';
2
+ import './chunk-W3J7CURM.js';
3
+ //# sourceMappingURL=skill-loader-RHCFIK74.js.map
4
+ //# sourceMappingURL=skill-loader-RHCFIK74.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"skill-loader-RHCFIK74.js"}
@@ -17,4 +17,4 @@ import {j,q,g,d,e,o,l,n,m}from'./chunk-64WUDYEM.js';function x(_,a){let c=_.comm
17
17
  Review Results
18
18
  ${"\u2500".repeat(42)}`);for(let o of t.review_results){let n=o.passed?"\u2713":"\u2717";if(console.log(` ${n} ${o.criterion}: ${o.passed?"passed":"failed"}`),o.output)for(let l of o.output.split(`
19
19
  `))console.log(` ${l}`);}}console.log();}),c.command("edit <id>").description("Open task in $EDITOR to modify title, priority and description").action(async e=>{let t=await a.taskService.get(e),{openInEditor:i,toEditorContent:o,fromEditorContent:n}=await import('./editor-7IFRWVTL.js'),l=t.attachments?.length?`
20
- # Attachments: ${t.attachments.join(", ")}`:"",d=o({title:t.title,priority:t.priority,description:t.description})+l,s=await i(d),r=n(s),g={};if(r.title&&r.title!==t.title&&(g.title=r.title),r.priority&&r.priority!==t.priority&&(g.priority=r.priority),r.description!==void 0&&r.description!==t.description&&(g.description=r.description??""),Object.keys(g).length===0){console.log(" No changes.");return}let w=await a.taskService.update(e,g);j(`Updated ${w.id} "${w.title}"`);}),c.command("assign <task-id> <agent-id>").description("Assign task to agent").action(async(e,t)=>{let i=await a.taskService.assign(e,t);j(`Assigned ${i.id} \u2192 ${t}`);}),c.command("cancel <id>").description("Cancel a task").action(async e=>{if((await a.taskService.get(e)).status==="in_progress"){let{buildFullContainer:i}=await import('./container-FXUUV6PP.js');await(await i(a.context)).orchestrator.cancelTask(e);}else await a.taskService.cancel(e);j(`Cancelled ${e}`);}),c.command("approve <id>").description("Approve a task in review").action(async e=>{await a.taskService.updateStatus(e,"done"),j(`Approved ${e}`);}),c.command("reject <id>").description("Reject a task and send it back for rework").option("-r, --reason <reason>","Feedback for the agent explaining what to fix").action(async(e,t)=>{await a.taskService.reject(e,t.reason),j(`Rejected ${e} \u2192 todo${t.reason?` (reason: ${t.reason})`:""}`);}),c.command("retry <id>").description("Retry a failed task").action(async e=>{await a.taskService.retry(e),j(`Reset ${e} to todo`);});}export{x as registerTaskCommand};
20
+ # Attachments: ${t.attachments.join(", ")}`:"",d=o({title:t.title,priority:t.priority,description:t.description})+l,s=await i(d),r=n(s),g={};if(r.title&&r.title!==t.title&&(g.title=r.title),r.priority&&r.priority!==t.priority&&(g.priority=r.priority),r.description!==void 0&&r.description!==t.description&&(g.description=r.description??""),Object.keys(g).length===0){console.log(" No changes.");return}let w=await a.taskService.update(e,g);j(`Updated ${w.id} "${w.title}"`);}),c.command("assign <task-id> <agent-id>").description("Assign task to agent").action(async(e,t)=>{let i=await a.taskService.assign(e,t);j(`Assigned ${i.id} \u2192 ${t}`);}),c.command("cancel <id>").description("Cancel a task").action(async e=>{if((await a.taskService.get(e)).status==="in_progress"){let{buildFullContainer:i}=await import('./container-SEIWOLHY.js');await(await i(a.context)).orchestrator.cancelTask(e);}else await a.taskService.cancel(e);j(`Cancelled ${e}`);}),c.command("approve <id>").description("Approve a task in review").action(async e=>{await a.taskService.updateStatus(e,"done"),j(`Approved ${e}`);}),c.command("reject <id>").description("Reject a task and send it back for rework").option("-r, --reason <reason>","Feedback for the agent explaining what to fix").action(async(e,t)=>{await a.taskService.reject(e,t.reason),j(`Rejected ${e} \u2192 todo${t.reason?` (reason: ${t.reason})`:""}`);}),c.command("retry <id>").description("Retry a failed task").action(async e=>{await a.taskService.retry(e),j(`Reset ${e} to todo`);});}export{x as registerTaskCommand};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- function ot(c,e){c.command("tui").description("Launch interactive TUI dashboard").action(async()=>{let v=await e.taskService.list(),S=await e.agentService.list(),w=await e.stateStore.read(),{render:f}=await import('ink'),{createElement:h}=await import('react'),{App:T}=await import('./App-LEVUTWQN.js'),k=async t=>{await e.orchestrator.runTask(t);},A=async(t,s)=>e.taskService.create({title:t,priority:s?.priority,description:s?.description,attachments:s?.attachments}),b=async t=>{await e.orchestrator.cancelTask(t);},C=async t=>{await e.taskService.retry(t);},R=async(t,s)=>{await e.taskService.assign(t,s);},_=async()=>{await e.orchestrator.runAll();},E=async t=>{await e.agentService.disable(t);},j=async t=>{await e.agentService.enable(t);},D=t=>e.eventBus.onAny(t),P=async()=>e.taskService.list(),G=async()=>e.agentService.list(),U=async()=>e.stateStore.read(),x=async(t,s,n)=>e.agentService.create({name:t,adapter:s??"claude",model:n?.model||void 0,role:n?.role||void 0,approval_policy:n?.approval_policy||void 0,skills:n?.skills||void 0}),L=async t=>{await e.agentService.remove(t);},H=async t=>{await e.taskService.delete(t);},I=async t=>{await e.taskService.updateStatus(t,"done");},W=async(t,s)=>{await e.taskService.reject(t,s);},F=async(t,s)=>e.taskService.update(t,s),N=async(t,s)=>e.agentService.update(t,{...s,approval_policy:s.approval_policy}),O=async t=>{await e.orchestrator.forceStopAgent(t);},B=async(t,s)=>e.agentService.setAutonomous(t,s),M=async t=>{let s=await e.runService.listAll();s.sort((a,r)=>new Date(r.started_at).getTime()-new Date(a.started_at).getTime());let n=s.filter(a=>a.status==="succeeded"||a.status==="failed"),m=3,rt=10,p=n.slice(0,m),u=n.slice(m,rt),y=async a=>(await e.runService.readEventsTail(a.id,30)).map(i=>({timestamp:i.timestamp,agentId:a.agent_id,taskId:a.task_id,type:i.type,data:i.data}));if(p.length>0){let a=(await Promise.all(p.map(y))).flat();a.sort((r,i)=>new Date(r.timestamp).getTime()-new Date(i.timestamp).getTime()),t(a.slice(-200));}if(u.length>0){let a=(await Promise.all(u.map(y))).flat();a.sort((r,i)=>new Date(r.timestamp).getTime()-new Date(i.timestamp).getTime()),t(a.slice(-200));}},V=async t=>e.teamService.create(t),J=async()=>e.teamService.list(),K=async(t,s)=>e.teamService.join(t,s),q=async(t,s)=>e.teamService.leave(t,s),z=async t=>{await e.teamService.disband(t);},Q=async(t,s)=>e.teamService.setLead(t,s),X=async()=>e.goalService.list(),Y=async t=>e.goalService.create(t),Z=async(t,s)=>e.goalService.update(t,s),$=async(t,s)=>e.goalService.updateStatus(t,s),tt=async t=>{await e.goalService.delete(t);},et=async t=>e.goalService.getProgressReport(t),st=async()=>{await e.orchestrator.startWatch();},at=async()=>{await e.orchestrator.stop();},l=c.version()??"0.0.0",nt=import('./update-check-HGMBDYHL.js').then(t=>t.checkForUpdateSWR(l)).catch(()=>null),o=false,g;try{await e.orchestrator.startWatch(),o=!0;}catch(t){g=t instanceof Error?t.message:String(t);}let d=await nt,{waitUntilExit:it}=f(h(T,{projectName:e.config.project.name,tasks:v,agents:S,state:w,onRunTask:k,onCreateTask:A,onCancelTask:b,onRetryTask:C,onAssignTask:R,onRunAll:_,onDisableAgent:E,onEnableAgent:j,onSubscribeEvents:D,onRefreshTasks:P,onRefreshAgents:G,onRefreshState:U,onLoadHistory:M,onAddAgent:x,onDeleteAgent:L,onApproveTask:I,onRejectTask:W,onDeleteTask:H,onUpdateTask:F,onUpdateAgent:N,onForceStopAgent:O,onToggleAutonomous:B,onRefreshGoals:X,onCreateGoal:Y,onUpdateGoal:Z,onUpdateGoalStatus:$,onDeleteGoal:tt,onGetGoalProgress:et,onCreateTeam:V,onListTeams:J,onJoinTeam:K,onLeaveTeam:q,onDisbandTeam:z,onSetTeamLead:Q,onStartWatch:st,onStopWatch:at,initialWatchActive:o,watchError:g,version:l,latestVersion:d?.updateAvailable?d.latest:void 0,initialActivityFilter:e.globalConfig.tui.activity_filter,onSaveActivityFilter:async t=>{await e.globalConfigStore.set("activity_filter",t);},initialNotifications:e.globalConfig.tui.notifications,onSaveNotifications:async t=>{await e.globalConfigStore.set("notifications",t);},initialMaxConcurrent:e.config.scheduling.max_concurrent_agents,onSaveMaxConcurrent:async t=>{await e.configStore.set("scheduling.max_concurrent_agents",t),e.config.scheduling.max_concurrent_agents=t;},onCompleteOnboarding:async()=>{let t=await e.stateStore.read();t.onboardingCompleted=true,await e.stateStore.write(t);}}),{kittyKeyboard:{mode:"auto",flags:["disambiguateEscapeCodes"]}});await it(),o&&await e.orchestrator.stop().catch(()=>{}),e.eventBus.clear();});}export{ot as registerTuiCommand};
2
+ function ot(c,e){c.command("tui").description("Launch interactive TUI dashboard").action(async()=>{let v=await e.taskService.list(),S=await e.agentService.list(),w=await e.stateStore.read(),{render:f}=await import('ink'),{createElement:h}=await import('react'),{App:T}=await import('./App-5OVBVRCD.js'),k=async t=>{await e.orchestrator.runTask(t);},A=async(t,s)=>e.taskService.create({title:t,priority:s?.priority,description:s?.description,attachments:s?.attachments}),b=async t=>{await e.orchestrator.cancelTask(t);},C=async t=>{await e.taskService.retry(t);},R=async(t,s)=>{await e.taskService.assign(t,s);},_=async()=>{await e.orchestrator.runAll();},E=async t=>{await e.agentService.disable(t);},j=async t=>{await e.agentService.enable(t);},D=t=>e.eventBus.onAny(t),P=async()=>e.taskService.list(),G=async()=>e.agentService.list(),U=async()=>e.stateStore.read(),x=async(t,s,n)=>e.agentService.create({name:t,adapter:s??"claude",model:n?.model||void 0,role:n?.role||void 0,approval_policy:n?.approval_policy||void 0,skills:n?.skills||void 0}),L=async t=>{await e.agentService.remove(t);},H=async t=>{await e.taskService.delete(t);},I=async t=>{await e.taskService.updateStatus(t,"done");},W=async(t,s)=>{await e.taskService.reject(t,s);},F=async(t,s)=>e.taskService.update(t,s),N=async(t,s)=>e.agentService.update(t,{...s,approval_policy:s.approval_policy}),O=async t=>{await e.orchestrator.forceStopAgent(t);},B=async(t,s)=>e.agentService.setAutonomous(t,s),M=async t=>{let s=await e.runService.listAll();s.sort((a,r)=>new Date(r.started_at).getTime()-new Date(a.started_at).getTime());let n=s.filter(a=>a.status==="succeeded"||a.status==="failed"),m=3,rt=10,p=n.slice(0,m),u=n.slice(m,rt),y=async a=>(await e.runService.readEventsTail(a.id,30)).map(i=>({timestamp:i.timestamp,agentId:a.agent_id,taskId:a.task_id,type:i.type,data:i.data}));if(p.length>0){let a=(await Promise.all(p.map(y))).flat();a.sort((r,i)=>new Date(r.timestamp).getTime()-new Date(i.timestamp).getTime()),t(a.slice(-200));}if(u.length>0){let a=(await Promise.all(u.map(y))).flat();a.sort((r,i)=>new Date(r.timestamp).getTime()-new Date(i.timestamp).getTime()),t(a.slice(-200));}},V=async t=>e.teamService.create(t),J=async()=>e.teamService.list(),K=async(t,s)=>e.teamService.join(t,s),q=async(t,s)=>e.teamService.leave(t,s),z=async t=>{await e.teamService.disband(t);},Q=async(t,s)=>e.teamService.setLead(t,s),X=async()=>e.goalService.list(),Y=async t=>e.goalService.create(t),Z=async(t,s)=>e.goalService.update(t,s),$=async(t,s)=>e.goalService.updateStatus(t,s),tt=async t=>{await e.goalService.delete(t);},et=async t=>e.goalService.getProgressReport(t),st=async()=>{await e.orchestrator.startWatch();},at=async()=>{await e.orchestrator.stop();},l=c.version()??"0.0.0",nt=import('./update-check-HGMBDYHL.js').then(t=>t.checkForUpdateSWR(l)).catch(()=>null),o=false,g;try{await e.orchestrator.startWatch(),o=!0;}catch(t){g=t instanceof Error?t.message:String(t);}let d=await nt,{waitUntilExit:it}=f(h(T,{projectName:e.config.project.name,tasks:v,agents:S,state:w,onRunTask:k,onCreateTask:A,onCancelTask:b,onRetryTask:C,onAssignTask:R,onRunAll:_,onDisableAgent:E,onEnableAgent:j,onSubscribeEvents:D,onRefreshTasks:P,onRefreshAgents:G,onRefreshState:U,onLoadHistory:M,onAddAgent:x,onDeleteAgent:L,onApproveTask:I,onRejectTask:W,onDeleteTask:H,onUpdateTask:F,onUpdateAgent:N,onForceStopAgent:O,onToggleAutonomous:B,onRefreshGoals:X,onCreateGoal:Y,onUpdateGoal:Z,onUpdateGoalStatus:$,onDeleteGoal:tt,onGetGoalProgress:et,onCreateTeam:V,onListTeams:J,onJoinTeam:K,onLeaveTeam:q,onDisbandTeam:z,onSetTeamLead:Q,onStartWatch:st,onStopWatch:at,initialWatchActive:o,watchError:g,version:l,latestVersion:d?.updateAvailable?d.latest:void 0,initialActivityFilter:e.globalConfig.tui.activity_filter,onSaveActivityFilter:async t=>{await e.globalConfigStore.set("activity_filter",t);},initialNotifications:e.globalConfig.tui.notifications,onSaveNotifications:async t=>{await e.globalConfigStore.set("notifications",t);},initialMaxConcurrent:e.config.scheduling.max_concurrent_agents,onSaveMaxConcurrent:async t=>{await e.configStore.set("scheduling.max_concurrent_agents",t),e.config.scheduling.max_concurrent_agents=t;},onCompleteOnboarding:async()=>{let t=await e.stateStore.read();t.onboardingCompleted=true,await e.stateStore.write(t);}}),{kittyKeyboard:{mode:"auto",flags:["disambiguateEscapeCodes"]}});await it(),o&&await e.orchestrator.stop().catch(()=>{}),e.eventBus.clear();});}export{ot as registerTuiCommand};
@@ -1,4 +1,5 @@
1
- import { sanitizeId, validateWorkspacePath, ensureDir } from './chunk-EH3HRQP4.js';
1
+ import { sanitizeId, validateWorkspacePath } from './chunk-J7ITYXE6.js';
2
+ import { ensureDir } from './chunk-W3J7CURM.js';
2
3
  import { WorkspaceError } from './chunk-NLQAJ7TW.js';
3
4
  import path from 'path';
4
5
  import fs from 'fs/promises';
@@ -228,5 +229,5 @@ function sanitizeTitle(title) {
228
229
  }
229
230
 
230
231
  export { WorkspaceManager };
231
- //# sourceMappingURL=workspace-manager-5EYCMAEO.js.map
232
- //# sourceMappingURL=workspace-manager-5EYCMAEO.js.map
232
+ //# sourceMappingURL=workspace-manager-RH24FSNT.js.map
233
+ //# sourceMappingURL=workspace-manager-RH24FSNT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/infrastructure/workspace/merge-strategy.ts","../src/infrastructure/workspace/workspace-manager.ts"],"names":[],"mappings":";;;;;;;AAYO,IAAM,gBAAN,MAAoB;AAAA,EACzB,WAAA,CACmB,aACA,cAAA,EACjB;AAFiB,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AACA,IAAA,IAAA,CAAA,cAAA,GAAA,cAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMH,MAAM,UAAU,MAAA,EAAsC;AACpD,IAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,KAAY;AAC9B,MAAA,MAAM,EAAE,OAAA,EAAS,IAAA,EAAK,GAAI,KAAK,cAAA,CAAe,KAAA;AAAA,QAC5C,KAAA;AAAA,QACA,CAAC,OAAA,EAAS,SAAA,EAAW,QAAQ,IAAA,EAAM,CAAA,MAAA,EAAS,MAAM,CAAA,CAAE,CAAA;AAAA,QACpD,EAAE,GAAA,EAAK,IAAA,CAAK,WAAA;AAAY,OAC1B;AAEA,MAAA,IAAI,MAAA,GAAS,EAAA;AACb,MAAA,MAAM,YAAA,GAAe,GAAA;AACrB,MAAA,MAAM,YAAA,GAAe,CAAC,KAAA,KAAkB;AACtC,QAAA,IAAI,MAAA,CAAO,MAAA,GAAS,YAAA,EAAc,MAAA,IAAU,MAAM,QAAA,EAAS;AAAA,MAC7D,CAAA;AACA,MAAA,IAAA,CAAK,MAAA,EAAQ,EAAA,CAAG,MAAA,EAAQ,YAAY,CAAA;AACpC,MAAA,IAAA,CAAK,MAAA,EAAQ,EAAA,CAAG,MAAA,EAAQ,YAAY,CAAA;AAEpC,MAAA,IAAA,CAAK,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AG,CAAA,CAC1B,OAAA,CAAQ,QAAA,EAAU,EAAE,CAAA,CACpB,KAAA,CAAM,GAAG,EAAE,CAAA;AAChB","file":"workspace-manager-RH24FSNT.js","sourcesContent":["/**\n * Git merge strategy for worktree branches.\n *\n * Encapsulates `git merge --no-ff` execution and conflict handling.\n */\n\nimport type { IProcessManager } from '../process/process-manager.js';\n\nexport type MergeResult =\n | { success: true }\n | { success: false; conflictInfo: string };\n\nexport class MergeStrategy {\n constructor(\n private readonly projectRoot: string,\n private readonly processManager: IProcessManager,\n ) {}\n\n /**\n * Merge a branch into the current branch with --no-ff.\n * On conflict, aborts the merge and returns conflict info.\n */\n async mergeBack(branch: string): Promise<MergeResult> {\n return new Promise((resolve) => {\n const { process: proc } = this.processManager.spawn(\n 'git',\n ['merge', '--no-ff', branch, '-m', `Merge ${branch}`],\n { cwd: this.projectRoot },\n );\n\n let output = '';\n const maxOutputLen = 2000;\n const appendOutput = (chunk: Buffer) => {\n if (output.length < maxOutputLen) output += chunk.toString();\n };\n proc.stdout?.on('data', appendOutput);\n proc.stderr?.on('data', appendOutput);\n\n proc.on('close', (code) => {\n if (code === 0) {\n resolve({ success: true });\n return;\n }\n\n const trimmedOutput = output.slice(0, 1000);\n const isConflict = trimmedOutput.includes('CONFLICT') || trimmedOutput.includes('Merge conflict');\n\n if (!isConflict) {\n // Non-conflict failure (branch not found, hook failure, etc.) — no merge to abort\n resolve({ success: false, conflictInfo: trimmedOutput });\n return;\n }\n\n // Abort the failed merge to restore clean state\n try {\n const { process: abortProc } = this.processManager.spawn(\n 'git',\n ['merge', '--abort'],\n { cwd: this.projectRoot },\n );\n abortProc.on('close', () => {\n resolve({ success: false, conflictInfo: trimmedOutput });\n });\n abortProc.on('error', () => {\n resolve({ success: false, conflictInfo: trimmedOutput });\n });\n } catch {\n resolve({ success: false, conflictInfo: trimmedOutput });\n }\n });\n\n proc.on('error', (err) => {\n resolve({ success: false, conflictInfo: err.message });\n });\n });\n }\n}\n","/**\n * Workspace manager implementation.\n *\n * Resolves workspace path based on mode priority chain:\n * task.workspace_mode → agent.config.workspace_mode → defaults.agent.workspace_mode → 'worktree'\n */\n\nimport path from 'node:path';\nimport fs from 'node:fs/promises';\nimport type { Agent } from '../../domain/agent.js';\nimport type { OrchestratorConfig } from '../../domain/config.js';\nimport type { Task, WorkspaceMode } from '../../domain/task.js';\nimport type { IProcessManager } from '../process/process-manager.js';\nimport { validateWorkspacePath, sanitizeId } from '../storage/paths.js';\nimport { ensureDir } from '../storage/fs-utils.js';\nimport type { IWorkspaceManager, PrepareResult } from './interface.js';\nimport { MergeStrategy, type MergeResult } from './merge-strategy.js';\nimport { WorkspaceError } from '../../domain/errors.js';\n\nexport class WorkspaceManager implements IWorkspaceManager {\n private readonly mergeStrategy: MergeStrategy;\n private gitRepoChecked = false;\n private isGitRepo = false;\n\n constructor(\n private readonly projectRoot: string,\n private readonly orchestryDir: string,\n private readonly processManager: IProcessManager,\n ) {\n this.mergeStrategy = new MergeStrategy(projectRoot, processManager);\n }\n\n async prepare(task: Task, agent: Agent, config: OrchestratorConfig): Promise<PrepareResult> {\n const mode = this.resolveMode(task, agent, config);\n\n if (mode !== 'shared') {\n await this.requireGitRepo(mode);\n }\n\n switch (mode) {\n case 'shared':\n return { path: this.projectRoot };\n\n case 'worktree':\n return this.prepareWorktree(task);\n\n case 'isolated':\n return { path: await this.prepareIsolated(task) };\n\n default:\n return { path: this.projectRoot };\n }\n }\n\n private async requireGitRepo(mode: WorkspaceMode): Promise<void> {\n if (!this.gitRepoChecked) {\n try {\n const { process: proc } = this.processManager.spawn(\n 'git',\n ['rev-parse', '--is-inside-work-tree'],\n { cwd: this.projectRoot },\n );\n const code = await new Promise<number | null>((resolve) => {\n proc.on('close', resolve);\n proc.on('error', () => resolve(1));\n });\n this.isGitRepo = code === 0;\n } catch {\n this.isGitRepo = false;\n }\n // Only cache positive result — negative may change if user runs git init\n if (this.isGitRepo) this.gitRepoChecked = true;\n }\n\n if (!this.isGitRepo) {\n throw new WorkspaceError(\n `workspace_mode \"${mode}\" requires a git repository`,\n 'Run: git init && git add -A && git commit -m \"Initial commit\"\\n Or set workspace_mode: shared in .orchestry/config.yml',\n );\n }\n }\n\n async mergeBack(branch: string): Promise<MergeResult> {\n return this.mergeStrategy.mergeBack(branch);\n }\n\n async cleanup(taskId: string, branch?: string): Promise<void> {\n const workspacePath = path.join(this.orchestryDir, 'workspaces', sanitizeId(taskId));\n\n // Try git worktree remove first (cleans up .git/worktrees/ metadata)\n try {\n const { process: proc } = this.processManager.spawn(\n 'git',\n ['worktree', 'remove', '--force', workspacePath],\n { cwd: this.projectRoot },\n );\n await new Promise<void>((resolve) => {\n proc.on('close', () => resolve());\n proc.on('error', () => resolve());\n });\n } catch {\n // Not a worktree or git not available — fall through to rm\n }\n\n // Delete branch + remove directory concurrently (independent of each other)\n const branchDeletion = branch\n ? (async () => {\n try {\n const { process: proc } = this.processManager.spawn(\n 'git',\n ['branch', '-D', branch],\n { cwd: this.projectRoot },\n );\n await new Promise<void>((resolve) => {\n proc.on('close', () => resolve());\n proc.on('error', () => resolve());\n });\n } catch {\n // Branch may not exist or git not available\n }\n })()\n : Promise.resolve();\n\n const dirRemoval = fs.rm(workspacePath, { recursive: true, force: true }).catch(() => {});\n\n await Promise.all([branchDeletion, dirRemoval]);\n }\n\n validate(workspacePath: string, projectRoot: string): void {\n validateWorkspacePath(workspacePath, projectRoot);\n }\n\n private resolveMode(task: Task, agent: Agent, config: OrchestratorConfig): WorkspaceMode {\n return (\n task.workspace_mode ??\n agent.config.workspace_mode ??\n config.defaults.agent.workspace_mode ??\n 'worktree'\n );\n }\n\n private async prepareWorktree(task: Task): Promise<PrepareResult> {\n const workspacePath = path.join(\n this.orchestryDir,\n 'workspaces',\n sanitizeId(task.id),\n );\n await ensureDir(path.dirname(workspacePath));\n\n const titleSlug = sanitizeTitle(task.title) || sanitizeId(task.id);\n const branchName = `orchestry/${sanitizeId(task.id)}/${titleSlug}`;\n\n const { process: proc } = this.processManager.spawn(\n 'git',\n ['worktree', 'add', workspacePath, '-b', branchName],\n { cwd: this.projectRoot },\n );\n\n await new Promise<void>((resolve, reject) => {\n proc.on('close', (code) => {\n if (code === 0) resolve();\n else reject(new WorkspaceError(\n `git worktree add failed with code ${code}`,\n 'Run: git worktree prune && git branch | grep orchestry | xargs -r git branch -D',\n ));\n });\n proc.on('error', reject);\n });\n\n // Remove .orchestry/ from worktree to prevent recursive state/workspaces\n const worktreeOrchestry = path.join(workspacePath, '.orchestry');\n await fs.rm(worktreeOrchestry, { recursive: true, force: true }).catch(() => {});\n\n return { path: workspacePath, branch: branchName };\n }\n\n private async prepareIsolated(task: Task): Promise<string> {\n const workspacePath = path.join(\n this.orchestryDir,\n 'workspaces',\n sanitizeId(task.id),\n );\n await ensureDir(path.dirname(workspacePath));\n\n // Try git clone first, fall back to rsync\n try {\n const { process: proc } = this.processManager.spawn(\n 'git',\n ['clone', '--local', '--no-hardlinks', '.', workspacePath],\n { cwd: this.projectRoot },\n );\n\n await new Promise<void>((resolve, reject) => {\n proc.on('close', (code) => {\n if (code === 0) resolve();\n else reject(new Error('git clone failed'));\n });\n proc.on('error', reject);\n });\n } catch {\n // Fallback: rsync\n const excludeFile = path.join(this.orchestryDir, 'workspace-exclude');\n const args = ['-a', `--exclude-from=${excludeFile}`, './', `${workspacePath}/`];\n\n const { process: proc } = this.processManager.spawn('rsync', args, {\n cwd: this.projectRoot,\n });\n\n await new Promise<void>((resolve, reject) => {\n proc.on('close', (code) => {\n if (code === 0) resolve();\n else reject(new Error(`rsync failed with code ${code}`));\n });\n proc.on('error', reject);\n });\n }\n\n // Remove .orchestry/ to prevent recursive workspaces (covers both clone and rsync)\n const clonedOrchestry = path.join(workspacePath, '.orchestry');\n await fs.rm(clonedOrchestry, { recursive: true, force: true }).catch(() => {});\n\n return workspacePath;\n }\n}\n\nfunction sanitizeTitle(title: string): string {\n return title\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '')\n .slice(0, 40);\n}\n"]}
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import {c,d}from'./chunk-3AXNSYCM.js';import {j}from'./chunk-ZMLF5HI5.js';import {l as l$1}from'./chunk-IKNBPOQL.js';import n from'path';import u from'fs/promises';var l=class{constructor(r,e){this.projectRoot=r;this.processManager=e;}async mergeBack(r){return new Promise(e=>{let{process:t}=this.processManager.spawn("git",["merge","--no-ff",r,"-m",`Merge ${r}`],{cwd:this.projectRoot}),o="",a=2e3,i=s=>{o.length<a&&(o+=s.toString());};t.stdout?.on("data",i),t.stderr?.on("data",i),t.on("close",s=>{if(s===0){e({success:true});return}let c=o.slice(0,1e3);if(!(c.includes("CONFLICT")||c.includes("Merge conflict"))){e({success:false,conflictInfo:c});return}try{let{process:f}=this.processManager.spawn("git",["merge","--abort"],{cwd:this.projectRoot});f.on("close",()=>{e({success:!1,conflictInfo:c});}),f.on("error",()=>{e({success:!1,conflictInfo:c});});}catch{e({success:false,conflictInfo:c});}}),t.on("error",s=>{e({success:false,conflictInfo:s.message});});})}};var y=class{constructor(r,e,t){this.projectRoot=r;this.orchestryDir=e;this.processManager=t;this.mergeStrategy=new l(r,t);}mergeStrategy;gitRepoChecked=false;isGitRepo=false;async prepare(r,e,t){let o=this.resolveMode(r,e,t);switch(o!=="shared"&&await this.requireGitRepo(o),o){case "shared":return {path:this.projectRoot};case "worktree":return this.prepareWorktree(r);case "isolated":return {path:await this.prepareIsolated(r)};default:return {path:this.projectRoot}}}async requireGitRepo(r){if(!this.gitRepoChecked){try{let{process:e}=this.processManager.spawn("git",["rev-parse","--is-inside-work-tree"],{cwd:this.projectRoot}),t=await new Promise(o=>{e.on("close",o),e.on("error",()=>o(1));});this.isGitRepo=t===0;}catch{this.isGitRepo=false;}this.isGitRepo&&(this.gitRepoChecked=true);}if(!this.isGitRepo)throw new l$1(`workspace_mode "${r}" requires a git repository`,`Run: git init && git add -A && git commit -m "Initial commit"
3
+ Or set workspace_mode: shared in .orchestry/config.yml`)}async mergeBack(r){return this.mergeStrategy.mergeBack(r)}async cleanup(r,e){let t=n.join(this.orchestryDir,"workspaces",c(r));try{let{process:i}=this.processManager.spawn("git",["worktree","remove","--force",t],{cwd:this.projectRoot});await new Promise(s=>{i.on("close",()=>s()),i.on("error",()=>s());});}catch{}let o=e?(async()=>{try{let{process:i}=this.processManager.spawn("git",["branch","-D",e],{cwd:this.projectRoot});await new Promise(s=>{i.on("close",()=>s()),i.on("error",()=>s());});}catch{}})():Promise.resolve(),a=u.rm(t,{recursive:true,force:true}).catch(()=>{});await Promise.all([o,a]);}validate(r,e){d(r,e);}resolveMode(r,e,t){return r.workspace_mode??e.config.workspace_mode??t.defaults.agent.workspace_mode??"worktree"}async prepareWorktree(r){let e=n.join(this.orchestryDir,"workspaces",c(r.id));await j(n.dirname(e));let t=k(r.title)||c(r.id),o=`orchestry/${c(r.id)}/${t}`,{process:a}=this.processManager.spawn("git",["worktree","add",e,"-b",o],{cwd:this.projectRoot});await new Promise((s,c)=>{a.on("close",p=>{p===0?s():c(new l$1(`git worktree add failed with code ${p}`,"Run: git worktree prune && git branch | grep orchestry | xargs -r git branch -D"));}),a.on("error",c);});let i=n.join(e,".orchestry");return await u.rm(i,{recursive:true,force:true}).catch(()=>{}),{path:e,branch:o}}async prepareIsolated(r){let e=n.join(this.orchestryDir,"workspaces",c(r.id));await j(n.dirname(e));try{let{process:o}=this.processManager.spawn("git",["clone","--local","--no-hardlinks",".",e],{cwd:this.projectRoot});await new Promise((a,i)=>{o.on("close",s=>{s===0?a():i(new Error("git clone failed"));}),o.on("error",i);});}catch{let a=["-a",`--exclude-from=${n.join(this.orchestryDir,"workspace-exclude")}`,"./",`${e}/`],{process:i}=this.processManager.spawn("rsync",a,{cwd:this.projectRoot});await new Promise((s,c)=>{i.on("close",p=>{p===0?s():c(new Error(`rsync failed with code ${p}`));}),i.on("error",c);});}let t=n.join(e,".orchestry");return await u.rm(t,{recursive:true,force:true}).catch(()=>{}),e}};function k(d){return d.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40)}export{y as WorkspaceManager};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxgeneral/orch",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "AI agent runtime — orchestrate Claude, Cursor, Codex & OpenCode as one team. Multi-agent task automation with state machine, auto-retry, inter-agent messaging, goals and teams. Zero-config CLI + programmatic API.",
5
5
  "type": "module",
6
6
  "engines": {