@namzu/sandbox 14.0.0 → 16.0.0

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 (100) hide show
  1. package/CHANGELOG.md +924 -0
  2. package/README.md +369 -14
  3. package/dist/backends/aci-standby-pool/index.d.ts.map +1 -1
  4. package/dist/backends/aci-standby-pool/index.js +13 -1
  5. package/dist/backends/aci-standby-pool/index.js.map +1 -1
  6. package/dist/backends/docker/index.d.ts +169 -6
  7. package/dist/backends/docker/index.d.ts.map +1 -1
  8. package/dist/backends/docker/index.js +499 -85
  9. package/dist/backends/docker/index.js.map +1 -1
  10. package/dist/backends/firecracker/index.d.ts.map +1 -1
  11. package/dist/backends/firecracker/index.js +12 -2
  12. package/dist/backends/firecracker/index.js.map +1 -1
  13. package/dist/backends/firecracker/protocol.d.ts +459 -8
  14. package/dist/backends/firecracker/protocol.d.ts.map +1 -1
  15. package/dist/backends/firecracker/protocol.js +136 -0
  16. package/dist/backends/firecracker/protocol.js.map +1 -1
  17. package/dist/backends/firecracker/transport.d.ts +539 -6
  18. package/dist/backends/firecracker/transport.d.ts.map +1 -1
  19. package/dist/backends/firecracker/transport.js +1171 -24
  20. package/dist/backends/firecracker/transport.js.map +1 -1
  21. package/dist/backends/kubernetes/egress-policy.d.ts +1181 -13
  22. package/dist/backends/kubernetes/egress-policy.d.ts.map +1 -1
  23. package/dist/backends/kubernetes/egress-policy.js +2350 -31
  24. package/dist/backends/kubernetes/egress-policy.js.map +1 -1
  25. package/dist/backends/kubernetes/identity.d.ts +193 -0
  26. package/dist/backends/kubernetes/identity.d.ts.map +1 -0
  27. package/dist/backends/kubernetes/identity.js +147 -0
  28. package/dist/backends/kubernetes/identity.js.map +1 -0
  29. package/dist/backends/kubernetes/index.d.ts +678 -33
  30. package/dist/backends/kubernetes/index.d.ts.map +1 -1
  31. package/dist/backends/kubernetes/index.js +1180 -95
  32. package/dist/backends/kubernetes/index.js.map +1 -1
  33. package/dist/backends/kubernetes/ingress-policy.d.ts +375 -0
  34. package/dist/backends/kubernetes/ingress-policy.d.ts.map +1 -0
  35. package/dist/backends/kubernetes/ingress-policy.js +1050 -0
  36. package/dist/backends/kubernetes/ingress-policy.js.map +1 -0
  37. package/dist/backends/kubernetes/k8s-client.d.ts +213 -4
  38. package/dist/backends/kubernetes/k8s-client.d.ts.map +1 -1
  39. package/dist/backends/kubernetes/k8s-client.js +359 -52
  40. package/dist/backends/kubernetes/k8s-client.js.map +1 -1
  41. package/dist/backends/kubernetes/lease.d.ts +40 -14
  42. package/dist/backends/kubernetes/lease.d.ts.map +1 -1
  43. package/dist/backends/kubernetes/lease.js +68 -18
  44. package/dist/backends/kubernetes/lease.js.map +1 -1
  45. package/dist/backends/kubernetes/objects.d.ts +423 -3
  46. package/dist/backends/kubernetes/objects.d.ts.map +1 -1
  47. package/dist/backends/kubernetes/objects.js +364 -2
  48. package/dist/backends/kubernetes/objects.js.map +1 -1
  49. package/dist/backends/kubernetes/per-sandbox-policy.d.ts +219 -0
  50. package/dist/backends/kubernetes/per-sandbox-policy.d.ts.map +1 -0
  51. package/dist/backends/kubernetes/per-sandbox-policy.js +375 -0
  52. package/dist/backends/kubernetes/per-sandbox-policy.js.map +1 -0
  53. package/dist/backends/kubernetes/rbac.d.ts +153 -0
  54. package/dist/backends/kubernetes/rbac.d.ts.map +1 -0
  55. package/dist/backends/kubernetes/rbac.js +177 -0
  56. package/dist/backends/kubernetes/rbac.js.map +1 -0
  57. package/dist/backends/kubernetes/sandbox.d.ts +81 -14
  58. package/dist/backends/kubernetes/sandbox.d.ts.map +1 -1
  59. package/dist/backends/kubernetes/sandbox.js +149 -15
  60. package/dist/backends/kubernetes/sandbox.js.map +1 -1
  61. package/dist/backends/kubernetes/transport.d.ts +935 -9
  62. package/dist/backends/kubernetes/transport.d.ts.map +1 -1
  63. package/dist/backends/kubernetes/transport.js +1958 -62
  64. package/dist/backends/kubernetes/transport.js.map +1 -1
  65. package/dist/backends/kubernetes/workspace.d.ts +1149 -18
  66. package/dist/backends/kubernetes/workspace.d.ts.map +1 -1
  67. package/dist/backends/kubernetes/workspace.js +2825 -186
  68. package/dist/backends/kubernetes/workspace.js.map +1 -1
  69. package/dist/backends/remote-execution-controller.d.ts +14 -0
  70. package/dist/backends/remote-execution-controller.d.ts.map +1 -1
  71. package/dist/backends/remote-execution-controller.js.map +1 -1
  72. package/dist/index.d.ts +294 -18
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +280 -10
  75. package/dist/index.js.map +1 -1
  76. package/dist/testing/sandbox-conformance.d.ts +39 -5
  77. package/dist/testing/sandbox-conformance.d.ts.map +1 -1
  78. package/dist/testing/sandbox-conformance.js +436 -5
  79. package/dist/testing/sandbox-conformance.js.map +1 -1
  80. package/package.json +3 -3
  81. package/src/backends/aci-standby-pool/index.ts +16 -1
  82. package/src/backends/docker/index.ts +617 -100
  83. package/src/backends/firecracker/index.ts +14 -2
  84. package/src/backends/firecracker/protocol.ts +514 -6
  85. package/src/backends/firecracker/transport.ts +1492 -40
  86. package/src/backends/kubernetes/egress-policy.ts +3334 -55
  87. package/src/backends/kubernetes/identity.ts +261 -0
  88. package/src/backends/kubernetes/index.ts +1785 -127
  89. package/src/backends/kubernetes/ingress-policy.ts +1344 -0
  90. package/src/backends/kubernetes/k8s-client.ts +444 -54
  91. package/src/backends/kubernetes/lease.ts +75 -19
  92. package/src/backends/kubernetes/objects.ts +626 -6
  93. package/src/backends/kubernetes/per-sandbox-policy.ts +497 -0
  94. package/src/backends/kubernetes/rbac.ts +192 -0
  95. package/src/backends/kubernetes/sandbox.ts +218 -20
  96. package/src/backends/kubernetes/transport.ts +2733 -124
  97. package/src/backends/kubernetes/workspace.ts +4476 -222
  98. package/src/backends/remote-execution-controller.ts +14 -0
  99. package/src/index.ts +668 -19
  100. package/src/testing/sandbox-conformance.ts +540 -5
@@ -28,10 +28,10 @@
28
28
  * Contract behaviour only — never a backend-specific object, field or
29
29
  * error string. A case never inspects `sandbox.constructor.name`, never
30
30
  * matches an error message, and never assumes a particular
31
- * {@link SandboxEnvironment}. `openTerminal` and `openTcpConnection` are
32
- * OPTIONAL on {@link Sandbox} by the SDK's own contract — a backend that
33
- * cannot honour one must omit it rather than accept and ignore it — so a
34
- * factory whose sandbox omits either capability skips that section rather
31
+ * {@link SandboxEnvironment}. `openTerminal`, `openTcpConnection` and
32
+ * `walkFiles` are OPTIONAL on {@link Sandbox} by the SDK's own contract — a
33
+ * backend that cannot honour one must omit it rather than accept and ignore
34
+ * it — so a factory whose sandbox omits any of them skips that section rather
35
35
  * than failing it. Every other section runs against every sandbox.
36
36
  *
37
37
  * ## Where it runs today
@@ -61,12 +61,16 @@
61
61
  * ```
62
62
  */
63
63
 
64
+ import { createHash } from 'node:crypto'
64
65
  import type {
65
66
  OpenTerminalOptions,
66
67
  Sandbox,
68
+ SandboxExecResult,
67
69
  SandboxTcpConnectOptions,
70
+ SandboxWalkFilesOptions,
68
71
  TerminalSession,
69
72
  } from '@namzu/sdk'
73
+
70
74
  import type {
71
75
  ConformanceAssertion,
72
76
  ConformanceDescribe,
@@ -79,8 +83,24 @@ import type {
79
83
  * label so a failure is legible on sight as "the sandbox contract", the
80
84
  * same convention `PROVIDER_DRIVER_CONTRACT_VERSION` uses — raised only
81
85
  * when a case is ADDED or TIGHTENED, never on a rewording.
86
+ *
87
+ * 3 is the `walkFiles`, concurrent-`exec` and `exec`-timeout sections, none
88
+ * of which needs a guest feature that did not already exist.
89
+ *
90
+ * **The ranged and streamed read cases deliberately did NOT raise it
91
+ * further.** Raising it for them would assert that every backend this suite
92
+ * runs against implements them, and one does not: the Firecracker tier's
93
+ * guest lives in a golden rootfs image that is NOT built from this
94
+ * repository — nothing here builds one, `packages/sandbox/package.json#files`
95
+ * does not even ship `agent/`, and `README.md` documents the image as
96
+ * something the operator builds and canaries on their own schedule. A
97
+ * deployment therefore runs whatever agent its last image build baked in,
98
+ * and a contract version that claimed otherwise would be a claim about
99
+ * images this repository cannot see. Those two cases are gated on
100
+ * {@link SandboxConformanceOptions.supportsRangedAndStreamedReads}
101
+ * instead, and skip by name when a backend does not declare them.
82
102
  */
83
- export const SANDBOX_CONTRACT_VERSION = 1
103
+ export const SANDBOX_CONTRACT_VERSION = 3
84
104
 
85
105
  /** A sandbox to test, plus whatever teardown building it required. */
86
106
  export interface SandboxConformanceHandle {
@@ -134,6 +154,24 @@ export interface SandboxConformanceOptions {
134
154
  * {@link GuestListenerCommand.parsePort} expects.
135
155
  */
136
156
  readonly guestListenerCommand?: () => GuestListenerCommand
157
+ /**
158
+ * Whether this backend's guest honours `readFile`'s `offset`/`length`
159
+ * and implements {@link Sandbox.readFileStream}.
160
+ *
161
+ * **Defaults to `false`, and the default is the honest one.** These
162
+ * cases are not in {@link SANDBOX_CONTRACT_VERSION} — see the comment
163
+ * on that constant for why — so the suite cannot assume a backend has
164
+ * them. A backend whose guest is built from this repository sets it
165
+ * `true`; every other backend gets the cases as named skips, counted in
166
+ * the runner's own totals and titled with the reason, rather than as
167
+ * failures for a contract it never agreed to.
168
+ *
169
+ * A backend that sets this `true` while its guest ignores
170
+ * `offset`/`length` FAILS, and that is the point: returning the whole
171
+ * file where a slice was asked for is a wrong answer, not a missing
172
+ * capability.
173
+ */
174
+ readonly supportsRangedAndStreamedReads?: boolean
137
175
  }
138
176
 
139
177
  /** Assert `call()` rejects. The contract cares that admission was refused, never the message. */
@@ -168,6 +206,36 @@ function sleep(ms: number): Promise<void> {
168
206
  return new Promise((resolve) => setTimeout(resolve, ms))
169
207
  }
170
208
 
209
+ /**
210
+ * `size` bytes of deterministic pseudo-random content (xorshift32 from a
211
+ * fixed seed).
212
+ *
213
+ * Pseudo-random rather than a repeated byte because the large-body case
214
+ * below is about whether every byte survived in the right ORDER: a body of
215
+ * one repeated value passes a length check and a content check even if the
216
+ * transport shipped its pieces out of order, duplicated one, or dropped
217
+ * one and padded. Deterministic rather than `randomBytes` so a failure is
218
+ * reproducible from the size alone.
219
+ */
220
+ function deterministicBytes(size: number): Buffer {
221
+ const out = Buffer.allocUnsafe(size)
222
+ let x = 0x9e3779b9
223
+ for (let i = 0; i < size; i += 1) {
224
+ x ^= x << 13
225
+ x >>>= 0
226
+ x ^= x >> 17
227
+ x ^= x << 5
228
+ x >>>= 0
229
+ out[i] = x & 0xff
230
+ }
231
+ return out
232
+ }
233
+
234
+ /** `sha256` of a buffer, hex — a byte-exact comparison that prints short. */
235
+ function digest(buffer: Buffer): string {
236
+ return createHash('sha256').update(buffer).digest('hex')
237
+ }
238
+
171
239
  /**
172
240
  * A program the `openTcpConnection` positive case can start INSIDE a guest
173
241
  * through {@link Sandbox.openTerminal}, and dial back into over
@@ -311,6 +379,7 @@ export function defineSandboxConformance(options: SandboxConformanceOptions): vo
311
379
  const label = options.label ?? 'sandbox'
312
380
  const guestCanRunNode = options.guestCanRunNode ?? true
313
381
  const guestListenerCommand = options.guestListenerCommand ?? nodeGuestListener
382
+ const supportsRangedAndStreamedReads = options.supportsRangedAndStreamedReads ?? false
314
383
 
315
384
  /**
316
385
  * Run `body` against a sandbox built for this case alone.
@@ -332,6 +401,24 @@ export function defineSandboxConformance(options: SandboxConformanceOptions): vo
332
401
  }
333
402
  }
334
403
 
404
+ /**
405
+ * A case that needs {@link SandboxConformanceOptions.supportsRangedAndStreamedReads}.
406
+ *
407
+ * The skip is deliberately visible: the reason is in the case's TITLE and
408
+ * the case still runs and is counted in the runner's totals, which is what
409
+ * {@link SANDBOX_CONTRACT_VERSION}'s note asks for. What it does not do is
410
+ * build a sandbox to skip inside — `withSandbox` is applied only on the
411
+ * branch that uses one, so a backend without the capability pays nothing
412
+ * per skipped case.
413
+ */
414
+ const rangedReadCase = (
415
+ title: string,
416
+ body: (sandbox: Sandbox) => Promise<void>,
417
+ ): [string, () => Promise<void>] =>
418
+ supportsRangedAndStreamedReads
419
+ ? [title, withSandbox(body)]
420
+ : [`${title} (skipped: supportsRangedAndStreamedReads is false)`, async () => {}]
421
+
335
422
  describe(`${label} — sandbox contract v${SANDBOX_CONTRACT_VERSION}`, () => {
336
423
  describe('exec', () => {
337
424
  it(
@@ -458,6 +545,123 @@ export function defineSandboxConformance(options: SandboxConformanceOptions): vo
458
545
  expect(read.toString('base64')).toBe(payload.toString('base64'))
459
546
  }),
460
547
  )
548
+
549
+ /**
550
+ * A body too large to cross the wire in ONE message.
551
+ *
552
+ * 7 MiB is chosen against a real number rather than a round one:
553
+ * a `write-file` body travels base64-encoded inside the request
554
+ * envelope, so 7 MiB of content is ~9.3 MiB of frame — past the
555
+ * 8 MiB ceiling the guest agent enforces on an unauthenticated
556
+ * connection's first frame, which on a transport that dials
557
+ * fresh per call is EVERY frame. That ceiling used to make this
558
+ * case a documented refusal on the kubernetes backend while the
559
+ * host-local backends served it without noticing, which is
560
+ * exactly the shape of divergence a contract suite exists to
561
+ * catch: `Sandbox.writeFile` promises to write a file, and a
562
+ * caller seeding a repository archive into a workspace cannot
563
+ * be told that the promise holds below a number nothing in the
564
+ * interface names.
565
+ *
566
+ * Compared by digest, not by content: a mismatch here belongs in
567
+ * the failure message as a short string, and 7 MiB of base64
568
+ * does not.
569
+ */
570
+ it(
571
+ 'round-trips a body larger than one wire frame',
572
+ withSandbox(async (sandbox) => {
573
+ const payload = deterministicBytes(7 * 1024 * 1024)
574
+ await sandbox.writeFile('conformance-large/archive.bin', payload)
575
+ const read = await sandbox.readFile('conformance-large/archive.bin')
576
+ expect(read.length).toBe(payload.length)
577
+ expect(digest(read)).toBe(digest(payload))
578
+ }),
579
+ )
580
+
581
+ /**
582
+ * A read ABOVE the ceiling the case above sits below.
583
+ *
584
+ * 7 MiB is chosen for what the WRITE costs — 9.3 MiB of base64
585
+ * envelope, past the guest's 8 MiB pre-auth frame limit — and a
586
+ * reply frame is not measured against that limit at all, so that
587
+ * case proves nothing about the read side. 9 MiB is above the
588
+ * number on both sides of the wire, which is the only way to tell
589
+ * a backend that reads a file in bounded pieces from one that
590
+ * hands back a single reply and hopes.
591
+ *
592
+ * Skipped by NAME, and counted in the runner's totals as a case,
593
+ * for a backend that has not declared the capability — see
594
+ * {@link SandboxConformanceOptions.supportsRangedAndStreamedReads}
595
+ * and the note on {@link SANDBOX_CONTRACT_VERSION}.
596
+ */
597
+ it(
598
+ ...rangedReadCase(
599
+ 'reads a file larger than one wire frame back in bounded pieces',
600
+ async (sandbox) => {
601
+ const payload = deterministicBytes(9 * 1024 * 1024)
602
+ await sandbox.writeFile('conformance-large/wide.bin', payload)
603
+
604
+ const whole = await sandbox.readFile('conformance-large/wide.bin')
605
+ expect(whole.length).toBe(payload.length)
606
+ expect(digest(whole)).toBe(digest(payload))
607
+
608
+ // A backend declaring the capability must expose the stream
609
+ // too: the whole point is that a caller can read a file it
610
+ // could not hold, and `readFile` hands back one buffer.
611
+ const readFileStream = sandbox.readFileStream
612
+ if (!readFileStream) {
613
+ throw new Error(
614
+ 'supportsRangedAndStreamedReads is true but this sandbox has no readFileStream. ' +
615
+ 'A backend that honours offset/length but cannot stream must pass ' +
616
+ 'supportsRangedAndStreamedReads: false and state why.',
617
+ )
618
+ }
619
+ const chunks: Buffer[] = []
620
+ for await (const chunk of readFileStream.call(sandbox, 'conformance-large/wide.bin')) {
621
+ chunks.push(Buffer.from(chunk))
622
+ }
623
+ // More than one chunk is what "bounded pieces" means; a
624
+ // backend yielding the whole file once satisfies the
625
+ // signature and none of the promise.
626
+ expect(chunks.length > 1).toBe(true)
627
+ expect(digest(Buffer.concat(chunks))).toBe(digest(payload))
628
+ },
629
+ ),
630
+ )
631
+
632
+ /**
633
+ * A slice, and the three things a slice has to get right: the
634
+ * bytes, a range that runs off the end, and the fact that asking
635
+ * for one must not hand back the whole file.
636
+ */
637
+ it(
638
+ ...rangedReadCase(
639
+ 'reads an explicit byte range, and clips it to the end of the file',
640
+ async (sandbox) => {
641
+ const payload = deterministicBytes(64 * 1024)
642
+ await sandbox.writeFile('conformance-range/slice.bin', payload)
643
+
644
+ const middle = await sandbox.readFile('conformance-range/slice.bin', {
645
+ offset: 1_000,
646
+ length: 256,
647
+ })
648
+ expect(middle.length).toBe(256)
649
+ expect(middle.toString('base64')).toBe(
650
+ payload.subarray(1_000, 1_256).toString('base64'),
651
+ )
652
+
653
+ // Past the end returns what exists rather than failing: a
654
+ // caller resuming from a remembered offset cannot be made to
655
+ // know the answer before it asks.
656
+ const straddling = await sandbox.readFile('conformance-range/slice.bin', {
657
+ offset: payload.length - 10,
658
+ length: 500,
659
+ })
660
+ expect(straddling.length).toBe(10)
661
+ expect(straddling.toString('base64')).toBe(payload.subarray(-10).toString('base64'))
662
+ },
663
+ ),
664
+ )
461
665
  })
462
666
 
463
667
  describe('listFiles', () => {
@@ -658,6 +862,337 @@ export function defineSandboxConformance(options: SandboxConformanceOptions): vo
658
862
  }),
659
863
  )
660
864
  })
865
+
866
+ /**
867
+ * Optional on {@link Sandbox} by the SDK's own contract, and the same
868
+ * documented skip as `openTerminal`: a factory whose sandbox omits
869
+ * `walkFiles` passes every case below vacuously. It is not a small
870
+ * omission to make, though — the SDK's `glob` and `grep` builtins
871
+ * REFUSE a sandbox that has no `walkFiles`, so a host that registers
872
+ * the default builtin set and moves to such a backend loses both
873
+ * tools with no change on its own side.
874
+ *
875
+ * What is asserted here is the contract's own wording: absolute paths,
876
+ * regular files only, symlinks not followed, the bounds honoured by
877
+ * whoever does the walking, and — the one that is easy to get wrong —
878
+ * an exhausted examined-entry budget raising an error carrying
879
+ * `ERR_FILE_WALK_LIMIT` rather than handing back a short list a caller
880
+ * would read as complete.
881
+ */
882
+ describe('walkFiles', () => {
883
+ /**
884
+ * Every path this walk yielded, sorted.
885
+ *
886
+ * `walkFiles` is called through `.call(sandbox, …)` for the same
887
+ * reason `openTerminal` is above: it may be an ordinary method
888
+ * relying on `this`, and detaching it would drop that binding.
889
+ */
890
+ const walkPaths = async (
891
+ sandbox: Sandbox,
892
+ root: string,
893
+ options: SandboxWalkFilesOptions,
894
+ ): Promise<string[]> => {
895
+ const walk = sandbox.walkFiles
896
+ if (!walk) throw new Error('unreachable: every case guards on walkFiles first')
897
+ const paths: string[] = []
898
+ for await (const entry of walk.call(sandbox, root, options)) paths.push(entry.path)
899
+ return paths.sort()
900
+ }
901
+
902
+ it(
903
+ 'yields written files as absolute paths with their sizes, bounded by maxEntries',
904
+ withSandbox(async (sandbox) => {
905
+ if (!sandbox.walkFiles) return
906
+ await sandbox.writeFile('conformance-walk/a.txt', '1')
907
+ await sandbox.writeFile('conformance-walk/b.txt', '22')
908
+ await sandbox.writeFile('conformance-walk/c.txt', '333')
909
+ const dir = `${sandbox.rootDir}/conformance-walk`
910
+
911
+ const sizes = new Map<string, number>()
912
+ const walk = sandbox.walkFiles
913
+ for await (const entry of walk.call(sandbox, dir, { maxEntries: 10 })) {
914
+ sizes.set(entry.path, entry.size)
915
+ }
916
+ expect([...sizes.keys()].sort()).toEqual([`${dir}/a.txt`, `${dir}/b.txt`, `${dir}/c.txt`])
917
+ expect(sizes.get(`${dir}/c.txt`)).toBe(3)
918
+
919
+ // The bound is on what is EMITTED, so a walk asked for two
920
+ // entries yields two and stops — it does not yield three and
921
+ // leave the caller to discard one.
922
+ expect((await walkPaths(sandbox, dir, { maxEntries: 2 })).length).toBe(2)
923
+ }),
924
+ )
925
+
926
+ it(
927
+ 'bounds the descent with maxDepth, counting direct children as depth 1',
928
+ withSandbox(async (sandbox) => {
929
+ if (!sandbox.walkFiles) return
930
+ await sandbox.writeFile('conformance-depth/top.txt', 'top')
931
+ await sandbox.writeFile('conformance-depth/one/mid.txt', 'mid')
932
+ await sandbox.writeFile('conformance-depth/one/two/deep.txt', 'deep')
933
+ const dir = `${sandbox.rootDir}/conformance-depth`
934
+
935
+ expect(await walkPaths(sandbox, dir, { maxEntries: 50, maxDepth: 1 })).toEqual([
936
+ `${dir}/top.txt`,
937
+ ])
938
+ expect(await walkPaths(sandbox, dir, { maxEntries: 50, maxDepth: 2 })).toEqual([
939
+ `${dir}/one/mid.txt`,
940
+ `${dir}/top.txt`,
941
+ ])
942
+ }),
943
+ )
944
+
945
+ it(
946
+ 'keeps hidden names out of a wildcard unless includeHidden is set',
947
+ withSandbox(async (sandbox) => {
948
+ if (!sandbox.walkFiles) return
949
+ await sandbox.writeFile('conformance-hidden/visible.txt', 'v')
950
+ await sandbox.writeFile('conformance-hidden/.secret.txt', 'h')
951
+ const dir = `${sandbox.rootDir}/conformance-hidden`
952
+
953
+ expect(await walkPaths(sandbox, dir, { maxEntries: 50 })).toEqual([`${dir}/visible.txt`])
954
+ expect(await walkPaths(sandbox, dir, { maxEntries: 50, includeHidden: true })).toEqual([
955
+ `${dir}/.secret.txt`,
956
+ `${dir}/visible.txt`,
957
+ ])
958
+ }),
959
+ )
960
+
961
+ it(
962
+ 'reports a root that does not exist as an empty walk rather than failing',
963
+ withSandbox(async (sandbox) => {
964
+ if (!sandbox.walkFiles) return
965
+ const paths = await walkPaths(sandbox, `${sandbox.rootDir}/conformance-never-walked`, {
966
+ maxEntries: 10,
967
+ })
968
+ expect(paths.length).toBe(0)
969
+ }),
970
+ )
971
+
972
+ it(
973
+ 'does not follow symbolic links, to a file or to a directory',
974
+ withSandbox(async (sandbox) => {
975
+ if (!sandbox.walkFiles) return
976
+ await sandbox.writeFile('conformance-links/real/target.txt', 'target')
977
+ const dir = `${sandbox.rootDir}/conformance-links`
978
+ const linked = await sandbox.exec('/bin/sh', [
979
+ '-c',
980
+ `cd ${dir} && ln -s real/target.txt link-to-file.txt && ln -s real link-to-dir`,
981
+ ])
982
+ // Never a silent skip. A runtime discovery cannot travel
983
+ // through this suite's one skip channel — the case's own
984
+ // title, decided synchronously from the options — so a guest
985
+ // that cannot build the fixture says so out loud instead of
986
+ // passing a case that asserted nothing.
987
+ if (linked.exitCode !== 0) {
988
+ throw new Error(
989
+ `walkFiles conformance: this case builds its fixture with POSIX \`ln -s\`, and the guest's shell answered ${linked.exitCode}: ${linked.stderr.trim()}. A guest image that cannot make a symbolic link is not held to "symlinks are not followed" by asserting nothing — ship \`ln\`, or raise the gap so the suite grows a declared skip rather than a quiet one.`,
990
+ )
991
+ }
992
+
993
+ // The real file, once, under its real path. Following the
994
+ // directory link would have reported it again through
995
+ // `link-to-dir/target.txt`, and the file link again as itself.
996
+ expect(await walkPaths(sandbox, dir, { maxEntries: 50 })).toEqual([
997
+ `${dir}/real/target.txt`,
998
+ ])
999
+ }),
1000
+ )
1001
+
1002
+ it(
1003
+ 'raises ERR_FILE_WALK_LIMIT when the examined-entry budget runs out',
1004
+ withSandbox(async (sandbox) => {
1005
+ if (!sandbox.walkFiles) return
1006
+ for (let index = 0; index < 12; index += 1) {
1007
+ await sandbox.writeFile(`conformance-budget/f${index}.txt`, 'x')
1008
+ }
1009
+ // An incomplete search is an ERROR carrying a code, never a
1010
+ // short list: a caller handed six of twelve files with no
1011
+ // signal reads it as "that is all there is".
1012
+ let code: unknown
1013
+ try {
1014
+ await walkPaths(sandbox, `${sandbox.rootDir}/conformance-budget`, {
1015
+ maxEntries: 50,
1016
+ maxVisitedEntries: 4,
1017
+ })
1018
+ } catch (error) {
1019
+ code = (error as { code?: unknown }).code
1020
+ }
1021
+ expect(code).toBe('ERR_FILE_WALK_LIMIT')
1022
+ }),
1023
+ )
1024
+
1025
+ it(
1026
+ 'refuses a walk once the sandbox has been destroyed',
1027
+ withSandbox(async (sandbox) => {
1028
+ if (!sandbox.walkFiles) return
1029
+ const root = sandbox.rootDir
1030
+ await sandbox.destroy()
1031
+ // Consumed, not merely constructed: an async generator runs
1032
+ // nothing until its first `next()`, so a case that built the
1033
+ // iterator and stopped would pass against a sandbox that
1034
+ // admits the walk happily.
1035
+ await expectRejects(expect, () => walkPaths(sandbox, root, { maxEntries: 10 }))
1036
+ }),
1037
+ )
1038
+ })
1039
+
1040
+ /**
1041
+ * One sandbox, several commands at once.
1042
+ *
1043
+ * A supervisor and its sub-agents share a sandbox, so this is the
1044
+ * ordinary case rather than an exotic one — and nothing in this suite
1045
+ * used to exercise it. A backend that serialises executions behind one
1046
+ * connection, or that lets two commands' output frames land in each
1047
+ * other's result, passes every other case here.
1048
+ *
1049
+ * Overlap is proved by the commands themselves rather than by a clock:
1050
+ * each appends its own mark to a shared file, waits for every other
1051
+ * mark to appear, and then prints the whole file back. If the backend
1052
+ * really ran them together every command sees every mark; if it ran
1053
+ * them one at a time the first one waits out its ceiling and can only
1054
+ * ever see its own.
1055
+ */
1056
+ describe('concurrent exec', () => {
1057
+ it(
1058
+ 'runs several commands at once on one sandbox, with no cross-talk between their results',
1059
+ withSandbox(async (sandbox) => {
1060
+ const count = 4
1061
+ await sandbox.writeFile('conformance-concurrent/marks', '')
1062
+ const marks = `${sandbox.rootDir}/conformance-concurrent/marks`
1063
+
1064
+ // A rendezvous rather than a sleep: each command appends its
1065
+ // own mark and then WAITS for every other mark to appear
1066
+ // before it prints. A backend that really runs them together
1067
+ // settles as soon as the slowest one has started — no clock
1068
+ // to tune, and nothing that gets tighter on a machine or a
1069
+ // cluster where four dials cost more than a fixed pause. A
1070
+ // backend that serialises them has the first command wait
1071
+ // out the ceiling below and still print only its own mark,
1072
+ // which is what the assertions catch.
1073
+ const everyMark = Array.from({ length: count }, (_unused, index) => index).join(' ')
1074
+ const rendezvous = (index: number): string =>
1075
+ [
1076
+ `printf '[%s]' '${index}' >> "${marks}"`,
1077
+ 'waited=0',
1078
+ // 60 × 0.1 s. Only a backend that has already failed
1079
+ // the case ever reaches it.
1080
+ 'while [ "$waited" -lt 60 ]; do',
1081
+ ` all=$(cat "${marks}")`,
1082
+ ' seen=1',
1083
+ ` for mark in ${everyMark}; do`,
1084
+ ' case "$all" in *"[$mark]"*) ;; *) seen=0 ;; esac',
1085
+ ' done',
1086
+ ' [ "$seen" -eq 1 ] && break',
1087
+ ' waited=$((waited + 1))',
1088
+ ' sleep 0.1',
1089
+ 'done',
1090
+ `printf 'own:%s ' '${index}'`,
1091
+ `cat "${marks}"`,
1092
+ ].join('\n')
1093
+
1094
+ const running = Array.from({ length: count }, (_unused, index) =>
1095
+ sandbox.exec('/bin/sh', ['-c', rendezvous(index)]),
1096
+ )
1097
+ // Attached BEFORE the first assertion, and that ordering is
1098
+ // load-bearing: an assertion that threw with four commands
1099
+ // still in flight would leave four promises nobody is
1100
+ // handling, and a backend that then rejects one of them
1101
+ // takes the runner down with an unhandled rejection instead
1102
+ // of failing this case.
1103
+ const settled = Promise.allSettled(running)
1104
+ // Every one of them is in flight right now.
1105
+ expect(sandbox.status).toBe('busy')
1106
+ const results: SandboxExecResult[] = []
1107
+ for (const outcome of await settled) {
1108
+ if (outcome.status === 'rejected') {
1109
+ throw outcome.reason instanceof Error
1110
+ ? outcome.reason
1111
+ : new Error(String(outcome.reason))
1112
+ }
1113
+ results.push(outcome.value)
1114
+ }
1115
+
1116
+ for (let index = 0; index < count; index += 1) {
1117
+ const result = results[index]
1118
+ if (!result) throw new Error('unreachable: one result per started command')
1119
+ expect(result.exitCode).toBe(0)
1120
+ // Its OWN identity, on its own result: a backend that
1121
+ // mixed two commands' output frames fails here.
1122
+ expect(result.stdout).toMatch(new RegExp(`own:${index} `))
1123
+ // And every other command's mark, which only holds if
1124
+ // they were all admitted before any of them finished.
1125
+ for (let other = 0; other < count; other += 1) {
1126
+ expect(result.stdout).toMatch(new RegExp(`\\[${other}\\]`))
1127
+ }
1128
+ }
1129
+ expect(sandbox.status).toBe('ready')
1130
+ }),
1131
+ )
1132
+ })
1133
+
1134
+ /**
1135
+ * `SandboxExecOptions.timeout` and the `timedOut` flag it sets.
1136
+ *
1137
+ * `SandboxExecResult.timedOut` is REQUIRED on the contract, so every
1138
+ * backend answers it on every result — and until now nothing checked
1139
+ * that a backend ever sets it to `true`. A backend that accepts
1140
+ * `timeout` and ignores it reports a clean, unaborted-looking success
1141
+ * after however long the command felt like taking, which is the same
1142
+ * defect class the `AbortSignal` case above exists for and reads the
1143
+ * same way to a caller: a result that says the work is done.
1144
+ */
1145
+ describe('exec timeout', () => {
1146
+ it(
1147
+ 'reports a command that outran its timeout as timedOut, and really terminates it',
1148
+ withSandbox(async (sandbox) => {
1149
+ // The same shape as the abort case: the marker file is
1150
+ // written a moment after "ready", so it only ever exists if
1151
+ // the command was left running past its timeout. `trap ''
1152
+ // TERM` on both the shell and the background job makes a
1153
+ // polite TERM insufficient, exactly as a real runaway
1154
+ // command would.
1155
+ const marker = 'conformance-timeout-marker.txt'
1156
+ const started = Date.now()
1157
+ const result = await sandbox.exec(
1158
+ '/bin/sh',
1159
+ [
1160
+ '-c',
1161
+ `trap '' TERM; (trap '' TERM; sleep 1.5; printf late > ${marker}) & echo ready; wait`,
1162
+ ],
1163
+ { timeout: 400 },
1164
+ )
1165
+ const elapsed = Date.now() - started
1166
+
1167
+ expect(result.timedOut).toBe(true)
1168
+ // Settled on the timeout rather than on the command
1169
+ // finishing: the script itself waits 1.5 s, and a generous
1170
+ // ceiling still separates the two outcomes.
1171
+ expect(elapsed < 10_000).toBe(true)
1172
+ // Long enough that a command left running would have written.
1173
+ await sleep(1_800)
1174
+ await expectRejects(expect, () => sandbox.readFile(marker))
1175
+ // And the sandbox is still usable: a timeout is one
1176
+ // command's outcome, not the handle's.
1177
+ expect(sandbox.status).toBe('ready')
1178
+ const after = await sandbox.exec('/bin/sh', ['-c', 'echo conformance-after-timeout'])
1179
+ expect(after.exitCode).toBe(0)
1180
+ expect(after.stdout).toMatch(/conformance-after-timeout/)
1181
+ }),
1182
+ )
1183
+
1184
+ it(
1185
+ 'leaves timedOut false for a command that finishes inside its timeout',
1186
+ withSandbox(async (sandbox) => {
1187
+ const result = await sandbox.exec('/bin/sh', ['-c', 'echo conformance-quick'], {
1188
+ timeout: 30_000,
1189
+ })
1190
+ expect(result.timedOut).toBe(false)
1191
+ expect(result.exitCode).toBe(0)
1192
+ expect(result.stdout).toMatch(/conformance-quick/)
1193
+ }),
1194
+ )
1195
+ })
661
1196
  })
662
1197
  }
663
1198