opencastle 1.12.7 → 1.12.9

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 (82) hide show
  1. package/dist/cli/convoy/crash-status.test.js +1 -1
  2. package/dist/cli/convoy/crash-status.test.js.map +1 -1
  3. package/dist/cli/convoy/engine.d.ts +3 -1
  4. package/dist/cli/convoy/engine.d.ts.map +1 -1
  5. package/dist/cli/convoy/engine.git.test.js +180 -3
  6. package/dist/cli/convoy/engine.git.test.js.map +1 -1
  7. package/dist/cli/convoy/engine.js +144 -16
  8. package/dist/cli/convoy/engine.js.map +1 -1
  9. package/dist/cli/convoy/engine.test.js +27 -1
  10. package/dist/cli/convoy/engine.test.js.map +1 -1
  11. package/dist/cli/convoy/event-schemas.d.ts.map +1 -1
  12. package/dist/cli/convoy/event-schemas.js +1 -0
  13. package/dist/cli/convoy/event-schemas.js.map +1 -1
  14. package/dist/cli/convoy/hangup.test.d.ts +2 -0
  15. package/dist/cli/convoy/hangup.test.d.ts.map +1 -0
  16. package/dist/cli/convoy/hangup.test.js +124 -0
  17. package/dist/cli/convoy/hangup.test.js.map +1 -0
  18. package/dist/cli/convoy/ledger-paths.test.js +1 -1
  19. package/dist/cli/convoy/ledger-paths.test.js.map +1 -1
  20. package/dist/cli/convoy/lock.d.ts.map +1 -1
  21. package/dist/cli/convoy/lock.js +28 -13
  22. package/dist/cli/convoy/lock.js.map +1 -1
  23. package/dist/cli/convoy/lock.test.js +44 -2
  24. package/dist/cli/convoy/lock.test.js.map +1 -1
  25. package/dist/cli/convoy/merge.d.ts +2 -0
  26. package/dist/cli/convoy/merge.d.ts.map +1 -1
  27. package/dist/cli/convoy/merge.js +4 -2
  28. package/dist/cli/convoy/merge.js.map +1 -1
  29. package/dist/cli/convoy/merge.test.js +14 -4
  30. package/dist/cli/convoy/merge.test.js.map +1 -1
  31. package/dist/cli/convoy/partition.d.ts +12 -6
  32. package/dist/cli/convoy/partition.d.ts.map +1 -1
  33. package/dist/cli/convoy/partition.js +76 -48
  34. package/dist/cli/convoy/partition.js.map +1 -1
  35. package/dist/cli/convoy/partition.symlinks.test.d.ts +2 -0
  36. package/dist/cli/convoy/partition.symlinks.test.d.ts.map +1 -0
  37. package/dist/cli/convoy/partition.symlinks.test.js +71 -0
  38. package/dist/cli/convoy/partition.symlinks.test.js.map +1 -0
  39. package/dist/cli/convoy/partition.test.js +2 -1
  40. package/dist/cli/convoy/partition.test.js.map +1 -1
  41. package/dist/cli/convoy/store.d.ts +1 -1
  42. package/dist/cli/convoy/store.d.ts.map +1 -1
  43. package/dist/cli/convoy/store.js +13 -2
  44. package/dist/cli/convoy/store.js.map +1 -1
  45. package/dist/cli/convoy/store.test.js +11 -11
  46. package/dist/cli/convoy/types.d.ts +9 -1
  47. package/dist/cli/convoy/types.d.ts.map +1 -1
  48. package/dist/cli/convoy/types.js.map +1 -1
  49. package/dist/cli/convoy/worktree.d.ts +2 -0
  50. package/dist/cli/convoy/worktree.d.ts.map +1 -1
  51. package/dist/cli/convoy/worktree.js +15 -3
  52. package/dist/cli/convoy/worktree.js.map +1 -1
  53. package/dist/cli/convoy/worktree.test.js +22 -1
  54. package/dist/cli/convoy/worktree.test.js.map +1 -1
  55. package/dist/cli/run/adapters/agent-process.d.ts.map +1 -1
  56. package/dist/cli/run/adapters/agent-process.js +58 -12
  57. package/dist/cli/run/adapters/agent-process.js.map +1 -1
  58. package/dist/cli/run/adapters/agent-process.test.js +59 -0
  59. package/dist/cli/run/adapters/agent-process.test.js.map +1 -1
  60. package/package.json +1 -1
  61. package/src/cli/convoy/TELEMETRY.md +3 -3
  62. package/src/cli/convoy/crash-status.test.ts +1 -1
  63. package/src/cli/convoy/engine.git.test.ts +197 -3
  64. package/src/cli/convoy/engine.test.ts +29 -1
  65. package/src/cli/convoy/engine.ts +146 -19
  66. package/src/cli/convoy/event-schemas.ts +1 -0
  67. package/src/cli/convoy/hangup.test.ts +126 -0
  68. package/src/cli/convoy/ledger-paths.test.ts +1 -1
  69. package/src/cli/convoy/lock.test.ts +63 -2
  70. package/src/cli/convoy/lock.ts +29 -13
  71. package/src/cli/convoy/merge.test.ts +17 -4
  72. package/src/cli/convoy/merge.ts +6 -2
  73. package/src/cli/convoy/partition.symlinks.test.ts +82 -0
  74. package/src/cli/convoy/partition.test.ts +2 -1
  75. package/src/cli/convoy/partition.ts +68 -55
  76. package/src/cli/convoy/store.test.ts +11 -11
  77. package/src/cli/convoy/store.ts +14 -3
  78. package/src/cli/convoy/types.ts +9 -1
  79. package/src/cli/convoy/worktree.test.ts +24 -1
  80. package/src/cli/convoy/worktree.ts +17 -3
  81. package/src/cli/run/adapters/agent-process.test.ts +59 -0
  82. package/src/cli/run/adapters/agent-process.ts +56 -10
@@ -21,7 +21,7 @@ import {
21
21
  BranchInUseError,
22
22
  type WorktreeManager,
23
23
  } from './worktree.js'
24
- import { createMergeQueue, MergeConflictError, type MergeQueue } from './merge.js'
24
+ import { createMergeQueue, MergeConflictError, type MergeQueue, type MergeResult } from './merge.js'
25
25
  import { collectFindings, recordLessons, LESSON_PATHS, type ReportedIssue, type ReportedLesson } from './findings.js'
26
26
  import type {
27
27
  TaskRecord, ConvoyStatus, ConvoyTaskStatus, GuardConfig, CircuitBreakerConfig, TaskStep, Hook,
@@ -87,7 +87,7 @@ export interface ConvoyEngineOptions {
87
87
  repoRoot?: string
88
88
  /** Aborting it stops the run the way Ctrl+C does. */
89
89
  signal?: AbortSignal
90
- /** Stop the run on SIGINT/SIGTERM (default true). */
90
+ /** Stop the run on SIGINT, SIGTERM or SIGHUP (default true). */
91
91
  handleSignals?: boolean
92
92
  /** Where progress is printed (default stdout). */
93
93
  output?: ProgressStream
@@ -104,6 +104,8 @@ export interface ConvoyEngineOptions {
104
104
  _convoyWorktreeDir?: string | null
105
105
  /** Replaces the default reviewer (tests). */
106
106
  _reviewRunner?: ReviewRunner
107
+ /** How long an interrupted run waits for its tasks to wind down (tests; default 10 s). */
108
+ _interruptGraceMs?: number
107
109
  }
108
110
 
109
111
  export interface ConvoyResult {
@@ -548,7 +550,7 @@ function usageOf(result: ExecuteResult, promptText: string, fallbackModel: strin
548
550
  interface RunControl {
549
551
  /** No new task starts: a task failed under `on_failure: stop`, or a stop rule fired. */
550
552
  stopDispatch: boolean
551
- /** Set by SIGINT/SIGTERM or the abort signal. */
553
+ /** Set by SIGINT, SIGTERM, SIGHUP or the abort signal. */
552
554
  interrupted: string | null
553
555
  /** Resolves when the run is interrupted, so waits can be cut short. */
554
556
  interruptedPromise: Promise<void>
@@ -608,6 +610,7 @@ interface RunContext {
608
610
  reviewRunner: ReviewRunner
609
611
  progress: Progress
610
612
  ctl: RunControl
613
+ interruptGraceMs: number
611
614
  }
612
615
 
613
616
  // ── Core convoy execution ─────────────────────────────────────────────────────
@@ -1266,7 +1269,9 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1266
1269
 
1267
1270
  if (files.length > 0) {
1268
1271
  try {
1269
- scanSymlinks(files, wt)
1272
+ // The links git tracks inside a declared directory, too: one there
1273
+ // sends the agent's writes wherever it points.
1274
+ scanSymlinks(files, wt, wtManager.symlinks ? await wtManager.symlinks(wt, files.map(normalizePath)) : [])
1270
1275
  } catch (err) {
1271
1276
  return fail('failed', `Symlink security check failed: ${(err as Error).message}`, { kind: 'symlink-escape' })
1272
1277
  }
@@ -1584,9 +1589,12 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1584
1589
  return fail('hook-failed', `post_task hook "${label}" failed: ${post.error ?? ''}`, { kind: 'hook-failed', hook: label })
1585
1590
  }
1586
1591
  }
1587
- if (files.length > 0) {
1592
+ // Every path the commit changed, not only the declared ones: a link added
1593
+ // inside a declared directory, or outside the task's paths (a partition
1594
+ // violation only warns), merges all the same.
1595
+ if (files.length > 0 || changedFiles.length > 0) {
1588
1596
  try {
1589
- scanNewSymlinks(wt, files)
1597
+ scanNewSymlinks(wt, files, changedFiles)
1590
1598
  } catch (err) {
1591
1599
  return fail('failed', `Post-execution symlink security check failed: ${(err as Error).message}`, { kind: 'symlink-escape-post' })
1592
1600
  }
@@ -1613,9 +1621,11 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1613
1621
  // ── Merge ───────────────────────────────────────────────────────────────
1614
1622
  const workerBranch = workerBranchName(workerId)
1615
1623
  const nothingToMerge = changes !== null && changedFiles.length === 0
1624
+ const finalOutput = redactSecrets(result.output).text
1616
1625
  if (!nothingToMerge) {
1626
+ let merged: MergeResult
1617
1627
  try {
1618
- await mergeQueue.merge(wt, workerBranch, branch)
1628
+ merged = await mergeQueue.merge(wt, workerBranch, branch)
1619
1629
  } catch (err) {
1620
1630
  const fresh = store.getTask(rec.id, convoyId) ?? rec
1621
1631
  if (err instanceof MergeConflictError) {
@@ -1653,6 +1663,18 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1653
1663
  failureType: 'merge-failed',
1654
1664
  })
1655
1665
  }
1666
+ // The work is on the convoy branch: from here the task is done, however
1667
+ // its run ends. Recorded before anything else is awaited, because what
1668
+ // follows takes time (removing a worktree that holds node_modules) and
1669
+ // can throw (saving artifacts). A run killed, interrupted or crashed in
1670
+ // that window used to leave the task running, and resume ran work
1671
+ // already merged a second time.
1672
+ store.updateTaskStatus(rec.id, convoyId, 'running', {
1673
+ merged_commit: merged.commit,
1674
+ output: finalOutput,
1675
+ exit_code: result.exitCode,
1676
+ contract_result: JSON.stringify(contractResult),
1677
+ })
1656
1678
  events.emit('task_merged', { branch, files: changedFiles.length }, { convoy_id: convoyId, task_id: rec.id })
1657
1679
  }
1658
1680
  await cleanup()
@@ -1744,7 +1766,7 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1744
1766
  store.withTransaction(() => {
1745
1767
  store.updateTaskStatus(rec.id, convoyId, 'done', {
1746
1768
  finished_at: now(),
1747
- output: redactSecrets(result.output).text,
1769
+ output: finalOutput,
1748
1770
  exit_code: result.exitCode,
1749
1771
  contract_result: JSON.stringify(contractResult),
1750
1772
  branch: null,
@@ -1855,7 +1877,7 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1855
1877
 
1856
1878
  let graceTimer: ReturnType<typeof setTimeout> | undefined
1857
1879
  const graceExpired = ctl.interruptedPromise.then(
1858
- () => new Promise<'grace'>(res => { graceTimer = setTimeout(() => res('grace'), INTERRUPT_GRACE_MS) }),
1880
+ () => new Promise<'grace'>(res => { graceTimer = setTimeout(() => res('grace'), ctx.interruptGraceMs) }),
1859
1881
  )
1860
1882
 
1861
1883
  try {
@@ -1871,7 +1893,11 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1871
1893
  const msg = (err as Error)?.message ?? String(err)
1872
1894
  try {
1873
1895
  const row = store.getTask(t.id, convoyId)
1874
- if (row && (row.status === 'running' || row.status === 'assigned' || row.status === 'pending')) {
1896
+ if (row?.merged_commit && row.status !== 'done') {
1897
+ // It threw after its work merged: the work stands.
1898
+ markMergedDone(store, events, convoyId, row)
1899
+ progress.line(` ${c.green('✓')} ${c.bold(`[${t.id}]`)} merged ${c.dim(`(an engine error after the merge: ${firstLine(msg)})`)}`)
1900
+ } else if (row && (row.status === 'running' || row.status === 'assigned' || row.status === 'pending')) {
1875
1901
  store.updateTaskStatus(t.id, convoyId, ctl.interrupted ? 'pending' : 'failed', {
1876
1902
  finished_at: ctl.interrupted ? null : new Date().toISOString(),
1877
1903
  output: redactSecrets(`Engine error: ${msg}`).text,
@@ -1972,18 +1998,36 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1972
1998
  if (ctl.interrupted || failedGates.length === 0 || gateAttempt >= maxGateRetries) break
1973
1999
 
1974
2000
  gateAttempt++
2001
+ // A gate's output is whatever the command printed, and a failing test that
2002
+ // dumps its environment or a connection string prints a credential. It is
2003
+ // masked before it is cut to length, so no token is cut in half where the
2004
+ // scanner can no longer see it, and the prompt is then scanned the way
2005
+ // every task's is.
1975
2006
  const failureSummary = failedGates
1976
- .map(g => `Command: ${g.command}\nExit code: ${g.exitCode}\nOutput:\n${(g.output ?? '(no output)').slice(-4000)}`)
2007
+ .map(g => `Command: ${g.command}\nExit code: ${g.exitCode}\nOutput:\n${redactSecrets(g.output ?? '(no output)').text.slice(-4000)}`)
1977
2008
  .join('\n\n---\n\n')
1978
2009
  const touchedFiles = store.getTasksByConvoy(convoyId).flatMap(t => parseJsonList(t.files))
1979
2010
  const filesContext = touchedFiles.length > 0
1980
2011
  ? `\n\nFiles changed by the convoy's tasks:\n${touchedFiles.map(f => `- ${f}`).join('\n')}\n`
1981
2012
  : ''
1982
2013
  const fixTaskId = `gate-fix-${gateAttempt}`
2014
+ const fixPrompt = `${sharedContext}\n\n---\n\n## Your task: ${fixTaskId}\nThese checks failed after every task was merged. Fix the code so they pass.${filesContext}\n\n${failureSummary}\n`
2015
+ const fixScan = scanForSecrets(fixPrompt, `task:${fixTaskId}`)
2016
+ if (!fixScan.clean) {
2017
+ const patterns = fixScan.findings.map(f => f.pattern)
2018
+ events.emit('secret_leak_prevented', {
2019
+ task_id: fixTaskId,
2020
+ findings_count: fixScan.findings.length,
2021
+ patterns,
2022
+ context: 'prompt',
2023
+ }, { convoy_id: convoyId, task_id: fixTaskId })
2024
+ progress.line(`\n ${c.red('✗')} ${c.bold(`[${fixTaskId}]`)} not started: secret detected in its prompt (${[...new Set(patterns)].join(', ')})`)
2025
+ break
2026
+ }
1983
2027
  progress.line(`\n ${c.yellow('⟳')} ${c.bold(`[${fixTaskId}]`)} fixing the failed gates (attempt ${gateAttempt}/${maxGateRetries})`)
1984
2028
  const fixTask: Task = {
1985
2029
  id: fixTaskId,
1986
- prompt: `${sharedContext}\n\n---\n\n## Your task: ${fixTaskId}\nThese checks failed after every task was merged. Fix the code so they pass.${filesContext}\n\n${failureSummary}\n`,
2030
+ prompt: fixPrompt,
1987
2031
  agent: spec.defaults?.agent ?? 'developer',
1988
2032
  timeout: spec.defaults?.timeout ?? '30m',
1989
2033
  depends_on: [],
@@ -2118,7 +2162,10 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
2118
2162
  function finishInterrupted(): ConvoyResult {
2119
2163
  const requeued: string[] = []
2120
2164
  for (const t of store.getTasksByConvoy(convoyId)) {
2121
- if (t.status === 'running' || t.status === 'assigned') {
2165
+ if ((t.status === 'running' || t.status === 'assigned') && t.merged_commit) {
2166
+ // Still winding down after its merge when the grace period ran out.
2167
+ markMergedDone(store, events, convoyId, t)
2168
+ } else if (t.status === 'running' || t.status === 'assigned') {
2122
2169
  store.updateTaskStatus(t.id, convoyId, 'pending', { worker_id: null, worktree: null, started_at: null })
2123
2170
  if (t.worker_id) {
2124
2171
  try { store.updateWorkerStatus(t.worker_id, 'killed', { finished_at: new Date().toISOString() }) } catch { /* gone */ }
@@ -2290,11 +2337,21 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2290
2337
 
2291
2338
  const validatePlan = (): Promise<void> => checkConvoyPlan(spec, adapter.name)
2292
2339
 
2293
- /** Stop on SIGINT/SIGTERM or the abort signal; a second Ctrl+C stops at once. */
2340
+ /**
2341
+ * Stop on SIGINT, SIGTERM, SIGHUP or the abort signal; a second Ctrl+C stops
2342
+ * at once.
2343
+ *
2344
+ * SIGHUP is a closed terminal or a dropped SSH session. Unhandled, it ended
2345
+ * this process on the spot and left every agent running: each leads its own
2346
+ * process group, so the hangup never reached them.
2347
+ */
2294
2348
  function installInterrupts(ctl: RunControl, progress: Progress): () => void {
2295
2349
  const disposers: Array<() => void> = []
2296
2350
  const onSignal = (sig: NodeJS.Signals): void => {
2297
2351
  if (ctl.interrupted) {
2352
+ // When a terminal closes, the kernel and the shell can each send a
2353
+ // hangup. A second one is no request to hurry.
2354
+ if (sig === 'SIGHUP') return
2298
2355
  // A second Ctrl+C means "now". Agents get SIGKILL through their
2299
2356
  // adapters; the exit is unavoidable, because the person has said they
2300
2357
  // will not wait for the cleanup the first signal started. The rows
@@ -2304,15 +2361,22 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2304
2361
  }
2305
2362
  process.exit(130)
2306
2363
  }
2307
- progress.line(`\n ${c.yellow('■')} ${sig} — stopping: killing running agents, no new tasks. Press Ctrl+C again to quit at once.`)
2364
+ if (sig === 'SIGHUP') {
2365
+ // Writing to a terminal that has gone fails with EIO. Unhandled, that
2366
+ // error would end the process before the run is recorded as
2367
+ // interrupted. Nobody can read the terminal now anyway.
2368
+ for (const stream of [process.stdout, process.stderr]) stream.on('error', () => {})
2369
+ progress.line(`\n ${c.yellow('■')} SIGHUP (the terminal closed) — stopping: killing running agents, no new tasks.`)
2370
+ } else {
2371
+ progress.line(`\n ${c.yellow('■')} ${sig} — stopping: killing running agents, no new tasks. Press Ctrl+C again to quit at once.`)
2372
+ }
2308
2373
  ctl.interrupt(sig)
2309
2374
  }
2310
2375
  if (options.handleSignals !== false) {
2311
- process.on('SIGINT', onSignal)
2312
- process.on('SIGTERM', onSignal)
2376
+ const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP']
2377
+ for (const sig of signals) process.on(sig, onSignal)
2313
2378
  disposers.push(() => {
2314
- process.removeListener('SIGINT', onSignal)
2315
- process.removeListener('SIGTERM', onSignal)
2379
+ for (const sig of signals) process.removeListener(sig, onSignal)
2316
2380
  })
2317
2381
  }
2318
2382
  if (options.signal) {
@@ -2448,6 +2512,7 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2448
2512
  convoyId, spec, adapter, store, events, wtManager, mergeQueue, repoRoot,
2449
2513
  workRoot: checkout.path, branch, baseRef, verbose, startTime, ndjsonPath,
2450
2514
  reviewRunner: options._reviewRunner ?? defaultReviewer, progress, ctl,
2515
+ interruptGraceMs: options._interruptGraceMs ?? INTERRUPT_GRACE_MS,
2451
2516
  })
2452
2517
  progress.stop()
2453
2518
  printSummary(progress, result, store, repoRoot)
@@ -2516,6 +2581,7 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2516
2581
  const wtManager = options._worktreeManager ?? createWorktreeManager(repoRoot)
2517
2582
  const mergeQueue = options._mergeQueue ?? createMergeQueue(checkout.path, { worktreesDir: worktreesDirFor(repoRoot) })
2518
2583
 
2584
+ await settleMergedTasks(store, events, convoyId, branch, repoRoot, progress)
2519
2585
  const reset = resetForResume(store, events, convoyId)
2520
2586
 
2521
2587
  // Worktrees left by a run that died — not the integration checkout.
@@ -2532,6 +2598,7 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2532
2598
  convoyId, spec, adapter, store, events, wtManager, mergeQueue, repoRoot,
2533
2599
  workRoot: checkout.path, branch, baseRef, verbose, startTime, ndjsonPath,
2534
2600
  reviewRunner: options._reviewRunner ?? defaultReviewer, progress, ctl,
2601
+ interruptGraceMs: options._interruptGraceMs ?? INTERRUPT_GRACE_MS,
2535
2602
  })
2536
2603
  progress.stop()
2537
2604
  printSummary(progress, result, store, repoRoot)
@@ -2558,6 +2625,8 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2558
2625
  : ndjsonPathForConvoy(convoyId, repoRoot)
2559
2626
  const events = createEventEmitter(store, { ndjsonPath })
2560
2627
  try {
2628
+ const branch = store.getConvoy(convoyId)?.branch
2629
+ if (branch) await settleMergedTasks(store, events, convoyId, branch, repoRoot)
2561
2630
  resetForResume(store, events, convoyId, taskIds)
2562
2631
  store.updateConvoyStatus(convoyId, 'running', {})
2563
2632
  } finally {
@@ -2709,6 +2778,62 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2709
2778
  return { run, resume, retryFailed, injectTask }
2710
2779
  }
2711
2780
 
2781
+ /**
2782
+ * Record as done a task whose work merged before its run could say so.
2783
+ *
2784
+ * Its output, exit code and contract were saved with the merge, so the row
2785
+ * reads as if the run had finished. A branch kept from an earlier failed
2786
+ * attempt stays listed: it still exists.
2787
+ */
2788
+ function markMergedDone(store: ConvoyStore, events: ConvoyEventEmitter, convoyId: string, task: TaskRecord): void {
2789
+ const finishedAt = new Date().toISOString()
2790
+ store.withTransaction(() => {
2791
+ store.updateTaskStatus(task.id, convoyId, 'done', { finished_at: finishedAt, retry_note: null })
2792
+ if (task.worker_id) {
2793
+ try { store.updateWorkerStatus(task.worker_id, 'done', { finished_at: finishedAt }) } catch { /* worker record may be absent */ }
2794
+ }
2795
+ })
2796
+ events.emit('task_done', {
2797
+ exit_code: task.exit_code ?? 0,
2798
+ ...(task.worker_id ? { worker_id: task.worker_id } : {}),
2799
+ tokens: task.total_tokens,
2800
+ cost_usd: task.cost_usd,
2801
+ estimated: Boolean(task.cost_estimated),
2802
+ model: task.model,
2803
+ recovered: true,
2804
+ }, { convoy_id: convoyId, task_id: task.id, ...(task.worker_id ? { worker_id: task.worker_id } : {}) })
2805
+ }
2806
+
2807
+ /**
2808
+ * Before a resume: every unfinished task whose recorded merge is on the convoy
2809
+ * branch is done.
2810
+ *
2811
+ * A run that died between a task's merge and its "done" left it running.
2812
+ * Resume then put it back to pending, nothing said the work had merged, and
2813
+ * the task ran again: the no-op gate failed it ("Produced no changes") or the
2814
+ * agent applied the change a second time. A commit the branch no longer has
2815
+ * (the branch was reset) is not counted, and the task runs again.
2816
+ */
2817
+ async function settleMergedTasks(
2818
+ store: ConvoyStore,
2819
+ events: ConvoyEventEmitter,
2820
+ convoyId: string,
2821
+ branch: string,
2822
+ repoRoot: string,
2823
+ progress?: Progress,
2824
+ ): Promise<void> {
2825
+ for (const task of store.getTasksByConvoy(convoyId)) {
2826
+ if (task.status === 'done' || !task.merged_commit) continue
2827
+ try {
2828
+ await git(['merge-base', '--is-ancestor', task.merged_commit, `refs/heads/${branch}`], repoRoot)
2829
+ } catch {
2830
+ continue // not on the branch, or not a commit this repository has
2831
+ }
2832
+ markMergedDone(store, events, convoyId, task)
2833
+ progress?.line(` ${c.green('✓')} ${c.bold(`[${task.id}]`)} ${c.dim('merged before the run stopped — done')}`)
2834
+ }
2835
+ }
2836
+
2712
2837
  /**
2713
2838
  * Put every unfinished task back to pending. Returns the ids it reset.
2714
2839
  *
@@ -2752,6 +2877,8 @@ function resetForResume(
2752
2877
  worktree: null,
2753
2878
  started_at: null,
2754
2879
  finished_at: null,
2880
+ // A commit `settleMergedTasks` did not find on the branch: the work runs again.
2881
+ merged_commit: null,
2755
2882
  ...(FAILED_STATUSES.has(task.status) ? { retries: 0 } : {}),
2756
2883
  ...(task.status === 'skipped' ? { retry_note: null } : {}),
2757
2884
  })
@@ -40,6 +40,7 @@ const EVENT_DATA_SCHEMAS: Record<string, AnySchema> = {
40
40
  cost_usd: optNum,
41
41
  estimated: v.optional(v.boolean()),
42
42
  model: optStr,
43
+ recovered: v.optional(v.boolean()),
43
44
  }),
44
45
  task_failed: v.looseObject({
45
46
  reason: v.string(),
@@ -0,0 +1,126 @@
1
+ /**
2
+ * `convoy run` when its terminal closes or its SSH session drops: SIGHUP.
3
+ *
4
+ * The engine stopped on SIGINT and SIGTERM only. SIGHUP's default action ended
5
+ * it on the spot, and every agent kept running: each leads its own process
6
+ * group, so the hangup never reached them. The next `convoy resume` then
7
+ * deleted the worktrees those agents were still writing to.
8
+ *
9
+ * This drives the real command in a child process, with a stand-in `claude`
10
+ * on PATH that runs until it is killed.
11
+ */
12
+ import { spawn, execFileSync } from 'node:child_process'
13
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
14
+ import { createRequire } from 'node:module'
15
+ import { tmpdir } from 'node:os'
16
+ import { join } from 'node:path'
17
+ import { pathToFileURL } from 'node:url'
18
+ import { DatabaseSync } from 'node:sqlite'
19
+ import { afterEach, describe, expect, it } from 'vitest'
20
+
21
+ const posix = process.platform !== 'win32'
22
+
23
+ function alive(pid: number): boolean {
24
+ try {
25
+ process.kill(pid, 0)
26
+ return true
27
+ } catch {
28
+ return false
29
+ }
30
+ }
31
+
32
+ async function waitFor(check: () => boolean, ms: number): Promise<boolean> {
33
+ const until = Date.now() + ms
34
+ while (Date.now() < until) {
35
+ if (check()) return true
36
+ await new Promise((r) => setTimeout(r, 50))
37
+ }
38
+ return check()
39
+ }
40
+
41
+ const STUB_CLAUDE = `#!/bin/sh
42
+ if [ "$1" = "--help" ] || [ "$1" = "--version" ]; then echo "claude 2.0.0"; exit 0; fi
43
+ cat > /dev/null
44
+ sleep 60 &
45
+ echo $! > "$STUB_LOG/child.pid"
46
+ echo $$ > "$STUB_LOG/agent.pid"
47
+ wait
48
+ `
49
+
50
+ const SPEC = `name: hangup
51
+ adapter: claude
52
+ on_failure: continue
53
+ defaults:
54
+ review: none
55
+ tasks:
56
+ - id: a
57
+ prompt: Write a.txt
58
+ agent: developer
59
+ files: [a.txt]
60
+ timeout: 5m
61
+ max_retries: 0
62
+ `
63
+
64
+ describe.skipIf(!posix)('convoy run when the terminal closes', () => {
65
+ let root: string
66
+ afterEach(() => {
67
+ rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })
68
+ })
69
+
70
+ it('stops every agent, records the run as interrupted and lets go of the lock', async () => {
71
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'oc-hangup-')))
72
+ const bin = join(root, 'bin')
73
+ const log = join(root, 'log')
74
+ const repo = join(root, 'repo')
75
+ for (const d of [bin, log, repo]) mkdirSync(d)
76
+ writeFileSync(join(bin, 'claude'), STUB_CLAUDE)
77
+ chmodSync(join(bin, 'claude'), 0o755)
78
+ const git = (...args: string[]): string => execFileSync('git', args, { cwd: repo, encoding: 'utf8' })
79
+ git('init', '-q', '-b', 'main')
80
+ git('config', 'user.email', 't@t')
81
+ git('config', 'user.name', 't')
82
+ writeFileSync(join(repo, 'README.md'), '# p\n')
83
+ writeFileSync(join(repo, '.gitignore'), '.opencastle/\n')
84
+ git('add', '-A')
85
+ git('commit', '-qm', 'init')
86
+ writeFileSync(join(repo, 'spec.yml'), SPEC)
87
+
88
+ const runModule = pathToFileURL(join(import.meta.dirname, '..', 'run.ts')).href
89
+ const driver = join(root, 'driver.mjs')
90
+ writeFileSync(driver, [
91
+ `const { default: run } = await import(${JSON.stringify(runModule)})`,
92
+ `await run({ args: ['spec.yml', '--adapter', 'claude'], pkgRoot: ${JSON.stringify(join(import.meta.dirname, '..', '..', '..'))} })`,
93
+ ].join('\n'))
94
+ const tsx = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href
95
+ const child = spawn(process.execPath, ['--import', tsx, driver], {
96
+ cwd: repo,
97
+ // The stand-in comes first, so no real agent CLI can be reached.
98
+ env: { ...process.env, PATH: `${bin}:/usr/bin:/bin`, STUB_LOG: log },
99
+ stdio: 'ignore',
100
+ })
101
+ const exited = new Promise<number | null>((r) => child.on('exit', (code) => r(code)))
102
+
103
+ const started = await waitFor(() => existsSync(join(log, 'agent.pid')) && existsSync(join(log, 'child.pid')), 20_000)
104
+ expect(started).toBe(true)
105
+ const agentPid = Number(readFileSync(join(log, 'agent.pid'), 'utf8').trim())
106
+ const childPid = Number(readFileSync(join(log, 'child.pid'), 'utf8').trim())
107
+
108
+ try {
109
+ child.kill('SIGHUP')
110
+ expect(await exited).toBe(130)
111
+ expect(await waitFor(() => !alive(agentPid) && !alive(childPid), 3_000)).toBe(true)
112
+
113
+ const db = new DatabaseSync(join(repo, '.opencastle', 'convoy.db'), { readOnly: true })
114
+ try {
115
+ expect((db.prepare('SELECT status FROM convoy').get() as { status: string }).status).toBe('interrupted')
116
+ expect((db.prepare("SELECT status FROM task WHERE id = 'a'").get() as { status: string }).status).toBe('pending')
117
+ expect(db.prepare('SELECT * FROM engine_lock').all()).toEqual([])
118
+ } finally {
119
+ db.close()
120
+ }
121
+ } finally {
122
+ try { process.kill(-agentPid, 'SIGKILL') } catch { /* gone */ }
123
+ child.kill('SIGKILL')
124
+ }
125
+ }, 60_000)
126
+ })
@@ -49,7 +49,7 @@ function makeWorktreeManager(): WorktreeManager {
49
49
 
50
50
  function makeMergeQueue(): MergeQueue {
51
51
  return {
52
- merge: vi.fn().mockResolvedValue({ success: true, conflicted: false, message: 'ok' }),
52
+ merge: vi.fn().mockResolvedValue({ success: true, conflicted: false, message: 'ok', commit: 'c0ffee' }),
53
53
  } as unknown as MergeQueue
54
54
  }
55
55
 
@@ -78,14 +78,75 @@ describe('engine lock', () => {
78
78
  })
79
79
 
80
80
  it('throws EngineAlreadyRunningError when lock is held by a live process', () => {
81
+ // The parent: a live process on this host that is not this one.
81
82
  const now = new Date().toISOString()
82
83
  db.prepare(
83
84
  'INSERT INTO engine_lock (id, pid, hostname, started_at, last_heartbeat) VALUES (1, ?, ?, ?, ?)',
84
- ).run(process.pid, hostname(), now, now)
85
+ ).run(process.ppid, hostname(), now, now)
85
86
 
86
87
  expect(() => acquireEngineLock(db, dbPath)).toThrow(EngineAlreadyRunningError)
87
88
  })
88
89
 
90
+ it('says when a refused lock frees itself, so nobody deletes the row by hand', () => {
91
+ const now = new Date().toISOString()
92
+ db.prepare(
93
+ 'INSERT INTO engine_lock (id, pid, hostname, started_at, last_heartbeat) VALUES (1, ?, ?, ?, ?)',
94
+ ).run(process.ppid, hostname(), now, now)
95
+
96
+ expect(() => acquireEngineLock(db, dbPath)).toThrow(/frees itself 30 s after that process's last heartbeat/)
97
+ })
98
+
99
+ describe('a pid that is alive on this host, which containers reuse', () => {
100
+ const hourAgo = (): string => new Date(Date.now() - 3_600_000).toISOString()
101
+
102
+ it('takes over when the heartbeat is older than 30 s: the pid now belongs to another process', () => {
103
+ const old = new Date(Date.now() - 31_000).toISOString()
104
+ db.prepare(
105
+ 'INSERT INTO engine_lock (id, pid, hostname, started_at, last_heartbeat) VALUES (1, ?, ?, ?, ?)',
106
+ ).run(process.ppid, hostname(), hourAgo(), old)
107
+
108
+ const lock = acquireEngineLock(db, dbPath)
109
+ const row = db.prepare('SELECT pid FROM engine_lock WHERE id = 1').get() as { pid: number }
110
+ expect(row.pid).toBe(process.pid)
111
+ lock.release()
112
+ })
113
+
114
+ it('takes over a row with this process\'s own pid that an earlier process wrote', () => {
115
+ // A container restarted and gave this process the pid its last run had.
116
+ // The refusal was "Another opencastle process … is already running".
117
+ db.prepare(
118
+ 'INSERT INTO engine_lock (id, pid, hostname, started_at, last_heartbeat) VALUES (1, ?, ?, ?, ?)',
119
+ ).run(process.pid, hostname(), hourAgo(), hourAgo())
120
+
121
+ const lock = acquireEngineLock(db, dbPath)
122
+ const row = db.prepare('SELECT pid, started_at FROM engine_lock WHERE id = 1').get() as { pid: number; started_at: string }
123
+ expect(row.pid).toBe(process.pid)
124
+ expect(Date.now() - Date.parse(row.started_at)).toBeLessThan(60_000)
125
+ lock.release()
126
+ })
127
+
128
+ it('takes over an earlier process\'s row with this pid at once, however fresh its heartbeat', () => {
129
+ // The restart came within 30 s of the last heartbeat.
130
+ const now = new Date().toISOString()
131
+ db.prepare(
132
+ 'INSERT INTO engine_lock (id, pid, hostname, started_at, last_heartbeat) VALUES (1, ?, ?, ?, ?)',
133
+ ).run(process.pid, hostname(), hourAgo(), now)
134
+
135
+ const lock = acquireEngineLock(db, dbPath)
136
+ lock.release()
137
+ })
138
+
139
+ it('refuses a second lock while this process holds the first, and takes over once its heartbeat is 30 s old', () => {
140
+ const first = acquireEngineLock(db, dbPath)
141
+ expect(() => acquireEngineLock(db, dbPath)).toThrow(EngineAlreadyRunningError)
142
+
143
+ db.prepare('UPDATE engine_lock SET last_heartbeat = ? WHERE id = 1').run(new Date(Date.now() - 31_000).toISOString())
144
+ const second = acquireEngineLock(db, dbPath)
145
+ second.release()
146
+ first.release()
147
+ })
148
+ })
149
+
89
150
  it('takes over when hostname differs (treated as stale regardless of PID)', () => {
90
151
  const staleTime = new Date(Date.now() - 60_000).toISOString()
91
152
  db.prepare(
@@ -181,7 +242,7 @@ describe('engine lock', () => {
181
242
  const now = new Date().toISOString()
182
243
  db.prepare(
183
244
  'INSERT INTO engine_lock (id, pid, hostname, started_at, last_heartbeat) VALUES (1, ?, ?, ?, ?)',
184
- ).run(process.pid, hostname(), now, now)
245
+ ).run(process.ppid, hostname(), now, now)
185
246
  expect(isLockStale(db)).toBe(false)
186
247
  })
187
248
 
@@ -1,16 +1,20 @@
1
1
  import { hostname as getHostname } from 'node:os'
2
2
  import { DatabaseSync } from 'node:sqlite'
3
3
 
4
+ /** A holder that has not written its heartbeat (every 10 s) for this long is gone. */
5
+ const HEARTBEAT_STALE_MS = 30_000
6
+
4
7
  export class EngineAlreadyRunningError extends Error {
5
8
  constructor(public readonly pid: number, public readonly hostname: string) {
6
9
  super(
7
- `Another opencastle process (PID ${pid} on ${hostname}) is already running against this database.`,
10
+ `Another opencastle process (PID ${pid} on ${hostname}) is already running against this database. ` +
11
+ `If it is not, the lock frees itself ${HEARTBEAT_STALE_MS / 1000} s after that process's last heartbeat.`,
8
12
  )
9
13
  this.name = 'EngineAlreadyRunningError'
10
14
  }
11
15
  }
12
16
 
13
- type LockRow = { pid: number; hostname: string; last_heartbeat: string }
17
+ type LockRow = { pid: number; hostname: string; started_at: string; last_heartbeat: string }
14
18
 
15
19
  /** False only when the process is certainly gone (ESRCH); EPERM means it exists. */
16
20
  function pidAlive(pid: number): boolean {
@@ -22,28 +26,38 @@ function pidAlive(pid: number): boolean {
22
26
  }
23
27
  }
24
28
 
29
+ /** The `started_at` of every lock row this process wrote and still holds. */
30
+ const heldHere = new Set<string>()
31
+
25
32
  /**
26
33
  * Whether a lock row may be taken over.
27
34
  *
28
- * On this host the pid answers the question outright: a dead owner is stale
29
- * at once. It used to count as live until its heartbeat was 30 s old, so a run
30
- * killed with Ctrl+C could not be resumed straight away — `resume` said
31
- * "another opencastle process is already running" about a process that no
32
- * longer existed. Another host's pid means nothing here, so only the heartbeat
33
- * can tell.
35
+ * On this host a dead pid is stale at once. It used to count as live until its
36
+ * heartbeat was 30 s old, so a run killed with Ctrl+C could not be resumed
37
+ * straight away — `resume` said "another opencastle process is already
38
+ * running" about a process that no longer existed.
39
+ *
40
+ * A live pid is not enough to prove the holder is alive, though. Containers
41
+ * restart with the same hostname and small, predictable pids, so the pid may
42
+ * now belong to another process, or to this one. Both were refused for good,
43
+ * until someone deleted the row by hand. A row with this process's own pid
44
+ * that this process did not write is an earlier process's, and stale at once.
45
+ * Any other live pid still needs a recent heartbeat. Another host's pid means
46
+ * nothing here, so there only the heartbeat can tell.
34
47
  */
35
48
  function checkStaleness(row: LockRow): boolean {
36
49
  if (row.hostname === getHostname()) {
37
- if (row.pid === process.pid) return false
38
- return !pidAlive(row.pid)
50
+ if (!pidAlive(row.pid)) return true
51
+ if (row.pid === process.pid && !heldHere.has(row.started_at)) return true
39
52
  }
40
53
  const heartbeatAge = Date.now() - new Date(row.last_heartbeat).getTime()
41
- return heartbeatAge > 30_000
54
+ // An unreadable timestamp is no proof of life.
55
+ return !(heartbeatAge <= HEARTBEAT_STALE_MS)
42
56
  }
43
57
 
44
58
  export function isLockStale(db: DatabaseSync): boolean {
45
59
  const row = db
46
- .prepare('SELECT pid, hostname, last_heartbeat FROM engine_lock WHERE id = 1')
60
+ .prepare('SELECT pid, hostname, started_at, last_heartbeat FROM engine_lock WHERE id = 1')
47
61
  .get() as LockRow | undefined
48
62
  if (!row) return true
49
63
  return checkStaleness(row)
@@ -68,7 +82,7 @@ export function acquireEngineLock(
68
82
  }
69
83
 
70
84
  const existing = db
71
- .prepare('SELECT pid, hostname, last_heartbeat FROM engine_lock WHERE id = 1')
85
+ .prepare('SELECT pid, hostname, started_at, last_heartbeat FROM engine_lock WHERE id = 1')
72
86
  .get() as LockRow | undefined
73
87
 
74
88
  if (existing) {
@@ -84,6 +98,7 @@ export function acquireEngineLock(
84
98
  'INSERT OR REPLACE INTO engine_lock (id, pid, hostname, started_at, last_heartbeat) VALUES (1, ?, ?, ?, ?)',
85
99
  ).run(process.pid, getHostname(), now, now)
86
100
  db.exec('COMMIT')
101
+ heldHere.add(now)
87
102
 
88
103
  let heartbeatInterval: NodeJS.Timeout | undefined
89
104
 
@@ -105,6 +120,7 @@ export function acquireEngineLock(
105
120
  clearInterval(heartbeatInterval)
106
121
  heartbeatInterval = undefined
107
122
  }
123
+ heldHere.delete(now)
108
124
  try {
109
125
  db.exec('DELETE FROM engine_lock WHERE id = 1')
110
126
  } catch {