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
@@ -973,7 +973,9 @@ async function runConvoy(ctx) {
973
973
  }
974
974
  if (files.length > 0) {
975
975
  try {
976
- scanSymlinks(files, wt);
976
+ // The links git tracks inside a declared directory, too: one there
977
+ // sends the agent's writes wherever it points.
978
+ scanSymlinks(files, wt, wtManager.symlinks ? await wtManager.symlinks(wt, files.map(normalizePath)) : []);
977
979
  }
978
980
  catch (err) {
979
981
  return fail('failed', `Symlink security check failed: ${err.message}`, { kind: 'symlink-escape' });
@@ -1287,9 +1289,12 @@ async function runConvoy(ctx) {
1287
1289
  return fail('hook-failed', `post_task hook "${label}" failed: ${post.error ?? ''}`, { kind: 'hook-failed', hook: label });
1288
1290
  }
1289
1291
  }
1290
- if (files.length > 0) {
1292
+ // Every path the commit changed, not only the declared ones: a link added
1293
+ // inside a declared directory, or outside the task's paths (a partition
1294
+ // violation only warns), merges all the same.
1295
+ if (files.length > 0 || changedFiles.length > 0) {
1291
1296
  try {
1292
- scanNewSymlinks(wt, files);
1297
+ scanNewSymlinks(wt, files, changedFiles);
1293
1298
  }
1294
1299
  catch (err) {
1295
1300
  return fail('failed', `Post-execution symlink security check failed: ${err.message}`, { kind: 'symlink-escape-post' });
@@ -1315,9 +1320,11 @@ async function runConvoy(ctx) {
1315
1320
  // ── Merge ───────────────────────────────────────────────────────────────
1316
1321
  const workerBranch = workerBranchName(workerId);
1317
1322
  const nothingToMerge = changes !== null && changedFiles.length === 0;
1323
+ const finalOutput = redactSecrets(result.output).text;
1318
1324
  if (!nothingToMerge) {
1325
+ let merged;
1319
1326
  try {
1320
- await mergeQueue.merge(wt, workerBranch, branch);
1327
+ merged = await mergeQueue.merge(wt, workerBranch, branch);
1321
1328
  }
1322
1329
  catch (err) {
1323
1330
  const fresh = store.getTask(rec.id, convoyId) ?? rec;
@@ -1355,6 +1362,18 @@ async function runConvoy(ctx) {
1355
1362
  failureType: 'merge-failed',
1356
1363
  });
1357
1364
  }
1365
+ // The work is on the convoy branch: from here the task is done, however
1366
+ // its run ends. Recorded before anything else is awaited, because what
1367
+ // follows takes time (removing a worktree that holds node_modules) and
1368
+ // can throw (saving artifacts). A run killed, interrupted or crashed in
1369
+ // that window used to leave the task running, and resume ran work
1370
+ // already merged a second time.
1371
+ store.updateTaskStatus(rec.id, convoyId, 'running', {
1372
+ merged_commit: merged.commit,
1373
+ output: finalOutput,
1374
+ exit_code: result.exitCode,
1375
+ contract_result: JSON.stringify(contractResult),
1376
+ });
1358
1377
  events.emit('task_merged', { branch, files: changedFiles.length }, { convoy_id: convoyId, task_id: rec.id });
1359
1378
  }
1360
1379
  await cleanup();
@@ -1456,7 +1475,7 @@ async function runConvoy(ctx) {
1456
1475
  store.withTransaction(() => {
1457
1476
  store.updateTaskStatus(rec.id, convoyId, 'done', {
1458
1477
  finished_at: now(),
1459
- output: redactSecrets(result.output).text,
1478
+ output: finalOutput,
1460
1479
  exit_code: result.exitCode,
1461
1480
  contract_result: JSON.stringify(contractResult),
1462
1481
  branch: null,
@@ -1571,7 +1590,7 @@ async function runConvoy(ctx) {
1571
1590
  return ` ${c.cyan('▸')} ${parts.join(' · ')}`;
1572
1591
  });
1573
1592
  let graceTimer;
1574
- const graceExpired = ctl.interruptedPromise.then(() => new Promise(res => { graceTimer = setTimeout(() => res('grace'), INTERRUPT_GRACE_MS); }));
1593
+ const graceExpired = ctl.interruptedPromise.then(() => new Promise(res => { graceTimer = setTimeout(() => res('grace'), ctx.interruptGraceMs); }));
1575
1594
  try {
1576
1595
  for (;;) {
1577
1596
  if (!ctl.stopDispatch) {
@@ -1585,7 +1604,12 @@ async function runConvoy(ctx) {
1585
1604
  const msg = err?.message ?? String(err);
1586
1605
  try {
1587
1606
  const row = store.getTask(t.id, convoyId);
1588
- if (row && (row.status === 'running' || row.status === 'assigned' || row.status === 'pending')) {
1607
+ if (row?.merged_commit && row.status !== 'done') {
1608
+ // It threw after its work merged: the work stands.
1609
+ markMergedDone(store, events, convoyId, row);
1610
+ progress.line(` ${c.green('✓')} ${c.bold(`[${t.id}]`)} merged ${c.dim(`(an engine error after the merge: ${firstLine(msg)})`)}`);
1611
+ }
1612
+ else if (row && (row.status === 'running' || row.status === 'assigned' || row.status === 'pending')) {
1589
1613
  store.updateTaskStatus(t.id, convoyId, ctl.interrupted ? 'pending' : 'failed', {
1590
1614
  finished_at: ctl.interrupted ? null : new Date().toISOString(),
1591
1615
  output: redactSecrets(`Engine error: ${msg}`).text,
@@ -1684,18 +1708,36 @@ async function runConvoy(ctx) {
1684
1708
  if (ctl.interrupted || failedGates.length === 0 || gateAttempt >= maxGateRetries)
1685
1709
  break;
1686
1710
  gateAttempt++;
1711
+ // A gate's output is whatever the command printed, and a failing test that
1712
+ // dumps its environment or a connection string prints a credential. It is
1713
+ // masked before it is cut to length, so no token is cut in half where the
1714
+ // scanner can no longer see it, and the prompt is then scanned the way
1715
+ // every task's is.
1687
1716
  const failureSummary = failedGates
1688
- .map(g => `Command: ${g.command}\nExit code: ${g.exitCode}\nOutput:\n${(g.output ?? '(no output)').slice(-4000)}`)
1717
+ .map(g => `Command: ${g.command}\nExit code: ${g.exitCode}\nOutput:\n${redactSecrets(g.output ?? '(no output)').text.slice(-4000)}`)
1689
1718
  .join('\n\n---\n\n');
1690
1719
  const touchedFiles = store.getTasksByConvoy(convoyId).flatMap(t => parseJsonList(t.files));
1691
1720
  const filesContext = touchedFiles.length > 0
1692
1721
  ? `\n\nFiles changed by the convoy's tasks:\n${touchedFiles.map(f => `- ${f}`).join('\n')}\n`
1693
1722
  : '';
1694
1723
  const fixTaskId = `gate-fix-${gateAttempt}`;
1724
+ 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`;
1725
+ const fixScan = scanForSecrets(fixPrompt, `task:${fixTaskId}`);
1726
+ if (!fixScan.clean) {
1727
+ const patterns = fixScan.findings.map(f => f.pattern);
1728
+ events.emit('secret_leak_prevented', {
1729
+ task_id: fixTaskId,
1730
+ findings_count: fixScan.findings.length,
1731
+ patterns,
1732
+ context: 'prompt',
1733
+ }, { convoy_id: convoyId, task_id: fixTaskId });
1734
+ progress.line(`\n ${c.red('✗')} ${c.bold(`[${fixTaskId}]`)} not started: secret detected in its prompt (${[...new Set(patterns)].join(', ')})`);
1735
+ break;
1736
+ }
1695
1737
  progress.line(`\n ${c.yellow('⟳')} ${c.bold(`[${fixTaskId}]`)} fixing the failed gates (attempt ${gateAttempt}/${maxGateRetries})`);
1696
1738
  const fixTask = {
1697
1739
  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`,
1740
+ prompt: fixPrompt,
1699
1741
  agent: spec.defaults?.agent ?? 'developer',
1700
1742
  timeout: spec.defaults?.timeout ?? '30m',
1701
1743
  depends_on: [],
@@ -1830,7 +1872,11 @@ async function runConvoy(ctx) {
1830
1872
  function finishInterrupted() {
1831
1873
  const requeued = [];
1832
1874
  for (const t of store.getTasksByConvoy(convoyId)) {
1833
- if (t.status === 'running' || t.status === 'assigned') {
1875
+ if ((t.status === 'running' || t.status === 'assigned') && t.merged_commit) {
1876
+ // Still winding down after its merge when the grace period ran out.
1877
+ markMergedDone(store, events, convoyId, t);
1878
+ }
1879
+ else if (t.status === 'running' || t.status === 'assigned') {
1834
1880
  store.updateTaskStatus(t.id, convoyId, 'pending', { worker_id: null, worktree: null, started_at: null });
1835
1881
  if (t.worker_id) {
1836
1882
  try {
@@ -2004,11 +2050,22 @@ export function createConvoyEngine(options) {
2004
2050
  };
2005
2051
  }
2006
2052
  const validatePlan = () => checkConvoyPlan(spec, adapter.name);
2007
- /** Stop on SIGINT/SIGTERM or the abort signal; a second Ctrl+C stops at once. */
2053
+ /**
2054
+ * Stop on SIGINT, SIGTERM, SIGHUP or the abort signal; a second Ctrl+C stops
2055
+ * at once.
2056
+ *
2057
+ * SIGHUP is a closed terminal or a dropped SSH session. Unhandled, it ended
2058
+ * this process on the spot and left every agent running: each leads its own
2059
+ * process group, so the hangup never reached them.
2060
+ */
2008
2061
  function installInterrupts(ctl, progress) {
2009
2062
  const disposers = [];
2010
2063
  const onSignal = (sig) => {
2011
2064
  if (ctl.interrupted) {
2065
+ // When a terminal closes, the kernel and the shell can each send a
2066
+ // hangup. A second one is no request to hurry.
2067
+ if (sig === 'SIGHUP')
2068
+ return;
2012
2069
  // A second Ctrl+C means "now". Agents get SIGKILL through their
2013
2070
  // adapters; the exit is unavoidable, because the person has said they
2014
2071
  // will not wait for the cleanup the first signal started. The rows
@@ -2021,15 +2078,26 @@ export function createConvoyEngine(options) {
2021
2078
  }
2022
2079
  process.exit(130);
2023
2080
  }
2024
- progress.line(`\n ${c.yellow('■')} ${sig} — stopping: killing running agents, no new tasks. Press Ctrl+C again to quit at once.`);
2081
+ if (sig === 'SIGHUP') {
2082
+ // Writing to a terminal that has gone fails with EIO. Unhandled, that
2083
+ // error would end the process before the run is recorded as
2084
+ // interrupted. Nobody can read the terminal now anyway.
2085
+ for (const stream of [process.stdout, process.stderr])
2086
+ stream.on('error', () => { });
2087
+ progress.line(`\n ${c.yellow('■')} SIGHUP (the terminal closed) — stopping: killing running agents, no new tasks.`);
2088
+ }
2089
+ else {
2090
+ progress.line(`\n ${c.yellow('■')} ${sig} — stopping: killing running agents, no new tasks. Press Ctrl+C again to quit at once.`);
2091
+ }
2025
2092
  ctl.interrupt(sig);
2026
2093
  };
2027
2094
  if (options.handleSignals !== false) {
2028
- process.on('SIGINT', onSignal);
2029
- process.on('SIGTERM', onSignal);
2095
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
2096
+ for (const sig of signals)
2097
+ process.on(sig, onSignal);
2030
2098
  disposers.push(() => {
2031
- process.removeListener('SIGINT', onSignal);
2032
- process.removeListener('SIGTERM', onSignal);
2099
+ for (const sig of signals)
2100
+ process.removeListener(sig, onSignal);
2033
2101
  });
2034
2102
  }
2035
2103
  if (options.signal) {
@@ -2166,6 +2234,7 @@ export function createConvoyEngine(options) {
2166
2234
  convoyId, spec, adapter, store, events, wtManager, mergeQueue, repoRoot,
2167
2235
  workRoot: checkout.path, branch, baseRef, verbose, startTime, ndjsonPath,
2168
2236
  reviewRunner: options._reviewRunner ?? defaultReviewer, progress, ctl,
2237
+ interruptGraceMs: options._interruptGraceMs ?? INTERRUPT_GRACE_MS,
2169
2238
  });
2170
2239
  progress.stop();
2171
2240
  printSummary(progress, result, store, repoRoot);
@@ -2232,6 +2301,7 @@ export function createConvoyEngine(options) {
2232
2301
  checkout = await integrationCheckout(repoRoot, branch, baseRef ?? 'HEAD', shortConvoyId(convoyId));
2233
2302
  const wtManager = options._worktreeManager ?? createWorktreeManager(repoRoot);
2234
2303
  const mergeQueue = options._mergeQueue ?? createMergeQueue(checkout.path, { worktreesDir: worktreesDirFor(repoRoot) });
2304
+ await settleMergedTasks(store, events, convoyId, branch, repoRoot, progress);
2235
2305
  const reset = resetForResume(store, events, convoyId);
2236
2306
  // Worktrees left by a run that died — not the integration checkout.
2237
2307
  await wtManager.removeAll({ except: [checkout.path] });
@@ -2245,6 +2315,7 @@ export function createConvoyEngine(options) {
2245
2315
  convoyId, spec, adapter, store, events, wtManager, mergeQueue, repoRoot,
2246
2316
  workRoot: checkout.path, branch, baseRef, verbose, startTime, ndjsonPath,
2247
2317
  reviewRunner: options._reviewRunner ?? defaultReviewer, progress, ctl,
2318
+ interruptGraceMs: options._interruptGraceMs ?? INTERRUPT_GRACE_MS,
2248
2319
  });
2249
2320
  progress.stop();
2250
2321
  printSummary(progress, result, store, repoRoot);
@@ -2273,6 +2344,9 @@ export function createConvoyEngine(options) {
2273
2344
  : ndjsonPathForConvoy(convoyId, repoRoot);
2274
2345
  const events = createEventEmitter(store, { ndjsonPath });
2275
2346
  try {
2347
+ const branch = store.getConvoy(convoyId)?.branch;
2348
+ if (branch)
2349
+ await settleMergedTasks(store, events, convoyId, branch, repoRoot);
2276
2350
  resetForResume(store, events, convoyId, taskIds);
2277
2351
  store.updateConvoyStatus(convoyId, 'running', {});
2278
2352
  }
@@ -2408,6 +2482,58 @@ export function createConvoyEngine(options) {
2408
2482
  }
2409
2483
  return { run, resume, retryFailed, injectTask };
2410
2484
  }
2485
+ /**
2486
+ * Record as done a task whose work merged before its run could say so.
2487
+ *
2488
+ * Its output, exit code and contract were saved with the merge, so the row
2489
+ * reads as if the run had finished. A branch kept from an earlier failed
2490
+ * attempt stays listed: it still exists.
2491
+ */
2492
+ function markMergedDone(store, events, convoyId, task) {
2493
+ const finishedAt = new Date().toISOString();
2494
+ store.withTransaction(() => {
2495
+ store.updateTaskStatus(task.id, convoyId, 'done', { finished_at: finishedAt, retry_note: null });
2496
+ if (task.worker_id) {
2497
+ try {
2498
+ store.updateWorkerStatus(task.worker_id, 'done', { finished_at: finishedAt });
2499
+ }
2500
+ catch { /* worker record may be absent */ }
2501
+ }
2502
+ });
2503
+ events.emit('task_done', {
2504
+ exit_code: task.exit_code ?? 0,
2505
+ ...(task.worker_id ? { worker_id: task.worker_id } : {}),
2506
+ tokens: task.total_tokens,
2507
+ cost_usd: task.cost_usd,
2508
+ estimated: Boolean(task.cost_estimated),
2509
+ model: task.model,
2510
+ recovered: true,
2511
+ }, { convoy_id: convoyId, task_id: task.id, ...(task.worker_id ? { worker_id: task.worker_id } : {}) });
2512
+ }
2513
+ /**
2514
+ * Before a resume: every unfinished task whose recorded merge is on the convoy
2515
+ * branch is done.
2516
+ *
2517
+ * A run that died between a task's merge and its "done" left it running.
2518
+ * Resume then put it back to pending, nothing said the work had merged, and
2519
+ * the task ran again: the no-op gate failed it ("Produced no changes") or the
2520
+ * agent applied the change a second time. A commit the branch no longer has
2521
+ * (the branch was reset) is not counted, and the task runs again.
2522
+ */
2523
+ async function settleMergedTasks(store, events, convoyId, branch, repoRoot, progress) {
2524
+ for (const task of store.getTasksByConvoy(convoyId)) {
2525
+ if (task.status === 'done' || !task.merged_commit)
2526
+ continue;
2527
+ try {
2528
+ await git(['merge-base', '--is-ancestor', task.merged_commit, `refs/heads/${branch}`], repoRoot);
2529
+ }
2530
+ catch {
2531
+ continue; // not on the branch, or not a commit this repository has
2532
+ }
2533
+ markMergedDone(store, events, convoyId, task);
2534
+ progress?.line(` ${c.green('✓')} ${c.bold(`[${task.id}]`)} ${c.dim('merged before the run stopped — done')}`);
2535
+ }
2536
+ }
2411
2537
  /**
2412
2538
  * Put every unfinished task back to pending. Returns the ids it reset.
2413
2539
  *
@@ -2450,6 +2576,8 @@ function resetForResume(store, events, convoyId, taskIds) {
2450
2576
  worktree: null,
2451
2577
  started_at: null,
2452
2578
  finished_at: null,
2579
+ // A commit `settleMergedTasks` did not find on the branch: the work runs again.
2580
+ merged_commit: null,
2453
2581
  ...(FAILED_STATUSES.has(task.status) ? { retries: 0 } : {}),
2454
2582
  ...(task.status === 'skipped' ? { retry_note: null } : {}),
2455
2583
  });