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
@@ -55,7 +55,20 @@ describe('merge - successful merge', () => {
55
55
 
56
56
  const result = await queue.merge(worktreePath, 'convoy-worker1', featureBranch)
57
57
 
58
- expect(result).toEqual({ success: true, conflicted: false, message: 'Merged successfully' })
58
+ expect(result).toEqual({ success: true, conflicted: false, message: 'Merged successfully', commit: expect.any(String) })
59
+ })
60
+
61
+ it('reports the worker commit it merged, which is then on the target branch', async () => {
62
+ // The engine records it the moment the merge lands, so a resume can tell
63
+ // the work is already on the branch.
64
+ const worktreePath = await addWorktree(repoPath, 'worker1', featureBranch)
65
+ writeFileSync(join(worktreePath, 'output.txt'), 'worker output')
66
+
67
+ const { commit } = await queue.merge(worktreePath, 'convoy-worker1', featureBranch)
68
+
69
+ const { stdout: tip } = await execFile('git', ['-C', repoPath, 'rev-parse', 'convoy-worker1'])
70
+ expect(commit).toBe(tip.trim())
71
+ await execFile('git', ['-C', repoPath, 'merge-base', '--is-ancestor', commit, featureBranch])
59
72
  })
60
73
 
61
74
  it('makes the merged file available in the target branch working tree', async () => {
@@ -87,7 +100,7 @@ describe('merge - no changes', () => {
87
100
 
88
101
  const result = await queue.merge(worktreePath, 'convoy-worker1', featureBranch)
89
102
 
90
- expect(result).toEqual({ success: true, conflicted: false, message: 'No changes to merge' })
103
+ expect(result).toEqual({ success: true, conflicted: false, message: 'No changes to merge', commit: expect.any(String) })
91
104
  })
92
105
 
93
106
  it('does not create a commit when there is nothing to stage', async () => {
@@ -111,7 +124,7 @@ describe('merge - conflict', () => {
111
124
  writeFileSync(join(worktree2, 'shared.txt'), 'content from worker 2')
112
125
 
113
126
  const first = await queue.merge(worktree1, 'convoy-worker1', featureBranch)
114
- expect(first).toEqual({ success: true, conflicted: false, message: 'Merged successfully' })
127
+ expect(first).toEqual({ success: true, conflicted: false, message: 'Merged successfully', commit: expect.any(String) })
115
128
 
116
129
  await expect(queue.merge(worktree2, 'convoy-worker2', featureBranch))
117
130
  .rejects.toThrow(MergeConflictError)
@@ -147,7 +160,7 @@ describe('merge - already committed changes', () => {
147
160
 
148
161
  const result = await queue.merge(worktreePath, 'convoy-worker1', featureBranch)
149
162
 
150
- expect(result).toEqual({ success: true, conflicted: false, message: 'Merged successfully' })
163
+ expect(result).toEqual({ success: true, conflicted: false, message: 'Merged successfully', commit: expect.any(String) })
151
164
  })
152
165
 
153
166
  it('makes pre-committed files available in the target branch after merge', async () => {
@@ -5,6 +5,8 @@ export interface MergeResult {
5
5
  success: boolean
6
6
  conflicted: boolean
7
7
  message: string
8
+ /** The worker's commit, now an ancestor of the target branch. */
9
+ commit: string
8
10
  }
9
11
 
10
12
  export class MergeConflictError extends Error {
@@ -76,8 +78,10 @@ export function createMergeQueue(
76
78
  throw new Error(`Path "${worktreePath}" is outside the managed worktrees directory`)
77
79
  }
78
80
 
81
+ let commit: string
79
82
  try {
80
83
  await commitAllIn(resolve(worktreePath), `convoy: ${worktreeBranch} completed`)
84
+ commit = (await git(['rev-parse', '--verify', 'HEAD^{commit}'], resolve(worktreePath))).trim()
81
85
  } catch (err) {
82
86
  throw new MergeError(`could not commit the task's work: ${firstLine((err as { stderr?: string }).stderr) || (err as Error).message}`)
83
87
  }
@@ -92,9 +96,9 @@ export function createMergeQueue(
92
96
  try {
93
97
  const stdout = await mergeIn(target, ['--no-edit', worktreeBranch])
94
98
  if (stdout.includes('Already up to date')) {
95
- return { success: true, conflicted: false, message: 'No changes to merge' }
99
+ return { success: true, conflicted: false, message: 'No changes to merge', commit }
96
100
  }
97
- return { success: true, conflicted: false, message: 'Merged successfully' }
101
+ return { success: true, conflicted: false, message: 'Merged successfully', commit }
98
102
  } catch (err) {
99
103
  const error = err as { code?: number | string; stderr?: string; stdout?: string; message?: string }
100
104
  const text = `${error.stdout ?? ''}\n${error.stderr ?? ''}`
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The symlink scans against real links on disk. partition.test.ts mocks
3
+ * node:fs, so it cannot follow a link through another one.
4
+ */
5
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
6
+ import { tmpdir } from 'node:os'
7
+ import { join } from 'node:path'
8
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest'
9
+ import { scanSymlinks, scanNewSymlinks } from './partition.js'
10
+
11
+ let root: string
12
+ /** The worktree the scans guard. */
13
+ let base: string
14
+ /** A directory beside it, outside. */
15
+ let outside: string
16
+
17
+ beforeEach(() => {
18
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'convoy-symlinks-')))
19
+ base = join(root, 'worktree')
20
+ outside = join(root, 'outside')
21
+ mkdirSync(join(base, 'src', 'auth'), { recursive: true })
22
+ mkdirSync(outside)
23
+ writeFileSync(join(outside, 'secret'), 'x\n')
24
+ })
25
+
26
+ afterEach(() => {
27
+ rmSync(root, { recursive: true, force: true })
28
+ })
29
+
30
+ describe('scanSymlinks, before the task', () => {
31
+ it('refuses a tracked link inside a declared directory that leads out', () => {
32
+ symlinkSync(outside, join(base, 'src/auth/keys'))
33
+ expect(() => scanSymlinks(['src/auth/'], base, ['src/auth/keys'])).toThrow('symlink_escape: "src/auth/keys"')
34
+ })
35
+
36
+ it('refuses a link above a declared file', () => {
37
+ symlinkSync(outside, join(base, 'src/vendor'))
38
+ expect(() => scanSymlinks(['src/vendor/lib.ts'], base)).toThrow('symlink_escape: "src/vendor"')
39
+ })
40
+
41
+ it('leaves alone a tracked link outside the declared paths', () => {
42
+ symlinkSync(outside, join(base, 'docs-link'))
43
+ expect(() => scanSymlinks(['src/auth/'], base, ['docs-link'])).not.toThrow()
44
+ })
45
+
46
+ it('passes a link to something inside that is not there yet, such as a build output', () => {
47
+ symlinkSync('../../dist/index.js', join(base, 'src/auth/built.js'))
48
+ expect(() => scanSymlinks(['src/auth/'], base, ['src/auth/built.js'])).not.toThrow()
49
+ })
50
+
51
+ it('refuses a link to something outside that is not there yet', () => {
52
+ symlinkSync(join(outside, 'new', 'authorized_keys'), join(base, 'src/auth/keys'))
53
+ expect(() => scanSymlinks(['src/auth/'], base, ['src/auth/keys'])).toThrow('resolves outside the partition')
54
+ })
55
+
56
+ it('follows the links on the way to a target that is not there yet', () => {
57
+ // src/auth/keys → src/vendor/keys, and src/vendor leads out.
58
+ symlinkSync(outside, join(base, 'src/vendor'))
59
+ symlinkSync('../vendor/keys', join(base, 'src/auth/keys'))
60
+ expect(() => scanSymlinks(['src/auth/'], base, ['src/auth/keys'])).toThrow('symlink_escape: "src/auth/keys"')
61
+ })
62
+ })
63
+
64
+ describe('scanNewSymlinks, after the task', () => {
65
+ it('refuses a new link inside a declared directory that leads out', () => {
66
+ symlinkSync(outside, join(base, 'src/auth/keys'))
67
+ expect(() => scanNewSymlinks(base, ['src/auth/'], ['src/auth/service.ts', 'src/auth/keys']))
68
+ .toThrow('symlink_escape_post_task: "src/auth/keys"')
69
+ })
70
+
71
+ it('refuses a new link outside the declared paths, and from a task that declares none', () => {
72
+ symlinkSync(join(outside, 'secret'), join(base, 'leak'))
73
+ expect(() => scanNewSymlinks(base, ['src/auth/'], ['leak'])).toThrow('symlink_escape_post_task: "leak"')
74
+ expect(() => scanNewSymlinks(base, [], ['leak'])).toThrow('symlink_escape_post_task: "leak"')
75
+ })
76
+
77
+ it('passes a link that stays inside, and a path the change deleted', () => {
78
+ writeFileSync(join(base, 'src/auth/service.ts'), 'export {}\n')
79
+ symlinkSync('service.ts', join(base, 'src/auth/alias.ts'))
80
+ expect(() => scanNewSymlinks(base, ['src/auth/'], ['src/auth/alias.ts', 'src/auth/gone.ts'])).not.toThrow()
81
+ })
82
+ })
@@ -336,7 +336,8 @@ describe('scanSymlinks', () => {
336
336
  .mockReturnValueOnce(BASE as unknown as string) // resolve(basePath)
337
337
  .mockReturnValueOnce(`${BASE}/src/auth/target.ts` as unknown as string) // symlink target
338
338
 
339
- vi.mocked(fs.lstatSync).mockReturnValue(makeFakeStats(true))
339
+ // The link itself; the directories above it are not links.
340
+ vi.mocked(fs.lstatSync).mockImplementation((p) => makeFakeStats(String(p).endsWith('/link.ts')))
340
341
 
341
342
  expect(() => scanSymlinks(['src/auth/link.ts'], BASE)).not.toThrow()
342
343
  })
@@ -1,6 +1,6 @@
1
- import { statSync, realpathSync, lstatSync, writeFileSync, rmSync } from 'node:fs'
1
+ import { statSync, realpathSync, lstatSync, readlinkSync, writeFileSync, rmSync } from 'node:fs'
2
2
  import { tmpdir } from 'node:os'
3
- import { normalize, join, resolve } from 'node:path'
3
+ import { basename, dirname, normalize, join, resolve, sep } from 'node:path'
4
4
  import type { Task } from './spec-types.js'
5
5
 
6
6
  // ── Path normalization ────────────────────────────────────────────────────────
@@ -164,69 +164,82 @@ export function determineFsCaseSensitivity(): boolean {
164
164
  // ── Symlink security scan ─────────────────────────────────────────────────────
165
165
 
166
166
  /**
167
- * Before task execution: scan each file in the task's files[] partition.
168
- * If any resolved symlink target escapes the basePath directory, throw symlink_escape.
167
+ * Where a write through the link at `absLink` lands, every link on the way
168
+ * followed. A link to something not there yet (a build output, say) lands
169
+ * where its target would be created. Null when even that cannot be told.
169
170
  */
170
- export function scanSymlinks(files: string[], basePath: string): void {
171
- const realBase = realpathSync(resolve(basePath))
171
+ function linkTarget(absLink: string): string | null {
172
+ try {
173
+ return realpathSync(absLink)
174
+ } catch { /* a link to nothing yet */ }
175
+ let target: string
176
+ try {
177
+ target = resolve(dirname(absLink), readlinkSync(absLink))
178
+ } catch {
179
+ return null
180
+ }
181
+ const missing: string[] = []
182
+ for (let dir = target; ; dir = dirname(dir)) {
183
+ try {
184
+ return join(realpathSync(dir), ...missing)
185
+ } catch { /* not there either: try its parent */ }
186
+ if (dirname(dir) === dir) return null
187
+ missing.unshift(basename(dir))
188
+ }
189
+ }
172
190
 
173
- for (const file of files) {
174
- const absPath = join(realBase, normalizePath(file))
175
- let stat: ReturnType<typeof lstatSync>
191
+ /** The first of `paths` (relative to `realBase`) that is a symlink leading out of it. */
192
+ function escapingLink(realBase: string, paths: Iterable<string>): { path: string; resolved: boolean } | null {
193
+ for (const rel of paths) {
194
+ const abs = join(realBase, rel)
176
195
  try {
177
- stat = lstatSync(absPath)
196
+ if (!lstatSync(abs).isSymbolicLink()) continue
178
197
  } catch {
179
- continue // file doesn't exist yet — skip
198
+ continue // not there (yet)
180
199
  }
200
+ const target = linkTarget(abs)
201
+ if (target === null) return { path: rel, resolved: false }
202
+ if (target !== realBase && !target.startsWith(realBase + sep)) return { path: rel, resolved: true }
203
+ }
204
+ return null
205
+ }
181
206
 
182
- if (stat.isSymbolicLink()) {
183
- let realTarget: string
184
- try {
185
- realTarget = realpathSync(absPath)
186
- } catch {
187
- throw new Error(`symlink_escape: symlink at "${file}" could not be resolved`)
188
- }
207
+ /** The directories above a path: `a/b/c` → `a`, `a/b`. */
208
+ function parentsOf(rel: string): string[] {
209
+ const parts = rel.replace(/\/+$/, '').split('/')
210
+ return parts.slice(0, -1).map((_, i) => parts.slice(0, i + 1).join('/'))
211
+ }
189
212
 
190
- if (!realTarget.startsWith(realBase + '/') && realTarget !== realBase) {
191
- throw new Error(
192
- `symlink_escape: "${file}" is a symlink that resolves outside the partition`,
193
- )
194
- }
195
- }
196
- }
213
+ /**
214
+ * Before task execution: no declared path may lead out of `basePath` through a
215
+ * symlink. Checked are the declared paths, the directories above them, and
216
+ * each of `trackedLinks` (the links git tracks, from the worktree) inside a
217
+ * declared directory, since a write through any of them lands wherever the
218
+ * link points. Throws symlink_escape.
219
+ */
220
+ export function scanSymlinks(files: string[], basePath: string, trackedLinks: string[] = []): void {
221
+ const realBase = realpathSync(resolve(basePath))
222
+ const declared = files.map(normalizePath)
223
+ const links = trackedLinks.filter(link => declared.some(file => pathsOverlap(file, link)))
224
+ const bad = escapingLink(realBase, new Set([...declared, ...declared.flatMap(parentsOf), ...links]))
225
+ if (!bad) return
226
+ throw new Error(bad.resolved
227
+ ? `symlink_escape: "${bad.path}" is a symlink that resolves outside the partition`
228
+ : `symlink_escape: symlink at "${bad.path}" could not be resolved`)
197
229
  }
198
230
 
199
231
  /**
200
- * After task execution: scan files[] in the worktree for new symlinks that escape the partition.
201
- * Throws symlink_escape_post_task if any symlink target is outside worktreePath.
232
+ * After task execution: no new symlink may lead out of the worktree. Checked
233
+ * are the declared paths and every path in `changed` (what the task's commit
234
+ * changed, from git), so a link added inside a declared directory, or outside
235
+ * the task's paths altogether, is found too: all of it merges.
236
+ * Throws symlink_escape_post_task.
202
237
  */
203
- export function scanNewSymlinks(worktreePath: string, files: string[]): void {
238
+ export function scanNewSymlinks(worktreePath: string, files: string[], changed: string[] = []): void {
204
239
  const realBase = realpathSync(resolve(worktreePath))
205
-
206
- for (const file of files) {
207
- const absPath = join(realBase, normalizePath(file))
208
- let stat: ReturnType<typeof lstatSync>
209
- try {
210
- stat = lstatSync(absPath)
211
- } catch {
212
- continue
213
- }
214
-
215
- if (stat.isSymbolicLink()) {
216
- let realTarget: string
217
- try {
218
- realTarget = realpathSync(absPath)
219
- } catch {
220
- throw new Error(
221
- `symlink_escape_post_task: "${file}" is a new symlink that cannot be resolved`,
222
- )
223
- }
224
-
225
- if (!realTarget.startsWith(realBase + '/') && realTarget !== realBase) {
226
- throw new Error(
227
- `symlink_escape_post_task: "${file}" is a new symlink that escapes the partition`,
228
- )
229
- }
230
- }
231
- }
240
+ const bad = escapingLink(realBase, new Set([...files.map(normalizePath), ...changed]))
241
+ if (!bad) return
242
+ throw new Error(bad.resolved
243
+ ? `symlink_escape_post_task: "${bad.path}" is a new symlink that escapes the partition`
244
+ : `symlink_escape_post_task: "${bad.path}" is a new symlink that cannot be resolved`)
232
245
  }
@@ -103,7 +103,7 @@ describe('DB creation', () => {
103
103
  const db = new DatabaseSync(dbPath)
104
104
  const row = db.prepare('PRAGMA user_version').get() as { user_version: number }
105
105
  db.close()
106
- expect(row.user_version).toBe(14)
106
+ expect(row.user_version).toBe(15)
107
107
  })
108
108
 
109
109
  it('creates all required tables', () => {
@@ -131,7 +131,7 @@ describe('DB creation', () => {
131
131
  store2.close()
132
132
  // Reassign so afterEach does not double-close
133
133
  store = createConvoyStore(dbPath)
134
- expect(row.user_version).toBe(14)
134
+ expect(row.user_version).toBe(15)
135
135
  })
136
136
  })
137
137
 
@@ -209,7 +209,7 @@ describe('schema migration', () => {
209
209
 
210
210
  expect(cols.map(c => c.name)).toContain('adapter')
211
211
  // v1 chains through v2→v3→v4→...→v12→v13→v14 in one init, so final version is 14
212
- expect(version.user_version).toBe(14)
212
+ expect(version.user_version).toBe(15)
213
213
  })
214
214
 
215
215
  it('schema migration v2 to v3 adds cost columns', () => {
@@ -295,7 +295,7 @@ describe('schema migration', () => {
295
295
  expect(convoyColNames).toContain('total_tokens')
296
296
  expect(convoyColNames).toContain('total_cost_usd')
297
297
 
298
- expect(version.user_version).toBe(14)
298
+ expect(version.user_version).toBe(15)
299
299
  })
300
300
 
301
301
  it('schema migration v1 to v3 chains correctly in a single init', () => {
@@ -381,7 +381,7 @@ describe('schema migration', () => {
381
381
  expect(convoyColNames).toContain('total_tokens')
382
382
  expect(convoyColNames).toContain('total_cost_usd')
383
383
 
384
- expect(version.user_version).toBe(14)
384
+ expect(version.user_version).toBe(15)
385
385
  })
386
386
 
387
387
  it('schema migration v3 to v4 creates pipeline table and adds pipeline_id to convoy', () => {
@@ -464,7 +464,7 @@ describe('schema migration', () => {
464
464
 
465
465
  expect(convoyCols.map(c => c.name)).toContain('pipeline_id')
466
466
  expect(tables.map(t => t.name)).toContain('pipeline')
467
- expect(version.user_version).toBe(14)
467
+ expect(version.user_version).toBe(15)
468
468
  })
469
469
  })
470
470
 
@@ -1458,7 +1458,7 @@ describe('schema migration v5 → v6', () => {
1458
1458
  v5Verify.close()
1459
1459
  migratedStore.close()
1460
1460
 
1461
- expect(row.user_version).toBe(14)
1461
+ expect(row.user_version).toBe(15)
1462
1462
  expect(taskStepTable?.name).toBe('task_step')
1463
1463
  expect(convoy?.id).toBe('convoy-auto')
1464
1464
  expect(task?.id).toBe('task-auto')
@@ -1628,7 +1628,7 @@ describe('schema migration v6→v7 (drift detection columns)', () => {
1628
1628
 
1629
1629
  expect(cols.map(c => c.name)).toContain('drift_score')
1630
1630
  expect(cols.map(c => c.name)).toContain('drift_retried')
1631
- expect(version.user_version).toBe(14)
1631
+ expect(version.user_version).toBe(15)
1632
1632
  })
1633
1633
 
1634
1634
  it('new databases include drift_score and drift_retried in CREATE TABLE', () => {
@@ -1862,7 +1862,7 @@ describe('migration full chain v4→v10', () => {
1862
1862
  const verifyDb = new DatabaseSync(chainDbPath)
1863
1863
  verifyDb.exec('PRAGMA foreign_keys = 0')
1864
1864
  const version = (verifyDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version
1865
- expect(version).toBe(14)
1865
+ expect(version).toBe(15)
1866
1866
 
1867
1867
  // Verify all new tables exist
1868
1868
  const tables = (verifyDb.prepare("SELECT name FROM sqlite_master WHERE type='table'").all() as Array<{ name: string }>).map(t => t.name)
@@ -1959,7 +1959,7 @@ describe('migration v12 → v13', () => {
1959
1959
 
1960
1960
  expect(cols).not.toContain('compaction_count')
1961
1961
  expect(cols).not.toContain('discovered_issues')
1962
- expect(version).toBe(14)
1962
+ expect(version).toBe(15)
1963
1963
 
1964
1964
  // The rows, and the fields beside the dropped ones, survive the rewrite.
1965
1965
  expect(convoy?.name).toBe('Kept')
@@ -2666,7 +2666,7 @@ describe('v9→v10 migration', () => {
2666
2666
  // Verify version = 11
2667
2667
  const verifyDb = new DatabaseSync(migDb)
2668
2668
  const version = (verifyDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version
2669
- expect(version).toBe(14)
2669
+ expect(version).toBe(15)
2670
2670
 
2671
2671
  // Verify new REAL columns exist
2672
2672
  const convoyCols = (verifyDb.prepare('PRAGMA table_info(convoy)').all() as Array<{ name: string }>).map(c => c.name)
@@ -17,7 +17,7 @@ import type {
17
17
  TaskStepRecord,
18
18
  } from './types.js'
19
19
 
20
- const SCHEMA_VERSION = 14
20
+ const SCHEMA_VERSION = 15
21
21
 
22
22
  // ── Size limits (bytes) ────────────────────────────────────────────────────────
23
23
  const LIMIT_SPEC_YAML = 256 * 1024 // 256 KB
@@ -65,7 +65,7 @@ export type TaskStatusExtra = Partial<
65
65
  | 'worker_id' | 'worktree' | 'output' | 'exit_code' | 'started_at' | 'finished_at'
66
66
  | 'retries' | 'prompt_tokens' | 'completion_tokens' | 'total_tokens' | 'cost_usd' | 'prompt'
67
67
  | 'contract_result' | 'model' | 'cache_read_tokens' | 'cache_write_tokens' | 'cost_estimated'
68
- | 'retry_note' | 'branch'
68
+ | 'retry_note' | 'branch' | 'merged_commit'
69
69
  >
70
70
  >
71
71
 
@@ -73,7 +73,7 @@ const TASK_EXTRA_FIELDS = [
73
73
  'worker_id', 'worktree', 'output', 'exit_code', 'started_at', 'finished_at',
74
74
  'retries', 'prompt_tokens', 'completion_tokens', 'total_tokens', 'cost_usd', 'prompt',
75
75
  'contract_result', 'model', 'cache_read_tokens', 'cache_write_tokens', 'cost_estimated',
76
- 'retry_note', 'branch',
76
+ 'retry_note', 'branch', 'merged_commit',
77
77
  ] as const
78
78
 
79
79
  export interface ConvoyStore {
@@ -293,6 +293,7 @@ class ConvoyStoreImpl implements ConvoyStore {
293
293
  cost_estimated INTEGER NOT NULL DEFAULT 0,
294
294
  retry_note TEXT,
295
295
  branch TEXT,
296
+ merged_commit TEXT,
296
297
  PRIMARY KEY (id, convoy_id)
297
298
  );
298
299
 
@@ -464,6 +465,10 @@ class ConvoyStoreImpl implements ConvoyStore {
464
465
  migrateSchema(this.db, this.dbPath, 13, 14)
465
466
  version = 14
466
467
  }
468
+ if (version === 14) {
469
+ migrateSchema(this.db, this.dbPath, 14, 15)
470
+ version = 15
471
+ }
467
472
  }
468
473
 
469
474
  insertConvoy(
@@ -1565,6 +1570,12 @@ export function migrateSchema(db: DatabaseSync, dbPath: string, fromVersion: num
1565
1570
  addColumnIfMissing(db, 'convoy', 'cost_estimated', 'INTEGER NOT NULL DEFAULT 0')
1566
1571
  addColumnIfMissing(db, 'convoy', 'adapter', 'TEXT')
1567
1572
  }
1573
+ if (v === 14) {
1574
+ // What a task merged. A run that died between the merge and the task's
1575
+ // "done" left it running, and resume ran work already on the branch a
1576
+ // second time.
1577
+ addColumnIfMissing(db, 'task', 'merged_commit', 'TEXT')
1578
+ }
1568
1579
  db.exec('COMMIT')
1569
1580
  } catch (err) {
1570
1581
  try { db.exec('ROLLBACK') } catch { /* ignore */ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `interrupted` is a run stopped by SIGINT or SIGTERM: its running tasks went
2
+ * `interrupted` is a run stopped by SIGINT, SIGTERM or SIGHUP: its running tasks went
3
3
  * back to pending, and `convoy resume` carries on from there.
4
4
  */
5
5
  export type ConvoyStatus = 'pending' | 'running' | 'done' | 'failed' | 'gate-failed' | 'hook-failed' | 'interrupted'
@@ -98,6 +98,12 @@ export interface TaskRecord {
98
98
  retry_note?: string | null
99
99
  /** A worker branch kept because its work could not be merged. */
100
100
  branch?: string | null
101
+ /**
102
+ * The worker commit that merged into the convoy branch, written the moment
103
+ * the merge lands. From then on the task is done, whatever happens before
104
+ * its row says so.
105
+ */
106
+ merged_commit?: string | null
101
107
  }
102
108
 
103
109
  export interface WorkerRecord {
@@ -305,6 +311,8 @@ export type ConvoyEventType =
305
311
  cost_usd?: number | null
306
312
  estimated?: boolean
307
313
  model?: string | null
314
+ /** Its work had merged before the run could record it done (see `markMergedDone`). */
315
+ recovered?: boolean
308
316
  }
309
317
  }
310
318
  | { type: 'task_failed'; data?: { reason: string; message?: string; worker_id?: string; gate?: string; hook?: string; exit_code?: number } }
@@ -1,4 +1,4 @@
1
- import { mkdtempSync, rmSync, realpathSync } from 'node:fs'
1
+ import { mkdirSync, mkdtempSync, rmSync, realpathSync, symlinkSync, writeFileSync } from 'node:fs'
2
2
  import { tmpdir } from 'node:os'
3
3
  import { join } from 'node:path'
4
4
  import { execFile as execFileCb } from 'node:child_process'
@@ -212,6 +212,29 @@ describe('commitAll and changes', () => {
212
212
  })
213
213
  })
214
214
 
215
+ describe('changes and symlinks, by name as it is', () => {
216
+ it('reports a file with a non-ASCII name as it is, not quoted', async () => {
217
+ const path = await manager.create('worker1', 'HEAD')
218
+ const start = await manager.head!(path)
219
+ writeFileSync(join(path, 'résumé.md'), 'x\n')
220
+ await manager.commitAll!(path, 'add résumé.md')
221
+ expect((await manager.changes!(path, start!))!.files).toEqual(['résumé.md'])
222
+ })
223
+
224
+ it('lists the symlinks git tracks under the paths it is given, and nothing else', async () => {
225
+ const path = await manager.create('worker1', 'HEAD')
226
+ mkdirSync(join(path, 'docs'))
227
+ writeFileSync(join(path, 'docs', 'file.txt'), 'x\n')
228
+ symlinkSync('file.txt', join(path, 'docs', 'alias.txt'))
229
+ symlinkSync(tmpDir, join(path, 'docs', 'café'))
230
+ symlinkSync(tmpDir, join(path, 'elsewhere'))
231
+ await manager.commitAll!(path, 'links')
232
+ symlinkSync('file.txt', join(path, 'docs', 'untracked-link'))
233
+ expect((await manager.symlinks!(path, ['docs/'])).sort()).toEqual(['docs/alias.txt', 'docs/café'])
234
+ expect(await manager.symlinks!(path, [])).toEqual([])
235
+ })
236
+ })
237
+
215
238
  describe('ensureRootWorktree', () => {
216
239
  it('creates the branch from the base and checks it out in its own worktree', async () => {
217
240
  const { ensureRootWorktree } = await import('./worktree.js')
@@ -48,6 +48,8 @@ export interface WorktreeManager {
48
48
  head?(worktreePath: string): Promise<string | null>
49
49
  /** Files and diff between `sinceRef` and the worktree's HEAD. */
50
50
  changes?(worktreePath: string, sinceRef: string): Promise<WorktreeChanges | null>
51
+ /** The symlinks git tracks in the worktree under `paths`, as repository-relative paths. */
52
+ symlinks?(worktreePath: string, paths: string[]): Promise<string[]>
51
53
  }
52
54
 
53
55
  /** The branch name a worker's worktree is created on. */
@@ -268,8 +270,10 @@ export function createWorktreeManager(repoRoot: string): WorktreeManager {
268
270
 
269
271
  async function changes(worktreePath: string, sinceRef: string): Promise<WorktreeChanges | null> {
270
272
  try {
271
- const files = (await git(['diff', '--name-only', `${sinceRef}..HEAD`], worktreePath))
272
- .split('\n').map((s) => s.trim()).filter(Boolean)
273
+ // `-z`: each path as it is. Without it git quotes a name with non-ASCII
274
+ // characters, and nothing that reads the list finds that file.
275
+ const files = (await git(['diff', '--name-only', '-z', `${sinceRef}..HEAD`], worktreePath))
276
+ .split('\0').filter(Boolean)
273
277
  const diff = await git(['diff', `${sinceRef}..HEAD`], worktreePath)
274
278
  return { files, diff }
275
279
  } catch {
@@ -277,7 +281,17 @@ export function createWorktreeManager(repoRoot: string): WorktreeManager {
277
281
  }
278
282
  }
279
283
 
280
- return { create, remove, list, removeAll, commitAll, head, changes }
284
+ async function symlinks(worktreePath: string, paths: string[]): Promise<string[]> {
285
+ // No paths would list the whole repository.
286
+ if (paths.length === 0) return []
287
+ // Each entry: `<mode> <object> <stage>\t<path>`; 120000 is a symlink.
288
+ return (await git(['--literal-pathspecs', 'ls-files', '-s', '-z', '--', ...paths], worktreePath))
289
+ .split('\0')
290
+ .filter((entry) => entry.startsWith('120000 '))
291
+ .map((entry) => entry.slice(entry.indexOf('\t') + 1))
292
+ }
293
+
294
+ return { create, remove, list, removeAll, commitAll, head, changes, symlinks }
281
295
  }
282
296
 
283
297
  // ── The convoy's integration checkout ───────────────────────────────────────
@@ -1,6 +1,9 @@
1
+ import { spawn } from 'node:child_process'
1
2
  import { mkdtempSync, writeFileSync, chmodSync, readFileSync, rmSync, realpathSync, existsSync } from 'node:fs'
3
+ import { createRequire } from 'node:module'
2
4
  import { tmpdir } from 'node:os'
3
5
  import { join } from 'node:path'
6
+ import { pathToFileURL } from 'node:url'
4
7
  import { describe, it, expect, afterEach } from 'vitest'
5
8
  import type { Task } from '../../convoy/spec-types.js'
6
9
  import { runAgent, stopTask, liveAgentCount, timeoutMsOf, promptOf } from './agent-process.js'
@@ -173,3 +176,59 @@ describe.skipIf(!posix)('running an agent CLI', () => {
173
176
  expect(await waitFor(() => !alive(childPid))).toBe(true)
174
177
  })
175
178
  })
179
+
180
+ describe.skipIf(!posix)('when a signal ends this process', () => {
181
+ // Each agent leads its own process group, so the terminal's Ctrl+C and its
182
+ // hangup never reach it. A signal's default action ends this process with no
183
+ // 'exit' event, so the exit hook never ran, and the agent kept editing its
184
+ // worktree and spending tokens with nobody watching. Planning, which handles
185
+ // no signal itself, left its agent running on every Ctrl+C.
186
+ const dirs: string[] = []
187
+ afterEach(() => {
188
+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true })
189
+ })
190
+
191
+ it.each(['SIGHUP', 'SIGINT', 'SIGTERM'] as const)('%s leaves no agent running, and still ends the process', async (sig) => {
192
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'oc-signal-')))
193
+ dirs.push(dir)
194
+ const agent = join(dir, 'fake-agent')
195
+ writeFileSync(agent, `#!/bin/sh\nsleep 60 &\necho $! > "${dir}/child"\necho $$ > "${dir}/agent"\nwait\n`)
196
+ chmodSync(agent, 0o755)
197
+ // A command that starts an agent and handles no signal itself.
198
+ const driver = join(dir, 'driver.mjs')
199
+ writeFileSync(driver, [
200
+ `const { runAgent } = await import(${JSON.stringify(pathToFileURL(join(import.meta.dirname, 'agent-process.ts')).href)})`,
201
+ `runAgent({ id: 't', prompt: 'p', agent: 'developer', timeout: '5m', depends_on: [], files: [], description: '', max_retries: 0 },`,
202
+ ` { command: ${JSON.stringify(agent)}, args: [], cwd: ${JSON.stringify(dir)} })`,
203
+ `setInterval(() => {}, 1000)`,
204
+ ].join('\n'))
205
+ const tsx = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href
206
+ const child = spawn(process.execPath, ['--import', tsx, driver], { cwd: dir, stdio: 'ignore' })
207
+ const ended = new Promise<NodeJS.Signals | null>((r) => child.on('exit', (_code, signal) => r(signal)))
208
+
209
+ expect(await waitFor(() => existsSync(join(dir, 'agent')) && existsSync(join(dir, 'child')), 15_000)).toBe(true)
210
+ const agentPid = Number(readFileSync(join(dir, 'agent'), 'utf8').trim())
211
+ const childPid = Number(readFileSync(join(dir, 'child'), 'utf8').trim())
212
+ child.kill(sig)
213
+
214
+ try {
215
+ expect(await ended).toBe(sig)
216
+ expect(await waitFor(() => !alive(agentPid) && !alive(childPid))).toBe(true)
217
+ } finally {
218
+ try { process.kill(-agentPid, 'SIGKILL') } catch { /* gone */ }
219
+ }
220
+ }, 30_000)
221
+
222
+ it('listens for those signals only while an agent runs', async () => {
223
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'oc-signal-')))
224
+ dirs.push(dir)
225
+ const agent = join(dir, 'fake-agent')
226
+ writeFileSync(agent, '#!/bin/sh\nsleep 0.3\n')
227
+ chmodSync(agent, 0o755)
228
+ const before = ['SIGHUP', 'SIGINT', 'SIGTERM'].map((s) => process.listenerCount(s))
229
+ const running = runAgent(task('guarded'), { command: agent, args: [], cwd: dir })
230
+ expect(['SIGHUP', 'SIGINT', 'SIGTERM'].map((s) => process.listenerCount(s))).toEqual(before.map((n) => n + 1))
231
+ await running
232
+ expect(['SIGHUP', 'SIGINT', 'SIGTERM'].map((s) => process.listenerCount(s))).toEqual(before)
233
+ })
234
+ })