opencastle 1.12.7 → 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 (61) 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 +130 -2
  6. package/dist/cli/convoy/engine.git.test.js.map +1 -1
  7. package/dist/cli/convoy/engine.js +136 -13
  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/store.d.ts +1 -1
  32. package/dist/cli/convoy/store.d.ts.map +1 -1
  33. package/dist/cli/convoy/store.js +13 -2
  34. package/dist/cli/convoy/store.js.map +1 -1
  35. package/dist/cli/convoy/store.test.js +11 -11
  36. package/dist/cli/convoy/types.d.ts +9 -1
  37. package/dist/cli/convoy/types.d.ts.map +1 -1
  38. package/dist/cli/convoy/types.js.map +1 -1
  39. package/dist/cli/run/adapters/agent-process.d.ts.map +1 -1
  40. package/dist/cli/run/adapters/agent-process.js +58 -12
  41. package/dist/cli/run/adapters/agent-process.js.map +1 -1
  42. package/dist/cli/run/adapters/agent-process.test.js +59 -0
  43. package/dist/cli/run/adapters/agent-process.test.js.map +1 -1
  44. package/package.json +1 -1
  45. package/src/cli/convoy/TELEMETRY.md +3 -3
  46. package/src/cli/convoy/crash-status.test.ts +1 -1
  47. package/src/cli/convoy/engine.git.test.ts +141 -2
  48. package/src/cli/convoy/engine.test.ts +29 -1
  49. package/src/cli/convoy/engine.ts +138 -16
  50. package/src/cli/convoy/event-schemas.ts +1 -0
  51. package/src/cli/convoy/hangup.test.ts +126 -0
  52. package/src/cli/convoy/ledger-paths.test.ts +1 -1
  53. package/src/cli/convoy/lock.test.ts +63 -2
  54. package/src/cli/convoy/lock.ts +29 -13
  55. package/src/cli/convoy/merge.test.ts +17 -4
  56. package/src/cli/convoy/merge.ts +6 -2
  57. package/src/cli/convoy/store.test.ts +11 -11
  58. package/src/cli/convoy/store.ts +14 -3
  59. package/src/cli/convoy/types.ts +9 -1
  60. package/src/cli/run/adapters/agent-process.test.ts +59 -0
  61. 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 ─────────────────────────────────────────────────────
@@ -1613,9 +1616,11 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1613
1616
  // ── Merge ───────────────────────────────────────────────────────────────
1614
1617
  const workerBranch = workerBranchName(workerId)
1615
1618
  const nothingToMerge = changes !== null && changedFiles.length === 0
1619
+ const finalOutput = redactSecrets(result.output).text
1616
1620
  if (!nothingToMerge) {
1621
+ let merged: MergeResult
1617
1622
  try {
1618
- await mergeQueue.merge(wt, workerBranch, branch)
1623
+ merged = await mergeQueue.merge(wt, workerBranch, branch)
1619
1624
  } catch (err) {
1620
1625
  const fresh = store.getTask(rec.id, convoyId) ?? rec
1621
1626
  if (err instanceof MergeConflictError) {
@@ -1653,6 +1658,18 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1653
1658
  failureType: 'merge-failed',
1654
1659
  })
1655
1660
  }
1661
+ // The work is on the convoy branch: from here the task is done, however
1662
+ // its run ends. Recorded before anything else is awaited, because what
1663
+ // follows takes time (removing a worktree that holds node_modules) and
1664
+ // can throw (saving artifacts). A run killed, interrupted or crashed in
1665
+ // that window used to leave the task running, and resume ran work
1666
+ // already merged a second time.
1667
+ store.updateTaskStatus(rec.id, convoyId, 'running', {
1668
+ merged_commit: merged.commit,
1669
+ output: finalOutput,
1670
+ exit_code: result.exitCode,
1671
+ contract_result: JSON.stringify(contractResult),
1672
+ })
1656
1673
  events.emit('task_merged', { branch, files: changedFiles.length }, { convoy_id: convoyId, task_id: rec.id })
1657
1674
  }
1658
1675
  await cleanup()
@@ -1744,7 +1761,7 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1744
1761
  store.withTransaction(() => {
1745
1762
  store.updateTaskStatus(rec.id, convoyId, 'done', {
1746
1763
  finished_at: now(),
1747
- output: redactSecrets(result.output).text,
1764
+ output: finalOutput,
1748
1765
  exit_code: result.exitCode,
1749
1766
  contract_result: JSON.stringify(contractResult),
1750
1767
  branch: null,
@@ -1855,7 +1872,7 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1855
1872
 
1856
1873
  let graceTimer: ReturnType<typeof setTimeout> | undefined
1857
1874
  const graceExpired = ctl.interruptedPromise.then(
1858
- () => new Promise<'grace'>(res => { graceTimer = setTimeout(() => res('grace'), INTERRUPT_GRACE_MS) }),
1875
+ () => new Promise<'grace'>(res => { graceTimer = setTimeout(() => res('grace'), ctx.interruptGraceMs) }),
1859
1876
  )
1860
1877
 
1861
1878
  try {
@@ -1871,7 +1888,11 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1871
1888
  const msg = (err as Error)?.message ?? String(err)
1872
1889
  try {
1873
1890
  const row = store.getTask(t.id, convoyId)
1874
- if (row && (row.status === 'running' || row.status === 'assigned' || row.status === 'pending')) {
1891
+ if (row?.merged_commit && row.status !== 'done') {
1892
+ // It threw after its work merged: the work stands.
1893
+ markMergedDone(store, events, convoyId, row)
1894
+ progress.line(` ${c.green('✓')} ${c.bold(`[${t.id}]`)} merged ${c.dim(`(an engine error after the merge: ${firstLine(msg)})`)}`)
1895
+ } else if (row && (row.status === 'running' || row.status === 'assigned' || row.status === 'pending')) {
1875
1896
  store.updateTaskStatus(t.id, convoyId, ctl.interrupted ? 'pending' : 'failed', {
1876
1897
  finished_at: ctl.interrupted ? null : new Date().toISOString(),
1877
1898
  output: redactSecrets(`Engine error: ${msg}`).text,
@@ -1972,18 +1993,36 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1972
1993
  if (ctl.interrupted || failedGates.length === 0 || gateAttempt >= maxGateRetries) break
1973
1994
 
1974
1995
  gateAttempt++
1996
+ // A gate's output is whatever the command printed, and a failing test that
1997
+ // dumps its environment or a connection string prints a credential. It is
1998
+ // masked before it is cut to length, so no token is cut in half where the
1999
+ // scanner can no longer see it, and the prompt is then scanned the way
2000
+ // every task's is.
1975
2001
  const failureSummary = failedGates
1976
- .map(g => `Command: ${g.command}\nExit code: ${g.exitCode}\nOutput:\n${(g.output ?? '(no output)').slice(-4000)}`)
2002
+ .map(g => `Command: ${g.command}\nExit code: ${g.exitCode}\nOutput:\n${redactSecrets(g.output ?? '(no output)').text.slice(-4000)}`)
1977
2003
  .join('\n\n---\n\n')
1978
2004
  const touchedFiles = store.getTasksByConvoy(convoyId).flatMap(t => parseJsonList(t.files))
1979
2005
  const filesContext = touchedFiles.length > 0
1980
2006
  ? `\n\nFiles changed by the convoy's tasks:\n${touchedFiles.map(f => `- ${f}`).join('\n')}\n`
1981
2007
  : ''
1982
2008
  const fixTaskId = `gate-fix-${gateAttempt}`
2009
+ 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`
2010
+ const fixScan = scanForSecrets(fixPrompt, `task:${fixTaskId}`)
2011
+ if (!fixScan.clean) {
2012
+ const patterns = fixScan.findings.map(f => f.pattern)
2013
+ events.emit('secret_leak_prevented', {
2014
+ task_id: fixTaskId,
2015
+ findings_count: fixScan.findings.length,
2016
+ patterns,
2017
+ context: 'prompt',
2018
+ }, { convoy_id: convoyId, task_id: fixTaskId })
2019
+ progress.line(`\n ${c.red('✗')} ${c.bold(`[${fixTaskId}]`)} not started: secret detected in its prompt (${[...new Set(patterns)].join(', ')})`)
2020
+ break
2021
+ }
1983
2022
  progress.line(`\n ${c.yellow('⟳')} ${c.bold(`[${fixTaskId}]`)} fixing the failed gates (attempt ${gateAttempt}/${maxGateRetries})`)
1984
2023
  const fixTask: Task = {
1985
2024
  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`,
2025
+ prompt: fixPrompt,
1987
2026
  agent: spec.defaults?.agent ?? 'developer',
1988
2027
  timeout: spec.defaults?.timeout ?? '30m',
1989
2028
  depends_on: [],
@@ -2118,7 +2157,10 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
2118
2157
  function finishInterrupted(): ConvoyResult {
2119
2158
  const requeued: string[] = []
2120
2159
  for (const t of store.getTasksByConvoy(convoyId)) {
2121
- if (t.status === 'running' || t.status === 'assigned') {
2160
+ if ((t.status === 'running' || t.status === 'assigned') && t.merged_commit) {
2161
+ // Still winding down after its merge when the grace period ran out.
2162
+ markMergedDone(store, events, convoyId, t)
2163
+ } else if (t.status === 'running' || t.status === 'assigned') {
2122
2164
  store.updateTaskStatus(t.id, convoyId, 'pending', { worker_id: null, worktree: null, started_at: null })
2123
2165
  if (t.worker_id) {
2124
2166
  try { store.updateWorkerStatus(t.worker_id, 'killed', { finished_at: new Date().toISOString() }) } catch { /* gone */ }
@@ -2290,11 +2332,21 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2290
2332
 
2291
2333
  const validatePlan = (): Promise<void> => checkConvoyPlan(spec, adapter.name)
2292
2334
 
2293
- /** Stop on SIGINT/SIGTERM or the abort signal; a second Ctrl+C stops at once. */
2335
+ /**
2336
+ * Stop on SIGINT, SIGTERM, SIGHUP or the abort signal; a second Ctrl+C stops
2337
+ * at once.
2338
+ *
2339
+ * SIGHUP is a closed terminal or a dropped SSH session. Unhandled, it ended
2340
+ * this process on the spot and left every agent running: each leads its own
2341
+ * process group, so the hangup never reached them.
2342
+ */
2294
2343
  function installInterrupts(ctl: RunControl, progress: Progress): () => void {
2295
2344
  const disposers: Array<() => void> = []
2296
2345
  const onSignal = (sig: NodeJS.Signals): void => {
2297
2346
  if (ctl.interrupted) {
2347
+ // When a terminal closes, the kernel and the shell can each send a
2348
+ // hangup. A second one is no request to hurry.
2349
+ if (sig === 'SIGHUP') return
2298
2350
  // A second Ctrl+C means "now". Agents get SIGKILL through their
2299
2351
  // adapters; the exit is unavoidable, because the person has said they
2300
2352
  // will not wait for the cleanup the first signal started. The rows
@@ -2304,15 +2356,22 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2304
2356
  }
2305
2357
  process.exit(130)
2306
2358
  }
2307
- progress.line(`\n ${c.yellow('■')} ${sig} — stopping: killing running agents, no new tasks. Press Ctrl+C again to quit at once.`)
2359
+ if (sig === 'SIGHUP') {
2360
+ // Writing to a terminal that has gone fails with EIO. Unhandled, that
2361
+ // error would end the process before the run is recorded as
2362
+ // interrupted. Nobody can read the terminal now anyway.
2363
+ for (const stream of [process.stdout, process.stderr]) stream.on('error', () => {})
2364
+ progress.line(`\n ${c.yellow('■')} SIGHUP (the terminal closed) — stopping: killing running agents, no new tasks.`)
2365
+ } else {
2366
+ progress.line(`\n ${c.yellow('■')} ${sig} — stopping: killing running agents, no new tasks. Press Ctrl+C again to quit at once.`)
2367
+ }
2308
2368
  ctl.interrupt(sig)
2309
2369
  }
2310
2370
  if (options.handleSignals !== false) {
2311
- process.on('SIGINT', onSignal)
2312
- process.on('SIGTERM', onSignal)
2371
+ const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP']
2372
+ for (const sig of signals) process.on(sig, onSignal)
2313
2373
  disposers.push(() => {
2314
- process.removeListener('SIGINT', onSignal)
2315
- process.removeListener('SIGTERM', onSignal)
2374
+ for (const sig of signals) process.removeListener(sig, onSignal)
2316
2375
  })
2317
2376
  }
2318
2377
  if (options.signal) {
@@ -2448,6 +2507,7 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2448
2507
  convoyId, spec, adapter, store, events, wtManager, mergeQueue, repoRoot,
2449
2508
  workRoot: checkout.path, branch, baseRef, verbose, startTime, ndjsonPath,
2450
2509
  reviewRunner: options._reviewRunner ?? defaultReviewer, progress, ctl,
2510
+ interruptGraceMs: options._interruptGraceMs ?? INTERRUPT_GRACE_MS,
2451
2511
  })
2452
2512
  progress.stop()
2453
2513
  printSummary(progress, result, store, repoRoot)
@@ -2516,6 +2576,7 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2516
2576
  const wtManager = options._worktreeManager ?? createWorktreeManager(repoRoot)
2517
2577
  const mergeQueue = options._mergeQueue ?? createMergeQueue(checkout.path, { worktreesDir: worktreesDirFor(repoRoot) })
2518
2578
 
2579
+ await settleMergedTasks(store, events, convoyId, branch, repoRoot, progress)
2519
2580
  const reset = resetForResume(store, events, convoyId)
2520
2581
 
2521
2582
  // Worktrees left by a run that died — not the integration checkout.
@@ -2532,6 +2593,7 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2532
2593
  convoyId, spec, adapter, store, events, wtManager, mergeQueue, repoRoot,
2533
2594
  workRoot: checkout.path, branch, baseRef, verbose, startTime, ndjsonPath,
2534
2595
  reviewRunner: options._reviewRunner ?? defaultReviewer, progress, ctl,
2596
+ interruptGraceMs: options._interruptGraceMs ?? INTERRUPT_GRACE_MS,
2535
2597
  })
2536
2598
  progress.stop()
2537
2599
  printSummary(progress, result, store, repoRoot)
@@ -2558,6 +2620,8 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2558
2620
  : ndjsonPathForConvoy(convoyId, repoRoot)
2559
2621
  const events = createEventEmitter(store, { ndjsonPath })
2560
2622
  try {
2623
+ const branch = store.getConvoy(convoyId)?.branch
2624
+ if (branch) await settleMergedTasks(store, events, convoyId, branch, repoRoot)
2561
2625
  resetForResume(store, events, convoyId, taskIds)
2562
2626
  store.updateConvoyStatus(convoyId, 'running', {})
2563
2627
  } finally {
@@ -2709,6 +2773,62 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2709
2773
  return { run, resume, retryFailed, injectTask }
2710
2774
  }
2711
2775
 
2776
+ /**
2777
+ * Record as done a task whose work merged before its run could say so.
2778
+ *
2779
+ * Its output, exit code and contract were saved with the merge, so the row
2780
+ * reads as if the run had finished. A branch kept from an earlier failed
2781
+ * attempt stays listed: it still exists.
2782
+ */
2783
+ function markMergedDone(store: ConvoyStore, events: ConvoyEventEmitter, convoyId: string, task: TaskRecord): void {
2784
+ const finishedAt = new Date().toISOString()
2785
+ store.withTransaction(() => {
2786
+ store.updateTaskStatus(task.id, convoyId, 'done', { finished_at: finishedAt, retry_note: null })
2787
+ if (task.worker_id) {
2788
+ try { store.updateWorkerStatus(task.worker_id, 'done', { finished_at: finishedAt }) } catch { /* worker record may be absent */ }
2789
+ }
2790
+ })
2791
+ events.emit('task_done', {
2792
+ exit_code: task.exit_code ?? 0,
2793
+ ...(task.worker_id ? { worker_id: task.worker_id } : {}),
2794
+ tokens: task.total_tokens,
2795
+ cost_usd: task.cost_usd,
2796
+ estimated: Boolean(task.cost_estimated),
2797
+ model: task.model,
2798
+ recovered: true,
2799
+ }, { convoy_id: convoyId, task_id: task.id, ...(task.worker_id ? { worker_id: task.worker_id } : {}) })
2800
+ }
2801
+
2802
+ /**
2803
+ * Before a resume: every unfinished task whose recorded merge is on the convoy
2804
+ * branch is done.
2805
+ *
2806
+ * A run that died between a task's merge and its "done" left it running.
2807
+ * Resume then put it back to pending, nothing said the work had merged, and
2808
+ * the task ran again: the no-op gate failed it ("Produced no changes") or the
2809
+ * agent applied the change a second time. A commit the branch no longer has
2810
+ * (the branch was reset) is not counted, and the task runs again.
2811
+ */
2812
+ async function settleMergedTasks(
2813
+ store: ConvoyStore,
2814
+ events: ConvoyEventEmitter,
2815
+ convoyId: string,
2816
+ branch: string,
2817
+ repoRoot: string,
2818
+ progress?: Progress,
2819
+ ): Promise<void> {
2820
+ for (const task of store.getTasksByConvoy(convoyId)) {
2821
+ if (task.status === 'done' || !task.merged_commit) continue
2822
+ try {
2823
+ await git(['merge-base', '--is-ancestor', task.merged_commit, `refs/heads/${branch}`], repoRoot)
2824
+ } catch {
2825
+ continue // not on the branch, or not a commit this repository has
2826
+ }
2827
+ markMergedDone(store, events, convoyId, task)
2828
+ progress?.line(` ${c.green('✓')} ${c.bold(`[${task.id}]`)} ${c.dim('merged before the run stopped — done')}`)
2829
+ }
2830
+ }
2831
+
2712
2832
  /**
2713
2833
  * Put every unfinished task back to pending. Returns the ids it reset.
2714
2834
  *
@@ -2752,6 +2872,8 @@ function resetForResume(
2752
2872
  worktree: null,
2753
2873
  started_at: null,
2754
2874
  finished_at: null,
2875
+ // A commit `settleMergedTasks` did not find on the branch: the work runs again.
2876
+ merged_commit: null,
2755
2877
  ...(FAILED_STATUSES.has(task.status) ? { retries: 0 } : {}),
2756
2878
  ...(task.status === 'skipped' ? { retry_note: null } : {}),
2757
2879
  })
@@ -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 {