Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

projection.test.ts

286 lines9.3 KB

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