opencastle 1.12.6 → 1.12.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/README.md +14 -13
  2. package/dist/cli/convoy/crash-status.test.js +1 -1
  3. package/dist/cli/convoy/crash-status.test.js.map +1 -1
  4. package/dist/cli/convoy/engine.d.ts +3 -1
  5. package/dist/cli/convoy/engine.d.ts.map +1 -1
  6. package/dist/cli/convoy/engine.git.test.js +130 -2
  7. package/dist/cli/convoy/engine.git.test.js.map +1 -1
  8. package/dist/cli/convoy/engine.js +136 -13
  9. package/dist/cli/convoy/engine.js.map +1 -1
  10. package/dist/cli/convoy/engine.test.js +27 -1
  11. package/dist/cli/convoy/engine.test.js.map +1 -1
  12. package/dist/cli/convoy/event-schemas.d.ts.map +1 -1
  13. package/dist/cli/convoy/event-schemas.js +1 -0
  14. package/dist/cli/convoy/event-schemas.js.map +1 -1
  15. package/dist/cli/convoy/hangup.test.d.ts +2 -0
  16. package/dist/cli/convoy/hangup.test.d.ts.map +1 -0
  17. package/dist/cli/convoy/hangup.test.js +124 -0
  18. package/dist/cli/convoy/hangup.test.js.map +1 -0
  19. package/dist/cli/convoy/ledger-paths.test.js +1 -1
  20. package/dist/cli/convoy/ledger-paths.test.js.map +1 -1
  21. package/dist/cli/convoy/lock.d.ts.map +1 -1
  22. package/dist/cli/convoy/lock.js +28 -13
  23. package/dist/cli/convoy/lock.js.map +1 -1
  24. package/dist/cli/convoy/lock.test.js +44 -2
  25. package/dist/cli/convoy/lock.test.js.map +1 -1
  26. package/dist/cli/convoy/merge.d.ts +2 -0
  27. package/dist/cli/convoy/merge.d.ts.map +1 -1
  28. package/dist/cli/convoy/merge.js +4 -2
  29. package/dist/cli/convoy/merge.js.map +1 -1
  30. package/dist/cli/convoy/merge.test.js +14 -4
  31. package/dist/cli/convoy/merge.test.js.map +1 -1
  32. package/dist/cli/convoy/store.d.ts +1 -1
  33. package/dist/cli/convoy/store.d.ts.map +1 -1
  34. package/dist/cli/convoy/store.js +13 -2
  35. package/dist/cli/convoy/store.js.map +1 -1
  36. package/dist/cli/convoy/store.test.js +11 -11
  37. package/dist/cli/convoy/types.d.ts +9 -1
  38. package/dist/cli/convoy/types.d.ts.map +1 -1
  39. package/dist/cli/convoy/types.js.map +1 -1
  40. package/dist/cli/doctor.js +1 -1
  41. package/dist/cli/explain.d.ts.map +1 -1
  42. package/dist/cli/explain.js +2 -1
  43. package/dist/cli/explain.js.map +1 -1
  44. package/dist/cli/remove.js +1 -1
  45. package/dist/cli/run/adapters/agent-process.d.ts.map +1 -1
  46. package/dist/cli/run/adapters/agent-process.js +58 -12
  47. package/dist/cli/run/adapters/agent-process.js.map +1 -1
  48. package/dist/cli/run/adapters/agent-process.test.js +59 -0
  49. package/dist/cli/run/adapters/agent-process.test.js.map +1 -1
  50. package/package.json +1 -1
  51. package/src/cli/convoy/TELEMETRY.md +3 -3
  52. package/src/cli/convoy/crash-status.test.ts +1 -1
  53. package/src/cli/convoy/engine.git.test.ts +141 -2
  54. package/src/cli/convoy/engine.test.ts +29 -1
  55. package/src/cli/convoy/engine.ts +138 -16
  56. package/src/cli/convoy/event-schemas.ts +1 -0
  57. package/src/cli/convoy/hangup.test.ts +126 -0
  58. package/src/cli/convoy/ledger-paths.test.ts +1 -1
  59. package/src/cli/convoy/lock.test.ts +63 -2
  60. package/src/cli/convoy/lock.ts +29 -13
  61. package/src/cli/convoy/merge.test.ts +17 -4
  62. package/src/cli/convoy/merge.ts +6 -2
  63. package/src/cli/convoy/store.test.ts +11 -11
  64. package/src/cli/convoy/store.ts +14 -3
  65. package/src/cli/convoy/types.ts +9 -1
  66. package/src/cli/doctor.ts +1 -1
  67. package/src/cli/explain.ts +2 -1
  68. package/src/cli/remove.ts +1 -1
  69. package/src/cli/run/adapters/agent-process.test.ts +59 -0
  70. package/src/cli/run/adapters/agent-process.ts +56 -10
@@ -55,7 +55,20 @@ describe('merge - successful merge', () => {
55
55
 
56
56
  const result = await queue.merge(worktreePath, 'convoy-worker1', featureBranch)
57
57
 
58
- expect(result).toEqual({ success: true, conflicted: false, message: 'Merged successfully' })
58
+ expect(result).toEqual({ success: true, conflicted: false, message: 'Merged successfully', commit: expect.any(String) })
59
+ })
60
+
61
+ it('reports the worker commit it merged, which is then on the target branch', async () => {
62
+ // The engine records it the moment the merge lands, so a resume can tell
63
+ // the work is already on the branch.
64
+ const worktreePath = await addWorktree(repoPath, 'worker1', featureBranch)
65
+ writeFileSync(join(worktreePath, 'output.txt'), 'worker output')
66
+
67
+ const { commit } = await queue.merge(worktreePath, 'convoy-worker1', featureBranch)
68
+
69
+ const { stdout: tip } = await execFile('git', ['-C', repoPath, 'rev-parse', 'convoy-worker1'])
70
+ expect(commit).toBe(tip.trim())
71
+ await execFile('git', ['-C', repoPath, 'merge-base', '--is-ancestor', commit, featureBranch])
59
72
  })
60
73
 
61
74
  it('makes the merged file available in the target branch working tree', async () => {
@@ -87,7 +100,7 @@ describe('merge - no changes', () => {
87
100
 
88
101
  const result = await queue.merge(worktreePath, 'convoy-worker1', featureBranch)
89
102
 
90
- expect(result).toEqual({ success: true, conflicted: false, message: 'No changes to merge' })
103
+ expect(result).toEqual({ success: true, conflicted: false, message: 'No changes to merge', commit: expect.any(String) })
91
104
  })
92
105
 
93
106
  it('does not create a commit when there is nothing to stage', async () => {
@@ -111,7 +124,7 @@ describe('merge - conflict', () => {
111
124
  writeFileSync(join(worktree2, 'shared.txt'), 'content from worker 2')
112
125
 
113
126
  const first = await queue.merge(worktree1, 'convoy-worker1', featureBranch)
114
- expect(first).toEqual({ success: true, conflicted: false, message: 'Merged successfully' })
127
+ expect(first).toEqual({ success: true, conflicted: false, message: 'Merged successfully', commit: expect.any(String) })
115
128
 
116
129
  await expect(queue.merge(worktree2, 'convoy-worker2', featureBranch))
117
130
  .rejects.toThrow(MergeConflictError)
@@ -147,7 +160,7 @@ describe('merge - already committed changes', () => {
147
160
 
148
161
  const result = await queue.merge(worktreePath, 'convoy-worker1', featureBranch)
149
162
 
150
- expect(result).toEqual({ success: true, conflicted: false, message: 'Merged successfully' })
163
+ expect(result).toEqual({ success: true, conflicted: false, message: 'Merged successfully', commit: expect.any(String) })
151
164
  })
152
165
 
153
166
  it('makes pre-committed files available in the target branch after merge', async () => {
@@ -5,6 +5,8 @@ export interface MergeResult {
5
5
  success: boolean
6
6
  conflicted: boolean
7
7
  message: string
8
+ /** The worker's commit, now an ancestor of the target branch. */
9
+ commit: string
8
10
  }
9
11
 
10
12
  export class MergeConflictError extends Error {
@@ -76,8 +78,10 @@ export function createMergeQueue(
76
78
  throw new Error(`Path "${worktreePath}" is outside the managed worktrees directory`)
77
79
  }
78
80
 
81
+ let commit: string
79
82
  try {
80
83
  await commitAllIn(resolve(worktreePath), `convoy: ${worktreeBranch} completed`)
84
+ commit = (await git(['rev-parse', '--verify', 'HEAD^{commit}'], resolve(worktreePath))).trim()
81
85
  } catch (err) {
82
86
  throw new MergeError(`could not commit the task's work: ${firstLine((err as { stderr?: string }).stderr) || (err as Error).message}`)
83
87
  }
@@ -92,9 +96,9 @@ export function createMergeQueue(
92
96
  try {
93
97
  const stdout = await mergeIn(target, ['--no-edit', worktreeBranch])
94
98
  if (stdout.includes('Already up to date')) {
95
- return { success: true, conflicted: false, message: 'No changes to merge' }
99
+ return { success: true, conflicted: false, message: 'No changes to merge', commit }
96
100
  }
97
- return { success: true, conflicted: false, message: 'Merged successfully' }
101
+ return { success: true, conflicted: false, message: 'Merged successfully', commit }
98
102
  } catch (err) {
99
103
  const error = err as { code?: number | string; stderr?: string; stdout?: string; message?: string }
100
104
  const text = `${error.stdout ?? ''}\n${error.stderr ?? ''}`
@@ -103,7 +103,7 @@ describe('DB creation', () => {
103
103
  const db = new DatabaseSync(dbPath)
104
104
  const row = db.prepare('PRAGMA user_version').get() as { user_version: number }
105
105
  db.close()
106
- expect(row.user_version).toBe(14)
106
+ expect(row.user_version).toBe(15)
107
107
  })
108
108
 
109
109
  it('creates all required tables', () => {
@@ -131,7 +131,7 @@ describe('DB creation', () => {
131
131
  store2.close()
132
132
  // Reassign so afterEach does not double-close
133
133
  store = createConvoyStore(dbPath)
134
- expect(row.user_version).toBe(14)
134
+ expect(row.user_version).toBe(15)
135
135
  })
136
136
  })
137
137
 
@@ -209,7 +209,7 @@ describe('schema migration', () => {
209
209
 
210
210
  expect(cols.map(c => c.name)).toContain('adapter')
211
211
  // v1 chains through v2→v3→v4→...→v12→v13→v14 in one init, so final version is 14
212
- expect(version.user_version).toBe(14)
212
+ expect(version.user_version).toBe(15)
213
213
  })
214
214
 
215
215
  it('schema migration v2 to v3 adds cost columns', () => {
@@ -295,7 +295,7 @@ describe('schema migration', () => {
295
295
  expect(convoyColNames).toContain('total_tokens')
296
296
  expect(convoyColNames).toContain('total_cost_usd')
297
297
 
298
- expect(version.user_version).toBe(14)
298
+ expect(version.user_version).toBe(15)
299
299
  })
300
300
 
301
301
  it('schema migration v1 to v3 chains correctly in a single init', () => {
@@ -381,7 +381,7 @@ describe('schema migration', () => {
381
381
  expect(convoyColNames).toContain('total_tokens')
382
382
  expect(convoyColNames).toContain('total_cost_usd')
383
383
 
384
- expect(version.user_version).toBe(14)
384
+ expect(version.user_version).toBe(15)
385
385
  })
386
386
 
387
387
  it('schema migration v3 to v4 creates pipeline table and adds pipeline_id to convoy', () => {
@@ -464,7 +464,7 @@ describe('schema migration', () => {
464
464
 
465
465
  expect(convoyCols.map(c => c.name)).toContain('pipeline_id')
466
466
  expect(tables.map(t => t.name)).toContain('pipeline')
467
- expect(version.user_version).toBe(14)
467
+ expect(version.user_version).toBe(15)
468
468
  })
469
469
  })
470
470
 
@@ -1458,7 +1458,7 @@ describe('schema migration v5 → v6', () => {
1458
1458
  v5Verify.close()
1459
1459
  migratedStore.close()
1460
1460
 
1461
- expect(row.user_version).toBe(14)
1461
+ expect(row.user_version).toBe(15)
1462
1462
  expect(taskStepTable?.name).toBe('task_step')
1463
1463
  expect(convoy?.id).toBe('convoy-auto')
1464
1464
  expect(task?.id).toBe('task-auto')
@@ -1628,7 +1628,7 @@ describe('schema migration v6→v7 (drift detection columns)', () => {
1628
1628
 
1629
1629
  expect(cols.map(c => c.name)).toContain('drift_score')
1630
1630
  expect(cols.map(c => c.name)).toContain('drift_retried')
1631
- expect(version.user_version).toBe(14)
1631
+ expect(version.user_version).toBe(15)
1632
1632
  })
1633
1633
 
1634
1634
  it('new databases include drift_score and drift_retried in CREATE TABLE', () => {
@@ -1862,7 +1862,7 @@ describe('migration full chain v4→v10', () => {
1862
1862
  const verifyDb = new DatabaseSync(chainDbPath)
1863
1863
  verifyDb.exec('PRAGMA foreign_keys = 0')
1864
1864
  const version = (verifyDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version
1865
- expect(version).toBe(14)
1865
+ expect(version).toBe(15)
1866
1866
 
1867
1867
  // Verify all new tables exist
1868
1868
  const tables = (verifyDb.prepare("SELECT name FROM sqlite_master WHERE type='table'").all() as Array<{ name: string }>).map(t => t.name)
@@ -1959,7 +1959,7 @@ describe('migration v12 → v13', () => {
1959
1959
 
1960
1960
  expect(cols).not.toContain('compaction_count')
1961
1961
  expect(cols).not.toContain('discovered_issues')
1962
- expect(version).toBe(14)
1962
+ expect(version).toBe(15)
1963
1963
 
1964
1964
  // The rows, and the fields beside the dropped ones, survive the rewrite.
1965
1965
  expect(convoy?.name).toBe('Kept')
@@ -2666,7 +2666,7 @@ describe('v9→v10 migration', () => {
2666
2666
  // Verify version = 11
2667
2667
  const verifyDb = new DatabaseSync(migDb)
2668
2668
  const version = (verifyDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version
2669
- expect(version).toBe(14)
2669
+ expect(version).toBe(15)
2670
2670
 
2671
2671
  // Verify new REAL columns exist
2672
2672
  const convoyCols = (verifyDb.prepare('PRAGMA table_info(convoy)').all() as Array<{ name: string }>).map(c => c.name)
@@ -17,7 +17,7 @@ import type {
17
17
  TaskStepRecord,
18
18
  } from './types.js'
19
19
 
20
- const SCHEMA_VERSION = 14
20
+ const SCHEMA_VERSION = 15
21
21
 
22
22
  // ── Size limits (bytes) ────────────────────────────────────────────────────────
23
23
  const LIMIT_SPEC_YAML = 256 * 1024 // 256 KB
@@ -65,7 +65,7 @@ export type TaskStatusExtra = Partial<
65
65
  | 'worker_id' | 'worktree' | 'output' | 'exit_code' | 'started_at' | 'finished_at'
66
66
  | 'retries' | 'prompt_tokens' | 'completion_tokens' | 'total_tokens' | 'cost_usd' | 'prompt'
67
67
  | 'contract_result' | 'model' | 'cache_read_tokens' | 'cache_write_tokens' | 'cost_estimated'
68
- | 'retry_note' | 'branch'
68
+ | 'retry_note' | 'branch' | 'merged_commit'
69
69
  >
70
70
  >
71
71
 
@@ -73,7 +73,7 @@ const TASK_EXTRA_FIELDS = [
73
73
  'worker_id', 'worktree', 'output', 'exit_code', 'started_at', 'finished_at',
74
74
  'retries', 'prompt_tokens', 'completion_tokens', 'total_tokens', 'cost_usd', 'prompt',
75
75
  'contract_result', 'model', 'cache_read_tokens', 'cache_write_tokens', 'cost_estimated',
76
- 'retry_note', 'branch',
76
+ 'retry_note', 'branch', 'merged_commit',
77
77
  ] as const
78
78
 
79
79
  export interface ConvoyStore {
@@ -293,6 +293,7 @@ class ConvoyStoreImpl implements ConvoyStore {
293
293
  cost_estimated INTEGER NOT NULL DEFAULT 0,
294
294
  retry_note TEXT,
295
295
  branch TEXT,
296
+ merged_commit TEXT,
296
297
  PRIMARY KEY (id, convoy_id)
297
298
  );
298
299
 
@@ -464,6 +465,10 @@ class ConvoyStoreImpl implements ConvoyStore {
464
465
  migrateSchema(this.db, this.dbPath, 13, 14)
465
466
  version = 14
466
467
  }
468
+ if (version === 14) {
469
+ migrateSchema(this.db, this.dbPath, 14, 15)
470
+ version = 15
471
+ }
467
472
  }
468
473
 
469
474
  insertConvoy(
@@ -1565,6 +1570,12 @@ export function migrateSchema(db: DatabaseSync, dbPath: string, fromVersion: num
1565
1570
  addColumnIfMissing(db, 'convoy', 'cost_estimated', 'INTEGER NOT NULL DEFAULT 0')
1566
1571
  addColumnIfMissing(db, 'convoy', 'adapter', 'TEXT')
1567
1572
  }
1573
+ if (v === 14) {
1574
+ // What a task merged. A run that died between the merge and the task's
1575
+ // "done" left it running, and resume ran work already on the branch a
1576
+ // second time.
1577
+ addColumnIfMissing(db, 'task', 'merged_commit', 'TEXT')
1578
+ }
1568
1579
  db.exec('COMMIT')
1569
1580
  } catch (err) {
1570
1581
  try { db.exec('ROLLBACK') } catch { /* ignore */ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `interrupted` is a run stopped by SIGINT or SIGTERM: its running tasks went
2
+ * `interrupted` is a run stopped by SIGINT, SIGTERM or SIGHUP: its running tasks went
3
3
  * back to pending, and `convoy resume` carries on from there.
4
4
  */
5
5
  export type ConvoyStatus = 'pending' | 'running' | 'done' | 'failed' | 'gate-failed' | 'hook-failed' | 'interrupted'
@@ -98,6 +98,12 @@ export interface TaskRecord {
98
98
  retry_note?: string | null
99
99
  /** A worker branch kept because its work could not be merged. */
100
100
  branch?: string | null
101
+ /**
102
+ * The worker commit that merged into the convoy branch, written the moment
103
+ * the merge lands. From then on the task is done, whatever happens before
104
+ * its row says so.
105
+ */
106
+ merged_commit?: string | null
101
107
  }
102
108
 
103
109
  export interface WorkerRecord {
@@ -305,6 +311,8 @@ export type ConvoyEventType =
305
311
  cost_usd?: number | null
306
312
  estimated?: boolean
307
313
  model?: string | null
314
+ /** Its work had merged before the run could record it done (see `markMergedDone`). */
315
+ recovered?: boolean
308
316
  }
309
317
  }
310
318
  | { type: 'task_failed'; data?: { reason: string; message?: string; worker_id?: string; gate?: string; hook?: string; exit_code?: number } }
package/src/cli/doctor.ts CHANGED
@@ -573,7 +573,7 @@ const DOCTOR_HELP = `
573
573
  npx opencastle doctor [options]
574
574
 
575
575
  Validate your OpenCastle setup — checks manifest, customizations, skills,
576
- logs, MCP configuration, and IDE-specific rules. MCP servers are audited too:
576
+ MCP configuration, and IDE-specific rules. MCP servers are audited too:
577
577
  a package run without an exact version, one OpenCastle knows is not on npm, a
578
578
  remote server Claude Code cannot load, a credential written into the file, or
579
579
  a server the team's policy does not allow.
@@ -33,7 +33,8 @@ const HELP = `
33
33
  set up — environment variables and sign-ins for the MCP servers.
34
34
 
35
35
  Options:
36
- --all List OpenCastle's own skills and agents too, not only the team's
36
+ --all List OpenCastle's own skills, agents, commands and workflows
37
+ too, not only the team's
37
38
  --json Machine-readable output
38
39
  --help, -h Show this help
39
40
  `
package/src/cli/remove.ts CHANGED
@@ -33,7 +33,7 @@ const REMOVE_HELP = `
33
33
  files (so they become standalone) or delete everything.
34
34
 
35
35
  Options:
36
- --keep-files Keep generated files; only drop the manifest
36
+ --keep-files Keep generated files; drop the manifest and the memory hooks
37
37
  --all Delete every generated file
38
38
  --dry-run Preview without changing anything
39
39
  --yes Skip the confirmation prompt
@@ -1,6 +1,9 @@
1
+ import { spawn } from 'node:child_process'
1
2
  import { mkdtempSync, writeFileSync, chmodSync, readFileSync, rmSync, realpathSync, existsSync } from 'node:fs'
3
+ import { createRequire } from 'node:module'
2
4
  import { tmpdir } from 'node:os'
3
5
  import { join } from 'node:path'
6
+ import { pathToFileURL } from 'node:url'
4
7
  import { describe, it, expect, afterEach } from 'vitest'
5
8
  import type { Task } from '../../convoy/spec-types.js'
6
9
  import { runAgent, stopTask, liveAgentCount, timeoutMsOf, promptOf } from './agent-process.js'
@@ -173,3 +176,59 @@ describe.skipIf(!posix)('running an agent CLI', () => {
173
176
  expect(await waitFor(() => !alive(childPid))).toBe(true)
174
177
  })
175
178
  })
179
+
180
+ describe.skipIf(!posix)('when a signal ends this process', () => {
181
+ // Each agent leads its own process group, so the terminal's Ctrl+C and its
182
+ // hangup never reach it. A signal's default action ends this process with no
183
+ // 'exit' event, so the exit hook never ran, and the agent kept editing its
184
+ // worktree and spending tokens with nobody watching. Planning, which handles
185
+ // no signal itself, left its agent running on every Ctrl+C.
186
+ const dirs: string[] = []
187
+ afterEach(() => {
188
+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true })
189
+ })
190
+
191
+ it.each(['SIGHUP', 'SIGINT', 'SIGTERM'] as const)('%s leaves no agent running, and still ends the process', async (sig) => {
192
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'oc-signal-')))
193
+ dirs.push(dir)
194
+ const agent = join(dir, 'fake-agent')
195
+ writeFileSync(agent, `#!/bin/sh\nsleep 60 &\necho $! > "${dir}/child"\necho $$ > "${dir}/agent"\nwait\n`)
196
+ chmodSync(agent, 0o755)
197
+ // A command that starts an agent and handles no signal itself.
198
+ const driver = join(dir, 'driver.mjs')
199
+ writeFileSync(driver, [
200
+ `const { runAgent } = await import(${JSON.stringify(pathToFileURL(join(import.meta.dirname, 'agent-process.ts')).href)})`,
201
+ `runAgent({ id: 't', prompt: 'p', agent: 'developer', timeout: '5m', depends_on: [], files: [], description: '', max_retries: 0 },`,
202
+ ` { command: ${JSON.stringify(agent)}, args: [], cwd: ${JSON.stringify(dir)} })`,
203
+ `setInterval(() => {}, 1000)`,
204
+ ].join('\n'))
205
+ const tsx = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href
206
+ const child = spawn(process.execPath, ['--import', tsx, driver], { cwd: dir, stdio: 'ignore' })
207
+ const ended = new Promise<NodeJS.Signals | null>((r) => child.on('exit', (_code, signal) => r(signal)))
208
+
209
+ expect(await waitFor(() => existsSync(join(dir, 'agent')) && existsSync(join(dir, 'child')), 15_000)).toBe(true)
210
+ const agentPid = Number(readFileSync(join(dir, 'agent'), 'utf8').trim())
211
+ const childPid = Number(readFileSync(join(dir, 'child'), 'utf8').trim())
212
+ child.kill(sig)
213
+
214
+ try {
215
+ expect(await ended).toBe(sig)
216
+ expect(await waitFor(() => !alive(agentPid) && !alive(childPid))).toBe(true)
217
+ } finally {
218
+ try { process.kill(-agentPid, 'SIGKILL') } catch { /* gone */ }
219
+ }
220
+ }, 30_000)
221
+
222
+ it('listens for those signals only while an agent runs', async () => {
223
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'oc-signal-')))
224
+ dirs.push(dir)
225
+ const agent = join(dir, 'fake-agent')
226
+ writeFileSync(agent, '#!/bin/sh\nsleep 0.3\n')
227
+ chmodSync(agent, 0o755)
228
+ const before = ['SIGHUP', 'SIGINT', 'SIGTERM'].map((s) => process.listenerCount(s))
229
+ const running = runAgent(task('guarded'), { command: agent, args: [], cwd: dir })
230
+ expect(['SIGHUP', 'SIGINT', 'SIGTERM'].map((s) => process.listenerCount(s))).toEqual(before.map((n) => n + 1))
231
+ await running
232
+ expect(['SIGHUP', 'SIGINT', 'SIGTERM'].map((s) => process.listenerCount(s))).toEqual(before)
233
+ })
234
+ })
@@ -57,20 +57,65 @@ const onStop = new WeakMap<ChildProcess, () => void>()
57
57
  const stoppedProcs = new WeakSet<ChildProcess>()
58
58
  let exitHookInstalled = false
59
59
 
60
+ /**
61
+ * The signals whose default action ends this process. Closing the terminal
62
+ * sends SIGHUP, Ctrl+C sends SIGINT, and `kill` sends SIGTERM.
63
+ */
64
+ const ENDING_SIGNALS = ['SIGHUP', 'SIGINT', 'SIGTERM'] as const
65
+ /** The listeners `guardSignals` added, while any agent runs. */
66
+ const signalGuards = new Map<NodeJS.Signals, () => void>()
67
+
68
+ /** SIGKILL every agent still running. There is no later to escalate in. */
69
+ function killAllNow(): void {
70
+ for (const s of live.values()) for (const c of s) killTree(c.pid, 0)
71
+ }
72
+
73
+ /**
74
+ * No agent outlives this process.
75
+ *
76
+ * On POSIX each agent leads its own process group, so it gets neither the
77
+ * terminal's Ctrl+C nor its hangup. Anything still running when this process
78
+ * goes would be orphaned, still editing a worktree and spending tokens with
79
+ * nobody watching.
80
+ *
81
+ * The 'exit' hook covers `process.exit` and an uncaught throw. A signal's
82
+ * default action ends the process with no 'exit' event, so while an agent
83
+ * runs, each ending signal has a listener too. A command that handles the
84
+ * signal itself (the convoy engine stops gracefully on all three) has a
85
+ * listener of its own, and this one stands aside for it. With no other
86
+ * listener, the agents are killed and the signal is raised again, so the
87
+ * process still ends the way the signal would have ended it.
88
+ */
89
+ function guardSignals(): void {
90
+ if (!exitHookInstalled) {
91
+ exitHookInstalled = true
92
+ process.once('exit', killAllNow)
93
+ }
94
+ // On Windows the agents share this process's console and close with it.
95
+ if (process.platform === 'win32' || signalGuards.size > 0) return
96
+ for (const sig of ENDING_SIGNALS) {
97
+ const onSignal = (): void => {
98
+ if (process.listenerCount(sig) > 1) return
99
+ killAllNow()
100
+ unguardSignals()
101
+ process.kill(process.pid, sig)
102
+ }
103
+ signalGuards.set(sig, onSignal)
104
+ process.on(sig, onSignal)
105
+ }
106
+ }
107
+
108
+ /** Once no agent runs, a signal does what it would have done anyway. */
109
+ function unguardSignals(): void {
110
+ for (const [sig, onSignal] of signalGuards) process.removeListener(sig, onSignal)
111
+ signalGuards.clear()
112
+ }
113
+
60
114
  function track(taskId: string, child: ChildProcess): void {
61
115
  let set = live.get(taskId)
62
116
  if (!set) live.set(taskId, (set = new Set()))
63
117
  set.add(child)
64
- if (!exitHookInstalled) {
65
- exitHookInstalled = true
66
- // On POSIX each agent leads its own process group, so it does not get the
67
- // terminal's Ctrl+C. Anything still running when this process exits would
68
- // be orphaned, still editing a worktree nobody is watching. There is no
69
- // later to escalate in, so it is SIGKILL now.
70
- process.once('exit', () => {
71
- for (const s of live.values()) for (const c of s) killTree(c.pid, 0)
72
- })
73
- }
118
+ guardSignals()
74
119
  }
75
120
 
76
121
  function untrack(taskId: string, child: ChildProcess): void {
@@ -78,6 +123,7 @@ function untrack(taskId: string, child: ChildProcess): void {
78
123
  if (!set) return
79
124
  set.delete(child)
80
125
  if (set.size === 0) live.delete(taskId)
126
+ if (live.size === 0) unguardSignals()
81
127
  }
82
128
 
83
129
  function stop(child: ChildProcess): void {