opencastle 1.13.0 → 1.13.1

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 (102) hide show
  1. package/dist/cli/adapters/rules-dir-base.d.ts.map +1 -1
  2. package/dist/cli/adapters/rules-dir-base.js +8 -5
  3. package/dist/cli/adapters/rules-dir-base.js.map +1 -1
  4. package/dist/cli/adapters/single-file-base.d.ts.map +1 -1
  5. package/dist/cli/adapters/single-file-base.js +25 -4
  6. package/dist/cli/adapters/single-file-base.js.map +1 -1
  7. package/dist/cli/adapters/vscode.d.ts.map +1 -1
  8. package/dist/cli/adapters/vscode.js +8 -5
  9. package/dist/cli/adapters/vscode.js.map +1 -1
  10. package/dist/cli/convoy/engine.d.ts.map +1 -1
  11. package/dist/cli/convoy/engine.git.test.js +206 -1
  12. package/dist/cli/convoy/engine.git.test.js.map +1 -1
  13. package/dist/cli/convoy/engine.js +116 -13
  14. package/dist/cli/convoy/engine.js.map +1 -1
  15. package/dist/cli/convoy/merge.d.ts +24 -5
  16. package/dist/cli/convoy/merge.d.ts.map +1 -1
  17. package/dist/cli/convoy/merge.js +108 -10
  18. package/dist/cli/convoy/merge.js.map +1 -1
  19. package/dist/cli/convoy/merge.test.js +59 -0
  20. package/dist/cli/convoy/merge.test.js.map +1 -1
  21. package/dist/cli/convoy/worktree.d.ts +6 -1
  22. package/dist/cli/convoy/worktree.d.ts.map +1 -1
  23. package/dist/cli/convoy/worktree.js +7 -0
  24. package/dist/cli/convoy/worktree.js.map +1 -1
  25. package/dist/cli/convoy/worktree.test.js +15 -1
  26. package/dist/cli/convoy/worktree.test.js.map +1 -1
  27. package/dist/cli/doctor.d.ts.map +1 -1
  28. package/dist/cli/doctor.js +23 -3
  29. package/dist/cli/doctor.js.map +1 -1
  30. package/dist/cli/foreign-skills.d.ts +23 -0
  31. package/dist/cli/foreign-skills.d.ts.map +1 -1
  32. package/dist/cli/foreign-skills.js +91 -1
  33. package/dist/cli/foreign-skills.js.map +1 -1
  34. package/dist/cli/foreign-skills.test.js +95 -2
  35. package/dist/cli/foreign-skills.test.js.map +1 -1
  36. package/dist/cli/init.d.ts.map +1 -1
  37. package/dist/cli/init.js +17 -5
  38. package/dist/cli/init.js.map +1 -1
  39. package/dist/cli/lock.d.ts +9 -0
  40. package/dist/cli/lock.d.ts.map +1 -1
  41. package/dist/cli/lock.js +16 -0
  42. package/dist/cli/lock.js.map +1 -1
  43. package/dist/cli/mcp-audit.d.ts +6 -3
  44. package/dist/cli/mcp-audit.d.ts.map +1 -1
  45. package/dist/cli/mcp-audit.js +22 -7
  46. package/dist/cli/mcp-audit.js.map +1 -1
  47. package/dist/cli/mcp-ownership.test.d.ts +2 -0
  48. package/dist/cli/mcp-ownership.test.d.ts.map +1 -0
  49. package/dist/cli/mcp-ownership.test.js +141 -0
  50. package/dist/cli/mcp-ownership.test.js.map +1 -0
  51. package/dist/cli/mcp.d.ts +36 -5
  52. package/dist/cli/mcp.d.ts.map +1 -1
  53. package/dist/cli/mcp.js +101 -33
  54. package/dist/cli/mcp.js.map +1 -1
  55. package/dist/cli/remove.d.ts.map +1 -1
  56. package/dist/cli/remove.js +4 -4
  57. package/dist/cli/remove.js.map +1 -1
  58. package/dist/cli/root-files.d.ts +59 -0
  59. package/dist/cli/root-files.d.ts.map +1 -0
  60. package/dist/cli/root-files.js +133 -0
  61. package/dist/cli/root-files.js.map +1 -0
  62. package/dist/cli/root-files.test.d.ts +2 -0
  63. package/dist/cli/root-files.test.d.ts.map +1 -0
  64. package/dist/cli/root-files.test.js +152 -0
  65. package/dist/cli/root-files.test.js.map +1 -0
  66. package/dist/cli/sync-check.d.ts +1 -1
  67. package/dist/cli/sync-check.d.ts.map +1 -1
  68. package/dist/cli/sync-check.js +19 -4
  69. package/dist/cli/sync-check.js.map +1 -1
  70. package/dist/cli/team-ci.test.js +8 -1
  71. package/dist/cli/team-ci.test.js.map +1 -1
  72. package/dist/cli/unreadable-report.d.ts.map +1 -1
  73. package/dist/cli/unreadable-report.js +3 -0
  74. package/dist/cli/unreadable-report.js.map +1 -1
  75. package/dist/cli/update.d.ts.map +1 -1
  76. package/dist/cli/update.js +33 -8
  77. package/dist/cli/update.js.map +1 -1
  78. package/package.json +1 -1
  79. package/src/cli/adapters/rules-dir-base.ts +6 -5
  80. package/src/cli/adapters/single-file-base.ts +25 -4
  81. package/src/cli/adapters/vscode.ts +10 -6
  82. package/src/cli/convoy/engine.git.test.ts +227 -1
  83. package/src/cli/convoy/engine.ts +112 -12
  84. package/src/cli/convoy/merge.test.ts +72 -0
  85. package/src/cli/convoy/merge.ts +128 -15
  86. package/src/cli/convoy/worktree.test.ts +16 -1
  87. package/src/cli/convoy/worktree.ts +13 -3
  88. package/src/cli/doctor.ts +23 -1
  89. package/src/cli/foreign-skills.test.ts +111 -2
  90. package/src/cli/foreign-skills.ts +93 -1
  91. package/src/cli/init.ts +15 -5
  92. package/src/cli/lock.ts +18 -0
  93. package/src/cli/mcp-audit.ts +22 -6
  94. package/src/cli/mcp-ownership.test.ts +167 -0
  95. package/src/cli/mcp.ts +104 -29
  96. package/src/cli/remove.ts +4 -3
  97. package/src/cli/root-files.test.ts +169 -0
  98. package/src/cli/root-files.ts +140 -0
  99. package/src/cli/sync-check.ts +20 -5
  100. package/src/cli/team-ci.test.ts +8 -1
  101. package/src/cli/unreadable-report.ts +3 -0
  102. package/src/cli/update.ts +30 -7
@@ -1,7 +1,8 @@
1
1
  import { resolve, basename, dirname, relative, sep } from 'node:path'
2
2
  import { mkdir, writeFile, readdir, readFile, rm, rename } from 'node:fs/promises'
3
3
  import { existsSync, readdirSync, realpathSync, rmdirSync } from 'node:fs'
4
- import { writeManagedBlock, recordMerge } from '../managed-block.js'
4
+ import { recordMerge } from '../managed-block.js'
5
+ import { writeRootBlock } from '../root-files.js'
5
6
  import { TIERS, TIER_IDS, isTier, tierForAgent, type Tier } from '../tiers.js'
6
7
  import { mergeCopyResults, copyDir } from '../copy.js'
7
8
  import { scaffoldMcpConfigInto } from '../mcp.js'
@@ -83,12 +84,30 @@ function subagentName(file: string): string {
83
84
  return basename(file).replace(/\.agent\.md$|\.md$/, '').toLowerCase().replace(/[^a-z0-9-]+/g, '-')
84
85
  }
85
86
 
87
+ /**
88
+ * A `tools` line written for Claude Code itself — `Read, Grep, Bash(git:*)`,
89
+ * `mcp__github__get_issue` — rather than VS Code's lower-case, slashed names
90
+ * in a YAML list, which mean nothing to it.
91
+ */
92
+ const CLAUDE_TOOLS = /^(?:[A-Z][A-Za-z]*(?:\([^)]*\))?|mcp__[\w.-]+)(?:\s*,\s*(?:[A-Z][A-Za-z]*(?:\([^)]*\))?|mcp__[\w.-]+))*$/
93
+ /** A `model` Claude Code takes: one of its aliases, or a model id. */
94
+ const CLAUDE_MODEL = /^(?:inherit|sonnet|opus|haiku|fable|claude-[a-z0-9.-]+)$/
95
+
86
96
  /** An agent file: the body, under a name and description when the assistant registers subagents. */
87
97
  function agentFile(file: string, content: string, withFrontmatter: boolean): string {
88
98
  const body = stripFrontmatter(content) + '\n'
89
99
  if (!withFrontmatter) return body
90
100
  const description = commandDescription(content) ?? subagentName(file)
91
- return `---\nname: ${subagentName(file)}\ndescription: ${JSON.stringify(description)}\n---\n\n${body}`
101
+ // An agent written for Claude Code in the first place — one `sync` kept from
102
+ // `.claude/agents/` (foreign-skills.ts) — keeps the tools and model it was
103
+ // given there. Dropping `tools` widened a subagent someone had limited to
104
+ // reading into one with every tool the session has.
105
+ const meta = parseFrontmatterMeta(content)
106
+ const own = [
107
+ meta.tools && CLAUDE_TOOLS.test(meta.tools) ? `tools: ${meta.tools}\n` : '',
108
+ meta.model && CLAUDE_MODEL.test(meta.model) ? `model: ${meta.model}\n` : '',
109
+ ].join('')
110
+ return `---\nname: ${subagentName(file)}\ndescription: ${JSON.stringify(description)}\n${own}---\n\n${body}`
92
111
  }
93
112
 
94
113
  /** The frontmatter `description`, or the first heading, as a command's one line. */
@@ -407,8 +426,10 @@ export function createSingleFileAdapter(
407
426
  'they are not repeated here, so they load once. ' +
408
427
  `Skills are in \`${skillsDirOf(config)}/\`; agent definitions are in \`${config.dotDir}/agents/\`.`
409
428
  : sections.join('\n')
410
- const merge = await writeManagedBlock(rootPath, body)
411
- recordMerge(results, rootPath, merge)
429
+ // Not through a link to another selected target's root file, which that
430
+ // target writes, nor one leading out of the project (root-files.ts).
431
+ const merge = await writeRootBlock(projectRoot, rootPath, body, stack?.ides, results)
432
+ if (merge) recordMerge(results, rootPath, merge)
412
433
  }
413
434
 
414
435
  const dotDirPath = resolve(projectRoot, config.dotDir)
@@ -1,7 +1,8 @@
1
1
  import { basename, resolve } from 'node:path'
2
2
  import { mkdir, readFile, unlink, rename } from 'node:fs/promises'
3
3
  import { existsSync, readdirSync, realpathSync } from 'node:fs'
4
- import { writeManagedBlock, recordMerge } from '../managed-block.js'
4
+ import { recordMerge } from '../managed-block.js'
5
+ import { writeRootBlock } from '../root-files.js'
5
6
  import { mergeCopyResults, copyDir } from '../copy.js'
6
7
  import { scaffoldMcpConfigInto } from '../mcp.js'
7
8
  import { compileTeamMemory } from '../memory-hooks.js'
@@ -142,8 +143,8 @@ async function installFrom(
142
143
  const copilotSrc = resolve(srcRoot, 'copilot-instructions.md')
143
144
  const copilotDest = resolve(destRoot, 'copilot-instructions.md')
144
145
  {
145
- const merge = await writeManagedBlock(copilotDest, await readFile(copilotSrc, 'utf8'))
146
- recordMerge(results, copilotDest, merge)
146
+ const merge = await writeRootBlock(projectRoot, copilotDest, await readFile(copilotSrc, 'utf8'), stack?.ides, results)
147
+ if (merge) recordMerge(results, copilotDest, merge)
147
148
  }
148
149
 
149
150
  // Framework directories
@@ -197,11 +198,14 @@ async function updateFrom(src: CompileSource, projectRoot: string, stack: StackC
197
198
 
198
199
  // Refresh only the managed block, leaving any surrounding user content alone.
199
200
  const copilotDest = resolve(destRoot, 'copilot-instructions.md')
200
- const rootMerge = await writeManagedBlock(
201
+ const rootMerge = await writeRootBlock(
202
+ projectRoot,
201
203
  copilotDest,
202
- await readFile(resolve(srcRoot, 'copilot-instructions.md'), 'utf8')
204
+ await readFile(resolve(srcRoot, 'copilot-instructions.md'), 'utf8'),
205
+ stack?.ides,
206
+ results,
203
207
  )
204
- recordMerge(results, copilotDest, rootMerge)
208
+ if (rootMerge) recordMerge(results, copilotDest, rootMerge)
205
209
 
206
210
  // Note what is here before the sweep, so the command can name anything it
207
211
  // removed that it did not generate. Only one adapter did this, so five of the
@@ -11,7 +11,7 @@ import { tmpdir, hostname } from 'node:os'
11
11
  import { dirname, join } from 'node:path'
12
12
  import { DatabaseSync } from 'node:sqlite'
13
13
  import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
14
- import { createConvoyEngine, defaultBranchName, type ConvoyEngineOptions } from './engine.js'
14
+ import { createConvoyEngine, defaultBranchName, shortConvoyId, type ConvoyEngineOptions } from './engine.js'
15
15
  import { createConvoyStore } from './store.js'
16
16
  import { createWorktreeManager, ensureRootWorktree, listAllWorktrees, type WorktreeManager } from './worktree.js'
17
17
  import { _resetAllowlistCache, _setAllowlistConfigPath } from './gates.js'
@@ -195,6 +195,143 @@ describe('the change is committed before anything checks it', () => {
195
195
  })
196
196
  })
197
197
 
198
+ describe('what merges is the commit the checks passed', () => {
199
+ function taskRow(convoyId: string, id: string) {
200
+ const store = createConvoyStore(join(repo, '.opencastle', 'convoy.db'))
201
+ try {
202
+ return store.getTask(id, convoyId)!
203
+ } finally {
204
+ store.close()
205
+ }
206
+ }
207
+
208
+ it('merges the work of an agent that ran `git checkout -b` in its worktree', async () => {
209
+ // A rule like "branch first, never commit to main" makes an agent do this.
210
+ // The engine merged `convoy-<id>` by name, still at the task's starting
211
+ // commit: "Already up to date", the task done with a merged_commit the
212
+ // branch did not have, and the worktree and its commits removed.
213
+ const adapter = stubAdapter((task, options) => {
214
+ execFileSync('git', ['checkout', '-qb', `agent/${task.id}`], { cwd: options.cwd! })
215
+ writeFileSync(join(options.cwd!, `${task.id}.txt`), `${task.id}\n`)
216
+ execFileSync('git', ['add', '-A'], { cwd: options.cwd! })
217
+ execFileSync('git', ['commit', '-qm', `agent work on ${task.id}`], { cwd: options.cwd! })
218
+ return { success: true, output: 'done', exitCode: 0 }
219
+ })
220
+ const result = await engine({ spec: spec([{ id: 'a', files: ['a.txt'] }]), adapter }).run()
221
+
222
+ expect(result.status, whyNotDone(result.convoyId)).toBe('done')
223
+ expect(filesOn(result.branch!)).toContain('a.txt')
224
+ git('merge-base', '--is-ancestor', taskRow(result.convoyId, 'a').merged_commit!, result.branch!)
225
+ })
226
+
227
+ it('merges what a task’s gate fixed, as part of the work', async () => {
228
+ // A gate that fixes as it checks, `eslint --fix` or `prettier --write`.
229
+ // Its changes were left out of the commit the checks passed, and every
230
+ // task whose gates formatted anything failed at the merge.
231
+ const adapter = stubAdapter(writesOwnFile)
232
+ const result = await engine({
233
+ spec: spec([{ id: 'a', files: ['a.txt'], gates: ['node -e "require(\'fs\').appendFileSync(\'a.txt\', \'fixed by the gate\\n\')"'] }]),
234
+ adapter,
235
+ }).run()
236
+
237
+ expect(result.status, whyNotDone(result.convoyId)).toBe('done')
238
+ expect(git('show', `${result.branch!}:a.txt`)).toBe('a\nfixed by the gate')
239
+ git('merge-base', '--is-ancestor', taskRow(result.convoyId, 'a').merged_commit!, result.branch!)
240
+ }, 30_000)
241
+
242
+ it('scans what a gate wrote before it merges', async () => {
243
+ const token = 'ghp_' + 'abcdefghijklmnopqrstuvwxyz0123456789AB'
244
+ const adapter = stubAdapter(writesOwnFile)
245
+ const result = await engine({
246
+ spec: spec(
247
+ [{ id: 'a', files: ['a.txt'], gates: [`node -e "require('fs').writeFileSync('gen.ts', 'export const t = \\"${token}\\"\\n')"`] }],
248
+ { defaults: { review: 'none', built_in_gates: { secret_scan: true } } },
249
+ ),
250
+ adapter,
251
+ }).run()
252
+
253
+ expect(result.status).toBe('failed')
254
+ const row = taskRow(result.convoyId, 'a')
255
+ expect(row.status).toBe('gate-failed')
256
+ expect(row.output).toContain('secret_scan')
257
+ expect(filesOn(result.branch!)).not.toContain('gen.ts')
258
+ }, 30_000)
259
+
260
+ it('does not merge a file a post_task hook wrote after the checks, keeps it, and says where a fix belongs', async () => {
261
+ const adapter = stubAdapter(writesOwnFile)
262
+ const result = await engine({
263
+ spec: spec([{
264
+ id: 'a',
265
+ files: ['a.txt'],
266
+ hooks: [{ type: 'command', on: 'post_task', command: 'node -e "require(\'fs\').writeFileSync(\'late.txt\', \'unchecked\\n\')"' }],
267
+ }]),
268
+ adapter,
269
+ }).run()
270
+
271
+ expect(result.status).toBe('failed')
272
+ expect(filesOn(result.branch!)).not.toContain('a.txt')
273
+ const row = taskRow(result.convoyId, 'a')
274
+ expect(row.output).toContain('late.txt')
275
+ expect(row.output).toContain('post_task hook')
276
+ expect(row.output).toContain('task\'s gates')
277
+ const kept = result.keptBranches?.find((k) => k.taskId === 'a')
278
+ expect(kept).toBeDefined()
279
+ expect(git('show', `${kept!.branch}:late.txt`)).toBe('unchecked')
280
+ expect(git('show', `${kept!.branch}:a.txt`)).toBe('a')
281
+ }, 30_000)
282
+
283
+ it('stops a task whose agent switched to another base, before anything checks it, and keeps the work', async () => {
284
+ // `git switch -c x <older commit>`: the diff from the task's start would
285
+ // undo everything since, and the merge would bring something else.
286
+ writeFileSync(join(repo, 'later.txt'), 'later\n')
287
+ git('add', '-A')
288
+ git('commit', '-qm', 'later')
289
+ const adapter = stubAdapter((task, options) => {
290
+ execFileSync('git', ['switch', '-qc', `agent/${task.id}`, 'HEAD~1'], { cwd: options.cwd! })
291
+ writeFileSync(join(options.cwd!, `${task.id}.txt`), `${task.id}\n`)
292
+ execFileSync('git', ['add', '-A'], { cwd: options.cwd! })
293
+ execFileSync('git', ['commit', '-qm', `agent work on ${task.id}`], { cwd: options.cwd! })
294
+ return { success: true, output: 'done', exitCode: 0 }
295
+ })
296
+ const result = await engine({
297
+ spec: spec([{ id: 'a', files: ['a.txt'], gates: ['node -e "process.exit(0)"'] }], { defaults: { review: 'none', built_in_gates: { secret_scan: true } } }),
298
+ adapter,
299
+ }).run()
300
+
301
+ expect(result.status).toBe('failed')
302
+ const row = taskRow(result.convoyId, 'a')
303
+ expect(row.output).toContain('not built on the task')
304
+ expect(filesOn(result.branch!)).toEqual(['.gitignore', 'README.md', 'later.txt'])
305
+ const kept = result.keptBranches?.find((k) => k.taskId === 'a')
306
+ expect(kept).toBeDefined()
307
+ expect(git('show', `${kept!.branch}:a.txt`)).toBe('a')
308
+ // Stopped before its gates: none of them ran.
309
+ const log = readFileSync(result.logPath!, 'utf8')
310
+ expect(log).not.toContain('"type":"gate_result"')
311
+ }, 30_000)
312
+
313
+ it('removes a branch the agent made once its work is merged, and never one that was there before', async () => {
314
+ git('branch', 'feature/theirs')
315
+ const adapter = stubAdapter((task, options) => {
316
+ execFileSync('git', ['checkout', '-qb', `agent/${task.id}`], { cwd: options.cwd! })
317
+ writeFileSync(join(options.cwd!, `${task.id}.txt`), `${task.id}\n`)
318
+ return { success: true, output: 'done', exitCode: 0 }
319
+ })
320
+ const theirs = stubAdapter((task, options) => {
321
+ execFileSync('git', ['checkout', '-q', 'feature/theirs'], { cwd: options.cwd! })
322
+ writeFileSync(join(options.cwd!, `${task.id}.txt`), `${task.id}\n`)
323
+ return { success: true, output: 'done', exitCode: 0 }
324
+ })
325
+ const first = await engine({ spec: spec([{ id: 'a', files: ['a.txt'] }]), adapter }).run()
326
+ expect(first.status, whyNotDone(first.convoyId)).toBe('done')
327
+ expect(git('branch', '--list', 'agent/a')).toBe('')
328
+
329
+ const second = await engine({ spec: spec([{ id: 'b', files: ['b.txt'] }]), adapter: theirs }).run()
330
+ expect(second.status, whyNotDone(second.convoyId)).toBe('done')
331
+ expect(git('branch', '--list', 'feature/theirs')).not.toBe('')
332
+ }, 30_000)
333
+ })
334
+
198
335
  describe('symlinks out of the repository', () => {
199
336
  function taskRow(convoyId: string, id: string) {
200
337
  const store = createConvoyStore(join(repo, '.opencastle', 'convoy.db'))
@@ -365,6 +502,95 @@ describe('resume', () => {
365
502
  expect(filesOn(branch)).toContain('a.txt')
366
503
  expect((await listAllWorktrees(repo)).map((w) => w.path)).toEqual([repo])
367
504
  })
505
+
506
+ it('from a linked checkout, leaves another convoy’s worktrees alone and clears only its own', async () => {
507
+ // A linked checkout has its own `.opencastle/` — its own lock and
508
+ // database — but the worktrees folder is the main repository's, shared.
509
+ // Resume cleared the whole folder: a convoy running in the main checkout
510
+ // lost a task worktree, uncommitted agent work and all.
511
+ const linked = realpathSync(mkdtempSync(join(tmpdir(), 'convoy-linked-')))
512
+ rmSync(linked, { recursive: true })
513
+ git('worktree', 'add', '-q', linked, '-b', 'feature', 'main')
514
+ try {
515
+ const manager = createWorktreeManager(repo)
516
+ // Another convoy, live, in the main checkout.
517
+ const theirs = await manager.create('ffffff-their-task-1', 'main')
518
+ writeFileSync(join(theirs, 'wip.txt'), 'uncommitted agent work\n')
519
+ // This convoy's own, left behind when its run died.
520
+ const convoyId = 'convoy-linked'
521
+ const mine = await manager.create(`${shortConvoyId(convoyId)}-a-1`, 'main')
522
+
523
+ const branch = 'convoy/linked-run'
524
+ git('branch', branch, 'main')
525
+ mkdirSync(join(linked, '.opencastle'), { recursive: true })
526
+ const store = createConvoyStore(join(linked, '.opencastle', 'convoy.db'))
527
+ store.insertConvoy({ id: convoyId, name: 'Linked', spec_hash: 'x', status: 'failed', branch, base_ref: 'feature', created_at: new Date().toISOString(), spec_yaml: 'name: l' })
528
+ store.insertTask({ id: 'a', convoy_id: convoyId, phase: 0, prompt: 'Do a', agent: 'developer', adapter: null, model: null, timeout_ms: 30_000, status: 'running', retries: 0, max_retries: 0, files: JSON.stringify(['a.txt']), depends_on: null, gates: null })
529
+ store.close()
530
+
531
+ const result = await engine({ basePath: linked, spec: spec([{ id: 'a', files: ['a.txt'] }]), adapter: stubAdapter(writesOwnFile) }).resume(convoyId)
532
+
533
+ expect(result.status, whyNotDone(convoyId)).toBe('done')
534
+ expect(readFileSync(join(theirs, 'wip.txt'), 'utf8')).toBe('uncommitted agent work\n')
535
+ expect(git('branch', '--list', 'convoy-ffffff-their-task-1')).not.toBe('')
536
+ expect(existsSync(mine)).toBe(false)
537
+ } finally {
538
+ try { git('worktree', 'remove', '--force', linked) } catch { /* already gone */ }
539
+ rmSync(linked, { recursive: true, force: true })
540
+ }
541
+ })
542
+
543
+ it('keeps a branch kept after a failed merge when the re-run merges nothing', async () => {
544
+ // The task's next finish deleted the kept branch as "superseded", also
545
+ // when the re-run changed nothing: the work the failure message said was
546
+ // kept, gone, and none of it on the convoy branch.
547
+ const convoyId = 'convoy-kept'
548
+ const branch = 'convoy/kept-run'
549
+ git('branch', branch, 'main')
550
+ git('branch', 'convoy-kept-b-1', 'main')
551
+ const keptTip = (() => {
552
+ const wt = join(repo, '..', `${repo.split('/').pop()}-kept`)
553
+ git('worktree', 'add', '-q', wt, 'convoy-kept-b-1')
554
+ writeFileSync(join(wt, 'b.txt'), 'the kept work\n')
555
+ execFileSync('git', ['add', '-A'], { cwd: wt })
556
+ execFileSync('git', ['commit', '-qm', 'b'], { cwd: wt })
557
+ const tip = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: wt, encoding: 'utf8' }).trim()
558
+ git('worktree', 'remove', '--force', wt)
559
+ return tip
560
+ })()
561
+ mkdirSync(join(repo, '.opencastle'), { recursive: true })
562
+ const store = createConvoyStore(join(repo, '.opencastle', 'convoy.db'))
563
+ store.insertConvoy({ id: convoyId, name: 'Kept', spec_hash: 'x', status: 'failed', branch, base_ref: 'main', created_at: new Date().toISOString(), spec_yaml: 'name: k' })
564
+ store.insertTask({ id: 'b', convoy_id: convoyId, phase: 0, prompt: 'Do b', agent: 'developer', adapter: null, model: null, timeout_ms: 30_000, status: 'failed', retries: 0, max_retries: 0, files: JSON.stringify([]), depends_on: null, gates: null })
565
+ store.updateTaskStatus('b', convoyId, 'failed', { branch: 'convoy-kept-b-1' })
566
+ store.close()
567
+
568
+ const nothing = stubAdapter(() => ({ success: true, output: 'nothing to do', exitCode: 0 }))
569
+ const result = await engine({ spec: spec([{ id: 'b' }]), adapter: nothing }).resume(convoyId)
570
+
571
+ expect(result.status, whyNotDone(convoyId)).toBe('done')
572
+ expect(git('rev-parse', 'convoy-kept-b-1')).toBe(keptTip)
573
+ expect(result.keptBranches).toEqual([{ taskId: 'b', branch: 'convoy-kept-b-1' }])
574
+ })
575
+
576
+ it('deletes a kept branch once its work is on the convoy branch', async () => {
577
+ const convoyId = 'convoy-landed'
578
+ const branch = 'convoy/landed-run'
579
+ git('branch', branch, 'main')
580
+ git('branch', 'convoy-landed-b-1', 'main')
581
+ mkdirSync(join(repo, '.opencastle'), { recursive: true })
582
+ const store = createConvoyStore(join(repo, '.opencastle', 'convoy.db'))
583
+ store.insertConvoy({ id: convoyId, name: 'Landed', spec_hash: 'x', status: 'failed', branch, base_ref: 'main', created_at: new Date().toISOString(), spec_yaml: 'name: l' })
584
+ store.insertTask({ id: 'b', convoy_id: convoyId, phase: 0, prompt: 'Do b', agent: 'developer', adapter: null, model: null, timeout_ms: 30_000, status: 'failed', retries: 0, max_retries: 0, files: JSON.stringify(['b.txt']), depends_on: null, gates: null })
585
+ store.updateTaskStatus('b', convoyId, 'failed', { branch: 'convoy-landed-b-1' })
586
+ store.close()
587
+
588
+ const result = await engine({ spec: spec([{ id: 'b', files: ['b.txt'] }]), adapter: stubAdapter(writesOwnFile) }).resume(convoyId)
589
+
590
+ expect(result.status, whyNotDone(convoyId)).toBe('done')
591
+ expect(git('branch', '--list', 'convoy-landed-b-1')).toBe('')
592
+ expect(result.keptBranches).toEqual([])
593
+ })
368
594
  })
369
595
 
370
596
  describe('interrupting a run', () => {
@@ -21,7 +21,7 @@ import {
21
21
  BranchInUseError,
22
22
  type WorktreeManager,
23
23
  } from './worktree.js'
24
- import { createMergeQueue, MergeConflictError, type MergeQueue, type MergeResult } from './merge.js'
24
+ import { ChangedAfterChecksError, 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,
@@ -1194,6 +1194,16 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1194
1194
  }
1195
1195
  const wt: string = worktreePath
1196
1196
  const startSha = wtManager.head ? await wtManager.head(wt) : null
1197
+ // The branches there are before the agent runs, so one it makes for itself
1198
+ // ("branch first" is a common project rule) can be told from the user's.
1199
+ const branchesBefore = new Set<string>()
1200
+ if (wtManager.commitAll) {
1201
+ try {
1202
+ for (const name of (await git(['for-each-ref', '--format=%(refname:short)', 'refs/heads'], repoRoot)).split('\n')) {
1203
+ if (name.trim()) branchesBefore.add(name.trim())
1204
+ }
1205
+ } catch { /* none known: no branch of the agent's is removed */ }
1206
+ }
1197
1207
 
1198
1208
  store.insertWorker({
1199
1209
  id: workerId,
@@ -1331,9 +1341,41 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1331
1341
  return retryOrFail('failed', `Could not commit the task's work: ${firstLine((err as { stderr?: string }).stderr) || (err as Error).message}`, { kind: 'commit' })
1332
1342
  }
1333
1343
  }
1334
- const changes = startSha && wtManager.changes ? await wtManager.changes(wt, startSha) : null
1335
- const changedFiles = changes?.files ?? []
1336
- const diff = changes?.diff ?? ''
1344
+ // The commit every check below looks at, and the one that merges. Taken
1345
+ // again after the task's gates, which may fix what they check; anything
1346
+ // written after that (a post_task hook) was not scanned or reviewed, and
1347
+ // the merge refuses it rather than taking it along.
1348
+ let checkedCommit = wtManager.head ? await wtManager.head(wt) : null
1349
+ let changes = startSha && wtManager.changes ? await wtManager.changes(wt, startSha) : null
1350
+ // What the agent itself changed: the no-op gate's question, which a
1351
+ // formatter run as a gate must not answer for it.
1352
+ const agentChanges = changes
1353
+ let changedFiles = changes?.files ?? []
1354
+ let diff = changes?.diff ?? ''
1355
+
1356
+ // ── Built on the task's starting point ──────────────────────────────────
1357
+ // An agent that checked out another base (`git switch -c x origin/main`)
1358
+ // left a commit whose diff from the start undoes everything merged since:
1359
+ // the review would judge that, and the merge would bring something else.
1360
+ // Stopped here, before any gate or review is spent on it, with the work
1361
+ // kept on the worker branch.
1362
+ if (startSha && checkedCommit && checkedCommit !== startSha && wtManager.commitAll) {
1363
+ let onBase = true
1364
+ try {
1365
+ await git(['merge-base', '--is-ancestor', startSha, checkedCommit], wt)
1366
+ } catch {
1367
+ onBase = false
1368
+ }
1369
+ if (!onBase) {
1370
+ const kept = workerBranchName(workerId)
1371
+ try { await git(['update-ref', `refs/heads/${kept}`, checkedCommit], wt) } catch { /* the message still names it */ }
1372
+ return fail(
1373
+ 'failed',
1374
+ `Not merged: the agent's commit ${checkedCommit.slice(0, 12)} is not built on the task's starting point ${startSha.slice(0, 12)} — it switched to another base. The work is kept on branch ${kept}`,
1375
+ { kind: 'off-base', keepBranch: kept, failureType: 'off-base' },
1376
+ )
1377
+ }
1378
+ }
1337
1379
 
1338
1380
  // ── Per-task gates from the spec ────────────────────────────────────────
1339
1381
  const taskGates = parseJsonList(rec.gates)
@@ -1354,6 +1396,26 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1354
1396
  }
1355
1397
  }
1356
1398
 
1399
+ // A gate that fixes as it checks — `eslint --fix`, `prettier --write` — made
1400
+ // changes that belong to the work. Committed now, so the secret scan, the
1401
+ // review and the merge below all see the same thing: the change as it will
1402
+ // land. Leaving them out of the checked commit failed every task whose
1403
+ // gates formatted anything.
1404
+ if (taskGates.length > 0 && wtManager.commitAll) {
1405
+ let committed = false
1406
+ try {
1407
+ committed = await wtManager.commitAll(wt, `convoy(${rec.id}): what its gates changed`)
1408
+ } catch (err) {
1409
+ return retryOrFail('failed', `Could not commit what the task's gates changed: ${firstLine((err as { stderr?: string }).stderr) || (err as Error).message}`, { kind: 'commit' })
1410
+ }
1411
+ if (committed) {
1412
+ checkedCommit = wtManager.head ? await wtManager.head(wt) : null
1413
+ changes = startSha && wtManager.changes ? await wtManager.changes(wt, startSha) : null
1414
+ changedFiles = changes?.files ?? []
1415
+ diff = changes?.diff ?? ''
1416
+ }
1417
+ }
1418
+
1357
1419
  const builtInGates = spec.defaults?.built_in_gates
1358
1420
  const contractResult = validateOutput(rec.agent, result.output)
1359
1421
 
@@ -1363,7 +1425,7 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1363
1425
  if (files.length > 0 && (builtInGates ? builtInGates.no_op !== false : true)) {
1364
1426
  const noOp = noOpGate({
1365
1427
  declaredFiles: files,
1366
- changedFiles: changes ? changedFiles : null,
1428
+ changedFiles: agentChanges ? agentChanges.files : null,
1367
1429
  agent: rec.agent,
1368
1430
  contractData: contractResult.data,
1369
1431
  })
@@ -1620,12 +1682,22 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1620
1682
 
1621
1683
  // ── Merge ───────────────────────────────────────────────────────────────
1622
1684
  const workerBranch = workerBranchName(workerId)
1685
+ // A branch the agent made and left its checkout on: once its commit is on
1686
+ // the convoy branch it is only clutter, one per task, in the user's
1687
+ // repository. One that was there before the task is never touched.
1688
+ let agentBranch: string | null = null
1689
+ if (wtManager.commitAll) {
1690
+ try {
1691
+ const name = (await git(['symbolic-ref', '--quiet', '--short', 'HEAD'], wt)).trim()
1692
+ if (name && name !== workerBranch && !branchesBefore.has(name)) agentBranch = name
1693
+ } catch { /* detached: no branch of its own */ }
1694
+ }
1623
1695
  const nothingToMerge = changes !== null && changedFiles.length === 0
1624
1696
  const finalOutput = redactSecrets(result.output).text
1625
1697
  if (!nothingToMerge) {
1626
1698
  let merged: MergeResult
1627
1699
  try {
1628
- merged = await mergeQueue.merge(wt, workerBranch, branch)
1700
+ merged = await mergeQueue.merge(wt, workerBranch, branch, checkedCommit ? { commit: checkedCommit } : undefined)
1629
1701
  } catch (err) {
1630
1702
  const fresh = store.getTask(rec.id, convoyId) ?? rec
1631
1703
  if (err instanceof MergeConflictError) {
@@ -1657,7 +1729,10 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1657
1729
  error: message,
1658
1730
  ...(conflicting ? { conflicting_files: conflicting } : {}),
1659
1731
  }, { convoy_id: convoyId, task_id: rec.id })
1660
- return fail('failed', `Merge failed (${message}); the work is kept on branch ${workerBranch}`, {
1732
+ const said = err instanceof ChangedAfterChecksError
1733
+ ? `Not merged: ${message}. The work, with those changes on top, is kept on branch ${workerBranch}`
1734
+ : `Merge failed (${message}); the work is kept on branch ${workerBranch}`
1735
+ return fail('failed', said, {
1661
1736
  kind: 'merge-failed',
1662
1737
  keepBranch: workerBranch,
1663
1738
  failureType: 'merge-failed',
@@ -1678,9 +1753,32 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1678
1753
  events.emit('task_merged', { branch, files: changedFiles.length }, { convoy_id: convoyId, task_id: rec.id })
1679
1754
  }
1680
1755
  await cleanup()
1756
+ if (agentBranch) {
1757
+ try {
1758
+ await git(['merge-base', '--is-ancestor', `refs/heads/${agentBranch}`, `refs/heads/${branch}`], repoRoot)
1759
+ await git(['branch', '-D', agentBranch], repoRoot)
1760
+ } catch { /* not all of it is on the convoy branch: it stays */ }
1761
+ }
1762
+ // A branch kept from an earlier failed merge goes only when its work is on
1763
+ // the convoy branch. It was deleted whenever the task next finished, on
1764
+ // the grounds that the new attempt superseded it — including a re-run that
1765
+ // changed nothing and merged nothing, which deleted the work the failure
1766
+ // message had said was kept, with none of it anywhere else.
1767
+ let keptBranch: string | null = null
1681
1768
  if (rec.branch && rec.branch !== workerBranch && wtManager.commitAll) {
1682
- // A branch kept from an earlier failed merge is superseded now.
1683
- try { await git(['branch', '-D', rec.branch], repoRoot) } catch { /* already gone */ }
1769
+ keptBranch = rec.branch
1770
+ try {
1771
+ await git(['rev-parse', '--verify', '--quiet', `refs/heads/${rec.branch}`], repoRoot)
1772
+ } catch {
1773
+ keptBranch = null // already gone
1774
+ }
1775
+ if (keptBranch) {
1776
+ try {
1777
+ await git(['merge-base', '--is-ancestor', `refs/heads/${rec.branch}`, `refs/heads/${branch}`], repoRoot)
1778
+ await git(['branch', '-D', rec.branch], repoRoot)
1779
+ keptBranch = null
1780
+ } catch { /* not on the convoy branch: it stays, and the summary still names it */ }
1781
+ }
1684
1782
  }
1685
1783
 
1686
1784
  // ── Outputs and artifacts ──────────────────────────────────────────────
@@ -1769,7 +1867,7 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1769
1867
  output: finalOutput,
1770
1868
  exit_code: result.exitCode,
1771
1869
  contract_result: JSON.stringify(contractResult),
1772
- branch: null,
1870
+ branch: keptBranch,
1773
1871
  retry_note: null,
1774
1872
  })
1775
1873
  store.updateWorkerStatus(workerId!, 'done', { finished_at: now() })
@@ -2584,8 +2682,10 @@ export function createConvoyEngine(options: ConvoyEngineOptions): ConvoyEngine {
2584
2682
  await settleMergedTasks(store, events, convoyId, branch, repoRoot, progress)
2585
2683
  const reset = resetForResume(store, events, convoyId)
2586
2684
 
2587
- // Worktrees left by a run that died — not the integration checkout.
2588
- await wtManager.removeAll({ except: [checkout.path] })
2685
+ // Worktrees left by this convoy's run that died — not the integration
2686
+ // checkout, and not another convoy's: the folder is shared by every
2687
+ // checkout of the repository, and one of them may be running now.
2688
+ await wtManager.removeAll({ except: [checkout.path], owner: shortConvoyId(convoyId) })
2589
2689
 
2590
2690
  recoverNdjson(store, convoyId, ndjsonPath)
2591
2691
  store.updateConvoyStatus(convoyId, 'running', {})
@@ -218,3 +218,75 @@ describe('merge - concurrency', () => {
218
218
  await expect(queue.merge(worktreePath, 'no-such-branch', featureBranch)).rejects.toBeInstanceOf(MergeError)
219
219
  })
220
220
  })
221
+
222
+ // ── the commit the checks passed ─────────────────────────────────────────────
223
+
224
+ describe('merge - the checked commit', () => {
225
+ async function commitIn(worktree: string, file: string, text: string): Promise<string> {
226
+ writeFileSync(join(worktree, file), text)
227
+ await execFile('git', ['-C', worktree, 'add', '-A'])
228
+ await execFile('git', ['-C', worktree, 'commit', '-qm', `add ${file}`])
229
+ return (await execFile('git', ['-C', worktree, 'rev-parse', 'HEAD'])).stdout.trim()
230
+ }
231
+
232
+ it('merges the commit when the agent ran `git checkout -b` in its worktree', async () => {
233
+ // Merged by name, `convoy-worker1` still pointed at the start: git said
234
+ // "Already up to date" and the work was reported merged, then deleted.
235
+ const worktreePath = await addWorktree(repoPath, 'worker1', featureBranch)
236
+ await execFile('git', ['-C', worktreePath, 'checkout', '-qb', 'agent/own-branch'])
237
+ const checked = await commitIn(worktreePath, 'work.txt', 'the work')
238
+
239
+ const result = await queue.merge(worktreePath, 'convoy-worker1', featureBranch, { commit: checked })
240
+
241
+ expect(result).toEqual({ success: true, conflicted: false, message: 'Merged successfully', commit: checked })
242
+ await execFile('git', ['-C', repoPath, 'merge-base', '--is-ancestor', checked, featureBranch])
243
+ const { stdout: onTarget } = await execFile('git', ['-C', repoPath, 'show', `${featureBranch}:work.txt`])
244
+ expect(onTarget).toBe('the work')
245
+ // The worker's branch holds the work too, so a branch kept after a failed merge is worth keeping.
246
+ const { stdout: tip } = await execFile('git', ['-C', repoPath, 'rev-parse', 'convoy-worker1'])
247
+ expect(tip.trim()).toBe(checked)
248
+ })
249
+
250
+ it('merges the commit from a detached HEAD', async () => {
251
+ const worktreePath = await addWorktree(repoPath, 'worker1', featureBranch)
252
+ await execFile('git', ['-C', worktreePath, 'checkout', '-q', '--detach'])
253
+ const checked = await commitIn(worktreePath, 'work.txt', 'detached work')
254
+
255
+ const result = await queue.merge(worktreePath, 'convoy-worker1', featureBranch, { commit: checked })
256
+
257
+ expect(result.commit).toBe(checked)
258
+ await execFile('git', ['-C', repoPath, 'merge-base', '--is-ancestor', checked, featureBranch])
259
+ })
260
+
261
+ it('refuses files written after the checks, merges nothing, and keeps everything on the worker branch', async () => {
262
+ const { ChangedAfterChecksError } = await import('./merge.js')
263
+ const worktreePath = await addWorktree(repoPath, 'worker1', featureBranch)
264
+ const checked = await commitIn(worktreePath, 'work.txt', 'checked\n')
265
+ // What a post_task hook that writes files leaves behind, after the checks.
266
+ writeFileSync(join(worktreePath, 'work.txt'), 'checked\nfixed later\n')
267
+ writeFileSync(join(worktreePath, 'late.txt'), 'never scanned\n')
268
+
269
+ const attempt = queue.merge(worktreePath, 'convoy-worker1', featureBranch, { commit: checked })
270
+ await expect(attempt).rejects.toBeInstanceOf(ChangedAfterChecksError)
271
+ await expect(attempt).rejects.toThrow(/late\.txt/)
272
+
273
+ const { stdout: onTarget } = await execFile('git', ['-C', repoPath, 'ls-tree', '--name-only', featureBranch])
274
+ expect(onTarget).not.toContain('work.txt')
275
+ expect(onTarget).not.toContain('late.txt')
276
+ const { stdout: kept } = await execFile('git', ['-C', repoPath, 'show', 'convoy-worker1:late.txt'])
277
+ expect(kept).toBe('never scanned\n')
278
+ await execFile('git', ['-C', repoPath, 'merge-base', '--is-ancestor', checked, 'convoy-worker1'])
279
+ })
280
+
281
+ it('refuses a worktree whose HEAD moved after the checks', async () => {
282
+ const { ChangedAfterChecksError } = await import('./merge.js')
283
+ const worktreePath = await addWorktree(repoPath, 'worker1', featureBranch)
284
+ const checked = await commitIn(worktreePath, 'work.txt', 'checked\n')
285
+ await commitIn(worktreePath, 'hook.txt', 'committed by a hook\n')
286
+
287
+ await expect(queue.merge(worktreePath, 'convoy-worker1', featureBranch, { commit: checked }))
288
+ .rejects.toBeInstanceOf(ChangedAfterChecksError)
289
+ const { stdout: onTarget } = await execFile('git', ['-C', repoPath, 'ls-tree', '--name-only', featureBranch])
290
+ expect(onTarget).not.toContain('work.txt')
291
+ })
292
+ })