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
@@ -27,14 +27,40 @@ export class MergeError extends Error {
27
27
  }
28
28
  }
29
29
 
30
+ /**
31
+ * The worktree is no longer the commit its checks passed: something wrote to
32
+ * it, or moved its HEAD, after the secret scan and the review had looked.
33
+ * Nothing is merged; everything there is kept on the worker's branch.
34
+ */
35
+ export class ChangedAfterChecksError extends MergeError {
36
+ constructor(
37
+ public readonly changedFiles: string[],
38
+ message: string,
39
+ ) {
40
+ super(message)
41
+ this.name = 'ChangedAfterChecksError'
42
+ }
43
+ }
44
+
45
+ export interface MergeOptions {
46
+ /**
47
+ * The commit the task's checks passed. Merged as it is, by its id: the
48
+ * worktree must still be exactly that commit, clean, or the merge is
49
+ * refused. Without it the queue commits whatever the worktree holds and
50
+ * merges that.
51
+ */
52
+ commit?: string
53
+ }
54
+
30
55
  export interface MergeQueue {
31
56
  /**
32
- * Merge a worker's branch into the target branch, one merge at a time.
33
- * Commits anything the worker left uncommitted first. Throws
34
- * `MergeConflictError` on a conflict and `MergeError` on anything else —
35
- * a merge that did not land is never reported as one that did.
57
+ * Merge a worker's work into the target branch, one merge at a time. With
58
+ * `opts.commit`, that commit and nothing else; without it, whatever the
59
+ * worktree holds, committed first. Throws `MergeConflictError` on a
60
+ * conflict and `MergeError` on anything else — a merge that did not land is
61
+ * never reported as one that did.
36
62
  */
37
- merge(worktreePath: string, worktreeBranch: string, targetBranch: string): Promise<MergeResult>
63
+ merge(worktreePath: string, worktreeBranch: string, targetBranch: string, opts?: MergeOptions): Promise<MergeResult>
38
64
  }
39
65
 
40
66
  /** A promise chain: each merge waits for the previous one to settle. */
@@ -73,17 +99,43 @@ export function createMergeQueue(
73
99
  worktreePath: string,
74
100
  worktreeBranch: string,
75
101
  targetBranch: string,
102
+ opts: MergeOptions = {},
76
103
  ): Promise<MergeResult> {
77
104
  if (!isInside(worktreesDir, worktreePath)) {
78
105
  throw new Error(`Path "${worktreePath}" is outside the managed worktrees directory`)
79
106
  }
107
+ const wt = resolve(worktreePath)
108
+ // Asked first, because the branch is moved below and moving a ref that
109
+ // is not there would create it.
110
+ try {
111
+ await git(['rev-parse', '--verify', '--quiet', `refs/heads/${worktreeBranch}`], wt)
112
+ } catch {
113
+ throw new MergeError(`there is no branch ${worktreeBranch} to keep the task's work on`)
114
+ }
80
115
 
81
116
  let commit: string
117
+ if (opts.commit) {
118
+ commit = opts.commit
119
+ await refuseChangedSinceChecks(wt, worktreeBranch, commit)
120
+ } else {
121
+ try {
122
+ await commitAllIn(wt, `convoy: ${worktreeBranch} completed`)
123
+ commit = (await git(['rev-parse', '--verify', 'HEAD^{commit}'], wt)).trim()
124
+ } catch (err) {
125
+ throw new MergeError(`could not commit the task's work: ${firstLine((err as { stderr?: string }).stderr) || (err as Error).message}`)
126
+ }
127
+ }
128
+
129
+ // The worker's branch holds the commit being merged, whatever the agent
130
+ // did with its checkout. An agent told to "branch first" runs
131
+ // `git checkout -b` in its worktree; its commits go to that branch, and
132
+ // `convoy-<id>` stays where the task started. The branch kept after a
133
+ // failed merge is how the person gets the work back, so it has to be the
134
+ // one with the work on it.
82
135
  try {
83
- await commitAllIn(resolve(worktreePath), `convoy: ${worktreeBranch} completed`)
84
- commit = (await git(['rev-parse', '--verify', 'HEAD^{commit}'], resolve(worktreePath))).trim()
136
+ await git(['update-ref', `refs/heads/${worktreeBranch}`, commit], wt)
85
137
  } catch (err) {
86
- throw new MergeError(`could not commit the task's work: ${firstLine((err as { stderr?: string }).stderr) || (err as Error).message}`)
138
+ throw new MergeError(`could not record the task's work on ${worktreeBranch}: ${firstLine((err as { stderr?: string }).stderr) || (err as Error).message}`)
87
139
  }
88
140
 
89
141
  try {
@@ -93,12 +145,15 @@ export function createMergeQueue(
93
145
  throw new MergeError(`could not check out ${targetBranch}: ${firstLine((err as { stderr?: string }).stderr) || (err as Error).message}`)
94
146
  }
95
147
 
148
+ // The commit, by its id, not the branch by its name. Merging the name
149
+ // merged wherever `convoy-<id>` pointed — the task's starting commit when
150
+ // the agent had switched branch — so git said "Already up to date", the
151
+ // task was recorded as merged with a commit the target did not have, and
152
+ // cleanup deleted the only copy. The message still names the branch, as
153
+ // git's own would.
154
+ let stdout: string
96
155
  try {
97
- const stdout = await mergeIn(target, ['--no-edit', worktreeBranch])
98
- if (stdout.includes('Already up to date')) {
99
- return { success: true, conflicted: false, message: 'No changes to merge', commit }
100
- }
101
- return { success: true, conflicted: false, message: 'Merged successfully', commit }
156
+ stdout = await mergeIn(target, ['--no-edit', '-m', `Merge branch '${worktreeBranch}'`, commit])
102
157
  } catch (err) {
103
158
  const error = err as { code?: number | string; stderr?: string; stdout?: string; message?: string }
104
159
  const text = `${error.stdout ?? ''}\n${error.stderr ?? ''}`
@@ -115,10 +170,68 @@ export function createMergeQueue(
115
170
  if (text.includes('CONFLICT')) throw new MergeConflictError(conflictingFiles)
116
171
  throw new MergeError(firstLine(error.stderr) || firstLine(error.stdout) || error.message || 'git merge failed')
117
172
  }
173
+
174
+ // Asked of the target, not taken from git's exit code: the task is about
175
+ // to be recorded as merged and its worktree and branch deleted, which is
176
+ // only safe when the commit really is there.
177
+ try {
178
+ await git(['merge-base', '--is-ancestor', commit, 'HEAD'], target)
179
+ } catch {
180
+ throw new MergeError(`the merge finished, but ${commit.slice(0, 12)} is not on ${targetBranch}`)
181
+ }
182
+ if (stdout.includes('Already up to date')) {
183
+ return { success: true, conflicted: false, message: 'No changes to merge', commit }
184
+ }
185
+ return { success: true, conflicted: false, message: 'Merged successfully', commit }
186
+ }
187
+
188
+ /**
189
+ * Throw unless the worktree is still exactly `checked`: no file changed or
190
+ * added since, and HEAD where it was.
191
+ *
192
+ * The queue used to `git add -A` here and merge the result, after the checks
193
+ * had run. Per-task gates, the secret scan, the review and the `post_task`
194
+ * hooks all come between the commit they look at and the merge, so a gate
195
+ * such as `eslint --fix`, or an agent hook, wrote files that went to the
196
+ * branch with nothing having looked at them. What was checked is what
197
+ * merges; anything else stops the task.
198
+ *
199
+ * Nothing is thrown away: the later changes are committed on top and the
200
+ * worker's branch moved there, so the branch kept for the person holds the
201
+ * checked commit and everything after it.
202
+ */
203
+ async function refuseChangedSinceChecks(wt: string, worktreeBranch: string, checked: string): Promise<void> {
204
+ let head: string
205
+ let changed: string[]
206
+ try {
207
+ head = (await git(['rev-parse', '--verify', 'HEAD^{commit}'], wt)).trim()
208
+ changed = (await git(['status', '--porcelain', '-z', '--untracked-files=all'], wt))
209
+ .split('\0')
210
+ .filter(Boolean)
211
+ // `XY path`; the second entry of a rename, its old path, has no status.
212
+ .filter((entry) => /^[ MADRCUT?!]{2} /.test(entry))
213
+ .map((entry) => entry.slice(3))
214
+ } catch (err) {
215
+ throw new MergeError(`could not read the task's worktree: ${firstLine((err as { stderr?: string }).stderr) || (err as Error).message}`)
216
+ }
217
+ if (head === checked && changed.length === 0) return
218
+
219
+ try {
220
+ await commitAllIn(wt, `convoy: ${worktreeBranch} changed after its checks, not merged`)
221
+ await git(['update-ref', `refs/heads/${worktreeBranch}`, 'HEAD'], wt)
222
+ } catch { /* the error below still says what changed */ }
223
+
224
+ const listed = changed.slice(0, 10).join(', ') + (changed.length > 10 ? `, and ${changed.length - 10} more` : '')
225
+ throw new ChangedAfterChecksError(
226
+ changed,
227
+ changed.length > 0
228
+ ? `files changed after the task's checks ran, so nothing was merged: ${listed}. Something run after the secret scan and review wrote them, most likely a post_task hook; a command that fixes files belongs in the task's gates, whose changes are checked and merged with the work`
229
+ : `the worktree moved from ${checked.slice(0, 12)} to ${head.slice(0, 12)} after the task's checks ran, so nothing was merged`,
230
+ )
118
231
  }
119
232
 
120
233
  return {
121
- merge: (worktreePath, worktreeBranch, targetBranch) =>
122
- serialize(() => mergeOnce(worktreePath, worktreeBranch, targetBranch)),
234
+ merge: (worktreePath, worktreeBranch, targetBranch, opts) =>
235
+ serialize(() => mergeOnce(worktreePath, worktreeBranch, targetBranch, opts)),
123
236
  }
124
237
  }
@@ -1,4 +1,4 @@
1
- import { mkdirSync, mkdtempSync, rmSync, realpathSync, symlinkSync, writeFileSync } from 'node:fs'
1
+ import { existsSync, 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'
@@ -197,6 +197,21 @@ describe('removeAll with except', () => {
197
197
  })
198
198
  })
199
199
 
200
+ describe('removeAll with owner', () => {
201
+ it('removes only the worktrees and branches named for that convoy', async () => {
202
+ // The folder is shared by every checkout of the repository; another
203
+ // convoy's task worktrees in it may be running.
204
+ const mine = await manager.create('abc123-task-1', 'HEAD')
205
+ const theirs = await manager.create('def456-task-1', 'HEAD')
206
+ const lookalike = await manager.create('abc1234-task-1', 'HEAD')
207
+ await manager.removeAll({ owner: 'abc123' })
208
+ expect((await manager.list()).map(w => w.path).sort()).toEqual([theirs, lookalike].sort())
209
+ expect(existsSync(mine)).toBe(false)
210
+ const { stdout } = await execFile('git', ['branch', '--list', 'convoy-def456-task-1'], { cwd: tmpDir })
211
+ expect(stdout).toContain('convoy-def456-task-1')
212
+ })
213
+ })
214
+
200
215
  describe('commitAll and changes', () => {
201
216
  it('commits what the agent left uncommitted and reports it against the start commit', async () => {
202
217
  const { writeFileSync } = await import('node:fs')
@@ -37,8 +37,12 @@ export interface WorktreeManager {
37
37
  /** Remove a worktree; its branch goes too unless `keepBranch` — kept when its work could not be merged. */
38
38
  remove(worktreePath: string, opts?: { keepBranch?: boolean }): Promise<void>
39
39
  list(): Promise<WorktreeInfo[]>
40
- /** Remove every managed worktree except the paths in `except`. */
41
- removeAll(opts?: { except?: string[] }): Promise<void>
40
+ /**
41
+ * Remove every managed worktree except the paths in `except` — with
42
+ * `owner`, only the ones whose directory is named `<owner>-…`, a convoy's
43
+ * own task worktrees.
44
+ */
45
+ removeAll(opts?: { except?: string[]; owner?: string }): Promise<void>
42
46
  /**
43
47
  * Commit everything in a worktree. Returns true when a commit was made.
44
48
  * Optional so a test double can leave git out entirely.
@@ -245,10 +249,16 @@ export function createWorktreeManager(repoRoot: string): WorktreeManager {
245
249
  return all.filter((w) => realOrResolved(w.path).startsWith(dir + sep))
246
250
  }
247
251
 
248
- async function removeAll(opts: { except?: string[] } = {}): Promise<void> {
252
+ async function removeAll(opts: { except?: string[]; owner?: string } = {}): Promise<void> {
249
253
  const keep = new Set((opts.except ?? []).map(realOrResolved))
250
254
  for (const wt of await list()) {
251
255
  if (keep.has(realOrResolved(wt.path))) continue
256
+ // The worktrees folder belongs to the repository, not to one convoy: a
257
+ // convoy run from a linked checkout keeps its lock and its database in
258
+ // that checkout's `.opencastle/`, and its worktrees here beside every
259
+ // other convoy's. A resume that cleared the whole folder force-removed
260
+ // another live run's task worktrees, uncommitted agent work and all.
261
+ if (opts.owner && !basename(wt.path).startsWith(`${opts.owner}-`)) continue
252
262
  await remove(wt.path)
253
263
  }
254
264
  // A directory deleted by hand leaves its registration behind, and git then
package/src/cli/doctor.ts CHANGED
@@ -32,7 +32,8 @@ import { cliVersionOf, requiredEnvVars } from './layers.js';
32
32
  import type { CliContext, DoctorCheck, IdeChoice, Manifest } from './types.js';
33
33
  import { IDE_LABELS } from './types.js';
34
34
  import { c } from './prompt.js';
35
- import { readLock } from './lock.js';
35
+ import { readLock, priorIntegrations } from './lock.js';
36
+ import { rootFileLink } from './root-files.js';
36
37
 
37
38
  // ── Styled output helpers ─────────────────────────────────────
38
39
 
@@ -804,8 +805,18 @@ async function checkTornBlocks(
804
805
  }))
805
806
 
806
807
  const found: Array<{ rel: string; diagnosis: FileDiagnosis }> = []
808
+ // Root files that are links out of the project, which `sync` leaves alone
809
+ // (root-files.ts). Said, because the assistant reading one gets none of the
810
+ // project's instructions, and `init` was the only command that mentioned it.
811
+ const linkedOut: string[] = []
812
+ const ides = manifest.ides?.length ? manifest.ides : [manifest.ide]
807
813
  for (const { rel, markers } of files) {
808
814
  const abs = resolve(projectRoot, rel)
815
+ const link = rootFileLink(projectRoot, abs, ides)
816
+ if (link.kind === 'outside') {
817
+ linkedOut.push(`${rel} links to ${link.to}, outside the project, so sync leaves it alone and its assistant gets no OpenCastle instructions`)
818
+ continue
819
+ }
809
820
  if (!existsSync(abs)) continue
810
821
  // Guarded, like `checkSkillMatrix` twelve lines up. `doctor` is what people
811
822
  // run *because* something is wrong, and an unreadable root file made it die
@@ -857,6 +868,15 @@ async function checkTornBlocks(
857
868
  }
858
869
  }
859
870
 
871
+ if (found.length === 0 && linkedOut.length > 0) {
872
+ return {
873
+ label,
874
+ ok: true,
875
+ warning: true,
876
+ detail: linkedOut.join('; '),
877
+ fix: 'make it a file, or a link to a file within the project, and run npx opencastle sync',
878
+ }
879
+ }
860
880
  if (found.length === 0) return { label, ok: true, warning: false }
861
881
 
862
882
  // Every file, not the first. Returning as soon as one was found dropped a
@@ -967,6 +987,7 @@ export async function runAdapterChecks(
967
987
  ide as IdeChoice,
968
988
  includedServers(manifest),
969
989
  state ? teamAuditContext(state, ide as IdeChoice) : undefined,
990
+ priorIntegrations(projectRoot),
970
991
  ),
971
992
  );
972
993
  }
@@ -1101,6 +1122,7 @@ export default async function doctor({ pkgRoot, args }: CliContext): Promise<voi
1101
1122
  ide as IdeChoice,
1102
1123
  includedServers(manifest),
1103
1124
  state ? teamAuditContext(state, ide as IdeChoice) : undefined,
1125
+ priorIntegrations(projectRoot),
1104
1126
  ),
1105
1127
  );
1106
1128
 
@@ -3,7 +3,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync
3
3
  import { tmpdir } from 'node:os'
4
4
  import { dirname, join, resolve } from 'node:path'
5
5
  import { describe, it, expect, beforeEach, afterEach } from 'vitest'
6
- import { adoptForeignSkills, foreignSkills, skillFolders } from './foreign-skills.js'
6
+ import { adoptForeignSkills, foreignSkills, skillFolders, adoptForeignAgents, foreignAgents, agentFolders } from './foreign-skills.js'
7
7
 
8
8
  const skill = (name: string, extra = ''): string =>
9
9
  `---\nname: ${name}\ndescription: How to run the e2e tests. Use when running them.\n---\n${extra}\n1. npm run e2e\n`
@@ -64,6 +64,75 @@ describe('a skill another tool wrote into a compiled folder', () => {
64
64
  })
65
65
  })
66
66
 
67
+ const agent = (name: string, extra = ''): string =>
68
+ `---\nname: ${name}\ndescription: Reviews a diff for bugs. Use after a change.\ntools: Read, Grep, Glob\n---\n${extra}\nYou review code.\n`
69
+
70
+ describe('an agent another tool wrote into a compiled folder', () => {
71
+ let dir: string
72
+ const write = (rel: string, text: string): void => {
73
+ mkdirSync(dirname(join(dir, rel)), { recursive: true })
74
+ writeFileSync(join(dir, rel), text)
75
+ }
76
+
77
+ beforeEach(() => {
78
+ dir = mkdtempSync(join(tmpdir(), 'oc-foreign-agents-'))
79
+ })
80
+ afterEach(() => rmSync(dir, { recursive: true, force: true }))
81
+
82
+ it('finds the compiled agent folders among a target’s paths', () => {
83
+ expect(agentFolders(['.claude/agents/', '.claude/skills/', '.agents/', '.agents/agents/', '.github/agents/', '.cursor/rules/'])).toEqual([
84
+ '.claude/agents',
85
+ '.agents/agents',
86
+ '.github/agents',
87
+ ])
88
+ })
89
+
90
+ it('is any agent file but one OpenCastle writes or wrote, kept under the name its assistant knows it by', () => {
91
+ // Claude Code's `/agents`: `<name>.md`, the subagent's name in frontmatter.
92
+ write('.claude/agents/mine.md', agent('code-reviewer'))
93
+ // One of ours, current, and one an earlier compile wrote (the lock says so).
94
+ write('.claude/agents/developer.agent.md', agent('developer'))
95
+ write('.claude/agents/retired.agent.md', agent('retired'))
96
+ // Marked by an older release.
97
+ write('.claude/agents/marked.md', agent('marked', '<!-- ⚠️ This file is managed by OpenCastle. -->'))
98
+ // A name a source already compiles: kept beside it, not over it.
99
+ write('.claude/agents/developer.md', agent('developer'))
100
+ // A Copilot agent of someone's own; the same file in a second folder is one agent.
101
+ write('.github/agents/planner.agent.md', '---\nname: Release Planner\n---\n\nPlan releases.\n')
102
+ write('.agents/agents/planner.agent.md', '---\nname: Release Planner\n---\n\nPlan releases.\n')
103
+ // Not an agent file, and not at the top of the folder.
104
+ write('.claude/agents/notes.txt', 'notes\n')
105
+ write('.claude/agents/sub/deep.md', agent('deep'))
106
+ write(
107
+ '.opencastle/lock.json',
108
+ JSON.stringify({
109
+ lockfileVersion: 1,
110
+ opencastle: '1.12.0',
111
+ targets: ['claude-code'],
112
+ integrations: [],
113
+ layers: [{ id: 'core' }],
114
+ content: { 'agents/retired': { from: 'core', sha: 'x' } },
115
+ mcp: {},
116
+ context: { tokens: 0, instructions: 0, index: 0 },
117
+ }),
118
+ )
119
+
120
+ const found = foreignAgents(dir, ['.claude/agents', '.github/agents', '.agents/agents'], new Set(['agents/developer']))
121
+ expect(found).toEqual([
122
+ { name: 'developer-2', from: '.claude/agents/developer.md' },
123
+ { name: 'code-reviewer', from: '.claude/agents/mine.md' },
124
+ { name: 'planner', from: '.github/agents/planner.agent.md' },
125
+ ])
126
+
127
+ adoptForeignAgents(dir, found)
128
+ expect(readFileSync(join(dir, '.opencastle/agents/code-reviewer.agent.md'), 'utf8')).toBe(agent('code-reviewer'))
129
+ expect(existsSync(join(dir, '.opencastle/agents/developer-2.agent.md'))).toBe(true)
130
+ expect(existsSync(join(dir, '.opencastle/agents/planner.agent.md'))).toBe(true)
131
+ // Kept now, so not found again.
132
+ expect(foreignAgents(dir, ['.github/agents'], new Set(['agents/developer', 'agents/planner']))).toEqual([])
133
+ })
134
+ })
135
+
67
136
  const repoRoot = resolve(import.meta.dirname, '..', '..')
68
137
  const cli = join(repoRoot, 'bin', 'cli.mjs')
69
138
  const cliBuilt = existsSync(join(repoRoot, 'dist', 'cli', 'init.js'))
@@ -94,7 +163,7 @@ describe.skipIf(!cliBuilt)('sync and a skill another tool added', () => {
94
163
 
95
164
  const check = run('sync', '--check')
96
165
  expect(check.status).toBe(1)
97
- expect(check.out).toContain('Skills another tool added')
166
+ expect(check.out).toContain('Skills and agents another tool added')
98
167
  expect(check.out).not.toContain('Not produced by any source')
99
168
 
100
169
  const sync = run('sync', '--yes')
@@ -115,3 +184,43 @@ describe.skipIf(!cliBuilt)('sync and a skill another tool added', () => {
115
184
  expect(existsSync(join(projectRoot, '.opencastle/skills/old-release'))).toBe(false)
116
185
  })
117
186
  })
187
+
188
+ // Claude Code's `/agents` writes a project subagent into `.claude/agents/`,
189
+ // which a project compiled for Claude Code treats as compiled output: `sync`
190
+ // deleted it, uncommitted, with no copy anywhere.
191
+ describe.skipIf(!cliBuilt)('sync and an agent made after init', () => {
192
+ let projectRoot: string
193
+ const run = (...args: string[]): { status: number | null; out: string } => {
194
+ const r = spawnSync('node', [cli, ...args], { cwd: projectRoot, encoding: 'utf8', input: '' })
195
+ return { status: r.status, out: `${r.stdout}${r.stderr}` }
196
+ }
197
+
198
+ beforeEach(() => {
199
+ projectRoot = mkdtempSync(join(tmpdir(), 'oc-foreign-agent-sync-'))
200
+ execFileSync('git', ['init', '-q'], { cwd: projectRoot })
201
+ writeFileSync(join(projectRoot, 'package.json'), JSON.stringify({ name: 'demo' }))
202
+ mkdirSync(join(projectRoot, '.claude'))
203
+ execFileSync('node', [cli, 'init', '--yes'], { cwd: projectRoot, stdio: 'ignore' })
204
+ })
205
+ afterEach(() => rmSync(projectRoot, { recursive: true, force: true }))
206
+
207
+ it('keeps it as the team’s, still the subagent it was, and the check is clean after', () => {
208
+ writeFileSync(join(projectRoot, '.claude/agents/mine.md'), agent('code-reviewer'))
209
+
210
+ const check = run('sync', '--check')
211
+ expect(check.status).toBe(1)
212
+ expect(check.out).toContain('Skills and agents another tool added')
213
+
214
+ const sync = run('sync', '--yes')
215
+ expect(sync.status).toBe(0)
216
+ expect(sync.out).toContain('.claude/agents/mine.md → .opencastle/agents/code-reviewer.agent.md')
217
+ expect(sync.out).not.toContain('no longer produced by any source')
218
+ expect(readFileSync(join(projectRoot, '.opencastle/agents/code-reviewer.agent.md'), 'utf8')).toBe(agent('code-reviewer'))
219
+ // Compiled back for Claude Code under its own name, with the tools it was
220
+ // limited to: dropping them handed it every tool the session has.
221
+ const compiled = readFileSync(join(projectRoot, '.claude/agents/code-reviewer.agent.md'), 'utf8')
222
+ expect(compiled).toMatch(/^---\nname: code-reviewer\n/)
223
+ expect(compiled).toContain('tools: Read, Grep, Glob\n')
224
+ expect(run('sync', '--check').status).toBe(0)
225
+ })
226
+ })
@@ -1,6 +1,7 @@
1
- import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync } from 'node:fs'
1
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { readLock } from './lock.js'
4
+ import { parseFrontmatterMeta } from './adapters/frontmatter.js'
4
5
 
5
6
  /**
6
7
  * Skills another tool put in a folder OpenCastle compiles, kept instead of swept.
@@ -18,6 +19,13 @@ import { readLock } from './lock.js'
18
19
  * and compiles for every assistant. When in doubt it is kept: a skill an old
19
20
  * release left behind becomes a team skill someone can delete, never the other
20
21
  * way round.
22
+ *
23
+ * Agents the same way. Claude Code's `/agents` writes a subagent into
24
+ * `.claude/agents/`, and Copilot, Codex and OpenCode have folders of their own,
25
+ * all of them compiled output here: `sync` deleted an agent made in the
26
+ * ordinary course of using the assistant, uncommitted work with no copy. One
27
+ * that no source produces and carries no marker moves into
28
+ * `.opencastle/agents/` instead.
21
29
  */
22
30
 
23
31
  const MARKER = /managed by OpenCastle|OpenCastle managed|generated by OpenCastle/i
@@ -72,3 +80,87 @@ export function adoptForeignSkills(projectRoot: string, skills: readonly Foreign
72
80
  cpSync(join(projectRoot, s.from), join(projectRoot, '.opencastle', 'skills', s.name), { recursive: true })
73
81
  }
74
82
  }
83
+
84
+ export interface ForeignAgent {
85
+ /** The name it is kept under: `.opencastle/agents/<name>.agent.md`. */
86
+ name: string
87
+ /** Where it was found, project-relative. */
88
+ from: string
89
+ }
90
+
91
+ /** The compiled agent folders among a target's framework paths: `.claude/agents`, `.github/agents`… */
92
+ export function agentFolders(framework: readonly string[]): string[] {
93
+ return [...new Set(framework.filter((p) => /(^|\/)agents\/?$/.test(p)).map((p) => p.replace(/\/$/, '')))]
94
+ }
95
+
96
+ /** A subagent name as Claude Code writes one: lower case and hyphens. */
97
+ const SUBAGENT_NAME = /^[a-z0-9][a-z0-9-]*$/
98
+ /** A name the project layer reads an agent file under. */
99
+ const ITEM_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
100
+
101
+ /**
102
+ * Agent files in those folders that nothing OpenCastle compiles produces, and
103
+ * OpenCastle never wrote.
104
+ *
105
+ * Every release has written an agent as `<name>.agent.md`, so a file of that
106
+ * shape whose name a source produces, or the lock records, is OpenCastle's —
107
+ * current or stale — and the sweep's. Anything else is someone's: Claude Code
108
+ * names its subagents `<name>.md`. It is kept under its subagent name, which
109
+ * is what the assistant knows it by; when a source already compiles an agent
110
+ * of that name, under the first free `<name>-2`, `<name>-3`…, because taking
111
+ * the name would replace the team's agent for every assistant.
112
+ */
113
+ export function foreignAgents(projectRoot: string, folders: readonly string[], produced: ReadonlySet<string>): ForeignAgent[] {
114
+ const lock = readLock(projectRoot)
115
+ const known = new Set([...Object.keys(lock?.content ?? {}), ...Object.keys(lock?.excluded ?? {})])
116
+ const taken = new Set([...produced].filter((k) => k.startsWith('agents/')).map((k) => k.slice('agents/'.length)))
117
+ try {
118
+ for (const f of readdirSync(join(projectRoot, '.opencastle', 'agents'))) {
119
+ if (f.endsWith('.agent.md')) taken.add(f.slice(0, -'.agent.md'.length))
120
+ }
121
+ } catch {
122
+ // No team agents yet.
123
+ }
124
+ const out: ForeignAgent[] = []
125
+ // The same file in two targets' folders is one agent, kept once.
126
+ const adopted = new Map<string, string>()
127
+ for (const folder of folders) {
128
+ let entries: import('node:fs').Dirent[]
129
+ try {
130
+ entries = readdirSync(join(projectRoot, folder), { withFileTypes: true })
131
+ } catch {
132
+ continue
133
+ }
134
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
135
+ if (!entry.isFile() || !entry.name.endsWith('.md')) continue
136
+ const ours = entry.name.endsWith('.agent.md')
137
+ const base = entry.name.slice(0, -(ours ? '.agent.md' : '.md').length)
138
+ if (ours && (produced.has(`agents/${base}`) || known.has(`agents/${base}`))) continue
139
+ let text = ''
140
+ try {
141
+ text = readFileSync(join(projectRoot, folder, entry.name), 'utf8')
142
+ } catch {
143
+ continue
144
+ }
145
+ if (MARKER.test(text) || adopted.has(text)) continue
146
+ const declared = parseFrontmatterMeta(text).name
147
+ const wanted = declared && SUBAGENT_NAME.test(declared)
148
+ ? declared
149
+ : ITEM_NAME.test(base) ? base : base.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '') || 'agent'
150
+ let name = wanted
151
+ for (let n = 2; taken.has(name); n++) name = `${wanted}-${n}`
152
+ taken.add(name)
153
+ adopted.set(text, name)
154
+ out.push({ name, from: `${folder}/${entry.name}` })
155
+ }
156
+ }
157
+ return out
158
+ }
159
+
160
+ /** Copy each, as written, into `.opencastle/agents/<name>.agent.md`, so the next compile writes it for every assistant. */
161
+ export function adoptForeignAgents(projectRoot: string, agents: readonly ForeignAgent[]): void {
162
+ if (agents.length > 0) mkdirSync(join(projectRoot, '.opencastle', 'agents'), { recursive: true })
163
+ for (const a of agents) {
164
+ writeFileSync(join(projectRoot, '.opencastle', 'agents', `${a.name}.agent.md`), readFileSync(join(projectRoot, a.from)))
165
+ }
166
+ }
package/src/cli/init.ts CHANGED
@@ -22,8 +22,8 @@ import { noteUnreadable, whyLeftAlone } from './unreadable-report.js'
22
22
  import { resolveSources, materialize, hasErrors, formatIssues, requiredEnvVars } from './layers.js'
23
23
  import { writeLessonRules } from './lessons-rules.js'
24
24
  import { memoryHooksDrift } from './memory-hooks.js'
25
- import { buildLock, writeLock, priorTeam } from './lock.js'
26
- import { adoptForeignSkills, foreignSkills, skillFolders } from './foreign-skills.js'
25
+ import { buildLock, writeLock, priorTeam, priorIntegrations } from './lock.js'
26
+ import { adoptForeignSkills, foreignSkills, skillFolders, adoptForeignAgents, foreignAgents, agentFolders } from './foreign-skills.js'
27
27
  import { parseVersion, compareVersions } from './version-range.js'
28
28
  import { COMMAND_NAMESPACE } from './command-namespace.js'
29
29
 
@@ -334,11 +334,20 @@ export default async function init({ pkgRoot, args }: CliContext): Promise<void>
334
334
  // team's first, so this compile writes them for every assistant instead of
335
335
  // leaving them for the next sync to sweep (foreign-skills.ts).
336
336
  if (!dryRun && !hasErrors(resolved)) {
337
- const foreign = foreignSkills(projectRoot, skillFolders((await declaredManagedPaths(ides)).framework), new Set(resolved.items.keys()))
337
+ const framework = (await declaredManagedPaths(ides)).framework
338
+ const foreign = foreignSkills(projectRoot, skillFolders(framework), new Set(resolved.items.keys()))
338
339
  if (foreign.length > 0) {
339
340
  adoptForeignSkills(projectRoot, foreign)
340
341
  console.log(` ${c.green('✓')} Kept ${foreign.length} skill(s) another tool added — moved into .opencastle/skills/, so every assistant gets ${foreign.length === 1 ? 'it' : 'them'}:`)
341
342
  for (const f of foreign) console.log(` ${c.dim(`${f.from} → .opencastle/skills/${f.name}`)}`)
343
+ }
344
+ const agents = foreignAgents(projectRoot, agentFolders(framework), new Set(resolved.items.keys()))
345
+ if (agents.length > 0) {
346
+ adoptForeignAgents(projectRoot, agents)
347
+ console.log(` ${c.green('✓')} Kept ${agents.length} agent(s) another tool added — moved into .opencastle/agents/, so every assistant gets ${agents.length === 1 ? 'it' : 'them'}:`)
348
+ for (const a of agents) console.log(` ${c.dim(`${a.from} → .opencastle/agents/${a.name}.agent.md`)}`)
349
+ }
350
+ if (foreign.length > 0 || agents.length > 0) {
342
351
  resolved = resolveSources({ pkgRoot, projectRoot, stack, repoInfo: combinedRepoInfo })
343
352
  }
344
353
  }
@@ -433,8 +442,8 @@ export default async function init({ pkgRoot, args }: CliContext): Promise<void>
433
442
  // it — the one path by which uninstalling could not reach its own output.
434
443
  for (const id of dropped) {
435
444
  if ((ides as string[]).includes(id)) continue
436
- await stripManagedMcpServers(projectRoot, id as IdeChoice)
437
- await retireLegacyMcpConfig(projectRoot, id as IdeChoice)
445
+ await stripManagedMcpServers(projectRoot, id as IdeChoice, false, [], [], priorIntegrations(projectRoot))
446
+ await retireLegacyMcpConfig(projectRoot, id as IdeChoice, false, [], [], priorIntegrations(projectRoot))
438
447
  }
439
448
 
440
449
  // Co-owned files are not ours to delete — take back only the block, and
@@ -775,6 +784,7 @@ export default async function init({ pkgRoot, args }: CliContext): Promise<void>
775
784
  // servers" for every entry, and the list now also carries generated rule and
776
785
  // skill files, so a skipped `.cursor/rules/x.mdc` was explained in terms of a
777
786
  // feature that has nothing to do with it.
787
+ if (why === 'outside') continue
778
788
  const isMcp = /(^|[/\\])(\.mcp\.json|mcp\.json|mcp_config\.json|opencode\.json|config\.toml)$/.test(name)
779
789
  console.log(
780
790
  ` ${c.dim(
package/src/cli/lock.ts CHANGED
@@ -393,3 +393,21 @@ export function priorTeam(projectRoot: string): [string[], string[]] {
393
393
  for (const k of keys) for (const v of lock?.mcp[k]?.env ?? []) vars.add(v)
394
394
  return [keys, [...vars].sort()]
395
395
  }
396
+
397
+ /**
398
+ * The integration servers the committed lock says the last compile gave this
399
+ * project. Only these are OpenCastle's to take back out of an MCP config: an
400
+ * entry under an integration's name that the project's stack never included
401
+ * is someone's own, however exactly it matches what this tool would write —
402
+ * chrome-devtools' upstream README gives, to the byte, a default an earlier
403
+ * release wrote. Null when there is no lock to ask, an install from before it.
404
+ */
405
+ export function priorIntegrations(projectRoot: string): Set<string> | null {
406
+ const lock = readLock(projectRoot)
407
+ if (!lock?.mcp) return null
408
+ return new Set(
409
+ Object.entries(lock.mcp)
410
+ .filter(([, s]) => s.from.startsWith('plugin:'))
411
+ .map(([k]) => k),
412
+ )
413
+ }