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
@@ -1315,9 +1315,11 @@ async function runConvoy(ctx) {
1315
1315
  // ── Merge ───────────────────────────────────────────────────────────────
1316
1316
  const workerBranch = workerBranchName(workerId);
1317
1317
  const nothingToMerge = changes !== null && changedFiles.length === 0;
1318
+ const finalOutput = redactSecrets(result.output).text;
1318
1319
  if (!nothingToMerge) {
1320
+ let merged;
1319
1321
  try {
1320
- await mergeQueue.merge(wt, workerBranch, branch);
1322
+ merged = await mergeQueue.merge(wt, workerBranch, branch);
1321
1323
  }
1322
1324
  catch (err) {
1323
1325
  const fresh = store.getTask(rec.id, convoyId) ?? rec;
@@ -1355,6 +1357,18 @@ async function runConvoy(ctx) {
1355
1357
  failureType: 'merge-failed',
1356
1358
  });
1357
1359
  }
1360
+ // The work is on the convoy branch: from here the task is done, however
1361
+ // its run ends. Recorded before anything else is awaited, because what
1362
+ // follows takes time (removing a worktree that holds node_modules) and
1363
+ // can throw (saving artifacts). A run killed, interrupted or crashed in
1364
+ // that window used to leave the task running, and resume ran work
1365
+ // already merged a second time.
1366
+ store.updateTaskStatus(rec.id, convoyId, 'running', {
1367
+ merged_commit: merged.commit,
1368
+ output: finalOutput,
1369
+ exit_code: result.exitCode,
1370
+ contract_result: JSON.stringify(contractResult),
1371
+ });
1358
1372
  events.emit('task_merged', { branch, files: changedFiles.length }, { convoy_id: convoyId, task_id: rec.id });
1359
1373
  }
1360
1374
  await cleanup();
@@ -1456,7 +1470,7 @@ async function runConvoy(ctx) {
1456
1470
  store.withTransaction(() => {
1457
1471
  store.updateTaskStatus(rec.id, convoyId, 'done', {
1458
1472
  finished_at: now(),
1459
- output: redactSecrets(result.output).text,
1473
+ output: finalOutput,
1460
1474
  exit_code: result.exitCode,
1461
1475
  contract_result: JSON.stringify(contractResult),
1462
1476
  branch: null,
@@ -1571,7 +1585,7 @@ async function runConvoy(ctx) {
1571
1585
  return ` ${c.cyan('▸')} ${parts.join(' · ')}`;
1572
1586
  });
1573
1587
  let graceTimer;
1574
- const graceExpired = ctl.interruptedPromise.then(() => new Promise(res => { graceTimer = setTimeout(() => res('grace'), INTERRUPT_GRACE_MS); }));
1588
+ const graceExpired = ctl.interruptedPromise.then(() => new Promise(res => { graceTimer = setTimeout(() => res('grace'), ctx.interruptGraceMs); }));
1575
1589
  try {
1576
1590
  for (;;) {
1577
1591
  if (!ctl.stopDispatch) {
@@ -1585,7 +1599,12 @@ async function runConvoy(ctx) {
1585
1599
  const msg = err?.message ?? String(err);
1586
1600
  try {
1587
1601
  const row = store.getTask(t.id, convoyId);
1588
- if (row && (row.status === 'running' || row.status === 'assigned' || row.status === 'pending')) {
1602
+ if (row?.merged_commit && row.status !== 'done') {
1603
+ // It threw after its work merged: the work stands.
1604
+ markMergedDone(store, events, convoyId, row);
1605
+ progress.line(` ${c.green('✓')} ${c.bold(`[${t.id}]`)} merged ${c.dim(`(an engine error after the merge: ${firstLine(msg)})`)}`);
1606
+ }
1607
+ else if (row && (row.status === 'running' || row.status === 'assigned' || row.status === 'pending')) {
1589
1608
  store.updateTaskStatus(t.id, convoyId, ctl.interrupted ? 'pending' : 'failed', {
1590
1609
  finished_at: ctl.interrupted ? null : new Date().toISOString(),
1591
1610
  output: redactSecrets(`Engine error: ${msg}`).text,
@@ -1684,18 +1703,36 @@ async function runConvoy(ctx) {
1684
1703
  if (ctl.interrupted || failedGates.length === 0 || gateAttempt >= maxGateRetries)
1685
1704
  break;
1686
1705
  gateAttempt++;
1706
+ // A gate's output is whatever the command printed, and a failing test that
1707
+ // dumps its environment or a connection string prints a credential. It is
1708
+ // masked before it is cut to length, so no token is cut in half where the
1709
+ // scanner can no longer see it, and the prompt is then scanned the way
1710
+ // every task's is.
1687
1711
  const failureSummary = failedGates
1688
- .map(g => `Command: ${g.command}\nExit code: ${g.exitCode}\nOutput:\n${(g.output ?? '(no output)').slice(-4000)}`)
1712
+ .map(g => `Command: ${g.command}\nExit code: ${g.exitCode}\nOutput:\n${redactSecrets(g.output ?? '(no output)').text.slice(-4000)}`)
1689
1713
  .join('\n\n---\n\n');
1690
1714
  const touchedFiles = store.getTasksByConvoy(convoyId).flatMap(t => parseJsonList(t.files));
1691
1715
  const filesContext = touchedFiles.length > 0
1692
1716
  ? `\n\nFiles changed by the convoy's tasks:\n${touchedFiles.map(f => `- ${f}`).join('\n')}\n`
1693
1717
  : '';
1694
1718
  const fixTaskId = `gate-fix-${gateAttempt}`;
1719
+ 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`;
1720
+ const fixScan = scanForSecrets(fixPrompt, `task:${fixTaskId}`);
1721
+ if (!fixScan.clean) {
1722
+ const patterns = fixScan.findings.map(f => f.pattern);
1723
+ events.emit('secret_leak_prevented', {
1724
+ task_id: fixTaskId,
1725
+ findings_count: fixScan.findings.length,
1726
+ patterns,
1727
+ context: 'prompt',
1728
+ }, { convoy_id: convoyId, task_id: fixTaskId });
1729
+ progress.line(`\n ${c.red('✗')} ${c.bold(`[${fixTaskId}]`)} not started: secret detected in its prompt (${[...new Set(patterns)].join(', ')})`);
1730
+ break;
1731
+ }
1695
1732
  progress.line(`\n ${c.yellow('⟳')} ${c.bold(`[${fixTaskId}]`)} fixing the failed gates (attempt ${gateAttempt}/${maxGateRetries})`);
1696
1733
  const fixTask = {
1697
1734
  id: fixTaskId,
1698
- 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`,
1735
+ prompt: fixPrompt,
1699
1736
  agent: spec.defaults?.agent ?? 'developer',
1700
1737
  timeout: spec.defaults?.timeout ?? '30m',
1701
1738
  depends_on: [],
@@ -1830,7 +1867,11 @@ async function runConvoy(ctx) {
1830
1867
  function finishInterrupted() {
1831
1868
  const requeued = [];
1832
1869
  for (const t of store.getTasksByConvoy(convoyId)) {
1833
- if (t.status === 'running' || t.status === 'assigned') {
1870
+ if ((t.status === 'running' || t.status === 'assigned') && t.merged_commit) {
1871
+ // Still winding down after its merge when the grace period ran out.
1872
+ markMergedDone(store, events, convoyId, t);
1873
+ }
1874
+ else if (t.status === 'running' || t.status === 'assigned') {
1834
1875
  store.updateTaskStatus(t.id, convoyId, 'pending', { worker_id: null, worktree: null, started_at: null });
1835
1876
  if (t.worker_id) {
1836
1877
  try {
@@ -2004,11 +2045,22 @@ export function createConvoyEngine(options) {
2004
2045
  };
2005
2046
  }
2006
2047
  const validatePlan = () => checkConvoyPlan(spec, adapter.name);
2007
- /** Stop on SIGINT/SIGTERM or the abort signal; a second Ctrl+C stops at once. */
2048
+ /**
2049
+ * Stop on SIGINT, SIGTERM, SIGHUP or the abort signal; a second Ctrl+C stops
2050
+ * at once.
2051
+ *
2052
+ * SIGHUP is a closed terminal or a dropped SSH session. Unhandled, it ended
2053
+ * this process on the spot and left every agent running: each leads its own
2054
+ * process group, so the hangup never reached them.
2055
+ */
2008
2056
  function installInterrupts(ctl, progress) {
2009
2057
  const disposers = [];
2010
2058
  const onSignal = (sig) => {
2011
2059
  if (ctl.interrupted) {
2060
+ // When a terminal closes, the kernel and the shell can each send a
2061
+ // hangup. A second one is no request to hurry.
2062
+ if (sig === 'SIGHUP')
2063
+ return;
2012
2064
  // A second Ctrl+C means "now". Agents get SIGKILL through their
2013
2065
  // adapters; the exit is unavoidable, because the person has said they
2014
2066
  // will not wait for the cleanup the first signal started. The rows
@@ -2021,15 +2073,26 @@ export function createConvoyEngine(options) {
2021
2073
  }
2022
2074
  process.exit(130);
2023
2075
  }
2024
- progress.line(`\n ${c.yellow('■')} ${sig} — stopping: killing running agents, no new tasks. Press Ctrl+C again to quit at once.`);
2076
+ if (sig === 'SIGHUP') {
2077
+ // Writing to a terminal that has gone fails with EIO. Unhandled, that
2078
+ // error would end the process before the run is recorded as
2079
+ // interrupted. Nobody can read the terminal now anyway.
2080
+ for (const stream of [process.stdout, process.stderr])
2081
+ stream.on('error', () => { });
2082
+ progress.line(`\n ${c.yellow('■')} SIGHUP (the terminal closed) — stopping: killing running agents, no new tasks.`);
2083
+ }
2084
+ else {
2085
+ progress.line(`\n ${c.yellow('■')} ${sig} — stopping: killing running agents, no new tasks. Press Ctrl+C again to quit at once.`);
2086
+ }
2025
2087
  ctl.interrupt(sig);
2026
2088
  };
2027
2089
  if (options.handleSignals !== false) {
2028
- process.on('SIGINT', onSignal);
2029
- process.on('SIGTERM', onSignal);
2090
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
2091
+ for (const sig of signals)
2092
+ process.on(sig, onSignal);
2030
2093
  disposers.push(() => {
2031
- process.removeListener('SIGINT', onSignal);
2032
- process.removeListener('SIGTERM', onSignal);
2094
+ for (const sig of signals)
2095
+ process.removeListener(sig, onSignal);
2033
2096
  });
2034
2097
  }
2035
2098
  if (options.signal) {
@@ -2166,6 +2229,7 @@ export function createConvoyEngine(options) {
2166
2229
  convoyId, spec, adapter, store, events, wtManager, mergeQueue, repoRoot,
2167
2230
  workRoot: checkout.path, branch, baseRef, verbose, startTime, ndjsonPath,
2168
2231
  reviewRunner: options._reviewRunner ?? defaultReviewer, progress, ctl,
2232
+ interruptGraceMs: options._interruptGraceMs ?? INTERRUPT_GRACE_MS,
2169
2233
  });
2170
2234
  progress.stop();
2171
2235
  printSummary(progress, result, store, repoRoot);
@@ -2232,6 +2296,7 @@ export function createConvoyEngine(options) {
2232
2296
  checkout = await integrationCheckout(repoRoot, branch, baseRef ?? 'HEAD', shortConvoyId(convoyId));
2233
2297
  const wtManager = options._worktreeManager ?? createWorktreeManager(repoRoot);
2234
2298
  const mergeQueue = options._mergeQueue ?? createMergeQueue(checkout.path, { worktreesDir: worktreesDirFor(repoRoot) });
2299
+ await settleMergedTasks(store, events, convoyId, branch, repoRoot, progress);
2235
2300
  const reset = resetForResume(store, events, convoyId);
2236
2301
  // Worktrees left by a run that died — not the integration checkout.
2237
2302
  await wtManager.removeAll({ except: [checkout.path] });
@@ -2245,6 +2310,7 @@ export function createConvoyEngine(options) {
2245
2310
  convoyId, spec, adapter, store, events, wtManager, mergeQueue, repoRoot,
2246
2311
  workRoot: checkout.path, branch, baseRef, verbose, startTime, ndjsonPath,
2247
2312
  reviewRunner: options._reviewRunner ?? defaultReviewer, progress, ctl,
2313
+ interruptGraceMs: options._interruptGraceMs ?? INTERRUPT_GRACE_MS,
2248
2314
  });
2249
2315
  progress.stop();
2250
2316
  printSummary(progress, result, store, repoRoot);
@@ -2273,6 +2339,9 @@ export function createConvoyEngine(options) {
2273
2339
  : ndjsonPathForConvoy(convoyId, repoRoot);
2274
2340
  const events = createEventEmitter(store, { ndjsonPath });
2275
2341
  try {
2342
+ const branch = store.getConvoy(convoyId)?.branch;
2343
+ if (branch)
2344
+ await settleMergedTasks(store, events, convoyId, branch, repoRoot);
2276
2345
  resetForResume(store, events, convoyId, taskIds);
2277
2346
  store.updateConvoyStatus(convoyId, 'running', {});
2278
2347
  }
@@ -2408,6 +2477,58 @@ export function createConvoyEngine(options) {
2408
2477
  }
2409
2478
  return { run, resume, retryFailed, injectTask };
2410
2479
  }
2480
+ /**
2481
+ * Record as done a task whose work merged before its run could say so.
2482
+ *
2483
+ * Its output, exit code and contract were saved with the merge, so the row
2484
+ * reads as if the run had finished. A branch kept from an earlier failed
2485
+ * attempt stays listed: it still exists.
2486
+ */
2487
+ function markMergedDone(store, events, convoyId, task) {
2488
+ const finishedAt = new Date().toISOString();
2489
+ store.withTransaction(() => {
2490
+ store.updateTaskStatus(task.id, convoyId, 'done', { finished_at: finishedAt, retry_note: null });
2491
+ if (task.worker_id) {
2492
+ try {
2493
+ store.updateWorkerStatus(task.worker_id, 'done', { finished_at: finishedAt });
2494
+ }
2495
+ catch { /* worker record may be absent */ }
2496
+ }
2497
+ });
2498
+ events.emit('task_done', {
2499
+ exit_code: task.exit_code ?? 0,
2500
+ ...(task.worker_id ? { worker_id: task.worker_id } : {}),
2501
+ tokens: task.total_tokens,
2502
+ cost_usd: task.cost_usd,
2503
+ estimated: Boolean(task.cost_estimated),
2504
+ model: task.model,
2505
+ recovered: true,
2506
+ }, { convoy_id: convoyId, task_id: task.id, ...(task.worker_id ? { worker_id: task.worker_id } : {}) });
2507
+ }
2508
+ /**
2509
+ * Before a resume: every unfinished task whose recorded merge is on the convoy
2510
+ * branch is done.
2511
+ *
2512
+ * A run that died between a task's merge and its "done" left it running.
2513
+ * Resume then put it back to pending, nothing said the work had merged, and
2514
+ * the task ran again: the no-op gate failed it ("Produced no changes") or the
2515
+ * agent applied the change a second time. A commit the branch no longer has
2516
+ * (the branch was reset) is not counted, and the task runs again.
2517
+ */
2518
+ async function settleMergedTasks(store, events, convoyId, branch, repoRoot, progress) {
2519
+ for (const task of store.getTasksByConvoy(convoyId)) {
2520
+ if (task.status === 'done' || !task.merged_commit)
2521
+ continue;
2522
+ try {
2523
+ await git(['merge-base', '--is-ancestor', task.merged_commit, `refs/heads/${branch}`], repoRoot);
2524
+ }
2525
+ catch {
2526
+ continue; // not on the branch, or not a commit this repository has
2527
+ }
2528
+ markMergedDone(store, events, convoyId, task);
2529
+ progress?.line(` ${c.green('✓')} ${c.bold(`[${task.id}]`)} ${c.dim('merged before the run stopped — done')}`);
2530
+ }
2531
+ }
2411
2532
  /**
2412
2533
  * Put every unfinished task back to pending. Returns the ids it reset.
2413
2534
  *
@@ -2450,6 +2571,8 @@ function resetForResume(store, events, convoyId, taskIds) {
2450
2571
  worktree: null,
2451
2572
  started_at: null,
2452
2573
  finished_at: null,
2574
+ // A commit `settleMergedTasks` did not find on the branch: the work runs again.
2575
+ merged_commit: null,
2453
2576
  ...(FAILED_STATUSES.has(task.status) ? { retries: 0 } : {}),
2454
2577
  ...(task.status === 'skipped' ? { retry_note: null } : {}),
2455
2578
  });