opencastle 1.0.0 → 1.1.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 (118) hide show
  1. package/README.md +9 -4
  2. package/dist/cli/adapters/claude-code.d.ts +8 -4
  3. package/dist/cli/adapters/claude-code.d.ts.map +1 -1
  4. package/dist/cli/adapters/claude-code.js +13 -7
  5. package/dist/cli/adapters/claude-code.js.map +1 -1
  6. package/dist/cli/adapters/codex.d.ts +19 -6
  7. package/dist/cli/adapters/codex.d.ts.map +1 -1
  8. package/dist/cli/adapters/codex.js +24 -7
  9. package/dist/cli/adapters/codex.js.map +1 -1
  10. package/dist/cli/adapters/single-file-base.d.ts +15 -1
  11. package/dist/cli/adapters/single-file-base.d.ts.map +1 -1
  12. package/dist/cli/adapters/single-file-base.js +46 -21
  13. package/dist/cli/adapters/single-file-base.js.map +1 -1
  14. package/dist/cli/adapters/vscode.d.ts +11 -1
  15. package/dist/cli/adapters/vscode.d.ts.map +1 -1
  16. package/dist/cli/adapters/vscode.js +48 -8
  17. package/dist/cli/adapters/vscode.js.map +1 -1
  18. package/dist/cli/codex-target.test.d.ts +2 -0
  19. package/dist/cli/codex-target.test.d.ts.map +1 -0
  20. package/dist/cli/codex-target.test.js +154 -0
  21. package/dist/cli/codex-target.test.js.map +1 -0
  22. package/dist/cli/command-namespace.d.ts +91 -0
  23. package/dist/cli/command-namespace.d.ts.map +1 -0
  24. package/dist/cli/command-namespace.js +218 -0
  25. package/dist/cli/command-namespace.js.map +1 -0
  26. package/dist/cli/command-namespace.test.d.ts +2 -0
  27. package/dist/cli/command-namespace.test.d.ts.map +1 -0
  28. package/dist/cli/command-namespace.test.js +356 -0
  29. package/dist/cli/command-namespace.test.js.map +1 -0
  30. package/dist/cli/copy.d.ts +1 -1
  31. package/dist/cli/copy.d.ts.map +1 -1
  32. package/dist/cli/copy.js +3 -2
  33. package/dist/cli/copy.js.map +1 -1
  34. package/dist/cli/doctor.d.ts.map +1 -1
  35. package/dist/cli/doctor.js +2 -1
  36. package/dist/cli/doctor.js.map +1 -1
  37. package/dist/cli/doctor.test.js +2 -2
  38. package/dist/cli/doctor.test.js.map +1 -1
  39. package/dist/cli/explain.d.ts.map +1 -1
  40. package/dist/cli/explain.js +13 -1
  41. package/dist/cli/explain.js.map +1 -1
  42. package/dist/cli/github-report.js +1 -1
  43. package/dist/cli/github-report.js.map +1 -1
  44. package/dist/cli/init.d.ts.map +1 -1
  45. package/dist/cli/init.js +45 -10
  46. package/dist/cli/init.js.map +1 -1
  47. package/dist/cli/init.test.js +31 -14
  48. package/dist/cli/init.test.js.map +1 -1
  49. package/dist/cli/managed-paths.d.ts +18 -1
  50. package/dist/cli/managed-paths.d.ts.map +1 -1
  51. package/dist/cli/managed-paths.js +74 -2
  52. package/dist/cli/managed-paths.js.map +1 -1
  53. package/dist/cli/manifest.d.ts.map +1 -1
  54. package/dist/cli/manifest.js +2 -0
  55. package/dist/cli/manifest.js.map +1 -1
  56. package/dist/cli/mcp-audit.d.ts.map +1 -1
  57. package/dist/cli/mcp-audit.js +7 -3
  58. package/dist/cli/mcp-audit.js.map +1 -1
  59. package/dist/cli/mcp-file.d.ts +37 -0
  60. package/dist/cli/mcp-file.d.ts.map +1 -0
  61. package/dist/cli/mcp-file.js +291 -0
  62. package/dist/cli/mcp-file.js.map +1 -0
  63. package/dist/cli/mcp-file.test.d.ts +2 -0
  64. package/dist/cli/mcp-file.test.d.ts.map +1 -0
  65. package/dist/cli/mcp-file.test.js +121 -0
  66. package/dist/cli/mcp-file.test.js.map +1 -0
  67. package/dist/cli/mcp.d.ts +15 -0
  68. package/dist/cli/mcp.d.ts.map +1 -1
  69. package/dist/cli/mcp.js +123 -56
  70. package/dist/cli/mcp.js.map +1 -1
  71. package/dist/cli/remove.d.ts.map +1 -1
  72. package/dist/cli/remove.js +45 -8
  73. package/dist/cli/remove.js.map +1 -1
  74. package/dist/cli/sync-check.d.ts.map +1 -1
  75. package/dist/cli/sync-check.js +26 -7
  76. package/dist/cli/sync-check.js.map +1 -1
  77. package/dist/cli/sync-check.test.js +2 -2
  78. package/dist/cli/sync-check.test.js.map +1 -1
  79. package/dist/cli/types.d.ts +37 -2
  80. package/dist/cli/types.d.ts.map +1 -1
  81. package/dist/cli/types.js +3 -0
  82. package/dist/cli/types.js.map +1 -1
  83. package/dist/cli/unreadable-report.d.ts +7 -0
  84. package/dist/cli/unreadable-report.d.ts.map +1 -1
  85. package/dist/cli/unreadable-report.js +14 -0
  86. package/dist/cli/unreadable-report.js.map +1 -1
  87. package/dist/cli/update.d.ts.map +1 -1
  88. package/dist/cli/update.js +69 -5
  89. package/dist/cli/update.js.map +1 -1
  90. package/package.json +3 -2
  91. package/src/cli/adapters/claude-code.ts +13 -7
  92. package/src/cli/adapters/codex.ts +25 -7
  93. package/src/cli/adapters/single-file-base.ts +66 -26
  94. package/src/cli/adapters/vscode.ts +51 -10
  95. package/src/cli/codex-target.test.ts +178 -0
  96. package/src/cli/command-namespace.test.ts +417 -0
  97. package/src/cli/command-namespace.ts +222 -0
  98. package/src/cli/copy.ts +6 -2
  99. package/src/cli/doctor.test.ts +2 -2
  100. package/src/cli/doctor.ts +3 -2
  101. package/src/cli/explain.ts +13 -1
  102. package/src/cli/github-report.ts +1 -1
  103. package/src/cli/init.test.ts +31 -14
  104. package/src/cli/init.ts +48 -11
  105. package/src/cli/managed-paths.ts +75 -3
  106. package/src/cli/manifest.ts +2 -0
  107. package/src/cli/mcp-audit.ts +7 -3
  108. package/src/cli/mcp-file.test.ts +138 -0
  109. package/src/cli/mcp-file.ts +302 -0
  110. package/src/cli/mcp.ts +130 -60
  111. package/src/cli/remove.ts +40 -8
  112. package/src/cli/sync-check.test.ts +2 -2
  113. package/src/cli/sync-check.ts +23 -6
  114. package/src/cli/types.ts +37 -2
  115. package/src/cli/unreadable-report.ts +14 -0
  116. package/src/cli/update.ts +73 -5
  117. package/src/dashboard/node_modules/.vite/deps/_metadata.json +6 -6
  118. package/src/orchestrator/prompts/bootstrap-customizations.prompt.md +4 -4
@@ -0,0 +1,417 @@
1
+ /**
2
+ * Compiled commands live under `oc:` — `/oc:bug-fix` — and OpenCastle owns that
3
+ * namespace and nothing beside it. A command someone writes by hand keeps its
4
+ * name, is never overwritten, never swept, and never reported as drift; what a
5
+ * release before the namespace left outside it is cleaned up once.
6
+ */
7
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync, readdirSync } from 'node:fs'
8
+ import { tmpdir } from 'node:os'
9
+ import { join, resolve, dirname } from 'node:path'
10
+ import { execFileSync } from 'node:child_process'
11
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
12
+ import { IDE_ADAPTERS } from './adapters/index.js'
13
+ import { resolveSources, materialize } from './layers.js'
14
+ import { buildCheckReport } from './sync-check.js'
15
+ import { writeManifest, createManifest } from './manifest.js'
16
+ import { recordLockFor } from './lock.js'
17
+ import { resolveManagedPaths, ownerOf, removeOwnedFiles } from './managed-paths.js'
18
+ import { carriesOurBanner, commandName, legacyClaudeCommands, withCommandName } from './command-namespace.js'
19
+ import type { Manifest, StackConfig } from './types.js'
20
+
21
+ vi.mock('./prompt.js', async (importOriginal) => {
22
+ const actual = await importOriginal<typeof import('./prompt.js')>()
23
+ return { ...actual, confirm: vi.fn().mockResolvedValue(true), select: vi.fn().mockResolvedValue('all'), closePrompts: vi.fn() }
24
+ })
25
+
26
+ import remove from './remove.js'
27
+
28
+ const pkgRoot = resolve(import.meta.dirname, '..', '..')
29
+
30
+ const BANNER = '<!-- ⚠️ This file is managed by OpenCastle. Edits will be overwritten on update. Customize in the .opencastle/ directory instead. -->'
31
+ /** What a release before the namespace compiled to `.claude/commands/bug-fix.md`. */
32
+ const LEGACY_COMMAND = `${BANNER}\n\n# Fix Bug\n\nYou are the Team Lead.\n`
33
+ /** A command a person wrote. */
34
+ const OWN_COMMAND = '# Deploy\n\nRun our deploy script and report back.\n'
35
+
36
+ function write(root: string, files: Record<string, string>): void {
37
+ for (const [rel, text] of Object.entries(files)) {
38
+ const abs = join(root, rel)
39
+ mkdirSync(dirname(abs), { recursive: true })
40
+ writeFileSync(abs, text)
41
+ }
42
+ }
43
+
44
+ function manifestFor(ides: StackConfig['ides'], version = '1.0.0', extra: Partial<Manifest> = {}): Manifest {
45
+ return {
46
+ version,
47
+ ide: ides[0],
48
+ ides,
49
+ installedAt: new Date().toISOString(),
50
+ updatedAt: new Date().toISOString(),
51
+ stack: { ides, techTools: [], teamTools: [] },
52
+ ...extra,
53
+ }
54
+ }
55
+
56
+ describe('the command name', () => {
57
+ it('is the source name under oc:', () => {
58
+ expect(commandName('bug-fix')).toBe('oc:bug-fix')
59
+ })
60
+
61
+ it('goes into the frontmatter first, keeping every other field', () => {
62
+ const out = withCommandName("---\ndescription: 'Fix it'\nagent: 'Team Lead (OpenCastle)'\n---\n\nBody\n", 'bug-fix')
63
+ expect(out).toBe("---\nname: 'oc:bug-fix'\ndescription: 'Fix it'\nagent: 'Team Lead (OpenCastle)'\n---\n\nBody\n")
64
+ })
65
+
66
+ it('replaces a name the source declared, so both assistants agree on it', () => {
67
+ const out = withCommandName("---\nname: ship\ndescription: 'Ship'\n---\nBody", 'release')
68
+ expect(out).toContain("name: 'oc:release'")
69
+ expect(out).not.toContain('name: ship')
70
+ })
71
+
72
+ it('drops a block-scalar name whole, so the YAML still parses', () => {
73
+ const out = withCommandName("---\nname: >\n ship it\n now\ndescription: 'Ship'\n---\nBody", 'release')
74
+ expect(out).toBe("---\nname: 'oc:release'\ndescription: 'Ship'\n---\nBody")
75
+ })
76
+
77
+ it('keeps CRLF endings in a prompt checked out on Windows', () => {
78
+ const out = withCommandName("---\r\ndescription: 'x'\r\n---\r\n\r\nBody\r\n", 'x')
79
+ expect(out).toBe("---\r\nname: 'oc:x'\r\ndescription: 'x'\r\n---\r\n\r\nBody\r\n")
80
+ })
81
+
82
+ it('adds frontmatter to a prompt that has none', () => {
83
+ expect(withCommandName('Just a body\n', 'plain')).toBe("---\nname: 'oc:plain'\n---\n\nJust a body\n")
84
+ })
85
+ })
86
+
87
+ describe('our banner', () => {
88
+ it('counts inside an HTML comment near the top', () => {
89
+ expect(carriesOurBanner(LEGACY_COMMAND)).toBe(true)
90
+ expect(carriesOurBanner(`${LEGACY_COMMAND}`)).toBe(true)
91
+ })
92
+
93
+ it('does not count in a sentence a person wrote', () => {
94
+ expect(carriesOurBanner('# Notes\n\nThis file is managed by OpenCastle, mostly.\n')).toBe(false)
95
+ expect(carriesOurBanner(OWN_COMMAND)).toBe(false)
96
+ })
97
+ })
98
+
99
+ describe('Claude Code: /oc:<name>', () => {
100
+ let project: string
101
+ const stack: StackConfig = { ides: ['claude-code'], techTools: [], teamTools: [] }
102
+
103
+ beforeEach(() => {
104
+ project = mkdtempSync(join(tmpdir(), 'oc-ns-claude-'))
105
+ })
106
+ afterEach(() => {
107
+ rmSync(project, { recursive: true, force: true })
108
+ })
109
+
110
+ it("compiles a team's own prompt into the namespace too", async () => {
111
+ write(project, { '.opencastle/prompts/release.prompt.md': "---\ndescription: 'Cut a release'\n---\n\nRELEASE-PROMPT\n" })
112
+ const src = materialize(resolveSources({ pkgRoot, projectRoot: project, stack }), pkgRoot)
113
+ try {
114
+ await (await IDE_ADAPTERS['claude-code']()).install(pkgRoot, project, stack, undefined, src)
115
+ } finally {
116
+ src.dispose()
117
+ }
118
+ expect(readFileSync(join(project, '.claude/commands/oc/release.md'), 'utf8')).toContain('RELEASE-PROMPT')
119
+ expect(existsSync(join(project, '.claude/commands/oc/bug-fix.md'))).toBe(true)
120
+ expect(existsSync(join(project, '.claude/commands/oc/workflow-bug-fix.md'))).toBe(true)
121
+ })
122
+
123
+ it('leaves a command someone wrote alone: not swept, not overwritten, not drift', async () => {
124
+ write(project, { '.claude/commands/deploy.md': OWN_COMMAND, '.claude/commands/bug-fix.md': OWN_COMMAND })
125
+ const adapter = await IDE_ADAPTERS['claude-code']()
126
+ await adapter.install(pkgRoot, project, stack)
127
+ const swept = await adapter.update(pkgRoot, project, stack)
128
+ await writeManifest(project, manifestFor(['claude-code']))
129
+ await recordLockFor(pkgRoot, project, manifestFor(['claude-code']))
130
+
131
+ // Their `/bug-fix` and ours, `/oc:bug-fix`, side by side.
132
+ expect(readFileSync(join(project, '.claude/commands/deploy.md'), 'utf8')).toBe(OWN_COMMAND)
133
+ expect(readFileSync(join(project, '.claude/commands/bug-fix.md'), 'utf8')).toBe(OWN_COMMAND)
134
+ expect(readFileSync(join(project, '.claude/commands/oc/bug-fix.md'), 'utf8')).toContain('# Fix Bug')
135
+ expect(swept.deleted ?? []).toEqual([])
136
+
137
+ const report = await buildCheckReport(pkgRoot, project)
138
+ expect(report.drift).toEqual([])
139
+ })
140
+
141
+ it('removes what a release before the namespace left at the top, and keeps what a person wrote', async () => {
142
+ write(project, {
143
+ '.claude/commands/bug-fix.md': LEGACY_COMMAND,
144
+ '.claude/commands/workflow-bug-fix.md': `${BANNER}\n\n# Workflow: Bug Fix\n`,
145
+ '.claude/commands/deploy.md': OWN_COMMAND,
146
+ })
147
+ const adapter = await IDE_ADAPTERS['claude-code']()
148
+ await writeManifest(project, manifestFor(['claude-code'], '0.38.2'))
149
+
150
+ // Before the sync, the check names the stale commands.
151
+ const before = await buildCheckReport(pkgRoot, project)
152
+ const extra = before.drift.filter((d) => d.kind === 'extra').map((d) => d.path)
153
+ expect(extra).toEqual(['.claude/commands/bug-fix.md', '.claude/commands/workflow-bug-fix.md'])
154
+
155
+ const results = await adapter.update(pkgRoot, project, stack)
156
+ expect(results.deleted).toEqual(expect.arrayContaining(['.claude/commands/bug-fix.md', '.claude/commands/workflow-bug-fix.md']))
157
+ expect(readdirSync(join(project, '.claude/commands')).sort()).toEqual(['deploy.md', 'oc'])
158
+ expect(readFileSync(join(project, '.claude/commands/deploy.md'), 'utf8')).toBe(OWN_COMMAND)
159
+ expect(legacyClaudeCommands(project)).toEqual([])
160
+ })
161
+
162
+ it("keeps a person's edited copy of a namespaced command, banner and all", async () => {
163
+ const adapter = await IDE_ADAPTERS['claude-code']()
164
+ await adapter.install(pkgRoot, project, stack)
165
+ const ours = readFileSync(join(project, '.claude/commands/oc/bug-fix.md'), 'utf8')
166
+ expect(carriesOurBanner(ours)).toBe(true)
167
+ write(project, { '.claude/commands/our-bug-fix.md': `${ours}\nOur extra step.\n` })
168
+
169
+ const results = await adapter.update(pkgRoot, project, stack)
170
+ expect(results.deleted ?? []).toEqual([])
171
+ expect(existsSync(join(project, '.claude/commands/our-bug-fix.md'))).toBe(true)
172
+ expect(legacyClaudeCommands(project)).toEqual([])
173
+ })
174
+
175
+ it('cleans up after 1.0.0 too, which shipped before the namespace', async () => {
176
+ write(project, { '.claude/commands/bug-fix.md': LEGACY_COMMAND, '.claude/commands/deploy.md': OWN_COMMAND })
177
+ // As 1.0.0 wrote it: a later version than any cut-off would have guessed,
178
+ // and no namespace mark.
179
+ await writeManifest(project, manifestFor(['claude-code'], '1.0.0'))
180
+ expect(legacyClaudeCommands(project)).toEqual(['.claude/commands/bug-fix.md'])
181
+
182
+ await (await IDE_ADAPTERS['claude-code']()).update(pkgRoot, project, stack)
183
+ expect(readdirSync(join(project, '.claude/commands')).sort()).toEqual(['deploy.md', 'oc'])
184
+ })
185
+
186
+ it('a new manifest carries the namespace mark from the start', async () => {
187
+ expect(createManifest('9.9.9', 'claude-code').commandNamespace).toBe('oc')
188
+ })
189
+
190
+ it('frees the old names once the project is namespaced: a copy under one is kept', async () => {
191
+ const adapter = await IDE_ADAPTERS['claude-code']()
192
+ await adapter.install(pkgRoot, project, stack)
193
+ await writeManifest(project, manifestFor(['claude-code'], '1.0.0', { commandNamespace: 'oc' }))
194
+ // A team that prefers the short name copies ours back, banner and all.
195
+ const ours = readFileSync(join(project, '.claude/commands/oc/bug-fix.md'), 'utf8')
196
+ write(project, { '.claude/commands/bug-fix.md': ours })
197
+
198
+ expect(legacyClaudeCommands(project)).toEqual([])
199
+ const results = await adapter.update(pkgRoot, project, stack)
200
+ expect(results.deleted ?? []).toEqual([])
201
+ expect(readFileSync(join(project, '.claude/commands/bug-fix.md'), 'utf8')).toBe(ours)
202
+ })
203
+
204
+ it('narrows a stored .claude/commands/ to the namespace, so nothing else is ever deleted by it', async () => {
205
+ const paths = await resolveManagedPaths(
206
+ manifestFor(['claude-code'], '0.38.2', {
207
+ managedPaths: { framework: ['.claude/agents/', '.claude/skills/', '.claude/commands/'], customizable: [] },
208
+ }),
209
+ )
210
+ expect(paths.framework).toContain('.claude/commands/oc/')
211
+ expect(paths.framework).not.toContain('.claude/commands/')
212
+ })
213
+ })
214
+
215
+ describe('remove --all', () => {
216
+ let project: string
217
+ let cwd: ReturnType<typeof vi.spyOn>
218
+ beforeEach(() => {
219
+ project = mkdtempSync(join(tmpdir(), 'oc-ns-remove-'))
220
+ cwd = vi.spyOn(process, 'cwd').mockReturnValue(project)
221
+ vi.spyOn(console, 'log').mockImplementation(() => {})
222
+ })
223
+ afterEach(() => {
224
+ cwd.mockRestore()
225
+ vi.restoreAllMocks()
226
+ rmSync(project, { recursive: true, force: true })
227
+ })
228
+
229
+ it("takes OpenCastle's commands, old and new, and leaves the user's", async () => {
230
+ const stack: StackConfig = { ides: ['claude-code'], techTools: [], teamTools: [] }
231
+ await (await IDE_ADAPTERS['claude-code']()).install(pkgRoot, project, stack)
232
+ write(project, {
233
+ '.claude/commands/bug-fix.md': LEGACY_COMMAND,
234
+ '.claude/commands/deploy.md': OWN_COMMAND,
235
+ })
236
+ // As a release before the namespace recorded it: the whole directory.
237
+ await writeManifest(
238
+ project,
239
+ manifestFor(['claude-code'], '0.38.2', {
240
+ managedPaths: { framework: ['.claude/agents/', '.claude/skills/', '.claude/commands/'], customizable: ['.opencastle/', '.mcp.json'], merged: ['CLAUDE.md'] },
241
+ }),
242
+ )
243
+
244
+ await remove({ pkgRoot, args: ['--all', '--yes'] })
245
+
246
+ expect(existsSync(join(project, '.claude/commands/oc'))).toBe(false)
247
+ expect(existsSync(join(project, '.claude/commands/bug-fix.md'))).toBe(false)
248
+ expect(readFileSync(join(project, '.claude/commands/deploy.md'), 'utf8')).toBe(OWN_COMMAND)
249
+ })
250
+ })
251
+
252
+ describe('VS Code: /oc:<name>', () => {
253
+ let project: string
254
+ const stack: StackConfig = { ides: ['vscode'], techTools: [], teamTools: [] }
255
+
256
+ beforeEach(() => {
257
+ project = mkdtempSync(join(tmpdir(), 'oc-ns-vscode-'))
258
+ })
259
+ afterEach(() => {
260
+ rmSync(project, { recursive: true, force: true })
261
+ })
262
+
263
+ it('names each prompt oc:<name>, in a file VS Code finds at the top of .github/prompts/', async () => {
264
+ await (await IDE_ADAPTERS['vscode']()).install(pkgRoot, project, stack)
265
+ const files = readdirSync(join(project, '.github/prompts'))
266
+ expect(files.length).toBeGreaterThan(0)
267
+ expect(files.every((f) => f.startsWith('oc.') && f.endsWith('.prompt.md'))).toBe(true)
268
+
269
+ const text = readFileSync(join(project, '.github/prompts/oc.bug-fix.prompt.md'), 'utf8')
270
+ expect(text.split('\n').slice(0, 2)).toEqual(['---', "name: 'oc:bug-fix'"])
271
+ // The rest of the source's frontmatter is still there.
272
+ expect(text).toContain("agent: 'Team Lead (OpenCastle)'")
273
+ })
274
+
275
+ it('replaces the un-namespaced prompt files an earlier release wrote', async () => {
276
+ const adapter = await IDE_ADAPTERS['vscode']()
277
+ await adapter.install(pkgRoot, project, stack)
278
+ write(project, { '.github/prompts/bug-fix.prompt.md': `---\ndescription: 'old'\n---\n\n${BANNER}\n` })
279
+ // The project as the upgrading sync finds it: last compiled before the namespace.
280
+ await writeManifest(project, manifestFor(['vscode'], '0.38.2'))
281
+
282
+ // Reported once, saying why.
283
+ const report = await buildCheckReport(pkgRoot, project)
284
+ expect(report.drift.filter((d) => d.kind === 'extra')).toEqual([
285
+ { ide: 'vscode', path: '.github/prompts/bug-fix.prompt.md', kind: 'extra', detail: 'written by a release before the oc: namespace' },
286
+ ])
287
+
288
+ const results = await adapter.update(pkgRoot, project, stack)
289
+ expect(results.deleted).toContain('.github/prompts/bug-fix.prompt.md')
290
+ expect(existsSync(join(project, '.github/prompts/oc.bug-fix.prompt.md'))).toBe(true)
291
+ })
292
+
293
+ it("leaves a prompt someone wrote in .github/prompts/ alone: not swept, not drift, not removed", async () => {
294
+ const own = "---\ndescription: 'Deploy'\n---\n\nRun our deploy.\n"
295
+ write(project, {
296
+ '.github/prompts/deploy.prompt.md': own,
297
+ // Same name as one of ours before the namespace, but theirs: no banner.
298
+ '.github/prompts/bug-fix.prompt.md': own,
299
+ })
300
+ const adapter = await IDE_ADAPTERS['vscode']()
301
+ await adapter.install(pkgRoot, project, stack)
302
+ const results = await adapter.update(pkgRoot, project, stack)
303
+ expect(results.deleted ?? []).toEqual([])
304
+ await writeManifest(project, manifestFor(['vscode']))
305
+ await recordLockFor(pkgRoot, project, manifestFor(['vscode']))
306
+ expect((await buildCheckReport(pkgRoot, project)).drift).toEqual([])
307
+
308
+ const cwd = vi.spyOn(process, 'cwd').mockReturnValue(project)
309
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
310
+ try {
311
+ await writeManifest(
312
+ project,
313
+ manifestFor(['vscode'], '1.0.0', { managedPaths: { framework: ['.github/prompts/', '.github/agents/'], customizable: [] } }),
314
+ )
315
+ await remove({ pkgRoot, args: ['--all', '--yes'] })
316
+ } finally {
317
+ cwd.mockRestore()
318
+ log.mockRestore()
319
+ }
320
+ expect(readFileSync(join(project, '.github/prompts/deploy.prompt.md'), 'utf8')).toBe(own)
321
+ expect(readFileSync(join(project, '.github/prompts/bug-fix.prompt.md'), 'utf8')).toBe(own)
322
+ expect(readdirSync(join(project, '.github/prompts')).sort()).toEqual(['bug-fix.prompt.md', 'deploy.prompt.md'])
323
+ expect(existsSync(join(project, '.github/agents'))).toBe(false)
324
+ })
325
+ })
326
+
327
+ const cli = join(pkgRoot, 'bin', 'cli.mjs')
328
+ const built = existsSync(join(pkgRoot, 'dist', 'cli', 'init.js'))
329
+
330
+ describe.skipIf(!built)('init over an install a release before the namespace left without a manifest', () => {
331
+ let project: string
332
+ beforeEach(() => {
333
+ project = mkdtempSync(join(tmpdir(), 'oc-ns-orphan-'))
334
+ execFileSync('git', ['init', '-q'], { cwd: project })
335
+ write(project, {
336
+ 'CLAUDE.md': '# House rules\n',
337
+ '.claude/commands/bug-fix.md': LEGACY_COMMAND,
338
+ '.claude/commands/deploy.md': OWN_COMMAND,
339
+ '.claude/agents/developer.agent.md': 'an old body\n',
340
+ })
341
+ })
342
+ afterEach(() => rmSync(project, { recursive: true, force: true }))
343
+
344
+ it('recompiles it: the stale /bug-fix goes, old bodies are refreshed, their own command stays', () => {
345
+ const out = execFileSync('node', [cli, 'init', '--yes'], { cwd: project, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
346
+ expect(out).toContain('from a previous installation')
347
+ expect(existsSync(join(project, '.claude/commands/bug-fix.md'))).toBe(false)
348
+ expect(readFileSync(join(project, '.claude/commands/deploy.md'), 'utf8')).toBe(OWN_COMMAND)
349
+ expect(readFileSync(join(project, '.claude/agents/developer.agent.md'), 'utf8')).not.toBe('an old body\n')
350
+ expect(existsSync(join(project, '.claude/commands/oc/bug-fix.md'))).toBe(true)
351
+ const manifest = JSON.parse(readFileSync(join(project, '.opencastle/manifest.json'), 'utf8')) as Manifest
352
+ expect(manifest.commandNamespace).toBe('oc')
353
+ })
354
+
355
+ it('the sync that upgrades a 1.0.0 project removes its old commands and marks it, once', () => {
356
+ execFileSync('node', [cli, 'init', '--yes'], { cwd: project, stdio: 'ignore' })
357
+ // Back to how 1.0.0 left it: its commands at the top, its manifest unmarked.
358
+ write(project, { '.claude/commands/bug-fix.md': LEGACY_COMMAND })
359
+ const path = join(project, '.opencastle/manifest.json')
360
+ const manifest = JSON.parse(readFileSync(path, 'utf8')) as Manifest
361
+ delete manifest.commandNamespace
362
+ manifest.version = '1.0.0'
363
+ writeFileSync(path, JSON.stringify(manifest, null, 2))
364
+
365
+ execFileSync('node', [cli, 'sync', '--yes'], { cwd: project, stdio: 'ignore' })
366
+ expect(existsSync(join(project, '.claude/commands/bug-fix.md'))).toBe(false)
367
+ expect((JSON.parse(readFileSync(path, 'utf8')) as Manifest).commandNamespace).toBe('oc')
368
+
369
+ // Now the short name is theirs to use.
370
+ write(project, { '.claude/commands/bug-fix.md': LEGACY_COMMAND })
371
+ execFileSync('node', [cli, 'sync', '--yes', '--force'], { cwd: project, stdio: 'ignore' })
372
+ expect(existsSync(join(project, '.claude/commands/bug-fix.md'))).toBe(true)
373
+ })
374
+ })
375
+
376
+ describe('removing from the shared prompts directory', () => {
377
+ let project: string
378
+ beforeEach(() => {
379
+ project = mkdtempSync(join(tmpdir(), 'oc-ns-shared-'))
380
+ })
381
+ afterEach(() => {
382
+ rmSync(project, { recursive: true, force: true })
383
+ })
384
+
385
+ it("takes only our files at the top, and none of a person's subfolders", () => {
386
+ write(project, {
387
+ '.github/prompts/oc.bug-fix.prompt.md': 'ours',
388
+ '.github/prompts/deploy.prompt.md': 'theirs',
389
+ '.github/prompts/drafts/oc.idea.prompt.md': 'theirs, below the top',
390
+ })
391
+ mkdirSync(join(project, '.github/prompts/empty-folder'))
392
+ const owns = (rel: string): boolean => /^\.github\/prompts\/oc\.[^/]+$/.test(rel)
393
+ expect(removeOwnedFiles(project, '.github/prompts/', owns)).toBe(1)
394
+ expect(readdirSync(join(project, '.github/prompts')).sort()).toEqual(['deploy.prompt.md', 'drafts', 'empty-folder'])
395
+ expect(existsSync(join(project, '.github/prompts/drafts/oc.idea.prompt.md'))).toBe(true)
396
+ })
397
+
398
+ it('leaves a file wearing the directory name for a person, without throwing', () => {
399
+ write(project, { '.github/prompts': 'not a directory' })
400
+ expect(removeOwnedFiles(project, '.github/prompts/', () => true)).toBe(0)
401
+ expect(readFileSync(join(project, '.github/prompts'), 'utf8')).toBe('not a directory')
402
+ })
403
+
404
+ it('removes the directory when ours was all it held', () => {
405
+ write(project, { '.github/prompts/oc.bug-fix.prompt.md': 'ours' })
406
+ expect(removeOwnedFiles(project, '.github/prompts/', () => true)).toBe(1)
407
+ expect(existsSync(join(project, '.github/prompts'))).toBe(false)
408
+ })
409
+
410
+ it('treats only .github/prompts/ as shared — every other VS Code directory is removed whole', async () => {
411
+ const vscode = await IDE_ADAPTERS['vscode']()
412
+ expect(ownerOf([vscode], '.github/prompts/', project)).toBeTypeOf('function')
413
+ for (const dir of ['.github/agents/', '.github/instructions/', '.github/skills/', '.github/agent-workflows/']) {
414
+ expect(ownerOf([vscode], dir, project)).toBeUndefined()
415
+ }
416
+ })
417
+ })
@@ -0,0 +1,222 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
2
+ import { resolve } from 'node:path'
3
+
4
+ /**
5
+ * The namespace every command OpenCastle compiles is invoked under.
6
+ *
7
+ * `/bug-fix` was a name anyone could want: a teammate's own command, another
8
+ * tool's, a skill. Compiled commands now live under one prefix, `/oc:bug-fix`,
9
+ * and in the directories commands live in OpenCastle owns that namespace and
10
+ * nothing beside it — so a command someone writes by hand is never overwritten,
11
+ * swept, removed, or reported as drift.
12
+ *
13
+ * The prefix is a namespace, not a mark of origin. A team's own prompt in a
14
+ * baseline or in `.opencastle/prompts/` compiles to `/oc:<name>` as well: it is
15
+ * shared, reviewed config that `sync` rewrites, which is what the prefix tells
16
+ * the person typing it.
17
+ */
18
+ export const COMMAND_NAMESPACE = 'oc'
19
+
20
+ /** What a person types after the slash: `oc:bug-fix`. */
21
+ export function commandName(name: string): string {
22
+ return `${COMMAND_NAMESPACE}:${name}`
23
+ }
24
+
25
+ /**
26
+ * Claude Code names a command after its path under `.claude/commands/`, with
27
+ * each directory becoming a `:` segment — `oc/bug-fix.md` is `/oc:bug-fix`. A
28
+ * directory, not a colon in the file name, because Windows cannot check out a
29
+ * file whose name contains one.
30
+ */
31
+ export const CLAUDE_COMMANDS_DIR = `commands/${COMMAND_NAMESPACE}`
32
+
33
+ /**
34
+ * VS Code reads prompt files from the top of `.github/prompts/` only, so the
35
+ * namespace goes in the file name, and the command name — `name:` in the
36
+ * frontmatter, which VS Code prefers to the file name — carries the colon.
37
+ */
38
+ export function vscodePromptFile(fileName: string): string {
39
+ return `${COMMAND_NAMESPACE}.${fileName}`
40
+ }
41
+
42
+ /**
43
+ * Give a prompt file the namespaced command name, in its frontmatter.
44
+ *
45
+ * Any `name:` the source declared is replaced rather than prefixed: Claude Code
46
+ * ignores the field and names commands after the file, so honouring it here
47
+ * would give one prompt two different names in two assistants.
48
+ */
49
+ export function withCommandName(content: string, name: string): string {
50
+ const line = `name: '${commandName(name)}'`
51
+ // The file's own line endings, so a CRLF checkout of a team's prompt is not
52
+ // rewritten into mixed endings.
53
+ const eol = content.includes('\r\n') ? '\r\n' : '\n'
54
+ const lines = content.split(/\r?\n/)
55
+ if (lines[0]?.trim() === '---') {
56
+ const close = lines.findIndex((l, i) => i > 0 && l.trim() === '---')
57
+ if (close > 0) {
58
+ // The declared name and, for a block scalar (`name: >`), the indented
59
+ // lines that continue it — left behind, they would break the YAML and
60
+ // take `description` and `agent` down with it.
61
+ const kept: string[] = []
62
+ let inName = false
63
+ for (const l of lines.slice(1, close)) {
64
+ if (/^name\s*:/.test(l)) {
65
+ inName = true
66
+ continue
67
+ }
68
+ if (inName && /^[ \t]/.test(l)) continue
69
+ inName = false
70
+ kept.push(l)
71
+ }
72
+ return ['---', line, ...kept, ...lines.slice(close)].join(eol)
73
+ }
74
+ }
75
+ return `---${eol}${line}${eol}---${eol}${eol}${content}`
76
+ }
77
+
78
+ /**
79
+ * Does this file say a release of ours wrote it?
80
+ *
81
+ * Every prompt and workflow OpenCastle has shipped since 0.2 opens with
82
+ * `<!-- ⚠️ This file is managed by OpenCastle. … -->`. Only inside an HTML
83
+ * comment, and only near the top: the same words in a person's own sentence
84
+ * are theirs, which is the distinction `managed-block.ts` learned for root
85
+ * files.
86
+ */
87
+ export function carriesOurBanner(content: string): boolean {
88
+ const lines = content
89
+ .replace(/^/, '')
90
+ .split(/\r?\n/)
91
+ .map((l) => l.trim())
92
+ .filter((l) => l !== '')
93
+ .slice(0, 12)
94
+ return lines.some((l) => l.startsWith('<!--') && l.includes('This file is managed by OpenCastle'))
95
+ }
96
+
97
+ /**
98
+ * Every prompt and workflow a release before the namespace shipped — read
99
+ * from all 103 release tags, 0.1.0 to 1.0.0. A closed list: those releases are
100
+ * done.
101
+ *
102
+ * The banner alone is not enough to call a file theirs. Namespaced output
103
+ * carries it too, so a person who copies `oc/bug-fix.md` to `our-bug-fix.md`
104
+ * and edits it would see their copy deleted on the next sync. A legacy file is
105
+ * one of these names *and* carries the banner.
106
+ */
107
+ const LEGACY_PROMPTS = [
108
+ 'assess-complexity', 'bootstrap-customizations', 'brainstorm', 'bug-fix', 'create-skill',
109
+ 'fix-convoy', 'fix-prd', 'generate-convoy', 'generate-prd', 'generate-task-spec',
110
+ 'implement-feature', 'metrics-report', 'quick-refinement', 'resolve-pr-comments',
111
+ 'validate-convoy', 'validate-prd',
112
+ ]
113
+ const LEGACY_WORKFLOWS = [
114
+ 'README', 'bug-fix', 'data-pipeline', 'database-migration', 'feature-implementation',
115
+ 'performance-optimization', 'refactoring', 'schema-changes', 'security-audit',
116
+ 'shared-delivery-phase',
117
+ ]
118
+
119
+ /** File names a release before the namespace wrote at the top of `.claude/commands/`. */
120
+ const LEGACY_CLAUDE_NAMES = new Set([
121
+ ...LEGACY_PROMPTS.map((n) => `${n}.md`),
122
+ ...LEGACY_WORKFLOWS.map((n) => `workflow-${n}.md`),
123
+ ])
124
+
125
+ /** File names a release before the namespace wrote in `.github/prompts/`. */
126
+ const LEGACY_VSCODE_NAMES = new Set(LEGACY_PROMPTS.map((n) => `${n}.prompt.md`))
127
+
128
+ /**
129
+ * Was this project last compiled by a release before the namespace?
130
+ *
131
+ * Legacy output is looked for only then — during the sync that upgrades it,
132
+ * or over an install whose manifest is gone. Afterwards the old names are free
133
+ * again: a team that copies `oc/bug-fix.md` back to `bug-fix.md` because it
134
+ * prefers the short name keeps its copy, banner and all.
135
+ *
136
+ * Read from a mark in the manifest, not from its version. 1.0.0 shipped
137
+ * without the namespace, and which number the namespaced release gets depends
138
+ * on what else merges first — a version cut-off guessed here would miss every
139
+ * project compiled in between, and leave a stale `/bug-fix` beside
140
+ * `/oc:bug-fix` in each of them.
141
+ */
142
+ export function compiledBeforeNamespace(projectRoot: string): boolean {
143
+ for (const rel of ['.opencastle/manifest.json', '.opencastle.json']) {
144
+ const abs = resolve(projectRoot, rel)
145
+ if (!existsSync(abs)) continue
146
+ try {
147
+ const manifest = JSON.parse(readFileSync(abs, 'utf8')) as { commandNamespace?: unknown }
148
+ return manifest.commandNamespace !== COMMAND_NAMESPACE
149
+ } catch {
150
+ return true
151
+ }
152
+ }
153
+ return true
154
+ }
155
+
156
+ /** Does the file at `abs` carry our banner? An unreadable file is not ours to delete. */
157
+ function bannerAt(abs: string): boolean {
158
+ try {
159
+ return carriesOurBanner(readFileSync(abs, 'utf8'))
160
+ } catch {
161
+ return false
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Commands a release before the namespace compiled into the top of
167
+ * `.claude/commands/`.
168
+ *
169
+ * Those releases wrote `bug-fix.md` and `workflow-bug-fix.md` there and swept
170
+ * the whole directory on every sync. Now commands go under `oc/`, and nothing
171
+ * the rest — so the old files would linger as a second, stale `/bug-fix` beside
172
+ * `/oc:bug-fix`. One of their names with our banner is theirs; anything else in
173
+ * the directory is a person's, and is left alone.
174
+ *
175
+ * Paths are relative to the project root, with forward slashes.
176
+ */
177
+ export function legacyClaudeCommands(projectRoot: string, dotDir = '.claude'): string[] {
178
+ const dir = resolve(projectRoot, dotDir, 'commands')
179
+ if (!existsSync(dir) || !compiledBeforeNamespace(projectRoot)) return []
180
+ let entries
181
+ try {
182
+ entries = readdirSync(dir, { withFileTypes: true })
183
+ } catch {
184
+ return []
185
+ }
186
+ return entries
187
+ .filter((e) => e.isFile() && LEGACY_CLAUDE_NAMES.has(e.name) && bannerAt(resolve(dir, e.name)))
188
+ .map((e) => `${dotDir}/commands/${e.name}`)
189
+ .sort()
190
+ }
191
+
192
+ /**
193
+ * Is this file in `.github/prompts/` one OpenCastle wrote?
194
+ *
195
+ * VS Code reads prompts only from the top of that directory, so OpenCastle's
196
+ * and a person's share it. Ours are the `oc.` files, plus the un-namespaced
197
+ * ones a release before the namespace wrote — which `sync` replaces. Everything else is
198
+ * theirs: never swept, never reported as drift, never removed.
199
+ */
200
+ export function isOurVscodePrompt(fileName: string, abs: string, projectRoot: string): boolean {
201
+ if (fileName.startsWith(`${COMMAND_NAMESPACE}.`)) return true
202
+ return LEGACY_VSCODE_NAMES.has(fileName) && compiledBeforeNamespace(projectRoot) && bannerAt(abs)
203
+ }
204
+
205
+ /**
206
+ * Prompt files a release before the namespace wrote in `.github/prompts/`,
207
+ * present now — `bug-fix.prompt.md`, written today as `oc.bug-fix.prompt.md`.
208
+ */
209
+ export function legacyVscodePrompts(projectRoot: string): string[] {
210
+ const dir = resolve(projectRoot, '.github', 'prompts')
211
+ if (!existsSync(dir) || !compiledBeforeNamespace(projectRoot)) return []
212
+ let entries
213
+ try {
214
+ entries = readdirSync(dir, { withFileTypes: true })
215
+ } catch {
216
+ return []
217
+ }
218
+ return entries
219
+ .filter((e) => e.isFile() && LEGACY_VSCODE_NAMES.has(e.name) && bannerAt(resolve(dir, e.name)))
220
+ .map((e) => `.github/prompts/${e.name}`)
221
+ .sort()
222
+ }
package/src/cli/copy.ts CHANGED
@@ -66,7 +66,7 @@ async function sameText(
66
66
  export async function copyDir(
67
67
  src: string,
68
68
  dest: string,
69
- { overwrite = false, filter, transform }: CopyDirOptions = {}
69
+ { overwrite = false, filter, transform, rename }: CopyDirOptions = {}
70
70
  ): Promise<CopyResults> {
71
71
  const entries = await readdir(src, { withFileTypes: true });
72
72
  await mkdir(dest, { recursive: true });
@@ -75,7 +75,10 @@ export async function copyDir(
75
75
 
76
76
  for (const entry of entries) {
77
77
  const srcPath = resolve(src, entry.name);
78
- const destPath = resolve(dest, entry.name);
78
+ const destPath = resolve(
79
+ dest,
80
+ rename && !entry.isDirectory() ? rename(entry.name) : entry.name,
81
+ );
79
82
 
80
83
  if (filter && !filter(entry.name, srcPath)) continue;
81
84
 
@@ -84,6 +87,7 @@ export async function copyDir(
84
87
  overwrite,
85
88
  filter,
86
89
  transform,
90
+ rename,
87
91
  });
88
92
  mergeCopyResults(results, sub);
89
93
  } else {