Open History to see the last commit
1/**
2 * Unit test for the Claude Code workspace projector.
3 *
4 * Drives `projectClaudeWorkspace` with a fake `SandboxHandle` (recording every
5 * `fs.write` / `process.exec`) and a `WorkspaceProjection` carrying one of each
6 * skill kind plus a plugin. Asserts the native projection (`.mcp.json` with the
7 * secret RESOLVED, gitSkill linked under `.claude/skills`, plugin installed,
8 * marker written), that a second call still REWRITES `.mcp.json` with the
9 * current secret but does NOT re-run the marker-gated gitSkill links / plugin
10 * installs, and that a `bearer(ref)` header resolves to `Bearer <value>`.
11 */
12import { describe, expect, it, vi } from 'vitest'
13import {
14 bearer,
15 createSecrets,
16 mcpSkill,
17 agentSkill,
18 gitSkill,
19 resolveGitSkillDir,
20} from '@tanstack/ai-sandbox'
21import { projectClaudeWorkspace } from '../src/adapters/projection'
22import type {
23 ExecResult,
24 SandboxHandle,
25 WorkspaceProjection,
26 WorkspaceSkill,
27} from '@tanstack/ai-sandbox'
28
29interface RecordedExec {
30 command: string
31 cwd: string | undefined
32}
33
34interface FakeHandle {
35 handle: SandboxHandle
36 writes: Map<string, string>
37 execs: Array<RecordedExec>
38 existing: Set<string>
39}
40
41/** Immediate children of `dir` from a flat path→content map. */
42function listChildren(
43 files: Map<string, string>,
44 dir: string,
45): Array<{ name: string; path: string; type: 'file' | 'dir' }> {
46 const prefix = dir.endsWith('/') ? dir : `${dir}/`
47 const children = new Map<
48 string,
49 { name: string; path: string; type: 'file' | 'dir' }
50 >()
51 for (const filePath of files.keys()) {
52 if (!filePath.startsWith(prefix)) continue
53 const rest = filePath.slice(prefix.length)
54 const name = rest.split('/')[0]
55 if (name === undefined || name === '') continue
56 children.set(name, {
57 name,
58 path: `${prefix}${name}`,
59 type: rest.includes('/') ? 'dir' : 'file',
60 })
61 }
62 return [...children.values()]
63}
64
65/** Build a fake handle that records writes/execs and tracks existing paths. */
66function makeFakeHandle(execResult: ExecResult): FakeHandle {
67 const writes = new Map<string, string>()
68 const execs: Array<RecordedExec> = []
69 const existing = new Set<string>()
70 const dirs = new Set<string>()
71
72 const handle = {
73 fs: {
74 write: (path: string, data: string | Uint8Array) => {
75 writes.set(path, typeof data === 'string' ? data : '')
76 existing.add(path)
77 return Promise.resolve()
78 },
79 exists: (path: string) => Promise.resolve(existing.has(path)),
80 mkdir: (path: string) => {
81 dirs.add(path)
82 return Promise.resolve()
83 },
84 list: (dir: string) => Promise.resolve(listChildren(writes, dir)),
85 },
86 process: {
87 exec: (command: string, options?: { cwd?: string }) => {
88 execs.push({ command, cwd: options?.cwd })
89 return Promise.resolve(execResult)
90 },
91 },
92 } as unknown as SandboxHandle
93
94 return { handle, writes, execs, existing }
95}
96
97const ROOT = '/workspace'
98const MARKER = `${ROOT}/.tanstack-projected-abc123`
99
100describe('projectClaudeWorkspace', () => {
101 function buildScenario() {
102 const secrets = createSecrets({ MCP_TOKEN: 'super-secret' })
103 const skills: Array<WorkspaceSkill> = [
104 mcpSkill('issues', {
105 url: 'https://mcp.example.com/mcp',
106 headers: { Authorization: secrets.MCP_TOKEN },
107 }),
108 agentSkill('public-skill'),
109 gitSkill({ repo: 'me/my-skill' }),
110 ]
111 const projection: WorkspaceProjection = {
112 skills,
113 plugins: ['@acme/plugin'],
114 resolveSecret: (ref) => {
115 if (ref.__secretName === 'MCP_TOKEN') return 'super-secret'
116 throw new Error(`unknown secret "${ref.__secretName}"`)
117 },
118 markerPath: MARKER,
119 root: ROOT,
120 }
121 return {
122 projection,
123 gitDir: resolveGitSkillDir(ROOT, { kind: 'git', repo: 'me/my-skill' }),
124 }
125 }
126
127 it('writes .mcp.json with the secret resolved, links the gitSkill, installs the plugin, writes the marker', async () => {
128 const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
129 const fake = makeFakeHandle({ stdout: '', stderr: '', exitCode: 0 })
130 const { projection, gitDir } = buildScenario()
131
132 await projectClaudeWorkspace(fake.handle, projection)
133
134 // MCP config written at project root with the SECRET RESOLVED (not the ref).
135 const mcpRaw = fake.writes.get(`${ROOT}/.mcp.json`)
136 expect(mcpRaw).toBeDefined()
137 const mcp = JSON.parse(mcpRaw ?? '{}')
138 expect(mcp.mcpServers.issues.type).toBe('http')
139 expect(mcp.mcpServers.issues.url).toBe('https://mcp.example.com/mcp')
140 expect(mcp.mcpServers.issues.headers.Authorization).toBe('super-secret')
141 expect(mcpRaw).not.toContain('__secretName')
142
143 // gitSkill linked (or copied) under .claude/skills/<basename>.
144 const target = `${ROOT}/.claude/skills/my-skill`
145 const linkExec = fake.execs.find(
146 (e) => e.command.includes('ln -s') && e.command.includes(target),
147 )
148 expect(linkExec).toBeDefined()
149 expect(linkExec?.command).toContain(gitDir)
150
151 // Plugin installed.
152 const pluginExec = fake.execs.find((e) =>
153 e.command.includes('claude plugin install'),
154 )
155 expect(pluginExec?.command).toContain('@acme/plugin')
156
157 // agentSkill warned (no claude primitive for bare names).
158 expect(warn).toHaveBeenCalled()
159
160 // Marker written.
161 expect(fake.writes.has(MARKER)).toBe(true)
162
163 warn.mockRestore()
164 })
165
166 it('passes plain-string header values through unchanged', async () => {
167 const fake = makeFakeHandle({ stdout: '', stderr: '', exitCode: 0 })
168 const projection: WorkspaceProjection = {
169 skills: [
170 mcpSkill('issues', {
171 url: 'https://mcp.example.com/mcp',
172 headers: { 'X-Plain': 'literal-value' },
173 }),
174 ],
175 plugins: [],
176 resolveSecret: () => {
177 throw new Error('resolveSecret should not be called for plain headers')
178 },
179 markerPath: MARKER,
180 root: ROOT,
181 }
182
183 await projectClaudeWorkspace(fake.handle, projection)
184
185 const mcp = JSON.parse(fake.writes.get(`${ROOT}/.mcp.json`) ?? '{}')
186 expect(mcp.mcpServers.issues.headers['X-Plain']).toBe('literal-value')
187 })
188
189 it('resolves a bearer(ref) header to "Bearer <resolved-value>"', async () => {
190 const fake = makeFakeHandle({ stdout: '', stderr: '', exitCode: 0 })
191 const secrets = createSecrets({ LIN: 'lin-token' })
192 const projection: WorkspaceProjection = {
193 skills: [
194 mcpSkill('issues', {
195 url: 'https://mcp.example.com/mcp',
196 headers: { Authorization: bearer(secrets.LIN) },
197 }),
198 ],
199 plugins: [],
200 resolveSecret: (ref) => {
201 if (ref.__secretName === 'LIN') return 'lin-token'
202 throw new Error(`unknown secret "${ref.__secretName}"`)
203 },
204 markerPath: MARKER,
205 root: ROOT,
206 }
207
208 await projectClaudeWorkspace(fake.handle, projection)
209
210 const mcpRaw = fake.writes.get(`${ROOT}/.mcp.json`)
211 const mcp = JSON.parse(mcpRaw ?? '{}')
212 expect(mcp.mcpServers.issues.headers.Authorization).toBe('Bearer lin-token')
213 expect(mcpRaw).not.toContain('__secretName')
214 expect(mcpRaw).not.toContain('__bearerRef')
215 })
216
217 it('rewrites .mcp.json on a second call but does not re-run gitSkill links / plugin installs', async () => {
218 const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
219 const fake = makeFakeHandle({ stdout: '', stderr: '', exitCode: 0 })
220 const { projection } = buildScenario()
221
222 await projectClaudeWorkspace(fake.handle, projection)
223 const execsAfterFirst = fake.execs.length
224 expect(fake.writes.get(`${ROOT}/.mcp.json`)).toContain('super-secret')
225
226 // Clear the recorded MCP write so we can prove the second call rewrites it.
227 fake.writes.delete(`${ROOT}/.mcp.json`)
228
229 await projectClaudeWorkspace(fake.handle, projection)
230
231 // The secret-bearing MCP config is rewritten every call, with the current
232 // secret resolved fresh, so a rotated secret always re-applies.
233 const rewritten = fake.writes.get(`${ROOT}/.mcp.json`)
234 expect(rewritten).toBeDefined()
235 expect(rewritten).toContain('super-secret')
236
237 // The safe, idempotent, non-secret operations (gitSkill links, plugin
238 // installs) are marker-gated and do NOT run again on the second call.
239 expect(fake.execs.length).toBe(execsAfterFirst)
240
241 warn.mockRestore()
242 })
243
244 // Nested packs (skills/foo/SKILL.md) must be linked by the skill folder
245 // name, not the clone basename. Issue #1081 item 3.
246 it('links each nested SKILL.md folder by its skill name', async () => {
247 const fake = makeFakeHandle({ stdout: '', stderr: '', exitCode: 0 })
248 const clone = resolveGitSkillDir(ROOT, {
249 kind: 'git',
250 repo: 'owner/skills-pack',
251 })
252 fake.writes.set(`${clone}/skills/foo/SKILL.md`, '# foo')
253 fake.writes.set(`${clone}/skills/bar/SKILL.md`, '# bar')
254
255 await projectClaudeWorkspace(fake.handle, {
256 skills: [gitSkill({ repo: 'owner/skills-pack' })],
257 plugins: [],
258 resolveSecret: () => '',
259 markerPath: MARKER,
260 root: ROOT,
261 })
262
263 expect(
264 fake.execs.some(
265 (e) =>
266 e.command.includes('ln -s') &&
267 e.command.includes(`${clone}/skills/foo`) &&
268 e.command.includes(`${ROOT}/.claude/skills/foo`),
269 ),
270 ).toBe(true)
271 expect(
272 fake.execs.some(
273 (e) =>
274 e.command.includes('ln -s') &&
275 e.command.includes(`${clone}/skills/bar`) &&
276 e.command.includes(`${ROOT}/.claude/skills/bar`),
277 ),
278 ).toBe(true)
279 expect(
280 fake.execs.some((e) =>
281 e.command.includes(`${ROOT}/.claude/skills/skills-pack`),
282 ),
283 ).toBe(false)
284 })
285})