@oxgeneral/orch 0.2.2 → 0.2.4

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 (46) hide show
  1. package/dist/{App-NHSVGERJ.js → App-KHUT3IV7.js} +316 -105
  2. package/dist/{chunk-VTA74YWX.js → chunk-2KSBOAW3.js} +1 -1
  3. package/dist/{chunk-O5AO5QIR.js → chunk-3TGCIXJA.js} +7 -1
  4. package/dist/{chunk-6GFVB6EK.js → chunk-FRTKB575.js} +24 -38
  5. package/dist/chunk-K6DMQERQ.js +89 -0
  6. package/dist/{chunk-2B32FPEB.js → chunk-QTDKQYZI.js} +3 -3
  7. package/dist/{chunk-2B32FPEB.js.map → chunk-QTDKQYZI.js.map} +1 -1
  8. package/dist/{chunk-ZU6AY2VU.js → chunk-VAAOW526.js} +2 -2
  9. package/dist/chunk-VAAOW526.js.map +1 -0
  10. package/dist/chunk-ZTQ3KWXR.js +13 -0
  11. package/dist/chunk-ZTQ3KWXR.js.map +1 -0
  12. package/dist/cli.js +17 -20
  13. package/dist/{container-JV7TAUP5.js → container-KPH4HVAJ.js} +6 -6
  14. package/dist/{doctor-IO4PV4D6.js → doctor-GHRV5I2S.js} +4 -4
  15. package/dist/doctor-service-QEJCE5FK.js +3 -0
  16. package/dist/doctor-service-QEJCE5FK.js.map +1 -0
  17. package/dist/doctor-service-TPOMFAIG.js +2 -0
  18. package/dist/index.d.ts +20 -4
  19. package/dist/index.js +3 -3
  20. package/dist/index.js.map +1 -1
  21. package/dist/{init-UCVRVBVI.js → init-EQTGQ4G2.js} +60 -52
  22. package/dist/{logs-IAUAS5TX.js → logs-AK255DEJ.js} +1 -1
  23. package/dist/orchestrator-L6QX2LJ7.js +2 -0
  24. package/dist/{orchestrator-TAFBYQQ5.js.map → orchestrator-L6QX2LJ7.js.map} +1 -1
  25. package/dist/{orchestrator-VGYKSOZJ.js → orchestrator-OMU46RCE.js} +47 -19
  26. package/dist/{task-5OJTXW27.js → task-35SDKXFC.js} +1 -1
  27. package/dist/{tui-AAEAU4HT.js → tui-AR6PVMBQ.js} +6 -1
  28. package/dist/{update-72GZMF65.js → update-DCCWVISK.js} +1 -1
  29. package/dist/update-check-4YKLGBFB.js +2 -0
  30. package/dist/workspace-manager-AS4TFA7R.js +3 -0
  31. package/dist/workspace-manager-AS4TFA7R.js.map +1 -0
  32. package/dist/{workspace-manager-47KI7B27.js → workspace-manager-G5EQRS72.js} +38 -2
  33. package/package.json +1 -1
  34. package/readme.md +6 -15
  35. package/scripts/release.sh +32 -0
  36. package/dist/chunk-E3TCKHU6.js +0 -13
  37. package/dist/chunk-E3TCKHU6.js.map +0 -1
  38. package/dist/chunk-XI4TU6VU.js +0 -50
  39. package/dist/chunk-ZU6AY2VU.js.map +0 -1
  40. package/dist/doctor-service-A34DHPKI.js +0 -2
  41. package/dist/doctor-service-NTWBWOM2.js +0 -2
  42. package/dist/doctor-service-NTWBWOM2.js.map +0 -1
  43. package/dist/orchestrator-TAFBYQQ5.js +0 -2
  44. package/dist/update-check-4RV7Z6WT.js +0 -2
  45. package/dist/workspace-manager-7M46ESUL.js +0 -2
  46. package/dist/workspace-manager-7M46ESUL.js.map +0 -1
@@ -8,6 +8,7 @@ var PACKAGE_NAME = "@oxgeneral/orch";
8
8
  var CACHE_DIR = path.join(os.homedir(), ".orchestry");
9
9
  var CACHE_FILE = path.join(CACHE_DIR, "update-check.json");
10
10
  var CHECK_INTERVAL_MS = 4 * 60 * 60 * 1e3;
11
+ var REVALIDATE_AFTER_MS = CHECK_INTERVAL_MS * 0.75;
11
12
  function compareSemver(a, b) {
12
13
  const pa = a.split(".").map(Number);
13
14
  const pb = b.split(".").map(Number);
@@ -35,7 +36,7 @@ async function writeCache(latest) {
35
36
  }
36
37
  function fetchLatestVersion() {
37
38
  return new Promise((resolve) => {
38
- execFile("npm", ["view", PACKAGE_NAME, "version", "--json"], { timeout: 5e3 }, (err, stdout) => {
39
+ const child = execFile("npm", ["view", PACKAGE_NAME, "version", "--json"], { timeout: 5e3 }, (err, stdout) => {
39
40
  if (err) return resolve(null);
40
41
  try {
41
42
  resolve(JSON.parse(stdout.trim()));
@@ -43,52 +44,37 @@ function fetchLatestVersion() {
43
44
  resolve(null);
44
45
  }
45
46
  });
47
+ child.unref();
46
48
  });
47
49
  }
48
- async function checkForUpdate(currentVersion) {
50
+ function buildUpdateInfo(current, latest) {
51
+ return { current, latest, updateAvailable: compareSemver(latest, current) > 0 };
52
+ }
53
+ async function checkForUpdateNow(currentVersion) {
54
+ const latest = await fetchLatestVersion();
55
+ if (!latest) return null;
56
+ await writeCache(latest).catch(() => {
57
+ });
58
+ return buildUpdateInfo(currentVersion, latest);
59
+ }
60
+ async function checkForUpdateSWR(currentVersion) {
49
61
  try {
50
62
  const cached = await readCache();
51
- if (cached) {
52
- return {
53
- current: currentVersion,
54
- latest: cached.latest,
55
- updateAvailable: compareSemver(cached.latest, currentVersion) > 0
56
- };
63
+ if (!cached) {
64
+ checkForUpdateNow(currentVersion).catch(() => {
65
+ });
66
+ return null;
57
67
  }
58
- fetchLatestVersion().then(async (latest) => {
59
- if (latest) await writeCache(latest).catch(() => {
68
+ const age = Date.now() - cached.checked_at;
69
+ if (age >= REVALIDATE_AFTER_MS) {
70
+ checkForUpdateNow(currentVersion).catch(() => {
60
71
  });
61
- }).catch(() => {
62
- });
63
- return null;
64
- } catch {
65
- return null;
66
- }
67
- }
68
- async function checkForUpdateCached(currentVersion) {
69
- try {
70
- const cached = await readCache();
71
- if (!cached) return null;
72
- return {
73
- current: currentVersion,
74
- latest: cached.latest,
75
- updateAvailable: compareSemver(cached.latest, currentVersion) > 0
76
- };
72
+ }
73
+ return buildUpdateInfo(currentVersion, cached.latest);
77
74
  } catch {
78
75
  return null;
79
76
  }
80
77
  }
81
- async function checkForUpdateNow(currentVersion) {
82
- const latest = await fetchLatestVersion();
83
- if (!latest) return null;
84
- await writeCache(latest).catch(() => {
85
- });
86
- return {
87
- current: currentVersion,
88
- latest,
89
- updateAvailable: compareSemver(latest, currentVersion) > 0
90
- };
91
- }
92
78
  function printUpdateNotification(info) {
93
79
  if (!info.updateAvailable) return;
94
80
  const msg = `
@@ -98,4 +84,4 @@ function printUpdateNotification(info) {
98
84
  process.stderr.write(msg);
99
85
  }
100
86
 
101
- export { checkForUpdate, checkForUpdateCached, checkForUpdateNow, printUpdateNotification };
87
+ export { checkForUpdateNow, checkForUpdateSWR, printUpdateNotification };
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ import { execFile } from 'child_process';
3
+ import { promisify } from 'util';
4
+ import fs from 'fs/promises';
5
+ import path from 'path';
6
+
7
+ var execFileAsync = promisify(execFile);
8
+ var DoctorService = class {
9
+ constructor(adapterRegistry, processManager, projectRoot) {
10
+ this.adapterRegistry = adapterRegistry;
11
+ this.processManager = processManager;
12
+ this.cwd = projectRoot ?? process.cwd();
13
+ }
14
+ cwd;
15
+ async runAll() {
16
+ const checks = [];
17
+ const adapters = this.adapterRegistry.list();
18
+ let adaptersReady = 0;
19
+ for (const adapter of adapters) {
20
+ const result = await adapter.test();
21
+ if (result.ok) {
22
+ adaptersReady++;
23
+ checks.push({
24
+ name: adapter.kind,
25
+ status: "ok",
26
+ detail: result.version
27
+ });
28
+ } else {
29
+ checks.push({
30
+ name: adapter.kind,
31
+ status: "fail",
32
+ detail: result.error
33
+ });
34
+ }
35
+ }
36
+ checks.push(await this.checkCommand("git", ["--version"], "git"));
37
+ checks.push(await this.checkGitRepo());
38
+ checks.push(await this.checkGitignore());
39
+ checks.push(await this.checkCommand("node", ["--version"], "node"));
40
+ return {
41
+ checks,
42
+ adaptersReady,
43
+ adaptersTotal: adapters.length
44
+ };
45
+ }
46
+ async checkCommand(command, args, name) {
47
+ try {
48
+ const { stdout } = await execFileAsync(command, args);
49
+ return { name, status: "ok", detail: stdout.trim() };
50
+ } catch {
51
+ return { name, status: "fail", detail: `${command}: command not found` };
52
+ }
53
+ }
54
+ async checkGitignore() {
55
+ const gitignorePath = path.join(this.cwd, ".gitignore");
56
+ try {
57
+ const content = await fs.readFile(gitignorePath, "utf-8");
58
+ const hasEntry = content.split("\n").some((line) => line.trim() === ".orchestry");
59
+ if (hasEntry) {
60
+ return { name: ".gitignore", status: "ok", detail: ".orchestry is excluded" };
61
+ }
62
+ return {
63
+ name: ".gitignore",
64
+ status: "fail",
65
+ detail: ".orchestry not in .gitignore \u2014 worktrees will copy state recursively. Run: orch init"
66
+ };
67
+ } catch {
68
+ return {
69
+ name: ".gitignore",
70
+ status: "fail",
71
+ detail: "no .gitignore found \u2014 .orchestry may be committed to git. Run: orch init"
72
+ };
73
+ }
74
+ }
75
+ async checkGitRepo() {
76
+ try {
77
+ await execFileAsync("git", ["rev-parse", "--is-inside-work-tree"], { cwd: this.cwd });
78
+ return { name: "git repo", status: "ok", detail: "git repository detected" };
79
+ } catch {
80
+ return {
81
+ name: "git repo",
82
+ status: "fail",
83
+ detail: "not a git repository \u2014 worktree/isolated modes will fail. Run: git init"
84
+ };
85
+ }
86
+ }
87
+ };
88
+
89
+ export { DoctorService };
@@ -1,4 +1,4 @@
1
- import {b as b$1}from'./chunk-ZU6AY2VU.js';import {randomBytes}from'crypto';import s from'fs/promises';import i from'path';import P from'js-yaml';import'fs';async function D(r,t){let n=i.dirname(r);await k(n);let e=i.join(n,`.${i.basename(r)}.${randomBytes(4).toString("hex")}.tmp`);try{await s.writeFile(e,t,"utf-8"),await s.rename(e,r);}catch(l){throw await s.unlink(e).catch(()=>{}),l}}async function L(r){try{let t=await s.readFile(r,"utf-8");return P.load(t)}catch(t){if(f(t))return null;throw t}}async function B(r,t){let n=P.dump(t,{indent:2,lineWidth:120,noRefs:true,sortKeys:false});await D(r,n);}async function M(r){try{let t=await s.readFile(r,"utf-8");return JSON.parse(t)}catch(t){if(f(t))return null;throw t}}async function W(r,t){let n=JSON.stringify(t,null,2)+`
1
+ import {b as b$1}from'./chunk-VAAOW526.js';import {randomBytes}from'crypto';import s from'fs/promises';import i from'path';import P from'js-yaml';import'fs';async function D(r,t){let n=i.dirname(r);await k(n);let e=i.join(n,`.${i.basename(r)}.${randomBytes(4).toString("hex")}.tmp`);try{await s.writeFile(e,t,"utf-8"),await s.rename(e,r);}catch(l){throw await s.unlink(e).catch(()=>{}),l}}async function L(r){try{let t=await s.readFile(r,"utf-8");return P.load(t)}catch(t){if(f(t))return null;throw t}}async function B(r,t){let n=P.dump(t,{indent:2,lineWidth:120,noRefs:true,sortKeys:false});await D(r,n);}async function M(r){try{let t=await s.readFile(r,"utf-8");return JSON.parse(t)}catch(t){if(f(t))return null;throw t}}async function W(r,t){let n=JSON.stringify(t,null,2)+`
2
2
  `;await D(r,n);}var x=4096;async function A(r,t){let n=i.dirname(r);await k(n);let e=JSON.stringify(t)+`
3
3
  `;if(Buffer.byteLength(e,"utf-8")>x&&t!==null&&typeof t=="object"){let a=t;if(typeof a.data=="string"&&a.data.length>0){let u=JSON.stringify({...a,data:""})+`
4
4
  `,h=Buffer.byteLength(u,"utf-8"),m=x-h-3;if(m>0){let g=a.data.slice(0,m);e=JSON.stringify({...a,data:g+"\u2026"})+`
@@ -7,5 +7,5 @@ import {b as b$1}from'./chunk-ZU6AY2VU.js';import {randomBytes}from'crypto';impo
7
7
  `).filter($=>$.trim().length>0);if(j.length>=t+1)return p(j.slice(-t));if(o===0)break;o=Math.max(0,o-l);}let h=u.split(`
8
8
  `).filter(g=>g.trim().length>0),m=a>0?h.slice(1):h;return p(m.slice(-t))}finally{await e.close();}}catch(n){if(f(n))return [];throw n}}async function E(r){let n=(await s.readFile(r,"utf-8")).split(`
9
9
  `).filter(e=>e.trim().length>0);return p(n)}function p(r){let t=[];for(let n of r){let e=n.trim();if(e)try{t.push(JSON.parse(e));}catch{process.stderr.write(`[readJsonl] skipping corrupt line: ${e.slice(0,200)}
10
- `);}}return t}async function k(r){await s.mkdir(r,{recursive:true});}async function v(r){try{return await s.access(r),!0}catch{return false}}async function Z(r,t){try{let n=await s.readdir(r);return t?n.filter(e=>e.endsWith(t)):n}catch(n){if(f(n))return [];throw n}}function f(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}var N=".orchestry",R=/^[A-Za-z0-9._-]+$/,J=class{constructor(t){this.projectRoot=t;}get root(){return i.join(this.projectRoot,N)}get configPath(){return i.join(this.root,"config.yml")}get statePath(){return i.join(this.root,"state.json")}get lockPath(){return i.join(this.root,"orchestry.lock")}get tasksDir(){return i.join(this.root,"tasks")}get agentsDir(){return i.join(this.root,"agents")}get runsDir(){return i.join(this.root,"runs")}get templatesDir(){return i.join(this.root,"templates")}get logsDir(){return i.join(this.root,"logs")}get contextDir(){return i.join(this.root,"context")}contextPath(t){return i.join(this.contextDir,`${c(t)}.json`)}get messagesDir(){return i.join(this.root,"messages")}messagePath(t){return i.join(this.messagesDir,`${c(t)}.json`)}get goalsDir(){return i.join(this.root,"goals")}goalPath(t){return i.join(this.goalsDir,`${c(t)}.yml`)}get teamsDir(){return i.join(this.root,"teams")}teamPath(t){return i.join(this.teamsDir,`${c(t)}.yml`)}get gitignorePath(){return i.join(this.root,".gitignore")}get workspaceExcludePath(){return i.join(this.root,"workspace-exclude")}taskPath(t){return i.join(this.tasksDir,`${c(t)}.yml`)}agentPath(t){return i.join(this.agentsDir,`${c(t)}.yml`)}runPath(t){return i.join(this.runsDir,`${c(t)}.json`)}runEventsPath(t){return i.join(this.runsDir,`${c(t)}.jsonl`)}defaultTemplatePath(){return i.join(this.templatesDir,"default.md")}async isInitialized(){return v(this.root)}async requireInit(){if(!await this.isInitialized())throw new b$1}};function c(r){if(!R.test(r))throw new Error(`Invalid identifier: "${r}"`);return r}function G(r,t){let n=i.resolve(r),e=i.resolve(t);if(!n.startsWith(e+i.sep)&&n!==e)throw new Error(`Workspace path "${r}" is outside project root`)}export{L as a,B as b,M as c,W as d,A as e,Y as f,z as g,k as h,v as i,Z as j,J as k,c as l,G as m};//# sourceMappingURL=chunk-2B32FPEB.js.map
11
- //# sourceMappingURL=chunk-2B32FPEB.js.map
10
+ `);}}return t}async function k(r){await s.mkdir(r,{recursive:true});}async function v(r){try{return await s.access(r),!0}catch{return false}}async function Z(r,t){try{let n=await s.readdir(r);return t?n.filter(e=>e.endsWith(t)):n}catch(n){if(f(n))return [];throw n}}function f(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}var N=".orchestry",R=/^[A-Za-z0-9._-]+$/,J=class{constructor(t){this.projectRoot=t;}get root(){return i.join(this.projectRoot,N)}get configPath(){return i.join(this.root,"config.yml")}get statePath(){return i.join(this.root,"state.json")}get lockPath(){return i.join(this.root,"orchestry.lock")}get tasksDir(){return i.join(this.root,"tasks")}get agentsDir(){return i.join(this.root,"agents")}get runsDir(){return i.join(this.root,"runs")}get templatesDir(){return i.join(this.root,"templates")}get logsDir(){return i.join(this.root,"logs")}get contextDir(){return i.join(this.root,"context")}contextPath(t){return i.join(this.contextDir,`${c(t)}.json`)}get messagesDir(){return i.join(this.root,"messages")}messagePath(t){return i.join(this.messagesDir,`${c(t)}.json`)}get goalsDir(){return i.join(this.root,"goals")}goalPath(t){return i.join(this.goalsDir,`${c(t)}.yml`)}get teamsDir(){return i.join(this.root,"teams")}teamPath(t){return i.join(this.teamsDir,`${c(t)}.yml`)}get gitignorePath(){return i.join(this.root,".gitignore")}get workspaceExcludePath(){return i.join(this.root,"workspace-exclude")}taskPath(t){return i.join(this.tasksDir,`${c(t)}.yml`)}agentPath(t){return i.join(this.agentsDir,`${c(t)}.yml`)}runPath(t){return i.join(this.runsDir,`${c(t)}.json`)}runEventsPath(t){return i.join(this.runsDir,`${c(t)}.jsonl`)}defaultTemplatePath(){return i.join(this.templatesDir,"default.md")}async isInitialized(){return v(this.root)}async requireInit(){if(!await this.isInitialized())throw new b$1}};function c(r){if(!R.test(r))throw new Error(`Invalid identifier: "${r}"`);return r}function G(r,t){let n=i.resolve(r),e=i.resolve(t);if(!n.startsWith(e+i.sep)&&n!==e)throw new Error(`Workspace path "${r}" is outside project root`)}export{L as a,B as b,M as c,W as d,A as e,Y as f,z as g,k as h,v as i,Z as j,J as k,c as l,G as m};//# sourceMappingURL=chunk-QTDKQYZI.js.map
11
+ //# sourceMappingURL=chunk-QTDKQYZI.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/infrastructure/storage/fs-utils.ts","../src/infrastructure/storage/paths.ts"],"names":["atomicWrite","filePath","content","dir","path","ensureDir","tmpPath","randomBytes","fs","err","readYaml","yaml","isENOENT","writeYaml","data","readJson","writeJson","PIPE_BUF","appendJsonl","record","line","obj","shell","overhead","budget","truncated","fd","MAX_JSONL_READ_SIZE","readJsonl","stat","readJsonlTail","readAndParseJsonl","count","chunkSize","position","earliestReadPosition","tail","attempt","readSize","buf","lines","l","parseJsonlLines","safeLines","results","raw","dirPath","pathExists","listFiles","ext","entries","ORCHESTRY_DIR","ID_PATTERN","Paths","projectRoot","key","sanitizeId","id","NotInitializedError","validateWorkspacePath","workspacePath","resolved","root"],"mappings":"6JAgBA,eAAsBA,CAAAA,CAAYC,CAAAA,CAAkBC,EAAgC,CAClF,IAAMC,EAAMC,CAAAA,CAAK,OAAA,CAAQH,CAAQ,CAAA,CACjC,MAAMI,CAAAA,CAAUF,CAAG,EAEnB,IAAMG,CAAAA,CAAUF,EAAK,IAAA,CAAKD,CAAAA,CAAK,IAAIC,CAAAA,CAAK,QAAA,CAASH,CAAQ,CAAC,CAAA,CAAA,EAAIM,YAAY,CAAC,CAAA,CAAE,SAAS,KAAK,CAAC,CAAA,IAAA,CAAM,CAAA,CAElG,GAAI,CACF,MAAMC,EAAG,SAAA,CAAUF,CAAAA,CAASJ,EAAS,OAAO,CAAA,CAC5C,MAAMM,CAAAA,CAAG,MAAA,CAAOF,EAASL,CAAQ,EACnC,OAASQ,CAAAA,CAAK,CAEZ,YAAMD,CAAAA,CAAG,MAAA,CAAOF,CAAO,CAAA,CAAE,MAAM,IAAM,CAAC,CAAC,CAAA,CACjCG,CACR,CACF,CAKA,eAAsBC,EAAYT,CAAAA,CAAqC,CACrE,GAAI,CACF,IAAMC,EAAU,MAAMM,CAAAA,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N,EAA2B,CACtF,IAAMO,CAAAA,CAAWzD,CAAAA,CAAK,OAAA,CAAQwD,CAAa,CAAA,CACrCE,CAAAA,CAAO1D,CAAAA,CAAK,OAAA,CAAQkD,CAAW,CAAA,CAErC,GAAI,CAACO,CAAAA,CAAS,UAAA,CAAWC,CAAAA,CAAO1D,CAAAA,CAAK,GAAG,CAAA,EAAKyD,CAAAA,GAAaC,CAAAA,CACxD,MAAM,IAAI,KAAA,CAAM,CAAA,gBAAA,EAAmBF,CAAa,CAAA,yBAAA,CAA2B,CAE/E","file":"chunk-2B32FPEB.js","sourcesContent":["/**\n * Low-level filesystem utilities.\n *\n * All file persistence goes through these functions.\n * atomicWrite guarantees no partial reads via temp → rename.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport yaml from 'js-yaml';\n\n/**\n * Write file atomically: write to temp file, then rename.\n * Prevents corrupted reads on concurrent access.\n */\nexport async function atomicWrite(filePath: string, content: string): Promise<void> {\n const dir = path.dirname(filePath);\n await ensureDir(dir);\n\n const tmpPath = path.join(dir, `.${path.basename(filePath)}.${randomBytes(4).toString('hex')}.tmp`);\n\n try {\n await fs.writeFile(tmpPath, content, 'utf-8');\n await fs.rename(tmpPath, filePath);\n } catch (err) {\n // Clean up temp file on failure\n await fs.unlink(tmpPath).catch(() => {});\n throw err;\n }\n}\n\n/**\n * Read and parse a YAML file. Returns null if file does not exist.\n */\nexport async function readYaml<T>(filePath: string): Promise<T | null> {\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n return yaml.load(content) as T;\n } catch (err) {\n if (isENOENT(err)) return null;\n throw err;\n }\n}\n\n/**\n * Write data as YAML atomically.\n */\nexport async function writeYaml<T>(filePath: string, data: T): Promise<void> {\n const content = yaml.dump(data, {\n indent: 2,\n lineWidth: 120,\n noRefs: true,\n sortKeys: false,\n });\n await atomicWrite(filePath, content);\n}\n\n/**\n * Read and parse a JSON file. Returns null if file does not exist.\n */\nexport async function readJson<T>(filePath: string): Promise<T | null> {\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n return JSON.parse(content) as T;\n } catch (err) {\n if (isENOENT(err)) return null;\n throw err;\n }\n}\n\n/**\n * Write data as JSON atomically.\n */\nexport async function writeJson<T>(filePath: string, data: T): Promise<void> {\n const content = JSON.stringify(data, null, 2) + '\\n';\n await atomicWrite(filePath, content);\n}\n\n/**\n * POSIX PIPE_BUF — writes up to this size are guaranteed atomic with O_APPEND.\n * 4096 on Linux/macOS. We leave some room for encoding overhead.\n */\nconst PIPE_BUF = 4096;\n\n/**\n * Append a JSON record to a .jsonl file (newline-delimited JSON).\n *\n * Uses a file handle opened with 'a' (O_APPEND) to ensure atomic writes.\n * On POSIX, O_APPEND guarantees that each write() call appends atomically\n * when the data fits within PIPE_BUF (typically 4096 bytes), preventing\n * interleaving from concurrent writers.\n *\n * If the serialized line exceeds PIPE_BUF, the record's `data` field is\n * truncated so the entire line fits within the atomic-write limit.\n * This prevents interleaving corruption from concurrent writers.\n */\nexport async function appendJsonl(filePath: string, record: unknown): Promise<void> {\n const dir = path.dirname(filePath);\n await ensureDir(dir);\n let line = JSON.stringify(record) + '\\n';\n\n // If the line exceeds PIPE_BUF, truncate the `data` field to fit\n const byteLen = Buffer.byteLength(line, 'utf-8');\n if (byteLen > PIPE_BUF && record !== null && typeof record === 'object') {\n const obj = record as Record<string, unknown>;\n if (typeof obj.data === 'string' && obj.data.length > 0) {\n // Measure overhead without data to know how much room data gets\n const shell = JSON.stringify({ ...obj, data: '' }) + '\\n';\n const overhead = Buffer.byteLength(shell, 'utf-8');\n const budget = PIPE_BUF - overhead - 3; // 3 bytes for the '…' suffix (UTF-8 ellipsis)\n if (budget > 0) {\n // Slice to budget chars — for ASCII (most event data) this equals bytes.\n // For multi-byte chars the result may be slightly over PIPE_BUF,\n // which is acceptable on local filesystems (ext4/APFS hold inode lock).\n const truncated = obj.data.slice(0, budget);\n line = JSON.stringify({ ...obj, data: truncated + '…' }) + '\\n';\n }\n }\n }\n\n const fd = await fs.open(filePath, 'a');\n try {\n await fd.write(line, null, 'utf-8');\n } finally {\n await fd.close();\n }\n}\n\n/** Max file size for full readJsonl (50 MB). Larger files use tail read. */\nconst MAX_JSONL_READ_SIZE = 50 * 1024 * 1024;\n\n/**\n * Read all records from a .jsonl file.\n * Falls back to reading only the last 200 records if the file exceeds MAX_JSONL_READ_SIZE.\n */\nexport async function readJsonl<T>(filePath: string): Promise<T[]> {\n try {\n const stat = await fs.stat(filePath);\n if (stat.size > MAX_JSONL_READ_SIZE) {\n process.stderr.write(\n `[readJsonl] file too large (${(stat.size / 1024 / 1024).toFixed(1)} MB), reading tail only: ${filePath}\\n`,\n );\n return readJsonlTail<T>(filePath, 200);\n }\n return readAndParseJsonl<T>(filePath);\n } catch (err) {\n if (isENOENT(err)) return [];\n throw err;\n }\n}\n\n/**\n * Read the last N records from a .jsonl file.\n *\n * Reads the file in reverse chunks to avoid loading multi-MB files into memory.\n * Falls back to full read for small files (< 32KB).\n */\nexport async function readJsonlTail<T>(filePath: string, count: number): Promise<T[]> {\n try {\n const stat = await fs.stat(filePath);\n // For small files, read directly and slice (avoid mutual recursion with readJsonl)\n if (stat.size < 32768) {\n return (await readAndParseJsonl<T>(filePath)).slice(-count);\n }\n\n // Read from end in chunks to find enough lines\n // Use larger chunks for bigger files (tool_result events can be 8KB+ per line)\n const fd = await fs.open(filePath, 'r');\n try {\n const chunkSize = Math.min(stat.size, stat.size > 1_048_576 ? 131072 : 65536);\n let position = Math.max(0, stat.size - chunkSize);\n let earliestReadPosition = position;\n let tail = '';\n\n // Read up to 4 chunks from the end\n for (let attempt = 0; attempt < 4 && position >= 0; attempt++) {\n earliestReadPosition = position;\n const readSize = Math.min(chunkSize, stat.size - position);\n const buf = Buffer.alloc(readSize);\n await fd.read(buf, 0, readSize, position);\n tail = buf.toString('utf-8') + tail;\n\n const lines = tail.split('\\n').filter((l) => l.trim().length > 0);\n if (lines.length >= count + 1) {\n // +1 because first line might be partial\n return parseJsonlLines<T>(lines.slice(-count));\n }\n if (position === 0) break;\n position = Math.max(0, position - chunkSize);\n }\n\n // Parse whatever we got\n const lines = tail.split('\\n').filter((l) => l.trim().length > 0);\n // Skip first line if we didn't read from start (could be partial)\n const safeLines = earliestReadPosition > 0 ? lines.slice(1) : lines;\n return parseJsonlLines<T>(safeLines.slice(-count));\n } finally {\n await fd.close();\n }\n } catch (err) {\n if (isENOENT(err)) return [];\n throw err;\n }\n}\n\n/** Read a file and parse all JSONL records. */\nasync function readAndParseJsonl<T>(filePath: string): Promise<T[]> {\n const content = await fs.readFile(filePath, 'utf-8');\n const lines = content.split('\\n').filter((l) => l.trim().length > 0);\n return parseJsonlLines<T>(lines);\n}\n\n/**\n * Parse JSONL lines with error tolerance — corrupt lines are logged and skipped.\n */\nfunction parseJsonlLines<T>(lines: string[]): T[] {\n const results: T[] = [];\n for (const raw of lines) {\n const line = raw.trim();\n if (!line) continue;\n try {\n results.push(JSON.parse(line) as T);\n } catch {\n process.stderr.write(`[readJsonl] skipping corrupt line: ${line.slice(0, 200)}\\n`);\n }\n }\n return results;\n}\n\n/**\n * Ensure a directory exists, creating it recursively if needed.\n */\nexport async function ensureDir(dirPath: string): Promise<void> {\n await fs.mkdir(dirPath, { recursive: true });\n}\n\n/**\n * Check if a path exists.\n */\nexport async function pathExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * List files in a directory matching an optional extension filter.\n */\nexport async function listFiles(dirPath: string, ext?: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(dirPath);\n if (ext) {\n return entries.filter((e) => e.endsWith(ext));\n }\n return entries;\n } catch (err) {\n if (isENOENT(err)) return [];\n throw err;\n }\n}\n\nfunction isENOENT(err: unknown): boolean {\n return err instanceof Error && 'code' in err && (err as NodeJS.ErrnoException).code === 'ENOENT';\n}\n","/**\n * Path resolution for .orchestry/ directory.\n *\n * All path construction goes through this module.\n * Validates initialization state and sanitizes identifiers.\n */\n\nimport path from 'node:path';\nimport { accessSync } from 'node:fs';\nimport { NotInitializedError } from '../../domain/errors.js';\nimport { pathExists } from './fs-utils.js';\n\nconst ORCHESTRY_DIR = '.orchestry';\nconst ID_PATTERN = /^[A-Za-z0-9._-]+$/;\n\nexport class Paths {\n constructor(private readonly projectRoot: string) {}\n\n /** Root .orchestry/ directory */\n get root(): string {\n return path.join(this.projectRoot, ORCHESTRY_DIR);\n }\n\n get configPath(): string {\n return path.join(this.root, 'config.yml');\n }\n\n get statePath(): string {\n return path.join(this.root, 'state.json');\n }\n\n get lockPath(): string {\n return path.join(this.root, 'orchestry.lock');\n }\n\n get tasksDir(): string {\n return path.join(this.root, 'tasks');\n }\n\n get agentsDir(): string {\n return path.join(this.root, 'agents');\n }\n\n get runsDir(): string {\n return path.join(this.root, 'runs');\n }\n\n get templatesDir(): string {\n return path.join(this.root, 'templates');\n }\n\n get logsDir(): string {\n return path.join(this.root, 'logs');\n }\n\n get contextDir(): string {\n return path.join(this.root, 'context');\n }\n\n contextPath(key: string): string {\n return path.join(this.contextDir, `${sanitizeId(key)}.json`);\n }\n\n get messagesDir(): string {\n return path.join(this.root, 'messages');\n }\n\n messagePath(id: string): string {\n return path.join(this.messagesDir, `${sanitizeId(id)}.json`);\n }\n\n get goalsDir(): string {\n return path.join(this.root, 'goals');\n }\n\n goalPath(id: string): string {\n return path.join(this.goalsDir, `${sanitizeId(id)}.yml`);\n }\n\n get teamsDir(): string {\n return path.join(this.root, 'teams');\n }\n\n teamPath(id: string): string {\n return path.join(this.teamsDir, `${sanitizeId(id)}.yml`);\n }\n\n get gitignorePath(): string {\n return path.join(this.root, '.gitignore');\n }\n\n get workspaceExcludePath(): string {\n return path.join(this.root, 'workspace-exclude');\n }\n\n taskPath(id: string): string {\n return path.join(this.tasksDir, `${sanitizeId(id)}.yml`);\n }\n\n agentPath(id: string): string {\n return path.join(this.agentsDir, `${sanitizeId(id)}.yml`);\n }\n\n runPath(id: string): string {\n return path.join(this.runsDir, `${sanitizeId(id)}.json`);\n }\n\n runEventsPath(id: string): string {\n return path.join(this.runsDir, `${sanitizeId(id)}.jsonl`);\n }\n\n defaultTemplatePath(): string {\n return path.join(this.templatesDir, 'default.md');\n }\n\n async isInitialized(): Promise<boolean> {\n return pathExists(this.root);\n }\n\n async requireInit(): Promise<void> {\n if (!(await this.isInitialized())) {\n throw new NotInitializedError();\n }\n }\n}\n\n/**\n * Validate an identifier for use in file paths.\n * Only allows [A-Za-z0-9._-] characters.\n * Rejects identifiers containing forbidden characters (path separators, etc.)\n * to prevent path traversal attacks.\n */\nexport function sanitizeId(id: string): string {\n if (!ID_PATTERN.test(id)) {\n throw new Error(`Invalid identifier: \"${id}\"`);\n }\n return id;\n}\n\n/**\n * Validate that a workspace path is within the project root.\n * Prevents path traversal attacks.\n */\nexport function validateWorkspacePath(workspacePath: string, projectRoot: string): void {\n const resolved = path.resolve(workspacePath);\n const root = path.resolve(projectRoot);\n\n if (!resolved.startsWith(root + path.sep) && resolved !== root) {\n throw new Error(`Workspace path \"${workspacePath}\" is outside project root`);\n }\n}\n\n/**\n * Resolve project root by walking up from cwd looking for .orchestry/.\n * Returns cwd if not found (for init command).\n */\nexport function findProjectRoot(startDir: string = process.cwd()): string {\n let dir = path.resolve(startDir);\n const root = path.parse(dir).root;\n\n while (dir !== root) {\n try {\n accessSync(path.join(dir, '.orchestry'));\n return dir;\n } catch {\n // Not found, go up\n }\n dir = path.dirname(dir);\n }\n\n // Not found — return original dir (for init command)\n return startDir;\n}\n"]}
1
+ {"version":3,"sources":["../src/infrastructure/storage/fs-utils.ts","../src/infrastructure/storage/paths.ts"],"names":["atomicWrite","filePath","content","dir","path","ensureDir","tmpPath","randomBytes","fs","err","readYaml","yaml","isENOENT","writeYaml","data","readJson","writeJson","PIPE_BUF","appendJsonl","record","line","obj","shell","overhead","budget","truncated","fd","MAX_JSONL_READ_SIZE","readJsonl","stat","readJsonlTail","readAndParseJsonl","count","chunkSize","position","earliestReadPosition","tail","attempt","readSize","buf","lines","l","parseJsonlLines","safeLines","results","raw","dirPath","pathExists","listFiles","ext","entries","ORCHESTRY_DIR","ID_PATTERN","Paths","projectRoot","key","sanitizeId","id","NotInitializedError","validateWorkspacePath","workspacePath","resolved","root"],"mappings":"6JAgBA,eAAsBA,CAAAA,CAAYC,CAAAA,CAAkBC,EAAgC,CAClF,IAAMC,EAAMC,CAAAA,CAAK,OAAA,CAAQH,CAAQ,CAAA,CACjC,MAAMI,CAAAA,CAAUF,CAAG,EAEnB,IAAMG,CAAAA,CAAUF,EAAK,IAAA,CAAKD,CAAAA,CAAK,IAAIC,CAAAA,CAAK,QAAA,CAASH,CAAQ,CAAC,CAAA,CAAA,EAAIM,YAAY,CAAC,CAAA,CAAE,SAAS,KAAK,CAAC,CAAA,IAAA,CAAM,CAAA,CAElG,GAAI,CACF,MAAMC,EAAG,SAAA,CAAUF,CAAAA,CAASJ,EAAS,OAAO,CAAA,CAC5C,MAAMM,CAAAA,CAAG,MAAA,CAAOF,EAASL,CAAQ,EACnC,OAASQ,CAAAA,CAAK,CAEZ,YAAMD,CAAAA,CAAG,MAAA,CAAOF,CAAO,CAAA,CAAE,MAAM,IAAM,CAAC,CAAC,CAAA,CACjCG,CACR,CACF,CAKA,eAAsBC,EAAYT,CAAAA,CAAqC,CACrE,GAAI,CACF,IAAMC,EAAU,MAAMM,CAAAA,CAAG,SAASP,CAAAA,CAAU,OAAO,CAAA,CACnD,OAAOU,EAAK,IAAA,CAAKT,CAAO,CAC1B,CAAA,MAASO,CAAAA,CAAK,CACZ,GAAIG,CAAAA,CAASH,CAAG,CAAA,CAAG,OAAO,KAC1B,MAAMA,CACR,CACF,CAKA,eAAsBI,EAAaZ,CAAAA,CAAkBa,CAAAA,CAAwB,CAC3E,IAAMZ,EAAUS,CAAAA,CAAK,IAAA,CAAKG,EAAM,CAC9B,MAAA,CAAQ,EACR,SAAA,CAAW,GAAA,CACX,OAAQ,IAAA,CACR,QAAA,CAAU,KACZ,CAAC,CAAA,CACD,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.\n *\n * All file persistence goes through these functions.\n * atomicWrite guarantees no partial reads via temp → rename.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport yaml from 'js-yaml';\n\n/**\n * Write file atomically: write to temp file, then rename.\n * Prevents corrupted reads on concurrent access.\n */\nexport async function atomicWrite(filePath: string, content: string): Promise<void> {\n const dir = path.dirname(filePath);\n await ensureDir(dir);\n\n const tmpPath = path.join(dir, `.${path.basename(filePath)}.${randomBytes(4).toString('hex')}.tmp`);\n\n try {\n await fs.writeFile(tmpPath, content, 'utf-8');\n await fs.rename(tmpPath, filePath);\n } catch (err) {\n // Clean up temp file on failure\n await fs.unlink(tmpPath).catch(() => {});\n throw err;\n }\n}\n\n/**\n * Read and parse a YAML file. Returns null if file does not exist.\n */\nexport async function readYaml<T>(filePath: string): Promise<T | null> {\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n return yaml.load(content) as T;\n } catch (err) {\n if (isENOENT(err)) return null;\n throw err;\n }\n}\n\n/**\n * Write data as YAML atomically.\n */\nexport async function writeYaml<T>(filePath: string, data: T): Promise<void> {\n const content = yaml.dump(data, {\n indent: 2,\n lineWidth: 120,\n noRefs: true,\n sortKeys: false,\n });\n await atomicWrite(filePath, content);\n}\n\n/**\n * Read and parse a JSON file. Returns null if file does not exist.\n */\nexport async function readJson<T>(filePath: string): Promise<T | null> {\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n return JSON.parse(content) as T;\n } catch (err) {\n if (isENOENT(err)) return null;\n throw err;\n }\n}\n\n/**\n * Write data as JSON atomically.\n */\nexport async function writeJson<T>(filePath: string, data: T): Promise<void> {\n const content = JSON.stringify(data, null, 2) + '\\n';\n await atomicWrite(filePath, content);\n}\n\n/**\n * POSIX PIPE_BUF — writes up to this size are guaranteed atomic with O_APPEND.\n * 4096 on Linux/macOS. We leave some room for encoding overhead.\n */\nconst PIPE_BUF = 4096;\n\n/**\n * Append a JSON record to a .jsonl file (newline-delimited JSON).\n *\n * Uses a file handle opened with 'a' (O_APPEND) to ensure atomic writes.\n * On POSIX, O_APPEND guarantees that each write() call appends atomically\n * when the data fits within PIPE_BUF (typically 4096 bytes), preventing\n * interleaving from concurrent writers.\n *\n * If the serialized line exceeds PIPE_BUF, the record's `data` field is\n * truncated so the entire line fits within the atomic-write limit.\n * This prevents interleaving corruption from concurrent writers.\n */\nexport async function appendJsonl(filePath: string, record: unknown): Promise<void> {\n const dir = path.dirname(filePath);\n await ensureDir(dir);\n let line = JSON.stringify(record) + '\\n';\n\n // If the line exceeds PIPE_BUF, truncate the `data` field to fit\n const byteLen = Buffer.byteLength(line, 'utf-8');\n if (byteLen > PIPE_BUF && record !== null && typeof record === 'object') {\n const obj = record as Record<string, unknown>;\n if (typeof obj.data === 'string' && obj.data.length > 0) {\n // Measure overhead without data to know how much room data gets\n const shell = JSON.stringify({ ...obj, data: '' }) + '\\n';\n const overhead = Buffer.byteLength(shell, 'utf-8');\n const budget = PIPE_BUF - overhead - 3; // 3 bytes for the '…' suffix (UTF-8 ellipsis)\n if (budget > 0) {\n // Slice to budget chars — for ASCII (most event data) this equals bytes.\n // For multi-byte chars the result may be slightly over PIPE_BUF,\n // which is acceptable on local filesystems (ext4/APFS hold inode lock).\n const truncated = obj.data.slice(0, budget);\n line = JSON.stringify({ ...obj, data: truncated + '…' }) + '\\n';\n }\n }\n }\n\n const fd = await fs.open(filePath, 'a');\n try {\n await fd.write(line, null, 'utf-8');\n } finally {\n await fd.close();\n }\n}\n\n/** Max file size for full readJsonl (50 MB). Larger files use tail read. */\nconst MAX_JSONL_READ_SIZE = 50 * 1024 * 1024;\n\n/**\n * Read all records from a .jsonl file.\n * Falls back to reading only the last 200 records if the file exceeds MAX_JSONL_READ_SIZE.\n */\nexport async function readJsonl<T>(filePath: string): Promise<T[]> {\n try {\n const stat = await fs.stat(filePath);\n if (stat.size > MAX_JSONL_READ_SIZE) {\n process.stderr.write(\n `[readJsonl] file too large (${(stat.size / 1024 / 1024).toFixed(1)} MB), reading tail only: ${filePath}\\n`,\n );\n return readJsonlTail<T>(filePath, 200);\n }\n return readAndParseJsonl<T>(filePath);\n } catch (err) {\n if (isENOENT(err)) return [];\n throw err;\n }\n}\n\n/**\n * Read the last N records from a .jsonl file.\n *\n * Reads the file in reverse chunks to avoid loading multi-MB files into memory.\n * Falls back to full read for small files (< 32KB).\n */\nexport async function readJsonlTail<T>(filePath: string, count: number): Promise<T[]> {\n try {\n const stat = await fs.stat(filePath);\n // For small files, read directly and slice (avoid mutual recursion with readJsonl)\n if (stat.size < 32768) {\n return (await readAndParseJsonl<T>(filePath)).slice(-count);\n }\n\n // Read from end in chunks to find enough lines\n // Use larger chunks for bigger files (tool_result events can be 8KB+ per line)\n const fd = await fs.open(filePath, 'r');\n try {\n const chunkSize = Math.min(stat.size, stat.size > 1_048_576 ? 131072 : 65536);\n let position = Math.max(0, stat.size - chunkSize);\n let earliestReadPosition = position;\n let tail = '';\n\n // Read up to 4 chunks from the end\n for (let attempt = 0; attempt < 4 && position >= 0; attempt++) {\n earliestReadPosition = position;\n const readSize = Math.min(chunkSize, stat.size - position);\n const buf = Buffer.alloc(readSize);\n await fd.read(buf, 0, readSize, position);\n tail = buf.toString('utf-8') + tail;\n\n const lines = tail.split('\\n').filter((l) => l.trim().length > 0);\n if (lines.length >= count + 1) {\n // +1 because first line might be partial\n return parseJsonlLines<T>(lines.slice(-count));\n }\n if (position === 0) break;\n position = Math.max(0, position - chunkSize);\n }\n\n // Parse whatever we got\n const lines = tail.split('\\n').filter((l) => l.trim().length > 0);\n // Skip first line if we didn't read from start (could be partial)\n const safeLines = earliestReadPosition > 0 ? lines.slice(1) : lines;\n return parseJsonlLines<T>(safeLines.slice(-count));\n } finally {\n await fd.close();\n }\n } catch (err) {\n if (isENOENT(err)) return [];\n throw err;\n }\n}\n\n/** Read a file and parse all JSONL records. */\nasync function readAndParseJsonl<T>(filePath: string): Promise<T[]> {\n const content = await fs.readFile(filePath, 'utf-8');\n const lines = content.split('\\n').filter((l) => l.trim().length > 0);\n return parseJsonlLines<T>(lines);\n}\n\n/**\n * Parse JSONL lines with error tolerance — corrupt lines are logged and skipped.\n */\nfunction parseJsonlLines<T>(lines: string[]): T[] {\n const results: T[] = [];\n for (const raw of lines) {\n const line = raw.trim();\n if (!line) continue;\n try {\n results.push(JSON.parse(line) as T);\n } catch {\n process.stderr.write(`[readJsonl] skipping corrupt line: ${line.slice(0, 200)}\\n`);\n }\n }\n return results;\n}\n\n/**\n * Ensure a directory exists, creating it recursively if needed.\n */\nexport async function ensureDir(dirPath: string): Promise<void> {\n await fs.mkdir(dirPath, { recursive: true });\n}\n\n/**\n * Check if a path exists.\n */\nexport async function pathExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * List files in a directory matching an optional extension filter.\n */\nexport async function listFiles(dirPath: string, ext?: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(dirPath);\n if (ext) {\n return entries.filter((e) => e.endsWith(ext));\n }\n return entries;\n } catch (err) {\n if (isENOENT(err)) return [];\n throw err;\n }\n}\n\nfunction isENOENT(err: unknown): boolean {\n return err instanceof Error && 'code' in err && (err as NodeJS.ErrnoException).code === 'ENOENT';\n}\n","/**\n * Path resolution for .orchestry/ directory.\n *\n * All path construction goes through this module.\n * Validates initialization state and sanitizes identifiers.\n */\n\nimport path from 'node:path';\nimport { accessSync } from 'node:fs';\nimport { NotInitializedError } from '../../domain/errors.js';\nimport { pathExists } from './fs-utils.js';\n\nconst ORCHESTRY_DIR = '.orchestry';\nconst ID_PATTERN = /^[A-Za-z0-9._-]+$/;\n\nexport class Paths {\n constructor(private readonly projectRoot: string) {}\n\n /** Root .orchestry/ directory */\n get root(): string {\n return path.join(this.projectRoot, ORCHESTRY_DIR);\n }\n\n get configPath(): string {\n return path.join(this.root, 'config.yml');\n }\n\n get statePath(): string {\n return path.join(this.root, 'state.json');\n }\n\n get lockPath(): string {\n return path.join(this.root, 'orchestry.lock');\n }\n\n get tasksDir(): string {\n return path.join(this.root, 'tasks');\n }\n\n get agentsDir(): string {\n return path.join(this.root, 'agents');\n }\n\n get runsDir(): string {\n return path.join(this.root, 'runs');\n }\n\n get templatesDir(): string {\n return path.join(this.root, 'templates');\n }\n\n get logsDir(): string {\n return path.join(this.root, 'logs');\n }\n\n get contextDir(): string {\n return path.join(this.root, 'context');\n }\n\n contextPath(key: string): string {\n return path.join(this.contextDir, `${sanitizeId(key)}.json`);\n }\n\n get messagesDir(): string {\n return path.join(this.root, 'messages');\n }\n\n messagePath(id: string): string {\n return path.join(this.messagesDir, `${sanitizeId(id)}.json`);\n }\n\n get goalsDir(): string {\n return path.join(this.root, 'goals');\n }\n\n goalPath(id: string): string {\n return path.join(this.goalsDir, `${sanitizeId(id)}.yml`);\n }\n\n get teamsDir(): string {\n return path.join(this.root, 'teams');\n }\n\n teamPath(id: string): string {\n return path.join(this.teamsDir, `${sanitizeId(id)}.yml`);\n }\n\n get gitignorePath(): string {\n return path.join(this.root, '.gitignore');\n }\n\n get workspaceExcludePath(): string {\n return path.join(this.root, 'workspace-exclude');\n }\n\n taskPath(id: string): string {\n return path.join(this.tasksDir, `${sanitizeId(id)}.yml`);\n }\n\n agentPath(id: string): string {\n return path.join(this.agentsDir, `${sanitizeId(id)}.yml`);\n }\n\n runPath(id: string): string {\n return path.join(this.runsDir, `${sanitizeId(id)}.json`);\n }\n\n runEventsPath(id: string): string {\n return path.join(this.runsDir, `${sanitizeId(id)}.jsonl`);\n }\n\n defaultTemplatePath(): string {\n return path.join(this.templatesDir, 'default.md');\n }\n\n async isInitialized(): Promise<boolean> {\n return pathExists(this.root);\n }\n\n async requireInit(): Promise<void> {\n if (!(await this.isInitialized())) {\n throw new NotInitializedError();\n }\n }\n}\n\n/**\n * Validate an identifier for use in file paths.\n * Only allows [A-Za-z0-9._-] characters.\n * Rejects identifiers containing forbidden characters (path separators, etc.)\n * to prevent path traversal attacks.\n */\nexport function sanitizeId(id: string): string {\n if (!ID_PATTERN.test(id)) {\n throw new Error(`Invalid identifier: \"${id}\"`);\n }\n return id;\n}\n\n/**\n * Validate that a workspace path is within the project root.\n * Prevents path traversal attacks.\n */\nexport function validateWorkspacePath(workspacePath: string, projectRoot: string): void {\n const resolved = path.resolve(workspacePath);\n const root = path.resolve(projectRoot);\n\n if (!resolved.startsWith(root + path.sep) && resolved !== root) {\n throw new Error(`Workspace path \"${workspacePath}\" is outside project root`);\n }\n}\n\n/**\n * Resolve project root by walking up from cwd looking for .orchestry/.\n * Returns cwd if not found (for init command).\n */\nexport function findProjectRoot(startDir: string = process.cwd()): string {\n let dir = path.resolve(startDir);\n const root = path.parse(dir).root;\n\n while (dir !== root) {\n try {\n accessSync(path.join(dir, '.orchestry'));\n return dir;\n } catch {\n // Not found, go up\n }\n dir = path.dirname(dir);\n }\n\n // Not found — return original dir (for init command)\n return startDir;\n}\n"]}
@@ -1,2 +1,2 @@
1
- var t=class extends Error{constructor(r,e,h){super(r);this.exitCode=e;this.hint=h;this.name="OrchestryError";}},o=class extends t{constructor(){super("Not initialized",3,"Run: orch init"),this.name="NotInitializedError";}},a=class extends t{constructor(s){super(s,2),this.name="InvalidArgumentsError";}},c=class extends t{constructor(s){super(`Orchestrator already running (PID: ${s})`,4,"Use: orch status"),this.name="LockConflictError";}};var i=class extends t{constructor(){super("No agents configured",1,"Run: orch agent add <name> --adapter claude"),this.name="NoAgentsError";}},u=class extends t{constructor(s){super(`Task not found: ${s}`,1),this.name="TaskNotFoundError";}},d=class extends t{constructor(s){super(`Agent not found: ${s}`,1),this.name="AgentNotFoundError";}},p=class extends t{constructor(s,r,e){super(`Task ${s} is already running (run: ${r}, agent: ${e})`,1,`Use: orch logs --task ${s} --follow`),this.name="TaskAlreadyRunningError";}},l=class extends t{constructor(s,r,e){super(`Invalid transition for ${s}: ${r} \u2192 ${e}`,1),this.name="InvalidTransitionError";}},x=class extends t{constructor(s){super(`Goal not found: ${s}`,1),this.name="GoalNotFoundError";}},g=class extends t{constructor(s){super(`Team not found: ${s}`,1),this.name="TeamNotFoundError";}};export{t as a,o as b,a as c,c as d,i as e,u as f,d as g,p as h,l as i,x as j,g as k};//# sourceMappingURL=chunk-ZU6AY2VU.js.map
2
- //# sourceMappingURL=chunk-ZU6AY2VU.js.map
1
+ var t=class extends Error{constructor(n,e,m){super(n);this.exitCode=e;this.hint=m;this.name="OrchestryError";}},o=class extends t{constructor(){super("Not initialized",3,"Run: orch init"),this.name="NotInitializedError";}},a=class extends t{constructor(s){super(s,2),this.name="InvalidArgumentsError";}},c=class extends t{constructor(s){super(`Orchestrator already running (PID: ${s})`,4,"Use: orch status"),this.name="LockConflictError";}};var i=class extends t{constructor(){super("No agents configured",1,"Run: orch agent add <name> --adapter claude"),this.name="NoAgentsError";}},u=class extends t{constructor(s){super(`Task not found: ${s}`,1),this.name="TaskNotFoundError";}},p=class extends t{constructor(s){super(`Agent not found: ${s}`,1),this.name="AgentNotFoundError";}},d=class extends t{constructor(s,n,e){super(`Task ${s} is already running (run: ${n}, agent: ${e})`,1,`Use: orch logs --task ${s} --follow`),this.name="TaskAlreadyRunningError";}},l=class extends t{constructor(s,n,e){super(`Invalid transition for ${s}: ${n} \u2192 ${e}`,1),this.name="InvalidTransitionError";}},x=class extends t{constructor(s){super(`Goal not found: ${s}`,1),this.name="GoalNotFoundError";}},g=class extends t{constructor(s){super(`Team not found: ${s}`,1),this.name="TeamNotFoundError";}};var h=class extends t{constructor(s,n){super(s,6,n),this.name="WorkspaceError";}};export{t as a,o as b,a as c,c as d,i as e,u as f,p as g,d as h,l as i,x as j,g as k,h as l};//# sourceMappingURL=chunk-VAAOW526.js.map
2
+ //# sourceMappingURL=chunk-VAAOW526.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/domain/errors.ts"],"names":["OrchestryError","message","exitCode","hint","NotInitializedError","InvalidArgumentsError","LockConflictError","pid","NoAgentsError","TaskNotFoundError","taskId","AgentNotFoundError","agentId","TaskAlreadyRunningError","runId","agentName","InvalidTransitionError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n * Typed error hierarchy for the orchestrator.\n *\n * Every error carries an exit code (matching CLI_UI_DESIGN.md §11)\n * and an optional hint for the user.\n *\n * Exit codes:\n * 0 - Success\n * 1 - General error\n * 2 - Invalid arguments\n * 3 - Not initialized (.orchestry/ not found)\n * 4 - Lock conflict (orchestrator already running)\n * 5 - Agent error (adapter test failed)\n */\n\nexport class OrchestryError extends Error {\n constructor(\n message: string,\n public readonly exitCode: number,\n public readonly hint?: string,\n ) {\n super(message);\n this.name = 'OrchestryError';\n }\n}\n\nexport class NotInitializedError extends OrchestryError {\n constructor() {\n super('Not initialized', 3, 'Run: orch init');\n this.name = 'NotInitializedError';\n }\n}\n\nexport class InvalidArgumentsError extends OrchestryError {\n constructor(message: string) {\n super(message, 2);\n this.name = 'InvalidArgumentsError';\n }\n}\n\nexport class LockConflictError extends OrchestryError {\n constructor(pid: number) {\n super(`Orchestrator already running (PID: ${pid})`, 4, 'Use: orch status');\n this.name = 'LockConflictError';\n }\n}\n\nexport class AgentAdapterError extends OrchestryError {\n constructor(adapter: string, detail: string) {\n super(`Agent adapter \"${adapter}\" not available`, 5, detail);\n this.name = 'AgentAdapterError';\n }\n}\n\nexport class NoAgentsError extends OrchestryError {\n constructor() {\n super('No agents configured', 1, 'Run: orch agent add <name> --adapter claude');\n this.name = 'NoAgentsError';\n }\n}\n\nexport class TaskNotFoundError extends OrchestryError {\n constructor(taskId: string) {\n super(`Task not found: ${taskId}`, 1);\n this.name = 'TaskNotFoundError';\n }\n}\n\nexport class AgentNotFoundError extends OrchestryError {\n constructor(agentId: string) {\n super(`Agent not found: ${agentId}`, 1);\n this.name = 'AgentNotFoundError';\n }\n}\n\nexport class TaskAlreadyRunningError extends OrchestryError {\n constructor(taskId: string, runId: string, agentName: string) {\n super(\n `Task ${taskId} is already running (run: ${runId}, agent: ${agentName})`,\n 1,\n `Use: orch logs --task ${taskId} --follow`,\n );\n this.name = 'TaskAlreadyRunningError';\n }\n}\n\nexport class InvalidTransitionError extends OrchestryError {\n constructor(taskId: string, from: string, to: string) {\n super(`Invalid transition for ${taskId}: ${from} → ${to}`, 1);\n this.name = 'InvalidTransitionError';\n }\n}\n\nexport class GoalNotFoundError extends OrchestryError {\n constructor(goalId: string) {\n super(`Goal not found: ${goalId}`, 1);\n this.name = 'GoalNotFoundError';\n }\n}\n\nexport class TeamNotFoundError extends OrchestryError {\n constructor(teamId: string) {\n super(`Team not found: ${teamId}`, 1);\n this.name = 'TeamNotFoundError';\n }\n}\n\nexport class MessageNotFoundError extends OrchestryError {\n constructor(messageId: string) {\n super(`Message not found: ${messageId}`, 1);\n this.name = 'MessageNotFoundError';\n }\n}\n\nexport class WorkspaceError extends OrchestryError {\n constructor(message: string, hint?: string) {\n super(message, 6, hint);\n this.name = 'WorkspaceError';\n }\n}\n"]}
@@ -0,0 +1,13 @@
1
+ import {d,l,h,e}from'./chunk-VAAOW526.js';import {a,d as d$1,c}from'./chunk-AELEEEV3.js';import {dirname}from'path';import k from'fs/promises';import {execFile}from'child_process';var Q={todo:["in_progress","cancelled"],in_progress:["review","retrying","failed","cancelled"],retrying:["in_progress","failed","cancelled"],review:["done","todo","cancelled"],done:[],failed:["todo","retrying"],cancelled:["todo"]},V=new Set(["done","failed","cancelled"]);function it(c,t){return Q[c].includes(t)}function A(c){return V.has(c)}function D(c){return c==="todo"||c==="retrying"}function N(c,t){return c.depends_on.length===0?false:c.depends_on.some(e=>{let s=t.find(i=>i.id===e);return !s||s.status!=="done"})}function R(c){return c.attempts<c.max_attempts?"retrying":"failed"}function F(c,t,e){return "review"}function I(c,t,e){let s=t*Math.pow(2,c);return Math.min(s,e)}function W(c,t){if(!c?.length||!t?.length)return false;for(let e of c)for(let s of t)if(X(e,s))return true;return false}function X(c,t){if(c===t)return true;let e=c.split("*")[0],s=t.split("*")[0];if(e.startsWith(s)||s.startsWith(e))return true;if(!e.endsWith("/")&&!s.endsWith("/")){let i=dirname(e),l=dirname(s);return i===l&&i!=="."}return false}async function C(c){let t=c+".bak",e=await H(c);if(e!==null){if(K(e))return {acquired:false,pid:e};try{await k.rename(c,t);}catch{}}try{let s=await k.open(c,"wx");return await s.writeFile(String(process.pid),"utf-8"),await s.close(),await k.unlink(t).catch(()=>{}),{acquired:!0,pid:process.pid}}catch(s){if(s.code==="EEXIST")return await k.rename(t,c).catch(()=>{}),{acquired:false,pid:await H(c)??void 0};throw s}}async function B(c){await k.unlink(c).catch(()=>{});}async function H(c){try{let t=await k.readFile(c,"utf-8"),e=parseInt(t.trim(),10);return isNaN(e)?null:e}catch{return null}}function K(c){try{return process.kill(c,0),!0}catch(t){return t.code==="EPERM"}}var 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();}},x=class{constructor(t){this.inner=t;}listCache=null;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){return this.inner.getByName(t)}async save(t){await this.inner.save(t),this.listCache=null;}async delete(t){await this.inner.delete(t),this.listCache=null;}invalidate(){this.listCache=null;}},E=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 Z={test_pass:{cmd:"npm",args:["test"]},typecheck:{cmd:"npx",args:["tsc","--noEmit"]},lint:{cmd:"npm",args:["run","lint"]}},_=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 i=await this.runCriterion(s);e.push(i);}return e}static allPassed(t){return t.length>0&&t.every(e=>e.passed)}static formatReport(t){return t.map(s=>{let i=s.passed?"\u2713":"\u2717",l=s.output.slice(0,500);return `${i} ${s.criterion}: ${s.passed?"PASSED":"FAILED"}
2
+ ${l}`}).join(`
3
+
4
+ `)}runCriterion(t){let{cmd:e,args:s}=Z[t];return new Promise(i=>{execFile(e,s,{cwd:this.cwd,timeout:this.timeoutMs,maxBuffer:1024*1024},(l,r,a)=>{let u=(r+`
5
+ `+a).trim();i({criterion:t,passed:!l,output:u.slice(0,2e3)});});})}};var tt=8192,et=4096,z=class{constructor(t){this.deps=t;this.cachedTaskStore=new b(t.taskStore),this.cachedAgentStore=new x(t.agentStore),this.cachedGoalStore=t.goalStore?new E(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;stateMutex=Promise.resolve();get isOwner(){return this.lockAcquired}withStateLock(t){let e,s=new Promise(l=>{e=l;}),i=this.stateMutex;return this.stateMutex=s,i.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 C(this.deps.lockPath);if(!e.acquired)throw new d(e.pid);this.lockAcquired=true;try{await t();}finally{this.lockAcquired=false,await B(this.deps.lockPath);}}async startWatch(){let t=await C(this.deps.lockPath);if(!t.acquired)throw new d(t.pid);this.lockAcquired=true,await this.loadState(),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;},e=>{this.consecutiveTickFailures++;let s=e instanceof Error?e.message:String(e);this.deps.eventBus.emit({type:"orchestrator:error",error:s,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(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:"stop after consecutive tick failures",fatal:false});}));}),this.deps.config.scheduling.poll_interval_ms);}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(){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]of Object.entries(this.state.running)){this.abortControllers.get(t)?.abort(),this.abortControllers.delete(t),await this.deps.processManager.killWithGrace(e.pid),await this.deps.runService.finish(e.run_id,"cancelled");let s=await this.deps.taskStore.get(t);s&&await this.deps.taskService.updateStatus(t,R(s)),await this.deps.agentService.setStatus(e.agent_id,"idle");}this.state.running={},this.state.claimed=[],this.state.pid=void 0,this.state.started_at=void 0,await this.saveState();}}),this.lockAcquired&&(await B(this.deps.lockPath),this.lockAcquired=false),this.removeSignalHandlers());}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(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:`cancelTask kill process ${s.pid} for task ${t}`,fatal:false});}),await this.deps.runService.finish(s.run_id,"cancelled").catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:`cancelTask finish run ${s.run_id}`,fatal:false});}),await this.deps.agentService.setStatus(s.agent_id,"idle").catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),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(i=>i.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,i]of Object.entries(e.running))if(i.agent_id===t){this.abortControllers.get(s)?.abort(),this.abortControllers.delete(s),await this.deps.processManager.killWithGrace(i.pid,3e3),await this.deps.runService.finish(i.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(),await this.seedAutonomousTasks(),await this.dispatchAll();let t=await this.cachedTaskStore.list(),e=Object.keys(this.state.running).length,s=t.filter(i=>D(i.status)).length;this.deps.eventBus.emit({type:"orchestrator:tick",running:e,queued:s});});}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();for(let[r,a]of Object.entries(t.running)){let u=await this.deps.taskStore.get(r);if(!u||A(u.status)){this.abortControllers.delete(r),delete t.running[r],await this.deps.agentService.setStatus(a.agent_id,"idle").catch(d=>{this.deps.eventBus.emit({type:"orchestrator:error",error:d instanceof Error?d.message:String(d),context:`reconcile setStatus idle for stale agent ${a.agent_id} (task ${r})`,fatal:false});});continue}if(!this.deps.processManager.isAlive(a.pid)){try{await this._handleRunFailure(r,a,"Process crashed unexpectedly");}catch{delete t.running[r],await this.deps.agentService.setStatus(a.agent_id,"idle").catch(d=>{this.deps.eventBus.emit({type:"orchestrator:error",error:d instanceof Error?d.message:String(d),context:`reconcile crash fallback setStatus idle for agent ${a.agent_id} (task ${r})`,fatal:false});});}continue}let o=new Date(a.last_event_at).getTime(),n=this.deps.config.defaults.agent.stall_timeout_ms;if(e-o>n){this.deps.eventBus.emit({type:"orchestrator:stall_detected",runId:a.run_id}),this.abortControllers.get(r)?.abort(),await this.deps.processManager.killWithGrace(a.pid,5e3);try{await this._handleRunFailure(r,a,"Agent stalled (no events)");}catch{delete t.running[r],await this.deps.agentService.setStatus(a.agent_id,"idle").catch(d=>{this.deps.eventBus.emit({type:"orchestrator:error",error:d instanceof Error?d.message:String(d),context:`reconcile stall fallback setStatus idle for agent ${a.agent_id} (task ${r})`,fatal:false});});}}}let s=new Set(Object.values(t.running).map(r=>r.agent_id)),i=await this.cachedAgentStore.list();for(let r of i)r.status==="running"&&!s.has(r.id)&&await this.deps.agentService.setStatus(r.id,"idle");let l=await this.cachedTaskStore.list();for(let r of l)if(r.status==="in_progress"&&!t.running[r.id]){try{await this.deps.taskService.updateStatus(r.id,"failed");}catch{r.status="failed",r.updated_at=new Date().toISOString(),await this.deps.taskStore.save(r).catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`force-write orphaned task ${r.id}`,fatal:false});});}this.deps.eventBus.emit({type:"task:orphaned",taskId:r.id});}for(let r=t.retry_queue.length-1;r>=0;r--){let a=t.retry_queue[r];e>=new Date(a.due_at).getTime()&&(t.retry_queue.splice(r,1),await this.dispatchTask(a.task_id));}await this.saveState();}async seedAutonomousTasks(){let e=(await this.cachedAgentStore.list()).filter(a=>a.autonomous&&a.status==="idle");if(e.length===0)return;let s=await this.cachedTaskStore.list(),i=this.cachedGoalStore?await this.cachedGoalStore.list({status:"active"}):[],l=false,r=new Set;for(let a$1 of e){if(s.some(h=>h.assignee===a$1.id&&!A(h.status)))continue;let o=i.find(h=>h.assignee===a$1.id&&!r.has(h.id))??i.find(h=>!h.assignee&&!r.has(h.id));o&&r.add(o.id);let n=a$1.role??"general assistant",d=o?`[auto] ${a$1.name}: ${o.title.slice(0,60)}`:`[auto] ${a$1.name}: ${n.slice(0,60)}`,g=o?`## GOAL (highest priority)
6
+
7
+ ${o.description||o.title}
8
+
9
+ ---
10
+ Agent role: ${n}`:`Autonomous work cycle. Agent role: ${n}`;try{await this.deps.taskService.create({title:d,description:g,assignee:a$1.id,labels:[a],priority:3}),l=!0;}catch(h){this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),context:`autonomous task for agent ${a$1.id}`,fatal:false});}}l&&this.cachedTaskStore.invalidate();}async dispatchAll(){let t=this.state,e=this.deps.config.scheduling.max_concurrent_agents,s=Object.keys(t.running).length,i=e-s;if(i<=0)return;let l$1=await this.cachedTaskStore.list(),r=l$1.filter(o=>D(o.status)&&!N(o,l$1)&&!t.running[o.id]&&!t.claimed.includes(o.id)).sort((o,n)=>{let d=n.updated_at??"",g=o.updated_at??"";return d<g?-1:d>g?1:0}).slice(0,i),a=new Set,u=l$1.filter(o=>o.status==="in_progress"&&o.scope?.length);for(let o=0;o<r.length;o++){let n=r[o];if(!n.scope?.length)continue;let d=r.slice(0,o).filter(v=>!a.has(v.id)),g=[...u,...d],h=false;for(let v of g)if(W(n.scope,v.scope)){this.deps.eventBus.emit({type:"task:scope_overlap",taskId:n.id,overlappingTaskId:v.id,patterns:n.scope}),h=true;break}h&&a.add(n.id);}for(let o of r)if(!a.has(o.id))try{await this.dispatchTask(o.id);}catch(n){if(n instanceof l)try{let d=await this.deps.taskStore.get(o.id);d&&!A(d.status)&&(d.status="failed",d.updated_at=new Date().toISOString(),await this.deps.taskStore.save(d));}catch{}this.deps.eventBus.emit({type:"orchestrator:error",error:n instanceof Error?n.message:String(n),context:`dispatch task ${o.id}`,fatal:false});}}async dispatchTask(t){let e$1=this.state;if(e$1.running[t]){let i=e$1.running[t];throw new h(t,i.run_id,i.agent_id)}let s=await this.deps.taskService.get(t);e$1.claimed.push(t),await this.saveState();try{let i=await this.deps.agentService.findBestAgent(s);if(!i){if((await this.cachedAgentStore.list()).length===0)throw new e;this.unclaim(t),await this.saveState();return}let{path:l,branch:r}=await this.deps.workspaceManager.prepare(s,i,this.deps.config),a=this.deps.config.prompt?.template??d$1,u=await this.cachedAgentStore.list(),o=s.attempts+1,n;if(o>1){let w=await this.deps.runService.getLastFailedRunContext(s.id);w&&(n={previous_error:w.error,previous_output:w.output});}let d=this.deps.contextStore?await this.deps.contextStore.getAll():void 0,g=this.deps.messageService?await this.deps.messageService.drainMailbox(i.id,s.id):[],h=c(s,i,o,l,this.deps.config,{allAgents:u,retryContext:n,sharedContext:d,feedback:s.feedback,messages:g.length?g:void 0}),v=await this.deps.templateEngine.render(a,h),p=await this.deps.runService.create({taskId:s.id,agentId:i.id,attempt:o,prompt:v,workspacePath:l});(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,i.id),await this.deps.taskService.incrementAttempts(t),r&&(s.proof={...s.proof??{files_changed:[]},branch:r},s.workspace=l,await this.deps.taskStore.save(s)),await this.deps.agentService.setStatus(i.id,"running");let m=await this.deps.agentService.get(i.id);m.current_task=t,await this.deps.agentStore.save(m);let f=this.deps.adapterRegistry.require(i.adapter),S=new AbortController;this.abortControllers.set(t,S);let y=f.execute({prompt:v,workspace:l,env:{...i.config.env,ORCH_AGENT_ID:i.id,ORCH_AGENT_NAME:i.name,ORCH_TASK_ID:s.id},config:m.config,signal:S.signal}),M=y.pid,O=new Date().toISOString();await this.deps.runService.start(p.id,M),this.unclaim(t),e$1.running[t]={run_id:p.id,agent_id:i.id,task_id:t,pid:M,started_at:O,last_event_at:O},await this.saveState(),this.collectEvents(y.events,p.id,t,i.id).catch(w=>{this.deps.eventBus.emit({type:"orchestrator:error",error:w instanceof Error?w.message:String(w),context:`adapter execution for ${t}`,fatal:!1});});}catch(i){throw this.unclaim(t),await this.saveState(),i}}async collectEvents(t,e,s,i){let l,r,a,u=new Set;try{for await(let n of t){if(this.shuttingDown)break;if(n.type==="done"){n.tokens&&(l=n.tokens);let p=n.data;p&&typeof p.result=="string"&&(r=p.result);}if(n.type==="output"){let p=n.data;if(p){let m=typeof p.text=="string"?p.text:typeof p.message=="string"?p.message:void 0;m?.trim()&&(a=m);}}if(n.type==="file_change"){let p=n.data;if(p&&Array.isArray(p.paths))for(let m of p.paths)typeof m=="string"&&u.add(m);else {let m=p&&typeof p.path=="string"?p.path:typeof n.data=="string"?n.data:String(n.data);u.add(m);}}let d=st(n.timestamp)?n.timestamp:new Date().toISOString(),g=J(n.data,tt);n.data=void 0;let h={timestamp:d,type:n.type==="output"?"agent_output":n.type==="file_change"?"file_changed":n.type==="command"?"command_run":n.type==="tool_call"?"tool_call":n.type==="error"?"error":"done",data:g};await this.deps.runService.appendEvent(e,h),this.state?.running[s]&&(this.state.running[s].last_event_at=d,this.saveStateLazy());let v=J(g,et);n.type==="output"||n.type==="tool_call"?this.deps.eventBus.emit({type:"agent:output",runId:e,agentId:i,data:v}):n.type==="file_change"?this.deps.eventBus.emit({type:"agent:file_changed",runId:e,agentId:i,path:typeof n.data=="string"?n.data:String(n.data)}):n.type==="error"&&this.deps.eventBus.emit({type:"agent:error",runId:e,agentId:i,error:v});}let o=r??a;await this.handleRunSuccess(s,e,i,l,o,[...u]);}catch(o){let n=o instanceof Error?o.message:String(o),d=this.state?.running[s];d&&await this.handleRunFailure(s,d,n);}}async handleRunSuccess(t,e,s,i,l,r){return this.withStateLock(()=>this._handleRunSuccess(t,e,s,i,l,r))}async _handleRunSuccess(t,e,s,i,l,r){await this.flushStateLazy(),this.abortControllers.delete(t);let a$1=this.state;if(!a$1.running[t])return;let u=await this.deps.taskStore.get(t);if(!u)return;u.proof={...u.proof,agent_summary:l?.slice(0,2e3)??u.proof?.agent_summary,files_changed:r?.length?r:u.proof?.files_changed??[]},delete u.feedback,await this.deps.taskStore.save(u);let o=await this.deps.agentStore.get(s),d=u.labels?.includes(a)||o?.config.approval_policy==="auto",g=F();await this.deps.runService.finish(e,"succeeded",i);let h=a$1.running[t],v=h?Date.now()-new Date(h.started_at).getTime():0;h&&(a$1.stats.total_runtime_ms+=v),delete a$1.running[t];let p={tasks_completed:(o?.stats.tasks_completed??0)+1,total_runs:(o?.stats.total_runs??0)+1,total_runtime_ms:(o?.stats.total_runtime_ms??0)+v};if(i&&(p.tokens_used=(o?.stats.tokens_used??0)+i.total),await this.deps.agentService.updateStats(s,p).catch(f=>{this.deps.eventBus.emit({type:"orchestrator:error",error:f instanceof Error?f.message:String(f),context:`agent stats update for ${s}`,fatal:false});}),a$1.stats.total_tasks_completed++,a$1.stats.total_runs++,i&&(a$1.stats.total_tokens.input+=i.input,a$1.stats.total_tokens.output+=i.output,a$1.stats.total_tokens.total=a$1.stats.total_tokens.input+a$1.stats.total_tokens.output),u.proof?.branch)try{let f=await this.deps.workspaceManager.mergeBack(u.proof.branch);if(f.success)this.deps.eventBus.emit({type:"workspace:merge_succeeded",taskId:t,branch:u.proof.branch}),await this.deps.workspaceManager.cleanup(t).catch(S=>{this.deps.eventBus.emit({type:"orchestrator:error",error:S instanceof Error?S.message:String(S),context:`workspace cleanup for ${t}`,fatal:!1});});else {this.deps.eventBus.emit({type:"workspace:merge_conflict",taskId:t,branch:u.proof.branch,conflictInfo:f.conflictInfo}),await this.forceTaskToReview(u,s,`MERGE CONFLICT: ${f.conflictInfo}`);return}}catch(f){let S=f instanceof Error?f.message:String(f);await this.forceTaskToReview(u,s,`MERGE ERROR: ${S}`);return}try{await this.deps.taskService.updateStatus(t,g);}catch(f){let S=f instanceof Error?f.message:String(f);this.deps.eventBus.emit({type:"orchestrator:error",error:S,context:`state machine validation failed for task ${t} -> ${g}, force-writing`,fatal:false}),u.status=g,u.updated_at=new Date().toISOString(),await this.deps.taskStore.save(u).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(f=>{this.deps.eventBus.emit({type:"orchestrator:error",error:f instanceof Error?f.message:String(f),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)),u.review_criteria?.length?await this.runAutoReview(t,u.review_criteria,u.workspace??this.deps.projectRoot):d&&await this.deps.taskService.updateStatus(t,"done"),await this.saveState(),this.scheduleImmediateDispatch();}async handleRunFailure(t,e,s){return this.withStateLock(()=>this._handleRunFailure(t,e,s))}async _handleRunFailure(t,e,s){await this.flushStateLazy(),this.abortControllers.delete(t);let i=this.state,l=await this.deps.taskStore.get(t);if(!l)return;await this.deps.runService.finish(e.run_id,"failed",void 0,s),await this.deps.agentService.setStatus(e.agent_id,"idle");let r=await this.deps.agentStore.get(e.agent_id);r&&(r.current_task=void 0,await this.deps.agentStore.save(r));let a=await this.deps.agentStore.get(e.agent_id),u=Date.now()-new Date(e.started_at).getTime();await this.deps.agentService.updateStats(e.agent_id,{tasks_failed:(a?.stats.tasks_failed??0)+1,total_runs:(a?.stats.total_runs??0)+1,total_runtime_ms:(a?.stats.total_runtime_ms??0)+u});let o=R(l);if(await this.deps.taskService.updateStatus(t,o),o==="retrying"){let n=I(l.attempts-1,this.deps.config.scheduling.retry_base_delay_ms,this.deps.config.scheduling.retry_max_delay_ms);i.retry_queue.some(g=>g.task_id===t)||(i.retry_queue.length>=this.maxRetryQueueSize&&i.retry_queue.shift(),i.retry_queue.push({task_id:t,attempt:l.attempts+1,due_at:new Date(Date.now()+n).toISOString(),error:s})),this.deps.eventBus.emit({type:"run:retry",runId:e.run_id,attempt:l.attempts+1,delay_ms:n});}else i.stats.total_tasks_failed++;i.stats.total_runtime_ms+=u,delete i.running[t],i.stats.total_runs++,await this.saveState(),this.scheduleImmediateDispatch();}async runAutoReview(t,e,s){let l=await new _({cwd:s}).runAll(e),r=_.allPassed(l),a=await this.deps.taskStore.get(t);if(a&&(a.review_results=l,a.proof={...a.proof,test_results:_.formatReport(l),files_changed:a.proof?.files_changed??[]},await this.deps.taskStore.save(a),this.deps.eventBus.emit({type:"task:auto_reviewed",taskId:t,passed:r,results:l}),r))try{await this.deps.taskService.updateStatus(t,"done");}catch(u){let o=u instanceof Error?u.message:String(u);this.deps.eventBus.emit({type:"orchestrator:error",error:o,context:`auto-review transition failed for task ${t} -> done, force-writing`,fatal:false}),a.status="done",a.updated_at=new Date().toISOString(),await this.deps.taskStore.save(a).catch(n=>{this.deps.eventBus.emit({type:"orchestrator:error",error:n instanceof Error?n.message:String(n),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
+
12
+ ${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(l=>{this.deps.eventBus.emit({type:"orchestrator:error",error:l instanceof Error?l.message:String(l),context:`forceTaskToReview setStatus idle for agent ${e}`,fatal:false});});let i=await this.deps.agentStore.get(e);i&&(i.current_task=void 0,await this.deps.agentStore.save(i)),await this.saveState();}unclaim(t){let e=this.state.claimed.indexOf(t);e!==-1&&this.state.claimed.splice(e,1);}requireOwnership(){if(!this.lockAcquired)throw new d(0)}async loadState(){this.state=await this.deps.stateStore.read();}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 st(c){if(typeof c!="string")return false;let t=new Date(c);return !isNaN(t.getTime())&&t.toISOString()===c}function J(c,t){let e=typeof c=="string"?c:JSON.stringify(c);return e.length>t?e.slice(0,t)+"\u2026":e}export{it as a,A as b,D as c,N as d,R as e,z as f};//# sourceMappingURL=chunk-ZTQ3KWXR.js.map
13
+ //# sourceMappingURL=chunk-ZTQ3KWXR.js.map