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

bootstrap.test.ts

900 lines28.7 KB

1import { describe, expect, it } from 'vitest'
2import { bootstrapWorkspace } from '../src/bootstrap'
3import { createSecrets } from '../src/secrets'
4import { resolveGitSkillDir } from '../src/agents-file'
5import { gitSkill, gitSource, fileSkill } from '../src/workspace'
6import type {
7 ExecResult,
8 ProcessOptions,
9 SandboxHandle,
10 SpawnHandle,
11} from '../src/contracts'
12import type { WorkspaceDefinition } from '../src/workspace'
13​
14/**
15 * A scripted sentinel-driven fake `spawn`. It mirrors the protocol the
16 * persistent bootstrap shell speaks: each stdin write of the form
17 * `<cmd>; printf "\n__BSSH_<N>__ $?\n"` is answered by emitting the scripted
18 * stdout for `<cmd>` followed by the matching sentinel line.
19 *
20 * `forkState()` issues `pwd` then `export -p`; we answer those so the shell
21 * resolves a real `{ cwd, env }`.
22 */
23function makeScriptedSpawn(forkCwd: string): {
24 spawn: SandboxHandle['process']['spawn']
25 spawnCount: () => number
26} {
27 let spawnCount = 0
28 return {
29 spawnCount: () => spawnCount,
30 spawn: (_command: string, _options?: ProcessOptions) => {
31 spawnCount += 1
32​
33 const queue: Array<string> = []
34 const waiters: Array<(result: IteratorResult<string>) => void> = []
35 let done = false
36​
37 function emit(chunk: string): void {
38 const waiter = waiters.shift()
39 if (waiter !== undefined) {
40 waiter({ value: chunk, done: false })
41 } else {
42 queue.push(chunk)
43 }
44 }
45​
46 const stdout: AsyncIterable<string> = {
47 [Symbol.asyncIterator](): AsyncIterator<string> {
48 return {
49 next(): Promise<IteratorResult<string>> {
50 const queued = queue.shift()
51 if (queued !== undefined) {
52 return Promise.resolve({ value: queued, done: false })
53 }
54 if (done) {
55 return Promise.resolve({ value: '', done: true })
56 }
57 return new Promise<IteratorResult<string>>((resolve) => {
58 waiters.push(resolve)
59 })
60 },
61 }
62 },
63 }
64​
65 let counter = 0
66 const handle: SpawnHandle = {
67 pid: 1,
68 stdout,
69 stderr: (async function* empty() {})(),
70 stdin: {
71 write: (data: string) => {
72 const sentinel = `__BSSH_${counter}__`
73 counter += 1
74 // Answer pwd / export -p so forkState resolves; everything else
75 // succeeds with no stdout. Commands are wrapped as `{ <cmd> ; } 2>&1`
76 // by the bootstrap shell (stderr merged into stdout), so match the
77 // wrapped form rather than a bare `pwd;` / `export -p;` prefix.
78 if (data.startsWith('{ pwd ')) {
79 emit(`${forkCwd}\n`)
80 } else if (data.startsWith('{ export -p ')) {
81 emit('declare -x SETUP_VAR="from-shell"\n')
82 }
83 emit(`${sentinel} 0\n`)
84 return Promise.resolve()
85 },
86 end: () => {
87 done = true
88 for (const waiter of waiters) {
89 waiter({ value: '', done: true })
90 }
91 waiters.length = 0
92 return Promise.resolve()
93 },
94 },
95 wait: () => Promise.resolve(0),
96 kill: () => Promise.resolve(),
97 }
98 return Promise.resolve(handle)
99 },
100 }
102​
103interface ExecCall {
104 command: string
105 options?: ProcessOptions
107​
108/**
109 * Build a fake handle that records every `exec` and drives the persistent
110 * shell via {@link makeScriptedSpawn}. The git source is treated as already
111 * cloned so bootstrap skips cloning.
112 *
113 * `execImpl` lets a test control how each `exec` resolves (e.g. to gate
114 * concurrency or to inject a non-zero exit code).
115 */
116function makeRecordingHandle(
117 forkCwd: string,
118 execImpl: (call: ExecCall) => Promise<ExecResult>,
119): {
120 handle: SandboxHandle
121 execCalls: Array<ExecCall>
122 spawnCount: () => number
123} {
124 const execCalls: Array<ExecCall> = []
125 const scripted = makeScriptedSpawn(forkCwd)
126​
127 const handle: SandboxHandle = {
128 id: 'rec',
129 provider: 'fake',
130 capabilities: {
131 fs: true,
132 exec: true,
133 env: true,
134 ports: false,
135 backgroundProcesses: true,
136 writableStdin: true,
137 killableProcesses: true,
138 snapshots: false,
139 networkPolicy: false,
140 durableFilesystem: false,
141 fork: false,
142 },
143 fs: {
144 read: () => Promise.resolve(''),
145 readBytes: () => Promise.resolve(new Uint8Array()),
146 write: () => Promise.resolve(),
147 list: () => Promise.resolve([]),
148 mkdir: () => Promise.resolve(),
149 remove: () => Promise.resolve(),
150 rename: () => Promise.resolve(),
151 // Report the source as already cloned so bootstrap skips git.clone.
152 exists: (path) => Promise.resolve(path.endsWith('/.git')),
153 },
154 git: {
155 clone: () => Promise.reject(new Error('clone should be skipped')),
156 status: () => Promise.resolve(''),
157 add: () => Promise.resolve(),
158 commit: () => Promise.resolve(),
159 push: () => Promise.resolve(),
160 pull: () => Promise.resolve(),
161 branch: () => Promise.resolve('main'),
162 },
163 process: {
164 exec: (command, options) => {
165 const call: ExecCall = { command, options }
166 execCalls.push(call)
167 return execImpl(call)
168 },
169 spawn: scripted.spawn,
170 },
171 ports: {
172 connect: () => Promise.reject(new Error('ports not used')),
173 },
174 env: { set: () => Promise.resolve() },
175 destroy: () => Promise.resolve(),
176 }
177​
178 return { handle, execCalls, spawnCount: scripted.spawnCount }
180​
181const ok: ExecResult = { stdout: '', stderr: '', exitCode: 0 }
182​
183describe('bootstrapWorkspace setup execution', () => {
184 it('runs a parallel group concurrently with the forked cwd', async () => {
185 let dispatched = 0
186 // Each parallel exec blocks until BOTH have been dispatched. If the two
187 // calls were issued sequentially (the second only after the first
188 // resolved), this barrier would never reach 2 and the test would hang —
189 // so resolving proves they were launched concurrently.
190 let releaseBarrier: () => void = () => {}
191 const barrier = new Promise<void>((resolve) => {
192 releaseBarrier = resolve
193 })
194​
195 const { handle, execCalls, spawnCount } = makeRecordingHandle(
196 '/workspace/x',
197 async () => {
198 dispatched += 1
199 if (dispatched === 2) releaseBarrier()
200 await barrier
201 return ok
202 },
203 )
204​
205 const workspace: WorkspaceDefinition = {
206 source: { type: 'git', url: 'https://github.com/me/app' },
207 setup: ({ serial, parallel }) => {
208 serial('cd x')
209 parallel(['a', 'b'])
210 },
211 }
212​
213 const result = await bootstrapWorkspace(handle, workspace)
214​
215 // Both parallel commands were exec'd (the serial `cd x` runs on the shell,
216 // not via exec, so it is NOT in execCalls).
217 const commands = execCalls.map((call) => call.command)
218 expect(commands).toEqual(['a', 'b'])
219 // They inherited the shell's forked cwd.
220 for (const call of execCalls) {
221 expect(call.options?.cwd).toBe('/workspace/x')
222 expect(call.options?.env?.['SETUP_VAR']).toBe('from-shell')
223 }
224 // Exactly one persistent shell drove the serial step + forkState.
225 expect(spawnCount()).toBe(1)
226 expect(result.ranSetup).toEqual(['cd x', 'a', 'b'])
227 })
228​
229 it('throws when a serial step exits non-zero', async () => {
230 // Override the scripted spawn so `bad-cmd` reports a non-zero sentinel.
231 const execCalls: Array<ExecCall> = []
232 const handle = makeFailingSerialHandle(execCalls)
233​
234 const workspace: WorkspaceDefinition = {
235 source: { type: 'git', url: 'https://github.com/me/app' },
236 setup: ['bad-cmd'],
237 }
238​
239 await expect(bootstrapWorkspace(handle, workspace)).rejects.toThrow(
240 'setup step failed: bad-cmd (exit 7)',
241 )
242 // Serial steps run on the shell, never via exec.
243 expect(execCalls).toHaveLength(0)
244 })
245})
246​
247/**
248 * A handle whose persistent shell answers `bad-cmd` with exit code 7, so a
249 * serial step fails. Reuses the recording exec surface (unused here).
250 */
251function makeFailingSerialHandle(execCalls: Array<ExecCall>): SandboxHandle {
252 const handle: SandboxHandle = {
253 id: 'fail',
254 provider: 'fake',
255 capabilities: {
256 fs: true,
257 exec: true,
258 env: true,
259 ports: false,
260 backgroundProcesses: true,
261 writableStdin: true,
262 killableProcesses: true,
263 snapshots: false,
264 networkPolicy: false,
265 durableFilesystem: false,
266 fork: false,
267 },
268 fs: {
269 read: () => Promise.resolve(''),
270 readBytes: () => Promise.resolve(new Uint8Array()),
271 write: () => Promise.resolve(),
272 list: () => Promise.resolve([]),
273 mkdir: () => Promise.resolve(),
274 remove: () => Promise.resolve(),
275 rename: () => Promise.resolve(),
276 exists: (path) => Promise.resolve(path.endsWith('/.git')),
277 },
278 git: {
279 clone: () => Promise.reject(new Error('clone should be skipped')),
280 status: () => Promise.resolve(''),
281 add: () => Promise.resolve(),
282 commit: () => Promise.resolve(),
283 push: () => Promise.resolve(),
284 pull: () => Promise.resolve(),
285 branch: () => Promise.resolve('main'),
286 },
287 process: {
288 exec: (command, options) => {
289 execCalls.push({ command, options })
290 return Promise.resolve(ok)
291 },
292 spawn: () => {
293 const queue: Array<string> = []
294 const waiters: Array<(result: IteratorResult<string>) => void> = []
295 let done = false
296 function emit(chunk: string): void {
297 const waiter = waiters.shift()
298 if (waiter !== undefined) waiter({ value: chunk, done: false })
299 else queue.push(chunk)
300 }
301 const stdout: AsyncIterable<string> = {
302 [Symbol.asyncIterator](): AsyncIterator<string> {
303 return {
304 next(): Promise<IteratorResult<string>> {
305 const queued = queue.shift()
306 if (queued !== undefined) {
307 return Promise.resolve({ value: queued, done: false })
308 }
309 if (done) return Promise.resolve({ value: '', done: true })
310 return new Promise<IteratorResult<string>>((resolve) => {
311 waiters.push(resolve)
312 })
313 },
314 }
315 },
316 }
317 let counter = 0
318 const spawnHandle: SpawnHandle = {
319 pid: 1,
320 stdout,
321 stderr: (async function* empty() {})(),
322 stdin: {
323 write: (_data: string) => {
324 const sentinel = `__BSSH_${counter}__`
325 counter += 1
326 // The only serial command is `bad-cmd` → exit 7.
327 emit(`${sentinel} 7\n`)
328 return Promise.resolve()
329 },
330 end: () => {
331 done = true
332 for (const waiter of waiters) waiter({ value: '', done: true })
333 waiters.length = 0
334 return Promise.resolve()
335 },
336 },
337 wait: () => Promise.resolve(0),
338 kill: () => Promise.resolve(),
339 }
340 return Promise.resolve(spawnHandle)
341 },
342 },
343 ports: { connect: () => Promise.reject(new Error('ports not used')) },
344 env: { set: () => Promise.resolve() },
345 destroy: () => Promise.resolve(),
346 }
347 return handle
349​
350// ---------------------------------------------------------------------------
351// Helpers for the new provisioning tests
352// ---------------------------------------------------------------------------
353​
354interface CloneCall {
355 url: string
356 dir?: string
357 auth?: { username?: string; token: string }
358 depth?: number | 'full'
360​
361interface WriteCall {
362 path: string
363 content: string
365​
366/**
367 * Build a fake handle that:
368 * - Reports the source repo as already cloned (`fs.exists` → true for `/.git`).
369 * - Records git.clone and fs.write calls.
370 * - exec always resolves with exit 0 (symlinks succeed).
371 * - No persistent shell needed: workspace has no `setup`.
372 */
373function makeProvisioningHandle(identity?: {
374 provider?: string
375 workspaceRoot?: string
376}): {
377 handle: SandboxHandle
378 cloneCalls: Array<CloneCall>
379 writeCalls: Array<WriteCall>
380 execCalls: Array<ExecCall>
381} {
382 const cloneCalls: Array<CloneCall> = []
383 const writeCalls: Array<WriteCall> = []
384 const execCalls: Array<ExecCall> = []
385​
386 const handle: SandboxHandle = {
387 id: 'prov',
388 provider: identity?.provider ?? 'fake',
389 ...(identity?.workspaceRoot !== undefined
390 ? { workspaceRoot: identity.workspaceRoot }
391 : {}),
392 capabilities: {
393 fs: true,
394 exec: true,
395 env: true,
396 ports: false,
397 backgroundProcesses: false,
398 writableStdin: true,
399 killableProcesses: true,
400 snapshots: false,
401 networkPolicy: false,
402 durableFilesystem: false,
403 fork: false,
404 },
405 fs: {
406 read: () => Promise.resolve(''),
407 readBytes: () => Promise.resolve(new Uint8Array()),
408 write: (path, content) => {
409 writeCalls.push({ path, content: String(content) })
410 return Promise.resolve()
411 },
412 list: () => Promise.resolve([]),
413 mkdir: () => Promise.resolve(),
414 remove: () => Promise.resolve(),
415 rename: () => Promise.resolve(),
416 // Source is already cloned; skill dirs are not yet present.
417 exists: (path) => Promise.resolve(path.endsWith('/.git')),
418 },
419 git: {
420 clone: (opts) => {
421 cloneCalls.push(opts as CloneCall)
422 return Promise.resolve()
423 },
424 status: () => Promise.resolve(''),
425 add: () => Promise.resolve(),
426 commit: () => Promise.resolve(),
427 push: () => Promise.resolve(),
428 pull: () => Promise.resolve(),
429 branch: () => Promise.resolve('main'),
430 },
431 process: {
432 exec: (command, options) => {
433 execCalls.push({ command, options })
434 return Promise.resolve(ok)
435 },
436 spawn: () =>
437 Promise.reject(new Error('spawn not expected in these tests')),
438 },
439 ports: { connect: () => Promise.reject(new Error('ports not used')) },
440 env: { set: () => Promise.resolve() },
441 destroy: () => Promise.resolve(),
442 }
443​
444 return { handle, cloneCalls, writeCalls, execCalls }
446​
447// ---------------------------------------------------------------------------
448// gitSkill clone tests
449// ---------------------------------------------------------------------------
450​
451describe('bootstrapWorkspace gitSkill cloning', () => {
452 it('clones a short owner/repo reference to the default skill dir', async () => {
453 const { handle, cloneCalls } = makeProvisioningHandle()
454​
455 const workspace: WorkspaceDefinition = {
456 source: { type: 'git', url: 'https://github.com/me/app' },
457 skills: [gitSkill({ repo: 'me/x' })],
458 }
459​
460 await bootstrapWorkspace(handle, workspace)
461​
462 expect(cloneCalls).toHaveLength(1)
463 expect(cloneCalls[0]?.url).toBe('https://github.com/me/x.git')
464 expect(cloneCalls[0]?.dir).toBe('/workspace/.tanstack-skills/x')
465 expect(cloneCalls[0]?.depth).toBe(1)
466 expect(cloneCalls[0]?.auth).toBeUndefined()
467 })
468​
469 it('resolves a secret token into auth when secret is provided', async () => {
470 const secrets = createSecrets({ GH: 'ghp_tok' })
471 const { handle, cloneCalls } = makeProvisioningHandle()
472​
473 const workspace: WorkspaceDefinition = {
474 source: { type: 'git', url: 'https://github.com/me/app' },
475 secrets,
476 skills: [gitSkill({ repo: 'me/x', secret: secrets.GH })],
477 }
478​
479 await bootstrapWorkspace(handle, workspace)
480​
481 expect(cloneCalls).toHaveLength(1)
482 expect(cloneCalls[0]?.auth?.token).toBe('ghp_tok')
483 expect(cloneCalls[0]?.url).toBe('https://github.com/me/x.git')
484 expect(cloneCalls[0]?.dir).toBe('/workspace/.tanstack-skills/x')
485 })
486​
487 it('respects the explicit into override', async () => {
488 const { handle, cloneCalls } = makeProvisioningHandle()
489​
490 const workspace: WorkspaceDefinition = {
491 source: { type: 'git', url: 'https://github.com/me/app' },
492 skills: [gitSkill({ repo: 'me/x', into: '/opt/myskill' })],
493 }
494​
495 await bootstrapWorkspace(handle, workspace)
496​
497 expect(cloneCalls[0]?.dir).toBe('/opt/myskill')
498 })
499​
500 it('passes a full HTTPS url through unchanged', async () => {
501 const { handle, cloneCalls } = makeProvisioningHandle()
502​
503 const workspace: WorkspaceDefinition = {
504 source: { type: 'git', url: 'https://github.com/me/app' },
505 skills: [gitSkill({ repo: 'https://example.com/org/repo.git' })],
506 }
507​
508 await bootstrapWorkspace(handle, workspace)
509​
510 expect(cloneCalls[0]?.url).toBe('https://example.com/org/repo.git')
511 })
512​
513 // Daytona (and other remapped providers) cannot interpolate a virtual
514 // `/workspace` dir into a shell `git clone`. Clone against the real
515 // workspaceRoot instead. Issue #1081 item 4.
516 it('remaps a virtual gitSkill dir onto handle.workspaceRoot', async () => {
517 const { handle, cloneCalls } = makeProvisioningHandle({
518 provider: 'daytona',
519 workspaceRoot: '/home/daytona/workspace',
520 })
521​
522 const workspace: WorkspaceDefinition = {
523 source: { type: 'git', url: 'https://github.com/me/app' },
524 skills: [gitSkill({ repo: 'owner/skills-pack' })],
525 }
526​
527 await bootstrapWorkspace(handle, workspace)
528​
529 expect(cloneCalls[0]?.dir).toBe(
530 '/home/daytona/workspace/.tanstack-skills/skills-pack',
531 )
532 })
533})
534​
535// ---------------------------------------------------------------------------
536// Source clone depth forwarding tests
537// ---------------------------------------------------------------------------
538​
539/**
540 * Build a fake handle where `fs.exists` returns FALSE for the `.git` sentinel,
541 * so `bootstrapWorkspace` runs the source git clone. Records all clone calls.
542 */
543function makeUnclonedHandle(): {
544 handle: SandboxHandle
545 cloneCalls: Array<CloneCall>
546} {
547 const cloneCalls: Array<CloneCall> = []
548​
549 const handle: SandboxHandle = {
550 id: 'uncloned',
551 provider: 'fake',
552 capabilities: {
553 fs: true,
554 exec: true,
555 env: true,
556 ports: false,
557 backgroundProcesses: false,
558 writableStdin: true,
559 killableProcesses: true,
560 snapshots: false,
561 networkPolicy: false,
562 durableFilesystem: false,
563 fork: false,
564 },
565 fs: {
566 read: () => Promise.resolve(''),
567 readBytes: () => Promise.resolve(new Uint8Array()),
568 write: () => Promise.resolve(),
569 list: () => Promise.resolve([]),
570 mkdir: () => Promise.resolve(),
571 remove: () => Promise.resolve(),
572 rename: () => Promise.resolve(),
573 // Never cloned — source clone should run.
574 exists: () => Promise.resolve(false),
575 },
576 git: {
577 clone: (opts) => {
578 cloneCalls.push(opts as CloneCall)
579 return Promise.resolve()
580 },
581 status: () => Promise.resolve(''),
582 add: () => Promise.resolve(),
583 commit: () => Promise.resolve(),
584 push: () => Promise.resolve(),
585 pull: () => Promise.resolve(),
586 branch: () => Promise.resolve('main'),
587 },
588 process: {
589 exec: () => Promise.resolve(ok),
590 spawn: () => Promise.reject(new Error('spawn not expected')),
591 },
592 ports: { connect: () => Promise.reject(new Error('ports not used')) },
593 env: { set: () => Promise.resolve() },
594 destroy: () => Promise.resolve(),
595 }
596​
597 return { handle, cloneCalls }
599​
600describe('bootstrapWorkspace source clone depth', () => {
601 it('forwards depth: "full" from gitSource to git.clone', async () => {
602 const { handle, cloneCalls } = makeUnclonedHandle()
603​
604 const workspace: WorkspaceDefinition = {
605 source: gitSource({ url: 'https://github.com/me/app', depth: 'full' }),
606 }
607​
608 await bootstrapWorkspace(handle, workspace)
609​
610 expect(cloneCalls).toHaveLength(1)
611 expect(cloneCalls[0]?.url).toBe('https://github.com/me/app')
612 expect(cloneCalls[0]?.depth).toBe('full')
613 })
614​
615 it('forwards a numeric depth from gitSource to git.clone', async () => {
616 const { handle, cloneCalls } = makeUnclonedHandle()
617​
618 const workspace: WorkspaceDefinition = {
619 source: gitSource({ url: 'https://github.com/me/app', depth: 10 }),
620 }
621​
622 await bootstrapWorkspace(handle, workspace)
623​
624 expect(cloneCalls).toHaveLength(1)
625 expect(cloneCalls[0]?.depth).toBe(10)
626 })
627​
628 it('omits depth from git.clone when not specified on the source', async () => {
629 const { handle, cloneCalls } = makeUnclonedHandle()
630​
631 const workspace: WorkspaceDefinition = {
632 source: gitSource({ url: 'https://github.com/me/app' }),
633 }
634​
635 await bootstrapWorkspace(handle, workspace)
636​
637 expect(cloneCalls).toHaveLength(1)
638 expect(cloneCalls[0]?.depth).toBeUndefined()
639 })
640})
641​
642// ---------------------------------------------------------------------------
643// resolveGitSkillDir unit tests
644// ---------------------------------------------------------------------------
645​
646describe('resolveGitSkillDir', () => {
647 it('strips .git suffix from basename', () => {
648 const skill = gitSkill({ repo: 'me/x' }) as Extract<
649 ReturnType<typeof gitSkill>,
650 { kind: 'git' }
651 >
652 // repo has no .git suffix here — should still work
653 expect(resolveGitSkillDir('/workspace', skill)).toBe(
654 '/workspace/.tanstack-skills/x',
655 )
656 })
657​
658 it('strips trailing .git when the repo url ends with .git', () => {
659 const skill = gitSkill({ repo: 'me/repo.git' }) as Extract<
660 ReturnType<typeof gitSkill>,
661 { kind: 'git' }
662 >
663 expect(resolveGitSkillDir('/workspace', skill)).toBe(
664 '/workspace/.tanstack-skills/repo',
665 )
666 })
667​
668 it('uses last path segment for full https urls', () => {
669 const skill = gitSkill({
670 repo: 'https://github.com/org/myskill.git',
671 }) as Extract<ReturnType<typeof gitSkill>, { kind: 'git' }>
672 expect(resolveGitSkillDir('/workspace', skill)).toBe(
673 '/workspace/.tanstack-skills/myskill',
674 )
675 })
676})
677​
678// ---------------------------------------------------------------------------
679// AGENTS.md + instructions tests
680// ---------------------------------------------------------------------------
681​
682describe('bootstrapWorkspace AGENTS.md + instructions', () => {
683 it('writes AGENTS.md via fs.write when instructions is set', async () => {
684 const { handle, writeCalls } = makeProvisioningHandle()
685​
686 const workspace: WorkspaceDefinition = {
687 source: { type: 'git', url: 'https://github.com/me/app' },
688 instructions: 'You are a helpful assistant.',
689 }
690​
691 await bootstrapWorkspace(handle, workspace)
692​
693 const agentsWrite = writeCalls.find(
694 (w) => w.path === '/workspace/AGENTS.md',
695 )
696 expect(agentsWrite).toBeDefined()
697 expect(agentsWrite?.content).toBe('You are a helpful assistant.')
698 })
699​
700 it('writes AGENTS.md from a fileSkill when instructions is absent', async () => {
701 const { handle, writeCalls } = makeProvisioningHandle()
702​
703 const workspace: WorkspaceDefinition = {
704 source: { type: 'git', url: 'https://github.com/me/app' },
705 skills: [
706 fileSkill({ path: 'AGENTS.md', content: 'Skill instructions.' }),
707 ],
708 }
709​
710 await bootstrapWorkspace(handle, workspace)
711​
712 const agentsWrite = writeCalls.find(
713 (w) => w.path === '/workspace/AGENTS.md',
714 )
715 expect(agentsWrite).toBeDefined()
716 expect(agentsWrite?.content).toBe('Skill instructions.')
717 })
718​
719 it('prefers instructions over a fileSkill AGENTS.md', async () => {
720 const { handle, writeCalls } = makeProvisioningHandle()
721​
722 const workspace: WorkspaceDefinition = {
723 source: { type: 'git', url: 'https://github.com/me/app' },
724 instructions: 'Direct instructions.',
725 skills: [
726 fileSkill({ path: 'AGENTS.md', content: 'Skill instructions.' }),
727 ],
728 }
729​
730 await bootstrapWorkspace(handle, workspace)
731​
732 const agentsWrites = writeCalls.filter(
733 (w) => w.path === '/workspace/AGENTS.md',
734 )
735 // Only one AGENTS.md write; it should use the direct instructions.
736 expect(agentsWrites).toHaveLength(1)
737 expect(agentsWrites[0]?.content).toBe('Direct instructions.')
738 })
739​
740 it('does not write AGENTS.md when instructions is empty and no fileSkill', async () => {
741 const { handle, writeCalls } = makeProvisioningHandle()
742​
743 const workspace: WorkspaceDefinition = {
744 source: { type: 'git', url: 'https://github.com/me/app' },
745 }
746​
747 await bootstrapWorkspace(handle, workspace)
748​
749 const agentsWrite = writeCalls.find((w) => w.path.endsWith('AGENTS.md'))
750 expect(agentsWrite).toBeUndefined()
751 })
752​
753 it('writes AGENTS.md with a Workspace scripts section when only scripts is set', async () => {
754 const { handle, writeCalls } = makeProvisioningHandle()
755​
756 const workspace: WorkspaceDefinition = {
757 source: { type: 'git', url: 'https://github.com/me/app' },
758 scripts: { test: 'pnpm test', build: 'pnpm build' },
759 }
760​
761 await bootstrapWorkspace(handle, workspace)
762​
763 const agentsWrite = writeCalls.find(
764 (w) => w.path === '/workspace/AGENTS.md',
765 )
766 expect(agentsWrite).toBeDefined()
767 expect(agentsWrite?.content).toContain('## Workspace scripts')
768 expect(agentsWrite?.content).toContain('- build → pnpm build')
769 expect(agentsWrite?.content).toContain('- test → pnpm test')
770 })
771​
772 it('merges instructions with the Workspace scripts section', async () => {
773 const { handle, writeCalls } = makeProvisioningHandle()
774​
775 const workspace: WorkspaceDefinition = {
776 source: { type: 'git', url: 'https://github.com/me/app' },
777 instructions: 'You are a helpful assistant.',
778 scripts: { test: 'pnpm test' },
779 }
780​
781 await bootstrapWorkspace(handle, workspace)
782​
783 const agentsWrite = writeCalls.find(
784 (w) => w.path === '/workspace/AGENTS.md',
785 )
786 expect(agentsWrite?.content).toBe(
787 'You are a helpful assistant.\n\n## Workspace scripts\n\n- test → pnpm test',
788 )
789 })
790​
791 it('merges a fileSkill AGENTS.md with the Workspace scripts section', async () => {
792 const { handle, writeCalls } = makeProvisioningHandle()
793​
794 const workspace: WorkspaceDefinition = {
795 source: { type: 'git', url: 'https://github.com/me/app' },
796 skills: [
797 fileSkill({ path: 'AGENTS.md', content: 'Skill instructions.' }),
798 ],
799 scripts: { lint: 'pnpm lint' },
800 }
801​
802 await bootstrapWorkspace(handle, workspace)
803​
804 const agentsWrite = writeCalls.find(
805 (w) => w.path === '/workspace/AGENTS.md',
806 )
807 expect(agentsWrite?.content).toBe(
808 'Skill instructions.\n\n## Workspace scripts\n\n- lint → pnpm lint',
809 )
810 })
811})
812​
813// ---------------------------------------------------------------------------
814// Non-AGENTS fileSkill tests
815// ---------------------------------------------------------------------------
816​
817describe('bootstrapWorkspace non-AGENTS fileSkills', () => {
818 it('writes a non-AGENTS fileSkill to the workspace root', async () => {
819 const { handle, writeCalls } = makeProvisioningHandle()
820​
821 const workspace: WorkspaceDefinition = {
822 source: { type: 'git', url: 'https://github.com/me/app' },
823 skills: [fileSkill({ path: '.env.example', content: 'KEY=value' })],
824 }
825​
826 await bootstrapWorkspace(handle, workspace)
827​
828 const fileWrite = writeCalls.find(
829 (w) => w.path === '/workspace/.env.example',
830 )
831 expect(fileWrite).toBeDefined()
832 expect(fileWrite?.content).toBe('KEY=value')
833 })
834​
835 it('writes multiple non-AGENTS fileSkills', async () => {
836 const { handle, writeCalls } = makeProvisioningHandle()
837​
838 const workspace: WorkspaceDefinition = {
839 source: { type: 'git', url: 'https://github.com/me/app' },
840 skills: [
841 fileSkill({ path: 'a.txt', content: 'aaa' }),
842 fileSkill({ path: 'b.txt', content: 'bbb' }),
843 ],
844 }
845​
846 await bootstrapWorkspace(handle, workspace)
847​
848 const paths = writeCalls.map((w) => w.path)
849 expect(paths).toContain('/workspace/a.txt')
850 expect(paths).toContain('/workspace/b.txt')
851 })
852​
853 it('passes its signal to the fs calls', async () => {
854 const { handle } = makeProvisioningHandle()
855 const signals: Array<AbortSignal | undefined> = []
856 const { exists, write } = handle.fs
857 handle.fs.exists = (path, options) => {
858 signals.push(options?.signal)
859 return exists(path)
860 }
861 handle.fs.write = (path, data, options) => {
862 signals.push(options?.signal)
863 return write(path, data)
864 }
865 const signal = new AbortController().signal
866​
867 await bootstrapWorkspace(
868 handle,
869 {
870 source: { type: 'git', url: 'https://github.com/me/app' },
871 instructions: 'Be nice.',
872 skills: [fileSkill({ path: 'a.txt', content: 'aaa' })],
873 },
874 { signal },
875 )
876​
877 // .git, AGENTS.md, a.txt and the lockfiles.
878 expect(signals.length).toBeGreaterThan(3)
879 expect(new Set(signals)).toEqual(new Set([signal]))
880 })
881​
882 it('does not re-write an AGENTS.md fileSkill through the generic path', async () => {
883 const { handle, writeCalls } = makeProvisioningHandle()
884​
885 const workspace: WorkspaceDefinition = {
886 source: { type: 'git', url: 'https://github.com/me/app' },
887 skills: [
888 fileSkill({ path: 'AGENTS.md', content: 'Skill instructions.' }),
889 ],
890 }
891​
892 await bootstrapWorkspace(handle, workspace)
893​
894 // Should appear exactly once (via writeAgentsFile, not the generic loop).
895 const agentsWrites = writeCalls.filter(
896 (w) => w.path === '/workspace/AGENTS.md',
897 )
898 expect(agentsWrites).toHaveLength(1)
899 })
900})